vfio: Query and store the maximum number of possible DMA mappings
[qemu/kevin.git] / hw / vfio / common.c
blob79628d60aede0d5a3a9dca425a2d50938f08d857
1 /*
2 * generic functions used by VFIO devices
4 * Copyright Red Hat, Inc. 2012
6 * Authors:
7 * Alex Williamson <alex.williamson@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
12 * Based on qemu-kvm device-assignment:
13 * Adapted for KVM by Qumranet.
14 * Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
15 * Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
16 * Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
17 * Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
18 * Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
21 #include "qemu/osdep.h"
22 #include <sys/ioctl.h>
23 #ifdef CONFIG_KVM
24 #include <linux/kvm.h>
25 #endif
26 #include <linux/vfio.h>
28 #include "hw/vfio/vfio-common.h"
29 #include "hw/vfio/vfio.h"
30 #include "exec/address-spaces.h"
31 #include "exec/memory.h"
32 #include "exec/ram_addr.h"
33 #include "hw/hw.h"
34 #include "qemu/error-report.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/range.h"
37 #include "sysemu/kvm.h"
38 #include "sysemu/reset.h"
39 #include "trace.h"
40 #include "qapi/error.h"
41 #include "migration/migration.h"
43 VFIOGroupList vfio_group_list =
44 QLIST_HEAD_INITIALIZER(vfio_group_list);
45 static QLIST_HEAD(, VFIOAddressSpace) vfio_address_spaces =
46 QLIST_HEAD_INITIALIZER(vfio_address_spaces);
48 #ifdef CONFIG_KVM
50 * We have a single VFIO pseudo device per KVM VM. Once created it lives
51 * for the life of the VM. Closing the file descriptor only drops our
52 * reference to it and the device's reference to kvm. Therefore once
53 * initialized, this file descriptor is only released on QEMU exit and
54 * we'll re-use it should another vfio device be attached before then.
56 static int vfio_kvm_device_fd = -1;
57 #endif
60 * Common VFIO interrupt disable
62 void vfio_disable_irqindex(VFIODevice *vbasedev, int index)
64 struct vfio_irq_set irq_set = {
65 .argsz = sizeof(irq_set),
66 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
67 .index = index,
68 .start = 0,
69 .count = 0,
72 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
75 void vfio_unmask_single_irqindex(VFIODevice *vbasedev, int index)
77 struct vfio_irq_set irq_set = {
78 .argsz = sizeof(irq_set),
79 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
80 .index = index,
81 .start = 0,
82 .count = 1,
85 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
88 void vfio_mask_single_irqindex(VFIODevice *vbasedev, int index)
90 struct vfio_irq_set irq_set = {
91 .argsz = sizeof(irq_set),
92 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK,
93 .index = index,
94 .start = 0,
95 .count = 1,
98 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
101 static inline const char *action_to_str(int action)
103 switch (action) {
104 case VFIO_IRQ_SET_ACTION_MASK:
105 return "MASK";
106 case VFIO_IRQ_SET_ACTION_UNMASK:
107 return "UNMASK";
108 case VFIO_IRQ_SET_ACTION_TRIGGER:
109 return "TRIGGER";
110 default:
111 return "UNKNOWN ACTION";
115 static const char *index_to_str(VFIODevice *vbasedev, int index)
117 if (vbasedev->type != VFIO_DEVICE_TYPE_PCI) {
118 return NULL;
121 switch (index) {
122 case VFIO_PCI_INTX_IRQ_INDEX:
123 return "INTX";
124 case VFIO_PCI_MSI_IRQ_INDEX:
125 return "MSI";
126 case VFIO_PCI_MSIX_IRQ_INDEX:
127 return "MSIX";
128 case VFIO_PCI_ERR_IRQ_INDEX:
129 return "ERR";
130 case VFIO_PCI_REQ_IRQ_INDEX:
131 return "REQ";
132 default:
133 return NULL;
137 int vfio_set_irq_signaling(VFIODevice *vbasedev, int index, int subindex,
138 int action, int fd, Error **errp)
140 struct vfio_irq_set *irq_set;
141 int argsz, ret = 0;
142 const char *name;
143 int32_t *pfd;
145 argsz = sizeof(*irq_set) + sizeof(*pfd);
147 irq_set = g_malloc0(argsz);
148 irq_set->argsz = argsz;
149 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | action;
150 irq_set->index = index;
151 irq_set->start = subindex;
152 irq_set->count = 1;
153 pfd = (int32_t *)&irq_set->data;
154 *pfd = fd;
156 if (ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, irq_set)) {
157 ret = -errno;
159 g_free(irq_set);
161 if (!ret) {
162 return 0;
165 error_setg_errno(errp, -ret, "VFIO_DEVICE_SET_IRQS failure");
167 name = index_to_str(vbasedev, index);
168 if (name) {
169 error_prepend(errp, "%s-%d: ", name, subindex);
170 } else {
171 error_prepend(errp, "index %d-%d: ", index, subindex);
173 error_prepend(errp,
174 "Failed to %s %s eventfd signaling for interrupt ",
175 fd < 0 ? "tear down" : "set up", action_to_str(action));
176 return ret;
180 * IO Port/MMIO - Beware of the endians, VFIO is always little endian
182 void vfio_region_write(void *opaque, hwaddr addr,
183 uint64_t data, unsigned size)
185 VFIORegion *region = opaque;
186 VFIODevice *vbasedev = region->vbasedev;
187 union {
188 uint8_t byte;
189 uint16_t word;
190 uint32_t dword;
191 uint64_t qword;
192 } buf;
194 switch (size) {
195 case 1:
196 buf.byte = data;
197 break;
198 case 2:
199 buf.word = cpu_to_le16(data);
200 break;
201 case 4:
202 buf.dword = cpu_to_le32(data);
203 break;
204 case 8:
205 buf.qword = cpu_to_le64(data);
206 break;
207 default:
208 hw_error("vfio: unsupported write size, %u bytes", size);
209 break;
212 if (pwrite(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
213 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", 0x%"PRIx64
214 ",%d) failed: %m",
215 __func__, vbasedev->name, region->nr,
216 addr, data, size);
219 trace_vfio_region_write(vbasedev->name, region->nr, addr, data, size);
222 * A read or write to a BAR always signals an INTx EOI. This will
223 * do nothing if not pending (including not in INTx mode). We assume
224 * that a BAR access is in response to an interrupt and that BAR
225 * accesses will service the interrupt. Unfortunately, we don't know
226 * which access will service the interrupt, so we're potentially
227 * getting quite a few host interrupts per guest interrupt.
229 vbasedev->ops->vfio_eoi(vbasedev);
232 uint64_t vfio_region_read(void *opaque,
233 hwaddr addr, unsigned size)
235 VFIORegion *region = opaque;
236 VFIODevice *vbasedev = region->vbasedev;
237 union {
238 uint8_t byte;
239 uint16_t word;
240 uint32_t dword;
241 uint64_t qword;
242 } buf;
243 uint64_t data = 0;
245 if (pread(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
246 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", %d) failed: %m",
247 __func__, vbasedev->name, region->nr,
248 addr, size);
249 return (uint64_t)-1;
251 switch (size) {
252 case 1:
253 data = buf.byte;
254 break;
255 case 2:
256 data = le16_to_cpu(buf.word);
257 break;
258 case 4:
259 data = le32_to_cpu(buf.dword);
260 break;
261 case 8:
262 data = le64_to_cpu(buf.qword);
263 break;
264 default:
265 hw_error("vfio: unsupported read size, %u bytes", size);
266 break;
269 trace_vfio_region_read(vbasedev->name, region->nr, addr, size, data);
271 /* Same as write above */
272 vbasedev->ops->vfio_eoi(vbasedev);
274 return data;
277 const MemoryRegionOps vfio_region_ops = {
278 .read = vfio_region_read,
279 .write = vfio_region_write,
280 .endianness = DEVICE_LITTLE_ENDIAN,
281 .valid = {
282 .min_access_size = 1,
283 .max_access_size = 8,
285 .impl = {
286 .min_access_size = 1,
287 .max_access_size = 8,
292 * Device state interfaces
295 bool vfio_mig_active(void)
297 VFIOGroup *group;
298 VFIODevice *vbasedev;
300 if (QLIST_EMPTY(&vfio_group_list)) {
301 return false;
304 QLIST_FOREACH(group, &vfio_group_list, next) {
305 QLIST_FOREACH(vbasedev, &group->device_list, next) {
306 if (vbasedev->migration_blocker) {
307 return false;
311 return true;
314 static bool vfio_devices_all_dirty_tracking(VFIOContainer *container)
316 VFIOGroup *group;
317 VFIODevice *vbasedev;
318 MigrationState *ms = migrate_get_current();
320 if (!migration_is_setup_or_active(ms->state)) {
321 return false;
324 QLIST_FOREACH(group, &container->group_list, container_next) {
325 QLIST_FOREACH(vbasedev, &group->device_list, next) {
326 VFIOMigration *migration = vbasedev->migration;
328 if (!migration) {
329 return false;
332 if ((vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF)
333 && (migration->device_state & VFIO_DEVICE_STATE_RUNNING)) {
334 return false;
338 return true;
341 static bool vfio_devices_all_running_and_saving(VFIOContainer *container)
343 VFIOGroup *group;
344 VFIODevice *vbasedev;
345 MigrationState *ms = migrate_get_current();
347 if (!migration_is_setup_or_active(ms->state)) {
348 return false;
351 QLIST_FOREACH(group, &container->group_list, container_next) {
352 QLIST_FOREACH(vbasedev, &group->device_list, next) {
353 VFIOMigration *migration = vbasedev->migration;
355 if (!migration) {
356 return false;
359 if ((migration->device_state & VFIO_DEVICE_STATE_SAVING) &&
360 (migration->device_state & VFIO_DEVICE_STATE_RUNNING)) {
361 continue;
362 } else {
363 return false;
367 return true;
370 static int vfio_dma_unmap_bitmap(VFIOContainer *container,
371 hwaddr iova, ram_addr_t size,
372 IOMMUTLBEntry *iotlb)
374 struct vfio_iommu_type1_dma_unmap *unmap;
375 struct vfio_bitmap *bitmap;
376 uint64_t pages = REAL_HOST_PAGE_ALIGN(size) / qemu_real_host_page_size;
377 int ret;
379 unmap = g_malloc0(sizeof(*unmap) + sizeof(*bitmap));
381 unmap->argsz = sizeof(*unmap) + sizeof(*bitmap);
382 unmap->iova = iova;
383 unmap->size = size;
384 unmap->flags |= VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP;
385 bitmap = (struct vfio_bitmap *)&unmap->data;
388 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
389 * qemu_real_host_page_size to mark those dirty. Hence set bitmap_pgsize
390 * to qemu_real_host_page_size.
393 bitmap->pgsize = qemu_real_host_page_size;
394 bitmap->size = ROUND_UP(pages, sizeof(__u64) * BITS_PER_BYTE) /
395 BITS_PER_BYTE;
397 if (bitmap->size > container->max_dirty_bitmap_size) {
398 error_report("UNMAP: Size of bitmap too big 0x%"PRIx64,
399 (uint64_t)bitmap->size);
400 ret = -E2BIG;
401 goto unmap_exit;
404 bitmap->data = g_try_malloc0(bitmap->size);
405 if (!bitmap->data) {
406 ret = -ENOMEM;
407 goto unmap_exit;
410 ret = ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, unmap);
411 if (!ret) {
412 cpu_physical_memory_set_dirty_lebitmap((unsigned long *)bitmap->data,
413 iotlb->translated_addr, pages);
414 } else {
415 error_report("VFIO_UNMAP_DMA with DIRTY_BITMAP : %m");
418 g_free(bitmap->data);
419 unmap_exit:
420 g_free(unmap);
421 return ret;
425 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
427 static int vfio_dma_unmap(VFIOContainer *container,
428 hwaddr iova, ram_addr_t size,
429 IOMMUTLBEntry *iotlb)
431 struct vfio_iommu_type1_dma_unmap unmap = {
432 .argsz = sizeof(unmap),
433 .flags = 0,
434 .iova = iova,
435 .size = size,
438 if (iotlb && container->dirty_pages_supported &&
439 vfio_devices_all_running_and_saving(container)) {
440 return vfio_dma_unmap_bitmap(container, iova, size, iotlb);
443 while (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
445 * The type1 backend has an off-by-one bug in the kernel (71a7d3d78e3c
446 * v4.15) where an overflow in its wrap-around check prevents us from
447 * unmapping the last page of the address space. Test for the error
448 * condition and re-try the unmap excluding the last page. The
449 * expectation is that we've never mapped the last page anyway and this
450 * unmap request comes via vIOMMU support which also makes it unlikely
451 * that this page is used. This bug was introduced well after type1 v2
452 * support was introduced, so we shouldn't need to test for v1. A fix
453 * is queued for kernel v5.0 so this workaround can be removed once
454 * affected kernels are sufficiently deprecated.
456 if (errno == EINVAL && unmap.size && !(unmap.iova + unmap.size) &&
457 container->iommu_type == VFIO_TYPE1v2_IOMMU) {
458 trace_vfio_dma_unmap_overflow_workaround();
459 unmap.size -= 1ULL << ctz64(container->pgsizes);
460 continue;
462 error_report("VFIO_UNMAP_DMA failed: %s", strerror(errno));
463 return -errno;
466 return 0;
469 static int vfio_dma_map(VFIOContainer *container, hwaddr iova,
470 ram_addr_t size, void *vaddr, bool readonly)
472 struct vfio_iommu_type1_dma_map map = {
473 .argsz = sizeof(map),
474 .flags = VFIO_DMA_MAP_FLAG_READ,
475 .vaddr = (__u64)(uintptr_t)vaddr,
476 .iova = iova,
477 .size = size,
480 if (!readonly) {
481 map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
485 * Try the mapping, if it fails with EBUSY, unmap the region and try
486 * again. This shouldn't be necessary, but we sometimes see it in
487 * the VGA ROM space.
489 if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
490 (errno == EBUSY && vfio_dma_unmap(container, iova, size, NULL) == 0 &&
491 ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
492 return 0;
495 error_report("VFIO_MAP_DMA failed: %s", strerror(errno));
496 return -errno;
499 static void vfio_host_win_add(VFIOContainer *container,
500 hwaddr min_iova, hwaddr max_iova,
501 uint64_t iova_pgsizes)
503 VFIOHostDMAWindow *hostwin;
505 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
506 if (ranges_overlap(hostwin->min_iova,
507 hostwin->max_iova - hostwin->min_iova + 1,
508 min_iova,
509 max_iova - min_iova + 1)) {
510 hw_error("%s: Overlapped IOMMU are not enabled", __func__);
514 hostwin = g_malloc0(sizeof(*hostwin));
516 hostwin->min_iova = min_iova;
517 hostwin->max_iova = max_iova;
518 hostwin->iova_pgsizes = iova_pgsizes;
519 QLIST_INSERT_HEAD(&container->hostwin_list, hostwin, hostwin_next);
522 static int vfio_host_win_del(VFIOContainer *container, hwaddr min_iova,
523 hwaddr max_iova)
525 VFIOHostDMAWindow *hostwin;
527 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
528 if (hostwin->min_iova == min_iova && hostwin->max_iova == max_iova) {
529 QLIST_REMOVE(hostwin, hostwin_next);
530 return 0;
534 return -1;
537 static bool vfio_listener_skipped_section(MemoryRegionSection *section)
539 return (!memory_region_is_ram(section->mr) &&
540 !memory_region_is_iommu(section->mr)) ||
542 * Sizing an enabled 64-bit BAR can cause spurious mappings to
543 * addresses in the upper part of the 64-bit address space. These
544 * are never accessed by the CPU and beyond the address width of
545 * some IOMMU hardware. TODO: VFIO should tell us the IOMMU width.
547 section->offset_within_address_space & (1ULL << 63);
550 /* Called with rcu_read_lock held. */
551 static bool vfio_get_xlat_addr(IOMMUTLBEntry *iotlb, void **vaddr,
552 ram_addr_t *ram_addr, bool *read_only)
554 MemoryRegion *mr;
555 hwaddr xlat;
556 hwaddr len = iotlb->addr_mask + 1;
557 bool writable = iotlb->perm & IOMMU_WO;
560 * The IOMMU TLB entry we have just covers translation through
561 * this IOMMU to its immediate target. We need to translate
562 * it the rest of the way through to memory.
564 mr = address_space_translate(&address_space_memory,
565 iotlb->translated_addr,
566 &xlat, &len, writable,
567 MEMTXATTRS_UNSPECIFIED);
568 if (!memory_region_is_ram(mr)) {
569 error_report("iommu map to non memory area %"HWADDR_PRIx"",
570 xlat);
571 return false;
575 * Translation truncates length to the IOMMU page size,
576 * check that it did not truncate too much.
578 if (len & iotlb->addr_mask) {
579 error_report("iommu has granularity incompatible with target AS");
580 return false;
583 if (vaddr) {
584 *vaddr = memory_region_get_ram_ptr(mr) + xlat;
587 if (ram_addr) {
588 *ram_addr = memory_region_get_ram_addr(mr) + xlat;
591 if (read_only) {
592 *read_only = !writable || mr->readonly;
595 return true;
598 static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
600 VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
601 VFIOContainer *container = giommu->container;
602 hwaddr iova = iotlb->iova + giommu->iommu_offset;
603 void *vaddr;
604 int ret;
606 trace_vfio_iommu_map_notify(iotlb->perm == IOMMU_NONE ? "UNMAP" : "MAP",
607 iova, iova + iotlb->addr_mask);
609 if (iotlb->target_as != &address_space_memory) {
610 error_report("Wrong target AS \"%s\", only system memory is allowed",
611 iotlb->target_as->name ? iotlb->target_as->name : "none");
612 return;
615 rcu_read_lock();
617 if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {
618 bool read_only;
620 if (!vfio_get_xlat_addr(iotlb, &vaddr, NULL, &read_only)) {
621 goto out;
624 * vaddr is only valid until rcu_read_unlock(). But after
625 * vfio_dma_map has set up the mapping the pages will be
626 * pinned by the kernel. This makes sure that the RAM backend
627 * of vaddr will always be there, even if the memory object is
628 * destroyed and its backing memory munmap-ed.
630 ret = vfio_dma_map(container, iova,
631 iotlb->addr_mask + 1, vaddr,
632 read_only);
633 if (ret) {
634 error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
635 "0x%"HWADDR_PRIx", %p) = %d (%m)",
636 container, iova,
637 iotlb->addr_mask + 1, vaddr, ret);
639 } else {
640 ret = vfio_dma_unmap(container, iova, iotlb->addr_mask + 1, iotlb);
641 if (ret) {
642 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
643 "0x%"HWADDR_PRIx") = %d (%m)",
644 container, iova,
645 iotlb->addr_mask + 1, ret);
648 out:
649 rcu_read_unlock();
652 static void vfio_ram_discard_notify_discard(RamDiscardListener *rdl,
653 MemoryRegionSection *section)
655 VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
656 listener);
657 const hwaddr size = int128_get64(section->size);
658 const hwaddr iova = section->offset_within_address_space;
659 int ret;
661 /* Unmap with a single call. */
662 ret = vfio_dma_unmap(vrdl->container, iova, size , NULL);
663 if (ret) {
664 error_report("%s: vfio_dma_unmap() failed: %s", __func__,
665 strerror(-ret));
669 static int vfio_ram_discard_notify_populate(RamDiscardListener *rdl,
670 MemoryRegionSection *section)
672 VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
673 listener);
674 const hwaddr end = section->offset_within_region +
675 int128_get64(section->size);
676 hwaddr start, next, iova;
677 void *vaddr;
678 int ret;
681 * Map in (aligned within memory region) minimum granularity, so we can
682 * unmap in minimum granularity later.
684 for (start = section->offset_within_region; start < end; start = next) {
685 next = ROUND_UP(start + 1, vrdl->granularity);
686 next = MIN(next, end);
688 iova = start - section->offset_within_region +
689 section->offset_within_address_space;
690 vaddr = memory_region_get_ram_ptr(section->mr) + start;
692 ret = vfio_dma_map(vrdl->container, iova, next - start,
693 vaddr, section->readonly);
694 if (ret) {
695 /* Rollback */
696 vfio_ram_discard_notify_discard(rdl, section);
697 return ret;
700 return 0;
703 static void vfio_register_ram_discard_listener(VFIOContainer *container,
704 MemoryRegionSection *section)
706 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
707 VFIORamDiscardListener *vrdl;
709 /* Ignore some corner cases not relevant in practice. */
710 g_assert(QEMU_IS_ALIGNED(section->offset_within_region, TARGET_PAGE_SIZE));
711 g_assert(QEMU_IS_ALIGNED(section->offset_within_address_space,
712 TARGET_PAGE_SIZE));
713 g_assert(QEMU_IS_ALIGNED(int128_get64(section->size), TARGET_PAGE_SIZE));
715 vrdl = g_new0(VFIORamDiscardListener, 1);
716 vrdl->container = container;
717 vrdl->mr = section->mr;
718 vrdl->offset_within_address_space = section->offset_within_address_space;
719 vrdl->size = int128_get64(section->size);
720 vrdl->granularity = ram_discard_manager_get_min_granularity(rdm,
721 section->mr);
723 g_assert(vrdl->granularity && is_power_of_2(vrdl->granularity));
724 g_assert(vrdl->granularity >= 1 << ctz64(container->pgsizes));
726 ram_discard_listener_init(&vrdl->listener,
727 vfio_ram_discard_notify_populate,
728 vfio_ram_discard_notify_discard, true);
729 ram_discard_manager_register_listener(rdm, &vrdl->listener, section);
730 QLIST_INSERT_HEAD(&container->vrdl_list, vrdl, next);
733 static void vfio_unregister_ram_discard_listener(VFIOContainer *container,
734 MemoryRegionSection *section)
736 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
737 VFIORamDiscardListener *vrdl = NULL;
739 QLIST_FOREACH(vrdl, &container->vrdl_list, next) {
740 if (vrdl->mr == section->mr &&
741 vrdl->offset_within_address_space ==
742 section->offset_within_address_space) {
743 break;
747 if (!vrdl) {
748 hw_error("vfio: Trying to unregister missing RAM discard listener");
751 ram_discard_manager_unregister_listener(rdm, &vrdl->listener);
752 QLIST_REMOVE(vrdl, next);
753 g_free(vrdl);
756 static void vfio_listener_region_add(MemoryListener *listener,
757 MemoryRegionSection *section)
759 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
760 hwaddr iova, end;
761 Int128 llend, llsize;
762 void *vaddr;
763 int ret;
764 VFIOHostDMAWindow *hostwin;
765 bool hostwin_found;
766 Error *err = NULL;
768 if (vfio_listener_skipped_section(section)) {
769 trace_vfio_listener_region_add_skip(
770 section->offset_within_address_space,
771 section->offset_within_address_space +
772 int128_get64(int128_sub(section->size, int128_one())));
773 return;
776 if (unlikely((section->offset_within_address_space &
777 ~qemu_real_host_page_mask) !=
778 (section->offset_within_region & ~qemu_real_host_page_mask))) {
779 error_report("%s received unaligned region", __func__);
780 return;
783 iova = REAL_HOST_PAGE_ALIGN(section->offset_within_address_space);
784 llend = int128_make64(section->offset_within_address_space);
785 llend = int128_add(llend, section->size);
786 llend = int128_and(llend, int128_exts64(qemu_real_host_page_mask));
788 if (int128_ge(int128_make64(iova), llend)) {
789 return;
791 end = int128_get64(int128_sub(llend, int128_one()));
793 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
794 hwaddr pgsize = 0;
796 /* For now intersections are not allowed, we may relax this later */
797 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
798 if (ranges_overlap(hostwin->min_iova,
799 hostwin->max_iova - hostwin->min_iova + 1,
800 section->offset_within_address_space,
801 int128_get64(section->size))) {
802 error_setg(&err,
803 "region [0x%"PRIx64",0x%"PRIx64"] overlaps with existing"
804 "host DMA window [0x%"PRIx64",0x%"PRIx64"]",
805 section->offset_within_address_space,
806 section->offset_within_address_space +
807 int128_get64(section->size) - 1,
808 hostwin->min_iova, hostwin->max_iova);
809 goto fail;
813 ret = vfio_spapr_create_window(container, section, &pgsize);
814 if (ret) {
815 error_setg_errno(&err, -ret, "Failed to create SPAPR window");
816 goto fail;
819 vfio_host_win_add(container, section->offset_within_address_space,
820 section->offset_within_address_space +
821 int128_get64(section->size) - 1, pgsize);
822 #ifdef CONFIG_KVM
823 if (kvm_enabled()) {
824 VFIOGroup *group;
825 IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
826 struct kvm_vfio_spapr_tce param;
827 struct kvm_device_attr attr = {
828 .group = KVM_DEV_VFIO_GROUP,
829 .attr = KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE,
830 .addr = (uint64_t)(unsigned long)&param,
833 if (!memory_region_iommu_get_attr(iommu_mr, IOMMU_ATTR_SPAPR_TCE_FD,
834 &param.tablefd)) {
835 QLIST_FOREACH(group, &container->group_list, container_next) {
836 param.groupfd = group->fd;
837 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
838 error_report("vfio: failed to setup fd %d "
839 "for a group with fd %d: %s",
840 param.tablefd, param.groupfd,
841 strerror(errno));
842 return;
844 trace_vfio_spapr_group_attach(param.groupfd, param.tablefd);
848 #endif
851 hostwin_found = false;
852 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
853 if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
854 hostwin_found = true;
855 break;
859 if (!hostwin_found) {
860 error_setg(&err, "Container %p can't map guest IOVA region"
861 " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx, container, iova, end);
862 goto fail;
865 memory_region_ref(section->mr);
867 if (memory_region_is_iommu(section->mr)) {
868 VFIOGuestIOMMU *giommu;
869 IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
870 int iommu_idx;
872 trace_vfio_listener_region_add_iommu(iova, end);
874 * FIXME: For VFIO iommu types which have KVM acceleration to
875 * avoid bouncing all map/unmaps through qemu this way, this
876 * would be the right place to wire that up (tell the KVM
877 * device emulation the VFIO iommu handles to use).
879 giommu = g_malloc0(sizeof(*giommu));
880 giommu->iommu = iommu_mr;
881 giommu->iommu_offset = section->offset_within_address_space -
882 section->offset_within_region;
883 giommu->container = container;
884 llend = int128_add(int128_make64(section->offset_within_region),
885 section->size);
886 llend = int128_sub(llend, int128_one());
887 iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
888 MEMTXATTRS_UNSPECIFIED);
889 iommu_notifier_init(&giommu->n, vfio_iommu_map_notify,
890 IOMMU_NOTIFIER_IOTLB_EVENTS,
891 section->offset_within_region,
892 int128_get64(llend),
893 iommu_idx);
895 ret = memory_region_iommu_set_page_size_mask(giommu->iommu,
896 container->pgsizes,
897 &err);
898 if (ret) {
899 g_free(giommu);
900 goto fail;
903 ret = memory_region_register_iommu_notifier(section->mr, &giommu->n,
904 &err);
905 if (ret) {
906 g_free(giommu);
907 goto fail;
909 QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
910 memory_region_iommu_replay(giommu->iommu, &giommu->n);
912 return;
915 /* Here we assume that memory_region_is_ram(section->mr)==true */
918 * For RAM memory regions with a RamDiscardManager, we only want to map the
919 * actually populated parts - and update the mapping whenever we're notified
920 * about changes.
922 if (memory_region_has_ram_discard_manager(section->mr)) {
923 vfio_register_ram_discard_listener(container, section);
924 return;
927 vaddr = memory_region_get_ram_ptr(section->mr) +
928 section->offset_within_region +
929 (iova - section->offset_within_address_space);
931 trace_vfio_listener_region_add_ram(iova, end, vaddr);
933 llsize = int128_sub(llend, int128_make64(iova));
935 if (memory_region_is_ram_device(section->mr)) {
936 hwaddr pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
938 if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) {
939 trace_vfio_listener_region_add_no_dma_map(
940 memory_region_name(section->mr),
941 section->offset_within_address_space,
942 int128_getlo(section->size),
943 pgmask + 1);
944 return;
948 ret = vfio_dma_map(container, iova, int128_get64(llsize),
949 vaddr, section->readonly);
950 if (ret) {
951 error_setg(&err, "vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
952 "0x%"HWADDR_PRIx", %p) = %d (%m)",
953 container, iova, int128_get64(llsize), vaddr, ret);
954 if (memory_region_is_ram_device(section->mr)) {
955 /* Allow unexpected mappings not to be fatal for RAM devices */
956 error_report_err(err);
957 return;
959 goto fail;
962 return;
964 fail:
965 if (memory_region_is_ram_device(section->mr)) {
966 error_report("failed to vfio_dma_map. pci p2p may not work");
967 return;
970 * On the initfn path, store the first error in the container so we
971 * can gracefully fail. Runtime, there's not much we can do other
972 * than throw a hardware error.
974 if (!container->initialized) {
975 if (!container->error) {
976 error_propagate_prepend(&container->error, err,
977 "Region %s: ",
978 memory_region_name(section->mr));
979 } else {
980 error_free(err);
982 } else {
983 error_report_err(err);
984 hw_error("vfio: DMA mapping failed, unable to continue");
988 static void vfio_listener_region_del(MemoryListener *listener,
989 MemoryRegionSection *section)
991 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
992 hwaddr iova, end;
993 Int128 llend, llsize;
994 int ret;
995 bool try_unmap = true;
997 if (vfio_listener_skipped_section(section)) {
998 trace_vfio_listener_region_del_skip(
999 section->offset_within_address_space,
1000 section->offset_within_address_space +
1001 int128_get64(int128_sub(section->size, int128_one())));
1002 return;
1005 if (unlikely((section->offset_within_address_space &
1006 ~qemu_real_host_page_mask) !=
1007 (section->offset_within_region & ~qemu_real_host_page_mask))) {
1008 error_report("%s received unaligned region", __func__);
1009 return;
1012 if (memory_region_is_iommu(section->mr)) {
1013 VFIOGuestIOMMU *giommu;
1015 QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
1016 if (MEMORY_REGION(giommu->iommu) == section->mr &&
1017 giommu->n.start == section->offset_within_region) {
1018 memory_region_unregister_iommu_notifier(section->mr,
1019 &giommu->n);
1020 QLIST_REMOVE(giommu, giommu_next);
1021 g_free(giommu);
1022 break;
1027 * FIXME: We assume the one big unmap below is adequate to
1028 * remove any individual page mappings in the IOMMU which
1029 * might have been copied into VFIO. This works for a page table
1030 * based IOMMU where a big unmap flattens a large range of IO-PTEs.
1031 * That may not be true for all IOMMU types.
1035 iova = REAL_HOST_PAGE_ALIGN(section->offset_within_address_space);
1036 llend = int128_make64(section->offset_within_address_space);
1037 llend = int128_add(llend, section->size);
1038 llend = int128_and(llend, int128_exts64(qemu_real_host_page_mask));
1040 if (int128_ge(int128_make64(iova), llend)) {
1041 return;
1043 end = int128_get64(int128_sub(llend, int128_one()));
1045 llsize = int128_sub(llend, int128_make64(iova));
1047 trace_vfio_listener_region_del(iova, end);
1049 if (memory_region_is_ram_device(section->mr)) {
1050 hwaddr pgmask;
1051 VFIOHostDMAWindow *hostwin;
1052 bool hostwin_found = false;
1054 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
1055 if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
1056 hostwin_found = true;
1057 break;
1060 assert(hostwin_found); /* or region_add() would have failed */
1062 pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
1063 try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask));
1064 } else if (memory_region_has_ram_discard_manager(section->mr)) {
1065 vfio_unregister_ram_discard_listener(container, section);
1066 /* Unregistering will trigger an unmap. */
1067 try_unmap = false;
1070 if (try_unmap) {
1071 if (int128_eq(llsize, int128_2_64())) {
1072 /* The unmap ioctl doesn't accept a full 64-bit span. */
1073 llsize = int128_rshift(llsize, 1);
1074 ret = vfio_dma_unmap(container, iova, int128_get64(llsize), NULL);
1075 if (ret) {
1076 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
1077 "0x%"HWADDR_PRIx") = %d (%m)",
1078 container, iova, int128_get64(llsize), ret);
1080 iova += int128_get64(llsize);
1082 ret = vfio_dma_unmap(container, iova, int128_get64(llsize), NULL);
1083 if (ret) {
1084 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
1085 "0x%"HWADDR_PRIx") = %d (%m)",
1086 container, iova, int128_get64(llsize), ret);
1090 memory_region_unref(section->mr);
1092 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
1093 vfio_spapr_remove_window(container,
1094 section->offset_within_address_space);
1095 if (vfio_host_win_del(container,
1096 section->offset_within_address_space,
1097 section->offset_within_address_space +
1098 int128_get64(section->size) - 1) < 0) {
1099 hw_error("%s: Cannot delete missing window at %"HWADDR_PRIx,
1100 __func__, section->offset_within_address_space);
1105 static void vfio_set_dirty_page_tracking(VFIOContainer *container, bool start)
1107 int ret;
1108 struct vfio_iommu_type1_dirty_bitmap dirty = {
1109 .argsz = sizeof(dirty),
1112 if (start) {
1113 dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_START;
1114 } else {
1115 dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP;
1118 ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, &dirty);
1119 if (ret) {
1120 error_report("Failed to set dirty tracking flag 0x%x errno: %d",
1121 dirty.flags, errno);
1125 static void vfio_listener_log_global_start(MemoryListener *listener)
1127 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1129 vfio_set_dirty_page_tracking(container, true);
1132 static void vfio_listener_log_global_stop(MemoryListener *listener)
1134 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1136 vfio_set_dirty_page_tracking(container, false);
1139 static int vfio_get_dirty_bitmap(VFIOContainer *container, uint64_t iova,
1140 uint64_t size, ram_addr_t ram_addr)
1142 struct vfio_iommu_type1_dirty_bitmap *dbitmap;
1143 struct vfio_iommu_type1_dirty_bitmap_get *range;
1144 uint64_t pages;
1145 int ret;
1147 dbitmap = g_malloc0(sizeof(*dbitmap) + sizeof(*range));
1149 dbitmap->argsz = sizeof(*dbitmap) + sizeof(*range);
1150 dbitmap->flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
1151 range = (struct vfio_iommu_type1_dirty_bitmap_get *)&dbitmap->data;
1152 range->iova = iova;
1153 range->size = size;
1156 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
1157 * qemu_real_host_page_size to mark those dirty. Hence set bitmap's pgsize
1158 * to qemu_real_host_page_size.
1160 range->bitmap.pgsize = qemu_real_host_page_size;
1162 pages = REAL_HOST_PAGE_ALIGN(range->size) / qemu_real_host_page_size;
1163 range->bitmap.size = ROUND_UP(pages, sizeof(__u64) * BITS_PER_BYTE) /
1164 BITS_PER_BYTE;
1165 range->bitmap.data = g_try_malloc0(range->bitmap.size);
1166 if (!range->bitmap.data) {
1167 ret = -ENOMEM;
1168 goto err_out;
1171 ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, dbitmap);
1172 if (ret) {
1173 error_report("Failed to get dirty bitmap for iova: 0x%"PRIx64
1174 " size: 0x%"PRIx64" err: %d", (uint64_t)range->iova,
1175 (uint64_t)range->size, errno);
1176 goto err_out;
1179 cpu_physical_memory_set_dirty_lebitmap((unsigned long *)range->bitmap.data,
1180 ram_addr, pages);
1182 trace_vfio_get_dirty_bitmap(container->fd, range->iova, range->size,
1183 range->bitmap.size, ram_addr);
1184 err_out:
1185 g_free(range->bitmap.data);
1186 g_free(dbitmap);
1188 return ret;
1191 typedef struct {
1192 IOMMUNotifier n;
1193 VFIOGuestIOMMU *giommu;
1194 } vfio_giommu_dirty_notifier;
1196 static void vfio_iommu_map_dirty_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
1198 vfio_giommu_dirty_notifier *gdn = container_of(n,
1199 vfio_giommu_dirty_notifier, n);
1200 VFIOGuestIOMMU *giommu = gdn->giommu;
1201 VFIOContainer *container = giommu->container;
1202 hwaddr iova = iotlb->iova + giommu->iommu_offset;
1203 ram_addr_t translated_addr;
1205 trace_vfio_iommu_map_dirty_notify(iova, iova + iotlb->addr_mask);
1207 if (iotlb->target_as != &address_space_memory) {
1208 error_report("Wrong target AS \"%s\", only system memory is allowed",
1209 iotlb->target_as->name ? iotlb->target_as->name : "none");
1210 return;
1213 rcu_read_lock();
1214 if (vfio_get_xlat_addr(iotlb, NULL, &translated_addr, NULL)) {
1215 int ret;
1217 ret = vfio_get_dirty_bitmap(container, iova, iotlb->addr_mask + 1,
1218 translated_addr);
1219 if (ret) {
1220 error_report("vfio_iommu_map_dirty_notify(%p, 0x%"HWADDR_PRIx", "
1221 "0x%"HWADDR_PRIx") = %d (%m)",
1222 container, iova,
1223 iotlb->addr_mask + 1, ret);
1226 rcu_read_unlock();
1229 static int vfio_ram_discard_get_dirty_bitmap(MemoryRegionSection *section,
1230 void *opaque)
1232 const hwaddr size = int128_get64(section->size);
1233 const hwaddr iova = section->offset_within_address_space;
1234 const ram_addr_t ram_addr = memory_region_get_ram_addr(section->mr) +
1235 section->offset_within_region;
1236 VFIORamDiscardListener *vrdl = opaque;
1239 * Sync the whole mapped region (spanning multiple individual mappings)
1240 * in one go.
1242 return vfio_get_dirty_bitmap(vrdl->container, iova, size, ram_addr);
1245 static int vfio_sync_ram_discard_listener_dirty_bitmap(VFIOContainer *container,
1246 MemoryRegionSection *section)
1248 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
1249 VFIORamDiscardListener *vrdl = NULL;
1251 QLIST_FOREACH(vrdl, &container->vrdl_list, next) {
1252 if (vrdl->mr == section->mr &&
1253 vrdl->offset_within_address_space ==
1254 section->offset_within_address_space) {
1255 break;
1259 if (!vrdl) {
1260 hw_error("vfio: Trying to sync missing RAM discard listener");
1264 * We only want/can synchronize the bitmap for actually mapped parts -
1265 * which correspond to populated parts. Replay all populated parts.
1267 return ram_discard_manager_replay_populated(rdm, section,
1268 vfio_ram_discard_get_dirty_bitmap,
1269 &vrdl);
1272 static int vfio_sync_dirty_bitmap(VFIOContainer *container,
1273 MemoryRegionSection *section)
1275 ram_addr_t ram_addr;
1277 if (memory_region_is_iommu(section->mr)) {
1278 VFIOGuestIOMMU *giommu;
1280 QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
1281 if (MEMORY_REGION(giommu->iommu) == section->mr &&
1282 giommu->n.start == section->offset_within_region) {
1283 Int128 llend;
1284 vfio_giommu_dirty_notifier gdn = { .giommu = giommu };
1285 int idx = memory_region_iommu_attrs_to_index(giommu->iommu,
1286 MEMTXATTRS_UNSPECIFIED);
1288 llend = int128_add(int128_make64(section->offset_within_region),
1289 section->size);
1290 llend = int128_sub(llend, int128_one());
1292 iommu_notifier_init(&gdn.n,
1293 vfio_iommu_map_dirty_notify,
1294 IOMMU_NOTIFIER_MAP,
1295 section->offset_within_region,
1296 int128_get64(llend),
1297 idx);
1298 memory_region_iommu_replay(giommu->iommu, &gdn.n);
1299 break;
1302 return 0;
1303 } else if (memory_region_has_ram_discard_manager(section->mr)) {
1304 return vfio_sync_ram_discard_listener_dirty_bitmap(container, section);
1307 ram_addr = memory_region_get_ram_addr(section->mr) +
1308 section->offset_within_region;
1310 return vfio_get_dirty_bitmap(container,
1311 REAL_HOST_PAGE_ALIGN(section->offset_within_address_space),
1312 int128_get64(section->size), ram_addr);
1315 static void vfio_listener_log_sync(MemoryListener *listener,
1316 MemoryRegionSection *section)
1318 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1320 if (vfio_listener_skipped_section(section) ||
1321 !container->dirty_pages_supported) {
1322 return;
1325 if (vfio_devices_all_dirty_tracking(container)) {
1326 vfio_sync_dirty_bitmap(container, section);
1330 static const MemoryListener vfio_memory_listener = {
1331 .region_add = vfio_listener_region_add,
1332 .region_del = vfio_listener_region_del,
1333 .log_global_start = vfio_listener_log_global_start,
1334 .log_global_stop = vfio_listener_log_global_stop,
1335 .log_sync = vfio_listener_log_sync,
1338 static void vfio_listener_release(VFIOContainer *container)
1340 memory_listener_unregister(&container->listener);
1341 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
1342 memory_listener_unregister(&container->prereg_listener);
1346 static struct vfio_info_cap_header *
1347 vfio_get_cap(void *ptr, uint32_t cap_offset, uint16_t id)
1349 struct vfio_info_cap_header *hdr;
1351 for (hdr = ptr + cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
1352 if (hdr->id == id) {
1353 return hdr;
1357 return NULL;
1360 struct vfio_info_cap_header *
1361 vfio_get_region_info_cap(struct vfio_region_info *info, uint16_t id)
1363 if (!(info->flags & VFIO_REGION_INFO_FLAG_CAPS)) {
1364 return NULL;
1367 return vfio_get_cap((void *)info, info->cap_offset, id);
1370 static struct vfio_info_cap_header *
1371 vfio_get_iommu_type1_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
1373 if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
1374 return NULL;
1377 return vfio_get_cap((void *)info, info->cap_offset, id);
1380 struct vfio_info_cap_header *
1381 vfio_get_device_info_cap(struct vfio_device_info *info, uint16_t id)
1383 if (!(info->flags & VFIO_DEVICE_FLAGS_CAPS)) {
1384 return NULL;
1387 return vfio_get_cap((void *)info, info->cap_offset, id);
1390 bool vfio_get_info_dma_avail(struct vfio_iommu_type1_info *info,
1391 unsigned int *avail)
1393 struct vfio_info_cap_header *hdr;
1394 struct vfio_iommu_type1_info_dma_avail *cap;
1396 /* If the capability cannot be found, assume no DMA limiting */
1397 hdr = vfio_get_iommu_type1_info_cap(info,
1398 VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL);
1399 if (hdr == NULL) {
1400 return false;
1403 if (avail != NULL) {
1404 cap = (void *) hdr;
1405 *avail = cap->avail;
1408 return true;
1411 static int vfio_setup_region_sparse_mmaps(VFIORegion *region,
1412 struct vfio_region_info *info)
1414 struct vfio_info_cap_header *hdr;
1415 struct vfio_region_info_cap_sparse_mmap *sparse;
1416 int i, j;
1418 hdr = vfio_get_region_info_cap(info, VFIO_REGION_INFO_CAP_SPARSE_MMAP);
1419 if (!hdr) {
1420 return -ENODEV;
1423 sparse = container_of(hdr, struct vfio_region_info_cap_sparse_mmap, header);
1425 trace_vfio_region_sparse_mmap_header(region->vbasedev->name,
1426 region->nr, sparse->nr_areas);
1428 region->mmaps = g_new0(VFIOMmap, sparse->nr_areas);
1430 for (i = 0, j = 0; i < sparse->nr_areas; i++) {
1431 trace_vfio_region_sparse_mmap_entry(i, sparse->areas[i].offset,
1432 sparse->areas[i].offset +
1433 sparse->areas[i].size);
1435 if (sparse->areas[i].size) {
1436 region->mmaps[j].offset = sparse->areas[i].offset;
1437 region->mmaps[j].size = sparse->areas[i].size;
1438 j++;
1442 region->nr_mmaps = j;
1443 region->mmaps = g_realloc(region->mmaps, j * sizeof(VFIOMmap));
1445 return 0;
1448 int vfio_region_setup(Object *obj, VFIODevice *vbasedev, VFIORegion *region,
1449 int index, const char *name)
1451 struct vfio_region_info *info;
1452 int ret;
1454 ret = vfio_get_region_info(vbasedev, index, &info);
1455 if (ret) {
1456 return ret;
1459 region->vbasedev = vbasedev;
1460 region->flags = info->flags;
1461 region->size = info->size;
1462 region->fd_offset = info->offset;
1463 region->nr = index;
1465 if (region->size) {
1466 region->mem = g_new0(MemoryRegion, 1);
1467 memory_region_init_io(region->mem, obj, &vfio_region_ops,
1468 region, name, region->size);
1470 if (!vbasedev->no_mmap &&
1471 region->flags & VFIO_REGION_INFO_FLAG_MMAP) {
1473 ret = vfio_setup_region_sparse_mmaps(region, info);
1475 if (ret) {
1476 region->nr_mmaps = 1;
1477 region->mmaps = g_new0(VFIOMmap, region->nr_mmaps);
1478 region->mmaps[0].offset = 0;
1479 region->mmaps[0].size = region->size;
1484 g_free(info);
1486 trace_vfio_region_setup(vbasedev->name, index, name,
1487 region->flags, region->fd_offset, region->size);
1488 return 0;
1491 static void vfio_subregion_unmap(VFIORegion *region, int index)
1493 trace_vfio_region_unmap(memory_region_name(&region->mmaps[index].mem),
1494 region->mmaps[index].offset,
1495 region->mmaps[index].offset +
1496 region->mmaps[index].size - 1);
1497 memory_region_del_subregion(region->mem, &region->mmaps[index].mem);
1498 munmap(region->mmaps[index].mmap, region->mmaps[index].size);
1499 object_unparent(OBJECT(&region->mmaps[index].mem));
1500 region->mmaps[index].mmap = NULL;
1503 int vfio_region_mmap(VFIORegion *region)
1505 int i, prot = 0;
1506 char *name;
1508 if (!region->mem) {
1509 return 0;
1512 prot |= region->flags & VFIO_REGION_INFO_FLAG_READ ? PROT_READ : 0;
1513 prot |= region->flags & VFIO_REGION_INFO_FLAG_WRITE ? PROT_WRITE : 0;
1515 for (i = 0; i < region->nr_mmaps; i++) {
1516 region->mmaps[i].mmap = mmap(NULL, region->mmaps[i].size, prot,
1517 MAP_SHARED, region->vbasedev->fd,
1518 region->fd_offset +
1519 region->mmaps[i].offset);
1520 if (region->mmaps[i].mmap == MAP_FAILED) {
1521 int ret = -errno;
1523 trace_vfio_region_mmap_fault(memory_region_name(region->mem), i,
1524 region->fd_offset +
1525 region->mmaps[i].offset,
1526 region->fd_offset +
1527 region->mmaps[i].offset +
1528 region->mmaps[i].size - 1, ret);
1530 region->mmaps[i].mmap = NULL;
1532 for (i--; i >= 0; i--) {
1533 vfio_subregion_unmap(region, i);
1536 return ret;
1539 name = g_strdup_printf("%s mmaps[%d]",
1540 memory_region_name(region->mem), i);
1541 memory_region_init_ram_device_ptr(&region->mmaps[i].mem,
1542 memory_region_owner(region->mem),
1543 name, region->mmaps[i].size,
1544 region->mmaps[i].mmap);
1545 g_free(name);
1546 memory_region_add_subregion(region->mem, region->mmaps[i].offset,
1547 &region->mmaps[i].mem);
1549 trace_vfio_region_mmap(memory_region_name(&region->mmaps[i].mem),
1550 region->mmaps[i].offset,
1551 region->mmaps[i].offset +
1552 region->mmaps[i].size - 1);
1555 return 0;
1558 void vfio_region_unmap(VFIORegion *region)
1560 int i;
1562 if (!region->mem) {
1563 return;
1566 for (i = 0; i < region->nr_mmaps; i++) {
1567 if (region->mmaps[i].mmap) {
1568 vfio_subregion_unmap(region, i);
1573 void vfio_region_exit(VFIORegion *region)
1575 int i;
1577 if (!region->mem) {
1578 return;
1581 for (i = 0; i < region->nr_mmaps; i++) {
1582 if (region->mmaps[i].mmap) {
1583 memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
1587 trace_vfio_region_exit(region->vbasedev->name, region->nr);
1590 void vfio_region_finalize(VFIORegion *region)
1592 int i;
1594 if (!region->mem) {
1595 return;
1598 for (i = 0; i < region->nr_mmaps; i++) {
1599 if (region->mmaps[i].mmap) {
1600 munmap(region->mmaps[i].mmap, region->mmaps[i].size);
1601 object_unparent(OBJECT(&region->mmaps[i].mem));
1605 object_unparent(OBJECT(region->mem));
1607 g_free(region->mem);
1608 g_free(region->mmaps);
1610 trace_vfio_region_finalize(region->vbasedev->name, region->nr);
1612 region->mem = NULL;
1613 region->mmaps = NULL;
1614 region->nr_mmaps = 0;
1615 region->size = 0;
1616 region->flags = 0;
1617 region->nr = 0;
1620 void vfio_region_mmaps_set_enabled(VFIORegion *region, bool enabled)
1622 int i;
1624 if (!region->mem) {
1625 return;
1628 for (i = 0; i < region->nr_mmaps; i++) {
1629 if (region->mmaps[i].mmap) {
1630 memory_region_set_enabled(&region->mmaps[i].mem, enabled);
1634 trace_vfio_region_mmaps_set_enabled(memory_region_name(region->mem),
1635 enabled);
1638 void vfio_reset_handler(void *opaque)
1640 VFIOGroup *group;
1641 VFIODevice *vbasedev;
1643 QLIST_FOREACH(group, &vfio_group_list, next) {
1644 QLIST_FOREACH(vbasedev, &group->device_list, next) {
1645 if (vbasedev->dev->realized) {
1646 vbasedev->ops->vfio_compute_needs_reset(vbasedev);
1651 QLIST_FOREACH(group, &vfio_group_list, next) {
1652 QLIST_FOREACH(vbasedev, &group->device_list, next) {
1653 if (vbasedev->dev->realized && vbasedev->needs_reset) {
1654 vbasedev->ops->vfio_hot_reset_multi(vbasedev);
1660 static void vfio_kvm_device_add_group(VFIOGroup *group)
1662 #ifdef CONFIG_KVM
1663 struct kvm_device_attr attr = {
1664 .group = KVM_DEV_VFIO_GROUP,
1665 .attr = KVM_DEV_VFIO_GROUP_ADD,
1666 .addr = (uint64_t)(unsigned long)&group->fd,
1669 if (!kvm_enabled()) {
1670 return;
1673 if (vfio_kvm_device_fd < 0) {
1674 struct kvm_create_device cd = {
1675 .type = KVM_DEV_TYPE_VFIO,
1678 if (kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd)) {
1679 error_report("Failed to create KVM VFIO device: %m");
1680 return;
1683 vfio_kvm_device_fd = cd.fd;
1686 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1687 error_report("Failed to add group %d to KVM VFIO device: %m",
1688 group->groupid);
1690 #endif
1693 static void vfio_kvm_device_del_group(VFIOGroup *group)
1695 #ifdef CONFIG_KVM
1696 struct kvm_device_attr attr = {
1697 .group = KVM_DEV_VFIO_GROUP,
1698 .attr = KVM_DEV_VFIO_GROUP_DEL,
1699 .addr = (uint64_t)(unsigned long)&group->fd,
1702 if (vfio_kvm_device_fd < 0) {
1703 return;
1706 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1707 error_report("Failed to remove group %d from KVM VFIO device: %m",
1708 group->groupid);
1710 #endif
1713 static VFIOAddressSpace *vfio_get_address_space(AddressSpace *as)
1715 VFIOAddressSpace *space;
1717 QLIST_FOREACH(space, &vfio_address_spaces, list) {
1718 if (space->as == as) {
1719 return space;
1723 /* No suitable VFIOAddressSpace, create a new one */
1724 space = g_malloc0(sizeof(*space));
1725 space->as = as;
1726 QLIST_INIT(&space->containers);
1728 QLIST_INSERT_HEAD(&vfio_address_spaces, space, list);
1730 return space;
1733 static void vfio_put_address_space(VFIOAddressSpace *space)
1735 if (QLIST_EMPTY(&space->containers)) {
1736 QLIST_REMOVE(space, list);
1737 g_free(space);
1742 * vfio_get_iommu_type - selects the richest iommu_type (v2 first)
1744 static int vfio_get_iommu_type(VFIOContainer *container,
1745 Error **errp)
1747 int iommu_types[] = { VFIO_TYPE1v2_IOMMU, VFIO_TYPE1_IOMMU,
1748 VFIO_SPAPR_TCE_v2_IOMMU, VFIO_SPAPR_TCE_IOMMU };
1749 int i;
1751 for (i = 0; i < ARRAY_SIZE(iommu_types); i++) {
1752 if (ioctl(container->fd, VFIO_CHECK_EXTENSION, iommu_types[i])) {
1753 return iommu_types[i];
1756 error_setg(errp, "No available IOMMU models");
1757 return -EINVAL;
1760 static int vfio_init_container(VFIOContainer *container, int group_fd,
1761 Error **errp)
1763 int iommu_type, ret;
1765 iommu_type = vfio_get_iommu_type(container, errp);
1766 if (iommu_type < 0) {
1767 return iommu_type;
1770 ret = ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container->fd);
1771 if (ret) {
1772 error_setg_errno(errp, errno, "Failed to set group container");
1773 return -errno;
1776 while (ioctl(container->fd, VFIO_SET_IOMMU, iommu_type)) {
1777 if (iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
1779 * On sPAPR, despite the IOMMU subdriver always advertises v1 and
1780 * v2, the running platform may not support v2 and there is no
1781 * way to guess it until an IOMMU group gets added to the container.
1782 * So in case it fails with v2, try v1 as a fallback.
1784 iommu_type = VFIO_SPAPR_TCE_IOMMU;
1785 continue;
1787 error_setg_errno(errp, errno, "Failed to set iommu for container");
1788 return -errno;
1791 container->iommu_type = iommu_type;
1792 return 0;
1795 static int vfio_get_iommu_info(VFIOContainer *container,
1796 struct vfio_iommu_type1_info **info)
1799 size_t argsz = sizeof(struct vfio_iommu_type1_info);
1801 *info = g_new0(struct vfio_iommu_type1_info, 1);
1802 again:
1803 (*info)->argsz = argsz;
1805 if (ioctl(container->fd, VFIO_IOMMU_GET_INFO, *info)) {
1806 g_free(*info);
1807 *info = NULL;
1808 return -errno;
1811 if (((*info)->argsz > argsz)) {
1812 argsz = (*info)->argsz;
1813 *info = g_realloc(*info, argsz);
1814 goto again;
1817 return 0;
1820 static struct vfio_info_cap_header *
1821 vfio_get_iommu_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
1823 struct vfio_info_cap_header *hdr;
1824 void *ptr = info;
1826 if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
1827 return NULL;
1830 for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
1831 if (hdr->id == id) {
1832 return hdr;
1836 return NULL;
1839 static void vfio_get_iommu_info_migration(VFIOContainer *container,
1840 struct vfio_iommu_type1_info *info)
1842 struct vfio_info_cap_header *hdr;
1843 struct vfio_iommu_type1_info_cap_migration *cap_mig;
1845 hdr = vfio_get_iommu_info_cap(info, VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION);
1846 if (!hdr) {
1847 return;
1850 cap_mig = container_of(hdr, struct vfio_iommu_type1_info_cap_migration,
1851 header);
1854 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
1855 * qemu_real_host_page_size to mark those dirty.
1857 if (cap_mig->pgsize_bitmap & qemu_real_host_page_size) {
1858 container->dirty_pages_supported = true;
1859 container->max_dirty_bitmap_size = cap_mig->max_dirty_bitmap_size;
1860 container->dirty_pgsizes = cap_mig->pgsize_bitmap;
1864 static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
1865 Error **errp)
1867 VFIOContainer *container;
1868 int ret, fd;
1869 VFIOAddressSpace *space;
1871 space = vfio_get_address_space(as);
1874 * VFIO is currently incompatible with discarding of RAM insofar as the
1875 * madvise to purge (zap) the page from QEMU's address space does not
1876 * interact with the memory API and therefore leaves stale virtual to
1877 * physical mappings in the IOMMU if the page was previously pinned. We
1878 * therefore set discarding broken for each group added to a container,
1879 * whether the container is used individually or shared. This provides
1880 * us with options to allow devices within a group to opt-in and allow
1881 * discarding, so long as it is done consistently for a group (for instance
1882 * if the device is an mdev device where it is known that the host vendor
1883 * driver will never pin pages outside of the working set of the guest
1884 * driver, which would thus not be discarding candidates).
1886 * The first opportunity to induce pinning occurs here where we attempt to
1887 * attach the group to existing containers within the AddressSpace. If any
1888 * pages are already zapped from the virtual address space, such as from
1889 * previous discards, new pinning will cause valid mappings to be
1890 * re-established. Likewise, when the overall MemoryListener for a new
1891 * container is registered, a replay of mappings within the AddressSpace
1892 * will occur, re-establishing any previously zapped pages as well.
1894 * Especially virtio-balloon is currently only prevented from discarding
1895 * new memory, it will not yet set ram_block_discard_set_required() and
1896 * therefore, neither stops us here or deals with the sudden memory
1897 * consumption of inflated memory.
1899 ret = ram_block_discard_disable(true);
1900 if (ret) {
1901 error_setg_errno(errp, -ret, "Cannot set discarding of RAM broken");
1902 return ret;
1905 QLIST_FOREACH(container, &space->containers, next) {
1906 if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
1907 group->container = container;
1908 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
1909 vfio_kvm_device_add_group(group);
1910 return 0;
1914 fd = qemu_open_old("/dev/vfio/vfio", O_RDWR);
1915 if (fd < 0) {
1916 error_setg_errno(errp, errno, "failed to open /dev/vfio/vfio");
1917 ret = -errno;
1918 goto put_space_exit;
1921 ret = ioctl(fd, VFIO_GET_API_VERSION);
1922 if (ret != VFIO_API_VERSION) {
1923 error_setg(errp, "supported vfio version: %d, "
1924 "reported version: %d", VFIO_API_VERSION, ret);
1925 ret = -EINVAL;
1926 goto close_fd_exit;
1929 container = g_malloc0(sizeof(*container));
1930 container->space = space;
1931 container->fd = fd;
1932 container->error = NULL;
1933 container->dirty_pages_supported = false;
1934 container->dma_max_mappings = 0;
1935 QLIST_INIT(&container->giommu_list);
1936 QLIST_INIT(&container->hostwin_list);
1937 QLIST_INIT(&container->vrdl_list);
1939 ret = vfio_init_container(container, group->fd, errp);
1940 if (ret) {
1941 goto free_container_exit;
1944 switch (container->iommu_type) {
1945 case VFIO_TYPE1v2_IOMMU:
1946 case VFIO_TYPE1_IOMMU:
1948 struct vfio_iommu_type1_info *info;
1951 * FIXME: This assumes that a Type1 IOMMU can map any 64-bit
1952 * IOVA whatsoever. That's not actually true, but the current
1953 * kernel interface doesn't tell us what it can map, and the
1954 * existing Type1 IOMMUs generally support any IOVA we're
1955 * going to actually try in practice.
1957 ret = vfio_get_iommu_info(container, &info);
1959 if (ret || !(info->flags & VFIO_IOMMU_INFO_PGSIZES)) {
1960 /* Assume 4k IOVA page size */
1961 info->iova_pgsizes = 4096;
1963 vfio_host_win_add(container, 0, (hwaddr)-1, info->iova_pgsizes);
1964 container->pgsizes = info->iova_pgsizes;
1966 /* The default in the kernel ("dma_entry_limit") is 65535. */
1967 container->dma_max_mappings = 65535;
1968 if (!ret) {
1969 vfio_get_info_dma_avail(info, &container->dma_max_mappings);
1970 vfio_get_iommu_info_migration(container, info);
1972 g_free(info);
1973 break;
1975 case VFIO_SPAPR_TCE_v2_IOMMU:
1976 case VFIO_SPAPR_TCE_IOMMU:
1978 struct vfio_iommu_spapr_tce_info info;
1979 bool v2 = container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU;
1982 * The host kernel code implementing VFIO_IOMMU_DISABLE is called
1983 * when container fd is closed so we do not call it explicitly
1984 * in this file.
1986 if (!v2) {
1987 ret = ioctl(fd, VFIO_IOMMU_ENABLE);
1988 if (ret) {
1989 error_setg_errno(errp, errno, "failed to enable container");
1990 ret = -errno;
1991 goto free_container_exit;
1993 } else {
1994 container->prereg_listener = vfio_prereg_listener;
1996 memory_listener_register(&container->prereg_listener,
1997 &address_space_memory);
1998 if (container->error) {
1999 memory_listener_unregister(&container->prereg_listener);
2000 ret = -1;
2001 error_propagate_prepend(errp, container->error,
2002 "RAM memory listener initialization failed: ");
2003 goto free_container_exit;
2007 info.argsz = sizeof(info);
2008 ret = ioctl(fd, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info);
2009 if (ret) {
2010 error_setg_errno(errp, errno,
2011 "VFIO_IOMMU_SPAPR_TCE_GET_INFO failed");
2012 ret = -errno;
2013 if (v2) {
2014 memory_listener_unregister(&container->prereg_listener);
2016 goto free_container_exit;
2019 if (v2) {
2020 container->pgsizes = info.ddw.pgsizes;
2022 * There is a default window in just created container.
2023 * To make region_add/del simpler, we better remove this
2024 * window now and let those iommu_listener callbacks
2025 * create/remove them when needed.
2027 ret = vfio_spapr_remove_window(container, info.dma32_window_start);
2028 if (ret) {
2029 error_setg_errno(errp, -ret,
2030 "failed to remove existing window");
2031 goto free_container_exit;
2033 } else {
2034 /* The default table uses 4K pages */
2035 container->pgsizes = 0x1000;
2036 vfio_host_win_add(container, info.dma32_window_start,
2037 info.dma32_window_start +
2038 info.dma32_window_size - 1,
2039 0x1000);
2044 vfio_kvm_device_add_group(group);
2046 QLIST_INIT(&container->group_list);
2047 QLIST_INSERT_HEAD(&space->containers, container, next);
2049 group->container = container;
2050 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
2052 container->listener = vfio_memory_listener;
2054 memory_listener_register(&container->listener, container->space->as);
2056 if (container->error) {
2057 ret = -1;
2058 error_propagate_prepend(errp, container->error,
2059 "memory listener initialization failed: ");
2060 goto listener_release_exit;
2063 container->initialized = true;
2065 return 0;
2066 listener_release_exit:
2067 QLIST_REMOVE(group, container_next);
2068 QLIST_REMOVE(container, next);
2069 vfio_kvm_device_del_group(group);
2070 vfio_listener_release(container);
2072 free_container_exit:
2073 g_free(container);
2075 close_fd_exit:
2076 close(fd);
2078 put_space_exit:
2079 ram_block_discard_disable(false);
2080 vfio_put_address_space(space);
2082 return ret;
2085 static void vfio_disconnect_container(VFIOGroup *group)
2087 VFIOContainer *container = group->container;
2089 QLIST_REMOVE(group, container_next);
2090 group->container = NULL;
2093 * Explicitly release the listener first before unset container,
2094 * since unset may destroy the backend container if it's the last
2095 * group.
2097 if (QLIST_EMPTY(&container->group_list)) {
2098 vfio_listener_release(container);
2101 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
2102 error_report("vfio: error disconnecting group %d from container",
2103 group->groupid);
2106 if (QLIST_EMPTY(&container->group_list)) {
2107 VFIOAddressSpace *space = container->space;
2108 VFIOGuestIOMMU *giommu, *tmp;
2110 QLIST_REMOVE(container, next);
2112 QLIST_FOREACH_SAFE(giommu, &container->giommu_list, giommu_next, tmp) {
2113 memory_region_unregister_iommu_notifier(
2114 MEMORY_REGION(giommu->iommu), &giommu->n);
2115 QLIST_REMOVE(giommu, giommu_next);
2116 g_free(giommu);
2119 trace_vfio_disconnect_container(container->fd);
2120 close(container->fd);
2121 g_free(container);
2123 vfio_put_address_space(space);
2127 VFIOGroup *vfio_get_group(int groupid, AddressSpace *as, Error **errp)
2129 VFIOGroup *group;
2130 char path[32];
2131 struct vfio_group_status status = { .argsz = sizeof(status) };
2133 QLIST_FOREACH(group, &vfio_group_list, next) {
2134 if (group->groupid == groupid) {
2135 /* Found it. Now is it already in the right context? */
2136 if (group->container->space->as == as) {
2137 return group;
2138 } else {
2139 error_setg(errp, "group %d used in multiple address spaces",
2140 group->groupid);
2141 return NULL;
2146 group = g_malloc0(sizeof(*group));
2148 snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
2149 group->fd = qemu_open_old(path, O_RDWR);
2150 if (group->fd < 0) {
2151 error_setg_errno(errp, errno, "failed to open %s", path);
2152 goto free_group_exit;
2155 if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
2156 error_setg_errno(errp, errno, "failed to get group %d status", groupid);
2157 goto close_fd_exit;
2160 if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
2161 error_setg(errp, "group %d is not viable", groupid);
2162 error_append_hint(errp,
2163 "Please ensure all devices within the iommu_group "
2164 "are bound to their vfio bus driver.\n");
2165 goto close_fd_exit;
2168 group->groupid = groupid;
2169 QLIST_INIT(&group->device_list);
2171 if (vfio_connect_container(group, as, errp)) {
2172 error_prepend(errp, "failed to setup container for group %d: ",
2173 groupid);
2174 goto close_fd_exit;
2177 if (QLIST_EMPTY(&vfio_group_list)) {
2178 qemu_register_reset(vfio_reset_handler, NULL);
2181 QLIST_INSERT_HEAD(&vfio_group_list, group, next);
2183 return group;
2185 close_fd_exit:
2186 close(group->fd);
2188 free_group_exit:
2189 g_free(group);
2191 return NULL;
2194 void vfio_put_group(VFIOGroup *group)
2196 if (!group || !QLIST_EMPTY(&group->device_list)) {
2197 return;
2200 if (!group->ram_block_discard_allowed) {
2201 ram_block_discard_disable(false);
2203 vfio_kvm_device_del_group(group);
2204 vfio_disconnect_container(group);
2205 QLIST_REMOVE(group, next);
2206 trace_vfio_put_group(group->fd);
2207 close(group->fd);
2208 g_free(group);
2210 if (QLIST_EMPTY(&vfio_group_list)) {
2211 qemu_unregister_reset(vfio_reset_handler, NULL);
2215 int vfio_get_device(VFIOGroup *group, const char *name,
2216 VFIODevice *vbasedev, Error **errp)
2218 struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
2219 int ret, fd;
2221 fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
2222 if (fd < 0) {
2223 error_setg_errno(errp, errno, "error getting device from group %d",
2224 group->groupid);
2225 error_append_hint(errp,
2226 "Verify all devices in group %d are bound to vfio-<bus> "
2227 "or pci-stub and not already in use\n", group->groupid);
2228 return fd;
2231 ret = ioctl(fd, VFIO_DEVICE_GET_INFO, &dev_info);
2232 if (ret) {
2233 error_setg_errno(errp, errno, "error getting device info");
2234 close(fd);
2235 return ret;
2239 * Set discarding of RAM as not broken for this group if the driver knows
2240 * the device operates compatibly with discarding. Setting must be
2241 * consistent per group, but since compatibility is really only possible
2242 * with mdev currently, we expect singleton groups.
2244 if (vbasedev->ram_block_discard_allowed !=
2245 group->ram_block_discard_allowed) {
2246 if (!QLIST_EMPTY(&group->device_list)) {
2247 error_setg(errp, "Inconsistent setting of support for discarding "
2248 "RAM (e.g., balloon) within group");
2249 close(fd);
2250 return -1;
2253 if (!group->ram_block_discard_allowed) {
2254 group->ram_block_discard_allowed = true;
2255 ram_block_discard_disable(false);
2259 vbasedev->fd = fd;
2260 vbasedev->group = group;
2261 QLIST_INSERT_HEAD(&group->device_list, vbasedev, next);
2263 vbasedev->num_irqs = dev_info.num_irqs;
2264 vbasedev->num_regions = dev_info.num_regions;
2265 vbasedev->flags = dev_info.flags;
2267 trace_vfio_get_device(name, dev_info.flags, dev_info.num_regions,
2268 dev_info.num_irqs);
2270 vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
2271 return 0;
2274 void vfio_put_base_device(VFIODevice *vbasedev)
2276 if (!vbasedev->group) {
2277 return;
2279 QLIST_REMOVE(vbasedev, next);
2280 vbasedev->group = NULL;
2281 trace_vfio_put_base_device(vbasedev->fd);
2282 close(vbasedev->fd);
2285 int vfio_get_region_info(VFIODevice *vbasedev, int index,
2286 struct vfio_region_info **info)
2288 size_t argsz = sizeof(struct vfio_region_info);
2290 *info = g_malloc0(argsz);
2292 (*info)->index = index;
2293 retry:
2294 (*info)->argsz = argsz;
2296 if (ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, *info)) {
2297 g_free(*info);
2298 *info = NULL;
2299 return -errno;
2302 if ((*info)->argsz > argsz) {
2303 argsz = (*info)->argsz;
2304 *info = g_realloc(*info, argsz);
2306 goto retry;
2309 return 0;
2312 int vfio_get_dev_region_info(VFIODevice *vbasedev, uint32_t type,
2313 uint32_t subtype, struct vfio_region_info **info)
2315 int i;
2317 for (i = 0; i < vbasedev->num_regions; i++) {
2318 struct vfio_info_cap_header *hdr;
2319 struct vfio_region_info_cap_type *cap_type;
2321 if (vfio_get_region_info(vbasedev, i, info)) {
2322 continue;
2325 hdr = vfio_get_region_info_cap(*info, VFIO_REGION_INFO_CAP_TYPE);
2326 if (!hdr) {
2327 g_free(*info);
2328 continue;
2331 cap_type = container_of(hdr, struct vfio_region_info_cap_type, header);
2333 trace_vfio_get_dev_region(vbasedev->name, i,
2334 cap_type->type, cap_type->subtype);
2336 if (cap_type->type == type && cap_type->subtype == subtype) {
2337 return 0;
2340 g_free(*info);
2343 *info = NULL;
2344 return -ENODEV;
2347 bool vfio_has_region_cap(VFIODevice *vbasedev, int region, uint16_t cap_type)
2349 struct vfio_region_info *info = NULL;
2350 bool ret = false;
2352 if (!vfio_get_region_info(vbasedev, region, &info)) {
2353 if (vfio_get_region_info_cap(info, cap_type)) {
2354 ret = true;
2356 g_free(info);
2359 return ret;
2363 * Interfaces for IBM EEH (Enhanced Error Handling)
2365 static bool vfio_eeh_container_ok(VFIOContainer *container)
2368 * As of 2016-03-04 (linux-4.5) the host kernel EEH/VFIO
2369 * implementation is broken if there are multiple groups in a
2370 * container. The hardware works in units of Partitionable
2371 * Endpoints (== IOMMU groups) and the EEH operations naively
2372 * iterate across all groups in the container, without any logic
2373 * to make sure the groups have their state synchronized. For
2374 * certain operations (ENABLE) that might be ok, until an error
2375 * occurs, but for others (GET_STATE) it's clearly broken.
2379 * XXX Once fixed kernels exist, test for them here
2382 if (QLIST_EMPTY(&container->group_list)) {
2383 return false;
2386 if (QLIST_NEXT(QLIST_FIRST(&container->group_list), container_next)) {
2387 return false;
2390 return true;
2393 static int vfio_eeh_container_op(VFIOContainer *container, uint32_t op)
2395 struct vfio_eeh_pe_op pe_op = {
2396 .argsz = sizeof(pe_op),
2397 .op = op,
2399 int ret;
2401 if (!vfio_eeh_container_ok(container)) {
2402 error_report("vfio/eeh: EEH_PE_OP 0x%x: "
2403 "kernel requires a container with exactly one group", op);
2404 return -EPERM;
2407 ret = ioctl(container->fd, VFIO_EEH_PE_OP, &pe_op);
2408 if (ret < 0) {
2409 error_report("vfio/eeh: EEH_PE_OP 0x%x failed: %m", op);
2410 return -errno;
2413 return ret;
2416 static VFIOContainer *vfio_eeh_as_container(AddressSpace *as)
2418 VFIOAddressSpace *space = vfio_get_address_space(as);
2419 VFIOContainer *container = NULL;
2421 if (QLIST_EMPTY(&space->containers)) {
2422 /* No containers to act on */
2423 goto out;
2426 container = QLIST_FIRST(&space->containers);
2428 if (QLIST_NEXT(container, next)) {
2429 /* We don't yet have logic to synchronize EEH state across
2430 * multiple containers */
2431 container = NULL;
2432 goto out;
2435 out:
2436 vfio_put_address_space(space);
2437 return container;
2440 bool vfio_eeh_as_ok(AddressSpace *as)
2442 VFIOContainer *container = vfio_eeh_as_container(as);
2444 return (container != NULL) && vfio_eeh_container_ok(container);
2447 int vfio_eeh_as_op(AddressSpace *as, uint32_t op)
2449 VFIOContainer *container = vfio_eeh_as_container(as);
2451 if (!container) {
2452 return -ENODEV;
2454 return vfio_eeh_container_op(container, op);