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