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