2 * generic functions used by VFIO devices
4 * Copyright Red Hat, Inc. 2012
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>
24 #include <linux/kvm.h>
26 #include <linux/vfio.h>
28 #include "hw/vfio/vfio-common.h"
29 #include "hw/vfio/vfio.h"
30 #include "exec/address-spaces.h"
31 #include "exec/memory.h"
32 #include "exec/ram_addr.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"
41 #include "qapi/error.h"
42 #include "migration/migration.h"
43 #include "migration/misc.h"
44 #include "migration/blocker.h"
45 #include "migration/qemu-file.h"
46 #include "sysemu/tpm.h"
48 VFIOGroupList vfio_group_list
=
49 QLIST_HEAD_INITIALIZER(vfio_group_list
);
50 static QLIST_HEAD(, VFIOAddressSpace
) vfio_address_spaces
=
51 QLIST_HEAD_INITIALIZER(vfio_address_spaces
);
55 * We have a single VFIO pseudo device per KVM VM. Once created it lives
56 * for the life of the VM. Closing the file descriptor only drops our
57 * reference to it and the device's reference to kvm. Therefore once
58 * initialized, this file descriptor is only released on QEMU exit and
59 * we'll re-use it should another vfio device be attached before then.
61 static int vfio_kvm_device_fd
= -1;
65 * Common VFIO interrupt disable
67 void vfio_disable_irqindex(VFIODevice
*vbasedev
, int index
)
69 struct vfio_irq_set irq_set
= {
70 .argsz
= sizeof(irq_set
),
71 .flags
= VFIO_IRQ_SET_DATA_NONE
| VFIO_IRQ_SET_ACTION_TRIGGER
,
77 ioctl(vbasedev
->fd
, VFIO_DEVICE_SET_IRQS
, &irq_set
);
80 void vfio_unmask_single_irqindex(VFIODevice
*vbasedev
, int index
)
82 struct vfio_irq_set irq_set
= {
83 .argsz
= sizeof(irq_set
),
84 .flags
= VFIO_IRQ_SET_DATA_NONE
| VFIO_IRQ_SET_ACTION_UNMASK
,
90 ioctl(vbasedev
->fd
, VFIO_DEVICE_SET_IRQS
, &irq_set
);
93 void vfio_mask_single_irqindex(VFIODevice
*vbasedev
, int index
)
95 struct vfio_irq_set irq_set
= {
96 .argsz
= sizeof(irq_set
),
97 .flags
= VFIO_IRQ_SET_DATA_NONE
| VFIO_IRQ_SET_ACTION_MASK
,
103 ioctl(vbasedev
->fd
, VFIO_DEVICE_SET_IRQS
, &irq_set
);
106 static inline const char *action_to_str(int action
)
109 case VFIO_IRQ_SET_ACTION_MASK
:
111 case VFIO_IRQ_SET_ACTION_UNMASK
:
113 case VFIO_IRQ_SET_ACTION_TRIGGER
:
116 return "UNKNOWN ACTION";
120 static const char *index_to_str(VFIODevice
*vbasedev
, int index
)
122 if (vbasedev
->type
!= VFIO_DEVICE_TYPE_PCI
) {
127 case VFIO_PCI_INTX_IRQ_INDEX
:
129 case VFIO_PCI_MSI_IRQ_INDEX
:
131 case VFIO_PCI_MSIX_IRQ_INDEX
:
133 case VFIO_PCI_ERR_IRQ_INDEX
:
135 case VFIO_PCI_REQ_IRQ_INDEX
:
142 static int vfio_ram_block_discard_disable(VFIOContainer
*container
, bool state
)
144 switch (container
->iommu_type
) {
145 case VFIO_TYPE1v2_IOMMU
:
146 case VFIO_TYPE1_IOMMU
:
148 * We support coordinated discarding of RAM via the RamDiscardManager.
150 return ram_block_uncoordinated_discard_disable(state
);
153 * VFIO_SPAPR_TCE_IOMMU most probably works just fine with
154 * RamDiscardManager, however, it is completely untested.
156 * VFIO_SPAPR_TCE_v2_IOMMU with "DMA memory preregistering" does
157 * completely the opposite of managing mapping/pinning dynamically as
158 * required by RamDiscardManager. We would have to special-case sections
159 * with a RamDiscardManager.
161 return ram_block_discard_disable(state
);
165 int vfio_set_irq_signaling(VFIODevice
*vbasedev
, int index
, int subindex
,
166 int action
, int fd
, Error
**errp
)
168 struct vfio_irq_set
*irq_set
;
173 argsz
= sizeof(*irq_set
) + sizeof(*pfd
);
175 irq_set
= g_malloc0(argsz
);
176 irq_set
->argsz
= argsz
;
177 irq_set
->flags
= VFIO_IRQ_SET_DATA_EVENTFD
| action
;
178 irq_set
->index
= index
;
179 irq_set
->start
= subindex
;
181 pfd
= (int32_t *)&irq_set
->data
;
184 if (ioctl(vbasedev
->fd
, VFIO_DEVICE_SET_IRQS
, irq_set
)) {
193 error_setg_errno(errp
, -ret
, "VFIO_DEVICE_SET_IRQS failure");
195 name
= index_to_str(vbasedev
, index
);
197 error_prepend(errp
, "%s-%d: ", name
, subindex
);
199 error_prepend(errp
, "index %d-%d: ", index
, subindex
);
202 "Failed to %s %s eventfd signaling for interrupt ",
203 fd
< 0 ? "tear down" : "set up", action_to_str(action
));
208 * IO Port/MMIO - Beware of the endians, VFIO is always little endian
210 void vfio_region_write(void *opaque
, hwaddr addr
,
211 uint64_t data
, unsigned size
)
213 VFIORegion
*region
= opaque
;
214 VFIODevice
*vbasedev
= region
->vbasedev
;
227 buf
.word
= cpu_to_le16(data
);
230 buf
.dword
= cpu_to_le32(data
);
233 buf
.qword
= cpu_to_le64(data
);
236 hw_error("vfio: unsupported write size, %u bytes", size
);
240 if (pwrite(vbasedev
->fd
, &buf
, size
, region
->fd_offset
+ addr
) != size
) {
241 error_report("%s(%s:region%d+0x%"HWADDR_PRIx
", 0x%"PRIx64
243 __func__
, vbasedev
->name
, region
->nr
,
247 trace_vfio_region_write(vbasedev
->name
, region
->nr
, addr
, data
, size
);
250 * A read or write to a BAR always signals an INTx EOI. This will
251 * do nothing if not pending (including not in INTx mode). We assume
252 * that a BAR access is in response to an interrupt and that BAR
253 * accesses will service the interrupt. Unfortunately, we don't know
254 * which access will service the interrupt, so we're potentially
255 * getting quite a few host interrupts per guest interrupt.
257 vbasedev
->ops
->vfio_eoi(vbasedev
);
260 uint64_t vfio_region_read(void *opaque
,
261 hwaddr addr
, unsigned size
)
263 VFIORegion
*region
= opaque
;
264 VFIODevice
*vbasedev
= region
->vbasedev
;
273 if (pread(vbasedev
->fd
, &buf
, size
, region
->fd_offset
+ addr
) != size
) {
274 error_report("%s(%s:region%d+0x%"HWADDR_PRIx
", %d) failed: %m",
275 __func__
, vbasedev
->name
, region
->nr
,
284 data
= le16_to_cpu(buf
.word
);
287 data
= le32_to_cpu(buf
.dword
);
290 data
= le64_to_cpu(buf
.qword
);
293 hw_error("vfio: unsupported read size, %u bytes", size
);
297 trace_vfio_region_read(vbasedev
->name
, region
->nr
, addr
, size
, data
);
299 /* Same as write above */
300 vbasedev
->ops
->vfio_eoi(vbasedev
);
305 const MemoryRegionOps vfio_region_ops
= {
306 .read
= vfio_region_read
,
307 .write
= vfio_region_write
,
308 .endianness
= DEVICE_LITTLE_ENDIAN
,
310 .min_access_size
= 1,
311 .max_access_size
= 8,
314 .min_access_size
= 1,
315 .max_access_size
= 8,
320 * Device state interfaces
324 unsigned long *bitmap
;
329 static int vfio_bitmap_alloc(VFIOBitmap
*vbmap
, hwaddr size
)
331 vbmap
->pages
= REAL_HOST_PAGE_ALIGN(size
) / qemu_real_host_page_size();
332 vbmap
->size
= ROUND_UP(vbmap
->pages
, sizeof(__u64
) * BITS_PER_BYTE
) /
334 vbmap
->bitmap
= g_try_malloc0(vbmap
->size
);
335 if (!vbmap
->bitmap
) {
342 static int vfio_get_dirty_bitmap(VFIOContainer
*container
, uint64_t iova
,
343 uint64_t size
, ram_addr_t ram_addr
);
345 bool vfio_mig_active(void)
348 VFIODevice
*vbasedev
;
350 if (QLIST_EMPTY(&vfio_group_list
)) {
354 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
355 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
356 if (vbasedev
->migration_blocker
) {
364 static Error
*multiple_devices_migration_blocker
;
365 static Error
*giommu_migration_blocker
;
367 static unsigned int vfio_migratable_device_num(void)
370 VFIODevice
*vbasedev
;
371 unsigned int device_num
= 0;
373 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
374 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
375 if (vbasedev
->migration
) {
384 int vfio_block_multiple_devices_migration(Error
**errp
)
388 if (multiple_devices_migration_blocker
||
389 vfio_migratable_device_num() <= 1) {
393 error_setg(&multiple_devices_migration_blocker
,
394 "Migration is currently not supported with multiple "
396 ret
= migrate_add_blocker(multiple_devices_migration_blocker
, errp
);
398 error_free(multiple_devices_migration_blocker
);
399 multiple_devices_migration_blocker
= NULL
;
405 void vfio_unblock_multiple_devices_migration(void)
407 if (!multiple_devices_migration_blocker
||
408 vfio_migratable_device_num() > 1) {
412 migrate_del_blocker(multiple_devices_migration_blocker
);
413 error_free(multiple_devices_migration_blocker
);
414 multiple_devices_migration_blocker
= NULL
;
417 static bool vfio_viommu_preset(void)
419 VFIOAddressSpace
*space
;
421 QLIST_FOREACH(space
, &vfio_address_spaces
, list
) {
422 if (space
->as
!= &address_space_memory
) {
430 int vfio_block_giommu_migration(Error
**errp
)
434 if (giommu_migration_blocker
||
435 !vfio_viommu_preset()) {
439 error_setg(&giommu_migration_blocker
,
440 "Migration is currently not supported with vIOMMU enabled");
441 ret
= migrate_add_blocker(giommu_migration_blocker
, errp
);
443 error_free(giommu_migration_blocker
);
444 giommu_migration_blocker
= NULL
;
450 void vfio_migration_finalize(void)
452 if (!giommu_migration_blocker
||
453 vfio_viommu_preset()) {
457 migrate_del_blocker(giommu_migration_blocker
);
458 error_free(giommu_migration_blocker
);
459 giommu_migration_blocker
= NULL
;
462 static void vfio_set_migration_error(int err
)
464 MigrationState
*ms
= migrate_get_current();
466 if (migration_is_setup_or_active(ms
->state
)) {
467 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
468 if (ms
->to_dst_file
) {
469 qemu_file_set_error(ms
->to_dst_file
, err
);
475 static bool vfio_devices_all_dirty_tracking(VFIOContainer
*container
)
478 VFIODevice
*vbasedev
;
479 MigrationState
*ms
= migrate_get_current();
481 if (ms
->state
!= MIGRATION_STATUS_ACTIVE
&&
482 ms
->state
!= MIGRATION_STATUS_DEVICE
) {
486 QLIST_FOREACH(group
, &container
->group_list
, container_next
) {
487 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
488 VFIOMigration
*migration
= vbasedev
->migration
;
494 if (vbasedev
->pre_copy_dirty_page_tracking
== ON_OFF_AUTO_OFF
&&
495 migration
->device_state
== VFIO_DEVICE_STATE_RUNNING
) {
503 static bool vfio_devices_all_device_dirty_tracking(VFIOContainer
*container
)
506 VFIODevice
*vbasedev
;
508 QLIST_FOREACH(group
, &container
->group_list
, container_next
) {
509 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
510 if (!vbasedev
->dirty_pages_supported
) {
520 * Check if all VFIO devices are running and migration is active, which is
521 * essentially equivalent to the migration being in pre-copy phase.
523 static bool vfio_devices_all_running_and_mig_active(VFIOContainer
*container
)
526 VFIODevice
*vbasedev
;
528 if (!migration_is_active(migrate_get_current())) {
532 QLIST_FOREACH(group
, &container
->group_list
, container_next
) {
533 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
534 VFIOMigration
*migration
= vbasedev
->migration
;
540 if (migration
->device_state
== VFIO_DEVICE_STATE_RUNNING
) {
550 static int vfio_dma_unmap_bitmap(VFIOContainer
*container
,
551 hwaddr iova
, ram_addr_t size
,
552 IOMMUTLBEntry
*iotlb
)
554 struct vfio_iommu_type1_dma_unmap
*unmap
;
555 struct vfio_bitmap
*bitmap
;
559 ret
= vfio_bitmap_alloc(&vbmap
, size
);
564 unmap
= g_malloc0(sizeof(*unmap
) + sizeof(*bitmap
));
566 unmap
->argsz
= sizeof(*unmap
) + sizeof(*bitmap
);
569 unmap
->flags
|= VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP
;
570 bitmap
= (struct vfio_bitmap
*)&unmap
->data
;
573 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
574 * qemu_real_host_page_size to mark those dirty. Hence set bitmap_pgsize
575 * to qemu_real_host_page_size.
577 bitmap
->pgsize
= qemu_real_host_page_size();
578 bitmap
->size
= vbmap
.size
;
579 bitmap
->data
= (__u64
*)vbmap
.bitmap
;
581 if (vbmap
.size
> container
->max_dirty_bitmap_size
) {
582 error_report("UNMAP: Size of bitmap too big 0x%"PRIx64
, vbmap
.size
);
587 ret
= ioctl(container
->fd
, VFIO_IOMMU_UNMAP_DMA
, unmap
);
589 cpu_physical_memory_set_dirty_lebitmap(vbmap
.bitmap
,
590 iotlb
->translated_addr
, vbmap
.pages
);
592 error_report("VFIO_UNMAP_DMA with DIRTY_BITMAP : %m");
597 g_free(vbmap
.bitmap
);
603 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
605 static int vfio_dma_unmap(VFIOContainer
*container
,
606 hwaddr iova
, ram_addr_t size
,
607 IOMMUTLBEntry
*iotlb
)
609 struct vfio_iommu_type1_dma_unmap unmap
= {
610 .argsz
= sizeof(unmap
),
615 bool need_dirty_sync
= false;
618 if (iotlb
&& vfio_devices_all_running_and_mig_active(container
)) {
619 if (!vfio_devices_all_device_dirty_tracking(container
) &&
620 container
->dirty_pages_supported
) {
621 return vfio_dma_unmap_bitmap(container
, iova
, size
, iotlb
);
624 need_dirty_sync
= true;
627 while (ioctl(container
->fd
, VFIO_IOMMU_UNMAP_DMA
, &unmap
)) {
629 * The type1 backend has an off-by-one bug in the kernel (71a7d3d78e3c
630 * v4.15) where an overflow in its wrap-around check prevents us from
631 * unmapping the last page of the address space. Test for the error
632 * condition and re-try the unmap excluding the last page. The
633 * expectation is that we've never mapped the last page anyway and this
634 * unmap request comes via vIOMMU support which also makes it unlikely
635 * that this page is used. This bug was introduced well after type1 v2
636 * support was introduced, so we shouldn't need to test for v1. A fix
637 * is queued for kernel v5.0 so this workaround can be removed once
638 * affected kernels are sufficiently deprecated.
640 if (errno
== EINVAL
&& unmap
.size
&& !(unmap
.iova
+ unmap
.size
) &&
641 container
->iommu_type
== VFIO_TYPE1v2_IOMMU
) {
642 trace_vfio_dma_unmap_overflow_workaround();
643 unmap
.size
-= 1ULL << ctz64(container
->pgsizes
);
646 error_report("VFIO_UNMAP_DMA failed: %s", strerror(errno
));
650 if (need_dirty_sync
) {
651 ret
= vfio_get_dirty_bitmap(container
, iova
, size
,
652 iotlb
->translated_addr
);
661 static int vfio_dma_map(VFIOContainer
*container
, hwaddr iova
,
662 ram_addr_t size
, void *vaddr
, bool readonly
)
664 struct vfio_iommu_type1_dma_map map
= {
665 .argsz
= sizeof(map
),
666 .flags
= VFIO_DMA_MAP_FLAG_READ
,
667 .vaddr
= (__u64
)(uintptr_t)vaddr
,
673 map
.flags
|= VFIO_DMA_MAP_FLAG_WRITE
;
677 * Try the mapping, if it fails with EBUSY, unmap the region and try
678 * again. This shouldn't be necessary, but we sometimes see it in
681 if (ioctl(container
->fd
, VFIO_IOMMU_MAP_DMA
, &map
) == 0 ||
682 (errno
== EBUSY
&& vfio_dma_unmap(container
, iova
, size
, NULL
) == 0 &&
683 ioctl(container
->fd
, VFIO_IOMMU_MAP_DMA
, &map
) == 0)) {
687 error_report("VFIO_MAP_DMA failed: %s", strerror(errno
));
691 static void vfio_host_win_add(VFIOContainer
*container
,
692 hwaddr min_iova
, hwaddr max_iova
,
693 uint64_t iova_pgsizes
)
695 VFIOHostDMAWindow
*hostwin
;
697 QLIST_FOREACH(hostwin
, &container
->hostwin_list
, hostwin_next
) {
698 if (ranges_overlap(hostwin
->min_iova
,
699 hostwin
->max_iova
- hostwin
->min_iova
+ 1,
701 max_iova
- min_iova
+ 1)) {
702 hw_error("%s: Overlapped IOMMU are not enabled", __func__
);
706 hostwin
= g_malloc0(sizeof(*hostwin
));
708 hostwin
->min_iova
= min_iova
;
709 hostwin
->max_iova
= max_iova
;
710 hostwin
->iova_pgsizes
= iova_pgsizes
;
711 QLIST_INSERT_HEAD(&container
->hostwin_list
, hostwin
, hostwin_next
);
714 static int vfio_host_win_del(VFIOContainer
*container
, hwaddr min_iova
,
717 VFIOHostDMAWindow
*hostwin
;
719 QLIST_FOREACH(hostwin
, &container
->hostwin_list
, hostwin_next
) {
720 if (hostwin
->min_iova
== min_iova
&& hostwin
->max_iova
== max_iova
) {
721 QLIST_REMOVE(hostwin
, hostwin_next
);
730 static bool vfio_listener_skipped_section(MemoryRegionSection
*section
)
732 return (!memory_region_is_ram(section
->mr
) &&
733 !memory_region_is_iommu(section
->mr
)) ||
734 memory_region_is_protected(section
->mr
) ||
736 * Sizing an enabled 64-bit BAR can cause spurious mappings to
737 * addresses in the upper part of the 64-bit address space. These
738 * are never accessed by the CPU and beyond the address width of
739 * some IOMMU hardware. TODO: VFIO should tell us the IOMMU width.
741 section
->offset_within_address_space
& (1ULL << 63);
744 /* Called with rcu_read_lock held. */
745 static bool vfio_get_xlat_addr(IOMMUTLBEntry
*iotlb
, void **vaddr
,
746 ram_addr_t
*ram_addr
, bool *read_only
)
748 bool ret
, mr_has_discard_manager
;
750 ret
= memory_get_xlat_addr(iotlb
, vaddr
, ram_addr
, read_only
,
751 &mr_has_discard_manager
);
752 if (ret
&& mr_has_discard_manager
) {
754 * Malicious VMs might trigger discarding of IOMMU-mapped memory. The
755 * pages will remain pinned inside vfio until unmapped, resulting in a
756 * higher memory consumption than expected. If memory would get
757 * populated again later, there would be an inconsistency between pages
758 * pinned by vfio and pages seen by QEMU. This is the case until
759 * unmapped from the IOMMU (e.g., during device reset).
761 * With malicious guests, we really only care about pinning more memory
762 * than expected. RLIMIT_MEMLOCK set for the user/process can never be
763 * exceeded and can be used to mitigate this problem.
765 warn_report_once("Using vfio with vIOMMUs and coordinated discarding of"
766 " RAM (e.g., virtio-mem) works, however, malicious"
767 " guests can trigger pinning of more memory than"
768 " intended via an IOMMU. It's possible to mitigate "
769 " by setting/adjusting RLIMIT_MEMLOCK.");
774 static void vfio_iommu_map_notify(IOMMUNotifier
*n
, IOMMUTLBEntry
*iotlb
)
776 VFIOGuestIOMMU
*giommu
= container_of(n
, VFIOGuestIOMMU
, n
);
777 VFIOContainer
*container
= giommu
->container
;
778 hwaddr iova
= iotlb
->iova
+ giommu
->iommu_offset
;
782 trace_vfio_iommu_map_notify(iotlb
->perm
== IOMMU_NONE
? "UNMAP" : "MAP",
783 iova
, iova
+ iotlb
->addr_mask
);
785 if (iotlb
->target_as
!= &address_space_memory
) {
786 error_report("Wrong target AS \"%s\", only system memory is allowed",
787 iotlb
->target_as
->name
? iotlb
->target_as
->name
: "none");
788 vfio_set_migration_error(-EINVAL
);
794 if ((iotlb
->perm
& IOMMU_RW
) != IOMMU_NONE
) {
797 if (!vfio_get_xlat_addr(iotlb
, &vaddr
, NULL
, &read_only
)) {
801 * vaddr is only valid until rcu_read_unlock(). But after
802 * vfio_dma_map has set up the mapping the pages will be
803 * pinned by the kernel. This makes sure that the RAM backend
804 * of vaddr will always be there, even if the memory object is
805 * destroyed and its backing memory munmap-ed.
807 ret
= vfio_dma_map(container
, iova
,
808 iotlb
->addr_mask
+ 1, vaddr
,
811 error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx
", "
812 "0x%"HWADDR_PRIx
", %p) = %d (%s)",
814 iotlb
->addr_mask
+ 1, vaddr
, ret
, strerror(-ret
));
817 ret
= vfio_dma_unmap(container
, iova
, iotlb
->addr_mask
+ 1, iotlb
);
819 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx
", "
820 "0x%"HWADDR_PRIx
") = %d (%s)",
822 iotlb
->addr_mask
+ 1, ret
, strerror(-ret
));
823 vfio_set_migration_error(ret
);
830 static void vfio_ram_discard_notify_discard(RamDiscardListener
*rdl
,
831 MemoryRegionSection
*section
)
833 VFIORamDiscardListener
*vrdl
= container_of(rdl
, VFIORamDiscardListener
,
835 const hwaddr size
= int128_get64(section
->size
);
836 const hwaddr iova
= section
->offset_within_address_space
;
839 /* Unmap with a single call. */
840 ret
= vfio_dma_unmap(vrdl
->container
, iova
, size
, NULL
);
842 error_report("%s: vfio_dma_unmap() failed: %s", __func__
,
847 static int vfio_ram_discard_notify_populate(RamDiscardListener
*rdl
,
848 MemoryRegionSection
*section
)
850 VFIORamDiscardListener
*vrdl
= container_of(rdl
, VFIORamDiscardListener
,
852 const hwaddr end
= section
->offset_within_region
+
853 int128_get64(section
->size
);
854 hwaddr start
, next
, iova
;
859 * Map in (aligned within memory region) minimum granularity, so we can
860 * unmap in minimum granularity later.
862 for (start
= section
->offset_within_region
; start
< end
; start
= next
) {
863 next
= ROUND_UP(start
+ 1, vrdl
->granularity
);
864 next
= MIN(next
, end
);
866 iova
= start
- section
->offset_within_region
+
867 section
->offset_within_address_space
;
868 vaddr
= memory_region_get_ram_ptr(section
->mr
) + start
;
870 ret
= vfio_dma_map(vrdl
->container
, iova
, next
- start
,
871 vaddr
, section
->readonly
);
874 vfio_ram_discard_notify_discard(rdl
, section
);
881 static void vfio_register_ram_discard_listener(VFIOContainer
*container
,
882 MemoryRegionSection
*section
)
884 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(section
->mr
);
885 VFIORamDiscardListener
*vrdl
;
887 /* Ignore some corner cases not relevant in practice. */
888 g_assert(QEMU_IS_ALIGNED(section
->offset_within_region
, TARGET_PAGE_SIZE
));
889 g_assert(QEMU_IS_ALIGNED(section
->offset_within_address_space
,
891 g_assert(QEMU_IS_ALIGNED(int128_get64(section
->size
), TARGET_PAGE_SIZE
));
893 vrdl
= g_new0(VFIORamDiscardListener
, 1);
894 vrdl
->container
= container
;
895 vrdl
->mr
= section
->mr
;
896 vrdl
->offset_within_address_space
= section
->offset_within_address_space
;
897 vrdl
->size
= int128_get64(section
->size
);
898 vrdl
->granularity
= ram_discard_manager_get_min_granularity(rdm
,
901 g_assert(vrdl
->granularity
&& is_power_of_2(vrdl
->granularity
));
902 g_assert(container
->pgsizes
&&
903 vrdl
->granularity
>= 1ULL << ctz64(container
->pgsizes
));
905 ram_discard_listener_init(&vrdl
->listener
,
906 vfio_ram_discard_notify_populate
,
907 vfio_ram_discard_notify_discard
, true);
908 ram_discard_manager_register_listener(rdm
, &vrdl
->listener
, section
);
909 QLIST_INSERT_HEAD(&container
->vrdl_list
, vrdl
, next
);
912 * Sanity-check if we have a theoretically problematic setup where we could
913 * exceed the maximum number of possible DMA mappings over time. We assume
914 * that each mapped section in the same address space as a RamDiscardManager
915 * section consumes exactly one DMA mapping, with the exception of
916 * RamDiscardManager sections; i.e., we don't expect to have gIOMMU sections
917 * in the same address space as RamDiscardManager sections.
919 * We assume that each section in the address space consumes one memslot.
920 * We take the number of KVM memory slots as a best guess for the maximum
921 * number of sections in the address space we could have over time,
922 * also consuming DMA mappings.
924 if (container
->dma_max_mappings
) {
925 unsigned int vrdl_count
= 0, vrdl_mappings
= 0, max_memslots
= 512;
929 max_memslots
= kvm_get_max_memslots();
933 QLIST_FOREACH(vrdl
, &container
->vrdl_list
, next
) {
936 start
= QEMU_ALIGN_DOWN(vrdl
->offset_within_address_space
,
938 end
= ROUND_UP(vrdl
->offset_within_address_space
+ vrdl
->size
,
940 vrdl_mappings
+= (end
- start
) / vrdl
->granularity
;
944 if (vrdl_mappings
+ max_memslots
- vrdl_count
>
945 container
->dma_max_mappings
) {
946 warn_report("%s: possibly running out of DMA mappings. E.g., try"
947 " increasing the 'block-size' of virtio-mem devies."
948 " Maximum possible DMA mappings: %d, Maximum possible"
949 " memslots: %d", __func__
, container
->dma_max_mappings
,
955 static void vfio_unregister_ram_discard_listener(VFIOContainer
*container
,
956 MemoryRegionSection
*section
)
958 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(section
->mr
);
959 VFIORamDiscardListener
*vrdl
= NULL
;
961 QLIST_FOREACH(vrdl
, &container
->vrdl_list
, next
) {
962 if (vrdl
->mr
== section
->mr
&&
963 vrdl
->offset_within_address_space
==
964 section
->offset_within_address_space
) {
970 hw_error("vfio: Trying to unregister missing RAM discard listener");
973 ram_discard_manager_unregister_listener(rdm
, &vrdl
->listener
);
974 QLIST_REMOVE(vrdl
, next
);
978 static VFIOHostDMAWindow
*vfio_find_hostwin(VFIOContainer
*container
,
979 hwaddr iova
, hwaddr end
)
981 VFIOHostDMAWindow
*hostwin
;
982 bool hostwin_found
= false;
984 QLIST_FOREACH(hostwin
, &container
->hostwin_list
, hostwin_next
) {
985 if (hostwin
->min_iova
<= iova
&& end
<= hostwin
->max_iova
) {
986 hostwin_found
= true;
991 return hostwin_found
? hostwin
: NULL
;
994 static bool vfio_known_safe_misalignment(MemoryRegionSection
*section
)
996 MemoryRegion
*mr
= section
->mr
;
998 if (!TPM_IS_CRB(mr
->owner
)) {
1002 /* this is a known safe misaligned region, just trace for debug purpose */
1003 trace_vfio_known_safe_misalignment(memory_region_name(mr
),
1004 section
->offset_within_address_space
,
1005 section
->offset_within_region
,
1006 qemu_real_host_page_size());
1010 static bool vfio_listener_valid_section(MemoryRegionSection
*section
,
1013 if (vfio_listener_skipped_section(section
)) {
1014 trace_vfio_listener_region_skip(name
,
1015 section
->offset_within_address_space
,
1016 section
->offset_within_address_space
+
1017 int128_get64(int128_sub(section
->size
, int128_one())));
1021 if (unlikely((section
->offset_within_address_space
&
1022 ~qemu_real_host_page_mask()) !=
1023 (section
->offset_within_region
& ~qemu_real_host_page_mask()))) {
1024 if (!vfio_known_safe_misalignment(section
)) {
1025 error_report("%s received unaligned region %s iova=0x%"PRIx64
1026 " offset_within_region=0x%"PRIx64
1027 " qemu_real_host_page_size=0x%"PRIxPTR
,
1028 __func__
, memory_region_name(section
->mr
),
1029 section
->offset_within_address_space
,
1030 section
->offset_within_region
,
1031 qemu_real_host_page_size());
1039 static bool vfio_get_section_iova_range(VFIOContainer
*container
,
1040 MemoryRegionSection
*section
,
1041 hwaddr
*out_iova
, hwaddr
*out_end
,
1047 iova
= REAL_HOST_PAGE_ALIGN(section
->offset_within_address_space
);
1048 llend
= int128_make64(section
->offset_within_address_space
);
1049 llend
= int128_add(llend
, section
->size
);
1050 llend
= int128_and(llend
, int128_exts64(qemu_real_host_page_mask()));
1052 if (int128_ge(int128_make64(iova
), llend
)) {
1057 *out_end
= int128_get64(int128_sub(llend
, int128_one()));
1064 static void vfio_listener_region_add(MemoryListener
*listener
,
1065 MemoryRegionSection
*section
)
1067 VFIOContainer
*container
= container_of(listener
, VFIOContainer
, listener
);
1069 Int128 llend
, llsize
;
1072 VFIOHostDMAWindow
*hostwin
;
1075 if (!vfio_listener_valid_section(section
, "region_add")) {
1079 if (!vfio_get_section_iova_range(container
, section
, &iova
, &end
, &llend
)) {
1080 if (memory_region_is_ram_device(section
->mr
)) {
1081 trace_vfio_listener_region_add_no_dma_map(
1082 memory_region_name(section
->mr
),
1083 section
->offset_within_address_space
,
1084 int128_getlo(section
->size
),
1085 qemu_real_host_page_size());
1090 if (container
->iommu_type
== VFIO_SPAPR_TCE_v2_IOMMU
) {
1093 /* For now intersections are not allowed, we may relax this later */
1094 QLIST_FOREACH(hostwin
, &container
->hostwin_list
, hostwin_next
) {
1095 if (ranges_overlap(hostwin
->min_iova
,
1096 hostwin
->max_iova
- hostwin
->min_iova
+ 1,
1097 section
->offset_within_address_space
,
1098 int128_get64(section
->size
))) {
1100 "region [0x%"PRIx64
",0x%"PRIx64
"] overlaps with existing"
1101 "host DMA window [0x%"PRIx64
",0x%"PRIx64
"]",
1102 section
->offset_within_address_space
,
1103 section
->offset_within_address_space
+
1104 int128_get64(section
->size
) - 1,
1105 hostwin
->min_iova
, hostwin
->max_iova
);
1110 ret
= vfio_spapr_create_window(container
, section
, &pgsize
);
1112 error_setg_errno(&err
, -ret
, "Failed to create SPAPR window");
1116 vfio_host_win_add(container
, section
->offset_within_address_space
,
1117 section
->offset_within_address_space
+
1118 int128_get64(section
->size
) - 1, pgsize
);
1120 if (kvm_enabled()) {
1122 IOMMUMemoryRegion
*iommu_mr
= IOMMU_MEMORY_REGION(section
->mr
);
1123 struct kvm_vfio_spapr_tce param
;
1124 struct kvm_device_attr attr
= {
1125 .group
= KVM_DEV_VFIO_GROUP
,
1126 .attr
= KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE
,
1127 .addr
= (uint64_t)(unsigned long)¶m
,
1130 if (!memory_region_iommu_get_attr(iommu_mr
, IOMMU_ATTR_SPAPR_TCE_FD
,
1132 QLIST_FOREACH(group
, &container
->group_list
, container_next
) {
1133 param
.groupfd
= group
->fd
;
1134 if (ioctl(vfio_kvm_device_fd
, KVM_SET_DEVICE_ATTR
, &attr
)) {
1135 error_report("vfio: failed to setup fd %d "
1136 "for a group with fd %d: %s",
1137 param
.tablefd
, param
.groupfd
,
1141 trace_vfio_spapr_group_attach(param
.groupfd
, param
.tablefd
);
1148 hostwin
= vfio_find_hostwin(container
, iova
, end
);
1150 error_setg(&err
, "Container %p can't map guest IOVA region"
1151 " 0x%"HWADDR_PRIx
"..0x%"HWADDR_PRIx
, container
, iova
, end
);
1155 memory_region_ref(section
->mr
);
1157 if (memory_region_is_iommu(section
->mr
)) {
1158 VFIOGuestIOMMU
*giommu
;
1159 IOMMUMemoryRegion
*iommu_mr
= IOMMU_MEMORY_REGION(section
->mr
);
1162 trace_vfio_listener_region_add_iommu(iova
, end
);
1164 * FIXME: For VFIO iommu types which have KVM acceleration to
1165 * avoid bouncing all map/unmaps through qemu this way, this
1166 * would be the right place to wire that up (tell the KVM
1167 * device emulation the VFIO iommu handles to use).
1169 giommu
= g_malloc0(sizeof(*giommu
));
1170 giommu
->iommu_mr
= iommu_mr
;
1171 giommu
->iommu_offset
= section
->offset_within_address_space
-
1172 section
->offset_within_region
;
1173 giommu
->container
= container
;
1174 llend
= int128_add(int128_make64(section
->offset_within_region
),
1176 llend
= int128_sub(llend
, int128_one());
1177 iommu_idx
= memory_region_iommu_attrs_to_index(iommu_mr
,
1178 MEMTXATTRS_UNSPECIFIED
);
1179 iommu_notifier_init(&giommu
->n
, vfio_iommu_map_notify
,
1180 IOMMU_NOTIFIER_IOTLB_EVENTS
,
1181 section
->offset_within_region
,
1182 int128_get64(llend
),
1185 ret
= memory_region_iommu_set_page_size_mask(giommu
->iommu_mr
,
1193 ret
= memory_region_register_iommu_notifier(section
->mr
, &giommu
->n
,
1199 QLIST_INSERT_HEAD(&container
->giommu_list
, giommu
, giommu_next
);
1200 memory_region_iommu_replay(giommu
->iommu_mr
, &giommu
->n
);
1205 /* Here we assume that memory_region_is_ram(section->mr)==true */
1208 * For RAM memory regions with a RamDiscardManager, we only want to map the
1209 * actually populated parts - and update the mapping whenever we're notified
1212 if (memory_region_has_ram_discard_manager(section
->mr
)) {
1213 vfio_register_ram_discard_listener(container
, section
);
1217 vaddr
= memory_region_get_ram_ptr(section
->mr
) +
1218 section
->offset_within_region
+
1219 (iova
- section
->offset_within_address_space
);
1221 trace_vfio_listener_region_add_ram(iova
, end
, vaddr
);
1223 llsize
= int128_sub(llend
, int128_make64(iova
));
1225 if (memory_region_is_ram_device(section
->mr
)) {
1226 hwaddr pgmask
= (1ULL << ctz64(hostwin
->iova_pgsizes
)) - 1;
1228 if ((iova
& pgmask
) || (int128_get64(llsize
) & pgmask
)) {
1229 trace_vfio_listener_region_add_no_dma_map(
1230 memory_region_name(section
->mr
),
1231 section
->offset_within_address_space
,
1232 int128_getlo(section
->size
),
1238 ret
= vfio_dma_map(container
, iova
, int128_get64(llsize
),
1239 vaddr
, section
->readonly
);
1241 error_setg(&err
, "vfio_dma_map(%p, 0x%"HWADDR_PRIx
", "
1242 "0x%"HWADDR_PRIx
", %p) = %d (%s)",
1243 container
, iova
, int128_get64(llsize
), vaddr
, ret
,
1245 if (memory_region_is_ram_device(section
->mr
)) {
1246 /* Allow unexpected mappings not to be fatal for RAM devices */
1247 error_report_err(err
);
1256 if (memory_region_is_ram_device(section
->mr
)) {
1257 error_report("failed to vfio_dma_map. pci p2p may not work");
1261 * On the initfn path, store the first error in the container so we
1262 * can gracefully fail. Runtime, there's not much we can do other
1263 * than throw a hardware error.
1265 if (!container
->initialized
) {
1266 if (!container
->error
) {
1267 error_propagate_prepend(&container
->error
, err
,
1269 memory_region_name(section
->mr
));
1274 error_report_err(err
);
1275 hw_error("vfio: DMA mapping failed, unable to continue");
1279 static void vfio_listener_region_del(MemoryListener
*listener
,
1280 MemoryRegionSection
*section
)
1282 VFIOContainer
*container
= container_of(listener
, VFIOContainer
, listener
);
1284 Int128 llend
, llsize
;
1286 bool try_unmap
= true;
1288 if (!vfio_listener_valid_section(section
, "region_del")) {
1292 if (memory_region_is_iommu(section
->mr
)) {
1293 VFIOGuestIOMMU
*giommu
;
1295 QLIST_FOREACH(giommu
, &container
->giommu_list
, giommu_next
) {
1296 if (MEMORY_REGION(giommu
->iommu_mr
) == section
->mr
&&
1297 giommu
->n
.start
== section
->offset_within_region
) {
1298 memory_region_unregister_iommu_notifier(section
->mr
,
1300 QLIST_REMOVE(giommu
, giommu_next
);
1307 * FIXME: We assume the one big unmap below is adequate to
1308 * remove any individual page mappings in the IOMMU which
1309 * might have been copied into VFIO. This works for a page table
1310 * based IOMMU where a big unmap flattens a large range of IO-PTEs.
1311 * That may not be true for all IOMMU types.
1315 if (!vfio_get_section_iova_range(container
, section
, &iova
, &end
, &llend
)) {
1319 llsize
= int128_sub(llend
, int128_make64(iova
));
1321 trace_vfio_listener_region_del(iova
, end
);
1323 if (memory_region_is_ram_device(section
->mr
)) {
1325 VFIOHostDMAWindow
*hostwin
;
1327 hostwin
= vfio_find_hostwin(container
, iova
, end
);
1328 assert(hostwin
); /* or region_add() would have failed */
1330 pgmask
= (1ULL << ctz64(hostwin
->iova_pgsizes
)) - 1;
1331 try_unmap
= !((iova
& pgmask
) || (int128_get64(llsize
) & pgmask
));
1332 } else if (memory_region_has_ram_discard_manager(section
->mr
)) {
1333 vfio_unregister_ram_discard_listener(container
, section
);
1334 /* Unregistering will trigger an unmap. */
1339 if (int128_eq(llsize
, int128_2_64())) {
1340 /* The unmap ioctl doesn't accept a full 64-bit span. */
1341 llsize
= int128_rshift(llsize
, 1);
1342 ret
= vfio_dma_unmap(container
, iova
, int128_get64(llsize
), NULL
);
1344 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx
", "
1345 "0x%"HWADDR_PRIx
") = %d (%s)",
1346 container
, iova
, int128_get64(llsize
), ret
,
1349 iova
+= int128_get64(llsize
);
1351 ret
= vfio_dma_unmap(container
, iova
, int128_get64(llsize
), NULL
);
1353 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx
", "
1354 "0x%"HWADDR_PRIx
") = %d (%s)",
1355 container
, iova
, int128_get64(llsize
), ret
,
1360 memory_region_unref(section
->mr
);
1362 if (container
->iommu_type
== VFIO_SPAPR_TCE_v2_IOMMU
) {
1363 vfio_spapr_remove_window(container
,
1364 section
->offset_within_address_space
);
1365 if (vfio_host_win_del(container
,
1366 section
->offset_within_address_space
,
1367 section
->offset_within_address_space
+
1368 int128_get64(section
->size
) - 1) < 0) {
1369 hw_error("%s: Cannot delete missing window at %"HWADDR_PRIx
,
1370 __func__
, section
->offset_within_address_space
);
1375 static int vfio_set_dirty_page_tracking(VFIOContainer
*container
, bool start
)
1378 struct vfio_iommu_type1_dirty_bitmap dirty
= {
1379 .argsz
= sizeof(dirty
),
1382 if (!container
->dirty_pages_supported
) {
1387 dirty
.flags
= VFIO_IOMMU_DIRTY_PAGES_FLAG_START
;
1389 dirty
.flags
= VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP
;
1392 ret
= ioctl(container
->fd
, VFIO_IOMMU_DIRTY_PAGES
, &dirty
);
1395 error_report("Failed to set dirty tracking flag 0x%x errno: %d",
1396 dirty
.flags
, errno
);
1402 typedef struct VFIODirtyRanges
{
1409 typedef struct VFIODirtyRangesListener
{
1410 VFIOContainer
*container
;
1411 VFIODirtyRanges ranges
;
1412 MemoryListener listener
;
1413 } VFIODirtyRangesListener
;
1415 static void vfio_dirty_tracking_update(MemoryListener
*listener
,
1416 MemoryRegionSection
*section
)
1418 VFIODirtyRangesListener
*dirty
= container_of(listener
,
1419 VFIODirtyRangesListener
,
1421 VFIODirtyRanges
*range
= &dirty
->ranges
;
1422 hwaddr iova
, end
, *min
, *max
;
1424 if (!vfio_listener_valid_section(section
, "tracking_update") ||
1425 !vfio_get_section_iova_range(dirty
->container
, section
,
1426 &iova
, &end
, NULL
)) {
1431 * The address space passed to the dirty tracker is reduced to two ranges:
1432 * one for 32-bit DMA ranges, and another one for 64-bit DMA ranges.
1433 * The underlying reports of dirty will query a sub-interval of each of
1436 * The purpose of the dual range handling is to handle known cases of big
1437 * holes in the address space, like the x86 AMD 1T hole. The alternative
1438 * would be an IOVATree but that has a much bigger runtime overhead and
1439 * unnecessary complexity.
1441 min
= (end
<= UINT32_MAX
) ? &range
->min32
: &range
->min64
;
1442 max
= (end
<= UINT32_MAX
) ? &range
->max32
: &range
->max64
;
1451 trace_vfio_device_dirty_tracking_update(iova
, end
, *min
, *max
);
1455 static const MemoryListener vfio_dirty_tracking_listener
= {
1456 .name
= "vfio-tracking",
1457 .region_add
= vfio_dirty_tracking_update
,
1460 static void vfio_dirty_tracking_init(VFIOContainer
*container
,
1461 VFIODirtyRanges
*ranges
)
1463 VFIODirtyRangesListener dirty
;
1465 memset(&dirty
, 0, sizeof(dirty
));
1466 dirty
.ranges
.min32
= UINT32_MAX
;
1467 dirty
.ranges
.min64
= UINT64_MAX
;
1468 dirty
.listener
= vfio_dirty_tracking_listener
;
1469 dirty
.container
= container
;
1471 memory_listener_register(&dirty
.listener
,
1472 container
->space
->as
);
1474 *ranges
= dirty
.ranges
;
1477 * The memory listener is synchronous, and used to calculate the range
1478 * to dirty tracking. Unregister it after we are done as we are not
1479 * interested in any follow-up updates.
1481 memory_listener_unregister(&dirty
.listener
);
1484 static void vfio_devices_dma_logging_stop(VFIOContainer
*container
)
1486 uint64_t buf
[DIV_ROUND_UP(sizeof(struct vfio_device_feature
),
1487 sizeof(uint64_t))] = {};
1488 struct vfio_device_feature
*feature
= (struct vfio_device_feature
*)buf
;
1489 VFIODevice
*vbasedev
;
1492 feature
->argsz
= sizeof(buf
);
1493 feature
->flags
= VFIO_DEVICE_FEATURE_SET
|
1494 VFIO_DEVICE_FEATURE_DMA_LOGGING_STOP
;
1496 QLIST_FOREACH(group
, &container
->group_list
, container_next
) {
1497 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
1498 if (!vbasedev
->dirty_tracking
) {
1502 if (ioctl(vbasedev
->fd
, VFIO_DEVICE_FEATURE
, feature
)) {
1503 warn_report("%s: Failed to stop DMA logging, err %d (%s)",
1504 vbasedev
->name
, -errno
, strerror(errno
));
1506 vbasedev
->dirty_tracking
= false;
1511 static struct vfio_device_feature
*
1512 vfio_device_feature_dma_logging_start_create(VFIOContainer
*container
,
1513 VFIODirtyRanges
*tracking
)
1515 struct vfio_device_feature
*feature
;
1516 size_t feature_size
;
1517 struct vfio_device_feature_dma_logging_control
*control
;
1518 struct vfio_device_feature_dma_logging_range
*ranges
;
1520 feature_size
= sizeof(struct vfio_device_feature
) +
1521 sizeof(struct vfio_device_feature_dma_logging_control
);
1522 feature
= g_try_malloc0(feature_size
);
1527 feature
->argsz
= feature_size
;
1528 feature
->flags
= VFIO_DEVICE_FEATURE_SET
|
1529 VFIO_DEVICE_FEATURE_DMA_LOGGING_START
;
1531 control
= (struct vfio_device_feature_dma_logging_control
*)feature
->data
;
1532 control
->page_size
= qemu_real_host_page_size();
1535 * DMA logging uAPI guarantees to support at least a number of ranges that
1536 * fits into a single host kernel base page.
1538 control
->num_ranges
= !!tracking
->max32
+ !!tracking
->max64
;
1539 ranges
= g_try_new0(struct vfio_device_feature_dma_logging_range
,
1540 control
->num_ranges
);
1548 control
->ranges
= (__u64
)(uintptr_t)ranges
;
1549 if (tracking
->max32
) {
1550 ranges
->iova
= tracking
->min32
;
1551 ranges
->length
= (tracking
->max32
- tracking
->min32
) + 1;
1554 if (tracking
->max64
) {
1555 ranges
->iova
= tracking
->min64
;
1556 ranges
->length
= (tracking
->max64
- tracking
->min64
) + 1;
1559 trace_vfio_device_dirty_tracking_start(control
->num_ranges
,
1560 tracking
->min32
, tracking
->max32
,
1561 tracking
->min64
, tracking
->max64
);
1566 static void vfio_device_feature_dma_logging_start_destroy(
1567 struct vfio_device_feature
*feature
)
1569 struct vfio_device_feature_dma_logging_control
*control
=
1570 (struct vfio_device_feature_dma_logging_control
*)feature
->data
;
1571 struct vfio_device_feature_dma_logging_range
*ranges
=
1572 (struct vfio_device_feature_dma_logging_range
*)(uintptr_t)control
->ranges
;
1578 static int vfio_devices_dma_logging_start(VFIOContainer
*container
)
1580 struct vfio_device_feature
*feature
;
1581 VFIODirtyRanges ranges
;
1582 VFIODevice
*vbasedev
;
1586 vfio_dirty_tracking_init(container
, &ranges
);
1587 feature
= vfio_device_feature_dma_logging_start_create(container
,
1593 QLIST_FOREACH(group
, &container
->group_list
, container_next
) {
1594 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
1595 if (vbasedev
->dirty_tracking
) {
1599 ret
= ioctl(vbasedev
->fd
, VFIO_DEVICE_FEATURE
, feature
);
1602 error_report("%s: Failed to start DMA logging, err %d (%s)",
1603 vbasedev
->name
, ret
, strerror(errno
));
1606 vbasedev
->dirty_tracking
= true;
1612 vfio_devices_dma_logging_stop(container
);
1615 vfio_device_feature_dma_logging_start_destroy(feature
);
1620 static void vfio_listener_log_global_start(MemoryListener
*listener
)
1622 VFIOContainer
*container
= container_of(listener
, VFIOContainer
, listener
);
1625 if (vfio_devices_all_device_dirty_tracking(container
)) {
1626 ret
= vfio_devices_dma_logging_start(container
);
1628 ret
= vfio_set_dirty_page_tracking(container
, true);
1632 error_report("vfio: Could not start dirty page tracking, err: %d (%s)",
1633 ret
, strerror(-ret
));
1634 vfio_set_migration_error(ret
);
1638 static void vfio_listener_log_global_stop(MemoryListener
*listener
)
1640 VFIOContainer
*container
= container_of(listener
, VFIOContainer
, listener
);
1643 if (vfio_devices_all_device_dirty_tracking(container
)) {
1644 vfio_devices_dma_logging_stop(container
);
1646 ret
= vfio_set_dirty_page_tracking(container
, false);
1650 error_report("vfio: Could not stop dirty page tracking, err: %d (%s)",
1651 ret
, strerror(-ret
));
1652 vfio_set_migration_error(ret
);
1656 static int vfio_device_dma_logging_report(VFIODevice
*vbasedev
, hwaddr iova
,
1657 hwaddr size
, void *bitmap
)
1659 uint64_t buf
[DIV_ROUND_UP(sizeof(struct vfio_device_feature
) +
1660 sizeof(struct vfio_device_feature_dma_logging_report
),
1661 sizeof(__u64
))] = {};
1662 struct vfio_device_feature
*feature
= (struct vfio_device_feature
*)buf
;
1663 struct vfio_device_feature_dma_logging_report
*report
=
1664 (struct vfio_device_feature_dma_logging_report
*)feature
->data
;
1666 report
->iova
= iova
;
1667 report
->length
= size
;
1668 report
->page_size
= qemu_real_host_page_size();
1669 report
->bitmap
= (__u64
)(uintptr_t)bitmap
;
1671 feature
->argsz
= sizeof(buf
);
1672 feature
->flags
= VFIO_DEVICE_FEATURE_GET
|
1673 VFIO_DEVICE_FEATURE_DMA_LOGGING_REPORT
;
1675 if (ioctl(vbasedev
->fd
, VFIO_DEVICE_FEATURE
, feature
)) {
1682 static int vfio_devices_query_dirty_bitmap(VFIOContainer
*container
,
1683 VFIOBitmap
*vbmap
, hwaddr iova
,
1686 VFIODevice
*vbasedev
;
1690 QLIST_FOREACH(group
, &container
->group_list
, container_next
) {
1691 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
1692 ret
= vfio_device_dma_logging_report(vbasedev
, iova
, size
,
1695 error_report("%s: Failed to get DMA logging report, iova: "
1696 "0x%" HWADDR_PRIx
", size: 0x%" HWADDR_PRIx
1698 vbasedev
->name
, iova
, size
, ret
, strerror(-ret
));
1708 static int vfio_query_dirty_bitmap(VFIOContainer
*container
, VFIOBitmap
*vbmap
,
1709 hwaddr iova
, hwaddr size
)
1711 struct vfio_iommu_type1_dirty_bitmap
*dbitmap
;
1712 struct vfio_iommu_type1_dirty_bitmap_get
*range
;
1715 dbitmap
= g_malloc0(sizeof(*dbitmap
) + sizeof(*range
));
1717 dbitmap
->argsz
= sizeof(*dbitmap
) + sizeof(*range
);
1718 dbitmap
->flags
= VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP
;
1719 range
= (struct vfio_iommu_type1_dirty_bitmap_get
*)&dbitmap
->data
;
1724 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
1725 * qemu_real_host_page_size to mark those dirty. Hence set bitmap's pgsize
1726 * to qemu_real_host_page_size.
1728 range
->bitmap
.pgsize
= qemu_real_host_page_size();
1729 range
->bitmap
.size
= vbmap
->size
;
1730 range
->bitmap
.data
= (__u64
*)vbmap
->bitmap
;
1732 ret
= ioctl(container
->fd
, VFIO_IOMMU_DIRTY_PAGES
, dbitmap
);
1735 error_report("Failed to get dirty bitmap for iova: 0x%"PRIx64
1736 " size: 0x%"PRIx64
" err: %d", (uint64_t)range
->iova
,
1737 (uint64_t)range
->size
, errno
);
1745 static int vfio_get_dirty_bitmap(VFIOContainer
*container
, uint64_t iova
,
1746 uint64_t size
, ram_addr_t ram_addr
)
1748 bool all_device_dirty_tracking
=
1749 vfio_devices_all_device_dirty_tracking(container
);
1753 if (!container
->dirty_pages_supported
&& !all_device_dirty_tracking
) {
1754 cpu_physical_memory_set_dirty_range(ram_addr
, size
,
1755 tcg_enabled() ? DIRTY_CLIENTS_ALL
:
1756 DIRTY_CLIENTS_NOCODE
);
1760 ret
= vfio_bitmap_alloc(&vbmap
, size
);
1765 if (all_device_dirty_tracking
) {
1766 ret
= vfio_devices_query_dirty_bitmap(container
, &vbmap
, iova
, size
);
1768 ret
= vfio_query_dirty_bitmap(container
, &vbmap
, iova
, size
);
1775 cpu_physical_memory_set_dirty_lebitmap(vbmap
.bitmap
, ram_addr
,
1778 trace_vfio_get_dirty_bitmap(container
->fd
, iova
, size
, vbmap
.size
,
1781 g_free(vbmap
.bitmap
);
1788 VFIOGuestIOMMU
*giommu
;
1789 } vfio_giommu_dirty_notifier
;
1791 static void vfio_iommu_map_dirty_notify(IOMMUNotifier
*n
, IOMMUTLBEntry
*iotlb
)
1793 vfio_giommu_dirty_notifier
*gdn
= container_of(n
,
1794 vfio_giommu_dirty_notifier
, n
);
1795 VFIOGuestIOMMU
*giommu
= gdn
->giommu
;
1796 VFIOContainer
*container
= giommu
->container
;
1797 hwaddr iova
= iotlb
->iova
+ giommu
->iommu_offset
;
1798 ram_addr_t translated_addr
;
1801 trace_vfio_iommu_map_dirty_notify(iova
, iova
+ iotlb
->addr_mask
);
1803 if (iotlb
->target_as
!= &address_space_memory
) {
1804 error_report("Wrong target AS \"%s\", only system memory is allowed",
1805 iotlb
->target_as
->name
? iotlb
->target_as
->name
: "none");
1810 if (vfio_get_xlat_addr(iotlb
, NULL
, &translated_addr
, NULL
)) {
1811 ret
= vfio_get_dirty_bitmap(container
, iova
, iotlb
->addr_mask
+ 1,
1814 error_report("vfio_iommu_map_dirty_notify(%p, 0x%"HWADDR_PRIx
", "
1815 "0x%"HWADDR_PRIx
") = %d (%s)",
1816 container
, iova
, iotlb
->addr_mask
+ 1, ret
,
1824 vfio_set_migration_error(ret
);
1828 static int vfio_ram_discard_get_dirty_bitmap(MemoryRegionSection
*section
,
1831 const hwaddr size
= int128_get64(section
->size
);
1832 const hwaddr iova
= section
->offset_within_address_space
;
1833 const ram_addr_t ram_addr
= memory_region_get_ram_addr(section
->mr
) +
1834 section
->offset_within_region
;
1835 VFIORamDiscardListener
*vrdl
= opaque
;
1838 * Sync the whole mapped region (spanning multiple individual mappings)
1841 return vfio_get_dirty_bitmap(vrdl
->container
, iova
, size
, ram_addr
);
1844 static int vfio_sync_ram_discard_listener_dirty_bitmap(VFIOContainer
*container
,
1845 MemoryRegionSection
*section
)
1847 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(section
->mr
);
1848 VFIORamDiscardListener
*vrdl
= NULL
;
1850 QLIST_FOREACH(vrdl
, &container
->vrdl_list
, next
) {
1851 if (vrdl
->mr
== section
->mr
&&
1852 vrdl
->offset_within_address_space
==
1853 section
->offset_within_address_space
) {
1859 hw_error("vfio: Trying to sync missing RAM discard listener");
1863 * We only want/can synchronize the bitmap for actually mapped parts -
1864 * which correspond to populated parts. Replay all populated parts.
1866 return ram_discard_manager_replay_populated(rdm
, section
,
1867 vfio_ram_discard_get_dirty_bitmap
,
1871 static int vfio_sync_dirty_bitmap(VFIOContainer
*container
,
1872 MemoryRegionSection
*section
)
1874 ram_addr_t ram_addr
;
1876 if (memory_region_is_iommu(section
->mr
)) {
1877 VFIOGuestIOMMU
*giommu
;
1879 QLIST_FOREACH(giommu
, &container
->giommu_list
, giommu_next
) {
1880 if (MEMORY_REGION(giommu
->iommu_mr
) == section
->mr
&&
1881 giommu
->n
.start
== section
->offset_within_region
) {
1883 vfio_giommu_dirty_notifier gdn
= { .giommu
= giommu
};
1884 int idx
= memory_region_iommu_attrs_to_index(giommu
->iommu_mr
,
1885 MEMTXATTRS_UNSPECIFIED
);
1887 llend
= int128_add(int128_make64(section
->offset_within_region
),
1889 llend
= int128_sub(llend
, int128_one());
1891 iommu_notifier_init(&gdn
.n
,
1892 vfio_iommu_map_dirty_notify
,
1894 section
->offset_within_region
,
1895 int128_get64(llend
),
1897 memory_region_iommu_replay(giommu
->iommu_mr
, &gdn
.n
);
1902 } else if (memory_region_has_ram_discard_manager(section
->mr
)) {
1903 return vfio_sync_ram_discard_listener_dirty_bitmap(container
, section
);
1906 ram_addr
= memory_region_get_ram_addr(section
->mr
) +
1907 section
->offset_within_region
;
1909 return vfio_get_dirty_bitmap(container
,
1910 REAL_HOST_PAGE_ALIGN(section
->offset_within_address_space
),
1911 int128_get64(section
->size
), ram_addr
);
1914 static void vfio_listener_log_sync(MemoryListener
*listener
,
1915 MemoryRegionSection
*section
)
1917 VFIOContainer
*container
= container_of(listener
, VFIOContainer
, listener
);
1920 if (vfio_listener_skipped_section(section
)) {
1924 if (vfio_devices_all_dirty_tracking(container
)) {
1925 ret
= vfio_sync_dirty_bitmap(container
, section
);
1927 error_report("vfio: Failed to sync dirty bitmap, err: %d (%s)", ret
,
1929 vfio_set_migration_error(ret
);
1934 static const MemoryListener vfio_memory_listener
= {
1936 .region_add
= vfio_listener_region_add
,
1937 .region_del
= vfio_listener_region_del
,
1938 .log_global_start
= vfio_listener_log_global_start
,
1939 .log_global_stop
= vfio_listener_log_global_stop
,
1940 .log_sync
= vfio_listener_log_sync
,
1943 static void vfio_listener_release(VFIOContainer
*container
)
1945 memory_listener_unregister(&container
->listener
);
1946 if (container
->iommu_type
== VFIO_SPAPR_TCE_v2_IOMMU
) {
1947 memory_listener_unregister(&container
->prereg_listener
);
1951 static struct vfio_info_cap_header
*
1952 vfio_get_cap(void *ptr
, uint32_t cap_offset
, uint16_t id
)
1954 struct vfio_info_cap_header
*hdr
;
1956 for (hdr
= ptr
+ cap_offset
; hdr
!= ptr
; hdr
= ptr
+ hdr
->next
) {
1957 if (hdr
->id
== id
) {
1965 struct vfio_info_cap_header
*
1966 vfio_get_region_info_cap(struct vfio_region_info
*info
, uint16_t id
)
1968 if (!(info
->flags
& VFIO_REGION_INFO_FLAG_CAPS
)) {
1972 return vfio_get_cap((void *)info
, info
->cap_offset
, id
);
1975 static struct vfio_info_cap_header
*
1976 vfio_get_iommu_type1_info_cap(struct vfio_iommu_type1_info
*info
, uint16_t id
)
1978 if (!(info
->flags
& VFIO_IOMMU_INFO_CAPS
)) {
1982 return vfio_get_cap((void *)info
, info
->cap_offset
, id
);
1985 struct vfio_info_cap_header
*
1986 vfio_get_device_info_cap(struct vfio_device_info
*info
, uint16_t id
)
1988 if (!(info
->flags
& VFIO_DEVICE_FLAGS_CAPS
)) {
1992 return vfio_get_cap((void *)info
, info
->cap_offset
, id
);
1995 bool vfio_get_info_dma_avail(struct vfio_iommu_type1_info
*info
,
1996 unsigned int *avail
)
1998 struct vfio_info_cap_header
*hdr
;
1999 struct vfio_iommu_type1_info_dma_avail
*cap
;
2001 /* If the capability cannot be found, assume no DMA limiting */
2002 hdr
= vfio_get_iommu_type1_info_cap(info
,
2003 VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL
);
2008 if (avail
!= NULL
) {
2010 *avail
= cap
->avail
;
2016 static int vfio_setup_region_sparse_mmaps(VFIORegion
*region
,
2017 struct vfio_region_info
*info
)
2019 struct vfio_info_cap_header
*hdr
;
2020 struct vfio_region_info_cap_sparse_mmap
*sparse
;
2023 hdr
= vfio_get_region_info_cap(info
, VFIO_REGION_INFO_CAP_SPARSE_MMAP
);
2028 sparse
= container_of(hdr
, struct vfio_region_info_cap_sparse_mmap
, header
);
2030 trace_vfio_region_sparse_mmap_header(region
->vbasedev
->name
,
2031 region
->nr
, sparse
->nr_areas
);
2033 region
->mmaps
= g_new0(VFIOMmap
, sparse
->nr_areas
);
2035 for (i
= 0, j
= 0; i
< sparse
->nr_areas
; i
++) {
2036 if (sparse
->areas
[i
].size
) {
2037 trace_vfio_region_sparse_mmap_entry(i
, sparse
->areas
[i
].offset
,
2038 sparse
->areas
[i
].offset
+
2039 sparse
->areas
[i
].size
- 1);
2040 region
->mmaps
[j
].offset
= sparse
->areas
[i
].offset
;
2041 region
->mmaps
[j
].size
= sparse
->areas
[i
].size
;
2046 region
->nr_mmaps
= j
;
2047 region
->mmaps
= g_realloc(region
->mmaps
, j
* sizeof(VFIOMmap
));
2052 int vfio_region_setup(Object
*obj
, VFIODevice
*vbasedev
, VFIORegion
*region
,
2053 int index
, const char *name
)
2055 struct vfio_region_info
*info
;
2058 ret
= vfio_get_region_info(vbasedev
, index
, &info
);
2063 region
->vbasedev
= vbasedev
;
2064 region
->flags
= info
->flags
;
2065 region
->size
= info
->size
;
2066 region
->fd_offset
= info
->offset
;
2070 region
->mem
= g_new0(MemoryRegion
, 1);
2071 memory_region_init_io(region
->mem
, obj
, &vfio_region_ops
,
2072 region
, name
, region
->size
);
2074 if (!vbasedev
->no_mmap
&&
2075 region
->flags
& VFIO_REGION_INFO_FLAG_MMAP
) {
2077 ret
= vfio_setup_region_sparse_mmaps(region
, info
);
2080 region
->nr_mmaps
= 1;
2081 region
->mmaps
= g_new0(VFIOMmap
, region
->nr_mmaps
);
2082 region
->mmaps
[0].offset
= 0;
2083 region
->mmaps
[0].size
= region
->size
;
2090 trace_vfio_region_setup(vbasedev
->name
, index
, name
,
2091 region
->flags
, region
->fd_offset
, region
->size
);
2095 static void vfio_subregion_unmap(VFIORegion
*region
, int index
)
2097 trace_vfio_region_unmap(memory_region_name(®ion
->mmaps
[index
].mem
),
2098 region
->mmaps
[index
].offset
,
2099 region
->mmaps
[index
].offset
+
2100 region
->mmaps
[index
].size
- 1);
2101 memory_region_del_subregion(region
->mem
, ®ion
->mmaps
[index
].mem
);
2102 munmap(region
->mmaps
[index
].mmap
, region
->mmaps
[index
].size
);
2103 object_unparent(OBJECT(®ion
->mmaps
[index
].mem
));
2104 region
->mmaps
[index
].mmap
= NULL
;
2107 int vfio_region_mmap(VFIORegion
*region
)
2116 prot
|= region
->flags
& VFIO_REGION_INFO_FLAG_READ
? PROT_READ
: 0;
2117 prot
|= region
->flags
& VFIO_REGION_INFO_FLAG_WRITE
? PROT_WRITE
: 0;
2119 for (i
= 0; i
< region
->nr_mmaps
; i
++) {
2120 region
->mmaps
[i
].mmap
= mmap(NULL
, region
->mmaps
[i
].size
, prot
,
2121 MAP_SHARED
, region
->vbasedev
->fd
,
2123 region
->mmaps
[i
].offset
);
2124 if (region
->mmaps
[i
].mmap
== MAP_FAILED
) {
2127 trace_vfio_region_mmap_fault(memory_region_name(region
->mem
), i
,
2129 region
->mmaps
[i
].offset
,
2131 region
->mmaps
[i
].offset
+
2132 region
->mmaps
[i
].size
- 1, ret
);
2134 region
->mmaps
[i
].mmap
= NULL
;
2136 for (i
--; i
>= 0; i
--) {
2137 vfio_subregion_unmap(region
, i
);
2143 name
= g_strdup_printf("%s mmaps[%d]",
2144 memory_region_name(region
->mem
), i
);
2145 memory_region_init_ram_device_ptr(®ion
->mmaps
[i
].mem
,
2146 memory_region_owner(region
->mem
),
2147 name
, region
->mmaps
[i
].size
,
2148 region
->mmaps
[i
].mmap
);
2150 memory_region_add_subregion(region
->mem
, region
->mmaps
[i
].offset
,
2151 ®ion
->mmaps
[i
].mem
);
2153 trace_vfio_region_mmap(memory_region_name(®ion
->mmaps
[i
].mem
),
2154 region
->mmaps
[i
].offset
,
2155 region
->mmaps
[i
].offset
+
2156 region
->mmaps
[i
].size
- 1);
2162 void vfio_region_unmap(VFIORegion
*region
)
2170 for (i
= 0; i
< region
->nr_mmaps
; i
++) {
2171 if (region
->mmaps
[i
].mmap
) {
2172 vfio_subregion_unmap(region
, i
);
2177 void vfio_region_exit(VFIORegion
*region
)
2185 for (i
= 0; i
< region
->nr_mmaps
; i
++) {
2186 if (region
->mmaps
[i
].mmap
) {
2187 memory_region_del_subregion(region
->mem
, ®ion
->mmaps
[i
].mem
);
2191 trace_vfio_region_exit(region
->vbasedev
->name
, region
->nr
);
2194 void vfio_region_finalize(VFIORegion
*region
)
2202 for (i
= 0; i
< region
->nr_mmaps
; i
++) {
2203 if (region
->mmaps
[i
].mmap
) {
2204 munmap(region
->mmaps
[i
].mmap
, region
->mmaps
[i
].size
);
2205 object_unparent(OBJECT(®ion
->mmaps
[i
].mem
));
2209 object_unparent(OBJECT(region
->mem
));
2211 g_free(region
->mem
);
2212 g_free(region
->mmaps
);
2214 trace_vfio_region_finalize(region
->vbasedev
->name
, region
->nr
);
2217 region
->mmaps
= NULL
;
2218 region
->nr_mmaps
= 0;
2224 void vfio_region_mmaps_set_enabled(VFIORegion
*region
, bool enabled
)
2232 for (i
= 0; i
< region
->nr_mmaps
; i
++) {
2233 if (region
->mmaps
[i
].mmap
) {
2234 memory_region_set_enabled(®ion
->mmaps
[i
].mem
, enabled
);
2238 trace_vfio_region_mmaps_set_enabled(memory_region_name(region
->mem
),
2242 void vfio_reset_handler(void *opaque
)
2245 VFIODevice
*vbasedev
;
2247 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
2248 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
2249 if (vbasedev
->dev
->realized
) {
2250 vbasedev
->ops
->vfio_compute_needs_reset(vbasedev
);
2255 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
2256 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
2257 if (vbasedev
->dev
->realized
&& vbasedev
->needs_reset
) {
2258 vbasedev
->ops
->vfio_hot_reset_multi(vbasedev
);
2264 static void vfio_kvm_device_add_group(VFIOGroup
*group
)
2267 struct kvm_device_attr attr
= {
2268 .group
= KVM_DEV_VFIO_GROUP
,
2269 .attr
= KVM_DEV_VFIO_GROUP_ADD
,
2270 .addr
= (uint64_t)(unsigned long)&group
->fd
,
2273 if (!kvm_enabled()) {
2277 if (vfio_kvm_device_fd
< 0) {
2278 struct kvm_create_device cd
= {
2279 .type
= KVM_DEV_TYPE_VFIO
,
2282 if (kvm_vm_ioctl(kvm_state
, KVM_CREATE_DEVICE
, &cd
)) {
2283 error_report("Failed to create KVM VFIO device: %m");
2287 vfio_kvm_device_fd
= cd
.fd
;
2290 if (ioctl(vfio_kvm_device_fd
, KVM_SET_DEVICE_ATTR
, &attr
)) {
2291 error_report("Failed to add group %d to KVM VFIO device: %m",
2297 static void vfio_kvm_device_del_group(VFIOGroup
*group
)
2300 struct kvm_device_attr attr
= {
2301 .group
= KVM_DEV_VFIO_GROUP
,
2302 .attr
= KVM_DEV_VFIO_GROUP_DEL
,
2303 .addr
= (uint64_t)(unsigned long)&group
->fd
,
2306 if (vfio_kvm_device_fd
< 0) {
2310 if (ioctl(vfio_kvm_device_fd
, KVM_SET_DEVICE_ATTR
, &attr
)) {
2311 error_report("Failed to remove group %d from KVM VFIO device: %m",
2317 static VFIOAddressSpace
*vfio_get_address_space(AddressSpace
*as
)
2319 VFIOAddressSpace
*space
;
2321 QLIST_FOREACH(space
, &vfio_address_spaces
, list
) {
2322 if (space
->as
== as
) {
2327 /* No suitable VFIOAddressSpace, create a new one */
2328 space
= g_malloc0(sizeof(*space
));
2330 QLIST_INIT(&space
->containers
);
2332 QLIST_INSERT_HEAD(&vfio_address_spaces
, space
, list
);
2337 static void vfio_put_address_space(VFIOAddressSpace
*space
)
2339 if (QLIST_EMPTY(&space
->containers
)) {
2340 QLIST_REMOVE(space
, list
);
2346 * vfio_get_iommu_type - selects the richest iommu_type (v2 first)
2348 static int vfio_get_iommu_type(VFIOContainer
*container
,
2351 int iommu_types
[] = { VFIO_TYPE1v2_IOMMU
, VFIO_TYPE1_IOMMU
,
2352 VFIO_SPAPR_TCE_v2_IOMMU
, VFIO_SPAPR_TCE_IOMMU
};
2355 for (i
= 0; i
< ARRAY_SIZE(iommu_types
); i
++) {
2356 if (ioctl(container
->fd
, VFIO_CHECK_EXTENSION
, iommu_types
[i
])) {
2357 return iommu_types
[i
];
2360 error_setg(errp
, "No available IOMMU models");
2364 static int vfio_init_container(VFIOContainer
*container
, int group_fd
,
2367 int iommu_type
, ret
;
2369 iommu_type
= vfio_get_iommu_type(container
, errp
);
2370 if (iommu_type
< 0) {
2374 ret
= ioctl(group_fd
, VFIO_GROUP_SET_CONTAINER
, &container
->fd
);
2376 error_setg_errno(errp
, errno
, "Failed to set group container");
2380 while (ioctl(container
->fd
, VFIO_SET_IOMMU
, iommu_type
)) {
2381 if (iommu_type
== VFIO_SPAPR_TCE_v2_IOMMU
) {
2383 * On sPAPR, despite the IOMMU subdriver always advertises v1 and
2384 * v2, the running platform may not support v2 and there is no
2385 * way to guess it until an IOMMU group gets added to the container.
2386 * So in case it fails with v2, try v1 as a fallback.
2388 iommu_type
= VFIO_SPAPR_TCE_IOMMU
;
2391 error_setg_errno(errp
, errno
, "Failed to set iommu for container");
2395 container
->iommu_type
= iommu_type
;
2399 static int vfio_get_iommu_info(VFIOContainer
*container
,
2400 struct vfio_iommu_type1_info
**info
)
2403 size_t argsz
= sizeof(struct vfio_iommu_type1_info
);
2405 *info
= g_new0(struct vfio_iommu_type1_info
, 1);
2407 (*info
)->argsz
= argsz
;
2409 if (ioctl(container
->fd
, VFIO_IOMMU_GET_INFO
, *info
)) {
2415 if (((*info
)->argsz
> argsz
)) {
2416 argsz
= (*info
)->argsz
;
2417 *info
= g_realloc(*info
, argsz
);
2424 static struct vfio_info_cap_header
*
2425 vfio_get_iommu_info_cap(struct vfio_iommu_type1_info
*info
, uint16_t id
)
2427 struct vfio_info_cap_header
*hdr
;
2430 if (!(info
->flags
& VFIO_IOMMU_INFO_CAPS
)) {
2434 for (hdr
= ptr
+ info
->cap_offset
; hdr
!= ptr
; hdr
= ptr
+ hdr
->next
) {
2435 if (hdr
->id
== id
) {
2443 static void vfio_get_iommu_info_migration(VFIOContainer
*container
,
2444 struct vfio_iommu_type1_info
*info
)
2446 struct vfio_info_cap_header
*hdr
;
2447 struct vfio_iommu_type1_info_cap_migration
*cap_mig
;
2449 hdr
= vfio_get_iommu_info_cap(info
, VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION
);
2454 cap_mig
= container_of(hdr
, struct vfio_iommu_type1_info_cap_migration
,
2458 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
2459 * qemu_real_host_page_size to mark those dirty.
2461 if (cap_mig
->pgsize_bitmap
& qemu_real_host_page_size()) {
2462 container
->dirty_pages_supported
= true;
2463 container
->max_dirty_bitmap_size
= cap_mig
->max_dirty_bitmap_size
;
2464 container
->dirty_pgsizes
= cap_mig
->pgsize_bitmap
;
2468 static int vfio_connect_container(VFIOGroup
*group
, AddressSpace
*as
,
2471 VFIOContainer
*container
;
2473 VFIOAddressSpace
*space
;
2475 space
= vfio_get_address_space(as
);
2478 * VFIO is currently incompatible with discarding of RAM insofar as the
2479 * madvise to purge (zap) the page from QEMU's address space does not
2480 * interact with the memory API and therefore leaves stale virtual to
2481 * physical mappings in the IOMMU if the page was previously pinned. We
2482 * therefore set discarding broken for each group added to a container,
2483 * whether the container is used individually or shared. This provides
2484 * us with options to allow devices within a group to opt-in and allow
2485 * discarding, so long as it is done consistently for a group (for instance
2486 * if the device is an mdev device where it is known that the host vendor
2487 * driver will never pin pages outside of the working set of the guest
2488 * driver, which would thus not be discarding candidates).
2490 * The first opportunity to induce pinning occurs here where we attempt to
2491 * attach the group to existing containers within the AddressSpace. If any
2492 * pages are already zapped from the virtual address space, such as from
2493 * previous discards, new pinning will cause valid mappings to be
2494 * re-established. Likewise, when the overall MemoryListener for a new
2495 * container is registered, a replay of mappings within the AddressSpace
2496 * will occur, re-establishing any previously zapped pages as well.
2498 * Especially virtio-balloon is currently only prevented from discarding
2499 * new memory, it will not yet set ram_block_discard_set_required() and
2500 * therefore, neither stops us here or deals with the sudden memory
2501 * consumption of inflated memory.
2503 * We do support discarding of memory coordinated via the RamDiscardManager
2504 * with some IOMMU types. vfio_ram_block_discard_disable() handles the
2505 * details once we know which type of IOMMU we are using.
2508 QLIST_FOREACH(container
, &space
->containers
, next
) {
2509 if (!ioctl(group
->fd
, VFIO_GROUP_SET_CONTAINER
, &container
->fd
)) {
2510 ret
= vfio_ram_block_discard_disable(container
, true);
2512 error_setg_errno(errp
, -ret
,
2513 "Cannot set discarding of RAM broken");
2514 if (ioctl(group
->fd
, VFIO_GROUP_UNSET_CONTAINER
,
2516 error_report("vfio: error disconnecting group %d from"
2517 " container", group
->groupid
);
2521 group
->container
= container
;
2522 QLIST_INSERT_HEAD(&container
->group_list
, group
, container_next
);
2523 vfio_kvm_device_add_group(group
);
2528 fd
= qemu_open_old("/dev/vfio/vfio", O_RDWR
);
2530 error_setg_errno(errp
, errno
, "failed to open /dev/vfio/vfio");
2532 goto put_space_exit
;
2535 ret
= ioctl(fd
, VFIO_GET_API_VERSION
);
2536 if (ret
!= VFIO_API_VERSION
) {
2537 error_setg(errp
, "supported vfio version: %d, "
2538 "reported version: %d", VFIO_API_VERSION
, ret
);
2543 container
= g_malloc0(sizeof(*container
));
2544 container
->space
= space
;
2546 container
->error
= NULL
;
2547 container
->dirty_pages_supported
= false;
2548 container
->dma_max_mappings
= 0;
2549 QLIST_INIT(&container
->giommu_list
);
2550 QLIST_INIT(&container
->hostwin_list
);
2551 QLIST_INIT(&container
->vrdl_list
);
2553 ret
= vfio_init_container(container
, group
->fd
, errp
);
2555 goto free_container_exit
;
2558 ret
= vfio_ram_block_discard_disable(container
, true);
2560 error_setg_errno(errp
, -ret
, "Cannot set discarding of RAM broken");
2561 goto free_container_exit
;
2564 switch (container
->iommu_type
) {
2565 case VFIO_TYPE1v2_IOMMU
:
2566 case VFIO_TYPE1_IOMMU
:
2568 struct vfio_iommu_type1_info
*info
;
2570 ret
= vfio_get_iommu_info(container
, &info
);
2572 error_setg_errno(errp
, -ret
, "Failed to get VFIO IOMMU info");
2573 goto enable_discards_exit
;
2576 if (info
->flags
& VFIO_IOMMU_INFO_PGSIZES
) {
2577 container
->pgsizes
= info
->iova_pgsizes
;
2579 container
->pgsizes
= qemu_real_host_page_size();
2582 if (!vfio_get_info_dma_avail(info
, &container
->dma_max_mappings
)) {
2583 container
->dma_max_mappings
= 65535;
2585 vfio_get_iommu_info_migration(container
, info
);
2589 * FIXME: We should parse VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE
2590 * information to get the actual window extent rather than assume
2591 * a 64-bit IOVA address space.
2593 vfio_host_win_add(container
, 0, (hwaddr
)-1, container
->pgsizes
);
2597 case VFIO_SPAPR_TCE_v2_IOMMU
:
2598 case VFIO_SPAPR_TCE_IOMMU
:
2600 struct vfio_iommu_spapr_tce_info info
;
2601 bool v2
= container
->iommu_type
== VFIO_SPAPR_TCE_v2_IOMMU
;
2604 * The host kernel code implementing VFIO_IOMMU_DISABLE is called
2605 * when container fd is closed so we do not call it explicitly
2609 ret
= ioctl(fd
, VFIO_IOMMU_ENABLE
);
2611 error_setg_errno(errp
, errno
, "failed to enable container");
2613 goto enable_discards_exit
;
2616 container
->prereg_listener
= vfio_prereg_listener
;
2618 memory_listener_register(&container
->prereg_listener
,
2619 &address_space_memory
);
2620 if (container
->error
) {
2621 memory_listener_unregister(&container
->prereg_listener
);
2623 error_propagate_prepend(errp
, container
->error
,
2624 "RAM memory listener initialization failed: ");
2625 goto enable_discards_exit
;
2629 info
.argsz
= sizeof(info
);
2630 ret
= ioctl(fd
, VFIO_IOMMU_SPAPR_TCE_GET_INFO
, &info
);
2632 error_setg_errno(errp
, errno
,
2633 "VFIO_IOMMU_SPAPR_TCE_GET_INFO failed");
2636 memory_listener_unregister(&container
->prereg_listener
);
2638 goto enable_discards_exit
;
2642 container
->pgsizes
= info
.ddw
.pgsizes
;
2644 * There is a default window in just created container.
2645 * To make region_add/del simpler, we better remove this
2646 * window now and let those iommu_listener callbacks
2647 * create/remove them when needed.
2649 ret
= vfio_spapr_remove_window(container
, info
.dma32_window_start
);
2651 error_setg_errno(errp
, -ret
,
2652 "failed to remove existing window");
2653 goto enable_discards_exit
;
2656 /* The default table uses 4K pages */
2657 container
->pgsizes
= 0x1000;
2658 vfio_host_win_add(container
, info
.dma32_window_start
,
2659 info
.dma32_window_start
+
2660 info
.dma32_window_size
- 1,
2666 vfio_kvm_device_add_group(group
);
2668 QLIST_INIT(&container
->group_list
);
2669 QLIST_INSERT_HEAD(&space
->containers
, container
, next
);
2671 group
->container
= container
;
2672 QLIST_INSERT_HEAD(&container
->group_list
, group
, container_next
);
2674 container
->listener
= vfio_memory_listener
;
2676 memory_listener_register(&container
->listener
, container
->space
->as
);
2678 if (container
->error
) {
2680 error_propagate_prepend(errp
, container
->error
,
2681 "memory listener initialization failed: ");
2682 goto listener_release_exit
;
2685 container
->initialized
= true;
2688 listener_release_exit
:
2689 QLIST_REMOVE(group
, container_next
);
2690 QLIST_REMOVE(container
, next
);
2691 vfio_kvm_device_del_group(group
);
2692 vfio_listener_release(container
);
2694 enable_discards_exit
:
2695 vfio_ram_block_discard_disable(container
, false);
2697 free_container_exit
:
2704 vfio_put_address_space(space
);
2709 static void vfio_disconnect_container(VFIOGroup
*group
)
2711 VFIOContainer
*container
= group
->container
;
2713 QLIST_REMOVE(group
, container_next
);
2714 group
->container
= NULL
;
2717 * Explicitly release the listener first before unset container,
2718 * since unset may destroy the backend container if it's the last
2721 if (QLIST_EMPTY(&container
->group_list
)) {
2722 vfio_listener_release(container
);
2725 if (ioctl(group
->fd
, VFIO_GROUP_UNSET_CONTAINER
, &container
->fd
)) {
2726 error_report("vfio: error disconnecting group %d from container",
2730 if (QLIST_EMPTY(&container
->group_list
)) {
2731 VFIOAddressSpace
*space
= container
->space
;
2732 VFIOGuestIOMMU
*giommu
, *tmp
;
2733 VFIOHostDMAWindow
*hostwin
, *next
;
2735 QLIST_REMOVE(container
, next
);
2737 QLIST_FOREACH_SAFE(giommu
, &container
->giommu_list
, giommu_next
, tmp
) {
2738 memory_region_unregister_iommu_notifier(
2739 MEMORY_REGION(giommu
->iommu_mr
), &giommu
->n
);
2740 QLIST_REMOVE(giommu
, giommu_next
);
2744 QLIST_FOREACH_SAFE(hostwin
, &container
->hostwin_list
, hostwin_next
,
2746 QLIST_REMOVE(hostwin
, hostwin_next
);
2750 trace_vfio_disconnect_container(container
->fd
);
2751 close(container
->fd
);
2754 vfio_put_address_space(space
);
2758 VFIOGroup
*vfio_get_group(int groupid
, AddressSpace
*as
, Error
**errp
)
2762 struct vfio_group_status status
= { .argsz
= sizeof(status
) };
2764 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
2765 if (group
->groupid
== groupid
) {
2766 /* Found it. Now is it already in the right context? */
2767 if (group
->container
->space
->as
== as
) {
2770 error_setg(errp
, "group %d used in multiple address spaces",
2777 group
= g_malloc0(sizeof(*group
));
2779 snprintf(path
, sizeof(path
), "/dev/vfio/%d", groupid
);
2780 group
->fd
= qemu_open_old(path
, O_RDWR
);
2781 if (group
->fd
< 0) {
2782 error_setg_errno(errp
, errno
, "failed to open %s", path
);
2783 goto free_group_exit
;
2786 if (ioctl(group
->fd
, VFIO_GROUP_GET_STATUS
, &status
)) {
2787 error_setg_errno(errp
, errno
, "failed to get group %d status", groupid
);
2791 if (!(status
.flags
& VFIO_GROUP_FLAGS_VIABLE
)) {
2792 error_setg(errp
, "group %d is not viable", groupid
);
2793 error_append_hint(errp
,
2794 "Please ensure all devices within the iommu_group "
2795 "are bound to their vfio bus driver.\n");
2799 group
->groupid
= groupid
;
2800 QLIST_INIT(&group
->device_list
);
2802 if (vfio_connect_container(group
, as
, errp
)) {
2803 error_prepend(errp
, "failed to setup container for group %d: ",
2808 if (QLIST_EMPTY(&vfio_group_list
)) {
2809 qemu_register_reset(vfio_reset_handler
, NULL
);
2812 QLIST_INSERT_HEAD(&vfio_group_list
, group
, next
);
2825 void vfio_put_group(VFIOGroup
*group
)
2827 if (!group
|| !QLIST_EMPTY(&group
->device_list
)) {
2831 if (!group
->ram_block_discard_allowed
) {
2832 vfio_ram_block_discard_disable(group
->container
, false);
2834 vfio_kvm_device_del_group(group
);
2835 vfio_disconnect_container(group
);
2836 QLIST_REMOVE(group
, next
);
2837 trace_vfio_put_group(group
->fd
);
2841 if (QLIST_EMPTY(&vfio_group_list
)) {
2842 qemu_unregister_reset(vfio_reset_handler
, NULL
);
2846 int vfio_get_device(VFIOGroup
*group
, const char *name
,
2847 VFIODevice
*vbasedev
, Error
**errp
)
2849 struct vfio_device_info dev_info
= { .argsz
= sizeof(dev_info
) };
2852 fd
= ioctl(group
->fd
, VFIO_GROUP_GET_DEVICE_FD
, name
);
2854 error_setg_errno(errp
, errno
, "error getting device from group %d",
2856 error_append_hint(errp
,
2857 "Verify all devices in group %d are bound to vfio-<bus> "
2858 "or pci-stub and not already in use\n", group
->groupid
);
2862 ret
= ioctl(fd
, VFIO_DEVICE_GET_INFO
, &dev_info
);
2864 error_setg_errno(errp
, errno
, "error getting device info");
2870 * Set discarding of RAM as not broken for this group if the driver knows
2871 * the device operates compatibly with discarding. Setting must be
2872 * consistent per group, but since compatibility is really only possible
2873 * with mdev currently, we expect singleton groups.
2875 if (vbasedev
->ram_block_discard_allowed
!=
2876 group
->ram_block_discard_allowed
) {
2877 if (!QLIST_EMPTY(&group
->device_list
)) {
2878 error_setg(errp
, "Inconsistent setting of support for discarding "
2879 "RAM (e.g., balloon) within group");
2884 if (!group
->ram_block_discard_allowed
) {
2885 group
->ram_block_discard_allowed
= true;
2886 vfio_ram_block_discard_disable(group
->container
, false);
2891 vbasedev
->group
= group
;
2892 QLIST_INSERT_HEAD(&group
->device_list
, vbasedev
, next
);
2894 vbasedev
->num_irqs
= dev_info
.num_irqs
;
2895 vbasedev
->num_regions
= dev_info
.num_regions
;
2896 vbasedev
->flags
= dev_info
.flags
;
2898 trace_vfio_get_device(name
, dev_info
.flags
, dev_info
.num_regions
,
2901 vbasedev
->reset_works
= !!(dev_info
.flags
& VFIO_DEVICE_FLAGS_RESET
);
2905 void vfio_put_base_device(VFIODevice
*vbasedev
)
2907 if (!vbasedev
->group
) {
2910 QLIST_REMOVE(vbasedev
, next
);
2911 vbasedev
->group
= NULL
;
2912 trace_vfio_put_base_device(vbasedev
->fd
);
2913 close(vbasedev
->fd
);
2916 int vfio_get_region_info(VFIODevice
*vbasedev
, int index
,
2917 struct vfio_region_info
**info
)
2919 size_t argsz
= sizeof(struct vfio_region_info
);
2921 *info
= g_malloc0(argsz
);
2923 (*info
)->index
= index
;
2925 (*info
)->argsz
= argsz
;
2927 if (ioctl(vbasedev
->fd
, VFIO_DEVICE_GET_REGION_INFO
, *info
)) {
2933 if ((*info
)->argsz
> argsz
) {
2934 argsz
= (*info
)->argsz
;
2935 *info
= g_realloc(*info
, argsz
);
2943 int vfio_get_dev_region_info(VFIODevice
*vbasedev
, uint32_t type
,
2944 uint32_t subtype
, struct vfio_region_info
**info
)
2948 for (i
= 0; i
< vbasedev
->num_regions
; i
++) {
2949 struct vfio_info_cap_header
*hdr
;
2950 struct vfio_region_info_cap_type
*cap_type
;
2952 if (vfio_get_region_info(vbasedev
, i
, info
)) {
2956 hdr
= vfio_get_region_info_cap(*info
, VFIO_REGION_INFO_CAP_TYPE
);
2962 cap_type
= container_of(hdr
, struct vfio_region_info_cap_type
, header
);
2964 trace_vfio_get_dev_region(vbasedev
->name
, i
,
2965 cap_type
->type
, cap_type
->subtype
);
2967 if (cap_type
->type
== type
&& cap_type
->subtype
== subtype
) {
2978 bool vfio_has_region_cap(VFIODevice
*vbasedev
, int region
, uint16_t cap_type
)
2980 struct vfio_region_info
*info
= NULL
;
2983 if (!vfio_get_region_info(vbasedev
, region
, &info
)) {
2984 if (vfio_get_region_info_cap(info
, cap_type
)) {
2994 * Interfaces for IBM EEH (Enhanced Error Handling)
2996 static bool vfio_eeh_container_ok(VFIOContainer
*container
)
2999 * As of 2016-03-04 (linux-4.5) the host kernel EEH/VFIO
3000 * implementation is broken if there are multiple groups in a
3001 * container. The hardware works in units of Partitionable
3002 * Endpoints (== IOMMU groups) and the EEH operations naively
3003 * iterate across all groups in the container, without any logic
3004 * to make sure the groups have their state synchronized. For
3005 * certain operations (ENABLE) that might be ok, until an error
3006 * occurs, but for others (GET_STATE) it's clearly broken.
3010 * XXX Once fixed kernels exist, test for them here
3013 if (QLIST_EMPTY(&container
->group_list
)) {
3017 if (QLIST_NEXT(QLIST_FIRST(&container
->group_list
), container_next
)) {
3024 static int vfio_eeh_container_op(VFIOContainer
*container
, uint32_t op
)
3026 struct vfio_eeh_pe_op pe_op
= {
3027 .argsz
= sizeof(pe_op
),
3032 if (!vfio_eeh_container_ok(container
)) {
3033 error_report("vfio/eeh: EEH_PE_OP 0x%x: "
3034 "kernel requires a container with exactly one group", op
);
3038 ret
= ioctl(container
->fd
, VFIO_EEH_PE_OP
, &pe_op
);
3040 error_report("vfio/eeh: EEH_PE_OP 0x%x failed: %m", op
);
3047 static VFIOContainer
*vfio_eeh_as_container(AddressSpace
*as
)
3049 VFIOAddressSpace
*space
= vfio_get_address_space(as
);
3050 VFIOContainer
*container
= NULL
;
3052 if (QLIST_EMPTY(&space
->containers
)) {
3053 /* No containers to act on */
3057 container
= QLIST_FIRST(&space
->containers
);
3059 if (QLIST_NEXT(container
, next
)) {
3060 /* We don't yet have logic to synchronize EEH state across
3061 * multiple containers */
3067 vfio_put_address_space(space
);
3071 bool vfio_eeh_as_ok(AddressSpace
*as
)
3073 VFIOContainer
*container
= vfio_eeh_as_container(as
);
3075 return (container
!= NULL
) && vfio_eeh_container_ok(container
);
3078 int vfio_eeh_as_op(AddressSpace
*as
, uint32_t op
)
3080 VFIOContainer
*container
= vfio_eeh_as_container(as
);
3085 return vfio_eeh_container_op(container
, op
);