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