xref: /openbmc/qemu/hw/vfio/common.c (revision 259ebed4)
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 "hw/vfio/pci.h"
31 #include "exec/address-spaces.h"
32 #include "exec/memory.h"
33 #include "exec/ram_addr.h"
34 #include "hw/hw.h"
35 #include "qemu/error-report.h"
36 #include "qemu/main-loop.h"
37 #include "qemu/range.h"
38 #include "sysemu/kvm.h"
39 #include "sysemu/reset.h"
40 #include "sysemu/runstate.h"
41 #include "trace.h"
42 #include "qapi/error.h"
43 #include "migration/migration.h"
44 #include "migration/misc.h"
45 #include "migration/blocker.h"
46 #include "migration/qemu-file.h"
47 #include "sysemu/tpm.h"
48 
49 VFIODeviceList vfio_device_list =
50     QLIST_HEAD_INITIALIZER(vfio_device_list);
51 static QLIST_HEAD(, VFIOAddressSpace) vfio_address_spaces =
52     QLIST_HEAD_INITIALIZER(vfio_address_spaces);
53 
54 #ifdef CONFIG_KVM
55 /*
56  * We have a single VFIO pseudo device per KVM VM.  Once created it lives
57  * for the life of the VM.  Closing the file descriptor only drops our
58  * reference to it and the device's reference to kvm.  Therefore once
59  * initialized, this file descriptor is only released on QEMU exit and
60  * we'll re-use it should another vfio device be attached before then.
61  */
62 int vfio_kvm_device_fd = -1;
63 #endif
64 
65 /*
66  * Device state interfaces
67  */
68 
69 bool vfio_mig_active(void)
70 {
71     VFIODevice *vbasedev;
72 
73     if (QLIST_EMPTY(&vfio_device_list)) {
74         return false;
75     }
76 
77     QLIST_FOREACH(vbasedev, &vfio_device_list, next) {
78         if (vbasedev->migration_blocker) {
79             return false;
80         }
81     }
82     return true;
83 }
84 
85 static Error *multiple_devices_migration_blocker;
86 
87 /*
88  * Multiple devices migration is allowed only if all devices support P2P
89  * migration. Single device migration is allowed regardless of P2P migration
90  * support.
91  */
92 static bool vfio_multiple_devices_migration_is_supported(void)
93 {
94     VFIODevice *vbasedev;
95     unsigned int device_num = 0;
96     bool all_support_p2p = true;
97 
98     QLIST_FOREACH(vbasedev, &vfio_device_list, next) {
99         if (vbasedev->migration) {
100             device_num++;
101 
102             if (!(vbasedev->migration->mig_flags & VFIO_MIGRATION_P2P)) {
103                 all_support_p2p = false;
104             }
105         }
106     }
107 
108     return all_support_p2p || device_num <= 1;
109 }
110 
111 int vfio_block_multiple_devices_migration(VFIODevice *vbasedev, Error **errp)
112 {
113     int ret;
114 
115     if (vfio_multiple_devices_migration_is_supported()) {
116         return 0;
117     }
118 
119     if (vbasedev->enable_migration == ON_OFF_AUTO_ON) {
120         error_setg(errp, "Multiple VFIO devices migration is supported only if "
121                          "all of them support P2P migration");
122         return -EINVAL;
123     }
124 
125     if (multiple_devices_migration_blocker) {
126         return 0;
127     }
128 
129     error_setg(&multiple_devices_migration_blocker,
130                "Multiple VFIO devices migration is supported only if all of "
131                "them support P2P migration");
132     ret = migrate_add_blocker(&multiple_devices_migration_blocker, errp);
133 
134     return ret;
135 }
136 
137 void vfio_unblock_multiple_devices_migration(void)
138 {
139     if (!multiple_devices_migration_blocker ||
140         !vfio_multiple_devices_migration_is_supported()) {
141         return;
142     }
143 
144     migrate_del_blocker(&multiple_devices_migration_blocker);
145 }
146 
147 bool vfio_viommu_preset(VFIODevice *vbasedev)
148 {
149     return vbasedev->container->space->as != &address_space_memory;
150 }
151 
152 static void vfio_set_migration_error(int err)
153 {
154     MigrationState *ms = migrate_get_current();
155 
156     if (migration_is_setup_or_active(ms->state)) {
157         WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
158             if (ms->to_dst_file) {
159                 qemu_file_set_error(ms->to_dst_file, err);
160             }
161         }
162     }
163 }
164 
165 bool vfio_device_state_is_running(VFIODevice *vbasedev)
166 {
167     VFIOMigration *migration = vbasedev->migration;
168 
169     return migration->device_state == VFIO_DEVICE_STATE_RUNNING ||
170            migration->device_state == VFIO_DEVICE_STATE_RUNNING_P2P;
171 }
172 
173 bool vfio_device_state_is_precopy(VFIODevice *vbasedev)
174 {
175     VFIOMigration *migration = vbasedev->migration;
176 
177     return migration->device_state == VFIO_DEVICE_STATE_PRE_COPY ||
178            migration->device_state == VFIO_DEVICE_STATE_PRE_COPY_P2P;
179 }
180 
181 static bool vfio_devices_all_dirty_tracking(VFIOContainer *container)
182 {
183     VFIODevice *vbasedev;
184     MigrationState *ms = migrate_get_current();
185 
186     if (ms->state != MIGRATION_STATUS_ACTIVE &&
187         ms->state != MIGRATION_STATUS_DEVICE) {
188         return false;
189     }
190 
191     QLIST_FOREACH(vbasedev, &container->device_list, container_next) {
192         VFIOMigration *migration = vbasedev->migration;
193 
194         if (!migration) {
195             return false;
196         }
197 
198         if (vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF &&
199             (vfio_device_state_is_running(vbasedev) ||
200              vfio_device_state_is_precopy(vbasedev))) {
201             return false;
202         }
203     }
204     return true;
205 }
206 
207 bool vfio_devices_all_device_dirty_tracking(VFIOContainer *container)
208 {
209     VFIODevice *vbasedev;
210 
211     QLIST_FOREACH(vbasedev, &container->device_list, container_next) {
212         if (!vbasedev->dirty_pages_supported) {
213             return false;
214         }
215     }
216 
217     return true;
218 }
219 
220 /*
221  * Check if all VFIO devices are running and migration is active, which is
222  * essentially equivalent to the migration being in pre-copy phase.
223  */
224 bool vfio_devices_all_running_and_mig_active(VFIOContainer *container)
225 {
226     VFIODevice *vbasedev;
227 
228     if (!migration_is_active(migrate_get_current())) {
229         return false;
230     }
231 
232     QLIST_FOREACH(vbasedev, &container->device_list, container_next) {
233         VFIOMigration *migration = vbasedev->migration;
234 
235         if (!migration) {
236             return false;
237         }
238 
239         if (vfio_device_state_is_running(vbasedev) ||
240             vfio_device_state_is_precopy(vbasedev)) {
241             continue;
242         } else {
243             return false;
244         }
245     }
246     return true;
247 }
248 
249 void vfio_host_win_add(VFIOContainer *container, hwaddr min_iova,
250                        hwaddr max_iova, uint64_t iova_pgsizes)
251 {
252     VFIOHostDMAWindow *hostwin;
253 
254     QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
255         if (ranges_overlap(hostwin->min_iova,
256                            hostwin->max_iova - hostwin->min_iova + 1,
257                            min_iova,
258                            max_iova - min_iova + 1)) {
259             hw_error("%s: Overlapped IOMMU are not enabled", __func__);
260         }
261     }
262 
263     hostwin = g_malloc0(sizeof(*hostwin));
264 
265     hostwin->min_iova = min_iova;
266     hostwin->max_iova = max_iova;
267     hostwin->iova_pgsizes = iova_pgsizes;
268     QLIST_INSERT_HEAD(&container->hostwin_list, hostwin, hostwin_next);
269 }
270 
271 int vfio_host_win_del(VFIOContainer *container,
272                       hwaddr min_iova, hwaddr max_iova)
273 {
274     VFIOHostDMAWindow *hostwin;
275 
276     QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
277         if (hostwin->min_iova == min_iova && hostwin->max_iova == max_iova) {
278             QLIST_REMOVE(hostwin, hostwin_next);
279             g_free(hostwin);
280             return 0;
281         }
282     }
283 
284     return -1;
285 }
286 
287 static bool vfio_listener_skipped_section(MemoryRegionSection *section)
288 {
289     return (!memory_region_is_ram(section->mr) &&
290             !memory_region_is_iommu(section->mr)) ||
291            memory_region_is_protected(section->mr) ||
292            /*
293             * Sizing an enabled 64-bit BAR can cause spurious mappings to
294             * addresses in the upper part of the 64-bit address space.  These
295             * are never accessed by the CPU and beyond the address width of
296             * some IOMMU hardware.  TODO: VFIO should tell us the IOMMU width.
297             */
298            section->offset_within_address_space & (1ULL << 63);
299 }
300 
301 /* Called with rcu_read_lock held.  */
302 static bool vfio_get_xlat_addr(IOMMUTLBEntry *iotlb, void **vaddr,
303                                ram_addr_t *ram_addr, bool *read_only)
304 {
305     bool ret, mr_has_discard_manager;
306 
307     ret = memory_get_xlat_addr(iotlb, vaddr, ram_addr, read_only,
308                                &mr_has_discard_manager);
309     if (ret && mr_has_discard_manager) {
310         /*
311          * Malicious VMs might trigger discarding of IOMMU-mapped memory. The
312          * pages will remain pinned inside vfio until unmapped, resulting in a
313          * higher memory consumption than expected. If memory would get
314          * populated again later, there would be an inconsistency between pages
315          * pinned by vfio and pages seen by QEMU. This is the case until
316          * unmapped from the IOMMU (e.g., during device reset).
317          *
318          * With malicious guests, we really only care about pinning more memory
319          * than expected. RLIMIT_MEMLOCK set for the user/process can never be
320          * exceeded and can be used to mitigate this problem.
321          */
322         warn_report_once("Using vfio with vIOMMUs and coordinated discarding of"
323                          " RAM (e.g., virtio-mem) works, however, malicious"
324                          " guests can trigger pinning of more memory than"
325                          " intended via an IOMMU. It's possible to mitigate "
326                          " by setting/adjusting RLIMIT_MEMLOCK.");
327     }
328     return ret;
329 }
330 
331 static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
332 {
333     VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
334     VFIOContainer *container = giommu->container;
335     hwaddr iova = iotlb->iova + giommu->iommu_offset;
336     void *vaddr;
337     int ret;
338 
339     trace_vfio_iommu_map_notify(iotlb->perm == IOMMU_NONE ? "UNMAP" : "MAP",
340                                 iova, iova + iotlb->addr_mask);
341 
342     if (iotlb->target_as != &address_space_memory) {
343         error_report("Wrong target AS \"%s\", only system memory is allowed",
344                      iotlb->target_as->name ? iotlb->target_as->name : "none");
345         vfio_set_migration_error(-EINVAL);
346         return;
347     }
348 
349     rcu_read_lock();
350 
351     if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {
352         bool read_only;
353 
354         if (!vfio_get_xlat_addr(iotlb, &vaddr, NULL, &read_only)) {
355             goto out;
356         }
357         /*
358          * vaddr is only valid until rcu_read_unlock(). But after
359          * vfio_dma_map has set up the mapping the pages will be
360          * pinned by the kernel. This makes sure that the RAM backend
361          * of vaddr will always be there, even if the memory object is
362          * destroyed and its backing memory munmap-ed.
363          */
364         ret = vfio_dma_map(container, iova,
365                            iotlb->addr_mask + 1, vaddr,
366                            read_only);
367         if (ret) {
368             error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
369                          "0x%"HWADDR_PRIx", %p) = %d (%s)",
370                          container, iova,
371                          iotlb->addr_mask + 1, vaddr, ret, strerror(-ret));
372         }
373     } else {
374         ret = vfio_dma_unmap(container, iova, iotlb->addr_mask + 1, iotlb);
375         if (ret) {
376             error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
377                          "0x%"HWADDR_PRIx") = %d (%s)",
378                          container, iova,
379                          iotlb->addr_mask + 1, ret, strerror(-ret));
380             vfio_set_migration_error(ret);
381         }
382     }
383 out:
384     rcu_read_unlock();
385 }
386 
387 static void vfio_ram_discard_notify_discard(RamDiscardListener *rdl,
388                                             MemoryRegionSection *section)
389 {
390     VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
391                                                 listener);
392     const hwaddr size = int128_get64(section->size);
393     const hwaddr iova = section->offset_within_address_space;
394     int ret;
395 
396     /* Unmap with a single call. */
397     ret = vfio_dma_unmap(vrdl->container, iova, size , NULL);
398     if (ret) {
399         error_report("%s: vfio_dma_unmap() failed: %s", __func__,
400                      strerror(-ret));
401     }
402 }
403 
404 static int vfio_ram_discard_notify_populate(RamDiscardListener *rdl,
405                                             MemoryRegionSection *section)
406 {
407     VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
408                                                 listener);
409     const hwaddr end = section->offset_within_region +
410                        int128_get64(section->size);
411     hwaddr start, next, iova;
412     void *vaddr;
413     int ret;
414 
415     /*
416      * Map in (aligned within memory region) minimum granularity, so we can
417      * unmap in minimum granularity later.
418      */
419     for (start = section->offset_within_region; start < end; start = next) {
420         next = ROUND_UP(start + 1, vrdl->granularity);
421         next = MIN(next, end);
422 
423         iova = start - section->offset_within_region +
424                section->offset_within_address_space;
425         vaddr = memory_region_get_ram_ptr(section->mr) + start;
426 
427         ret = vfio_dma_map(vrdl->container, iova, next - start,
428                            vaddr, section->readonly);
429         if (ret) {
430             /* Rollback */
431             vfio_ram_discard_notify_discard(rdl, section);
432             return ret;
433         }
434     }
435     return 0;
436 }
437 
438 static void vfio_register_ram_discard_listener(VFIOContainer *container,
439                                                MemoryRegionSection *section)
440 {
441     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
442     VFIORamDiscardListener *vrdl;
443 
444     /* Ignore some corner cases not relevant in practice. */
445     g_assert(QEMU_IS_ALIGNED(section->offset_within_region, TARGET_PAGE_SIZE));
446     g_assert(QEMU_IS_ALIGNED(section->offset_within_address_space,
447                              TARGET_PAGE_SIZE));
448     g_assert(QEMU_IS_ALIGNED(int128_get64(section->size), TARGET_PAGE_SIZE));
449 
450     vrdl = g_new0(VFIORamDiscardListener, 1);
451     vrdl->container = container;
452     vrdl->mr = section->mr;
453     vrdl->offset_within_address_space = section->offset_within_address_space;
454     vrdl->size = int128_get64(section->size);
455     vrdl->granularity = ram_discard_manager_get_min_granularity(rdm,
456                                                                 section->mr);
457 
458     g_assert(vrdl->granularity && is_power_of_2(vrdl->granularity));
459     g_assert(container->pgsizes &&
460              vrdl->granularity >= 1ULL << ctz64(container->pgsizes));
461 
462     ram_discard_listener_init(&vrdl->listener,
463                               vfio_ram_discard_notify_populate,
464                               vfio_ram_discard_notify_discard, true);
465     ram_discard_manager_register_listener(rdm, &vrdl->listener, section);
466     QLIST_INSERT_HEAD(&container->vrdl_list, vrdl, next);
467 
468     /*
469      * Sanity-check if we have a theoretically problematic setup where we could
470      * exceed the maximum number of possible DMA mappings over time. We assume
471      * that each mapped section in the same address space as a RamDiscardManager
472      * section consumes exactly one DMA mapping, with the exception of
473      * RamDiscardManager sections; i.e., we don't expect to have gIOMMU sections
474      * in the same address space as RamDiscardManager sections.
475      *
476      * We assume that each section in the address space consumes one memslot.
477      * We take the number of KVM memory slots as a best guess for the maximum
478      * number of sections in the address space we could have over time,
479      * also consuming DMA mappings.
480      */
481     if (container->dma_max_mappings) {
482         unsigned int vrdl_count = 0, vrdl_mappings = 0, max_memslots = 512;
483 
484 #ifdef CONFIG_KVM
485         if (kvm_enabled()) {
486             max_memslots = kvm_get_max_memslots();
487         }
488 #endif
489 
490         QLIST_FOREACH(vrdl, &container->vrdl_list, next) {
491             hwaddr start, end;
492 
493             start = QEMU_ALIGN_DOWN(vrdl->offset_within_address_space,
494                                     vrdl->granularity);
495             end = ROUND_UP(vrdl->offset_within_address_space + vrdl->size,
496                            vrdl->granularity);
497             vrdl_mappings += (end - start) / vrdl->granularity;
498             vrdl_count++;
499         }
500 
501         if (vrdl_mappings + max_memslots - vrdl_count >
502             container->dma_max_mappings) {
503             warn_report("%s: possibly running out of DMA mappings. E.g., try"
504                         " increasing the 'block-size' of virtio-mem devies."
505                         " Maximum possible DMA mappings: %d, Maximum possible"
506                         " memslots: %d", __func__, container->dma_max_mappings,
507                         max_memslots);
508         }
509     }
510 }
511 
512 static void vfio_unregister_ram_discard_listener(VFIOContainer *container,
513                                                  MemoryRegionSection *section)
514 {
515     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
516     VFIORamDiscardListener *vrdl = NULL;
517 
518     QLIST_FOREACH(vrdl, &container->vrdl_list, next) {
519         if (vrdl->mr == section->mr &&
520             vrdl->offset_within_address_space ==
521             section->offset_within_address_space) {
522             break;
523         }
524     }
525 
526     if (!vrdl) {
527         hw_error("vfio: Trying to unregister missing RAM discard listener");
528     }
529 
530     ram_discard_manager_unregister_listener(rdm, &vrdl->listener);
531     QLIST_REMOVE(vrdl, next);
532     g_free(vrdl);
533 }
534 
535 static VFIOHostDMAWindow *vfio_find_hostwin(VFIOContainer *container,
536                                             hwaddr iova, hwaddr end)
537 {
538     VFIOHostDMAWindow *hostwin;
539     bool hostwin_found = false;
540 
541     QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
542         if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
543             hostwin_found = true;
544             break;
545         }
546     }
547 
548     return hostwin_found ? hostwin : NULL;
549 }
550 
551 static bool vfio_known_safe_misalignment(MemoryRegionSection *section)
552 {
553     MemoryRegion *mr = section->mr;
554 
555     if (!TPM_IS_CRB(mr->owner)) {
556         return false;
557     }
558 
559     /* this is a known safe misaligned region, just trace for debug purpose */
560     trace_vfio_known_safe_misalignment(memory_region_name(mr),
561                                        section->offset_within_address_space,
562                                        section->offset_within_region,
563                                        qemu_real_host_page_size());
564     return true;
565 }
566 
567 static bool vfio_listener_valid_section(MemoryRegionSection *section,
568                                         const char *name)
569 {
570     if (vfio_listener_skipped_section(section)) {
571         trace_vfio_listener_region_skip(name,
572                 section->offset_within_address_space,
573                 section->offset_within_address_space +
574                 int128_get64(int128_sub(section->size, int128_one())));
575         return false;
576     }
577 
578     if (unlikely((section->offset_within_address_space &
579                   ~qemu_real_host_page_mask()) !=
580                  (section->offset_within_region & ~qemu_real_host_page_mask()))) {
581         if (!vfio_known_safe_misalignment(section)) {
582             error_report("%s received unaligned region %s iova=0x%"PRIx64
583                          " offset_within_region=0x%"PRIx64
584                          " qemu_real_host_page_size=0x%"PRIxPTR,
585                          __func__, memory_region_name(section->mr),
586                          section->offset_within_address_space,
587                          section->offset_within_region,
588                          qemu_real_host_page_size());
589         }
590         return false;
591     }
592 
593     return true;
594 }
595 
596 static bool vfio_get_section_iova_range(VFIOContainer *container,
597                                         MemoryRegionSection *section,
598                                         hwaddr *out_iova, hwaddr *out_end,
599                                         Int128 *out_llend)
600 {
601     Int128 llend;
602     hwaddr iova;
603 
604     iova = REAL_HOST_PAGE_ALIGN(section->offset_within_address_space);
605     llend = int128_make64(section->offset_within_address_space);
606     llend = int128_add(llend, section->size);
607     llend = int128_and(llend, int128_exts64(qemu_real_host_page_mask()));
608 
609     if (int128_ge(int128_make64(iova), llend)) {
610         return false;
611     }
612 
613     *out_iova = iova;
614     *out_end = int128_get64(int128_sub(llend, int128_one()));
615     if (out_llend) {
616         *out_llend = llend;
617     }
618     return true;
619 }
620 
621 static void vfio_listener_region_add(MemoryListener *listener,
622                                      MemoryRegionSection *section)
623 {
624     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
625     hwaddr iova, end;
626     Int128 llend, llsize;
627     void *vaddr;
628     int ret;
629     VFIOHostDMAWindow *hostwin;
630     Error *err = NULL;
631 
632     if (!vfio_listener_valid_section(section, "region_add")) {
633         return;
634     }
635 
636     if (!vfio_get_section_iova_range(container, section, &iova, &end, &llend)) {
637         if (memory_region_is_ram_device(section->mr)) {
638             trace_vfio_listener_region_add_no_dma_map(
639                 memory_region_name(section->mr),
640                 section->offset_within_address_space,
641                 int128_getlo(section->size),
642                 qemu_real_host_page_size());
643         }
644         return;
645     }
646 
647     if (vfio_container_add_section_window(container, section, &err)) {
648         goto fail;
649     }
650 
651     hostwin = vfio_find_hostwin(container, iova, end);
652     if (!hostwin) {
653         error_setg(&err, "Container %p can't map guest IOVA region"
654                    " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx, container, iova, end);
655         goto fail;
656     }
657 
658     memory_region_ref(section->mr);
659 
660     if (memory_region_is_iommu(section->mr)) {
661         VFIOGuestIOMMU *giommu;
662         IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
663         int iommu_idx;
664 
665         trace_vfio_listener_region_add_iommu(iova, end);
666         /*
667          * FIXME: For VFIO iommu types which have KVM acceleration to
668          * avoid bouncing all map/unmaps through qemu this way, this
669          * would be the right place to wire that up (tell the KVM
670          * device emulation the VFIO iommu handles to use).
671          */
672         giommu = g_malloc0(sizeof(*giommu));
673         giommu->iommu_mr = iommu_mr;
674         giommu->iommu_offset = section->offset_within_address_space -
675                                section->offset_within_region;
676         giommu->container = container;
677         llend = int128_add(int128_make64(section->offset_within_region),
678                            section->size);
679         llend = int128_sub(llend, int128_one());
680         iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
681                                                        MEMTXATTRS_UNSPECIFIED);
682         iommu_notifier_init(&giommu->n, vfio_iommu_map_notify,
683                             IOMMU_NOTIFIER_IOTLB_EVENTS,
684                             section->offset_within_region,
685                             int128_get64(llend),
686                             iommu_idx);
687 
688         ret = memory_region_iommu_set_page_size_mask(giommu->iommu_mr,
689                                                      container->pgsizes,
690                                                      &err);
691         if (ret) {
692             g_free(giommu);
693             goto fail;
694         }
695 
696         ret = memory_region_register_iommu_notifier(section->mr, &giommu->n,
697                                                     &err);
698         if (ret) {
699             g_free(giommu);
700             goto fail;
701         }
702         QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
703         memory_region_iommu_replay(giommu->iommu_mr, &giommu->n);
704 
705         return;
706     }
707 
708     /* Here we assume that memory_region_is_ram(section->mr)==true */
709 
710     /*
711      * For RAM memory regions with a RamDiscardManager, we only want to map the
712      * actually populated parts - and update the mapping whenever we're notified
713      * about changes.
714      */
715     if (memory_region_has_ram_discard_manager(section->mr)) {
716         vfio_register_ram_discard_listener(container, section);
717         return;
718     }
719 
720     vaddr = memory_region_get_ram_ptr(section->mr) +
721             section->offset_within_region +
722             (iova - section->offset_within_address_space);
723 
724     trace_vfio_listener_region_add_ram(iova, end, vaddr);
725 
726     llsize = int128_sub(llend, int128_make64(iova));
727 
728     if (memory_region_is_ram_device(section->mr)) {
729         hwaddr pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
730 
731         if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) {
732             trace_vfio_listener_region_add_no_dma_map(
733                 memory_region_name(section->mr),
734                 section->offset_within_address_space,
735                 int128_getlo(section->size),
736                 pgmask + 1);
737             return;
738         }
739     }
740 
741     ret = vfio_dma_map(container, iova, int128_get64(llsize),
742                        vaddr, section->readonly);
743     if (ret) {
744         error_setg(&err, "vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
745                    "0x%"HWADDR_PRIx", %p) = %d (%s)",
746                    container, iova, int128_get64(llsize), vaddr, ret,
747                    strerror(-ret));
748         if (memory_region_is_ram_device(section->mr)) {
749             /* Allow unexpected mappings not to be fatal for RAM devices */
750             error_report_err(err);
751             return;
752         }
753         goto fail;
754     }
755 
756     return;
757 
758 fail:
759     if (memory_region_is_ram_device(section->mr)) {
760         error_reportf_err(err, "PCI p2p may not work: ");
761         return;
762     }
763     /*
764      * On the initfn path, store the first error in the container so we
765      * can gracefully fail.  Runtime, there's not much we can do other
766      * than throw a hardware error.
767      */
768     if (!container->initialized) {
769         if (!container->error) {
770             error_propagate_prepend(&container->error, err,
771                                     "Region %s: ",
772                                     memory_region_name(section->mr));
773         } else {
774             error_free(err);
775         }
776     } else {
777         error_report_err(err);
778         hw_error("vfio: DMA mapping failed, unable to continue");
779     }
780 }
781 
782 static void vfio_listener_region_del(MemoryListener *listener,
783                                      MemoryRegionSection *section)
784 {
785     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
786     hwaddr iova, end;
787     Int128 llend, llsize;
788     int ret;
789     bool try_unmap = true;
790 
791     if (!vfio_listener_valid_section(section, "region_del")) {
792         return;
793     }
794 
795     if (memory_region_is_iommu(section->mr)) {
796         VFIOGuestIOMMU *giommu;
797 
798         QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
799             if (MEMORY_REGION(giommu->iommu_mr) == section->mr &&
800                 giommu->n.start == section->offset_within_region) {
801                 memory_region_unregister_iommu_notifier(section->mr,
802                                                         &giommu->n);
803                 QLIST_REMOVE(giommu, giommu_next);
804                 g_free(giommu);
805                 break;
806             }
807         }
808 
809         /*
810          * FIXME: We assume the one big unmap below is adequate to
811          * remove any individual page mappings in the IOMMU which
812          * might have been copied into VFIO. This works for a page table
813          * based IOMMU where a big unmap flattens a large range of IO-PTEs.
814          * That may not be true for all IOMMU types.
815          */
816     }
817 
818     if (!vfio_get_section_iova_range(container, section, &iova, &end, &llend)) {
819         return;
820     }
821 
822     llsize = int128_sub(llend, int128_make64(iova));
823 
824     trace_vfio_listener_region_del(iova, end);
825 
826     if (memory_region_is_ram_device(section->mr)) {
827         hwaddr pgmask;
828         VFIOHostDMAWindow *hostwin;
829 
830         hostwin = vfio_find_hostwin(container, iova, end);
831         assert(hostwin); /* or region_add() would have failed */
832 
833         pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
834         try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask));
835     } else if (memory_region_has_ram_discard_manager(section->mr)) {
836         vfio_unregister_ram_discard_listener(container, section);
837         /* Unregistering will trigger an unmap. */
838         try_unmap = false;
839     }
840 
841     if (try_unmap) {
842         if (int128_eq(llsize, int128_2_64())) {
843             /* The unmap ioctl doesn't accept a full 64-bit span. */
844             llsize = int128_rshift(llsize, 1);
845             ret = vfio_dma_unmap(container, iova, int128_get64(llsize), NULL);
846             if (ret) {
847                 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
848                              "0x%"HWADDR_PRIx") = %d (%s)",
849                              container, iova, int128_get64(llsize), ret,
850                              strerror(-ret));
851             }
852             iova += int128_get64(llsize);
853         }
854         ret = vfio_dma_unmap(container, iova, int128_get64(llsize), NULL);
855         if (ret) {
856             error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
857                          "0x%"HWADDR_PRIx") = %d (%s)",
858                          container, iova, int128_get64(llsize), ret,
859                          strerror(-ret));
860         }
861     }
862 
863     memory_region_unref(section->mr);
864 
865     vfio_container_del_section_window(container, section);
866 }
867 
868 typedef struct VFIODirtyRanges {
869     hwaddr min32;
870     hwaddr max32;
871     hwaddr min64;
872     hwaddr max64;
873     hwaddr minpci64;
874     hwaddr maxpci64;
875 } VFIODirtyRanges;
876 
877 typedef struct VFIODirtyRangesListener {
878     VFIOContainer *container;
879     VFIODirtyRanges ranges;
880     MemoryListener listener;
881 } VFIODirtyRangesListener;
882 
883 static bool vfio_section_is_vfio_pci(MemoryRegionSection *section,
884                                      VFIOContainer *container)
885 {
886     VFIOPCIDevice *pcidev;
887     VFIODevice *vbasedev;
888     Object *owner;
889 
890     owner = memory_region_owner(section->mr);
891 
892     QLIST_FOREACH(vbasedev, &container->device_list, container_next) {
893         if (vbasedev->type != VFIO_DEVICE_TYPE_PCI) {
894             continue;
895         }
896         pcidev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
897         if (OBJECT(pcidev) == owner) {
898             return true;
899         }
900     }
901 
902     return false;
903 }
904 
905 static void vfio_dirty_tracking_update(MemoryListener *listener,
906                                        MemoryRegionSection *section)
907 {
908     VFIODirtyRangesListener *dirty = container_of(listener,
909                                                   VFIODirtyRangesListener,
910                                                   listener);
911     VFIODirtyRanges *range = &dirty->ranges;
912     hwaddr iova, end, *min, *max;
913 
914     if (!vfio_listener_valid_section(section, "tracking_update") ||
915         !vfio_get_section_iova_range(dirty->container, section,
916                                      &iova, &end, NULL)) {
917         return;
918     }
919 
920     /*
921      * The address space passed to the dirty tracker is reduced to three ranges:
922      * one for 32-bit DMA ranges, one for 64-bit DMA ranges and one for the
923      * PCI 64-bit hole.
924      *
925      * The underlying reports of dirty will query a sub-interval of each of
926      * these ranges.
927      *
928      * The purpose of the three range handling is to handle known cases of big
929      * holes in the address space, like the x86 AMD 1T hole, and firmware (like
930      * OVMF) which may relocate the pci-hole64 to the end of the address space.
931      * The latter would otherwise generate large ranges for tracking, stressing
932      * the limits of supported hardware. The pci-hole32 will always be below 4G
933      * (overlapping or not) so it doesn't need special handling and is part of
934      * the 32-bit range.
935      *
936      * The alternative would be an IOVATree but that has a much bigger runtime
937      * overhead and unnecessary complexity.
938      */
939     if (vfio_section_is_vfio_pci(section, dirty->container) &&
940         iova >= UINT32_MAX) {
941         min = &range->minpci64;
942         max = &range->maxpci64;
943     } else {
944         min = (end <= UINT32_MAX) ? &range->min32 : &range->min64;
945         max = (end <= UINT32_MAX) ? &range->max32 : &range->max64;
946     }
947     if (*min > iova) {
948         *min = iova;
949     }
950     if (*max < end) {
951         *max = end;
952     }
953 
954     trace_vfio_device_dirty_tracking_update(iova, end, *min, *max);
955     return;
956 }
957 
958 static const MemoryListener vfio_dirty_tracking_listener = {
959     .name = "vfio-tracking",
960     .region_add = vfio_dirty_tracking_update,
961 };
962 
963 static void vfio_dirty_tracking_init(VFIOContainer *container,
964                                      VFIODirtyRanges *ranges)
965 {
966     VFIODirtyRangesListener dirty;
967 
968     memset(&dirty, 0, sizeof(dirty));
969     dirty.ranges.min32 = UINT32_MAX;
970     dirty.ranges.min64 = UINT64_MAX;
971     dirty.ranges.minpci64 = UINT64_MAX;
972     dirty.listener = vfio_dirty_tracking_listener;
973     dirty.container = container;
974 
975     memory_listener_register(&dirty.listener,
976                              container->space->as);
977 
978     *ranges = dirty.ranges;
979 
980     /*
981      * The memory listener is synchronous, and used to calculate the range
982      * to dirty tracking. Unregister it after we are done as we are not
983      * interested in any follow-up updates.
984      */
985     memory_listener_unregister(&dirty.listener);
986 }
987 
988 static void vfio_devices_dma_logging_stop(VFIOContainer *container)
989 {
990     uint64_t buf[DIV_ROUND_UP(sizeof(struct vfio_device_feature),
991                               sizeof(uint64_t))] = {};
992     struct vfio_device_feature *feature = (struct vfio_device_feature *)buf;
993     VFIODevice *vbasedev;
994 
995     feature->argsz = sizeof(buf);
996     feature->flags = VFIO_DEVICE_FEATURE_SET |
997                      VFIO_DEVICE_FEATURE_DMA_LOGGING_STOP;
998 
999     QLIST_FOREACH(vbasedev, &container->device_list, container_next) {
1000         if (!vbasedev->dirty_tracking) {
1001             continue;
1002         }
1003 
1004         if (ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature)) {
1005             warn_report("%s: Failed to stop DMA logging, err %d (%s)",
1006                         vbasedev->name, -errno, strerror(errno));
1007         }
1008         vbasedev->dirty_tracking = false;
1009     }
1010 }
1011 
1012 static struct vfio_device_feature *
1013 vfio_device_feature_dma_logging_start_create(VFIOContainer *container,
1014                                              VFIODirtyRanges *tracking)
1015 {
1016     struct vfio_device_feature *feature;
1017     size_t feature_size;
1018     struct vfio_device_feature_dma_logging_control *control;
1019     struct vfio_device_feature_dma_logging_range *ranges;
1020 
1021     feature_size = sizeof(struct vfio_device_feature) +
1022                    sizeof(struct vfio_device_feature_dma_logging_control);
1023     feature = g_try_malloc0(feature_size);
1024     if (!feature) {
1025         errno = ENOMEM;
1026         return NULL;
1027     }
1028     feature->argsz = feature_size;
1029     feature->flags = VFIO_DEVICE_FEATURE_SET |
1030                      VFIO_DEVICE_FEATURE_DMA_LOGGING_START;
1031 
1032     control = (struct vfio_device_feature_dma_logging_control *)feature->data;
1033     control->page_size = qemu_real_host_page_size();
1034 
1035     /*
1036      * DMA logging uAPI guarantees to support at least a number of ranges that
1037      * fits into a single host kernel base page.
1038      */
1039     control->num_ranges = !!tracking->max32 + !!tracking->max64 +
1040         !!tracking->maxpci64;
1041     ranges = g_try_new0(struct vfio_device_feature_dma_logging_range,
1042                         control->num_ranges);
1043     if (!ranges) {
1044         g_free(feature);
1045         errno = ENOMEM;
1046 
1047         return NULL;
1048     }
1049 
1050     control->ranges = (__u64)(uintptr_t)ranges;
1051     if (tracking->max32) {
1052         ranges->iova = tracking->min32;
1053         ranges->length = (tracking->max32 - tracking->min32) + 1;
1054         ranges++;
1055     }
1056     if (tracking->max64) {
1057         ranges->iova = tracking->min64;
1058         ranges->length = (tracking->max64 - tracking->min64) + 1;
1059         ranges++;
1060     }
1061     if (tracking->maxpci64) {
1062         ranges->iova = tracking->minpci64;
1063         ranges->length = (tracking->maxpci64 - tracking->minpci64) + 1;
1064     }
1065 
1066     trace_vfio_device_dirty_tracking_start(control->num_ranges,
1067                                            tracking->min32, tracking->max32,
1068                                            tracking->min64, tracking->max64,
1069                                            tracking->minpci64, tracking->maxpci64);
1070 
1071     return feature;
1072 }
1073 
1074 static void vfio_device_feature_dma_logging_start_destroy(
1075     struct vfio_device_feature *feature)
1076 {
1077     struct vfio_device_feature_dma_logging_control *control =
1078         (struct vfio_device_feature_dma_logging_control *)feature->data;
1079     struct vfio_device_feature_dma_logging_range *ranges =
1080         (struct vfio_device_feature_dma_logging_range *)(uintptr_t)control->ranges;
1081 
1082     g_free(ranges);
1083     g_free(feature);
1084 }
1085 
1086 static int vfio_devices_dma_logging_start(VFIOContainer *container)
1087 {
1088     struct vfio_device_feature *feature;
1089     VFIODirtyRanges ranges;
1090     VFIODevice *vbasedev;
1091     int ret = 0;
1092 
1093     vfio_dirty_tracking_init(container, &ranges);
1094     feature = vfio_device_feature_dma_logging_start_create(container,
1095                                                            &ranges);
1096     if (!feature) {
1097         return -errno;
1098     }
1099 
1100     QLIST_FOREACH(vbasedev, &container->device_list, container_next) {
1101         if (vbasedev->dirty_tracking) {
1102             continue;
1103         }
1104 
1105         ret = ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature);
1106         if (ret) {
1107             ret = -errno;
1108             error_report("%s: Failed to start DMA logging, err %d (%s)",
1109                          vbasedev->name, ret, strerror(errno));
1110             goto out;
1111         }
1112         vbasedev->dirty_tracking = true;
1113     }
1114 
1115 out:
1116     if (ret) {
1117         vfio_devices_dma_logging_stop(container);
1118     }
1119 
1120     vfio_device_feature_dma_logging_start_destroy(feature);
1121 
1122     return ret;
1123 }
1124 
1125 static void vfio_listener_log_global_start(MemoryListener *listener)
1126 {
1127     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1128     int ret;
1129 
1130     if (vfio_devices_all_device_dirty_tracking(container)) {
1131         ret = vfio_devices_dma_logging_start(container);
1132     } else {
1133         ret = vfio_set_dirty_page_tracking(container, true);
1134     }
1135 
1136     if (ret) {
1137         error_report("vfio: Could not start dirty page tracking, err: %d (%s)",
1138                      ret, strerror(-ret));
1139         vfio_set_migration_error(ret);
1140     }
1141 }
1142 
1143 static void vfio_listener_log_global_stop(MemoryListener *listener)
1144 {
1145     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1146     int ret = 0;
1147 
1148     if (vfio_devices_all_device_dirty_tracking(container)) {
1149         vfio_devices_dma_logging_stop(container);
1150     } else {
1151         ret = vfio_set_dirty_page_tracking(container, false);
1152     }
1153 
1154     if (ret) {
1155         error_report("vfio: Could not stop dirty page tracking, err: %d (%s)",
1156                      ret, strerror(-ret));
1157         vfio_set_migration_error(ret);
1158     }
1159 }
1160 
1161 static int vfio_device_dma_logging_report(VFIODevice *vbasedev, hwaddr iova,
1162                                           hwaddr size, void *bitmap)
1163 {
1164     uint64_t buf[DIV_ROUND_UP(sizeof(struct vfio_device_feature) +
1165                         sizeof(struct vfio_device_feature_dma_logging_report),
1166                         sizeof(__u64))] = {};
1167     struct vfio_device_feature *feature = (struct vfio_device_feature *)buf;
1168     struct vfio_device_feature_dma_logging_report *report =
1169         (struct vfio_device_feature_dma_logging_report *)feature->data;
1170 
1171     report->iova = iova;
1172     report->length = size;
1173     report->page_size = qemu_real_host_page_size();
1174     report->bitmap = (__u64)(uintptr_t)bitmap;
1175 
1176     feature->argsz = sizeof(buf);
1177     feature->flags = VFIO_DEVICE_FEATURE_GET |
1178                      VFIO_DEVICE_FEATURE_DMA_LOGGING_REPORT;
1179 
1180     if (ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature)) {
1181         return -errno;
1182     }
1183 
1184     return 0;
1185 }
1186 
1187 int vfio_devices_query_dirty_bitmap(VFIOContainer *container,
1188                                     VFIOBitmap *vbmap, hwaddr iova,
1189                                     hwaddr size)
1190 {
1191     VFIODevice *vbasedev;
1192     int ret;
1193 
1194     QLIST_FOREACH(vbasedev, &container->device_list, container_next) {
1195         ret = vfio_device_dma_logging_report(vbasedev, iova, size,
1196                                              vbmap->bitmap);
1197         if (ret) {
1198             error_report("%s: Failed to get DMA logging report, iova: "
1199                          "0x%" HWADDR_PRIx ", size: 0x%" HWADDR_PRIx
1200                          ", err: %d (%s)",
1201                          vbasedev->name, iova, size, ret, strerror(-ret));
1202 
1203             return ret;
1204         }
1205     }
1206 
1207     return 0;
1208 }
1209 
1210 int vfio_get_dirty_bitmap(VFIOContainer *container, uint64_t iova,
1211                           uint64_t size, ram_addr_t ram_addr)
1212 {
1213     bool all_device_dirty_tracking =
1214         vfio_devices_all_device_dirty_tracking(container);
1215     uint64_t dirty_pages;
1216     VFIOBitmap vbmap;
1217     int ret;
1218 
1219     if (!container->dirty_pages_supported && !all_device_dirty_tracking) {
1220         cpu_physical_memory_set_dirty_range(ram_addr, size,
1221                                             tcg_enabled() ? DIRTY_CLIENTS_ALL :
1222                                             DIRTY_CLIENTS_NOCODE);
1223         return 0;
1224     }
1225 
1226     ret = vfio_bitmap_alloc(&vbmap, size);
1227     if (ret) {
1228         return ret;
1229     }
1230 
1231     if (all_device_dirty_tracking) {
1232         ret = vfio_devices_query_dirty_bitmap(container, &vbmap, iova, size);
1233     } else {
1234         ret = vfio_query_dirty_bitmap(container, &vbmap, iova, size);
1235     }
1236 
1237     if (ret) {
1238         goto out;
1239     }
1240 
1241     dirty_pages = cpu_physical_memory_set_dirty_lebitmap(vbmap.bitmap, ram_addr,
1242                                                          vbmap.pages);
1243 
1244     trace_vfio_get_dirty_bitmap(container->fd, iova, size, vbmap.size,
1245                                 ram_addr, dirty_pages);
1246 out:
1247     g_free(vbmap.bitmap);
1248 
1249     return ret;
1250 }
1251 
1252 typedef struct {
1253     IOMMUNotifier n;
1254     VFIOGuestIOMMU *giommu;
1255 } vfio_giommu_dirty_notifier;
1256 
1257 static void vfio_iommu_map_dirty_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
1258 {
1259     vfio_giommu_dirty_notifier *gdn = container_of(n,
1260                                                 vfio_giommu_dirty_notifier, n);
1261     VFIOGuestIOMMU *giommu = gdn->giommu;
1262     VFIOContainer *container = giommu->container;
1263     hwaddr iova = iotlb->iova + giommu->iommu_offset;
1264     ram_addr_t translated_addr;
1265     int ret = -EINVAL;
1266 
1267     trace_vfio_iommu_map_dirty_notify(iova, iova + iotlb->addr_mask);
1268 
1269     if (iotlb->target_as != &address_space_memory) {
1270         error_report("Wrong target AS \"%s\", only system memory is allowed",
1271                      iotlb->target_as->name ? iotlb->target_as->name : "none");
1272         goto out;
1273     }
1274 
1275     rcu_read_lock();
1276     if (vfio_get_xlat_addr(iotlb, NULL, &translated_addr, NULL)) {
1277         ret = vfio_get_dirty_bitmap(container, iova, iotlb->addr_mask + 1,
1278                                     translated_addr);
1279         if (ret) {
1280             error_report("vfio_iommu_map_dirty_notify(%p, 0x%"HWADDR_PRIx", "
1281                          "0x%"HWADDR_PRIx") = %d (%s)",
1282                          container, iova, iotlb->addr_mask + 1, ret,
1283                          strerror(-ret));
1284         }
1285     }
1286     rcu_read_unlock();
1287 
1288 out:
1289     if (ret) {
1290         vfio_set_migration_error(ret);
1291     }
1292 }
1293 
1294 static int vfio_ram_discard_get_dirty_bitmap(MemoryRegionSection *section,
1295                                              void *opaque)
1296 {
1297     const hwaddr size = int128_get64(section->size);
1298     const hwaddr iova = section->offset_within_address_space;
1299     const ram_addr_t ram_addr = memory_region_get_ram_addr(section->mr) +
1300                                 section->offset_within_region;
1301     VFIORamDiscardListener *vrdl = opaque;
1302 
1303     /*
1304      * Sync the whole mapped region (spanning multiple individual mappings)
1305      * in one go.
1306      */
1307     return vfio_get_dirty_bitmap(vrdl->container, iova, size, ram_addr);
1308 }
1309 
1310 static int vfio_sync_ram_discard_listener_dirty_bitmap(VFIOContainer *container,
1311                                                    MemoryRegionSection *section)
1312 {
1313     RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
1314     VFIORamDiscardListener *vrdl = NULL;
1315 
1316     QLIST_FOREACH(vrdl, &container->vrdl_list, next) {
1317         if (vrdl->mr == section->mr &&
1318             vrdl->offset_within_address_space ==
1319             section->offset_within_address_space) {
1320             break;
1321         }
1322     }
1323 
1324     if (!vrdl) {
1325         hw_error("vfio: Trying to sync missing RAM discard listener");
1326     }
1327 
1328     /*
1329      * We only want/can synchronize the bitmap for actually mapped parts -
1330      * which correspond to populated parts. Replay all populated parts.
1331      */
1332     return ram_discard_manager_replay_populated(rdm, section,
1333                                               vfio_ram_discard_get_dirty_bitmap,
1334                                                 &vrdl);
1335 }
1336 
1337 static int vfio_sync_dirty_bitmap(VFIOContainer *container,
1338                                   MemoryRegionSection *section)
1339 {
1340     ram_addr_t ram_addr;
1341 
1342     if (memory_region_is_iommu(section->mr)) {
1343         VFIOGuestIOMMU *giommu;
1344 
1345         QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
1346             if (MEMORY_REGION(giommu->iommu_mr) == section->mr &&
1347                 giommu->n.start == section->offset_within_region) {
1348                 Int128 llend;
1349                 vfio_giommu_dirty_notifier gdn = { .giommu = giommu };
1350                 int idx = memory_region_iommu_attrs_to_index(giommu->iommu_mr,
1351                                                        MEMTXATTRS_UNSPECIFIED);
1352 
1353                 llend = int128_add(int128_make64(section->offset_within_region),
1354                                    section->size);
1355                 llend = int128_sub(llend, int128_one());
1356 
1357                 iommu_notifier_init(&gdn.n,
1358                                     vfio_iommu_map_dirty_notify,
1359                                     IOMMU_NOTIFIER_MAP,
1360                                     section->offset_within_region,
1361                                     int128_get64(llend),
1362                                     idx);
1363                 memory_region_iommu_replay(giommu->iommu_mr, &gdn.n);
1364                 break;
1365             }
1366         }
1367         return 0;
1368     } else if (memory_region_has_ram_discard_manager(section->mr)) {
1369         return vfio_sync_ram_discard_listener_dirty_bitmap(container, section);
1370     }
1371 
1372     ram_addr = memory_region_get_ram_addr(section->mr) +
1373                section->offset_within_region;
1374 
1375     return vfio_get_dirty_bitmap(container,
1376                    REAL_HOST_PAGE_ALIGN(section->offset_within_address_space),
1377                    int128_get64(section->size), ram_addr);
1378 }
1379 
1380 static void vfio_listener_log_sync(MemoryListener *listener,
1381         MemoryRegionSection *section)
1382 {
1383     VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1384     int ret;
1385 
1386     if (vfio_listener_skipped_section(section)) {
1387         return;
1388     }
1389 
1390     if (vfio_devices_all_dirty_tracking(container)) {
1391         ret = vfio_sync_dirty_bitmap(container, section);
1392         if (ret) {
1393             error_report("vfio: Failed to sync dirty bitmap, err: %d (%s)", ret,
1394                          strerror(-ret));
1395             vfio_set_migration_error(ret);
1396         }
1397     }
1398 }
1399 
1400 const MemoryListener vfio_memory_listener = {
1401     .name = "vfio",
1402     .region_add = vfio_listener_region_add,
1403     .region_del = vfio_listener_region_del,
1404     .log_global_start = vfio_listener_log_global_start,
1405     .log_global_stop = vfio_listener_log_global_stop,
1406     .log_sync = vfio_listener_log_sync,
1407 };
1408 
1409 void vfio_reset_handler(void *opaque)
1410 {
1411     VFIODevice *vbasedev;
1412 
1413     QLIST_FOREACH(vbasedev, &vfio_device_list, next) {
1414         if (vbasedev->dev->realized) {
1415             vbasedev->ops->vfio_compute_needs_reset(vbasedev);
1416         }
1417     }
1418 
1419     QLIST_FOREACH(vbasedev, &vfio_device_list, next) {
1420         if (vbasedev->dev->realized && vbasedev->needs_reset) {
1421             vbasedev->ops->vfio_hot_reset_multi(vbasedev);
1422         }
1423     }
1424 }
1425 
1426 int vfio_kvm_device_add_fd(int fd, Error **errp)
1427 {
1428 #ifdef CONFIG_KVM
1429     struct kvm_device_attr attr = {
1430         .group = KVM_DEV_VFIO_FILE,
1431         .attr = KVM_DEV_VFIO_FILE_ADD,
1432         .addr = (uint64_t)(unsigned long)&fd,
1433     };
1434 
1435     if (!kvm_enabled()) {
1436         return 0;
1437     }
1438 
1439     if (vfio_kvm_device_fd < 0) {
1440         struct kvm_create_device cd = {
1441             .type = KVM_DEV_TYPE_VFIO,
1442         };
1443 
1444         if (kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd)) {
1445             error_setg_errno(errp, errno, "Failed to create KVM VFIO device");
1446             return -errno;
1447         }
1448 
1449         vfio_kvm_device_fd = cd.fd;
1450     }
1451 
1452     if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1453         error_setg_errno(errp, errno, "Failed to add fd %d to KVM VFIO device",
1454                          fd);
1455         return -errno;
1456     }
1457 #endif
1458     return 0;
1459 }
1460 
1461 int vfio_kvm_device_del_fd(int fd, Error **errp)
1462 {
1463 #ifdef CONFIG_KVM
1464     struct kvm_device_attr attr = {
1465         .group = KVM_DEV_VFIO_FILE,
1466         .attr = KVM_DEV_VFIO_FILE_DEL,
1467         .addr = (uint64_t)(unsigned long)&fd,
1468     };
1469 
1470     if (vfio_kvm_device_fd < 0) {
1471         error_setg(errp, "KVM VFIO device isn't created yet");
1472         return -EINVAL;
1473     }
1474 
1475     if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1476         error_setg_errno(errp, errno,
1477                          "Failed to remove fd %d from KVM VFIO device", fd);
1478         return -errno;
1479     }
1480 #endif
1481     return 0;
1482 }
1483 
1484 VFIOAddressSpace *vfio_get_address_space(AddressSpace *as)
1485 {
1486     VFIOAddressSpace *space;
1487 
1488     QLIST_FOREACH(space, &vfio_address_spaces, list) {
1489         if (space->as == as) {
1490             return space;
1491         }
1492     }
1493 
1494     /* No suitable VFIOAddressSpace, create a new one */
1495     space = g_malloc0(sizeof(*space));
1496     space->as = as;
1497     QLIST_INIT(&space->containers);
1498 
1499     if (QLIST_EMPTY(&vfio_address_spaces)) {
1500         qemu_register_reset(vfio_reset_handler, NULL);
1501     }
1502 
1503     QLIST_INSERT_HEAD(&vfio_address_spaces, space, list);
1504 
1505     return space;
1506 }
1507 
1508 void vfio_put_address_space(VFIOAddressSpace *space)
1509 {
1510     if (QLIST_EMPTY(&space->containers)) {
1511         QLIST_REMOVE(space, list);
1512         g_free(space);
1513     }
1514     if (QLIST_EMPTY(&vfio_address_spaces)) {
1515         qemu_unregister_reset(vfio_reset_handler, NULL);
1516     }
1517 }
1518 
1519 struct vfio_device_info *vfio_get_device_info(int fd)
1520 {
1521     struct vfio_device_info *info;
1522     uint32_t argsz = sizeof(*info);
1523 
1524     info = g_malloc0(argsz);
1525 
1526 retry:
1527     info->argsz = argsz;
1528 
1529     if (ioctl(fd, VFIO_DEVICE_GET_INFO, info)) {
1530         g_free(info);
1531         return NULL;
1532     }
1533 
1534     if (info->argsz > argsz) {
1535         argsz = info->argsz;
1536         info = g_realloc(info, argsz);
1537         goto retry;
1538     }
1539 
1540     return info;
1541 }
1542