xref: /openbmc/qemu/hw/vfio/container.c (revision aa90d775f0f568239f2a6bd3ead7e8d3b4a35a57)
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 #include <linux/vfio.h>
24 
25 #include "hw/vfio/vfio-common.h"
26 #include "system/address-spaces.h"
27 #include "system/memory.h"
28 #include "system/ram_addr.h"
29 #include "qemu/error-report.h"
30 #include "qemu/range.h"
31 #include "system/reset.h"
32 #include "trace.h"
33 #include "qapi/error.h"
34 #include "pci.h"
35 #include "hw/vfio/vfio-container.h"
36 
37 VFIOGroupList vfio_group_list =
38     QLIST_HEAD_INITIALIZER(vfio_group_list);
39 
40 static int vfio_ram_block_discard_disable(VFIOContainer *container, bool state)
41 {
42     switch (container->iommu_type) {
43     case VFIO_TYPE1v2_IOMMU:
44     case VFIO_TYPE1_IOMMU:
45         /*
46          * We support coordinated discarding of RAM via the RamDiscardManager.
47          */
48         return ram_block_uncoordinated_discard_disable(state);
49     default:
50         /*
51          * VFIO_SPAPR_TCE_IOMMU most probably works just fine with
52          * RamDiscardManager, however, it is completely untested.
53          *
54          * VFIO_SPAPR_TCE_v2_IOMMU with "DMA memory preregistering" does
55          * completely the opposite of managing mapping/pinning dynamically as
56          * required by RamDiscardManager. We would have to special-case sections
57          * with a RamDiscardManager.
58          */
59         return ram_block_discard_disable(state);
60     }
61 }
62 
63 static int vfio_dma_unmap_bitmap(const VFIOContainer *container,
64                                  hwaddr iova, ram_addr_t size,
65                                  IOMMUTLBEntry *iotlb)
66 {
67     const VFIOContainerBase *bcontainer = &container->bcontainer;
68     struct vfio_iommu_type1_dma_unmap *unmap;
69     struct vfio_bitmap *bitmap;
70     VFIOBitmap vbmap;
71     int ret;
72 
73     ret = vfio_bitmap_alloc(&vbmap, size);
74     if (ret) {
75         return ret;
76     }
77 
78     unmap = g_malloc0(sizeof(*unmap) + sizeof(*bitmap));
79 
80     unmap->argsz = sizeof(*unmap) + sizeof(*bitmap);
81     unmap->iova = iova;
82     unmap->size = size;
83     unmap->flags |= VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP;
84     bitmap = (struct vfio_bitmap *)&unmap->data;
85 
86     /*
87      * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
88      * qemu_real_host_page_size to mark those dirty. Hence set bitmap_pgsize
89      * to qemu_real_host_page_size.
90      */
91     bitmap->pgsize = qemu_real_host_page_size();
92     bitmap->size = vbmap.size;
93     bitmap->data = (__u64 *)vbmap.bitmap;
94 
95     if (vbmap.size > bcontainer->max_dirty_bitmap_size) {
96         error_report("UNMAP: Size of bitmap too big 0x%"PRIx64, vbmap.size);
97         ret = -E2BIG;
98         goto unmap_exit;
99     }
100 
101     ret = ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, unmap);
102     if (!ret) {
103         cpu_physical_memory_set_dirty_lebitmap(vbmap.bitmap,
104                 iotlb->translated_addr, vbmap.pages);
105     } else {
106         error_report("VFIO_UNMAP_DMA with DIRTY_BITMAP : %m");
107     }
108 
109 unmap_exit:
110     g_free(unmap);
111     g_free(vbmap.bitmap);
112 
113     return ret;
114 }
115 
116 /*
117  * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
118  */
119 static int vfio_legacy_dma_unmap(const VFIOContainerBase *bcontainer,
120                                  hwaddr iova, ram_addr_t size,
121                                  IOMMUTLBEntry *iotlb)
122 {
123     const VFIOContainer *container = container_of(bcontainer, VFIOContainer,
124                                                   bcontainer);
125     struct vfio_iommu_type1_dma_unmap unmap = {
126         .argsz = sizeof(unmap),
127         .flags = 0,
128         .iova = iova,
129         .size = size,
130     };
131     bool need_dirty_sync = false;
132     int ret;
133     Error *local_err = NULL;
134 
135     if (iotlb && vfio_devices_all_dirty_tracking_started(bcontainer)) {
136         if (!vfio_devices_all_device_dirty_tracking(bcontainer) &&
137             bcontainer->dirty_pages_supported) {
138             return vfio_dma_unmap_bitmap(container, iova, size, iotlb);
139         }
140 
141         need_dirty_sync = true;
142     }
143 
144     while (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
145         /*
146          * The type1 backend has an off-by-one bug in the kernel (71a7d3d78e3c
147          * v4.15) where an overflow in its wrap-around check prevents us from
148          * unmapping the last page of the address space.  Test for the error
149          * condition and re-try the unmap excluding the last page.  The
150          * expectation is that we've never mapped the last page anyway and this
151          * unmap request comes via vIOMMU support which also makes it unlikely
152          * that this page is used.  This bug was introduced well after type1 v2
153          * support was introduced, so we shouldn't need to test for v1.  A fix
154          * is queued for kernel v5.0 so this workaround can be removed once
155          * affected kernels are sufficiently deprecated.
156          */
157         if (errno == EINVAL && unmap.size && !(unmap.iova + unmap.size) &&
158             container->iommu_type == VFIO_TYPE1v2_IOMMU) {
159             trace_vfio_legacy_dma_unmap_overflow_workaround();
160             unmap.size -= 1ULL << ctz64(bcontainer->pgsizes);
161             continue;
162         }
163         return -errno;
164     }
165 
166     if (need_dirty_sync) {
167         ret = vfio_get_dirty_bitmap(bcontainer, iova, size,
168                                     iotlb->translated_addr, &local_err);
169         if (ret) {
170             error_report_err(local_err);
171             return ret;
172         }
173     }
174 
175     return 0;
176 }
177 
178 static int vfio_legacy_dma_map(const VFIOContainerBase *bcontainer, hwaddr iova,
179                                ram_addr_t size, void *vaddr, bool readonly)
180 {
181     const VFIOContainer *container = container_of(bcontainer, VFIOContainer,
182                                                   bcontainer);
183     struct vfio_iommu_type1_dma_map map = {
184         .argsz = sizeof(map),
185         .flags = VFIO_DMA_MAP_FLAG_READ,
186         .vaddr = (__u64)(uintptr_t)vaddr,
187         .iova = iova,
188         .size = size,
189     };
190 
191     if (!readonly) {
192         map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
193     }
194 
195     /*
196      * Try the mapping, if it fails with EBUSY, unmap the region and try
197      * again.  This shouldn't be necessary, but we sometimes see it in
198      * the VGA ROM space.
199      */
200     if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
201         (errno == EBUSY &&
202          vfio_legacy_dma_unmap(bcontainer, iova, size, NULL) == 0 &&
203          ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
204         return 0;
205     }
206 
207     return -errno;
208 }
209 
210 static int
211 vfio_legacy_set_dirty_page_tracking(const VFIOContainerBase *bcontainer,
212                                     bool start, Error **errp)
213 {
214     const VFIOContainer *container = container_of(bcontainer, VFIOContainer,
215                                                   bcontainer);
216     int ret;
217     struct vfio_iommu_type1_dirty_bitmap dirty = {
218         .argsz = sizeof(dirty),
219     };
220 
221     if (start) {
222         dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_START;
223     } else {
224         dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP;
225     }
226 
227     ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, &dirty);
228     if (ret) {
229         ret = -errno;
230         error_setg_errno(errp, errno, "Failed to set dirty tracking flag 0x%x",
231                          dirty.flags);
232     }
233 
234     return ret;
235 }
236 
237 static int vfio_legacy_query_dirty_bitmap(const VFIOContainerBase *bcontainer,
238                       VFIOBitmap *vbmap, hwaddr iova, hwaddr size, Error **errp)
239 {
240     const VFIOContainer *container = container_of(bcontainer, VFIOContainer,
241                                                   bcontainer);
242     struct vfio_iommu_type1_dirty_bitmap *dbitmap;
243     struct vfio_iommu_type1_dirty_bitmap_get *range;
244     int ret;
245 
246     dbitmap = g_malloc0(sizeof(*dbitmap) + sizeof(*range));
247 
248     dbitmap->argsz = sizeof(*dbitmap) + sizeof(*range);
249     dbitmap->flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
250     range = (struct vfio_iommu_type1_dirty_bitmap_get *)&dbitmap->data;
251     range->iova = iova;
252     range->size = size;
253 
254     /*
255      * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
256      * qemu_real_host_page_size to mark those dirty. Hence set bitmap's pgsize
257      * to qemu_real_host_page_size.
258      */
259     range->bitmap.pgsize = qemu_real_host_page_size();
260     range->bitmap.size = vbmap->size;
261     range->bitmap.data = (__u64 *)vbmap->bitmap;
262 
263     ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, dbitmap);
264     if (ret) {
265         ret = -errno;
266         error_setg_errno(errp, errno,
267                          "Failed to get dirty bitmap for iova: 0x%"PRIx64
268                          " size: 0x%"PRIx64, (uint64_t)range->iova,
269                          (uint64_t)range->size);
270     }
271 
272     g_free(dbitmap);
273 
274     return ret;
275 }
276 
277 static struct vfio_info_cap_header *
278 vfio_get_iommu_type1_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
279 {
280     if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
281         return NULL;
282     }
283 
284     return vfio_get_cap((void *)info, info->cap_offset, id);
285 }
286 
287 bool vfio_get_info_dma_avail(struct vfio_iommu_type1_info *info,
288                              unsigned int *avail)
289 {
290     struct vfio_info_cap_header *hdr;
291     struct vfio_iommu_type1_info_dma_avail *cap;
292 
293     /* If the capability cannot be found, assume no DMA limiting */
294     hdr = vfio_get_iommu_type1_info_cap(info,
295                                         VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL);
296     if (!hdr) {
297         return false;
298     }
299 
300     if (avail != NULL) {
301         cap = (void *) hdr;
302         *avail = cap->avail;
303     }
304 
305     return true;
306 }
307 
308 static bool vfio_get_info_iova_range(struct vfio_iommu_type1_info *info,
309                                      VFIOContainerBase *bcontainer)
310 {
311     struct vfio_info_cap_header *hdr;
312     struct vfio_iommu_type1_info_cap_iova_range *cap;
313 
314     hdr = vfio_get_iommu_type1_info_cap(info,
315                                         VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE);
316     if (!hdr) {
317         return false;
318     }
319 
320     cap = (void *)hdr;
321 
322     for (int i = 0; i < cap->nr_iovas; i++) {
323         Range *range = g_new(Range, 1);
324 
325         range_set_bounds(range, cap->iova_ranges[i].start,
326                          cap->iova_ranges[i].end);
327         bcontainer->iova_ranges =
328             range_list_insert(bcontainer->iova_ranges, range);
329     }
330 
331     return true;
332 }
333 
334 static void vfio_kvm_device_add_group(VFIOGroup *group)
335 {
336     Error *err = NULL;
337 
338     if (vfio_kvm_device_add_fd(group->fd, &err)) {
339         error_reportf_err(err, "group ID %d: ", group->groupid);
340     }
341 }
342 
343 static void vfio_kvm_device_del_group(VFIOGroup *group)
344 {
345     Error *err = NULL;
346 
347     if (vfio_kvm_device_del_fd(group->fd, &err)) {
348         error_reportf_err(err, "group ID %d: ", group->groupid);
349     }
350 }
351 
352 /*
353  * vfio_get_iommu_type - selects the richest iommu_type (v2 first)
354  */
355 static int vfio_get_iommu_type(int container_fd,
356                                Error **errp)
357 {
358     int iommu_types[] = { VFIO_TYPE1v2_IOMMU, VFIO_TYPE1_IOMMU,
359                           VFIO_SPAPR_TCE_v2_IOMMU, VFIO_SPAPR_TCE_IOMMU };
360     int i;
361 
362     for (i = 0; i < ARRAY_SIZE(iommu_types); i++) {
363         if (ioctl(container_fd, VFIO_CHECK_EXTENSION, iommu_types[i])) {
364             return iommu_types[i];
365         }
366     }
367     error_setg(errp, "No available IOMMU models");
368     return -EINVAL;
369 }
370 
371 /*
372  * vfio_get_iommu_ops - get a VFIOIOMMUClass associated with a type
373  */
374 static const char *vfio_get_iommu_class_name(int iommu_type)
375 {
376     switch (iommu_type) {
377     case VFIO_TYPE1v2_IOMMU:
378     case VFIO_TYPE1_IOMMU:
379         return TYPE_VFIO_IOMMU_LEGACY;
380         break;
381     case VFIO_SPAPR_TCE_v2_IOMMU:
382     case VFIO_SPAPR_TCE_IOMMU:
383         return TYPE_VFIO_IOMMU_SPAPR;
384         break;
385     default:
386         g_assert_not_reached();
387     };
388 }
389 
390 static bool vfio_set_iommu(int container_fd, int group_fd,
391                            int *iommu_type, Error **errp)
392 {
393     if (ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container_fd)) {
394         error_setg_errno(errp, errno, "Failed to set group container");
395         return false;
396     }
397 
398     while (ioctl(container_fd, VFIO_SET_IOMMU, *iommu_type)) {
399         if (*iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
400             /*
401              * On sPAPR, despite the IOMMU subdriver always advertises v1 and
402              * v2, the running platform may not support v2 and there is no
403              * way to guess it until an IOMMU group gets added to the container.
404              * So in case it fails with v2, try v1 as a fallback.
405              */
406             *iommu_type = VFIO_SPAPR_TCE_IOMMU;
407             continue;
408         }
409         error_setg_errno(errp, errno, "Failed to set iommu for container");
410         return false;
411     }
412 
413     return true;
414 }
415 
416 static VFIOContainer *vfio_create_container(int fd, VFIOGroup *group,
417                                             Error **errp)
418 {
419     int iommu_type;
420     const char *vioc_name;
421     VFIOContainer *container;
422 
423     iommu_type = vfio_get_iommu_type(fd, errp);
424     if (iommu_type < 0) {
425         return NULL;
426     }
427 
428     if (!vfio_set_iommu(fd, group->fd, &iommu_type, errp)) {
429         return NULL;
430     }
431 
432     vioc_name = vfio_get_iommu_class_name(iommu_type);
433 
434     container = VFIO_IOMMU_LEGACY(object_new(vioc_name));
435     container->fd = fd;
436     container->iommu_type = iommu_type;
437     return container;
438 }
439 
440 static int vfio_get_iommu_info(VFIOContainer *container,
441                                struct vfio_iommu_type1_info **info)
442 {
443 
444     size_t argsz = sizeof(struct vfio_iommu_type1_info);
445 
446     *info = g_new0(struct vfio_iommu_type1_info, 1);
447 again:
448     (*info)->argsz = argsz;
449 
450     if (ioctl(container->fd, VFIO_IOMMU_GET_INFO, *info)) {
451         g_free(*info);
452         *info = NULL;
453         return -errno;
454     }
455 
456     if (((*info)->argsz > argsz)) {
457         argsz = (*info)->argsz;
458         *info = g_realloc(*info, argsz);
459         goto again;
460     }
461 
462     return 0;
463 }
464 
465 static struct vfio_info_cap_header *
466 vfio_get_iommu_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
467 {
468     struct vfio_info_cap_header *hdr;
469     void *ptr = info;
470 
471     if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
472         return NULL;
473     }
474 
475     for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
476         if (hdr->id == id) {
477             return hdr;
478         }
479     }
480 
481     return NULL;
482 }
483 
484 static void vfio_get_iommu_info_migration(VFIOContainer *container,
485                                           struct vfio_iommu_type1_info *info)
486 {
487     struct vfio_info_cap_header *hdr;
488     struct vfio_iommu_type1_info_cap_migration *cap_mig;
489     VFIOContainerBase *bcontainer = &container->bcontainer;
490 
491     hdr = vfio_get_iommu_info_cap(info, VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION);
492     if (!hdr) {
493         return;
494     }
495 
496     cap_mig = container_of(hdr, struct vfio_iommu_type1_info_cap_migration,
497                             header);
498 
499     /*
500      * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
501      * qemu_real_host_page_size to mark those dirty.
502      */
503     if (cap_mig->pgsize_bitmap & qemu_real_host_page_size()) {
504         bcontainer->dirty_pages_supported = true;
505         bcontainer->max_dirty_bitmap_size = cap_mig->max_dirty_bitmap_size;
506         bcontainer->dirty_pgsizes = cap_mig->pgsize_bitmap;
507     }
508 }
509 
510 static bool vfio_legacy_setup(VFIOContainerBase *bcontainer, Error **errp)
511 {
512     VFIOContainer *container = container_of(bcontainer, VFIOContainer,
513                                             bcontainer);
514     g_autofree struct vfio_iommu_type1_info *info = NULL;
515     int ret;
516 
517     ret = vfio_get_iommu_info(container, &info);
518     if (ret) {
519         error_setg_errno(errp, -ret, "Failed to get VFIO IOMMU info");
520         return false;
521     }
522 
523     if (info->flags & VFIO_IOMMU_INFO_PGSIZES) {
524         bcontainer->pgsizes = info->iova_pgsizes;
525     } else {
526         bcontainer->pgsizes = qemu_real_host_page_size();
527     }
528 
529     if (!vfio_get_info_dma_avail(info, &bcontainer->dma_max_mappings)) {
530         bcontainer->dma_max_mappings = 65535;
531     }
532 
533     vfio_get_info_iova_range(info, bcontainer);
534 
535     vfio_get_iommu_info_migration(container, info);
536     return true;
537 }
538 
539 static bool vfio_connect_container(VFIOGroup *group, AddressSpace *as,
540                                    Error **errp)
541 {
542     VFIOContainer *container;
543     VFIOContainerBase *bcontainer;
544     int ret, fd;
545     VFIOAddressSpace *space;
546     VFIOIOMMUClass *vioc;
547 
548     space = vfio_get_address_space(as);
549 
550     /*
551      * VFIO is currently incompatible with discarding of RAM insofar as the
552      * madvise to purge (zap) the page from QEMU's address space does not
553      * interact with the memory API and therefore leaves stale virtual to
554      * physical mappings in the IOMMU if the page was previously pinned.  We
555      * therefore set discarding broken for each group added to a container,
556      * whether the container is used individually or shared.  This provides
557      * us with options to allow devices within a group to opt-in and allow
558      * discarding, so long as it is done consistently for a group (for instance
559      * if the device is an mdev device where it is known that the host vendor
560      * driver will never pin pages outside of the working set of the guest
561      * driver, which would thus not be discarding candidates).
562      *
563      * The first opportunity to induce pinning occurs here where we attempt to
564      * attach the group to existing containers within the AddressSpace.  If any
565      * pages are already zapped from the virtual address space, such as from
566      * previous discards, new pinning will cause valid mappings to be
567      * re-established.  Likewise, when the overall MemoryListener for a new
568      * container is registered, a replay of mappings within the AddressSpace
569      * will occur, re-establishing any previously zapped pages as well.
570      *
571      * Especially virtio-balloon is currently only prevented from discarding
572      * new memory, it will not yet set ram_block_discard_set_required() and
573      * therefore, neither stops us here or deals with the sudden memory
574      * consumption of inflated memory.
575      *
576      * We do support discarding of memory coordinated via the RamDiscardManager
577      * with some IOMMU types. vfio_ram_block_discard_disable() handles the
578      * details once we know which type of IOMMU we are using.
579      */
580 
581     QLIST_FOREACH(bcontainer, &space->containers, next) {
582         container = container_of(bcontainer, VFIOContainer, bcontainer);
583         if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
584             ret = vfio_ram_block_discard_disable(container, true);
585             if (ret) {
586                 error_setg_errno(errp, -ret,
587                                  "Cannot set discarding of RAM broken");
588                 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER,
589                           &container->fd)) {
590                     error_report("vfio: error disconnecting group %d from"
591                                  " container", group->groupid);
592                 }
593                 return false;
594             }
595             group->container = container;
596             QLIST_INSERT_HEAD(&container->group_list, group, container_next);
597             vfio_kvm_device_add_group(group);
598             return true;
599         }
600     }
601 
602     fd = qemu_open("/dev/vfio/vfio", O_RDWR, errp);
603     if (fd < 0) {
604         goto put_space_exit;
605     }
606 
607     ret = ioctl(fd, VFIO_GET_API_VERSION);
608     if (ret != VFIO_API_VERSION) {
609         error_setg(errp, "supported vfio version: %d, "
610                    "reported version: %d", VFIO_API_VERSION, ret);
611         goto close_fd_exit;
612     }
613 
614     container = vfio_create_container(fd, group, errp);
615     if (!container) {
616         goto close_fd_exit;
617     }
618     bcontainer = &container->bcontainer;
619 
620     if (!vfio_cpr_register_container(bcontainer, errp)) {
621         goto free_container_exit;
622     }
623 
624     ret = vfio_ram_block_discard_disable(container, true);
625     if (ret) {
626         error_setg_errno(errp, -ret, "Cannot set discarding of RAM broken");
627         goto unregister_container_exit;
628     }
629 
630     vioc = VFIO_IOMMU_GET_CLASS(bcontainer);
631     assert(vioc->setup);
632 
633     if (!vioc->setup(bcontainer, errp)) {
634         goto enable_discards_exit;
635     }
636 
637     vfio_kvm_device_add_group(group);
638 
639     vfio_address_space_insert(space, bcontainer);
640 
641     group->container = container;
642     QLIST_INSERT_HEAD(&container->group_list, group, container_next);
643 
644     bcontainer->listener = vfio_memory_listener;
645     memory_listener_register(&bcontainer->listener, bcontainer->space->as);
646 
647     if (bcontainer->error) {
648         error_propagate_prepend(errp, bcontainer->error,
649             "memory listener initialization failed: ");
650         goto listener_release_exit;
651     }
652 
653     bcontainer->initialized = true;
654 
655     return true;
656 listener_release_exit:
657     QLIST_REMOVE(group, container_next);
658     vfio_kvm_device_del_group(group);
659     memory_listener_unregister(&bcontainer->listener);
660     if (vioc->release) {
661         vioc->release(bcontainer);
662     }
663 
664 enable_discards_exit:
665     vfio_ram_block_discard_disable(container, false);
666 
667 unregister_container_exit:
668     vfio_cpr_unregister_container(bcontainer);
669 
670 free_container_exit:
671     object_unref(container);
672 
673 close_fd_exit:
674     close(fd);
675 
676 put_space_exit:
677     vfio_put_address_space(space);
678 
679     return false;
680 }
681 
682 static void vfio_disconnect_container(VFIOGroup *group)
683 {
684     VFIOContainer *container = group->container;
685     VFIOContainerBase *bcontainer = &container->bcontainer;
686     VFIOIOMMUClass *vioc = VFIO_IOMMU_GET_CLASS(bcontainer);
687 
688     QLIST_REMOVE(group, container_next);
689     group->container = NULL;
690 
691     /*
692      * Explicitly release the listener first before unset container,
693      * since unset may destroy the backend container if it's the last
694      * group.
695      */
696     if (QLIST_EMPTY(&container->group_list)) {
697         memory_listener_unregister(&bcontainer->listener);
698         if (vioc->release) {
699             vioc->release(bcontainer);
700         }
701     }
702 
703     if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
704         error_report("vfio: error disconnecting group %d from container",
705                      group->groupid);
706     }
707 
708     if (QLIST_EMPTY(&container->group_list)) {
709         VFIOAddressSpace *space = bcontainer->space;
710 
711         trace_vfio_disconnect_container(container->fd);
712         vfio_cpr_unregister_container(bcontainer);
713         close(container->fd);
714         object_unref(container);
715 
716         vfio_put_address_space(space);
717     }
718 }
719 
720 static VFIOGroup *vfio_get_group(int groupid, AddressSpace *as, Error **errp)
721 {
722     ERRP_GUARD();
723     VFIOGroup *group;
724     char path[32];
725     struct vfio_group_status status = { .argsz = sizeof(status) };
726 
727     QLIST_FOREACH(group, &vfio_group_list, next) {
728         if (group->groupid == groupid) {
729             /* Found it.  Now is it already in the right context? */
730             if (group->container->bcontainer.space->as == as) {
731                 return group;
732             } else {
733                 error_setg(errp, "group %d used in multiple address spaces",
734                            group->groupid);
735                 return NULL;
736             }
737         }
738     }
739 
740     group = g_malloc0(sizeof(*group));
741 
742     snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
743     group->fd = qemu_open(path, O_RDWR, errp);
744     if (group->fd < 0) {
745         goto free_group_exit;
746     }
747 
748     if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
749         error_setg_errno(errp, errno, "failed to get group %d status", groupid);
750         goto close_fd_exit;
751     }
752 
753     if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
754         error_setg(errp, "group %d is not viable", groupid);
755         error_append_hint(errp,
756                           "Please ensure all devices within the iommu_group "
757                           "are bound to their vfio bus driver.\n");
758         goto close_fd_exit;
759     }
760 
761     group->groupid = groupid;
762     QLIST_INIT(&group->device_list);
763 
764     if (!vfio_connect_container(group, as, errp)) {
765         error_prepend(errp, "failed to setup container for group %d: ",
766                       groupid);
767         goto close_fd_exit;
768     }
769 
770     QLIST_INSERT_HEAD(&vfio_group_list, group, next);
771 
772     return group;
773 
774 close_fd_exit:
775     close(group->fd);
776 
777 free_group_exit:
778     g_free(group);
779 
780     return NULL;
781 }
782 
783 static void vfio_put_group(VFIOGroup *group)
784 {
785     if (!group || !QLIST_EMPTY(&group->device_list)) {
786         return;
787     }
788 
789     if (!group->ram_block_discard_allowed) {
790         vfio_ram_block_discard_disable(group->container, false);
791     }
792     vfio_kvm_device_del_group(group);
793     vfio_disconnect_container(group);
794     QLIST_REMOVE(group, next);
795     trace_vfio_put_group(group->fd);
796     close(group->fd);
797     g_free(group);
798 }
799 
800 static bool vfio_get_device(VFIOGroup *group, const char *name,
801                             VFIODevice *vbasedev, Error **errp)
802 {
803     g_autofree struct vfio_device_info *info = NULL;
804     int fd;
805 
806     fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
807     if (fd < 0) {
808         error_setg_errno(errp, errno, "error getting device from group %d",
809                          group->groupid);
810         error_append_hint(errp,
811                       "Verify all devices in group %d are bound to vfio-<bus> "
812                       "or pci-stub and not already in use\n", group->groupid);
813         return false;
814     }
815 
816     info = vfio_get_device_info(fd);
817     if (!info) {
818         error_setg_errno(errp, errno, "error getting device info");
819         close(fd);
820         return false;
821     }
822 
823     /*
824      * Set discarding of RAM as not broken for this group if the driver knows
825      * the device operates compatibly with discarding.  Setting must be
826      * consistent per group, but since compatibility is really only possible
827      * with mdev currently, we expect singleton groups.
828      */
829     if (vbasedev->ram_block_discard_allowed !=
830         group->ram_block_discard_allowed) {
831         if (!QLIST_EMPTY(&group->device_list)) {
832             error_setg(errp, "Inconsistent setting of support for discarding "
833                        "RAM (e.g., balloon) within group");
834             close(fd);
835             return false;
836         }
837 
838         if (!group->ram_block_discard_allowed) {
839             group->ram_block_discard_allowed = true;
840             vfio_ram_block_discard_disable(group->container, false);
841         }
842     }
843 
844     vbasedev->fd = fd;
845     vbasedev->group = group;
846     QLIST_INSERT_HEAD(&group->device_list, vbasedev, next);
847 
848     vbasedev->num_irqs = info->num_irqs;
849     vbasedev->num_regions = info->num_regions;
850     vbasedev->flags = info->flags;
851 
852     trace_vfio_get_device(name, info->flags, info->num_regions, info->num_irqs);
853 
854     vbasedev->reset_works = !!(info->flags & VFIO_DEVICE_FLAGS_RESET);
855 
856     return true;
857 }
858 
859 static void vfio_put_base_device(VFIODevice *vbasedev)
860 {
861     if (!vbasedev->group) {
862         return;
863     }
864     QLIST_REMOVE(vbasedev, next);
865     vbasedev->group = NULL;
866     trace_vfio_put_base_device(vbasedev->fd);
867     close(vbasedev->fd);
868 }
869 
870 static int vfio_device_groupid(VFIODevice *vbasedev, Error **errp)
871 {
872     char *tmp, group_path[PATH_MAX];
873     g_autofree char *group_name = NULL;
874     int ret, groupid;
875     ssize_t len;
876 
877     tmp = g_strdup_printf("%s/iommu_group", vbasedev->sysfsdev);
878     len = readlink(tmp, group_path, sizeof(group_path));
879     g_free(tmp);
880 
881     if (len <= 0 || len >= sizeof(group_path)) {
882         ret = len < 0 ? -errno : -ENAMETOOLONG;
883         error_setg_errno(errp, -ret, "no iommu_group found");
884         return ret;
885     }
886 
887     group_path[len] = 0;
888 
889     group_name = g_path_get_basename(group_path);
890     if (sscanf(group_name, "%d", &groupid) != 1) {
891         error_setg_errno(errp, errno, "failed to read %s", group_path);
892         return -errno;
893     }
894     return groupid;
895 }
896 
897 /*
898  * vfio_attach_device: attach a device to a security context
899  * @name and @vbasedev->name are likely to be different depending
900  * on the type of the device, hence the need for passing @name
901  */
902 static bool vfio_legacy_attach_device(const char *name, VFIODevice *vbasedev,
903                                       AddressSpace *as, Error **errp)
904 {
905     int groupid = vfio_device_groupid(vbasedev, errp);
906     VFIODevice *vbasedev_iter;
907     VFIOGroup *group;
908     VFIOContainerBase *bcontainer;
909 
910     if (groupid < 0) {
911         return false;
912     }
913 
914     trace_vfio_attach_device(vbasedev->name, groupid);
915 
916     if (!vfio_device_hiod_realize(vbasedev, errp)) {
917         return false;
918     }
919 
920     group = vfio_get_group(groupid, as, errp);
921     if (!group) {
922         return false;
923     }
924 
925     QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
926         if (strcmp(vbasedev_iter->name, vbasedev->name) == 0) {
927             error_setg(errp, "device is already attached");
928             vfio_put_group(group);
929             return false;
930         }
931     }
932     if (!vfio_get_device(group, name, vbasedev, errp)) {
933         vfio_put_group(group);
934         return false;
935     }
936 
937     bcontainer = &group->container->bcontainer;
938     vbasedev->bcontainer = bcontainer;
939     QLIST_INSERT_HEAD(&bcontainer->device_list, vbasedev, container_next);
940     QLIST_INSERT_HEAD(&vfio_device_list, vbasedev, global_next);
941 
942     return true;
943 }
944 
945 static void vfio_legacy_detach_device(VFIODevice *vbasedev)
946 {
947     VFIOGroup *group = vbasedev->group;
948 
949     QLIST_REMOVE(vbasedev, global_next);
950     QLIST_REMOVE(vbasedev, container_next);
951     vbasedev->bcontainer = NULL;
952     trace_vfio_detach_device(vbasedev->name, group->groupid);
953     vfio_put_base_device(vbasedev);
954     vfio_put_group(group);
955 }
956 
957 static int vfio_legacy_pci_hot_reset(VFIODevice *vbasedev, bool single)
958 {
959     VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
960     VFIOGroup *group;
961     struct vfio_pci_hot_reset_info *info = NULL;
962     struct vfio_pci_dependent_device *devices;
963     struct vfio_pci_hot_reset *reset;
964     int32_t *fds;
965     int ret, i, count;
966     bool multi = false;
967 
968     trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
969 
970     if (!single) {
971         vfio_pci_pre_reset(vdev);
972     }
973     vdev->vbasedev.needs_reset = false;
974 
975     ret = vfio_pci_get_pci_hot_reset_info(vdev, &info);
976 
977     if (ret) {
978         goto out_single;
979     }
980     devices = &info->devices[0];
981 
982     trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
983 
984     /* Verify that we have all the groups required */
985     for (i = 0; i < info->count; i++) {
986         PCIHostDeviceAddress host;
987         VFIOPCIDevice *tmp;
988         VFIODevice *vbasedev_iter;
989 
990         host.domain = devices[i].segment;
991         host.bus = devices[i].bus;
992         host.slot = PCI_SLOT(devices[i].devfn);
993         host.function = PCI_FUNC(devices[i].devfn);
994 
995         trace_vfio_pci_hot_reset_dep_devices(host.domain,
996                 host.bus, host.slot, host.function, devices[i].group_id);
997 
998         if (vfio_pci_host_match(&host, vdev->vbasedev.name)) {
999             continue;
1000         }
1001 
1002         QLIST_FOREACH(group, &vfio_group_list, next) {
1003             if (group->groupid == devices[i].group_id) {
1004                 break;
1005             }
1006         }
1007 
1008         if (!group) {
1009             if (!vdev->has_pm_reset) {
1010                 error_report("vfio: Cannot reset device %s, "
1011                              "depends on group %d which is not owned.",
1012                              vdev->vbasedev.name, devices[i].group_id);
1013             }
1014             ret = -EPERM;
1015             goto out;
1016         }
1017 
1018         /* Prep dependent devices for reset and clear our marker. */
1019         QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
1020             if (!vbasedev_iter->dev->realized ||
1021                 vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
1022                 continue;
1023             }
1024             tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
1025             if (vfio_pci_host_match(&host, tmp->vbasedev.name)) {
1026                 if (single) {
1027                     ret = -EINVAL;
1028                     goto out_single;
1029                 }
1030                 vfio_pci_pre_reset(tmp);
1031                 tmp->vbasedev.needs_reset = false;
1032                 multi = true;
1033                 break;
1034             }
1035         }
1036     }
1037 
1038     if (!single && !multi) {
1039         ret = -EINVAL;
1040         goto out_single;
1041     }
1042 
1043     /* Determine how many group fds need to be passed */
1044     count = 0;
1045     QLIST_FOREACH(group, &vfio_group_list, next) {
1046         for (i = 0; i < info->count; i++) {
1047             if (group->groupid == devices[i].group_id) {
1048                 count++;
1049                 break;
1050             }
1051         }
1052     }
1053 
1054     reset = g_malloc0(sizeof(*reset) + (count * sizeof(*fds)));
1055     reset->argsz = sizeof(*reset) + (count * sizeof(*fds));
1056     fds = &reset->group_fds[0];
1057 
1058     /* Fill in group fds */
1059     QLIST_FOREACH(group, &vfio_group_list, next) {
1060         for (i = 0; i < info->count; i++) {
1061             if (group->groupid == devices[i].group_id) {
1062                 fds[reset->count++] = group->fd;
1063                 break;
1064             }
1065         }
1066     }
1067 
1068     /* Bus reset! */
1069     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
1070     g_free(reset);
1071     if (ret) {
1072         ret = -errno;
1073     }
1074 
1075     trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
1076                                     ret ? strerror(errno) : "Success");
1077 
1078 out:
1079     /* Re-enable INTx on affected devices */
1080     for (i = 0; i < info->count; i++) {
1081         PCIHostDeviceAddress host;
1082         VFIOPCIDevice *tmp;
1083         VFIODevice *vbasedev_iter;
1084 
1085         host.domain = devices[i].segment;
1086         host.bus = devices[i].bus;
1087         host.slot = PCI_SLOT(devices[i].devfn);
1088         host.function = PCI_FUNC(devices[i].devfn);
1089 
1090         if (vfio_pci_host_match(&host, vdev->vbasedev.name)) {
1091             continue;
1092         }
1093 
1094         QLIST_FOREACH(group, &vfio_group_list, next) {
1095             if (group->groupid == devices[i].group_id) {
1096                 break;
1097             }
1098         }
1099 
1100         if (!group) {
1101             break;
1102         }
1103 
1104         QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
1105             if (!vbasedev_iter->dev->realized ||
1106                 vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
1107                 continue;
1108             }
1109             tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
1110             if (vfio_pci_host_match(&host, tmp->vbasedev.name)) {
1111                 vfio_pci_post_reset(tmp);
1112                 break;
1113             }
1114         }
1115     }
1116 out_single:
1117     if (!single) {
1118         vfio_pci_post_reset(vdev);
1119     }
1120     g_free(info);
1121 
1122     return ret;
1123 }
1124 
1125 static void vfio_iommu_legacy_class_init(ObjectClass *klass, void *data)
1126 {
1127     VFIOIOMMUClass *vioc = VFIO_IOMMU_CLASS(klass);
1128 
1129     vioc->hiod_typename = TYPE_HOST_IOMMU_DEVICE_LEGACY_VFIO;
1130 
1131     vioc->setup = vfio_legacy_setup;
1132     vioc->dma_map = vfio_legacy_dma_map;
1133     vioc->dma_unmap = vfio_legacy_dma_unmap;
1134     vioc->attach_device = vfio_legacy_attach_device;
1135     vioc->detach_device = vfio_legacy_detach_device;
1136     vioc->set_dirty_page_tracking = vfio_legacy_set_dirty_page_tracking;
1137     vioc->query_dirty_bitmap = vfio_legacy_query_dirty_bitmap;
1138     vioc->pci_hot_reset = vfio_legacy_pci_hot_reset;
1139 };
1140 
1141 static bool hiod_legacy_vfio_realize(HostIOMMUDevice *hiod, void *opaque,
1142                                      Error **errp)
1143 {
1144     VFIODevice *vdev = opaque;
1145 
1146     hiod->name = g_strdup(vdev->name);
1147     hiod->agent = opaque;
1148 
1149     return true;
1150 }
1151 
1152 static int hiod_legacy_vfio_get_cap(HostIOMMUDevice *hiod, int cap,
1153                                     Error **errp)
1154 {
1155     switch (cap) {
1156     case HOST_IOMMU_DEVICE_CAP_AW_BITS:
1157         return vfio_device_get_aw_bits(hiod->agent);
1158     default:
1159         error_setg(errp, "%s: unsupported capability %x", hiod->name, cap);
1160         return -EINVAL;
1161     }
1162 }
1163 
1164 static GList *
1165 hiod_legacy_vfio_get_iova_ranges(HostIOMMUDevice *hiod)
1166 {
1167     VFIODevice *vdev = hiod->agent;
1168 
1169     g_assert(vdev);
1170     return vfio_container_get_iova_ranges(vdev->bcontainer);
1171 }
1172 
1173 static uint64_t
1174 hiod_legacy_vfio_get_page_size_mask(HostIOMMUDevice *hiod)
1175 {
1176     VFIODevice *vdev = hiod->agent;
1177 
1178     g_assert(vdev);
1179     return vfio_container_get_page_size_mask(vdev->bcontainer);
1180 }
1181 
1182 static void vfio_iommu_legacy_instance_init(Object *obj)
1183 {
1184     VFIOContainer *container = VFIO_IOMMU_LEGACY(obj);
1185 
1186     QLIST_INIT(&container->group_list);
1187 }
1188 
1189 static void hiod_legacy_vfio_class_init(ObjectClass *oc, void *data)
1190 {
1191     HostIOMMUDeviceClass *hioc = HOST_IOMMU_DEVICE_CLASS(oc);
1192 
1193     hioc->realize = hiod_legacy_vfio_realize;
1194     hioc->get_cap = hiod_legacy_vfio_get_cap;
1195     hioc->get_iova_ranges = hiod_legacy_vfio_get_iova_ranges;
1196     hioc->get_page_size_mask = hiod_legacy_vfio_get_page_size_mask;
1197 };
1198 
1199 static const TypeInfo types[] = {
1200     {
1201         .name = TYPE_VFIO_IOMMU_LEGACY,
1202         .parent = TYPE_VFIO_IOMMU,
1203         .instance_init = vfio_iommu_legacy_instance_init,
1204         .instance_size = sizeof(VFIOContainer),
1205         .class_init = vfio_iommu_legacy_class_init,
1206     }, {
1207         .name = TYPE_HOST_IOMMU_DEVICE_LEGACY_VFIO,
1208         .parent = TYPE_HOST_IOMMU_DEVICE,
1209         .class_init = hiod_legacy_vfio_class_init,
1210     }
1211 };
1212 
1213 DEFINE_TYPES(types)
1214