Merge tag 'migration-20240311-pull-request' of https://gitlab.com/peterx/qemu into...
[qemu/armbru.git] / hw / vfio / common.c
blob011ceaab89433de4496dffadc737286e053f321d
1 /*
2 * generic functions used by VFIO devices
4 * Copyright Red Hat, Inc. 2012
6 * Authors:
7 * Alex Williamson <alex.williamson@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
12 * Based on qemu-kvm device-assignment:
13 * Adapted for KVM by Qumranet.
14 * Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
15 * Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
16 * Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
17 * Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
18 * Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
21 #include "qemu/osdep.h"
22 #include <sys/ioctl.h>
23 #ifdef CONFIG_KVM
24 #include <linux/kvm.h>
25 #endif
26 #include <linux/vfio.h>
28 #include "hw/vfio/vfio-common.h"
29 #include "hw/vfio/pci.h"
30 #include "exec/address-spaces.h"
31 #include "exec/memory.h"
32 #include "exec/ram_addr.h"
33 #include "hw/hw.h"
34 #include "qemu/error-report.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/range.h"
37 #include "sysemu/kvm.h"
38 #include "sysemu/reset.h"
39 #include "sysemu/runstate.h"
40 #include "trace.h"
41 #include "qapi/error.h"
42 #include "migration/misc.h"
43 #include "migration/blocker.h"
44 #include "migration/qemu-file.h"
45 #include "sysemu/tpm.h"
47 VFIODeviceList vfio_device_list =
48 QLIST_HEAD_INITIALIZER(vfio_device_list);
49 static QLIST_HEAD(, VFIOAddressSpace) vfio_address_spaces =
50 QLIST_HEAD_INITIALIZER(vfio_address_spaces);
52 #ifdef CONFIG_KVM
54 * We have a single VFIO pseudo device per KVM VM. Once created it lives
55 * for the life of the VM. Closing the file descriptor only drops our
56 * reference to it and the device's reference to kvm. Therefore once
57 * initialized, this file descriptor is only released on QEMU exit and
58 * we'll re-use it should another vfio device be attached before then.
60 int vfio_kvm_device_fd = -1;
61 #endif
64 * Device state interfaces
67 bool vfio_mig_active(void)
69 VFIODevice *vbasedev;
71 if (QLIST_EMPTY(&vfio_device_list)) {
72 return false;
75 QLIST_FOREACH(vbasedev, &vfio_device_list, global_next) {
76 if (vbasedev->migration_blocker) {
77 return false;
80 return true;
83 static Error *multiple_devices_migration_blocker;
86 * Multiple devices migration is allowed only if all devices support P2P
87 * migration. Single device migration is allowed regardless of P2P migration
88 * support.
90 static bool vfio_multiple_devices_migration_is_supported(void)
92 VFIODevice *vbasedev;
93 unsigned int device_num = 0;
94 bool all_support_p2p = true;
96 QLIST_FOREACH(vbasedev, &vfio_device_list, global_next) {
97 if (vbasedev->migration) {
98 device_num++;
100 if (!(vbasedev->migration->mig_flags & VFIO_MIGRATION_P2P)) {
101 all_support_p2p = false;
106 return all_support_p2p || device_num <= 1;
109 int vfio_block_multiple_devices_migration(VFIODevice *vbasedev, Error **errp)
111 int ret;
113 if (vfio_multiple_devices_migration_is_supported()) {
114 return 0;
117 if (vbasedev->enable_migration == ON_OFF_AUTO_ON) {
118 error_setg(errp, "Multiple VFIO devices migration is supported only if "
119 "all of them support P2P migration");
120 return -EINVAL;
123 if (multiple_devices_migration_blocker) {
124 return 0;
127 error_setg(&multiple_devices_migration_blocker,
128 "Multiple VFIO devices migration is supported only if all of "
129 "them support P2P migration");
130 ret = migrate_add_blocker_normal(&multiple_devices_migration_blocker, errp);
132 return ret;
135 void vfio_unblock_multiple_devices_migration(void)
137 if (!multiple_devices_migration_blocker ||
138 !vfio_multiple_devices_migration_is_supported()) {
139 return;
142 migrate_del_blocker(&multiple_devices_migration_blocker);
145 bool vfio_viommu_preset(VFIODevice *vbasedev)
147 return vbasedev->bcontainer->space->as != &address_space_memory;
150 static void vfio_set_migration_error(int err)
152 if (migration_is_setup_or_active()) {
153 migration_file_set_error(err);
157 bool vfio_device_state_is_running(VFIODevice *vbasedev)
159 VFIOMigration *migration = vbasedev->migration;
161 return migration->device_state == VFIO_DEVICE_STATE_RUNNING ||
162 migration->device_state == VFIO_DEVICE_STATE_RUNNING_P2P;
165 bool vfio_device_state_is_precopy(VFIODevice *vbasedev)
167 VFIOMigration *migration = vbasedev->migration;
169 return migration->device_state == VFIO_DEVICE_STATE_PRE_COPY ||
170 migration->device_state == VFIO_DEVICE_STATE_PRE_COPY_P2P;
173 static bool vfio_devices_all_dirty_tracking(VFIOContainerBase *bcontainer)
175 VFIODevice *vbasedev;
177 if (!migration_is_active() && !migration_is_device()) {
178 return false;
181 QLIST_FOREACH(vbasedev, &bcontainer->device_list, container_next) {
182 VFIOMigration *migration = vbasedev->migration;
184 if (!migration) {
185 return false;
188 if (vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF &&
189 (vfio_device_state_is_running(vbasedev) ||
190 vfio_device_state_is_precopy(vbasedev))) {
191 return false;
194 return true;
197 bool vfio_devices_all_device_dirty_tracking(const VFIOContainerBase *bcontainer)
199 VFIODevice *vbasedev;
201 QLIST_FOREACH(vbasedev, &bcontainer->device_list, container_next) {
202 if (!vbasedev->dirty_pages_supported) {
203 return false;
207 return true;
211 * Check if all VFIO devices are running and migration is active, which is
212 * essentially equivalent to the migration being in pre-copy phase.
214 bool
215 vfio_devices_all_running_and_mig_active(const VFIOContainerBase *bcontainer)
217 VFIODevice *vbasedev;
219 if (!migration_is_active()) {
220 return false;
223 QLIST_FOREACH(vbasedev, &bcontainer->device_list, container_next) {
224 VFIOMigration *migration = vbasedev->migration;
226 if (!migration) {
227 return false;
230 if (vfio_device_state_is_running(vbasedev) ||
231 vfio_device_state_is_precopy(vbasedev)) {
232 continue;
233 } else {
234 return false;
237 return true;
240 static bool vfio_listener_skipped_section(MemoryRegionSection *section)
242 return (!memory_region_is_ram(section->mr) &&
243 !memory_region_is_iommu(section->mr)) ||
244 memory_region_is_protected(section->mr) ||
246 * Sizing an enabled 64-bit BAR can cause spurious mappings to
247 * addresses in the upper part of the 64-bit address space. These
248 * are never accessed by the CPU and beyond the address width of
249 * some IOMMU hardware. TODO: VFIO should tell us the IOMMU width.
251 section->offset_within_address_space & (1ULL << 63);
254 /* Called with rcu_read_lock held. */
255 static bool vfio_get_xlat_addr(IOMMUTLBEntry *iotlb, void **vaddr,
256 ram_addr_t *ram_addr, bool *read_only)
258 bool ret, mr_has_discard_manager;
260 ret = memory_get_xlat_addr(iotlb, vaddr, ram_addr, read_only,
261 &mr_has_discard_manager);
262 if (ret && mr_has_discard_manager) {
264 * Malicious VMs might trigger discarding of IOMMU-mapped memory. The
265 * pages will remain pinned inside vfio until unmapped, resulting in a
266 * higher memory consumption than expected. If memory would get
267 * populated again later, there would be an inconsistency between pages
268 * pinned by vfio and pages seen by QEMU. This is the case until
269 * unmapped from the IOMMU (e.g., during device reset).
271 * With malicious guests, we really only care about pinning more memory
272 * than expected. RLIMIT_MEMLOCK set for the user/process can never be
273 * exceeded and can be used to mitigate this problem.
275 warn_report_once("Using vfio with vIOMMUs and coordinated discarding of"
276 " RAM (e.g., virtio-mem) works, however, malicious"
277 " guests can trigger pinning of more memory than"
278 " intended via an IOMMU. It's possible to mitigate "
279 " by setting/adjusting RLIMIT_MEMLOCK.");
281 return ret;
284 static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
286 VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
287 VFIOContainerBase *bcontainer = giommu->bcontainer;
288 hwaddr iova = iotlb->iova + giommu->iommu_offset;
289 void *vaddr;
290 int ret;
292 trace_vfio_iommu_map_notify(iotlb->perm == IOMMU_NONE ? "UNMAP" : "MAP",
293 iova, iova + iotlb->addr_mask);
295 if (iotlb->target_as != &address_space_memory) {
296 error_report("Wrong target AS \"%s\", only system memory is allowed",
297 iotlb->target_as->name ? iotlb->target_as->name : "none");
298 vfio_set_migration_error(-EINVAL);
299 return;
302 rcu_read_lock();
304 if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {
305 bool read_only;
307 if (!vfio_get_xlat_addr(iotlb, &vaddr, NULL, &read_only)) {
308 goto out;
311 * vaddr is only valid until rcu_read_unlock(). But after
312 * vfio_dma_map has set up the mapping the pages will be
313 * pinned by the kernel. This makes sure that the RAM backend
314 * of vaddr will always be there, even if the memory object is
315 * destroyed and its backing memory munmap-ed.
317 ret = vfio_container_dma_map(bcontainer, iova,
318 iotlb->addr_mask + 1, vaddr,
319 read_only);
320 if (ret) {
321 error_report("vfio_container_dma_map(%p, 0x%"HWADDR_PRIx", "
322 "0x%"HWADDR_PRIx", %p) = %d (%s)",
323 bcontainer, iova,
324 iotlb->addr_mask + 1, vaddr, ret, strerror(-ret));
326 } else {
327 ret = vfio_container_dma_unmap(bcontainer, iova,
328 iotlb->addr_mask + 1, iotlb);
329 if (ret) {
330 error_report("vfio_container_dma_unmap(%p, 0x%"HWADDR_PRIx", "
331 "0x%"HWADDR_PRIx") = %d (%s)",
332 bcontainer, iova,
333 iotlb->addr_mask + 1, ret, strerror(-ret));
334 vfio_set_migration_error(ret);
337 out:
338 rcu_read_unlock();
341 static void vfio_ram_discard_notify_discard(RamDiscardListener *rdl,
342 MemoryRegionSection *section)
344 VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
345 listener);
346 VFIOContainerBase *bcontainer = vrdl->bcontainer;
347 const hwaddr size = int128_get64(section->size);
348 const hwaddr iova = section->offset_within_address_space;
349 int ret;
351 /* Unmap with a single call. */
352 ret = vfio_container_dma_unmap(bcontainer, iova, size , NULL);
353 if (ret) {
354 error_report("%s: vfio_container_dma_unmap() failed: %s", __func__,
355 strerror(-ret));
359 static int vfio_ram_discard_notify_populate(RamDiscardListener *rdl,
360 MemoryRegionSection *section)
362 VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
363 listener);
364 VFIOContainerBase *bcontainer = vrdl->bcontainer;
365 const hwaddr end = section->offset_within_region +
366 int128_get64(section->size);
367 hwaddr start, next, iova;
368 void *vaddr;
369 int ret;
372 * Map in (aligned within memory region) minimum granularity, so we can
373 * unmap in minimum granularity later.
375 for (start = section->offset_within_region; start < end; start = next) {
376 next = ROUND_UP(start + 1, vrdl->granularity);
377 next = MIN(next, end);
379 iova = start - section->offset_within_region +
380 section->offset_within_address_space;
381 vaddr = memory_region_get_ram_ptr(section->mr) + start;
383 ret = vfio_container_dma_map(bcontainer, iova, next - start,
384 vaddr, section->readonly);
385 if (ret) {
386 /* Rollback */
387 vfio_ram_discard_notify_discard(rdl, section);
388 return ret;
391 return 0;
394 static void vfio_register_ram_discard_listener(VFIOContainerBase *bcontainer,
395 MemoryRegionSection *section)
397 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
398 VFIORamDiscardListener *vrdl;
400 /* Ignore some corner cases not relevant in practice. */
401 g_assert(QEMU_IS_ALIGNED(section->offset_within_region, TARGET_PAGE_SIZE));
402 g_assert(QEMU_IS_ALIGNED(section->offset_within_address_space,
403 TARGET_PAGE_SIZE));
404 g_assert(QEMU_IS_ALIGNED(int128_get64(section->size), TARGET_PAGE_SIZE));
406 vrdl = g_new0(VFIORamDiscardListener, 1);
407 vrdl->bcontainer = bcontainer;
408 vrdl->mr = section->mr;
409 vrdl->offset_within_address_space = section->offset_within_address_space;
410 vrdl->size = int128_get64(section->size);
411 vrdl->granularity = ram_discard_manager_get_min_granularity(rdm,
412 section->mr);
414 g_assert(vrdl->granularity && is_power_of_2(vrdl->granularity));
415 g_assert(bcontainer->pgsizes &&
416 vrdl->granularity >= 1ULL << ctz64(bcontainer->pgsizes));
418 ram_discard_listener_init(&vrdl->listener,
419 vfio_ram_discard_notify_populate,
420 vfio_ram_discard_notify_discard, true);
421 ram_discard_manager_register_listener(rdm, &vrdl->listener, section);
422 QLIST_INSERT_HEAD(&bcontainer->vrdl_list, vrdl, next);
425 * Sanity-check if we have a theoretically problematic setup where we could
426 * exceed the maximum number of possible DMA mappings over time. We assume
427 * that each mapped section in the same address space as a RamDiscardManager
428 * section consumes exactly one DMA mapping, with the exception of
429 * RamDiscardManager sections; i.e., we don't expect to have gIOMMU sections
430 * in the same address space as RamDiscardManager sections.
432 * We assume that each section in the address space consumes one memslot.
433 * We take the number of KVM memory slots as a best guess for the maximum
434 * number of sections in the address space we could have over time,
435 * also consuming DMA mappings.
437 if (bcontainer->dma_max_mappings) {
438 unsigned int vrdl_count = 0, vrdl_mappings = 0, max_memslots = 512;
440 #ifdef CONFIG_KVM
441 if (kvm_enabled()) {
442 max_memslots = kvm_get_max_memslots();
444 #endif
446 QLIST_FOREACH(vrdl, &bcontainer->vrdl_list, next) {
447 hwaddr start, end;
449 start = QEMU_ALIGN_DOWN(vrdl->offset_within_address_space,
450 vrdl->granularity);
451 end = ROUND_UP(vrdl->offset_within_address_space + vrdl->size,
452 vrdl->granularity);
453 vrdl_mappings += (end - start) / vrdl->granularity;
454 vrdl_count++;
457 if (vrdl_mappings + max_memslots - vrdl_count >
458 bcontainer->dma_max_mappings) {
459 warn_report("%s: possibly running out of DMA mappings. E.g., try"
460 " increasing the 'block-size' of virtio-mem devies."
461 " Maximum possible DMA mappings: %d, Maximum possible"
462 " memslots: %d", __func__, bcontainer->dma_max_mappings,
463 max_memslots);
468 static void vfio_unregister_ram_discard_listener(VFIOContainerBase *bcontainer,
469 MemoryRegionSection *section)
471 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
472 VFIORamDiscardListener *vrdl = NULL;
474 QLIST_FOREACH(vrdl, &bcontainer->vrdl_list, next) {
475 if (vrdl->mr == section->mr &&
476 vrdl->offset_within_address_space ==
477 section->offset_within_address_space) {
478 break;
482 if (!vrdl) {
483 hw_error("vfio: Trying to unregister missing RAM discard listener");
486 ram_discard_manager_unregister_listener(rdm, &vrdl->listener);
487 QLIST_REMOVE(vrdl, next);
488 g_free(vrdl);
491 static bool vfio_known_safe_misalignment(MemoryRegionSection *section)
493 MemoryRegion *mr = section->mr;
495 if (!TPM_IS_CRB(mr->owner)) {
496 return false;
499 /* this is a known safe misaligned region, just trace for debug purpose */
500 trace_vfio_known_safe_misalignment(memory_region_name(mr),
501 section->offset_within_address_space,
502 section->offset_within_region,
503 qemu_real_host_page_size());
504 return true;
507 static bool vfio_listener_valid_section(MemoryRegionSection *section,
508 const char *name)
510 if (vfio_listener_skipped_section(section)) {
511 trace_vfio_listener_region_skip(name,
512 section->offset_within_address_space,
513 section->offset_within_address_space +
514 int128_get64(int128_sub(section->size, int128_one())));
515 return false;
518 if (unlikely((section->offset_within_address_space &
519 ~qemu_real_host_page_mask()) !=
520 (section->offset_within_region & ~qemu_real_host_page_mask()))) {
521 if (!vfio_known_safe_misalignment(section)) {
522 error_report("%s received unaligned region %s iova=0x%"PRIx64
523 " offset_within_region=0x%"PRIx64
524 " qemu_real_host_page_size=0x%"PRIxPTR,
525 __func__, memory_region_name(section->mr),
526 section->offset_within_address_space,
527 section->offset_within_region,
528 qemu_real_host_page_size());
530 return false;
533 return true;
536 static bool vfio_get_section_iova_range(VFIOContainerBase *bcontainer,
537 MemoryRegionSection *section,
538 hwaddr *out_iova, hwaddr *out_end,
539 Int128 *out_llend)
541 Int128 llend;
542 hwaddr iova;
544 iova = REAL_HOST_PAGE_ALIGN(section->offset_within_address_space);
545 llend = int128_make64(section->offset_within_address_space);
546 llend = int128_add(llend, section->size);
547 llend = int128_and(llend, int128_exts64(qemu_real_host_page_mask()));
549 if (int128_ge(int128_make64(iova), llend)) {
550 return false;
553 *out_iova = iova;
554 *out_end = int128_get64(int128_sub(llend, int128_one()));
555 if (out_llend) {
556 *out_llend = llend;
558 return true;
561 static void vfio_listener_region_add(MemoryListener *listener,
562 MemoryRegionSection *section)
564 VFIOContainerBase *bcontainer = container_of(listener, VFIOContainerBase,
565 listener);
566 hwaddr iova, end;
567 Int128 llend, llsize;
568 void *vaddr;
569 int ret;
570 Error *err = NULL;
572 if (!vfio_listener_valid_section(section, "region_add")) {
573 return;
576 if (!vfio_get_section_iova_range(bcontainer, section, &iova, &end,
577 &llend)) {
578 if (memory_region_is_ram_device(section->mr)) {
579 trace_vfio_listener_region_add_no_dma_map(
580 memory_region_name(section->mr),
581 section->offset_within_address_space,
582 int128_getlo(section->size),
583 qemu_real_host_page_size());
585 return;
588 if (vfio_container_add_section_window(bcontainer, section, &err)) {
589 goto fail;
592 memory_region_ref(section->mr);
594 if (memory_region_is_iommu(section->mr)) {
595 VFIOGuestIOMMU *giommu;
596 IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
597 int iommu_idx;
599 trace_vfio_listener_region_add_iommu(iova, end);
601 * FIXME: For VFIO iommu types which have KVM acceleration to
602 * avoid bouncing all map/unmaps through qemu this way, this
603 * would be the right place to wire that up (tell the KVM
604 * device emulation the VFIO iommu handles to use).
606 giommu = g_malloc0(sizeof(*giommu));
607 giommu->iommu_mr = iommu_mr;
608 giommu->iommu_offset = section->offset_within_address_space -
609 section->offset_within_region;
610 giommu->bcontainer = bcontainer;
611 llend = int128_add(int128_make64(section->offset_within_region),
612 section->size);
613 llend = int128_sub(llend, int128_one());
614 iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
615 MEMTXATTRS_UNSPECIFIED);
616 iommu_notifier_init(&giommu->n, vfio_iommu_map_notify,
617 IOMMU_NOTIFIER_IOTLB_EVENTS,
618 section->offset_within_region,
619 int128_get64(llend),
620 iommu_idx);
622 ret = memory_region_iommu_set_page_size_mask(giommu->iommu_mr,
623 bcontainer->pgsizes,
624 &err);
625 if (ret) {
626 g_free(giommu);
627 goto fail;
630 if (bcontainer->iova_ranges) {
631 ret = memory_region_iommu_set_iova_ranges(giommu->iommu_mr,
632 bcontainer->iova_ranges,
633 &err);
634 if (ret) {
635 g_free(giommu);
636 goto fail;
640 ret = memory_region_register_iommu_notifier(section->mr, &giommu->n,
641 &err);
642 if (ret) {
643 g_free(giommu);
644 goto fail;
646 QLIST_INSERT_HEAD(&bcontainer->giommu_list, giommu, giommu_next);
647 memory_region_iommu_replay(giommu->iommu_mr, &giommu->n);
649 return;
652 /* Here we assume that memory_region_is_ram(section->mr)==true */
655 * For RAM memory regions with a RamDiscardManager, we only want to map the
656 * actually populated parts - and update the mapping whenever we're notified
657 * about changes.
659 if (memory_region_has_ram_discard_manager(section->mr)) {
660 vfio_register_ram_discard_listener(bcontainer, section);
661 return;
664 vaddr = memory_region_get_ram_ptr(section->mr) +
665 section->offset_within_region +
666 (iova - section->offset_within_address_space);
668 trace_vfio_listener_region_add_ram(iova, end, vaddr);
670 llsize = int128_sub(llend, int128_make64(iova));
672 if (memory_region_is_ram_device(section->mr)) {
673 hwaddr pgmask = (1ULL << ctz64(bcontainer->pgsizes)) - 1;
675 if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) {
676 trace_vfio_listener_region_add_no_dma_map(
677 memory_region_name(section->mr),
678 section->offset_within_address_space,
679 int128_getlo(section->size),
680 pgmask + 1);
681 return;
685 ret = vfio_container_dma_map(bcontainer, iova, int128_get64(llsize),
686 vaddr, section->readonly);
687 if (ret) {
688 error_setg(&err, "vfio_container_dma_map(%p, 0x%"HWADDR_PRIx", "
689 "0x%"HWADDR_PRIx", %p) = %d (%s)",
690 bcontainer, iova, int128_get64(llsize), vaddr, ret,
691 strerror(-ret));
692 if (memory_region_is_ram_device(section->mr)) {
693 /* Allow unexpected mappings not to be fatal for RAM devices */
694 error_report_err(err);
695 return;
697 goto fail;
700 return;
702 fail:
703 if (memory_region_is_ram_device(section->mr)) {
704 error_reportf_err(err, "PCI p2p may not work: ");
705 return;
708 * On the initfn path, store the first error in the container so we
709 * can gracefully fail. Runtime, there's not much we can do other
710 * than throw a hardware error.
712 if (!bcontainer->initialized) {
713 if (!bcontainer->error) {
714 error_propagate_prepend(&bcontainer->error, err,
715 "Region %s: ",
716 memory_region_name(section->mr));
717 } else {
718 error_free(err);
720 } else {
721 error_report_err(err);
722 hw_error("vfio: DMA mapping failed, unable to continue");
726 static void vfio_listener_region_del(MemoryListener *listener,
727 MemoryRegionSection *section)
729 VFIOContainerBase *bcontainer = container_of(listener, VFIOContainerBase,
730 listener);
731 hwaddr iova, end;
732 Int128 llend, llsize;
733 int ret;
734 bool try_unmap = true;
736 if (!vfio_listener_valid_section(section, "region_del")) {
737 return;
740 if (memory_region_is_iommu(section->mr)) {
741 VFIOGuestIOMMU *giommu;
743 QLIST_FOREACH(giommu, &bcontainer->giommu_list, giommu_next) {
744 if (MEMORY_REGION(giommu->iommu_mr) == section->mr &&
745 giommu->n.start == section->offset_within_region) {
746 memory_region_unregister_iommu_notifier(section->mr,
747 &giommu->n);
748 QLIST_REMOVE(giommu, giommu_next);
749 g_free(giommu);
750 break;
755 * FIXME: We assume the one big unmap below is adequate to
756 * remove any individual page mappings in the IOMMU which
757 * might have been copied into VFIO. This works for a page table
758 * based IOMMU where a big unmap flattens a large range of IO-PTEs.
759 * That may not be true for all IOMMU types.
763 if (!vfio_get_section_iova_range(bcontainer, section, &iova, &end,
764 &llend)) {
765 return;
768 llsize = int128_sub(llend, int128_make64(iova));
770 trace_vfio_listener_region_del(iova, end);
772 if (memory_region_is_ram_device(section->mr)) {
773 hwaddr pgmask;
775 pgmask = (1ULL << ctz64(bcontainer->pgsizes)) - 1;
776 try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask));
777 } else if (memory_region_has_ram_discard_manager(section->mr)) {
778 vfio_unregister_ram_discard_listener(bcontainer, section);
779 /* Unregistering will trigger an unmap. */
780 try_unmap = false;
783 if (try_unmap) {
784 if (int128_eq(llsize, int128_2_64())) {
785 /* The unmap ioctl doesn't accept a full 64-bit span. */
786 llsize = int128_rshift(llsize, 1);
787 ret = vfio_container_dma_unmap(bcontainer, iova,
788 int128_get64(llsize), NULL);
789 if (ret) {
790 error_report("vfio_container_dma_unmap(%p, 0x%"HWADDR_PRIx", "
791 "0x%"HWADDR_PRIx") = %d (%s)",
792 bcontainer, iova, int128_get64(llsize), ret,
793 strerror(-ret));
795 iova += int128_get64(llsize);
797 ret = vfio_container_dma_unmap(bcontainer, iova,
798 int128_get64(llsize), NULL);
799 if (ret) {
800 error_report("vfio_container_dma_unmap(%p, 0x%"HWADDR_PRIx", "
801 "0x%"HWADDR_PRIx") = %d (%s)",
802 bcontainer, iova, int128_get64(llsize), ret,
803 strerror(-ret));
807 memory_region_unref(section->mr);
809 vfio_container_del_section_window(bcontainer, section);
812 typedef struct VFIODirtyRanges {
813 hwaddr min32;
814 hwaddr max32;
815 hwaddr min64;
816 hwaddr max64;
817 hwaddr minpci64;
818 hwaddr maxpci64;
819 } VFIODirtyRanges;
821 typedef struct VFIODirtyRangesListener {
822 VFIOContainerBase *bcontainer;
823 VFIODirtyRanges ranges;
824 MemoryListener listener;
825 } VFIODirtyRangesListener;
827 static bool vfio_section_is_vfio_pci(MemoryRegionSection *section,
828 VFIOContainerBase *bcontainer)
830 VFIOPCIDevice *pcidev;
831 VFIODevice *vbasedev;
832 Object *owner;
834 owner = memory_region_owner(section->mr);
836 QLIST_FOREACH(vbasedev, &bcontainer->device_list, container_next) {
837 if (vbasedev->type != VFIO_DEVICE_TYPE_PCI) {
838 continue;
840 pcidev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
841 if (OBJECT(pcidev) == owner) {
842 return true;
846 return false;
849 static void vfio_dirty_tracking_update(MemoryListener *listener,
850 MemoryRegionSection *section)
852 VFIODirtyRangesListener *dirty = container_of(listener,
853 VFIODirtyRangesListener,
854 listener);
855 VFIODirtyRanges *range = &dirty->ranges;
856 hwaddr iova, end, *min, *max;
858 if (!vfio_listener_valid_section(section, "tracking_update") ||
859 !vfio_get_section_iova_range(dirty->bcontainer, section,
860 &iova, &end, NULL)) {
861 return;
865 * The address space passed to the dirty tracker is reduced to three ranges:
866 * one for 32-bit DMA ranges, one for 64-bit DMA ranges and one for the
867 * PCI 64-bit hole.
869 * The underlying reports of dirty will query a sub-interval of each of
870 * these ranges.
872 * The purpose of the three range handling is to handle known cases of big
873 * holes in the address space, like the x86 AMD 1T hole, and firmware (like
874 * OVMF) which may relocate the pci-hole64 to the end of the address space.
875 * The latter would otherwise generate large ranges for tracking, stressing
876 * the limits of supported hardware. The pci-hole32 will always be below 4G
877 * (overlapping or not) so it doesn't need special handling and is part of
878 * the 32-bit range.
880 * The alternative would be an IOVATree but that has a much bigger runtime
881 * overhead and unnecessary complexity.
883 if (vfio_section_is_vfio_pci(section, dirty->bcontainer) &&
884 iova >= UINT32_MAX) {
885 min = &range->minpci64;
886 max = &range->maxpci64;
887 } else {
888 min = (end <= UINT32_MAX) ? &range->min32 : &range->min64;
889 max = (end <= UINT32_MAX) ? &range->max32 : &range->max64;
891 if (*min > iova) {
892 *min = iova;
894 if (*max < end) {
895 *max = end;
898 trace_vfio_device_dirty_tracking_update(iova, end, *min, *max);
899 return;
902 static const MemoryListener vfio_dirty_tracking_listener = {
903 .name = "vfio-tracking",
904 .region_add = vfio_dirty_tracking_update,
907 static void vfio_dirty_tracking_init(VFIOContainerBase *bcontainer,
908 VFIODirtyRanges *ranges)
910 VFIODirtyRangesListener dirty;
912 memset(&dirty, 0, sizeof(dirty));
913 dirty.ranges.min32 = UINT32_MAX;
914 dirty.ranges.min64 = UINT64_MAX;
915 dirty.ranges.minpci64 = UINT64_MAX;
916 dirty.listener = vfio_dirty_tracking_listener;
917 dirty.bcontainer = bcontainer;
919 memory_listener_register(&dirty.listener,
920 bcontainer->space->as);
922 *ranges = dirty.ranges;
925 * The memory listener is synchronous, and used to calculate the range
926 * to dirty tracking. Unregister it after we are done as we are not
927 * interested in any follow-up updates.
929 memory_listener_unregister(&dirty.listener);
932 static void vfio_devices_dma_logging_stop(VFIOContainerBase *bcontainer)
934 uint64_t buf[DIV_ROUND_UP(sizeof(struct vfio_device_feature),
935 sizeof(uint64_t))] = {};
936 struct vfio_device_feature *feature = (struct vfio_device_feature *)buf;
937 VFIODevice *vbasedev;
939 feature->argsz = sizeof(buf);
940 feature->flags = VFIO_DEVICE_FEATURE_SET |
941 VFIO_DEVICE_FEATURE_DMA_LOGGING_STOP;
943 QLIST_FOREACH(vbasedev, &bcontainer->device_list, container_next) {
944 if (!vbasedev->dirty_tracking) {
945 continue;
948 if (ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature)) {
949 warn_report("%s: Failed to stop DMA logging, err %d (%s)",
950 vbasedev->name, -errno, strerror(errno));
952 vbasedev->dirty_tracking = false;
956 static struct vfio_device_feature *
957 vfio_device_feature_dma_logging_start_create(VFIOContainerBase *bcontainer,
958 VFIODirtyRanges *tracking)
960 struct vfio_device_feature *feature;
961 size_t feature_size;
962 struct vfio_device_feature_dma_logging_control *control;
963 struct vfio_device_feature_dma_logging_range *ranges;
965 feature_size = sizeof(struct vfio_device_feature) +
966 sizeof(struct vfio_device_feature_dma_logging_control);
967 feature = g_try_malloc0(feature_size);
968 if (!feature) {
969 errno = ENOMEM;
970 return NULL;
972 feature->argsz = feature_size;
973 feature->flags = VFIO_DEVICE_FEATURE_SET |
974 VFIO_DEVICE_FEATURE_DMA_LOGGING_START;
976 control = (struct vfio_device_feature_dma_logging_control *)feature->data;
977 control->page_size = qemu_real_host_page_size();
980 * DMA logging uAPI guarantees to support at least a number of ranges that
981 * fits into a single host kernel base page.
983 control->num_ranges = !!tracking->max32 + !!tracking->max64 +
984 !!tracking->maxpci64;
985 ranges = g_try_new0(struct vfio_device_feature_dma_logging_range,
986 control->num_ranges);
987 if (!ranges) {
988 g_free(feature);
989 errno = ENOMEM;
991 return NULL;
994 control->ranges = (uintptr_t)ranges;
995 if (tracking->max32) {
996 ranges->iova = tracking->min32;
997 ranges->length = (tracking->max32 - tracking->min32) + 1;
998 ranges++;
1000 if (tracking->max64) {
1001 ranges->iova = tracking->min64;
1002 ranges->length = (tracking->max64 - tracking->min64) + 1;
1003 ranges++;
1005 if (tracking->maxpci64) {
1006 ranges->iova = tracking->minpci64;
1007 ranges->length = (tracking->maxpci64 - tracking->minpci64) + 1;
1010 trace_vfio_device_dirty_tracking_start(control->num_ranges,
1011 tracking->min32, tracking->max32,
1012 tracking->min64, tracking->max64,
1013 tracking->minpci64, tracking->maxpci64);
1015 return feature;
1018 static void vfio_device_feature_dma_logging_start_destroy(
1019 struct vfio_device_feature *feature)
1021 struct vfio_device_feature_dma_logging_control *control =
1022 (struct vfio_device_feature_dma_logging_control *)feature->data;
1023 struct vfio_device_feature_dma_logging_range *ranges =
1024 (struct vfio_device_feature_dma_logging_range *)(uintptr_t)control->ranges;
1026 g_free(ranges);
1027 g_free(feature);
1030 static int vfio_devices_dma_logging_start(VFIOContainerBase *bcontainer)
1032 struct vfio_device_feature *feature;
1033 VFIODirtyRanges ranges;
1034 VFIODevice *vbasedev;
1035 int ret = 0;
1037 vfio_dirty_tracking_init(bcontainer, &ranges);
1038 feature = vfio_device_feature_dma_logging_start_create(bcontainer,
1039 &ranges);
1040 if (!feature) {
1041 return -errno;
1044 QLIST_FOREACH(vbasedev, &bcontainer->device_list, container_next) {
1045 if (vbasedev->dirty_tracking) {
1046 continue;
1049 ret = ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature);
1050 if (ret) {
1051 ret = -errno;
1052 error_report("%s: Failed to start DMA logging, err %d (%s)",
1053 vbasedev->name, ret, strerror(errno));
1054 goto out;
1056 vbasedev->dirty_tracking = true;
1059 out:
1060 if (ret) {
1061 vfio_devices_dma_logging_stop(bcontainer);
1064 vfio_device_feature_dma_logging_start_destroy(feature);
1066 return ret;
1069 static void vfio_listener_log_global_start(MemoryListener *listener)
1071 VFIOContainerBase *bcontainer = container_of(listener, VFIOContainerBase,
1072 listener);
1073 int ret;
1075 if (vfio_devices_all_device_dirty_tracking(bcontainer)) {
1076 ret = vfio_devices_dma_logging_start(bcontainer);
1077 } else {
1078 ret = vfio_container_set_dirty_page_tracking(bcontainer, true);
1081 if (ret) {
1082 error_report("vfio: Could not start dirty page tracking, err: %d (%s)",
1083 ret, strerror(-ret));
1084 vfio_set_migration_error(ret);
1088 static void vfio_listener_log_global_stop(MemoryListener *listener)
1090 VFIOContainerBase *bcontainer = container_of(listener, VFIOContainerBase,
1091 listener);
1092 int ret = 0;
1094 if (vfio_devices_all_device_dirty_tracking(bcontainer)) {
1095 vfio_devices_dma_logging_stop(bcontainer);
1096 } else {
1097 ret = vfio_container_set_dirty_page_tracking(bcontainer, false);
1100 if (ret) {
1101 error_report("vfio: Could not stop dirty page tracking, err: %d (%s)",
1102 ret, strerror(-ret));
1103 vfio_set_migration_error(ret);
1107 static int vfio_device_dma_logging_report(VFIODevice *vbasedev, hwaddr iova,
1108 hwaddr size, void *bitmap)
1110 uint64_t buf[DIV_ROUND_UP(sizeof(struct vfio_device_feature) +
1111 sizeof(struct vfio_device_feature_dma_logging_report),
1112 sizeof(uint64_t))] = {};
1113 struct vfio_device_feature *feature = (struct vfio_device_feature *)buf;
1114 struct vfio_device_feature_dma_logging_report *report =
1115 (struct vfio_device_feature_dma_logging_report *)feature->data;
1117 report->iova = iova;
1118 report->length = size;
1119 report->page_size = qemu_real_host_page_size();
1120 report->bitmap = (uintptr_t)bitmap;
1122 feature->argsz = sizeof(buf);
1123 feature->flags = VFIO_DEVICE_FEATURE_GET |
1124 VFIO_DEVICE_FEATURE_DMA_LOGGING_REPORT;
1126 if (ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature)) {
1127 return -errno;
1130 return 0;
1133 int vfio_devices_query_dirty_bitmap(const VFIOContainerBase *bcontainer,
1134 VFIOBitmap *vbmap, hwaddr iova,
1135 hwaddr size)
1137 VFIODevice *vbasedev;
1138 int ret;
1140 QLIST_FOREACH(vbasedev, &bcontainer->device_list, container_next) {
1141 ret = vfio_device_dma_logging_report(vbasedev, iova, size,
1142 vbmap->bitmap);
1143 if (ret) {
1144 error_report("%s: Failed to get DMA logging report, iova: "
1145 "0x%" HWADDR_PRIx ", size: 0x%" HWADDR_PRIx
1146 ", err: %d (%s)",
1147 vbasedev->name, iova, size, ret, strerror(-ret));
1149 return ret;
1153 return 0;
1156 int vfio_get_dirty_bitmap(const VFIOContainerBase *bcontainer, uint64_t iova,
1157 uint64_t size, ram_addr_t ram_addr)
1159 bool all_device_dirty_tracking =
1160 vfio_devices_all_device_dirty_tracking(bcontainer);
1161 uint64_t dirty_pages;
1162 VFIOBitmap vbmap;
1163 int ret;
1165 if (!bcontainer->dirty_pages_supported && !all_device_dirty_tracking) {
1166 cpu_physical_memory_set_dirty_range(ram_addr, size,
1167 tcg_enabled() ? DIRTY_CLIENTS_ALL :
1168 DIRTY_CLIENTS_NOCODE);
1169 return 0;
1172 ret = vfio_bitmap_alloc(&vbmap, size);
1173 if (ret) {
1174 return ret;
1177 if (all_device_dirty_tracking) {
1178 ret = vfio_devices_query_dirty_bitmap(bcontainer, &vbmap, iova, size);
1179 } else {
1180 ret = vfio_container_query_dirty_bitmap(bcontainer, &vbmap, iova, size);
1183 if (ret) {
1184 goto out;
1187 dirty_pages = cpu_physical_memory_set_dirty_lebitmap(vbmap.bitmap, ram_addr,
1188 vbmap.pages);
1190 trace_vfio_get_dirty_bitmap(iova, size, vbmap.size, ram_addr, dirty_pages);
1191 out:
1192 g_free(vbmap.bitmap);
1194 return ret;
1197 typedef struct {
1198 IOMMUNotifier n;
1199 VFIOGuestIOMMU *giommu;
1200 } vfio_giommu_dirty_notifier;
1202 static void vfio_iommu_map_dirty_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
1204 vfio_giommu_dirty_notifier *gdn = container_of(n,
1205 vfio_giommu_dirty_notifier, n);
1206 VFIOGuestIOMMU *giommu = gdn->giommu;
1207 VFIOContainerBase *bcontainer = giommu->bcontainer;
1208 hwaddr iova = iotlb->iova + giommu->iommu_offset;
1209 ram_addr_t translated_addr;
1210 int ret = -EINVAL;
1212 trace_vfio_iommu_map_dirty_notify(iova, iova + iotlb->addr_mask);
1214 if (iotlb->target_as != &address_space_memory) {
1215 error_report("Wrong target AS \"%s\", only system memory is allowed",
1216 iotlb->target_as->name ? iotlb->target_as->name : "none");
1217 goto out;
1220 rcu_read_lock();
1221 if (vfio_get_xlat_addr(iotlb, NULL, &translated_addr, NULL)) {
1222 ret = vfio_get_dirty_bitmap(bcontainer, iova, iotlb->addr_mask + 1,
1223 translated_addr);
1224 if (ret) {
1225 error_report("vfio_iommu_map_dirty_notify(%p, 0x%"HWADDR_PRIx", "
1226 "0x%"HWADDR_PRIx") = %d (%s)",
1227 bcontainer, iova, iotlb->addr_mask + 1, ret,
1228 strerror(-ret));
1231 rcu_read_unlock();
1233 out:
1234 if (ret) {
1235 vfio_set_migration_error(ret);
1239 static int vfio_ram_discard_get_dirty_bitmap(MemoryRegionSection *section,
1240 void *opaque)
1242 const hwaddr size = int128_get64(section->size);
1243 const hwaddr iova = section->offset_within_address_space;
1244 const ram_addr_t ram_addr = memory_region_get_ram_addr(section->mr) +
1245 section->offset_within_region;
1246 VFIORamDiscardListener *vrdl = opaque;
1249 * Sync the whole mapped region (spanning multiple individual mappings)
1250 * in one go.
1252 return vfio_get_dirty_bitmap(vrdl->bcontainer, iova, size, ram_addr);
1255 static int
1256 vfio_sync_ram_discard_listener_dirty_bitmap(VFIOContainerBase *bcontainer,
1257 MemoryRegionSection *section)
1259 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
1260 VFIORamDiscardListener *vrdl = NULL;
1262 QLIST_FOREACH(vrdl, &bcontainer->vrdl_list, next) {
1263 if (vrdl->mr == section->mr &&
1264 vrdl->offset_within_address_space ==
1265 section->offset_within_address_space) {
1266 break;
1270 if (!vrdl) {
1271 hw_error("vfio: Trying to sync missing RAM discard listener");
1275 * We only want/can synchronize the bitmap for actually mapped parts -
1276 * which correspond to populated parts. Replay all populated parts.
1278 return ram_discard_manager_replay_populated(rdm, section,
1279 vfio_ram_discard_get_dirty_bitmap,
1280 &vrdl);
1283 static int vfio_sync_dirty_bitmap(VFIOContainerBase *bcontainer,
1284 MemoryRegionSection *section)
1286 ram_addr_t ram_addr;
1288 if (memory_region_is_iommu(section->mr)) {
1289 VFIOGuestIOMMU *giommu;
1291 QLIST_FOREACH(giommu, &bcontainer->giommu_list, giommu_next) {
1292 if (MEMORY_REGION(giommu->iommu_mr) == section->mr &&
1293 giommu->n.start == section->offset_within_region) {
1294 Int128 llend;
1295 vfio_giommu_dirty_notifier gdn = { .giommu = giommu };
1296 int idx = memory_region_iommu_attrs_to_index(giommu->iommu_mr,
1297 MEMTXATTRS_UNSPECIFIED);
1299 llend = int128_add(int128_make64(section->offset_within_region),
1300 section->size);
1301 llend = int128_sub(llend, int128_one());
1303 iommu_notifier_init(&gdn.n,
1304 vfio_iommu_map_dirty_notify,
1305 IOMMU_NOTIFIER_MAP,
1306 section->offset_within_region,
1307 int128_get64(llend),
1308 idx);
1309 memory_region_iommu_replay(giommu->iommu_mr, &gdn.n);
1310 break;
1313 return 0;
1314 } else if (memory_region_has_ram_discard_manager(section->mr)) {
1315 return vfio_sync_ram_discard_listener_dirty_bitmap(bcontainer, section);
1318 ram_addr = memory_region_get_ram_addr(section->mr) +
1319 section->offset_within_region;
1321 return vfio_get_dirty_bitmap(bcontainer,
1322 REAL_HOST_PAGE_ALIGN(section->offset_within_address_space),
1323 int128_get64(section->size), ram_addr);
1326 static void vfio_listener_log_sync(MemoryListener *listener,
1327 MemoryRegionSection *section)
1329 VFIOContainerBase *bcontainer = container_of(listener, VFIOContainerBase,
1330 listener);
1331 int ret;
1333 if (vfio_listener_skipped_section(section)) {
1334 return;
1337 if (vfio_devices_all_dirty_tracking(bcontainer)) {
1338 ret = vfio_sync_dirty_bitmap(bcontainer, section);
1339 if (ret) {
1340 error_report("vfio: Failed to sync dirty bitmap, err: %d (%s)", ret,
1341 strerror(-ret));
1342 vfio_set_migration_error(ret);
1347 const MemoryListener vfio_memory_listener = {
1348 .name = "vfio",
1349 .region_add = vfio_listener_region_add,
1350 .region_del = vfio_listener_region_del,
1351 .log_global_start = vfio_listener_log_global_start,
1352 .log_global_stop = vfio_listener_log_global_stop,
1353 .log_sync = vfio_listener_log_sync,
1356 void vfio_reset_handler(void *opaque)
1358 VFIODevice *vbasedev;
1360 QLIST_FOREACH(vbasedev, &vfio_device_list, global_next) {
1361 if (vbasedev->dev->realized) {
1362 vbasedev->ops->vfio_compute_needs_reset(vbasedev);
1366 QLIST_FOREACH(vbasedev, &vfio_device_list, global_next) {
1367 if (vbasedev->dev->realized && vbasedev->needs_reset) {
1368 vbasedev->ops->vfio_hot_reset_multi(vbasedev);
1373 int vfio_kvm_device_add_fd(int fd, Error **errp)
1375 #ifdef CONFIG_KVM
1376 struct kvm_device_attr attr = {
1377 .group = KVM_DEV_VFIO_FILE,
1378 .attr = KVM_DEV_VFIO_FILE_ADD,
1379 .addr = (uint64_t)(unsigned long)&fd,
1382 if (!kvm_enabled()) {
1383 return 0;
1386 if (vfio_kvm_device_fd < 0) {
1387 struct kvm_create_device cd = {
1388 .type = KVM_DEV_TYPE_VFIO,
1391 if (kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd)) {
1392 error_setg_errno(errp, errno, "Failed to create KVM VFIO device");
1393 return -errno;
1396 vfio_kvm_device_fd = cd.fd;
1399 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1400 error_setg_errno(errp, errno, "Failed to add fd %d to KVM VFIO device",
1401 fd);
1402 return -errno;
1404 #endif
1405 return 0;
1408 int vfio_kvm_device_del_fd(int fd, Error **errp)
1410 #ifdef CONFIG_KVM
1411 struct kvm_device_attr attr = {
1412 .group = KVM_DEV_VFIO_FILE,
1413 .attr = KVM_DEV_VFIO_FILE_DEL,
1414 .addr = (uint64_t)(unsigned long)&fd,
1417 if (vfio_kvm_device_fd < 0) {
1418 error_setg(errp, "KVM VFIO device isn't created yet");
1419 return -EINVAL;
1422 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1423 error_setg_errno(errp, errno,
1424 "Failed to remove fd %d from KVM VFIO device", fd);
1425 return -errno;
1427 #endif
1428 return 0;
1431 VFIOAddressSpace *vfio_get_address_space(AddressSpace *as)
1433 VFIOAddressSpace *space;
1435 QLIST_FOREACH(space, &vfio_address_spaces, list) {
1436 if (space->as == as) {
1437 return space;
1441 /* No suitable VFIOAddressSpace, create a new one */
1442 space = g_malloc0(sizeof(*space));
1443 space->as = as;
1444 QLIST_INIT(&space->containers);
1446 if (QLIST_EMPTY(&vfio_address_spaces)) {
1447 qemu_register_reset(vfio_reset_handler, NULL);
1450 QLIST_INSERT_HEAD(&vfio_address_spaces, space, list);
1452 return space;
1455 void vfio_put_address_space(VFIOAddressSpace *space)
1457 if (!QLIST_EMPTY(&space->containers)) {
1458 return;
1461 QLIST_REMOVE(space, list);
1462 g_free(space);
1464 if (QLIST_EMPTY(&vfio_address_spaces)) {
1465 qemu_unregister_reset(vfio_reset_handler, NULL);
1469 struct vfio_device_info *vfio_get_device_info(int fd)
1471 struct vfio_device_info *info;
1472 uint32_t argsz = sizeof(*info);
1474 info = g_malloc0(argsz);
1476 retry:
1477 info->argsz = argsz;
1479 if (ioctl(fd, VFIO_DEVICE_GET_INFO, info)) {
1480 g_free(info);
1481 return NULL;
1484 if (info->argsz > argsz) {
1485 argsz = info->argsz;
1486 info = g_realloc(info, argsz);
1487 goto retry;
1490 return info;
1493 int vfio_attach_device(char *name, VFIODevice *vbasedev,
1494 AddressSpace *as, Error **errp)
1496 const VFIOIOMMUClass *ops =
1497 VFIO_IOMMU_CLASS(object_class_by_name(TYPE_VFIO_IOMMU_LEGACY));
1499 if (vbasedev->iommufd) {
1500 ops = VFIO_IOMMU_CLASS(object_class_by_name(TYPE_VFIO_IOMMU_IOMMUFD));
1503 assert(ops);
1505 return ops->attach_device(name, vbasedev, as, errp);
1508 void vfio_detach_device(VFIODevice *vbasedev)
1510 if (!vbasedev->bcontainer) {
1511 return;
1513 vbasedev->bcontainer->ops->detach_device(vbasedev);