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