xref: /openbmc/qemu/hw/vfio/common.c (revision d1987c81)
1 /*
2  * generic functions used by VFIO devices
3  *
4  * Copyright Red Hat, Inc. 2012
5  *
6  * Authors:
7  *  Alex Williamson <alex.williamson@redhat.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
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)
19  */
20 
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>
27 
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 "sysemu/runstate.h"
40 #include "trace.h"
41 #include "qapi/error.h"
42 #include "migration/migration.h"
43 
44 VFIOGroupList vfio_group_list =
45     QLIST_HEAD_INITIALIZER(vfio_group_list);
46 static QLIST_HEAD(, VFIOAddressSpace) vfio_address_spaces =
47     QLIST_HEAD_INITIALIZER(vfio_address_spaces);
48 
49 #ifdef CONFIG_KVM
50 /*
51  * We have a single VFIO pseudo device per KVM VM.  Once created it lives
52  * for the life of the VM.  Closing the file descriptor only drops our
53  * reference to it and the device's reference to kvm.  Therefore once
54  * initialized, this file descriptor is only released on QEMU exit and
55  * we'll re-use it should another vfio device be attached before then.
56  */
57 static int vfio_kvm_device_fd = -1;
58 #endif
59 
60 /*
61  * Common VFIO interrupt disable
62  */
63 void vfio_disable_irqindex(VFIODevice *vbasedev, int index)
64 {
65     struct vfio_irq_set irq_set = {
66         .argsz = sizeof(irq_set),
67         .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
68         .index = index,
69         .start = 0,
70         .count = 0,
71     };
72 
73     ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
74 }
75 
76 void vfio_unmask_single_irqindex(VFIODevice *vbasedev, int index)
77 {
78     struct vfio_irq_set irq_set = {
79         .argsz = sizeof(irq_set),
80         .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
81         .index = index,
82         .start = 0,
83         .count = 1,
84     };
85 
86     ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
87 }
88 
89 void vfio_mask_single_irqindex(VFIODevice *vbasedev, int index)
90 {
91     struct vfio_irq_set irq_set = {
92         .argsz = sizeof(irq_set),
93         .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK,
94         .index = index,
95         .start = 0,
96         .count = 1,
97     };
98 
99     ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
100 }
101 
102 static inline const char *action_to_str(int action)
103 {
104     switch (action) {
105     case VFIO_IRQ_SET_ACTION_MASK:
106         return "MASK";
107     case VFIO_IRQ_SET_ACTION_UNMASK:
108         return "UNMASK";
109     case VFIO_IRQ_SET_ACTION_TRIGGER:
110         return "TRIGGER";
111     default:
112         return "UNKNOWN ACTION";
113     }
114 }
115 
116 static const char *index_to_str(VFIODevice *vbasedev, int index)
117 {
118     if (vbasedev->type != VFIO_DEVICE_TYPE_PCI) {
119         return NULL;
120     }
121 
122     switch (index) {
123     case VFIO_PCI_INTX_IRQ_INDEX:
124         return "INTX";
125     case VFIO_PCI_MSI_IRQ_INDEX:
126         return "MSI";
127     case VFIO_PCI_MSIX_IRQ_INDEX:
128         return "MSIX";
129     case VFIO_PCI_ERR_IRQ_INDEX:
130         return "ERR";
131     case VFIO_PCI_REQ_IRQ_INDEX:
132         return "REQ";
133     default:
134         return NULL;
135     }
136 }
137 
138 static int vfio_ram_block_discard_disable(VFIOContainer *container, bool state)
139 {
140     switch (container->iommu_type) {
141     case VFIO_TYPE1v2_IOMMU:
142     case VFIO_TYPE1_IOMMU:
143         /*
144          * We support coordinated discarding of RAM via the RamDiscardManager.
145          */
146         return ram_block_uncoordinated_discard_disable(state);
147     default:
148         /*
149          * VFIO_SPAPR_TCE_IOMMU most probably works just fine with
150          * RamDiscardManager, however, it is completely untested.
151          *
152          * VFIO_SPAPR_TCE_v2_IOMMU with "DMA memory preregistering" does
153          * completely the opposite of managing mapping/pinning dynamically as
154          * required by RamDiscardManager. We would have to special-case sections
155          * with a RamDiscardManager.
156          */
157         return ram_block_discard_disable(state);
158     }
159 }
160 
161 int vfio_set_irq_signaling(VFIODevice *vbasedev, int index, int subindex,
162                            int action, int fd, Error **errp)
163 {
164     struct vfio_irq_set *irq_set;
165     int argsz, ret = 0;
166     const char *name;
167     int32_t *pfd;
168 
169     argsz = sizeof(*irq_set) + sizeof(*pfd);
170 
171     irq_set = g_malloc0(argsz);
172     irq_set->argsz = argsz;
173     irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | action;
174     irq_set->index = index;
175     irq_set->start = subindex;
176     irq_set->count = 1;
177     pfd = (int32_t *)&irq_set->data;
178     *pfd = fd;
179 
180     if (ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, irq_set)) {
181         ret = -errno;
182     }
183     g_free(irq_set);
184 
185     if (!ret) {
186         return 0;
187     }
188 
189     error_setg_errno(errp, -ret, "VFIO_DEVICE_SET_IRQS failure");
190 
191     name = index_to_str(vbasedev, index);
192     if (name) {
193         error_prepend(errp, "%s-%d: ", name, subindex);
194     } else {
195         error_prepend(errp, "index %d-%d: ", index, subindex);
196     }
197     error_prepend(errp,
198                   "Failed to %s %s eventfd signaling for interrupt ",
199                   fd < 0 ? "tear down" : "set up", action_to_str(action));
200     return ret;
201 }
202 
203 /*
204  * IO Port/MMIO - Beware of the endians, VFIO is always little endian
205  */
206 void vfio_region_write(void *opaque, hwaddr addr,
207                        uint64_t data, unsigned size)
208 {
209     VFIORegion *region = opaque;
210     VFIODevice *vbasedev = region->vbasedev;
211     union {
212         uint8_t byte;
213         uint16_t word;
214         uint32_t dword;
215         uint64_t qword;
216     } buf;
217 
218     switch (size) {
219     case 1:
220         buf.byte = data;
221         break;
222     case 2:
223         buf.word = cpu_to_le16(data);
224         break;
225     case 4:
226         buf.dword = cpu_to_le32(data);
227         break;
228     case 8:
229         buf.qword = cpu_to_le64(data);
230         break;
231     default:
232         hw_error("vfio: unsupported write size, %u bytes", size);
233         break;
234     }
235 
236     if (pwrite(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
237         error_report("%s(%s:region%d+0x%"HWADDR_PRIx", 0x%"PRIx64
238                      ",%d) failed: %m",
239                      __func__, vbasedev->name, region->nr,
240                      addr, data, size);
241     }
242 
243     trace_vfio_region_write(vbasedev->name, region->nr, addr, data, size);
244 
245     /*
246      * A read or write to a BAR always signals an INTx EOI.  This will
247      * do nothing if not pending (including not in INTx mode).  We assume
248      * that a BAR access is in response to an interrupt and that BAR
249      * accesses will service the interrupt.  Unfortunately, we don't know
250      * which access will service the interrupt, so we're potentially
251      * getting quite a few host interrupts per guest interrupt.
252      */
253     vbasedev->ops->vfio_eoi(vbasedev);
254 }
255 
256 uint64_t vfio_region_read(void *opaque,
257                           hwaddr addr, unsigned size)
258 {
259     VFIORegion *region = opaque;
260     VFIODevice *vbasedev = region->vbasedev;
261     union {
262         uint8_t byte;
263         uint16_t word;
264         uint32_t dword;
265         uint64_t qword;
266     } buf;
267     uint64_t data = 0;
268 
269     if (pread(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
270         error_report("%s(%s:region%d+0x%"HWADDR_PRIx", %d) failed: %m",
271                      __func__, vbasedev->name, region->nr,
272                      addr, size);
273         return (uint64_t)-1;
274     }
275     switch (size) {
276     case 1:
277         data = buf.byte;
278         break;
279     case 2:
280         data = le16_to_cpu(buf.word);
281         break;
282     case 4:
283         data = le32_to_cpu(buf.dword);
284         break;
285     case 8:
286         data = le64_to_cpu(buf.qword);
287         break;
288     default:
289         hw_error("vfio: unsupported read size, %u bytes", size);
290         break;
291     }
292 
293     trace_vfio_region_read(vbasedev->name, region->nr, addr, size, data);
294 
295     /* Same as write above */
296     vbasedev->ops->vfio_eoi(vbasedev);
297 
298     return data;
299 }
300 
301 const MemoryRegionOps vfio_region_ops = {
302     .read = vfio_region_read,
303     .write = vfio_region_write,
304     .endianness = DEVICE_LITTLE_ENDIAN,
305     .valid = {
306         .min_access_size = 1,
307         .max_access_size = 8,
308     },
309     .impl = {
310         .min_access_size = 1,
311         .max_access_size = 8,
312     },
313 };
314 
315 /*
316  * Device state interfaces
317  */
318 
319 bool vfio_mig_active(void)
320 {
321     VFIOGroup *group;
322     VFIODevice *vbasedev;
323 
324     if (QLIST_EMPTY(&vfio_group_list)) {
325         return false;
326     }
327 
328     QLIST_FOREACH(group, &vfio_group_list, next) {
329         QLIST_FOREACH(vbasedev, &group->device_list, next) {
330             if (vbasedev->migration_blocker) {
331                 return false;
332             }
333         }
334     }
335     return true;
336 }
337 
338 static bool vfio_devices_all_dirty_tracking(VFIOContainer *container)
339 {
340     VFIOGroup *group;
341     VFIODevice *vbasedev;
342     MigrationState *ms = migrate_get_current();
343 
344     if (!migration_is_setup_or_active(ms->state)) {
345         return false;
346     }
347 
348     QLIST_FOREACH(group, &container->group_list, container_next) {
349         QLIST_FOREACH(vbasedev, &group->device_list, next) {
350             VFIOMigration *migration = vbasedev->migration;
351 
352             if (!migration) {
353                 return false;
354             }
355 
356             if ((vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF)
357                 && (migration->device_state & VFIO_DEVICE_STATE_RUNNING)) {
358                 return false;
359             }
360         }
361     }
362     return true;
363 }
364 
365 static bool vfio_devices_all_running_and_saving(VFIOContainer *container)
366 {
367     VFIOGroup *group;
368     VFIODevice *vbasedev;
369     MigrationState *ms = migrate_get_current();
370 
371     if (!migration_is_setup_or_active(ms->state)) {
372         return false;
373     }
374 
375     QLIST_FOREACH(group, &container->group_list, container_next) {
376         QLIST_FOREACH(vbasedev, &group->device_list, next) {
377             VFIOMigration *migration = vbasedev->migration;
378 
379             if (!migration) {
380                 return false;
381             }
382 
383             if ((migration->device_state & VFIO_DEVICE_STATE_SAVING) &&
384                 (migration->device_state & VFIO_DEVICE_STATE_RUNNING)) {
385                 continue;
386             } else {
387                 return false;
388             }
389         }
390     }
391     return true;
392 }
393 
394 static int vfio_dma_unmap_bitmap(VFIOContainer *container,
395                                  hwaddr iova, ram_addr_t size,
396                                  IOMMUTLBEntry *iotlb)
397 {
398     struct vfio_iommu_type1_dma_unmap *unmap;
399     struct vfio_bitmap *bitmap;
400     uint64_t pages = REAL_HOST_PAGE_ALIGN(size) / qemu_real_host_page_size;
401     int ret;
402 
403     unmap = g_malloc0(sizeof(*unmap) + sizeof(*bitmap));
404 
405     unmap->argsz = sizeof(*unmap) + sizeof(*bitmap);
406     unmap->iova = iova;
407     unmap->size = size;
408     unmap->flags |= VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP;
409     bitmap = (struct vfio_bitmap *)&unmap->data;
410 
411     /*
412      * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
413      * qemu_real_host_page_size to mark those dirty. Hence set bitmap_pgsize
414      * to qemu_real_host_page_size.
415      */
416 
417     bitmap->pgsize = qemu_real_host_page_size;
418     bitmap->size = ROUND_UP(pages, sizeof(__u64) * BITS_PER_BYTE) /
419                    BITS_PER_BYTE;
420 
421     if (bitmap->size > container->max_dirty_bitmap_size) {
422         error_report("UNMAP: Size of bitmap too big 0x%"PRIx64,
423                      (uint64_t)bitmap->size);
424         ret = -E2BIG;
425         goto unmap_exit;
426     }
427 
428     bitmap->data = g_try_malloc0(bitmap->size);
429     if (!bitmap->data) {
430         ret = -ENOMEM;
431         goto unmap_exit;
432     }
433 
434     ret = ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, unmap);
435     if (!ret) {
436         cpu_physical_memory_set_dirty_lebitmap((unsigned long *)bitmap->data,
437                 iotlb->translated_addr, pages);
438     } else {
439         error_report("VFIO_UNMAP_DMA with DIRTY_BITMAP : %m");
440     }
441 
442     g_free(bitmap->data);
443 unmap_exit:
444     g_free(unmap);
445     return ret;
446 }
447 
448 /*
449  * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
450  */
451 static int vfio_dma_unmap(VFIOContainer *container,
452                           hwaddr iova, ram_addr_t size,
453                           IOMMUTLBEntry *iotlb)
454 {
455     struct vfio_iommu_type1_dma_unmap unmap = {
456         .argsz = sizeof(unmap),
457         .flags = 0,
458         .iova = iova,
459         .size = size,
460     };
461 
462     if (iotlb && container->dirty_pages_supported &&
463         vfio_devices_all_running_and_saving(container)) {
464         return vfio_dma_unmap_bitmap(container, iova, size, iotlb);
465     }
466 
467     while (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
468         /*
469          * The type1 backend has an off-by-one bug in the kernel (71a7d3d78e3c
470          * v4.15) where an overflow in its wrap-around check prevents us from
471          * unmapping the last page of the address space.  Test for the error
472          * condition and re-try the unmap excluding the last page.  The
473          * expectation is that we've never mapped the last page anyway and this
474          * unmap request comes via vIOMMU support which also makes it unlikely
475          * that this page is used.  This bug was introduced well after type1 v2
476          * support was introduced, so we shouldn't need to test for v1.  A fix
477          * is queued for kernel v5.0 so this workaround can be removed once
478          * affected kernels are sufficiently deprecated.
479          */
480         if (errno == EINVAL && unmap.size && !(unmap.iova + unmap.size) &&
481             container->iommu_type == VFIO_TYPE1v2_IOMMU) {
482             trace_vfio_dma_unmap_overflow_workaround();
483             unmap.size -= 1ULL << ctz64(container->pgsizes);
484             continue;
485         }
486         error_report("VFIO_UNMAP_DMA failed: %s", strerror(errno));
487         return -errno;
488     }
489 
490     return 0;
491 }
492 
493 static int vfio_dma_map(VFIOContainer *container, hwaddr iova,
494                         ram_addr_t size, void *vaddr, bool readonly)
495 {
496     struct vfio_iommu_type1_dma_map map = {
497         .argsz = sizeof(map),
498         .flags = VFIO_DMA_MAP_FLAG_READ,
499         .vaddr = (__u64)(uintptr_t)vaddr,
500         .iova = iova,
501         .size = size,
502     };
503 
504     if (!readonly) {
505         map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
506     }
507 
508     /*
509      * Try the mapping, if it fails with EBUSY, unmap the region and try
510      * again.  This shouldn't be necessary, but we sometimes see it in
511      * the VGA ROM space.
512      */
513     if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
514         (errno == EBUSY && vfio_dma_unmap(container, iova, size, NULL) == 0 &&
515          ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
516         return 0;
517     }
518 
519     error_report("VFIO_MAP_DMA failed: %s", strerror(errno));
520     return -errno;
521 }
522 
523 static void vfio_host_win_add(VFIOContainer *container,
524                               hwaddr min_iova, hwaddr max_iova,
525                               uint64_t iova_pgsizes)
526 {
527     VFIOHostDMAWindow *hostwin;
528 
529     QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
530         if (ranges_overlap(hostwin->min_iova,
531                            hostwin->max_iova - hostwin->min_iova + 1,
532                            min_iova,
533                            max_iova - min_iova + 1)) {
534             hw_error("%s: Overlapped IOMMU are not enabled", __func__);
535         }
536     }
537 
538     hostwin = g_malloc0(sizeof(*hostwin));
539 
540     hostwin->min_iova = min_iova;
541     hostwin->max_iova = max_iova;
542     hostwin->iova_pgsizes = iova_pgsizes;
543     QLIST_INSERT_HEAD(&container->hostwin_list, hostwin, hostwin_next);
544 }
545 
546 static int vfio_host_win_del(VFIOContainer *container, hwaddr min_iova,
547                              hwaddr max_iova)
548 {
549     VFIOHostDMAWindow *hostwin;
550 
551     QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
552         if (hostwin->min_iova == min_iova && hostwin->max_iova == max_iova) {
553             QLIST_REMOVE(hostwin, hostwin_next);
554             return 0;
555         }
556     }
557 
558     return -1;
559 }
560 
561 static bool vfio_listener_skipped_section(MemoryRegionSection *section)
562 {
563     return (!memory_region_is_ram(section->mr) &&
564             !memory_region_is_iommu(section->mr)) ||
565            /*
566             * Sizing an enabled 64-bit BAR can cause spurious mappings to
567             * addresses in the upper part of the 64-bit address space.  These
568             * are never accessed by the CPU and beyond the address width of
569             * some IOMMU hardware.  TODO: VFIO should tell us the IOMMU width.
570             */
571            section->offset_within_address_space & (1ULL << 63);
572 }
573 
574 /* Called with rcu_read_lock held.  */
575 static bool vfio_get_xlat_addr(IOMMUTLBEntry *iotlb, void **vaddr,
576                                ram_addr_t *ram_addr, bool *read_only)
577 {
578     MemoryRegion *mr;
579     hwaddr xlat;
580     hwaddr len = iotlb->addr_mask + 1;
581     bool writable = iotlb->perm & IOMMU_WO;
582 
583     /*
584      * The IOMMU TLB entry we have just covers translation through
585      * this IOMMU to its immediate target.  We need to translate
586      * it the rest of the way through to memory.
587      */
588     mr = address_space_translate(&address_space_memory,
589                                  iotlb->translated_addr,
590                                  &xlat, &len, writable,
591                                  MEMTXATTRS_UNSPECIFIED);
592     if (!memory_region_is_ram(mr)) {
593         error_report("iommu map to non memory area %"HWADDR_PRIx"",
594                      xlat);
595         return false;
596     } else if (memory_region_has_ram_discard_manager(mr)) {
597         RamDiscardManager *rdm = memory_region_get_ram_discard_manager(mr);
598         MemoryRegionSection tmp = {
599             .mr = mr,
600             .offset_within_region = xlat,
601             .size = int128_make64(len),
602         };
603 
604         /*
605          * Malicious VMs can map memory into the IOMMU, which is expected
606          * to remain discarded. vfio will pin all pages, populating memory.
607          * Disallow that. vmstate priorities make sure any RamDiscardManager
608          * were already restored before IOMMUs are restored.
609          */
610         if (!ram_discard_manager_is_populated(rdm, &tmp)) {
611             error_report("iommu map to discarded memory (e.g., unplugged via"
612                          " virtio-mem): %"HWADDR_PRIx"",
613                          iotlb->translated_addr);
614             return false;
615         }
616 
617         /*
618          * Malicious VMs might trigger discarding of IOMMU-mapped memory. The
619          * pages will remain pinned inside vfio until unmapped, resulting in a
620          * higher memory consumption than expected. If memory would get
621          * populated again later, there would be an inconsistency between pages
622          * pinned by vfio and pages seen by QEMU. This is the case until
623          * unmapped from the IOMMU (e.g., during device reset).
624          *
625          * With malicious guests, we really only care about pinning more memory
626          * than expected. RLIMIT_MEMLOCK set for the user/process can never be
627          * exceeded and can be used to mitigate this problem.
628          */
629         warn_report_once("Using vfio with vIOMMUs and coordinated discarding of"
630                          " RAM (e.g., virtio-mem) works, however, malicious"
631                          " guests can trigger pinning of more memory than"
632                          " intended via an IOMMU. It's possible to mitigate "
633                          " by setting/adjusting RLIMIT_MEMLOCK.");
634     }
635 
636     /*
637      * Translation truncates length to the IOMMU page size,
638      * check that it did not truncate too much.
639      */
640     if (len & iotlb->addr_mask) {
641         error_report("iommu has granularity incompatible with target AS");
642         return false;
643     }
644 
645     if (vaddr) {
646         *vaddr = memory_region_get_ram_ptr(mr) + xlat;
647     }
648 
649     if (ram_addr) {
650         *ram_addr = memory_region_get_ram_addr(mr) + xlat;
651     }
652 
653     if (read_only) {
654         *read_only = !writable || mr->readonly;
655     }
656 
657     return true;
658 }
659 
660 static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
661 {
662     VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
663     VFIOContainer *container = giommu->container;
664     hwaddr iova = iotlb->iova + giommu->iommu_offset;
665     void *vaddr;
666     int ret;
667 
668     trace_vfio_iommu_map_notify(iotlb->perm == IOMMU_NONE ? "UNMAP" : "MAP",
669                                 iova, iova + iotlb->addr_mask);
670 
671     if (iotlb->target_as != &address_space_memory) {
672         error_report("Wrong target AS \"%s\", only system memory is allowed",
673                      iotlb->target_as->name ? iotlb->target_as->name : "none");
674         return;
675     }
676 
677     rcu_read_lock();
678 
679     if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {
680         bool read_only;
681 
682         if (!vfio_get_xlat_addr(iotlb, &vaddr, NULL, &read_only)) {
683             goto out;
684         }
685         /*
686          * vaddr is only valid until rcu_read_unlock(). But after
687          * vfio_dma_map has set up the mapping the pages will be
688          * pinned by the kernel. This makes sure that the RAM backend
689          * of vaddr will always be there, even if the memory object is
690          * destroyed and its backing memory munmap-ed.
691          */
692         ret = vfio_dma_map(container, iova,
693                            iotlb->addr_mask + 1, vaddr,
694                            read_only);
695         if (ret) {
696             error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
697                          "0x%"HWADDR_PRIx", %p) = %d (%m)",
698                          container, iova,
699                          iotlb->addr_mask + 1, vaddr, ret);
700         }
701     } else {
702         ret = vfio_dma_unmap(container, iova, iotlb->addr_mask + 1, iotlb);
703         if (ret) {
704             error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
705                          "0x%"HWADDR_PRIx") = %d (%m)",
706                          container, iova,
707                          iotlb->addr_mask + 1, ret);
708         }
709     }
710 out:
711     rcu_read_unlock();
712 }
713 
714 static void vfio_ram_discard_notify_discard(RamDiscardListener *rdl,
715                                             MemoryRegionSection *section)
716 {
717     VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
718                                                 listener);
719     const hwaddr size = int128_get64(section->size);
720     const hwaddr iova = section->offset_within_address_space;
721     int ret;
722 
723     /* Unmap with a single call. */
724     ret = vfio_dma_unmap(vrdl->container, iova, size , NULL);
725     if (ret) {
726         error_report("%s: vfio_dma_unmap() failed: %s", __func__,
727                      strerror(-ret));
728     }
729 }
730 
731 static int vfio_ram_discard_notify_populate(RamDiscardListener *rdl,
732                                             MemoryRegionSection *section)
733 {
734     VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
735                                                 listener);
736     const hwaddr end = section->offset_within_region +
737                        int128_get64(section->size);
738     hwaddr start, next, iova;
739     void *vaddr;
740     int ret;
741 
742     /*
743      * Map in (aligned within memory region) minimum granularity, so we can
744      * unmap in minimum granularity later.
745      */
746     for (start = section->offset_within_region; start < end; start = next) {
747         next = ROUND_UP(start + 1, vrdl->granularity);
748         next = MIN(next, end);
749 
750         iova = start - section->offset_within_region +
751                section->offset_within_address_space;
752         vaddr = memory_region_get_ram_ptr(section->mr) + start;
753 
754         ret = vfio_dma_map(vrdl->container, iova, next - start,
755                            vaddr, section->readonly);
756         if (ret) {
757             /* Rollback */
758             vfio_ram_discard_notify_discard(rdl, section);
759             return ret;
760         }
761     }
762     return 0;
763 }
764 
765 static void vfio_register_ram_discard_listener(VFIOContainer *container,
766                                                MemoryRegionSection *section)
767 {
768     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
769     VFIORamDiscardListener *vrdl;
770 
771     /* Ignore some corner cases not relevant in practice. */
772     g_assert(QEMU_IS_ALIGNED(section->offset_within_region, TARGET_PAGE_SIZE));
773     g_assert(QEMU_IS_ALIGNED(section->offset_within_address_space,
774                              TARGET_PAGE_SIZE));
775     g_assert(QEMU_IS_ALIGNED(int128_get64(section->size), TARGET_PAGE_SIZE));
776 
777     vrdl = g_new0(VFIORamDiscardListener, 1);
778     vrdl->container = container;
779     vrdl->mr = section->mr;
780     vrdl->offset_within_address_space = section->offset_within_address_space;
781     vrdl->size = int128_get64(section->size);
782     vrdl->granularity = ram_discard_manager_get_min_granularity(rdm,
783                                                                 section->mr);
784 
785     g_assert(vrdl->granularity && is_power_of_2(vrdl->granularity));
786     g_assert(vrdl->granularity >= 1 << ctz64(container->pgsizes));
787 
788     ram_discard_listener_init(&vrdl->listener,
789                               vfio_ram_discard_notify_populate,
790                               vfio_ram_discard_notify_discard, true);
791     ram_discard_manager_register_listener(rdm, &vrdl->listener, section);
792     QLIST_INSERT_HEAD(&container->vrdl_list, vrdl, next);
793 
794     /*
795      * Sanity-check if we have a theoretically problematic setup where we could
796      * exceed the maximum number of possible DMA mappings over time. We assume
797      * that each mapped section in the same address space as a RamDiscardManager
798      * section consumes exactly one DMA mapping, with the exception of
799      * RamDiscardManager sections; i.e., we don't expect to have gIOMMU sections
800      * in the same address space as RamDiscardManager sections.
801      *
802      * We assume that each section in the address space consumes one memslot.
803      * We take the number of KVM memory slots as a best guess for the maximum
804      * number of sections in the address space we could have over time,
805      * also consuming DMA mappings.
806      */
807     if (container->dma_max_mappings) {
808         unsigned int vrdl_count = 0, vrdl_mappings = 0, max_memslots = 512;
809 
810 #ifdef CONFIG_KVM
811         if (kvm_enabled()) {
812             max_memslots = kvm_get_max_memslots();
813         }
814 #endif
815 
816         QLIST_FOREACH(vrdl, &container->vrdl_list, next) {
817             hwaddr start, end;
818 
819             start = QEMU_ALIGN_DOWN(vrdl->offset_within_address_space,
820                                     vrdl->granularity);
821             end = ROUND_UP(vrdl->offset_within_address_space + vrdl->size,
822                            vrdl->granularity);
823             vrdl_mappings += (end - start) / vrdl->granularity;
824             vrdl_count++;
825         }
826 
827         if (vrdl_mappings + max_memslots - vrdl_count >
828             container->dma_max_mappings) {
829             warn_report("%s: possibly running out of DMA mappings. E.g., try"
830                         " increasing the 'block-size' of virtio-mem devies."
831                         " Maximum possible DMA mappings: %d, Maximum possible"
832                         " memslots: %d", __func__, container->dma_max_mappings,
833                         max_memslots);
834         }
835     }
836 }
837 
838 static void vfio_unregister_ram_discard_listener(VFIOContainer *container,
839                                                  MemoryRegionSection *section)
840 {
841     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
842     VFIORamDiscardListener *vrdl = NULL;
843 
844     QLIST_FOREACH(vrdl, &container->vrdl_list, next) {
845         if (vrdl->mr == section->mr &&
846             vrdl->offset_within_address_space ==
847             section->offset_within_address_space) {
848             break;
849         }
850     }
851 
852     if (!vrdl) {
853         hw_error("vfio: Trying to unregister missing RAM discard listener");
854     }
855 
856     ram_discard_manager_unregister_listener(rdm, &vrdl->listener);
857     QLIST_REMOVE(vrdl, next);
858     g_free(vrdl);
859 }
860 
861 static void vfio_listener_region_add(MemoryListener *listener,
862                                      MemoryRegionSection *section)
863 {
864     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
865     hwaddr iova, end;
866     Int128 llend, llsize;
867     void *vaddr;
868     int ret;
869     VFIOHostDMAWindow *hostwin;
870     bool hostwin_found;
871     Error *err = NULL;
872 
873     if (vfio_listener_skipped_section(section)) {
874         trace_vfio_listener_region_add_skip(
875                 section->offset_within_address_space,
876                 section->offset_within_address_space +
877                 int128_get64(int128_sub(section->size, int128_one())));
878         return;
879     }
880 
881     if (unlikely((section->offset_within_address_space &
882                   ~qemu_real_host_page_mask) !=
883                  (section->offset_within_region & ~qemu_real_host_page_mask))) {
884         error_report("%s received unaligned region", __func__);
885         return;
886     }
887 
888     iova = REAL_HOST_PAGE_ALIGN(section->offset_within_address_space);
889     llend = int128_make64(section->offset_within_address_space);
890     llend = int128_add(llend, section->size);
891     llend = int128_and(llend, int128_exts64(qemu_real_host_page_mask));
892 
893     if (int128_ge(int128_make64(iova), llend)) {
894         return;
895     }
896     end = int128_get64(int128_sub(llend, int128_one()));
897 
898     if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
899         hwaddr pgsize = 0;
900 
901         /* For now intersections are not allowed, we may relax this later */
902         QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
903             if (ranges_overlap(hostwin->min_iova,
904                                hostwin->max_iova - hostwin->min_iova + 1,
905                                section->offset_within_address_space,
906                                int128_get64(section->size))) {
907                 error_setg(&err,
908                     "region [0x%"PRIx64",0x%"PRIx64"] overlaps with existing"
909                     "host DMA window [0x%"PRIx64",0x%"PRIx64"]",
910                     section->offset_within_address_space,
911                     section->offset_within_address_space +
912                         int128_get64(section->size) - 1,
913                     hostwin->min_iova, hostwin->max_iova);
914                 goto fail;
915             }
916         }
917 
918         ret = vfio_spapr_create_window(container, section, &pgsize);
919         if (ret) {
920             error_setg_errno(&err, -ret, "Failed to create SPAPR window");
921             goto fail;
922         }
923 
924         vfio_host_win_add(container, section->offset_within_address_space,
925                           section->offset_within_address_space +
926                           int128_get64(section->size) - 1, pgsize);
927 #ifdef CONFIG_KVM
928         if (kvm_enabled()) {
929             VFIOGroup *group;
930             IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
931             struct kvm_vfio_spapr_tce param;
932             struct kvm_device_attr attr = {
933                 .group = KVM_DEV_VFIO_GROUP,
934                 .attr = KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE,
935                 .addr = (uint64_t)(unsigned long)&param,
936             };
937 
938             if (!memory_region_iommu_get_attr(iommu_mr, IOMMU_ATTR_SPAPR_TCE_FD,
939                                               &param.tablefd)) {
940                 QLIST_FOREACH(group, &container->group_list, container_next) {
941                     param.groupfd = group->fd;
942                     if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
943                         error_report("vfio: failed to setup fd %d "
944                                      "for a group with fd %d: %s",
945                                      param.tablefd, param.groupfd,
946                                      strerror(errno));
947                         return;
948                     }
949                     trace_vfio_spapr_group_attach(param.groupfd, param.tablefd);
950                 }
951             }
952         }
953 #endif
954     }
955 
956     hostwin_found = false;
957     QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
958         if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
959             hostwin_found = true;
960             break;
961         }
962     }
963 
964     if (!hostwin_found) {
965         error_setg(&err, "Container %p can't map guest IOVA region"
966                    " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx, container, iova, end);
967         goto fail;
968     }
969 
970     memory_region_ref(section->mr);
971 
972     if (memory_region_is_iommu(section->mr)) {
973         VFIOGuestIOMMU *giommu;
974         IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
975         int iommu_idx;
976 
977         trace_vfio_listener_region_add_iommu(iova, end);
978         /*
979          * FIXME: For VFIO iommu types which have KVM acceleration to
980          * avoid bouncing all map/unmaps through qemu this way, this
981          * would be the right place to wire that up (tell the KVM
982          * device emulation the VFIO iommu handles to use).
983          */
984         giommu = g_malloc0(sizeof(*giommu));
985         giommu->iommu = iommu_mr;
986         giommu->iommu_offset = section->offset_within_address_space -
987                                section->offset_within_region;
988         giommu->container = container;
989         llend = int128_add(int128_make64(section->offset_within_region),
990                            section->size);
991         llend = int128_sub(llend, int128_one());
992         iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
993                                                        MEMTXATTRS_UNSPECIFIED);
994         iommu_notifier_init(&giommu->n, vfio_iommu_map_notify,
995                             IOMMU_NOTIFIER_IOTLB_EVENTS,
996                             section->offset_within_region,
997                             int128_get64(llend),
998                             iommu_idx);
999 
1000         ret = memory_region_iommu_set_page_size_mask(giommu->iommu,
1001                                                      container->pgsizes,
1002                                                      &err);
1003         if (ret) {
1004             g_free(giommu);
1005             goto fail;
1006         }
1007 
1008         ret = memory_region_register_iommu_notifier(section->mr, &giommu->n,
1009                                                     &err);
1010         if (ret) {
1011             g_free(giommu);
1012             goto fail;
1013         }
1014         QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
1015         memory_region_iommu_replay(giommu->iommu, &giommu->n);
1016 
1017         return;
1018     }
1019 
1020     /* Here we assume that memory_region_is_ram(section->mr)==true */
1021 
1022     /*
1023      * For RAM memory regions with a RamDiscardManager, we only want to map the
1024      * actually populated parts - and update the mapping whenever we're notified
1025      * about changes.
1026      */
1027     if (memory_region_has_ram_discard_manager(section->mr)) {
1028         vfio_register_ram_discard_listener(container, section);
1029         return;
1030     }
1031 
1032     vaddr = memory_region_get_ram_ptr(section->mr) +
1033             section->offset_within_region +
1034             (iova - section->offset_within_address_space);
1035 
1036     trace_vfio_listener_region_add_ram(iova, end, vaddr);
1037 
1038     llsize = int128_sub(llend, int128_make64(iova));
1039 
1040     if (memory_region_is_ram_device(section->mr)) {
1041         hwaddr pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
1042 
1043         if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) {
1044             trace_vfio_listener_region_add_no_dma_map(
1045                 memory_region_name(section->mr),
1046                 section->offset_within_address_space,
1047                 int128_getlo(section->size),
1048                 pgmask + 1);
1049             return;
1050         }
1051     }
1052 
1053     ret = vfio_dma_map(container, iova, int128_get64(llsize),
1054                        vaddr, section->readonly);
1055     if (ret) {
1056         error_setg(&err, "vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
1057                    "0x%"HWADDR_PRIx", %p) = %d (%m)",
1058                    container, iova, int128_get64(llsize), vaddr, ret);
1059         if (memory_region_is_ram_device(section->mr)) {
1060             /* Allow unexpected mappings not to be fatal for RAM devices */
1061             error_report_err(err);
1062             return;
1063         }
1064         goto fail;
1065     }
1066 
1067     return;
1068 
1069 fail:
1070     if (memory_region_is_ram_device(section->mr)) {
1071         error_report("failed to vfio_dma_map. pci p2p may not work");
1072         return;
1073     }
1074     /*
1075      * On the initfn path, store the first error in the container so we
1076      * can gracefully fail.  Runtime, there's not much we can do other
1077      * than throw a hardware error.
1078      */
1079     if (!container->initialized) {
1080         if (!container->error) {
1081             error_propagate_prepend(&container->error, err,
1082                                     "Region %s: ",
1083                                     memory_region_name(section->mr));
1084         } else {
1085             error_free(err);
1086         }
1087     } else {
1088         error_report_err(err);
1089         hw_error("vfio: DMA mapping failed, unable to continue");
1090     }
1091 }
1092 
1093 static void vfio_listener_region_del(MemoryListener *listener,
1094                                      MemoryRegionSection *section)
1095 {
1096     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1097     hwaddr iova, end;
1098     Int128 llend, llsize;
1099     int ret;
1100     bool try_unmap = true;
1101 
1102     if (vfio_listener_skipped_section(section)) {
1103         trace_vfio_listener_region_del_skip(
1104                 section->offset_within_address_space,
1105                 section->offset_within_address_space +
1106                 int128_get64(int128_sub(section->size, int128_one())));
1107         return;
1108     }
1109 
1110     if (unlikely((section->offset_within_address_space &
1111                   ~qemu_real_host_page_mask) !=
1112                  (section->offset_within_region & ~qemu_real_host_page_mask))) {
1113         error_report("%s received unaligned region", __func__);
1114         return;
1115     }
1116 
1117     if (memory_region_is_iommu(section->mr)) {
1118         VFIOGuestIOMMU *giommu;
1119 
1120         QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
1121             if (MEMORY_REGION(giommu->iommu) == section->mr &&
1122                 giommu->n.start == section->offset_within_region) {
1123                 memory_region_unregister_iommu_notifier(section->mr,
1124                                                         &giommu->n);
1125                 QLIST_REMOVE(giommu, giommu_next);
1126                 g_free(giommu);
1127                 break;
1128             }
1129         }
1130 
1131         /*
1132          * FIXME: We assume the one big unmap below is adequate to
1133          * remove any individual page mappings in the IOMMU which
1134          * might have been copied into VFIO. This works for a page table
1135          * based IOMMU where a big unmap flattens a large range of IO-PTEs.
1136          * That may not be true for all IOMMU types.
1137          */
1138     }
1139 
1140     iova = REAL_HOST_PAGE_ALIGN(section->offset_within_address_space);
1141     llend = int128_make64(section->offset_within_address_space);
1142     llend = int128_add(llend, section->size);
1143     llend = int128_and(llend, int128_exts64(qemu_real_host_page_mask));
1144 
1145     if (int128_ge(int128_make64(iova), llend)) {
1146         return;
1147     }
1148     end = int128_get64(int128_sub(llend, int128_one()));
1149 
1150     llsize = int128_sub(llend, int128_make64(iova));
1151 
1152     trace_vfio_listener_region_del(iova, end);
1153 
1154     if (memory_region_is_ram_device(section->mr)) {
1155         hwaddr pgmask;
1156         VFIOHostDMAWindow *hostwin;
1157         bool hostwin_found = false;
1158 
1159         QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
1160             if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
1161                 hostwin_found = true;
1162                 break;
1163             }
1164         }
1165         assert(hostwin_found); /* or region_add() would have failed */
1166 
1167         pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
1168         try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask));
1169     } else if (memory_region_has_ram_discard_manager(section->mr)) {
1170         vfio_unregister_ram_discard_listener(container, section);
1171         /* Unregistering will trigger an unmap. */
1172         try_unmap = false;
1173     }
1174 
1175     if (try_unmap) {
1176         if (int128_eq(llsize, int128_2_64())) {
1177             /* The unmap ioctl doesn't accept a full 64-bit span. */
1178             llsize = int128_rshift(llsize, 1);
1179             ret = vfio_dma_unmap(container, iova, int128_get64(llsize), NULL);
1180             if (ret) {
1181                 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
1182                              "0x%"HWADDR_PRIx") = %d (%m)",
1183                              container, iova, int128_get64(llsize), ret);
1184             }
1185             iova += int128_get64(llsize);
1186         }
1187         ret = vfio_dma_unmap(container, iova, int128_get64(llsize), NULL);
1188         if (ret) {
1189             error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
1190                          "0x%"HWADDR_PRIx") = %d (%m)",
1191                          container, iova, int128_get64(llsize), ret);
1192         }
1193     }
1194 
1195     memory_region_unref(section->mr);
1196 
1197     if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
1198         vfio_spapr_remove_window(container,
1199                                  section->offset_within_address_space);
1200         if (vfio_host_win_del(container,
1201                               section->offset_within_address_space,
1202                               section->offset_within_address_space +
1203                               int128_get64(section->size) - 1) < 0) {
1204             hw_error("%s: Cannot delete missing window at %"HWADDR_PRIx,
1205                      __func__, section->offset_within_address_space);
1206         }
1207     }
1208 }
1209 
1210 static void vfio_set_dirty_page_tracking(VFIOContainer *container, bool start)
1211 {
1212     int ret;
1213     struct vfio_iommu_type1_dirty_bitmap dirty = {
1214         .argsz = sizeof(dirty),
1215     };
1216 
1217     if (start) {
1218         dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_START;
1219     } else {
1220         dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP;
1221     }
1222 
1223     ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, &dirty);
1224     if (ret) {
1225         error_report("Failed to set dirty tracking flag 0x%x errno: %d",
1226                      dirty.flags, errno);
1227     }
1228 }
1229 
1230 static void vfio_listener_log_global_start(MemoryListener *listener)
1231 {
1232     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1233 
1234     vfio_set_dirty_page_tracking(container, true);
1235 }
1236 
1237 static void vfio_listener_log_global_stop(MemoryListener *listener)
1238 {
1239     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1240 
1241     vfio_set_dirty_page_tracking(container, false);
1242 }
1243 
1244 static int vfio_get_dirty_bitmap(VFIOContainer *container, uint64_t iova,
1245                                  uint64_t size, ram_addr_t ram_addr)
1246 {
1247     struct vfio_iommu_type1_dirty_bitmap *dbitmap;
1248     struct vfio_iommu_type1_dirty_bitmap_get *range;
1249     uint64_t pages;
1250     int ret;
1251 
1252     dbitmap = g_malloc0(sizeof(*dbitmap) + sizeof(*range));
1253 
1254     dbitmap->argsz = sizeof(*dbitmap) + sizeof(*range);
1255     dbitmap->flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
1256     range = (struct vfio_iommu_type1_dirty_bitmap_get *)&dbitmap->data;
1257     range->iova = iova;
1258     range->size = size;
1259 
1260     /*
1261      * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
1262      * qemu_real_host_page_size to mark those dirty. Hence set bitmap's pgsize
1263      * to qemu_real_host_page_size.
1264      */
1265     range->bitmap.pgsize = qemu_real_host_page_size;
1266 
1267     pages = REAL_HOST_PAGE_ALIGN(range->size) / qemu_real_host_page_size;
1268     range->bitmap.size = ROUND_UP(pages, sizeof(__u64) * BITS_PER_BYTE) /
1269                                          BITS_PER_BYTE;
1270     range->bitmap.data = g_try_malloc0(range->bitmap.size);
1271     if (!range->bitmap.data) {
1272         ret = -ENOMEM;
1273         goto err_out;
1274     }
1275 
1276     ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, dbitmap);
1277     if (ret) {
1278         error_report("Failed to get dirty bitmap for iova: 0x%"PRIx64
1279                 " size: 0x%"PRIx64" err: %d", (uint64_t)range->iova,
1280                 (uint64_t)range->size, errno);
1281         goto err_out;
1282     }
1283 
1284     cpu_physical_memory_set_dirty_lebitmap((unsigned long *)range->bitmap.data,
1285                                             ram_addr, pages);
1286 
1287     trace_vfio_get_dirty_bitmap(container->fd, range->iova, range->size,
1288                                 range->bitmap.size, ram_addr);
1289 err_out:
1290     g_free(range->bitmap.data);
1291     g_free(dbitmap);
1292 
1293     return ret;
1294 }
1295 
1296 typedef struct {
1297     IOMMUNotifier n;
1298     VFIOGuestIOMMU *giommu;
1299 } vfio_giommu_dirty_notifier;
1300 
1301 static void vfio_iommu_map_dirty_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
1302 {
1303     vfio_giommu_dirty_notifier *gdn = container_of(n,
1304                                                 vfio_giommu_dirty_notifier, n);
1305     VFIOGuestIOMMU *giommu = gdn->giommu;
1306     VFIOContainer *container = giommu->container;
1307     hwaddr iova = iotlb->iova + giommu->iommu_offset;
1308     ram_addr_t translated_addr;
1309 
1310     trace_vfio_iommu_map_dirty_notify(iova, iova + iotlb->addr_mask);
1311 
1312     if (iotlb->target_as != &address_space_memory) {
1313         error_report("Wrong target AS \"%s\", only system memory is allowed",
1314                      iotlb->target_as->name ? iotlb->target_as->name : "none");
1315         return;
1316     }
1317 
1318     rcu_read_lock();
1319     if (vfio_get_xlat_addr(iotlb, NULL, &translated_addr, NULL)) {
1320         int ret;
1321 
1322         ret = vfio_get_dirty_bitmap(container, iova, iotlb->addr_mask + 1,
1323                                     translated_addr);
1324         if (ret) {
1325             error_report("vfio_iommu_map_dirty_notify(%p, 0x%"HWADDR_PRIx", "
1326                          "0x%"HWADDR_PRIx") = %d (%m)",
1327                          container, iova,
1328                          iotlb->addr_mask + 1, ret);
1329         }
1330     }
1331     rcu_read_unlock();
1332 }
1333 
1334 static int vfio_ram_discard_get_dirty_bitmap(MemoryRegionSection *section,
1335                                              void *opaque)
1336 {
1337     const hwaddr size = int128_get64(section->size);
1338     const hwaddr iova = section->offset_within_address_space;
1339     const ram_addr_t ram_addr = memory_region_get_ram_addr(section->mr) +
1340                                 section->offset_within_region;
1341     VFIORamDiscardListener *vrdl = opaque;
1342 
1343     /*
1344      * Sync the whole mapped region (spanning multiple individual mappings)
1345      * in one go.
1346      */
1347     return vfio_get_dirty_bitmap(vrdl->container, iova, size, ram_addr);
1348 }
1349 
1350 static int vfio_sync_ram_discard_listener_dirty_bitmap(VFIOContainer *container,
1351                                                    MemoryRegionSection *section)
1352 {
1353     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
1354     VFIORamDiscardListener *vrdl = NULL;
1355 
1356     QLIST_FOREACH(vrdl, &container->vrdl_list, next) {
1357         if (vrdl->mr == section->mr &&
1358             vrdl->offset_within_address_space ==
1359             section->offset_within_address_space) {
1360             break;
1361         }
1362     }
1363 
1364     if (!vrdl) {
1365         hw_error("vfio: Trying to sync missing RAM discard listener");
1366     }
1367 
1368     /*
1369      * We only want/can synchronize the bitmap for actually mapped parts -
1370      * which correspond to populated parts. Replay all populated parts.
1371      */
1372     return ram_discard_manager_replay_populated(rdm, section,
1373                                               vfio_ram_discard_get_dirty_bitmap,
1374                                                 &vrdl);
1375 }
1376 
1377 static int vfio_sync_dirty_bitmap(VFIOContainer *container,
1378                                   MemoryRegionSection *section)
1379 {
1380     ram_addr_t ram_addr;
1381 
1382     if (memory_region_is_iommu(section->mr)) {
1383         VFIOGuestIOMMU *giommu;
1384 
1385         QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
1386             if (MEMORY_REGION(giommu->iommu) == section->mr &&
1387                 giommu->n.start == section->offset_within_region) {
1388                 Int128 llend;
1389                 vfio_giommu_dirty_notifier gdn = { .giommu = giommu };
1390                 int idx = memory_region_iommu_attrs_to_index(giommu->iommu,
1391                                                        MEMTXATTRS_UNSPECIFIED);
1392 
1393                 llend = int128_add(int128_make64(section->offset_within_region),
1394                                    section->size);
1395                 llend = int128_sub(llend, int128_one());
1396 
1397                 iommu_notifier_init(&gdn.n,
1398                                     vfio_iommu_map_dirty_notify,
1399                                     IOMMU_NOTIFIER_MAP,
1400                                     section->offset_within_region,
1401                                     int128_get64(llend),
1402                                     idx);
1403                 memory_region_iommu_replay(giommu->iommu, &gdn.n);
1404                 break;
1405             }
1406         }
1407         return 0;
1408     } else if (memory_region_has_ram_discard_manager(section->mr)) {
1409         return vfio_sync_ram_discard_listener_dirty_bitmap(container, section);
1410     }
1411 
1412     ram_addr = memory_region_get_ram_addr(section->mr) +
1413                section->offset_within_region;
1414 
1415     return vfio_get_dirty_bitmap(container,
1416                    REAL_HOST_PAGE_ALIGN(section->offset_within_address_space),
1417                    int128_get64(section->size), ram_addr);
1418 }
1419 
1420 static void vfio_listener_log_sync(MemoryListener *listener,
1421         MemoryRegionSection *section)
1422 {
1423     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1424 
1425     if (vfio_listener_skipped_section(section) ||
1426         !container->dirty_pages_supported) {
1427         return;
1428     }
1429 
1430     if (vfio_devices_all_dirty_tracking(container)) {
1431         vfio_sync_dirty_bitmap(container, section);
1432     }
1433 }
1434 
1435 static const MemoryListener vfio_memory_listener = {
1436     .region_add = vfio_listener_region_add,
1437     .region_del = vfio_listener_region_del,
1438     .log_global_start = vfio_listener_log_global_start,
1439     .log_global_stop = vfio_listener_log_global_stop,
1440     .log_sync = vfio_listener_log_sync,
1441 };
1442 
1443 static void vfio_listener_release(VFIOContainer *container)
1444 {
1445     memory_listener_unregister(&container->listener);
1446     if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
1447         memory_listener_unregister(&container->prereg_listener);
1448     }
1449 }
1450 
1451 static struct vfio_info_cap_header *
1452 vfio_get_cap(void *ptr, uint32_t cap_offset, uint16_t id)
1453 {
1454     struct vfio_info_cap_header *hdr;
1455 
1456     for (hdr = ptr + cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
1457         if (hdr->id == id) {
1458             return hdr;
1459         }
1460     }
1461 
1462     return NULL;
1463 }
1464 
1465 struct vfio_info_cap_header *
1466 vfio_get_region_info_cap(struct vfio_region_info *info, uint16_t id)
1467 {
1468     if (!(info->flags & VFIO_REGION_INFO_FLAG_CAPS)) {
1469         return NULL;
1470     }
1471 
1472     return vfio_get_cap((void *)info, info->cap_offset, id);
1473 }
1474 
1475 static struct vfio_info_cap_header *
1476 vfio_get_iommu_type1_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
1477 {
1478     if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
1479         return NULL;
1480     }
1481 
1482     return vfio_get_cap((void *)info, info->cap_offset, id);
1483 }
1484 
1485 struct vfio_info_cap_header *
1486 vfio_get_device_info_cap(struct vfio_device_info *info, uint16_t id)
1487 {
1488     if (!(info->flags & VFIO_DEVICE_FLAGS_CAPS)) {
1489         return NULL;
1490     }
1491 
1492     return vfio_get_cap((void *)info, info->cap_offset, id);
1493 }
1494 
1495 bool vfio_get_info_dma_avail(struct vfio_iommu_type1_info *info,
1496                              unsigned int *avail)
1497 {
1498     struct vfio_info_cap_header *hdr;
1499     struct vfio_iommu_type1_info_dma_avail *cap;
1500 
1501     /* If the capability cannot be found, assume no DMA limiting */
1502     hdr = vfio_get_iommu_type1_info_cap(info,
1503                                         VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL);
1504     if (hdr == NULL) {
1505         return false;
1506     }
1507 
1508     if (avail != NULL) {
1509         cap = (void *) hdr;
1510         *avail = cap->avail;
1511     }
1512 
1513     return true;
1514 }
1515 
1516 static int vfio_setup_region_sparse_mmaps(VFIORegion *region,
1517                                           struct vfio_region_info *info)
1518 {
1519     struct vfio_info_cap_header *hdr;
1520     struct vfio_region_info_cap_sparse_mmap *sparse;
1521     int i, j;
1522 
1523     hdr = vfio_get_region_info_cap(info, VFIO_REGION_INFO_CAP_SPARSE_MMAP);
1524     if (!hdr) {
1525         return -ENODEV;
1526     }
1527 
1528     sparse = container_of(hdr, struct vfio_region_info_cap_sparse_mmap, header);
1529 
1530     trace_vfio_region_sparse_mmap_header(region->vbasedev->name,
1531                                          region->nr, sparse->nr_areas);
1532 
1533     region->mmaps = g_new0(VFIOMmap, sparse->nr_areas);
1534 
1535     for (i = 0, j = 0; i < sparse->nr_areas; i++) {
1536         trace_vfio_region_sparse_mmap_entry(i, sparse->areas[i].offset,
1537                                             sparse->areas[i].offset +
1538                                             sparse->areas[i].size);
1539 
1540         if (sparse->areas[i].size) {
1541             region->mmaps[j].offset = sparse->areas[i].offset;
1542             region->mmaps[j].size = sparse->areas[i].size;
1543             j++;
1544         }
1545     }
1546 
1547     region->nr_mmaps = j;
1548     region->mmaps = g_realloc(region->mmaps, j * sizeof(VFIOMmap));
1549 
1550     return 0;
1551 }
1552 
1553 int vfio_region_setup(Object *obj, VFIODevice *vbasedev, VFIORegion *region,
1554                       int index, const char *name)
1555 {
1556     struct vfio_region_info *info;
1557     int ret;
1558 
1559     ret = vfio_get_region_info(vbasedev, index, &info);
1560     if (ret) {
1561         return ret;
1562     }
1563 
1564     region->vbasedev = vbasedev;
1565     region->flags = info->flags;
1566     region->size = info->size;
1567     region->fd_offset = info->offset;
1568     region->nr = index;
1569 
1570     if (region->size) {
1571         region->mem = g_new0(MemoryRegion, 1);
1572         memory_region_init_io(region->mem, obj, &vfio_region_ops,
1573                               region, name, region->size);
1574 
1575         if (!vbasedev->no_mmap &&
1576             region->flags & VFIO_REGION_INFO_FLAG_MMAP) {
1577 
1578             ret = vfio_setup_region_sparse_mmaps(region, info);
1579 
1580             if (ret) {
1581                 region->nr_mmaps = 1;
1582                 region->mmaps = g_new0(VFIOMmap, region->nr_mmaps);
1583                 region->mmaps[0].offset = 0;
1584                 region->mmaps[0].size = region->size;
1585             }
1586         }
1587     }
1588 
1589     g_free(info);
1590 
1591     trace_vfio_region_setup(vbasedev->name, index, name,
1592                             region->flags, region->fd_offset, region->size);
1593     return 0;
1594 }
1595 
1596 static void vfio_subregion_unmap(VFIORegion *region, int index)
1597 {
1598     trace_vfio_region_unmap(memory_region_name(&region->mmaps[index].mem),
1599                             region->mmaps[index].offset,
1600                             region->mmaps[index].offset +
1601                             region->mmaps[index].size - 1);
1602     memory_region_del_subregion(region->mem, &region->mmaps[index].mem);
1603     munmap(region->mmaps[index].mmap, region->mmaps[index].size);
1604     object_unparent(OBJECT(&region->mmaps[index].mem));
1605     region->mmaps[index].mmap = NULL;
1606 }
1607 
1608 int vfio_region_mmap(VFIORegion *region)
1609 {
1610     int i, prot = 0;
1611     char *name;
1612 
1613     if (!region->mem) {
1614         return 0;
1615     }
1616 
1617     prot |= region->flags & VFIO_REGION_INFO_FLAG_READ ? PROT_READ : 0;
1618     prot |= region->flags & VFIO_REGION_INFO_FLAG_WRITE ? PROT_WRITE : 0;
1619 
1620     for (i = 0; i < region->nr_mmaps; i++) {
1621         region->mmaps[i].mmap = mmap(NULL, region->mmaps[i].size, prot,
1622                                      MAP_SHARED, region->vbasedev->fd,
1623                                      region->fd_offset +
1624                                      region->mmaps[i].offset);
1625         if (region->mmaps[i].mmap == MAP_FAILED) {
1626             int ret = -errno;
1627 
1628             trace_vfio_region_mmap_fault(memory_region_name(region->mem), i,
1629                                          region->fd_offset +
1630                                          region->mmaps[i].offset,
1631                                          region->fd_offset +
1632                                          region->mmaps[i].offset +
1633                                          region->mmaps[i].size - 1, ret);
1634 
1635             region->mmaps[i].mmap = NULL;
1636 
1637             for (i--; i >= 0; i--) {
1638                 vfio_subregion_unmap(region, i);
1639             }
1640 
1641             return ret;
1642         }
1643 
1644         name = g_strdup_printf("%s mmaps[%d]",
1645                                memory_region_name(region->mem), i);
1646         memory_region_init_ram_device_ptr(&region->mmaps[i].mem,
1647                                           memory_region_owner(region->mem),
1648                                           name, region->mmaps[i].size,
1649                                           region->mmaps[i].mmap);
1650         g_free(name);
1651         memory_region_add_subregion(region->mem, region->mmaps[i].offset,
1652                                     &region->mmaps[i].mem);
1653 
1654         trace_vfio_region_mmap(memory_region_name(&region->mmaps[i].mem),
1655                                region->mmaps[i].offset,
1656                                region->mmaps[i].offset +
1657                                region->mmaps[i].size - 1);
1658     }
1659 
1660     return 0;
1661 }
1662 
1663 void vfio_region_unmap(VFIORegion *region)
1664 {
1665     int i;
1666 
1667     if (!region->mem) {
1668         return;
1669     }
1670 
1671     for (i = 0; i < region->nr_mmaps; i++) {
1672         if (region->mmaps[i].mmap) {
1673             vfio_subregion_unmap(region, i);
1674         }
1675     }
1676 }
1677 
1678 void vfio_region_exit(VFIORegion *region)
1679 {
1680     int i;
1681 
1682     if (!region->mem) {
1683         return;
1684     }
1685 
1686     for (i = 0; i < region->nr_mmaps; i++) {
1687         if (region->mmaps[i].mmap) {
1688             memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
1689         }
1690     }
1691 
1692     trace_vfio_region_exit(region->vbasedev->name, region->nr);
1693 }
1694 
1695 void vfio_region_finalize(VFIORegion *region)
1696 {
1697     int i;
1698 
1699     if (!region->mem) {
1700         return;
1701     }
1702 
1703     for (i = 0; i < region->nr_mmaps; i++) {
1704         if (region->mmaps[i].mmap) {
1705             munmap(region->mmaps[i].mmap, region->mmaps[i].size);
1706             object_unparent(OBJECT(&region->mmaps[i].mem));
1707         }
1708     }
1709 
1710     object_unparent(OBJECT(region->mem));
1711 
1712     g_free(region->mem);
1713     g_free(region->mmaps);
1714 
1715     trace_vfio_region_finalize(region->vbasedev->name, region->nr);
1716 
1717     region->mem = NULL;
1718     region->mmaps = NULL;
1719     region->nr_mmaps = 0;
1720     region->size = 0;
1721     region->flags = 0;
1722     region->nr = 0;
1723 }
1724 
1725 void vfio_region_mmaps_set_enabled(VFIORegion *region, bool enabled)
1726 {
1727     int i;
1728 
1729     if (!region->mem) {
1730         return;
1731     }
1732 
1733     for (i = 0; i < region->nr_mmaps; i++) {
1734         if (region->mmaps[i].mmap) {
1735             memory_region_set_enabled(&region->mmaps[i].mem, enabled);
1736         }
1737     }
1738 
1739     trace_vfio_region_mmaps_set_enabled(memory_region_name(region->mem),
1740                                         enabled);
1741 }
1742 
1743 void vfio_reset_handler(void *opaque)
1744 {
1745     VFIOGroup *group;
1746     VFIODevice *vbasedev;
1747 
1748     QLIST_FOREACH(group, &vfio_group_list, next) {
1749         QLIST_FOREACH(vbasedev, &group->device_list, next) {
1750             if (vbasedev->dev->realized) {
1751                 vbasedev->ops->vfio_compute_needs_reset(vbasedev);
1752             }
1753         }
1754     }
1755 
1756     QLIST_FOREACH(group, &vfio_group_list, next) {
1757         QLIST_FOREACH(vbasedev, &group->device_list, next) {
1758             if (vbasedev->dev->realized && vbasedev->needs_reset) {
1759                 vbasedev->ops->vfio_hot_reset_multi(vbasedev);
1760             }
1761         }
1762     }
1763 }
1764 
1765 static void vfio_kvm_device_add_group(VFIOGroup *group)
1766 {
1767 #ifdef CONFIG_KVM
1768     struct kvm_device_attr attr = {
1769         .group = KVM_DEV_VFIO_GROUP,
1770         .attr = KVM_DEV_VFIO_GROUP_ADD,
1771         .addr = (uint64_t)(unsigned long)&group->fd,
1772     };
1773 
1774     if (!kvm_enabled()) {
1775         return;
1776     }
1777 
1778     if (vfio_kvm_device_fd < 0) {
1779         struct kvm_create_device cd = {
1780             .type = KVM_DEV_TYPE_VFIO,
1781         };
1782 
1783         if (kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd)) {
1784             error_report("Failed to create KVM VFIO device: %m");
1785             return;
1786         }
1787 
1788         vfio_kvm_device_fd = cd.fd;
1789     }
1790 
1791     if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1792         error_report("Failed to add group %d to KVM VFIO device: %m",
1793                      group->groupid);
1794     }
1795 #endif
1796 }
1797 
1798 static void vfio_kvm_device_del_group(VFIOGroup *group)
1799 {
1800 #ifdef CONFIG_KVM
1801     struct kvm_device_attr attr = {
1802         .group = KVM_DEV_VFIO_GROUP,
1803         .attr = KVM_DEV_VFIO_GROUP_DEL,
1804         .addr = (uint64_t)(unsigned long)&group->fd,
1805     };
1806 
1807     if (vfio_kvm_device_fd < 0) {
1808         return;
1809     }
1810 
1811     if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1812         error_report("Failed to remove group %d from KVM VFIO device: %m",
1813                      group->groupid);
1814     }
1815 #endif
1816 }
1817 
1818 static VFIOAddressSpace *vfio_get_address_space(AddressSpace *as)
1819 {
1820     VFIOAddressSpace *space;
1821 
1822     QLIST_FOREACH(space, &vfio_address_spaces, list) {
1823         if (space->as == as) {
1824             return space;
1825         }
1826     }
1827 
1828     /* No suitable VFIOAddressSpace, create a new one */
1829     space = g_malloc0(sizeof(*space));
1830     space->as = as;
1831     QLIST_INIT(&space->containers);
1832 
1833     QLIST_INSERT_HEAD(&vfio_address_spaces, space, list);
1834 
1835     return space;
1836 }
1837 
1838 static void vfio_put_address_space(VFIOAddressSpace *space)
1839 {
1840     if (QLIST_EMPTY(&space->containers)) {
1841         QLIST_REMOVE(space, list);
1842         g_free(space);
1843     }
1844 }
1845 
1846 /*
1847  * vfio_get_iommu_type - selects the richest iommu_type (v2 first)
1848  */
1849 static int vfio_get_iommu_type(VFIOContainer *container,
1850                                Error **errp)
1851 {
1852     int iommu_types[] = { VFIO_TYPE1v2_IOMMU, VFIO_TYPE1_IOMMU,
1853                           VFIO_SPAPR_TCE_v2_IOMMU, VFIO_SPAPR_TCE_IOMMU };
1854     int i;
1855 
1856     for (i = 0; i < ARRAY_SIZE(iommu_types); i++) {
1857         if (ioctl(container->fd, VFIO_CHECK_EXTENSION, iommu_types[i])) {
1858             return iommu_types[i];
1859         }
1860     }
1861     error_setg(errp, "No available IOMMU models");
1862     return -EINVAL;
1863 }
1864 
1865 static int vfio_init_container(VFIOContainer *container, int group_fd,
1866                                Error **errp)
1867 {
1868     int iommu_type, ret;
1869 
1870     iommu_type = vfio_get_iommu_type(container, errp);
1871     if (iommu_type < 0) {
1872         return iommu_type;
1873     }
1874 
1875     ret = ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container->fd);
1876     if (ret) {
1877         error_setg_errno(errp, errno, "Failed to set group container");
1878         return -errno;
1879     }
1880 
1881     while (ioctl(container->fd, VFIO_SET_IOMMU, iommu_type)) {
1882         if (iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
1883             /*
1884              * On sPAPR, despite the IOMMU subdriver always advertises v1 and
1885              * v2, the running platform may not support v2 and there is no
1886              * way to guess it until an IOMMU group gets added to the container.
1887              * So in case it fails with v2, try v1 as a fallback.
1888              */
1889             iommu_type = VFIO_SPAPR_TCE_IOMMU;
1890             continue;
1891         }
1892         error_setg_errno(errp, errno, "Failed to set iommu for container");
1893         return -errno;
1894     }
1895 
1896     container->iommu_type = iommu_type;
1897     return 0;
1898 }
1899 
1900 static int vfio_get_iommu_info(VFIOContainer *container,
1901                                struct vfio_iommu_type1_info **info)
1902 {
1903 
1904     size_t argsz = sizeof(struct vfio_iommu_type1_info);
1905 
1906     *info = g_new0(struct vfio_iommu_type1_info, 1);
1907 again:
1908     (*info)->argsz = argsz;
1909 
1910     if (ioctl(container->fd, VFIO_IOMMU_GET_INFO, *info)) {
1911         g_free(*info);
1912         *info = NULL;
1913         return -errno;
1914     }
1915 
1916     if (((*info)->argsz > argsz)) {
1917         argsz = (*info)->argsz;
1918         *info = g_realloc(*info, argsz);
1919         goto again;
1920     }
1921 
1922     return 0;
1923 }
1924 
1925 static struct vfio_info_cap_header *
1926 vfio_get_iommu_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
1927 {
1928     struct vfio_info_cap_header *hdr;
1929     void *ptr = info;
1930 
1931     if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
1932         return NULL;
1933     }
1934 
1935     for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
1936         if (hdr->id == id) {
1937             return hdr;
1938         }
1939     }
1940 
1941     return NULL;
1942 }
1943 
1944 static void vfio_get_iommu_info_migration(VFIOContainer *container,
1945                                          struct vfio_iommu_type1_info *info)
1946 {
1947     struct vfio_info_cap_header *hdr;
1948     struct vfio_iommu_type1_info_cap_migration *cap_mig;
1949 
1950     hdr = vfio_get_iommu_info_cap(info, VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION);
1951     if (!hdr) {
1952         return;
1953     }
1954 
1955     cap_mig = container_of(hdr, struct vfio_iommu_type1_info_cap_migration,
1956                             header);
1957 
1958     /*
1959      * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
1960      * qemu_real_host_page_size to mark those dirty.
1961      */
1962     if (cap_mig->pgsize_bitmap & qemu_real_host_page_size) {
1963         container->dirty_pages_supported = true;
1964         container->max_dirty_bitmap_size = cap_mig->max_dirty_bitmap_size;
1965         container->dirty_pgsizes = cap_mig->pgsize_bitmap;
1966     }
1967 }
1968 
1969 static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
1970                                   Error **errp)
1971 {
1972     VFIOContainer *container;
1973     int ret, fd;
1974     VFIOAddressSpace *space;
1975 
1976     space = vfio_get_address_space(as);
1977 
1978     /*
1979      * VFIO is currently incompatible with discarding of RAM insofar as the
1980      * madvise to purge (zap) the page from QEMU's address space does not
1981      * interact with the memory API and therefore leaves stale virtual to
1982      * physical mappings in the IOMMU if the page was previously pinned.  We
1983      * therefore set discarding broken for each group added to a container,
1984      * whether the container is used individually or shared.  This provides
1985      * us with options to allow devices within a group to opt-in and allow
1986      * discarding, so long as it is done consistently for a group (for instance
1987      * if the device is an mdev device where it is known that the host vendor
1988      * driver will never pin pages outside of the working set of the guest
1989      * driver, which would thus not be discarding candidates).
1990      *
1991      * The first opportunity to induce pinning occurs here where we attempt to
1992      * attach the group to existing containers within the AddressSpace.  If any
1993      * pages are already zapped from the virtual address space, such as from
1994      * previous discards, new pinning will cause valid mappings to be
1995      * re-established.  Likewise, when the overall MemoryListener for a new
1996      * container is registered, a replay of mappings within the AddressSpace
1997      * will occur, re-establishing any previously zapped pages as well.
1998      *
1999      * Especially virtio-balloon is currently only prevented from discarding
2000      * new memory, it will not yet set ram_block_discard_set_required() and
2001      * therefore, neither stops us here or deals with the sudden memory
2002      * consumption of inflated memory.
2003      *
2004      * We do support discarding of memory coordinated via the RamDiscardManager
2005      * with some IOMMU types. vfio_ram_block_discard_disable() handles the
2006      * details once we know which type of IOMMU we are using.
2007      */
2008 
2009     QLIST_FOREACH(container, &space->containers, next) {
2010         if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
2011             ret = vfio_ram_block_discard_disable(container, true);
2012             if (ret) {
2013                 error_setg_errno(errp, -ret,
2014                                  "Cannot set discarding of RAM broken");
2015                 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER,
2016                           &container->fd)) {
2017                     error_report("vfio: error disconnecting group %d from"
2018                                  " container", group->groupid);
2019                 }
2020                 return ret;
2021             }
2022             group->container = container;
2023             QLIST_INSERT_HEAD(&container->group_list, group, container_next);
2024             vfio_kvm_device_add_group(group);
2025             return 0;
2026         }
2027     }
2028 
2029     fd = qemu_open_old("/dev/vfio/vfio", O_RDWR);
2030     if (fd < 0) {
2031         error_setg_errno(errp, errno, "failed to open /dev/vfio/vfio");
2032         ret = -errno;
2033         goto put_space_exit;
2034     }
2035 
2036     ret = ioctl(fd, VFIO_GET_API_VERSION);
2037     if (ret != VFIO_API_VERSION) {
2038         error_setg(errp, "supported vfio version: %d, "
2039                    "reported version: %d", VFIO_API_VERSION, ret);
2040         ret = -EINVAL;
2041         goto close_fd_exit;
2042     }
2043 
2044     container = g_malloc0(sizeof(*container));
2045     container->space = space;
2046     container->fd = fd;
2047     container->error = NULL;
2048     container->dirty_pages_supported = false;
2049     container->dma_max_mappings = 0;
2050     QLIST_INIT(&container->giommu_list);
2051     QLIST_INIT(&container->hostwin_list);
2052     QLIST_INIT(&container->vrdl_list);
2053 
2054     ret = vfio_init_container(container, group->fd, errp);
2055     if (ret) {
2056         goto free_container_exit;
2057     }
2058 
2059     ret = vfio_ram_block_discard_disable(container, true);
2060     if (ret) {
2061         error_setg_errno(errp, -ret, "Cannot set discarding of RAM broken");
2062         goto free_container_exit;
2063     }
2064 
2065     switch (container->iommu_type) {
2066     case VFIO_TYPE1v2_IOMMU:
2067     case VFIO_TYPE1_IOMMU:
2068     {
2069         struct vfio_iommu_type1_info *info;
2070 
2071         /*
2072          * FIXME: This assumes that a Type1 IOMMU can map any 64-bit
2073          * IOVA whatsoever.  That's not actually true, but the current
2074          * kernel interface doesn't tell us what it can map, and the
2075          * existing Type1 IOMMUs generally support any IOVA we're
2076          * going to actually try in practice.
2077          */
2078         ret = vfio_get_iommu_info(container, &info);
2079 
2080         if (ret || !(info->flags & VFIO_IOMMU_INFO_PGSIZES)) {
2081             /* Assume 4k IOVA page size */
2082             info->iova_pgsizes = 4096;
2083         }
2084         vfio_host_win_add(container, 0, (hwaddr)-1, info->iova_pgsizes);
2085         container->pgsizes = info->iova_pgsizes;
2086 
2087         /* The default in the kernel ("dma_entry_limit") is 65535. */
2088         container->dma_max_mappings = 65535;
2089         if (!ret) {
2090             vfio_get_info_dma_avail(info, &container->dma_max_mappings);
2091             vfio_get_iommu_info_migration(container, info);
2092         }
2093         g_free(info);
2094         break;
2095     }
2096     case VFIO_SPAPR_TCE_v2_IOMMU:
2097     case VFIO_SPAPR_TCE_IOMMU:
2098     {
2099         struct vfio_iommu_spapr_tce_info info;
2100         bool v2 = container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU;
2101 
2102         /*
2103          * The host kernel code implementing VFIO_IOMMU_DISABLE is called
2104          * when container fd is closed so we do not call it explicitly
2105          * in this file.
2106          */
2107         if (!v2) {
2108             ret = ioctl(fd, VFIO_IOMMU_ENABLE);
2109             if (ret) {
2110                 error_setg_errno(errp, errno, "failed to enable container");
2111                 ret = -errno;
2112                 goto enable_discards_exit;
2113             }
2114         } else {
2115             container->prereg_listener = vfio_prereg_listener;
2116 
2117             memory_listener_register(&container->prereg_listener,
2118                                      &address_space_memory);
2119             if (container->error) {
2120                 memory_listener_unregister(&container->prereg_listener);
2121                 ret = -1;
2122                 error_propagate_prepend(errp, container->error,
2123                     "RAM memory listener initialization failed: ");
2124                 goto enable_discards_exit;
2125             }
2126         }
2127 
2128         info.argsz = sizeof(info);
2129         ret = ioctl(fd, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info);
2130         if (ret) {
2131             error_setg_errno(errp, errno,
2132                              "VFIO_IOMMU_SPAPR_TCE_GET_INFO failed");
2133             ret = -errno;
2134             if (v2) {
2135                 memory_listener_unregister(&container->prereg_listener);
2136             }
2137             goto enable_discards_exit;
2138         }
2139 
2140         if (v2) {
2141             container->pgsizes = info.ddw.pgsizes;
2142             /*
2143              * There is a default window in just created container.
2144              * To make region_add/del simpler, we better remove this
2145              * window now and let those iommu_listener callbacks
2146              * create/remove them when needed.
2147              */
2148             ret = vfio_spapr_remove_window(container, info.dma32_window_start);
2149             if (ret) {
2150                 error_setg_errno(errp, -ret,
2151                                  "failed to remove existing window");
2152                 goto enable_discards_exit;
2153             }
2154         } else {
2155             /* The default table uses 4K pages */
2156             container->pgsizes = 0x1000;
2157             vfio_host_win_add(container, info.dma32_window_start,
2158                               info.dma32_window_start +
2159                               info.dma32_window_size - 1,
2160                               0x1000);
2161         }
2162     }
2163     }
2164 
2165     vfio_kvm_device_add_group(group);
2166 
2167     QLIST_INIT(&container->group_list);
2168     QLIST_INSERT_HEAD(&space->containers, container, next);
2169 
2170     group->container = container;
2171     QLIST_INSERT_HEAD(&container->group_list, group, container_next);
2172 
2173     container->listener = vfio_memory_listener;
2174 
2175     memory_listener_register(&container->listener, container->space->as);
2176 
2177     if (container->error) {
2178         ret = -1;
2179         error_propagate_prepend(errp, container->error,
2180             "memory listener initialization failed: ");
2181         goto listener_release_exit;
2182     }
2183 
2184     container->initialized = true;
2185 
2186     return 0;
2187 listener_release_exit:
2188     QLIST_REMOVE(group, container_next);
2189     QLIST_REMOVE(container, next);
2190     vfio_kvm_device_del_group(group);
2191     vfio_listener_release(container);
2192 
2193 enable_discards_exit:
2194     vfio_ram_block_discard_disable(container, false);
2195 
2196 free_container_exit:
2197     g_free(container);
2198 
2199 close_fd_exit:
2200     close(fd);
2201 
2202 put_space_exit:
2203     vfio_put_address_space(space);
2204 
2205     return ret;
2206 }
2207 
2208 static void vfio_disconnect_container(VFIOGroup *group)
2209 {
2210     VFIOContainer *container = group->container;
2211 
2212     QLIST_REMOVE(group, container_next);
2213     group->container = NULL;
2214 
2215     /*
2216      * Explicitly release the listener first before unset container,
2217      * since unset may destroy the backend container if it's the last
2218      * group.
2219      */
2220     if (QLIST_EMPTY(&container->group_list)) {
2221         vfio_listener_release(container);
2222     }
2223 
2224     if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
2225         error_report("vfio: error disconnecting group %d from container",
2226                      group->groupid);
2227     }
2228 
2229     if (QLIST_EMPTY(&container->group_list)) {
2230         VFIOAddressSpace *space = container->space;
2231         VFIOGuestIOMMU *giommu, *tmp;
2232 
2233         QLIST_REMOVE(container, next);
2234 
2235         QLIST_FOREACH_SAFE(giommu, &container->giommu_list, giommu_next, tmp) {
2236             memory_region_unregister_iommu_notifier(
2237                     MEMORY_REGION(giommu->iommu), &giommu->n);
2238             QLIST_REMOVE(giommu, giommu_next);
2239             g_free(giommu);
2240         }
2241 
2242         trace_vfio_disconnect_container(container->fd);
2243         close(container->fd);
2244         g_free(container);
2245 
2246         vfio_put_address_space(space);
2247     }
2248 }
2249 
2250 VFIOGroup *vfio_get_group(int groupid, AddressSpace *as, Error **errp)
2251 {
2252     VFIOGroup *group;
2253     char path[32];
2254     struct vfio_group_status status = { .argsz = sizeof(status) };
2255 
2256     QLIST_FOREACH(group, &vfio_group_list, next) {
2257         if (group->groupid == groupid) {
2258             /* Found it.  Now is it already in the right context? */
2259             if (group->container->space->as == as) {
2260                 return group;
2261             } else {
2262                 error_setg(errp, "group %d used in multiple address spaces",
2263                            group->groupid);
2264                 return NULL;
2265             }
2266         }
2267     }
2268 
2269     group = g_malloc0(sizeof(*group));
2270 
2271     snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
2272     group->fd = qemu_open_old(path, O_RDWR);
2273     if (group->fd < 0) {
2274         error_setg_errno(errp, errno, "failed to open %s", path);
2275         goto free_group_exit;
2276     }
2277 
2278     if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
2279         error_setg_errno(errp, errno, "failed to get group %d status", groupid);
2280         goto close_fd_exit;
2281     }
2282 
2283     if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
2284         error_setg(errp, "group %d is not viable", groupid);
2285         error_append_hint(errp,
2286                           "Please ensure all devices within the iommu_group "
2287                           "are bound to their vfio bus driver.\n");
2288         goto close_fd_exit;
2289     }
2290 
2291     group->groupid = groupid;
2292     QLIST_INIT(&group->device_list);
2293 
2294     if (vfio_connect_container(group, as, errp)) {
2295         error_prepend(errp, "failed to setup container for group %d: ",
2296                       groupid);
2297         goto close_fd_exit;
2298     }
2299 
2300     if (QLIST_EMPTY(&vfio_group_list)) {
2301         qemu_register_reset(vfio_reset_handler, NULL);
2302     }
2303 
2304     QLIST_INSERT_HEAD(&vfio_group_list, group, next);
2305 
2306     return group;
2307 
2308 close_fd_exit:
2309     close(group->fd);
2310 
2311 free_group_exit:
2312     g_free(group);
2313 
2314     return NULL;
2315 }
2316 
2317 void vfio_put_group(VFIOGroup *group)
2318 {
2319     if (!group || !QLIST_EMPTY(&group->device_list)) {
2320         return;
2321     }
2322 
2323     if (!group->ram_block_discard_allowed) {
2324         vfio_ram_block_discard_disable(group->container, false);
2325     }
2326     vfio_kvm_device_del_group(group);
2327     vfio_disconnect_container(group);
2328     QLIST_REMOVE(group, next);
2329     trace_vfio_put_group(group->fd);
2330     close(group->fd);
2331     g_free(group);
2332 
2333     if (QLIST_EMPTY(&vfio_group_list)) {
2334         qemu_unregister_reset(vfio_reset_handler, NULL);
2335     }
2336 }
2337 
2338 int vfio_get_device(VFIOGroup *group, const char *name,
2339                     VFIODevice *vbasedev, Error **errp)
2340 {
2341     struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
2342     int ret, fd;
2343 
2344     fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
2345     if (fd < 0) {
2346         error_setg_errno(errp, errno, "error getting device from group %d",
2347                          group->groupid);
2348         error_append_hint(errp,
2349                       "Verify all devices in group %d are bound to vfio-<bus> "
2350                       "or pci-stub and not already in use\n", group->groupid);
2351         return fd;
2352     }
2353 
2354     ret = ioctl(fd, VFIO_DEVICE_GET_INFO, &dev_info);
2355     if (ret) {
2356         error_setg_errno(errp, errno, "error getting device info");
2357         close(fd);
2358         return ret;
2359     }
2360 
2361     /*
2362      * Set discarding of RAM as not broken for this group if the driver knows
2363      * the device operates compatibly with discarding.  Setting must be
2364      * consistent per group, but since compatibility is really only possible
2365      * with mdev currently, we expect singleton groups.
2366      */
2367     if (vbasedev->ram_block_discard_allowed !=
2368         group->ram_block_discard_allowed) {
2369         if (!QLIST_EMPTY(&group->device_list)) {
2370             error_setg(errp, "Inconsistent setting of support for discarding "
2371                        "RAM (e.g., balloon) within group");
2372             close(fd);
2373             return -1;
2374         }
2375 
2376         if (!group->ram_block_discard_allowed) {
2377             group->ram_block_discard_allowed = true;
2378             vfio_ram_block_discard_disable(group->container, false);
2379         }
2380     }
2381 
2382     vbasedev->fd = fd;
2383     vbasedev->group = group;
2384     QLIST_INSERT_HEAD(&group->device_list, vbasedev, next);
2385 
2386     vbasedev->num_irqs = dev_info.num_irqs;
2387     vbasedev->num_regions = dev_info.num_regions;
2388     vbasedev->flags = dev_info.flags;
2389 
2390     trace_vfio_get_device(name, dev_info.flags, dev_info.num_regions,
2391                           dev_info.num_irqs);
2392 
2393     vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
2394     return 0;
2395 }
2396 
2397 void vfio_put_base_device(VFIODevice *vbasedev)
2398 {
2399     if (!vbasedev->group) {
2400         return;
2401     }
2402     QLIST_REMOVE(vbasedev, next);
2403     vbasedev->group = NULL;
2404     trace_vfio_put_base_device(vbasedev->fd);
2405     close(vbasedev->fd);
2406 }
2407 
2408 int vfio_get_region_info(VFIODevice *vbasedev, int index,
2409                          struct vfio_region_info **info)
2410 {
2411     size_t argsz = sizeof(struct vfio_region_info);
2412 
2413     *info = g_malloc0(argsz);
2414 
2415     (*info)->index = index;
2416 retry:
2417     (*info)->argsz = argsz;
2418 
2419     if (ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, *info)) {
2420         g_free(*info);
2421         *info = NULL;
2422         return -errno;
2423     }
2424 
2425     if ((*info)->argsz > argsz) {
2426         argsz = (*info)->argsz;
2427         *info = g_realloc(*info, argsz);
2428 
2429         goto retry;
2430     }
2431 
2432     return 0;
2433 }
2434 
2435 int vfio_get_dev_region_info(VFIODevice *vbasedev, uint32_t type,
2436                              uint32_t subtype, struct vfio_region_info **info)
2437 {
2438     int i;
2439 
2440     for (i = 0; i < vbasedev->num_regions; i++) {
2441         struct vfio_info_cap_header *hdr;
2442         struct vfio_region_info_cap_type *cap_type;
2443 
2444         if (vfio_get_region_info(vbasedev, i, info)) {
2445             continue;
2446         }
2447 
2448         hdr = vfio_get_region_info_cap(*info, VFIO_REGION_INFO_CAP_TYPE);
2449         if (!hdr) {
2450             g_free(*info);
2451             continue;
2452         }
2453 
2454         cap_type = container_of(hdr, struct vfio_region_info_cap_type, header);
2455 
2456         trace_vfio_get_dev_region(vbasedev->name, i,
2457                                   cap_type->type, cap_type->subtype);
2458 
2459         if (cap_type->type == type && cap_type->subtype == subtype) {
2460             return 0;
2461         }
2462 
2463         g_free(*info);
2464     }
2465 
2466     *info = NULL;
2467     return -ENODEV;
2468 }
2469 
2470 bool vfio_has_region_cap(VFIODevice *vbasedev, int region, uint16_t cap_type)
2471 {
2472     struct vfio_region_info *info = NULL;
2473     bool ret = false;
2474 
2475     if (!vfio_get_region_info(vbasedev, region, &info)) {
2476         if (vfio_get_region_info_cap(info, cap_type)) {
2477             ret = true;
2478         }
2479         g_free(info);
2480     }
2481 
2482     return ret;
2483 }
2484 
2485 /*
2486  * Interfaces for IBM EEH (Enhanced Error Handling)
2487  */
2488 static bool vfio_eeh_container_ok(VFIOContainer *container)
2489 {
2490     /*
2491      * As of 2016-03-04 (linux-4.5) the host kernel EEH/VFIO
2492      * implementation is broken if there are multiple groups in a
2493      * container.  The hardware works in units of Partitionable
2494      * Endpoints (== IOMMU groups) and the EEH operations naively
2495      * iterate across all groups in the container, without any logic
2496      * to make sure the groups have their state synchronized.  For
2497      * certain operations (ENABLE) that might be ok, until an error
2498      * occurs, but for others (GET_STATE) it's clearly broken.
2499      */
2500 
2501     /*
2502      * XXX Once fixed kernels exist, test for them here
2503      */
2504 
2505     if (QLIST_EMPTY(&container->group_list)) {
2506         return false;
2507     }
2508 
2509     if (QLIST_NEXT(QLIST_FIRST(&container->group_list), container_next)) {
2510         return false;
2511     }
2512 
2513     return true;
2514 }
2515 
2516 static int vfio_eeh_container_op(VFIOContainer *container, uint32_t op)
2517 {
2518     struct vfio_eeh_pe_op pe_op = {
2519         .argsz = sizeof(pe_op),
2520         .op = op,
2521     };
2522     int ret;
2523 
2524     if (!vfio_eeh_container_ok(container)) {
2525         error_report("vfio/eeh: EEH_PE_OP 0x%x: "
2526                      "kernel requires a container with exactly one group", op);
2527         return -EPERM;
2528     }
2529 
2530     ret = ioctl(container->fd, VFIO_EEH_PE_OP, &pe_op);
2531     if (ret < 0) {
2532         error_report("vfio/eeh: EEH_PE_OP 0x%x failed: %m", op);
2533         return -errno;
2534     }
2535 
2536     return ret;
2537 }
2538 
2539 static VFIOContainer *vfio_eeh_as_container(AddressSpace *as)
2540 {
2541     VFIOAddressSpace *space = vfio_get_address_space(as);
2542     VFIOContainer *container = NULL;
2543 
2544     if (QLIST_EMPTY(&space->containers)) {
2545         /* No containers to act on */
2546         goto out;
2547     }
2548 
2549     container = QLIST_FIRST(&space->containers);
2550 
2551     if (QLIST_NEXT(container, next)) {
2552         /* We don't yet have logic to synchronize EEH state across
2553          * multiple containers */
2554         container = NULL;
2555         goto out;
2556     }
2557 
2558 out:
2559     vfio_put_address_space(space);
2560     return container;
2561 }
2562 
2563 bool vfio_eeh_as_ok(AddressSpace *as)
2564 {
2565     VFIOContainer *container = vfio_eeh_as_container(as);
2566 
2567     return (container != NULL) && vfio_eeh_container_ok(container);
2568 }
2569 
2570 int vfio_eeh_as_op(AddressSpace *as, uint32_t op)
2571 {
2572     VFIOContainer *container = vfio_eeh_as_container(as);
2573 
2574     if (!container) {
2575         return -ENODEV;
2576     }
2577     return vfio_eeh_container_op(container, op);
2578 }
2579