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 "sysemu/tpm.h"
45 VFIOGroupList vfio_group_list
=
46 QLIST_HEAD_INITIALIZER(vfio_group_list
);
47 static QLIST_HEAD(, VFIOAddressSpace
) vfio_address_spaces
=
48 QLIST_HEAD_INITIALIZER(vfio_address_spaces
);
52 * We have a single VFIO pseudo device per KVM VM. Once created it lives
53 * for the life of the VM. Closing the file descriptor only drops our
54 * reference to it and the device's reference to kvm. Therefore once
55 * initialized, this file descriptor is only released on QEMU exit and
56 * we'll re-use it should another vfio device be attached before then.
58 static int vfio_kvm_device_fd
= -1;
62 * Common VFIO interrupt disable
64 void vfio_disable_irqindex(VFIODevice
*vbasedev
, int index
)
66 struct vfio_irq_set irq_set
= {
67 .argsz
= sizeof(irq_set
),
68 .flags
= VFIO_IRQ_SET_DATA_NONE
| VFIO_IRQ_SET_ACTION_TRIGGER
,
74 ioctl(vbasedev
->fd
, VFIO_DEVICE_SET_IRQS
, &irq_set
);
77 void vfio_unmask_single_irqindex(VFIODevice
*vbasedev
, int index
)
79 struct vfio_irq_set irq_set
= {
80 .argsz
= sizeof(irq_set
),
81 .flags
= VFIO_IRQ_SET_DATA_NONE
| VFIO_IRQ_SET_ACTION_UNMASK
,
87 ioctl(vbasedev
->fd
, VFIO_DEVICE_SET_IRQS
, &irq_set
);
90 void vfio_mask_single_irqindex(VFIODevice
*vbasedev
, int index
)
92 struct vfio_irq_set irq_set
= {
93 .argsz
= sizeof(irq_set
),
94 .flags
= VFIO_IRQ_SET_DATA_NONE
| VFIO_IRQ_SET_ACTION_MASK
,
100 ioctl(vbasedev
->fd
, VFIO_DEVICE_SET_IRQS
, &irq_set
);
103 static inline const char *action_to_str(int action
)
106 case VFIO_IRQ_SET_ACTION_MASK
:
108 case VFIO_IRQ_SET_ACTION_UNMASK
:
110 case VFIO_IRQ_SET_ACTION_TRIGGER
:
113 return "UNKNOWN ACTION";
117 static const char *index_to_str(VFIODevice
*vbasedev
, int index
)
119 if (vbasedev
->type
!= VFIO_DEVICE_TYPE_PCI
) {
124 case VFIO_PCI_INTX_IRQ_INDEX
:
126 case VFIO_PCI_MSI_IRQ_INDEX
:
128 case VFIO_PCI_MSIX_IRQ_INDEX
:
130 case VFIO_PCI_ERR_IRQ_INDEX
:
132 case VFIO_PCI_REQ_IRQ_INDEX
:
139 static int vfio_ram_block_discard_disable(VFIOContainer
*container
, bool state
)
141 switch (container
->iommu_type
) {
142 case VFIO_TYPE1v2_IOMMU
:
143 case VFIO_TYPE1_IOMMU
:
145 * We support coordinated discarding of RAM via the RamDiscardManager.
147 return ram_block_uncoordinated_discard_disable(state
);
150 * VFIO_SPAPR_TCE_IOMMU most probably works just fine with
151 * RamDiscardManager, however, it is completely untested.
153 * VFIO_SPAPR_TCE_v2_IOMMU with "DMA memory preregistering" does
154 * completely the opposite of managing mapping/pinning dynamically as
155 * required by RamDiscardManager. We would have to special-case sections
156 * with a RamDiscardManager.
158 return ram_block_discard_disable(state
);
162 int vfio_set_irq_signaling(VFIODevice
*vbasedev
, int index
, int subindex
,
163 int action
, int fd
, Error
**errp
)
165 struct vfio_irq_set
*irq_set
;
170 argsz
= sizeof(*irq_set
) + sizeof(*pfd
);
172 irq_set
= g_malloc0(argsz
);
173 irq_set
->argsz
= argsz
;
174 irq_set
->flags
= VFIO_IRQ_SET_DATA_EVENTFD
| action
;
175 irq_set
->index
= index
;
176 irq_set
->start
= subindex
;
178 pfd
= (int32_t *)&irq_set
->data
;
181 if (ioctl(vbasedev
->fd
, VFIO_DEVICE_SET_IRQS
, irq_set
)) {
190 error_setg_errno(errp
, -ret
, "VFIO_DEVICE_SET_IRQS failure");
192 name
= index_to_str(vbasedev
, index
);
194 error_prepend(errp
, "%s-%d: ", name
, subindex
);
196 error_prepend(errp
, "index %d-%d: ", index
, subindex
);
199 "Failed to %s %s eventfd signaling for interrupt ",
200 fd
< 0 ? "tear down" : "set up", action_to_str(action
));
205 * IO Port/MMIO - Beware of the endians, VFIO is always little endian
207 void vfio_region_write(void *opaque
, hwaddr addr
,
208 uint64_t data
, unsigned size
)
210 VFIORegion
*region
= opaque
;
211 VFIODevice
*vbasedev
= region
->vbasedev
;
224 buf
.word
= cpu_to_le16(data
);
227 buf
.dword
= cpu_to_le32(data
);
230 buf
.qword
= cpu_to_le64(data
);
233 hw_error("vfio: unsupported write size, %u bytes", size
);
237 if (pwrite(vbasedev
->fd
, &buf
, size
, region
->fd_offset
+ addr
) != size
) {
238 error_report("%s(%s:region%d+0x%"HWADDR_PRIx
", 0x%"PRIx64
240 __func__
, vbasedev
->name
, region
->nr
,
244 trace_vfio_region_write(vbasedev
->name
, region
->nr
, addr
, data
, size
);
247 * A read or write to a BAR always signals an INTx EOI. This will
248 * do nothing if not pending (including not in INTx mode). We assume
249 * that a BAR access is in response to an interrupt and that BAR
250 * accesses will service the interrupt. Unfortunately, we don't know
251 * which access will service the interrupt, so we're potentially
252 * getting quite a few host interrupts per guest interrupt.
254 vbasedev
->ops
->vfio_eoi(vbasedev
);
257 uint64_t vfio_region_read(void *opaque
,
258 hwaddr addr
, unsigned size
)
260 VFIORegion
*region
= opaque
;
261 VFIODevice
*vbasedev
= region
->vbasedev
;
270 if (pread(vbasedev
->fd
, &buf
, size
, region
->fd_offset
+ addr
) != size
) {
271 error_report("%s(%s:region%d+0x%"HWADDR_PRIx
", %d) failed: %m",
272 __func__
, vbasedev
->name
, region
->nr
,
281 data
= le16_to_cpu(buf
.word
);
284 data
= le32_to_cpu(buf
.dword
);
287 data
= le64_to_cpu(buf
.qword
);
290 hw_error("vfio: unsupported read size, %u bytes", size
);
294 trace_vfio_region_read(vbasedev
->name
, region
->nr
, addr
, size
, data
);
296 /* Same as write above */
297 vbasedev
->ops
->vfio_eoi(vbasedev
);
302 const MemoryRegionOps vfio_region_ops
= {
303 .read
= vfio_region_read
,
304 .write
= vfio_region_write
,
305 .endianness
= DEVICE_LITTLE_ENDIAN
,
307 .min_access_size
= 1,
308 .max_access_size
= 8,
311 .min_access_size
= 1,
312 .max_access_size
= 8,
317 * Device state interfaces
320 bool vfio_mig_active(void)
323 VFIODevice
*vbasedev
;
325 if (QLIST_EMPTY(&vfio_group_list
)) {
329 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
330 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
331 if (vbasedev
->migration_blocker
) {
339 static bool vfio_devices_all_dirty_tracking(VFIOContainer
*container
)
342 VFIODevice
*vbasedev
;
343 MigrationState
*ms
= migrate_get_current();
345 if (!migration_is_setup_or_active(ms
->state
)) {
349 QLIST_FOREACH(group
, &container
->group_list
, container_next
) {
350 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
351 VFIOMigration
*migration
= vbasedev
->migration
;
357 if ((vbasedev
->pre_copy_dirty_page_tracking
== ON_OFF_AUTO_OFF
)
358 && (migration
->device_state
& VFIO_DEVICE_STATE_V1_RUNNING
)) {
366 static bool vfio_devices_all_running_and_saving(VFIOContainer
*container
)
369 VFIODevice
*vbasedev
;
370 MigrationState
*ms
= migrate_get_current();
372 if (!migration_is_setup_or_active(ms
->state
)) {
376 QLIST_FOREACH(group
, &container
->group_list
, container_next
) {
377 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
378 VFIOMigration
*migration
= vbasedev
->migration
;
384 if ((migration
->device_state
& VFIO_DEVICE_STATE_V1_SAVING
) &&
385 (migration
->device_state
& VFIO_DEVICE_STATE_V1_RUNNING
)) {
395 static int vfio_dma_unmap_bitmap(VFIOContainer
*container
,
396 hwaddr iova
, ram_addr_t size
,
397 IOMMUTLBEntry
*iotlb
)
399 struct vfio_iommu_type1_dma_unmap
*unmap
;
400 struct vfio_bitmap
*bitmap
;
401 uint64_t pages
= REAL_HOST_PAGE_ALIGN(size
) / qemu_real_host_page_size();
404 unmap
= g_malloc0(sizeof(*unmap
) + sizeof(*bitmap
));
406 unmap
->argsz
= sizeof(*unmap
) + sizeof(*bitmap
);
409 unmap
->flags
|= VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP
;
410 bitmap
= (struct vfio_bitmap
*)&unmap
->data
;
413 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
414 * qemu_real_host_page_size to mark those dirty. Hence set bitmap_pgsize
415 * to qemu_real_host_page_size.
418 bitmap
->pgsize
= qemu_real_host_page_size();
419 bitmap
->size
= ROUND_UP(pages
, sizeof(__u64
) * BITS_PER_BYTE
) /
422 if (bitmap
->size
> container
->max_dirty_bitmap_size
) {
423 error_report("UNMAP: Size of bitmap too big 0x%"PRIx64
,
424 (uint64_t)bitmap
->size
);
429 bitmap
->data
= g_try_malloc0(bitmap
->size
);
435 ret
= ioctl(container
->fd
, VFIO_IOMMU_UNMAP_DMA
, unmap
);
437 cpu_physical_memory_set_dirty_lebitmap((unsigned long *)bitmap
->data
,
438 iotlb
->translated_addr
, pages
);
440 error_report("VFIO_UNMAP_DMA with DIRTY_BITMAP : %m");
443 g_free(bitmap
->data
);
450 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
452 static int vfio_dma_unmap(VFIOContainer
*container
,
453 hwaddr iova
, ram_addr_t size
,
454 IOMMUTLBEntry
*iotlb
)
456 struct vfio_iommu_type1_dma_unmap unmap
= {
457 .argsz
= sizeof(unmap
),
463 if (iotlb
&& container
->dirty_pages_supported
&&
464 vfio_devices_all_running_and_saving(container
)) {
465 return vfio_dma_unmap_bitmap(container
, iova
, size
, iotlb
);
468 while (ioctl(container
->fd
, VFIO_IOMMU_UNMAP_DMA
, &unmap
)) {
470 * The type1 backend has an off-by-one bug in the kernel (71a7d3d78e3c
471 * v4.15) where an overflow in its wrap-around check prevents us from
472 * unmapping the last page of the address space. Test for the error
473 * condition and re-try the unmap excluding the last page. The
474 * expectation is that we've never mapped the last page anyway and this
475 * unmap request comes via vIOMMU support which also makes it unlikely
476 * that this page is used. This bug was introduced well after type1 v2
477 * support was introduced, so we shouldn't need to test for v1. A fix
478 * is queued for kernel v5.0 so this workaround can be removed once
479 * affected kernels are sufficiently deprecated.
481 if (errno
== EINVAL
&& unmap
.size
&& !(unmap
.iova
+ unmap
.size
) &&
482 container
->iommu_type
== VFIO_TYPE1v2_IOMMU
) {
483 trace_vfio_dma_unmap_overflow_workaround();
484 unmap
.size
-= 1ULL << ctz64(container
->pgsizes
);
487 error_report("VFIO_UNMAP_DMA failed: %s", strerror(errno
));
494 static int vfio_dma_map(VFIOContainer
*container
, hwaddr iova
,
495 ram_addr_t size
, void *vaddr
, bool readonly
)
497 struct vfio_iommu_type1_dma_map map
= {
498 .argsz
= sizeof(map
),
499 .flags
= VFIO_DMA_MAP_FLAG_READ
,
500 .vaddr
= (__u64
)(uintptr_t)vaddr
,
506 map
.flags
|= VFIO_DMA_MAP_FLAG_WRITE
;
510 * Try the mapping, if it fails with EBUSY, unmap the region and try
511 * again. This shouldn't be necessary, but we sometimes see it in
514 if (ioctl(container
->fd
, VFIO_IOMMU_MAP_DMA
, &map
) == 0 ||
515 (errno
== EBUSY
&& vfio_dma_unmap(container
, iova
, size
, NULL
) == 0 &&
516 ioctl(container
->fd
, VFIO_IOMMU_MAP_DMA
, &map
) == 0)) {
520 error_report("VFIO_MAP_DMA failed: %s", strerror(errno
));
524 static void vfio_host_win_add(VFIOContainer
*container
,
525 hwaddr min_iova
, hwaddr max_iova
,
526 uint64_t iova_pgsizes
)
528 VFIOHostDMAWindow
*hostwin
;
530 QLIST_FOREACH(hostwin
, &container
->hostwin_list
, hostwin_next
) {
531 if (ranges_overlap(hostwin
->min_iova
,
532 hostwin
->max_iova
- hostwin
->min_iova
+ 1,
534 max_iova
- min_iova
+ 1)) {
535 hw_error("%s: Overlapped IOMMU are not enabled", __func__
);
539 hostwin
= g_malloc0(sizeof(*hostwin
));
541 hostwin
->min_iova
= min_iova
;
542 hostwin
->max_iova
= max_iova
;
543 hostwin
->iova_pgsizes
= iova_pgsizes
;
544 QLIST_INSERT_HEAD(&container
->hostwin_list
, hostwin
, hostwin_next
);
547 static int vfio_host_win_del(VFIOContainer
*container
, hwaddr min_iova
,
550 VFIOHostDMAWindow
*hostwin
;
552 QLIST_FOREACH(hostwin
, &container
->hostwin_list
, hostwin_next
) {
553 if (hostwin
->min_iova
== min_iova
&& hostwin
->max_iova
== max_iova
) {
554 QLIST_REMOVE(hostwin
, hostwin_next
);
563 static bool vfio_listener_skipped_section(MemoryRegionSection
*section
)
565 return (!memory_region_is_ram(section
->mr
) &&
566 !memory_region_is_iommu(section
->mr
)) ||
567 memory_region_is_protected(section
->mr
) ||
569 * Sizing an enabled 64-bit BAR can cause spurious mappings to
570 * addresses in the upper part of the 64-bit address space. These
571 * are never accessed by the CPU and beyond the address width of
572 * some IOMMU hardware. TODO: VFIO should tell us the IOMMU width.
574 section
->offset_within_address_space
& (1ULL << 63);
577 /* Called with rcu_read_lock held. */
578 static bool vfio_get_xlat_addr(IOMMUTLBEntry
*iotlb
, void **vaddr
,
579 ram_addr_t
*ram_addr
, bool *read_only
)
583 hwaddr len
= iotlb
->addr_mask
+ 1;
584 bool writable
= iotlb
->perm
& IOMMU_WO
;
587 * The IOMMU TLB entry we have just covers translation through
588 * this IOMMU to its immediate target. We need to translate
589 * it the rest of the way through to memory.
591 mr
= address_space_translate(&address_space_memory
,
592 iotlb
->translated_addr
,
593 &xlat
, &len
, writable
,
594 MEMTXATTRS_UNSPECIFIED
);
595 if (!memory_region_is_ram(mr
)) {
596 error_report("iommu map to non memory area %"HWADDR_PRIx
"",
599 } else if (memory_region_has_ram_discard_manager(mr
)) {
600 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(mr
);
601 MemoryRegionSection tmp
= {
603 .offset_within_region
= xlat
,
604 .size
= int128_make64(len
),
608 * Malicious VMs can map memory into the IOMMU, which is expected
609 * to remain discarded. vfio will pin all pages, populating memory.
610 * Disallow that. vmstate priorities make sure any RamDiscardManager
611 * were already restored before IOMMUs are restored.
613 if (!ram_discard_manager_is_populated(rdm
, &tmp
)) {
614 error_report("iommu map to discarded memory (e.g., unplugged via"
615 " virtio-mem): %"HWADDR_PRIx
"",
616 iotlb
->translated_addr
);
621 * Malicious VMs might trigger discarding of IOMMU-mapped memory. The
622 * pages will remain pinned inside vfio until unmapped, resulting in a
623 * higher memory consumption than expected. If memory would get
624 * populated again later, there would be an inconsistency between pages
625 * pinned by vfio and pages seen by QEMU. This is the case until
626 * unmapped from the IOMMU (e.g., during device reset).
628 * With malicious guests, we really only care about pinning more memory
629 * than expected. RLIMIT_MEMLOCK set for the user/process can never be
630 * exceeded and can be used to mitigate this problem.
632 warn_report_once("Using vfio with vIOMMUs and coordinated discarding of"
633 " RAM (e.g., virtio-mem) works, however, malicious"
634 " guests can trigger pinning of more memory than"
635 " intended via an IOMMU. It's possible to mitigate "
636 " by setting/adjusting RLIMIT_MEMLOCK.");
640 * Translation truncates length to the IOMMU page size,
641 * check that it did not truncate too much.
643 if (len
& iotlb
->addr_mask
) {
644 error_report("iommu has granularity incompatible with target AS");
649 *vaddr
= memory_region_get_ram_ptr(mr
) + xlat
;
653 *ram_addr
= memory_region_get_ram_addr(mr
) + xlat
;
657 *read_only
= !writable
|| mr
->readonly
;
663 static void vfio_iommu_map_notify(IOMMUNotifier
*n
, IOMMUTLBEntry
*iotlb
)
665 VFIOGuestIOMMU
*giommu
= container_of(n
, VFIOGuestIOMMU
, n
);
666 VFIOContainer
*container
= giommu
->container
;
667 hwaddr iova
= iotlb
->iova
+ giommu
->iommu_offset
;
671 trace_vfio_iommu_map_notify(iotlb
->perm
== IOMMU_NONE
? "UNMAP" : "MAP",
672 iova
, iova
+ iotlb
->addr_mask
);
674 if (iotlb
->target_as
!= &address_space_memory
) {
675 error_report("Wrong target AS \"%s\", only system memory is allowed",
676 iotlb
->target_as
->name
? iotlb
->target_as
->name
: "none");
682 if ((iotlb
->perm
& IOMMU_RW
) != IOMMU_NONE
) {
685 if (!vfio_get_xlat_addr(iotlb
, &vaddr
, NULL
, &read_only
)) {
689 * vaddr is only valid until rcu_read_unlock(). But after
690 * vfio_dma_map has set up the mapping the pages will be
691 * pinned by the kernel. This makes sure that the RAM backend
692 * of vaddr will always be there, even if the memory object is
693 * destroyed and its backing memory munmap-ed.
695 ret
= vfio_dma_map(container
, iova
,
696 iotlb
->addr_mask
+ 1, vaddr
,
699 error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx
", "
700 "0x%"HWADDR_PRIx
", %p) = %d (%m)",
702 iotlb
->addr_mask
+ 1, vaddr
, ret
);
705 ret
= vfio_dma_unmap(container
, iova
, iotlb
->addr_mask
+ 1, iotlb
);
707 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx
", "
708 "0x%"HWADDR_PRIx
") = %d (%m)",
710 iotlb
->addr_mask
+ 1, ret
);
717 static void vfio_ram_discard_notify_discard(RamDiscardListener
*rdl
,
718 MemoryRegionSection
*section
)
720 VFIORamDiscardListener
*vrdl
= container_of(rdl
, VFIORamDiscardListener
,
722 const hwaddr size
= int128_get64(section
->size
);
723 const hwaddr iova
= section
->offset_within_address_space
;
726 /* Unmap with a single call. */
727 ret
= vfio_dma_unmap(vrdl
->container
, iova
, size
, NULL
);
729 error_report("%s: vfio_dma_unmap() failed: %s", __func__
,
734 static int vfio_ram_discard_notify_populate(RamDiscardListener
*rdl
,
735 MemoryRegionSection
*section
)
737 VFIORamDiscardListener
*vrdl
= container_of(rdl
, VFIORamDiscardListener
,
739 const hwaddr end
= section
->offset_within_region
+
740 int128_get64(section
->size
);
741 hwaddr start
, next
, iova
;
746 * Map in (aligned within memory region) minimum granularity, so we can
747 * unmap in minimum granularity later.
749 for (start
= section
->offset_within_region
; start
< end
; start
= next
) {
750 next
= ROUND_UP(start
+ 1, vrdl
->granularity
);
751 next
= MIN(next
, end
);
753 iova
= start
- section
->offset_within_region
+
754 section
->offset_within_address_space
;
755 vaddr
= memory_region_get_ram_ptr(section
->mr
) + start
;
757 ret
= vfio_dma_map(vrdl
->container
, iova
, next
- start
,
758 vaddr
, section
->readonly
);
761 vfio_ram_discard_notify_discard(rdl
, section
);
768 static void vfio_register_ram_discard_listener(VFIOContainer
*container
,
769 MemoryRegionSection
*section
)
771 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(section
->mr
);
772 VFIORamDiscardListener
*vrdl
;
774 /* Ignore some corner cases not relevant in practice. */
775 g_assert(QEMU_IS_ALIGNED(section
->offset_within_region
, TARGET_PAGE_SIZE
));
776 g_assert(QEMU_IS_ALIGNED(section
->offset_within_address_space
,
778 g_assert(QEMU_IS_ALIGNED(int128_get64(section
->size
), TARGET_PAGE_SIZE
));
780 vrdl
= g_new0(VFIORamDiscardListener
, 1);
781 vrdl
->container
= container
;
782 vrdl
->mr
= section
->mr
;
783 vrdl
->offset_within_address_space
= section
->offset_within_address_space
;
784 vrdl
->size
= int128_get64(section
->size
);
785 vrdl
->granularity
= ram_discard_manager_get_min_granularity(rdm
,
788 g_assert(vrdl
->granularity
&& is_power_of_2(vrdl
->granularity
));
789 g_assert(container
->pgsizes
&&
790 vrdl
->granularity
>= 1ULL << ctz64(container
->pgsizes
));
792 ram_discard_listener_init(&vrdl
->listener
,
793 vfio_ram_discard_notify_populate
,
794 vfio_ram_discard_notify_discard
, true);
795 ram_discard_manager_register_listener(rdm
, &vrdl
->listener
, section
);
796 QLIST_INSERT_HEAD(&container
->vrdl_list
, vrdl
, next
);
799 * Sanity-check if we have a theoretically problematic setup where we could
800 * exceed the maximum number of possible DMA mappings over time. We assume
801 * that each mapped section in the same address space as a RamDiscardManager
802 * section consumes exactly one DMA mapping, with the exception of
803 * RamDiscardManager sections; i.e., we don't expect to have gIOMMU sections
804 * in the same address space as RamDiscardManager sections.
806 * We assume that each section in the address space consumes one memslot.
807 * We take the number of KVM memory slots as a best guess for the maximum
808 * number of sections in the address space we could have over time,
809 * also consuming DMA mappings.
811 if (container
->dma_max_mappings
) {
812 unsigned int vrdl_count
= 0, vrdl_mappings
= 0, max_memslots
= 512;
816 max_memslots
= kvm_get_max_memslots();
820 QLIST_FOREACH(vrdl
, &container
->vrdl_list
, next
) {
823 start
= QEMU_ALIGN_DOWN(vrdl
->offset_within_address_space
,
825 end
= ROUND_UP(vrdl
->offset_within_address_space
+ vrdl
->size
,
827 vrdl_mappings
+= (end
- start
) / vrdl
->granularity
;
831 if (vrdl_mappings
+ max_memslots
- vrdl_count
>
832 container
->dma_max_mappings
) {
833 warn_report("%s: possibly running out of DMA mappings. E.g., try"
834 " increasing the 'block-size' of virtio-mem devies."
835 " Maximum possible DMA mappings: %d, Maximum possible"
836 " memslots: %d", __func__
, container
->dma_max_mappings
,
842 static void vfio_unregister_ram_discard_listener(VFIOContainer
*container
,
843 MemoryRegionSection
*section
)
845 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(section
->mr
);
846 VFIORamDiscardListener
*vrdl
= NULL
;
848 QLIST_FOREACH(vrdl
, &container
->vrdl_list
, next
) {
849 if (vrdl
->mr
== section
->mr
&&
850 vrdl
->offset_within_address_space
==
851 section
->offset_within_address_space
) {
857 hw_error("vfio: Trying to unregister missing RAM discard listener");
860 ram_discard_manager_unregister_listener(rdm
, &vrdl
->listener
);
861 QLIST_REMOVE(vrdl
, next
);
865 static bool vfio_known_safe_misalignment(MemoryRegionSection
*section
)
867 MemoryRegion
*mr
= section
->mr
;
869 if (!TPM_IS_CRB(mr
->owner
)) {
873 /* this is a known safe misaligned region, just trace for debug purpose */
874 trace_vfio_known_safe_misalignment(memory_region_name(mr
),
875 section
->offset_within_address_space
,
876 section
->offset_within_region
,
877 qemu_real_host_page_size());
881 static void vfio_listener_region_add(MemoryListener
*listener
,
882 MemoryRegionSection
*section
)
884 VFIOContainer
*container
= container_of(listener
, VFIOContainer
, listener
);
886 Int128 llend
, llsize
;
889 VFIOHostDMAWindow
*hostwin
;
893 if (vfio_listener_skipped_section(section
)) {
894 trace_vfio_listener_region_add_skip(
895 section
->offset_within_address_space
,
896 section
->offset_within_address_space
+
897 int128_get64(int128_sub(section
->size
, int128_one())));
901 if (unlikely((section
->offset_within_address_space
&
902 ~qemu_real_host_page_mask()) !=
903 (section
->offset_within_region
& ~qemu_real_host_page_mask()))) {
904 if (!vfio_known_safe_misalignment(section
)) {
905 error_report("%s received unaligned region %s iova=0x%"PRIx64
906 " offset_within_region=0x%"PRIx64
907 " qemu_real_host_page_size=0x%"PRIxPTR
,
908 __func__
, memory_region_name(section
->mr
),
909 section
->offset_within_address_space
,
910 section
->offset_within_region
,
911 qemu_real_host_page_size());
916 iova
= REAL_HOST_PAGE_ALIGN(section
->offset_within_address_space
);
917 llend
= int128_make64(section
->offset_within_address_space
);
918 llend
= int128_add(llend
, section
->size
);
919 llend
= int128_and(llend
, int128_exts64(qemu_real_host_page_mask()));
921 if (int128_ge(int128_make64(iova
), llend
)) {
922 if (memory_region_is_ram_device(section
->mr
)) {
923 trace_vfio_listener_region_add_no_dma_map(
924 memory_region_name(section
->mr
),
925 section
->offset_within_address_space
,
926 int128_getlo(section
->size
),
927 qemu_real_host_page_size());
931 end
= int128_get64(int128_sub(llend
, int128_one()));
933 if (container
->iommu_type
== VFIO_SPAPR_TCE_v2_IOMMU
) {
936 /* For now intersections are not allowed, we may relax this later */
937 QLIST_FOREACH(hostwin
, &container
->hostwin_list
, hostwin_next
) {
938 if (ranges_overlap(hostwin
->min_iova
,
939 hostwin
->max_iova
- hostwin
->min_iova
+ 1,
940 section
->offset_within_address_space
,
941 int128_get64(section
->size
))) {
943 "region [0x%"PRIx64
",0x%"PRIx64
"] overlaps with existing"
944 "host DMA window [0x%"PRIx64
",0x%"PRIx64
"]",
945 section
->offset_within_address_space
,
946 section
->offset_within_address_space
+
947 int128_get64(section
->size
) - 1,
948 hostwin
->min_iova
, hostwin
->max_iova
);
953 ret
= vfio_spapr_create_window(container
, section
, &pgsize
);
955 error_setg_errno(&err
, -ret
, "Failed to create SPAPR window");
959 vfio_host_win_add(container
, section
->offset_within_address_space
,
960 section
->offset_within_address_space
+
961 int128_get64(section
->size
) - 1, pgsize
);
965 IOMMUMemoryRegion
*iommu_mr
= IOMMU_MEMORY_REGION(section
->mr
);
966 struct kvm_vfio_spapr_tce param
;
967 struct kvm_device_attr attr
= {
968 .group
= KVM_DEV_VFIO_GROUP
,
969 .attr
= KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE
,
970 .addr
= (uint64_t)(unsigned long)¶m
,
973 if (!memory_region_iommu_get_attr(iommu_mr
, IOMMU_ATTR_SPAPR_TCE_FD
,
975 QLIST_FOREACH(group
, &container
->group_list
, container_next
) {
976 param
.groupfd
= group
->fd
;
977 if (ioctl(vfio_kvm_device_fd
, KVM_SET_DEVICE_ATTR
, &attr
)) {
978 error_report("vfio: failed to setup fd %d "
979 "for a group with fd %d: %s",
980 param
.tablefd
, param
.groupfd
,
984 trace_vfio_spapr_group_attach(param
.groupfd
, param
.tablefd
);
991 hostwin_found
= false;
992 QLIST_FOREACH(hostwin
, &container
->hostwin_list
, hostwin_next
) {
993 if (hostwin
->min_iova
<= iova
&& end
<= hostwin
->max_iova
) {
994 hostwin_found
= true;
999 if (!hostwin_found
) {
1000 error_setg(&err
, "Container %p can't map guest IOVA region"
1001 " 0x%"HWADDR_PRIx
"..0x%"HWADDR_PRIx
, container
, iova
, end
);
1005 memory_region_ref(section
->mr
);
1007 if (memory_region_is_iommu(section
->mr
)) {
1008 VFIOGuestIOMMU
*giommu
;
1009 IOMMUMemoryRegion
*iommu_mr
= IOMMU_MEMORY_REGION(section
->mr
);
1012 trace_vfio_listener_region_add_iommu(iova
, end
);
1014 * FIXME: For VFIO iommu types which have KVM acceleration to
1015 * avoid bouncing all map/unmaps through qemu this way, this
1016 * would be the right place to wire that up (tell the KVM
1017 * device emulation the VFIO iommu handles to use).
1019 giommu
= g_malloc0(sizeof(*giommu
));
1020 giommu
->iommu_mr
= iommu_mr
;
1021 giommu
->iommu_offset
= section
->offset_within_address_space
-
1022 section
->offset_within_region
;
1023 giommu
->container
= container
;
1024 llend
= int128_add(int128_make64(section
->offset_within_region
),
1026 llend
= int128_sub(llend
, int128_one());
1027 iommu_idx
= memory_region_iommu_attrs_to_index(iommu_mr
,
1028 MEMTXATTRS_UNSPECIFIED
);
1029 iommu_notifier_init(&giommu
->n
, vfio_iommu_map_notify
,
1030 IOMMU_NOTIFIER_IOTLB_EVENTS
,
1031 section
->offset_within_region
,
1032 int128_get64(llend
),
1035 ret
= memory_region_iommu_set_page_size_mask(giommu
->iommu_mr
,
1043 ret
= memory_region_register_iommu_notifier(section
->mr
, &giommu
->n
,
1049 QLIST_INSERT_HEAD(&container
->giommu_list
, giommu
, giommu_next
);
1050 memory_region_iommu_replay(giommu
->iommu_mr
, &giommu
->n
);
1055 /* Here we assume that memory_region_is_ram(section->mr)==true */
1058 * For RAM memory regions with a RamDiscardManager, we only want to map the
1059 * actually populated parts - and update the mapping whenever we're notified
1062 if (memory_region_has_ram_discard_manager(section
->mr
)) {
1063 vfio_register_ram_discard_listener(container
, section
);
1067 vaddr
= memory_region_get_ram_ptr(section
->mr
) +
1068 section
->offset_within_region
+
1069 (iova
- section
->offset_within_address_space
);
1071 trace_vfio_listener_region_add_ram(iova
, end
, vaddr
);
1073 llsize
= int128_sub(llend
, int128_make64(iova
));
1075 if (memory_region_is_ram_device(section
->mr
)) {
1076 hwaddr pgmask
= (1ULL << ctz64(hostwin
->iova_pgsizes
)) - 1;
1078 if ((iova
& pgmask
) || (int128_get64(llsize
) & pgmask
)) {
1079 trace_vfio_listener_region_add_no_dma_map(
1080 memory_region_name(section
->mr
),
1081 section
->offset_within_address_space
,
1082 int128_getlo(section
->size
),
1088 ret
= vfio_dma_map(container
, iova
, int128_get64(llsize
),
1089 vaddr
, section
->readonly
);
1091 error_setg(&err
, "vfio_dma_map(%p, 0x%"HWADDR_PRIx
", "
1092 "0x%"HWADDR_PRIx
", %p) = %d (%m)",
1093 container
, iova
, int128_get64(llsize
), vaddr
, ret
);
1094 if (memory_region_is_ram_device(section
->mr
)) {
1095 /* Allow unexpected mappings not to be fatal for RAM devices */
1096 error_report_err(err
);
1105 if (memory_region_is_ram_device(section
->mr
)) {
1106 error_report("failed to vfio_dma_map. pci p2p may not work");
1110 * On the initfn path, store the first error in the container so we
1111 * can gracefully fail. Runtime, there's not much we can do other
1112 * than throw a hardware error.
1114 if (!container
->initialized
) {
1115 if (!container
->error
) {
1116 error_propagate_prepend(&container
->error
, err
,
1118 memory_region_name(section
->mr
));
1123 error_report_err(err
);
1124 hw_error("vfio: DMA mapping failed, unable to continue");
1128 static void vfio_listener_region_del(MemoryListener
*listener
,
1129 MemoryRegionSection
*section
)
1131 VFIOContainer
*container
= container_of(listener
, VFIOContainer
, listener
);
1133 Int128 llend
, llsize
;
1135 bool try_unmap
= true;
1137 if (vfio_listener_skipped_section(section
)) {
1138 trace_vfio_listener_region_del_skip(
1139 section
->offset_within_address_space
,
1140 section
->offset_within_address_space
+
1141 int128_get64(int128_sub(section
->size
, int128_one())));
1145 if (unlikely((section
->offset_within_address_space
&
1146 ~qemu_real_host_page_mask()) !=
1147 (section
->offset_within_region
& ~qemu_real_host_page_mask()))) {
1148 if (!vfio_known_safe_misalignment(section
)) {
1149 error_report("%s received unaligned region %s iova=0x%"PRIx64
1150 " offset_within_region=0x%"PRIx64
1151 " qemu_real_host_page_size=0x%"PRIxPTR
,
1152 __func__
, memory_region_name(section
->mr
),
1153 section
->offset_within_address_space
,
1154 section
->offset_within_region
,
1155 qemu_real_host_page_size());
1160 if (memory_region_is_iommu(section
->mr
)) {
1161 VFIOGuestIOMMU
*giommu
;
1163 QLIST_FOREACH(giommu
, &container
->giommu_list
, giommu_next
) {
1164 if (MEMORY_REGION(giommu
->iommu_mr
) == section
->mr
&&
1165 giommu
->n
.start
== section
->offset_within_region
) {
1166 memory_region_unregister_iommu_notifier(section
->mr
,
1168 QLIST_REMOVE(giommu
, giommu_next
);
1175 * FIXME: We assume the one big unmap below is adequate to
1176 * remove any individual page mappings in the IOMMU which
1177 * might have been copied into VFIO. This works for a page table
1178 * based IOMMU where a big unmap flattens a large range of IO-PTEs.
1179 * That may not be true for all IOMMU types.
1183 iova
= REAL_HOST_PAGE_ALIGN(section
->offset_within_address_space
);
1184 llend
= int128_make64(section
->offset_within_address_space
);
1185 llend
= int128_add(llend
, section
->size
);
1186 llend
= int128_and(llend
, int128_exts64(qemu_real_host_page_mask()));
1188 if (int128_ge(int128_make64(iova
), llend
)) {
1191 end
= int128_get64(int128_sub(llend
, int128_one()));
1193 llsize
= int128_sub(llend
, int128_make64(iova
));
1195 trace_vfio_listener_region_del(iova
, end
);
1197 if (memory_region_is_ram_device(section
->mr
)) {
1199 VFIOHostDMAWindow
*hostwin
;
1200 bool hostwin_found
= false;
1202 QLIST_FOREACH(hostwin
, &container
->hostwin_list
, hostwin_next
) {
1203 if (hostwin
->min_iova
<= iova
&& end
<= hostwin
->max_iova
) {
1204 hostwin_found
= true;
1208 assert(hostwin_found
); /* or region_add() would have failed */
1210 pgmask
= (1ULL << ctz64(hostwin
->iova_pgsizes
)) - 1;
1211 try_unmap
= !((iova
& pgmask
) || (int128_get64(llsize
) & pgmask
));
1212 } else if (memory_region_has_ram_discard_manager(section
->mr
)) {
1213 vfio_unregister_ram_discard_listener(container
, section
);
1214 /* Unregistering will trigger an unmap. */
1219 if (int128_eq(llsize
, int128_2_64())) {
1220 /* The unmap ioctl doesn't accept a full 64-bit span. */
1221 llsize
= int128_rshift(llsize
, 1);
1222 ret
= vfio_dma_unmap(container
, iova
, int128_get64(llsize
), NULL
);
1224 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx
", "
1225 "0x%"HWADDR_PRIx
") = %d (%m)",
1226 container
, iova
, int128_get64(llsize
), ret
);
1228 iova
+= int128_get64(llsize
);
1230 ret
= vfio_dma_unmap(container
, iova
, int128_get64(llsize
), NULL
);
1232 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx
", "
1233 "0x%"HWADDR_PRIx
") = %d (%m)",
1234 container
, iova
, int128_get64(llsize
), ret
);
1238 memory_region_unref(section
->mr
);
1240 if (container
->iommu_type
== VFIO_SPAPR_TCE_v2_IOMMU
) {
1241 vfio_spapr_remove_window(container
,
1242 section
->offset_within_address_space
);
1243 if (vfio_host_win_del(container
,
1244 section
->offset_within_address_space
,
1245 section
->offset_within_address_space
+
1246 int128_get64(section
->size
) - 1) < 0) {
1247 hw_error("%s: Cannot delete missing window at %"HWADDR_PRIx
,
1248 __func__
, section
->offset_within_address_space
);
1253 static void vfio_set_dirty_page_tracking(VFIOContainer
*container
, bool start
)
1256 struct vfio_iommu_type1_dirty_bitmap dirty
= {
1257 .argsz
= sizeof(dirty
),
1261 dirty
.flags
= VFIO_IOMMU_DIRTY_PAGES_FLAG_START
;
1263 dirty
.flags
= VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP
;
1266 ret
= ioctl(container
->fd
, VFIO_IOMMU_DIRTY_PAGES
, &dirty
);
1268 error_report("Failed to set dirty tracking flag 0x%x errno: %d",
1269 dirty
.flags
, errno
);
1273 static void vfio_listener_log_global_start(MemoryListener
*listener
)
1275 VFIOContainer
*container
= container_of(listener
, VFIOContainer
, listener
);
1277 vfio_set_dirty_page_tracking(container
, true);
1280 static void vfio_listener_log_global_stop(MemoryListener
*listener
)
1282 VFIOContainer
*container
= container_of(listener
, VFIOContainer
, listener
);
1284 vfio_set_dirty_page_tracking(container
, false);
1287 static int vfio_get_dirty_bitmap(VFIOContainer
*container
, uint64_t iova
,
1288 uint64_t size
, ram_addr_t ram_addr
)
1290 struct vfio_iommu_type1_dirty_bitmap
*dbitmap
;
1291 struct vfio_iommu_type1_dirty_bitmap_get
*range
;
1295 dbitmap
= g_malloc0(sizeof(*dbitmap
) + sizeof(*range
));
1297 dbitmap
->argsz
= sizeof(*dbitmap
) + sizeof(*range
);
1298 dbitmap
->flags
= VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP
;
1299 range
= (struct vfio_iommu_type1_dirty_bitmap_get
*)&dbitmap
->data
;
1304 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
1305 * qemu_real_host_page_size to mark those dirty. Hence set bitmap's pgsize
1306 * to qemu_real_host_page_size.
1308 range
->bitmap
.pgsize
= qemu_real_host_page_size();
1310 pages
= REAL_HOST_PAGE_ALIGN(range
->size
) / qemu_real_host_page_size();
1311 range
->bitmap
.size
= ROUND_UP(pages
, sizeof(__u64
) * BITS_PER_BYTE
) /
1313 range
->bitmap
.data
= g_try_malloc0(range
->bitmap
.size
);
1314 if (!range
->bitmap
.data
) {
1319 ret
= ioctl(container
->fd
, VFIO_IOMMU_DIRTY_PAGES
, dbitmap
);
1321 error_report("Failed to get dirty bitmap for iova: 0x%"PRIx64
1322 " size: 0x%"PRIx64
" err: %d", (uint64_t)range
->iova
,
1323 (uint64_t)range
->size
, errno
);
1327 cpu_physical_memory_set_dirty_lebitmap((unsigned long *)range
->bitmap
.data
,
1330 trace_vfio_get_dirty_bitmap(container
->fd
, range
->iova
, range
->size
,
1331 range
->bitmap
.size
, ram_addr
);
1333 g_free(range
->bitmap
.data
);
1341 VFIOGuestIOMMU
*giommu
;
1342 } vfio_giommu_dirty_notifier
;
1344 static void vfio_iommu_map_dirty_notify(IOMMUNotifier
*n
, IOMMUTLBEntry
*iotlb
)
1346 vfio_giommu_dirty_notifier
*gdn
= container_of(n
,
1347 vfio_giommu_dirty_notifier
, n
);
1348 VFIOGuestIOMMU
*giommu
= gdn
->giommu
;
1349 VFIOContainer
*container
= giommu
->container
;
1350 hwaddr iova
= iotlb
->iova
+ giommu
->iommu_offset
;
1351 ram_addr_t translated_addr
;
1353 trace_vfio_iommu_map_dirty_notify(iova
, iova
+ iotlb
->addr_mask
);
1355 if (iotlb
->target_as
!= &address_space_memory
) {
1356 error_report("Wrong target AS \"%s\", only system memory is allowed",
1357 iotlb
->target_as
->name
? iotlb
->target_as
->name
: "none");
1362 if (vfio_get_xlat_addr(iotlb
, NULL
, &translated_addr
, NULL
)) {
1365 ret
= vfio_get_dirty_bitmap(container
, iova
, iotlb
->addr_mask
+ 1,
1368 error_report("vfio_iommu_map_dirty_notify(%p, 0x%"HWADDR_PRIx
", "
1369 "0x%"HWADDR_PRIx
") = %d (%m)",
1371 iotlb
->addr_mask
+ 1, ret
);
1377 static int vfio_ram_discard_get_dirty_bitmap(MemoryRegionSection
*section
,
1380 const hwaddr size
= int128_get64(section
->size
);
1381 const hwaddr iova
= section
->offset_within_address_space
;
1382 const ram_addr_t ram_addr
= memory_region_get_ram_addr(section
->mr
) +
1383 section
->offset_within_region
;
1384 VFIORamDiscardListener
*vrdl
= opaque
;
1387 * Sync the whole mapped region (spanning multiple individual mappings)
1390 return vfio_get_dirty_bitmap(vrdl
->container
, iova
, size
, ram_addr
);
1393 static int vfio_sync_ram_discard_listener_dirty_bitmap(VFIOContainer
*container
,
1394 MemoryRegionSection
*section
)
1396 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(section
->mr
);
1397 VFIORamDiscardListener
*vrdl
= NULL
;
1399 QLIST_FOREACH(vrdl
, &container
->vrdl_list
, next
) {
1400 if (vrdl
->mr
== section
->mr
&&
1401 vrdl
->offset_within_address_space
==
1402 section
->offset_within_address_space
) {
1408 hw_error("vfio: Trying to sync missing RAM discard listener");
1412 * We only want/can synchronize the bitmap for actually mapped parts -
1413 * which correspond to populated parts. Replay all populated parts.
1415 return ram_discard_manager_replay_populated(rdm
, section
,
1416 vfio_ram_discard_get_dirty_bitmap
,
1420 static int vfio_sync_dirty_bitmap(VFIOContainer
*container
,
1421 MemoryRegionSection
*section
)
1423 ram_addr_t ram_addr
;
1425 if (memory_region_is_iommu(section
->mr
)) {
1426 VFIOGuestIOMMU
*giommu
;
1428 QLIST_FOREACH(giommu
, &container
->giommu_list
, giommu_next
) {
1429 if (MEMORY_REGION(giommu
->iommu_mr
) == section
->mr
&&
1430 giommu
->n
.start
== section
->offset_within_region
) {
1432 vfio_giommu_dirty_notifier gdn
= { .giommu
= giommu
};
1433 int idx
= memory_region_iommu_attrs_to_index(giommu
->iommu_mr
,
1434 MEMTXATTRS_UNSPECIFIED
);
1436 llend
= int128_add(int128_make64(section
->offset_within_region
),
1438 llend
= int128_sub(llend
, int128_one());
1440 iommu_notifier_init(&gdn
.n
,
1441 vfio_iommu_map_dirty_notify
,
1443 section
->offset_within_region
,
1444 int128_get64(llend
),
1446 memory_region_iommu_replay(giommu
->iommu_mr
, &gdn
.n
);
1451 } else if (memory_region_has_ram_discard_manager(section
->mr
)) {
1452 return vfio_sync_ram_discard_listener_dirty_bitmap(container
, section
);
1455 ram_addr
= memory_region_get_ram_addr(section
->mr
) +
1456 section
->offset_within_region
;
1458 return vfio_get_dirty_bitmap(container
,
1459 REAL_HOST_PAGE_ALIGN(section
->offset_within_address_space
),
1460 int128_get64(section
->size
), ram_addr
);
1463 static void vfio_listener_log_sync(MemoryListener
*listener
,
1464 MemoryRegionSection
*section
)
1466 VFIOContainer
*container
= container_of(listener
, VFIOContainer
, listener
);
1468 if (vfio_listener_skipped_section(section
) ||
1469 !container
->dirty_pages_supported
) {
1473 if (vfio_devices_all_dirty_tracking(container
)) {
1474 vfio_sync_dirty_bitmap(container
, section
);
1478 static const MemoryListener vfio_memory_listener
= {
1480 .region_add
= vfio_listener_region_add
,
1481 .region_del
= vfio_listener_region_del
,
1482 .log_global_start
= vfio_listener_log_global_start
,
1483 .log_global_stop
= vfio_listener_log_global_stop
,
1484 .log_sync
= vfio_listener_log_sync
,
1487 static void vfio_listener_release(VFIOContainer
*container
)
1489 memory_listener_unregister(&container
->listener
);
1490 if (container
->iommu_type
== VFIO_SPAPR_TCE_v2_IOMMU
) {
1491 memory_listener_unregister(&container
->prereg_listener
);
1495 static struct vfio_info_cap_header
*
1496 vfio_get_cap(void *ptr
, uint32_t cap_offset
, uint16_t id
)
1498 struct vfio_info_cap_header
*hdr
;
1500 for (hdr
= ptr
+ cap_offset
; hdr
!= ptr
; hdr
= ptr
+ hdr
->next
) {
1501 if (hdr
->id
== id
) {
1509 struct vfio_info_cap_header
*
1510 vfio_get_region_info_cap(struct vfio_region_info
*info
, uint16_t id
)
1512 if (!(info
->flags
& VFIO_REGION_INFO_FLAG_CAPS
)) {
1516 return vfio_get_cap((void *)info
, info
->cap_offset
, id
);
1519 static struct vfio_info_cap_header
*
1520 vfio_get_iommu_type1_info_cap(struct vfio_iommu_type1_info
*info
, uint16_t id
)
1522 if (!(info
->flags
& VFIO_IOMMU_INFO_CAPS
)) {
1526 return vfio_get_cap((void *)info
, info
->cap_offset
, id
);
1529 struct vfio_info_cap_header
*
1530 vfio_get_device_info_cap(struct vfio_device_info
*info
, uint16_t id
)
1532 if (!(info
->flags
& VFIO_DEVICE_FLAGS_CAPS
)) {
1536 return vfio_get_cap((void *)info
, info
->cap_offset
, id
);
1539 bool vfio_get_info_dma_avail(struct vfio_iommu_type1_info
*info
,
1540 unsigned int *avail
)
1542 struct vfio_info_cap_header
*hdr
;
1543 struct vfio_iommu_type1_info_dma_avail
*cap
;
1545 /* If the capability cannot be found, assume no DMA limiting */
1546 hdr
= vfio_get_iommu_type1_info_cap(info
,
1547 VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL
);
1552 if (avail
!= NULL
) {
1554 *avail
= cap
->avail
;
1560 static int vfio_setup_region_sparse_mmaps(VFIORegion
*region
,
1561 struct vfio_region_info
*info
)
1563 struct vfio_info_cap_header
*hdr
;
1564 struct vfio_region_info_cap_sparse_mmap
*sparse
;
1567 hdr
= vfio_get_region_info_cap(info
, VFIO_REGION_INFO_CAP_SPARSE_MMAP
);
1572 sparse
= container_of(hdr
, struct vfio_region_info_cap_sparse_mmap
, header
);
1574 trace_vfio_region_sparse_mmap_header(region
->vbasedev
->name
,
1575 region
->nr
, sparse
->nr_areas
);
1577 region
->mmaps
= g_new0(VFIOMmap
, sparse
->nr_areas
);
1579 for (i
= 0, j
= 0; i
< sparse
->nr_areas
; i
++) {
1580 if (sparse
->areas
[i
].size
) {
1581 trace_vfio_region_sparse_mmap_entry(i
, sparse
->areas
[i
].offset
,
1582 sparse
->areas
[i
].offset
+
1583 sparse
->areas
[i
].size
- 1);
1584 region
->mmaps
[j
].offset
= sparse
->areas
[i
].offset
;
1585 region
->mmaps
[j
].size
= sparse
->areas
[i
].size
;
1590 region
->nr_mmaps
= j
;
1591 region
->mmaps
= g_realloc(region
->mmaps
, j
* sizeof(VFIOMmap
));
1596 int vfio_region_setup(Object
*obj
, VFIODevice
*vbasedev
, VFIORegion
*region
,
1597 int index
, const char *name
)
1599 struct vfio_region_info
*info
;
1602 ret
= vfio_get_region_info(vbasedev
, index
, &info
);
1607 region
->vbasedev
= vbasedev
;
1608 region
->flags
= info
->flags
;
1609 region
->size
= info
->size
;
1610 region
->fd_offset
= info
->offset
;
1614 region
->mem
= g_new0(MemoryRegion
, 1);
1615 memory_region_init_io(region
->mem
, obj
, &vfio_region_ops
,
1616 region
, name
, region
->size
);
1618 if (!vbasedev
->no_mmap
&&
1619 region
->flags
& VFIO_REGION_INFO_FLAG_MMAP
) {
1621 ret
= vfio_setup_region_sparse_mmaps(region
, info
);
1624 region
->nr_mmaps
= 1;
1625 region
->mmaps
= g_new0(VFIOMmap
, region
->nr_mmaps
);
1626 region
->mmaps
[0].offset
= 0;
1627 region
->mmaps
[0].size
= region
->size
;
1634 trace_vfio_region_setup(vbasedev
->name
, index
, name
,
1635 region
->flags
, region
->fd_offset
, region
->size
);
1639 static void vfio_subregion_unmap(VFIORegion
*region
, int index
)
1641 trace_vfio_region_unmap(memory_region_name(®ion
->mmaps
[index
].mem
),
1642 region
->mmaps
[index
].offset
,
1643 region
->mmaps
[index
].offset
+
1644 region
->mmaps
[index
].size
- 1);
1645 memory_region_del_subregion(region
->mem
, ®ion
->mmaps
[index
].mem
);
1646 munmap(region
->mmaps
[index
].mmap
, region
->mmaps
[index
].size
);
1647 object_unparent(OBJECT(®ion
->mmaps
[index
].mem
));
1648 region
->mmaps
[index
].mmap
= NULL
;
1651 int vfio_region_mmap(VFIORegion
*region
)
1660 prot
|= region
->flags
& VFIO_REGION_INFO_FLAG_READ
? PROT_READ
: 0;
1661 prot
|= region
->flags
& VFIO_REGION_INFO_FLAG_WRITE
? PROT_WRITE
: 0;
1663 for (i
= 0; i
< region
->nr_mmaps
; i
++) {
1664 region
->mmaps
[i
].mmap
= mmap(NULL
, region
->mmaps
[i
].size
, prot
,
1665 MAP_SHARED
, region
->vbasedev
->fd
,
1667 region
->mmaps
[i
].offset
);
1668 if (region
->mmaps
[i
].mmap
== MAP_FAILED
) {
1671 trace_vfio_region_mmap_fault(memory_region_name(region
->mem
), i
,
1673 region
->mmaps
[i
].offset
,
1675 region
->mmaps
[i
].offset
+
1676 region
->mmaps
[i
].size
- 1, ret
);
1678 region
->mmaps
[i
].mmap
= NULL
;
1680 for (i
--; i
>= 0; i
--) {
1681 vfio_subregion_unmap(region
, i
);
1687 name
= g_strdup_printf("%s mmaps[%d]",
1688 memory_region_name(region
->mem
), i
);
1689 memory_region_init_ram_device_ptr(®ion
->mmaps
[i
].mem
,
1690 memory_region_owner(region
->mem
),
1691 name
, region
->mmaps
[i
].size
,
1692 region
->mmaps
[i
].mmap
);
1694 memory_region_add_subregion(region
->mem
, region
->mmaps
[i
].offset
,
1695 ®ion
->mmaps
[i
].mem
);
1697 trace_vfio_region_mmap(memory_region_name(®ion
->mmaps
[i
].mem
),
1698 region
->mmaps
[i
].offset
,
1699 region
->mmaps
[i
].offset
+
1700 region
->mmaps
[i
].size
- 1);
1706 void vfio_region_unmap(VFIORegion
*region
)
1714 for (i
= 0; i
< region
->nr_mmaps
; i
++) {
1715 if (region
->mmaps
[i
].mmap
) {
1716 vfio_subregion_unmap(region
, i
);
1721 void vfio_region_exit(VFIORegion
*region
)
1729 for (i
= 0; i
< region
->nr_mmaps
; i
++) {
1730 if (region
->mmaps
[i
].mmap
) {
1731 memory_region_del_subregion(region
->mem
, ®ion
->mmaps
[i
].mem
);
1735 trace_vfio_region_exit(region
->vbasedev
->name
, region
->nr
);
1738 void vfio_region_finalize(VFIORegion
*region
)
1746 for (i
= 0; i
< region
->nr_mmaps
; i
++) {
1747 if (region
->mmaps
[i
].mmap
) {
1748 munmap(region
->mmaps
[i
].mmap
, region
->mmaps
[i
].size
);
1749 object_unparent(OBJECT(®ion
->mmaps
[i
].mem
));
1753 object_unparent(OBJECT(region
->mem
));
1755 g_free(region
->mem
);
1756 g_free(region
->mmaps
);
1758 trace_vfio_region_finalize(region
->vbasedev
->name
, region
->nr
);
1761 region
->mmaps
= NULL
;
1762 region
->nr_mmaps
= 0;
1768 void vfio_region_mmaps_set_enabled(VFIORegion
*region
, bool enabled
)
1776 for (i
= 0; i
< region
->nr_mmaps
; i
++) {
1777 if (region
->mmaps
[i
].mmap
) {
1778 memory_region_set_enabled(®ion
->mmaps
[i
].mem
, enabled
);
1782 trace_vfio_region_mmaps_set_enabled(memory_region_name(region
->mem
),
1786 void vfio_reset_handler(void *opaque
)
1789 VFIODevice
*vbasedev
;
1791 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
1792 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
1793 if (vbasedev
->dev
->realized
) {
1794 vbasedev
->ops
->vfio_compute_needs_reset(vbasedev
);
1799 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
1800 QLIST_FOREACH(vbasedev
, &group
->device_list
, next
) {
1801 if (vbasedev
->dev
->realized
&& vbasedev
->needs_reset
) {
1802 vbasedev
->ops
->vfio_hot_reset_multi(vbasedev
);
1808 static void vfio_kvm_device_add_group(VFIOGroup
*group
)
1811 struct kvm_device_attr attr
= {
1812 .group
= KVM_DEV_VFIO_GROUP
,
1813 .attr
= KVM_DEV_VFIO_GROUP_ADD
,
1814 .addr
= (uint64_t)(unsigned long)&group
->fd
,
1817 if (!kvm_enabled()) {
1821 if (vfio_kvm_device_fd
< 0) {
1822 struct kvm_create_device cd
= {
1823 .type
= KVM_DEV_TYPE_VFIO
,
1826 if (kvm_vm_ioctl(kvm_state
, KVM_CREATE_DEVICE
, &cd
)) {
1827 error_report("Failed to create KVM VFIO device: %m");
1831 vfio_kvm_device_fd
= cd
.fd
;
1834 if (ioctl(vfio_kvm_device_fd
, KVM_SET_DEVICE_ATTR
, &attr
)) {
1835 error_report("Failed to add group %d to KVM VFIO device: %m",
1841 static void vfio_kvm_device_del_group(VFIOGroup
*group
)
1844 struct kvm_device_attr attr
= {
1845 .group
= KVM_DEV_VFIO_GROUP
,
1846 .attr
= KVM_DEV_VFIO_GROUP_DEL
,
1847 .addr
= (uint64_t)(unsigned long)&group
->fd
,
1850 if (vfio_kvm_device_fd
< 0) {
1854 if (ioctl(vfio_kvm_device_fd
, KVM_SET_DEVICE_ATTR
, &attr
)) {
1855 error_report("Failed to remove group %d from KVM VFIO device: %m",
1861 static VFIOAddressSpace
*vfio_get_address_space(AddressSpace
*as
)
1863 VFIOAddressSpace
*space
;
1865 QLIST_FOREACH(space
, &vfio_address_spaces
, list
) {
1866 if (space
->as
== as
) {
1871 /* No suitable VFIOAddressSpace, create a new one */
1872 space
= g_malloc0(sizeof(*space
));
1874 QLIST_INIT(&space
->containers
);
1876 QLIST_INSERT_HEAD(&vfio_address_spaces
, space
, list
);
1881 static void vfio_put_address_space(VFIOAddressSpace
*space
)
1883 if (QLIST_EMPTY(&space
->containers
)) {
1884 QLIST_REMOVE(space
, list
);
1890 * vfio_get_iommu_type - selects the richest iommu_type (v2 first)
1892 static int vfio_get_iommu_type(VFIOContainer
*container
,
1895 int iommu_types
[] = { VFIO_TYPE1v2_IOMMU
, VFIO_TYPE1_IOMMU
,
1896 VFIO_SPAPR_TCE_v2_IOMMU
, VFIO_SPAPR_TCE_IOMMU
};
1899 for (i
= 0; i
< ARRAY_SIZE(iommu_types
); i
++) {
1900 if (ioctl(container
->fd
, VFIO_CHECK_EXTENSION
, iommu_types
[i
])) {
1901 return iommu_types
[i
];
1904 error_setg(errp
, "No available IOMMU models");
1908 static int vfio_init_container(VFIOContainer
*container
, int group_fd
,
1911 int iommu_type
, ret
;
1913 iommu_type
= vfio_get_iommu_type(container
, errp
);
1914 if (iommu_type
< 0) {
1918 ret
= ioctl(group_fd
, VFIO_GROUP_SET_CONTAINER
, &container
->fd
);
1920 error_setg_errno(errp
, errno
, "Failed to set group container");
1924 while (ioctl(container
->fd
, VFIO_SET_IOMMU
, iommu_type
)) {
1925 if (iommu_type
== VFIO_SPAPR_TCE_v2_IOMMU
) {
1927 * On sPAPR, despite the IOMMU subdriver always advertises v1 and
1928 * v2, the running platform may not support v2 and there is no
1929 * way to guess it until an IOMMU group gets added to the container.
1930 * So in case it fails with v2, try v1 as a fallback.
1932 iommu_type
= VFIO_SPAPR_TCE_IOMMU
;
1935 error_setg_errno(errp
, errno
, "Failed to set iommu for container");
1939 container
->iommu_type
= iommu_type
;
1943 static int vfio_get_iommu_info(VFIOContainer
*container
,
1944 struct vfio_iommu_type1_info
**info
)
1947 size_t argsz
= sizeof(struct vfio_iommu_type1_info
);
1949 *info
= g_new0(struct vfio_iommu_type1_info
, 1);
1951 (*info
)->argsz
= argsz
;
1953 if (ioctl(container
->fd
, VFIO_IOMMU_GET_INFO
, *info
)) {
1959 if (((*info
)->argsz
> argsz
)) {
1960 argsz
= (*info
)->argsz
;
1961 *info
= g_realloc(*info
, argsz
);
1968 static struct vfio_info_cap_header
*
1969 vfio_get_iommu_info_cap(struct vfio_iommu_type1_info
*info
, uint16_t id
)
1971 struct vfio_info_cap_header
*hdr
;
1974 if (!(info
->flags
& VFIO_IOMMU_INFO_CAPS
)) {
1978 for (hdr
= ptr
+ info
->cap_offset
; hdr
!= ptr
; hdr
= ptr
+ hdr
->next
) {
1979 if (hdr
->id
== id
) {
1987 static void vfio_get_iommu_info_migration(VFIOContainer
*container
,
1988 struct vfio_iommu_type1_info
*info
)
1990 struct vfio_info_cap_header
*hdr
;
1991 struct vfio_iommu_type1_info_cap_migration
*cap_mig
;
1993 hdr
= vfio_get_iommu_info_cap(info
, VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION
);
1998 cap_mig
= container_of(hdr
, struct vfio_iommu_type1_info_cap_migration
,
2002 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
2003 * qemu_real_host_page_size to mark those dirty.
2005 if (cap_mig
->pgsize_bitmap
& qemu_real_host_page_size()) {
2006 container
->dirty_pages_supported
= true;
2007 container
->max_dirty_bitmap_size
= cap_mig
->max_dirty_bitmap_size
;
2008 container
->dirty_pgsizes
= cap_mig
->pgsize_bitmap
;
2012 static int vfio_connect_container(VFIOGroup
*group
, AddressSpace
*as
,
2015 VFIOContainer
*container
;
2017 VFIOAddressSpace
*space
;
2019 space
= vfio_get_address_space(as
);
2022 * VFIO is currently incompatible with discarding of RAM insofar as the
2023 * madvise to purge (zap) the page from QEMU's address space does not
2024 * interact with the memory API and therefore leaves stale virtual to
2025 * physical mappings in the IOMMU if the page was previously pinned. We
2026 * therefore set discarding broken for each group added to a container,
2027 * whether the container is used individually or shared. This provides
2028 * us with options to allow devices within a group to opt-in and allow
2029 * discarding, so long as it is done consistently for a group (for instance
2030 * if the device is an mdev device where it is known that the host vendor
2031 * driver will never pin pages outside of the working set of the guest
2032 * driver, which would thus not be discarding candidates).
2034 * The first opportunity to induce pinning occurs here where we attempt to
2035 * attach the group to existing containers within the AddressSpace. If any
2036 * pages are already zapped from the virtual address space, such as from
2037 * previous discards, new pinning will cause valid mappings to be
2038 * re-established. Likewise, when the overall MemoryListener for a new
2039 * container is registered, a replay of mappings within the AddressSpace
2040 * will occur, re-establishing any previously zapped pages as well.
2042 * Especially virtio-balloon is currently only prevented from discarding
2043 * new memory, it will not yet set ram_block_discard_set_required() and
2044 * therefore, neither stops us here or deals with the sudden memory
2045 * consumption of inflated memory.
2047 * We do support discarding of memory coordinated via the RamDiscardManager
2048 * with some IOMMU types. vfio_ram_block_discard_disable() handles the
2049 * details once we know which type of IOMMU we are using.
2052 QLIST_FOREACH(container
, &space
->containers
, next
) {
2053 if (!ioctl(group
->fd
, VFIO_GROUP_SET_CONTAINER
, &container
->fd
)) {
2054 ret
= vfio_ram_block_discard_disable(container
, true);
2056 error_setg_errno(errp
, -ret
,
2057 "Cannot set discarding of RAM broken");
2058 if (ioctl(group
->fd
, VFIO_GROUP_UNSET_CONTAINER
,
2060 error_report("vfio: error disconnecting group %d from"
2061 " container", group
->groupid
);
2065 group
->container
= container
;
2066 QLIST_INSERT_HEAD(&container
->group_list
, group
, container_next
);
2067 vfio_kvm_device_add_group(group
);
2072 fd
= qemu_open_old("/dev/vfio/vfio", O_RDWR
);
2074 error_setg_errno(errp
, errno
, "failed to open /dev/vfio/vfio");
2076 goto put_space_exit
;
2079 ret
= ioctl(fd
, VFIO_GET_API_VERSION
);
2080 if (ret
!= VFIO_API_VERSION
) {
2081 error_setg(errp
, "supported vfio version: %d, "
2082 "reported version: %d", VFIO_API_VERSION
, ret
);
2087 container
= g_malloc0(sizeof(*container
));
2088 container
->space
= space
;
2090 container
->error
= NULL
;
2091 container
->dirty_pages_supported
= false;
2092 container
->dma_max_mappings
= 0;
2093 QLIST_INIT(&container
->giommu_list
);
2094 QLIST_INIT(&container
->hostwin_list
);
2095 QLIST_INIT(&container
->vrdl_list
);
2097 ret
= vfio_init_container(container
, group
->fd
, errp
);
2099 goto free_container_exit
;
2102 ret
= vfio_ram_block_discard_disable(container
, true);
2104 error_setg_errno(errp
, -ret
, "Cannot set discarding of RAM broken");
2105 goto free_container_exit
;
2108 switch (container
->iommu_type
) {
2109 case VFIO_TYPE1v2_IOMMU
:
2110 case VFIO_TYPE1_IOMMU
:
2112 struct vfio_iommu_type1_info
*info
;
2114 ret
= vfio_get_iommu_info(container
, &info
);
2116 error_setg_errno(errp
, -ret
, "Failed to get VFIO IOMMU info");
2117 goto enable_discards_exit
;
2120 if (info
->flags
& VFIO_IOMMU_INFO_PGSIZES
) {
2121 container
->pgsizes
= info
->iova_pgsizes
;
2123 container
->pgsizes
= qemu_real_host_page_size();
2126 if (!vfio_get_info_dma_avail(info
, &container
->dma_max_mappings
)) {
2127 container
->dma_max_mappings
= 65535;
2129 vfio_get_iommu_info_migration(container
, info
);
2133 * FIXME: We should parse VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE
2134 * information to get the actual window extent rather than assume
2135 * a 64-bit IOVA address space.
2137 vfio_host_win_add(container
, 0, (hwaddr
)-1, container
->pgsizes
);
2141 case VFIO_SPAPR_TCE_v2_IOMMU
:
2142 case VFIO_SPAPR_TCE_IOMMU
:
2144 struct vfio_iommu_spapr_tce_info info
;
2145 bool v2
= container
->iommu_type
== VFIO_SPAPR_TCE_v2_IOMMU
;
2148 * The host kernel code implementing VFIO_IOMMU_DISABLE is called
2149 * when container fd is closed so we do not call it explicitly
2153 ret
= ioctl(fd
, VFIO_IOMMU_ENABLE
);
2155 error_setg_errno(errp
, errno
, "failed to enable container");
2157 goto enable_discards_exit
;
2160 container
->prereg_listener
= vfio_prereg_listener
;
2162 memory_listener_register(&container
->prereg_listener
,
2163 &address_space_memory
);
2164 if (container
->error
) {
2165 memory_listener_unregister(&container
->prereg_listener
);
2167 error_propagate_prepend(errp
, container
->error
,
2168 "RAM memory listener initialization failed: ");
2169 goto enable_discards_exit
;
2173 info
.argsz
= sizeof(info
);
2174 ret
= ioctl(fd
, VFIO_IOMMU_SPAPR_TCE_GET_INFO
, &info
);
2176 error_setg_errno(errp
, errno
,
2177 "VFIO_IOMMU_SPAPR_TCE_GET_INFO failed");
2180 memory_listener_unregister(&container
->prereg_listener
);
2182 goto enable_discards_exit
;
2186 container
->pgsizes
= info
.ddw
.pgsizes
;
2188 * There is a default window in just created container.
2189 * To make region_add/del simpler, we better remove this
2190 * window now and let those iommu_listener callbacks
2191 * create/remove them when needed.
2193 ret
= vfio_spapr_remove_window(container
, info
.dma32_window_start
);
2195 error_setg_errno(errp
, -ret
,
2196 "failed to remove existing window");
2197 goto enable_discards_exit
;
2200 /* The default table uses 4K pages */
2201 container
->pgsizes
= 0x1000;
2202 vfio_host_win_add(container
, info
.dma32_window_start
,
2203 info
.dma32_window_start
+
2204 info
.dma32_window_size
- 1,
2210 vfio_kvm_device_add_group(group
);
2212 QLIST_INIT(&container
->group_list
);
2213 QLIST_INSERT_HEAD(&space
->containers
, container
, next
);
2215 group
->container
= container
;
2216 QLIST_INSERT_HEAD(&container
->group_list
, group
, container_next
);
2218 container
->listener
= vfio_memory_listener
;
2220 memory_listener_register(&container
->listener
, container
->space
->as
);
2222 if (container
->error
) {
2224 error_propagate_prepend(errp
, container
->error
,
2225 "memory listener initialization failed: ");
2226 goto listener_release_exit
;
2229 container
->initialized
= true;
2232 listener_release_exit
:
2233 QLIST_REMOVE(group
, container_next
);
2234 QLIST_REMOVE(container
, next
);
2235 vfio_kvm_device_del_group(group
);
2236 vfio_listener_release(container
);
2238 enable_discards_exit
:
2239 vfio_ram_block_discard_disable(container
, false);
2241 free_container_exit
:
2248 vfio_put_address_space(space
);
2253 static void vfio_disconnect_container(VFIOGroup
*group
)
2255 VFIOContainer
*container
= group
->container
;
2257 QLIST_REMOVE(group
, container_next
);
2258 group
->container
= NULL
;
2261 * Explicitly release the listener first before unset container,
2262 * since unset may destroy the backend container if it's the last
2265 if (QLIST_EMPTY(&container
->group_list
)) {
2266 vfio_listener_release(container
);
2269 if (ioctl(group
->fd
, VFIO_GROUP_UNSET_CONTAINER
, &container
->fd
)) {
2270 error_report("vfio: error disconnecting group %d from container",
2274 if (QLIST_EMPTY(&container
->group_list
)) {
2275 VFIOAddressSpace
*space
= container
->space
;
2276 VFIOGuestIOMMU
*giommu
, *tmp
;
2277 VFIOHostDMAWindow
*hostwin
, *next
;
2279 QLIST_REMOVE(container
, next
);
2281 QLIST_FOREACH_SAFE(giommu
, &container
->giommu_list
, giommu_next
, tmp
) {
2282 memory_region_unregister_iommu_notifier(
2283 MEMORY_REGION(giommu
->iommu_mr
), &giommu
->n
);
2284 QLIST_REMOVE(giommu
, giommu_next
);
2288 QLIST_FOREACH_SAFE(hostwin
, &container
->hostwin_list
, hostwin_next
,
2290 QLIST_REMOVE(hostwin
, hostwin_next
);
2294 trace_vfio_disconnect_container(container
->fd
);
2295 close(container
->fd
);
2298 vfio_put_address_space(space
);
2302 VFIOGroup
*vfio_get_group(int groupid
, AddressSpace
*as
, Error
**errp
)
2306 struct vfio_group_status status
= { .argsz
= sizeof(status
) };
2308 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
2309 if (group
->groupid
== groupid
) {
2310 /* Found it. Now is it already in the right context? */
2311 if (group
->container
->space
->as
== as
) {
2314 error_setg(errp
, "group %d used in multiple address spaces",
2321 group
= g_malloc0(sizeof(*group
));
2323 snprintf(path
, sizeof(path
), "/dev/vfio/%d", groupid
);
2324 group
->fd
= qemu_open_old(path
, O_RDWR
);
2325 if (group
->fd
< 0) {
2326 error_setg_errno(errp
, errno
, "failed to open %s", path
);
2327 goto free_group_exit
;
2330 if (ioctl(group
->fd
, VFIO_GROUP_GET_STATUS
, &status
)) {
2331 error_setg_errno(errp
, errno
, "failed to get group %d status", groupid
);
2335 if (!(status
.flags
& VFIO_GROUP_FLAGS_VIABLE
)) {
2336 error_setg(errp
, "group %d is not viable", groupid
);
2337 error_append_hint(errp
,
2338 "Please ensure all devices within the iommu_group "
2339 "are bound to their vfio bus driver.\n");
2343 group
->groupid
= groupid
;
2344 QLIST_INIT(&group
->device_list
);
2346 if (vfio_connect_container(group
, as
, errp
)) {
2347 error_prepend(errp
, "failed to setup container for group %d: ",
2352 if (QLIST_EMPTY(&vfio_group_list
)) {
2353 qemu_register_reset(vfio_reset_handler
, NULL
);
2356 QLIST_INSERT_HEAD(&vfio_group_list
, group
, next
);
2369 void vfio_put_group(VFIOGroup
*group
)
2371 if (!group
|| !QLIST_EMPTY(&group
->device_list
)) {
2375 if (!group
->ram_block_discard_allowed
) {
2376 vfio_ram_block_discard_disable(group
->container
, false);
2378 vfio_kvm_device_del_group(group
);
2379 vfio_disconnect_container(group
);
2380 QLIST_REMOVE(group
, next
);
2381 trace_vfio_put_group(group
->fd
);
2385 if (QLIST_EMPTY(&vfio_group_list
)) {
2386 qemu_unregister_reset(vfio_reset_handler
, NULL
);
2390 int vfio_get_device(VFIOGroup
*group
, const char *name
,
2391 VFIODevice
*vbasedev
, Error
**errp
)
2393 struct vfio_device_info dev_info
= { .argsz
= sizeof(dev_info
) };
2396 fd
= ioctl(group
->fd
, VFIO_GROUP_GET_DEVICE_FD
, name
);
2398 error_setg_errno(errp
, errno
, "error getting device from group %d",
2400 error_append_hint(errp
,
2401 "Verify all devices in group %d are bound to vfio-<bus> "
2402 "or pci-stub and not already in use\n", group
->groupid
);
2406 ret
= ioctl(fd
, VFIO_DEVICE_GET_INFO
, &dev_info
);
2408 error_setg_errno(errp
, errno
, "error getting device info");
2414 * Set discarding of RAM as not broken for this group if the driver knows
2415 * the device operates compatibly with discarding. Setting must be
2416 * consistent per group, but since compatibility is really only possible
2417 * with mdev currently, we expect singleton groups.
2419 if (vbasedev
->ram_block_discard_allowed
!=
2420 group
->ram_block_discard_allowed
) {
2421 if (!QLIST_EMPTY(&group
->device_list
)) {
2422 error_setg(errp
, "Inconsistent setting of support for discarding "
2423 "RAM (e.g., balloon) within group");
2428 if (!group
->ram_block_discard_allowed
) {
2429 group
->ram_block_discard_allowed
= true;
2430 vfio_ram_block_discard_disable(group
->container
, false);
2435 vbasedev
->group
= group
;
2436 QLIST_INSERT_HEAD(&group
->device_list
, vbasedev
, next
);
2438 vbasedev
->num_irqs
= dev_info
.num_irqs
;
2439 vbasedev
->num_regions
= dev_info
.num_regions
;
2440 vbasedev
->flags
= dev_info
.flags
;
2442 trace_vfio_get_device(name
, dev_info
.flags
, dev_info
.num_regions
,
2445 vbasedev
->reset_works
= !!(dev_info
.flags
& VFIO_DEVICE_FLAGS_RESET
);
2449 void vfio_put_base_device(VFIODevice
*vbasedev
)
2451 if (!vbasedev
->group
) {
2454 QLIST_REMOVE(vbasedev
, next
);
2455 vbasedev
->group
= NULL
;
2456 trace_vfio_put_base_device(vbasedev
->fd
);
2457 close(vbasedev
->fd
);
2460 int vfio_get_region_info(VFIODevice
*vbasedev
, int index
,
2461 struct vfio_region_info
**info
)
2463 size_t argsz
= sizeof(struct vfio_region_info
);
2465 *info
= g_malloc0(argsz
);
2467 (*info
)->index
= index
;
2469 (*info
)->argsz
= argsz
;
2471 if (ioctl(vbasedev
->fd
, VFIO_DEVICE_GET_REGION_INFO
, *info
)) {
2477 if ((*info
)->argsz
> argsz
) {
2478 argsz
= (*info
)->argsz
;
2479 *info
= g_realloc(*info
, argsz
);
2487 int vfio_get_dev_region_info(VFIODevice
*vbasedev
, uint32_t type
,
2488 uint32_t subtype
, struct vfio_region_info
**info
)
2492 for (i
= 0; i
< vbasedev
->num_regions
; i
++) {
2493 struct vfio_info_cap_header
*hdr
;
2494 struct vfio_region_info_cap_type
*cap_type
;
2496 if (vfio_get_region_info(vbasedev
, i
, info
)) {
2500 hdr
= vfio_get_region_info_cap(*info
, VFIO_REGION_INFO_CAP_TYPE
);
2506 cap_type
= container_of(hdr
, struct vfio_region_info_cap_type
, header
);
2508 trace_vfio_get_dev_region(vbasedev
->name
, i
,
2509 cap_type
->type
, cap_type
->subtype
);
2511 if (cap_type
->type
== type
&& cap_type
->subtype
== subtype
) {
2522 bool vfio_has_region_cap(VFIODevice
*vbasedev
, int region
, uint16_t cap_type
)
2524 struct vfio_region_info
*info
= NULL
;
2527 if (!vfio_get_region_info(vbasedev
, region
, &info
)) {
2528 if (vfio_get_region_info_cap(info
, cap_type
)) {
2538 * Interfaces for IBM EEH (Enhanced Error Handling)
2540 static bool vfio_eeh_container_ok(VFIOContainer
*container
)
2543 * As of 2016-03-04 (linux-4.5) the host kernel EEH/VFIO
2544 * implementation is broken if there are multiple groups in a
2545 * container. The hardware works in units of Partitionable
2546 * Endpoints (== IOMMU groups) and the EEH operations naively
2547 * iterate across all groups in the container, without any logic
2548 * to make sure the groups have their state synchronized. For
2549 * certain operations (ENABLE) that might be ok, until an error
2550 * occurs, but for others (GET_STATE) it's clearly broken.
2554 * XXX Once fixed kernels exist, test for them here
2557 if (QLIST_EMPTY(&container
->group_list
)) {
2561 if (QLIST_NEXT(QLIST_FIRST(&container
->group_list
), container_next
)) {
2568 static int vfio_eeh_container_op(VFIOContainer
*container
, uint32_t op
)
2570 struct vfio_eeh_pe_op pe_op
= {
2571 .argsz
= sizeof(pe_op
),
2576 if (!vfio_eeh_container_ok(container
)) {
2577 error_report("vfio/eeh: EEH_PE_OP 0x%x: "
2578 "kernel requires a container with exactly one group", op
);
2582 ret
= ioctl(container
->fd
, VFIO_EEH_PE_OP
, &pe_op
);
2584 error_report("vfio/eeh: EEH_PE_OP 0x%x failed: %m", op
);
2591 static VFIOContainer
*vfio_eeh_as_container(AddressSpace
*as
)
2593 VFIOAddressSpace
*space
= vfio_get_address_space(as
);
2594 VFIOContainer
*container
= NULL
;
2596 if (QLIST_EMPTY(&space
->containers
)) {
2597 /* No containers to act on */
2601 container
= QLIST_FIRST(&space
->containers
);
2603 if (QLIST_NEXT(container
, next
)) {
2604 /* We don't yet have logic to synchronize EEH state across
2605 * multiple containers */
2611 vfio_put_address_space(space
);
2615 bool vfio_eeh_as_ok(AddressSpace
*as
)
2617 VFIOContainer
*container
= vfio_eeh_as_container(as
);
2619 return (container
!= NULL
) && vfio_eeh_container_ok(container
);
2622 int vfio_eeh_as_op(AddressSpace
*as
, uint32_t op
)
2624 VFIOContainer
*container
= vfio_eeh_as_container(as
);
2629 return vfio_eeh_container_op(container
, op
);