xref: /openbmc/qemu/hw/vfio/container.c (revision 07c08661)
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 "exec/address-spaces.h"
27 #include "exec/memory.h"
28 #include "exec/ram_addr.h"
29 #include "hw/hw.h"
30 #include "qemu/error-report.h"
31 #include "qemu/range.h"
32 #include "sysemu/reset.h"
33 #include "trace.h"
34 #include "qapi/error.h"
35 #include "pci.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_running_and_mig_active(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         error_report("VFIO_UNMAP_DMA failed: %s", strerror(errno));
164         return -errno;
165     }
166 
167     if (need_dirty_sync) {
168         ret = vfio_get_dirty_bitmap(bcontainer, iova, size,
169                                     iotlb->translated_addr, &local_err);
170         if (ret) {
171             error_report_err(local_err);
172             return ret;
173         }
174     }
175 
176     return 0;
177 }
178 
179 static int vfio_legacy_dma_map(const VFIOContainerBase *bcontainer, hwaddr iova,
180                                ram_addr_t size, void *vaddr, bool readonly)
181 {
182     const VFIOContainer *container = container_of(bcontainer, VFIOContainer,
183                                                   bcontainer);
184     struct vfio_iommu_type1_dma_map map = {
185         .argsz = sizeof(map),
186         .flags = VFIO_DMA_MAP_FLAG_READ,
187         .vaddr = (__u64)(uintptr_t)vaddr,
188         .iova = iova,
189         .size = size,
190     };
191 
192     if (!readonly) {
193         map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
194     }
195 
196     /*
197      * Try the mapping, if it fails with EBUSY, unmap the region and try
198      * again.  This shouldn't be necessary, but we sometimes see it in
199      * the VGA ROM space.
200      */
201     if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
202         (errno == EBUSY &&
203          vfio_legacy_dma_unmap(bcontainer, iova, size, NULL) == 0 &&
204          ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
205         return 0;
206     }
207 
208     error_report("VFIO_MAP_DMA failed: %s", strerror(errno));
209     return -errno;
210 }
211 
212 static int
213 vfio_legacy_set_dirty_page_tracking(const VFIOContainerBase *bcontainer,
214                                     bool start, Error **errp)
215 {
216     const VFIOContainer *container = container_of(bcontainer, VFIOContainer,
217                                                   bcontainer);
218     int ret;
219     struct vfio_iommu_type1_dirty_bitmap dirty = {
220         .argsz = sizeof(dirty),
221     };
222 
223     if (start) {
224         dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_START;
225     } else {
226         dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP;
227     }
228 
229     ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, &dirty);
230     if (ret) {
231         ret = -errno;
232         error_setg_errno(errp, errno, "Failed to set dirty tracking flag 0x%x",
233                          dirty.flags);
234     }
235 
236     return ret;
237 }
238 
239 static int vfio_legacy_query_dirty_bitmap(const VFIOContainerBase *bcontainer,
240                       VFIOBitmap *vbmap, hwaddr iova, hwaddr size, Error **errp)
241 {
242     const VFIOContainer *container = container_of(bcontainer, VFIOContainer,
243                                                   bcontainer);
244     struct vfio_iommu_type1_dirty_bitmap *dbitmap;
245     struct vfio_iommu_type1_dirty_bitmap_get *range;
246     int ret;
247 
248     dbitmap = g_malloc0(sizeof(*dbitmap) + sizeof(*range));
249 
250     dbitmap->argsz = sizeof(*dbitmap) + sizeof(*range);
251     dbitmap->flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
252     range = (struct vfio_iommu_type1_dirty_bitmap_get *)&dbitmap->data;
253     range->iova = iova;
254     range->size = size;
255 
256     /*
257      * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
258      * qemu_real_host_page_size to mark those dirty. Hence set bitmap's pgsize
259      * to qemu_real_host_page_size.
260      */
261     range->bitmap.pgsize = qemu_real_host_page_size();
262     range->bitmap.size = vbmap->size;
263     range->bitmap.data = (__u64 *)vbmap->bitmap;
264 
265     ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, dbitmap);
266     if (ret) {
267         ret = -errno;
268         error_setg_errno(errp, errno,
269                          "Failed to get dirty bitmap for iova: 0x%"PRIx64
270                          " size: 0x%"PRIx64, (uint64_t)range->iova,
271                          (uint64_t)range->size);
272     }
273 
274     g_free(dbitmap);
275 
276     return ret;
277 }
278 
279 static struct vfio_info_cap_header *
280 vfio_get_iommu_type1_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
281 {
282     if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
283         return NULL;
284     }
285 
286     return vfio_get_cap((void *)info, info->cap_offset, id);
287 }
288 
289 bool vfio_get_info_dma_avail(struct vfio_iommu_type1_info *info,
290                              unsigned int *avail)
291 {
292     struct vfio_info_cap_header *hdr;
293     struct vfio_iommu_type1_info_dma_avail *cap;
294 
295     /* If the capability cannot be found, assume no DMA limiting */
296     hdr = vfio_get_iommu_type1_info_cap(info,
297                                         VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL);
298     if (!hdr) {
299         return false;
300     }
301 
302     if (avail != NULL) {
303         cap = (void *) hdr;
304         *avail = cap->avail;
305     }
306 
307     return true;
308 }
309 
310 static bool vfio_get_info_iova_range(struct vfio_iommu_type1_info *info,
311                                      VFIOContainerBase *bcontainer)
312 {
313     struct vfio_info_cap_header *hdr;
314     struct vfio_iommu_type1_info_cap_iova_range *cap;
315 
316     hdr = vfio_get_iommu_type1_info_cap(info,
317                                         VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE);
318     if (!hdr) {
319         return false;
320     }
321 
322     cap = (void *)hdr;
323 
324     for (int i = 0; i < cap->nr_iovas; i++) {
325         Range *range = g_new(Range, 1);
326 
327         range_set_bounds(range, cap->iova_ranges[i].start,
328                          cap->iova_ranges[i].end);
329         bcontainer->iova_ranges =
330             range_list_insert(bcontainer->iova_ranges, range);
331     }
332 
333     return true;
334 }
335 
336 static void vfio_kvm_device_add_group(VFIOGroup *group)
337 {
338     Error *err = NULL;
339 
340     if (vfio_kvm_device_add_fd(group->fd, &err)) {
341         error_reportf_err(err, "group ID %d: ", group->groupid);
342     }
343 }
344 
345 static void vfio_kvm_device_del_group(VFIOGroup *group)
346 {
347     Error *err = NULL;
348 
349     if (vfio_kvm_device_del_fd(group->fd, &err)) {
350         error_reportf_err(err, "group ID %d: ", group->groupid);
351     }
352 }
353 
354 /*
355  * vfio_get_iommu_type - selects the richest iommu_type (v2 first)
356  */
357 static int vfio_get_iommu_type(VFIOContainer *container,
358                                Error **errp)
359 {
360     int iommu_types[] = { VFIO_TYPE1v2_IOMMU, VFIO_TYPE1_IOMMU,
361                           VFIO_SPAPR_TCE_v2_IOMMU, VFIO_SPAPR_TCE_IOMMU };
362     int i;
363 
364     for (i = 0; i < ARRAY_SIZE(iommu_types); i++) {
365         if (ioctl(container->fd, VFIO_CHECK_EXTENSION, iommu_types[i])) {
366             return iommu_types[i];
367         }
368     }
369     error_setg(errp, "No available IOMMU models");
370     return -EINVAL;
371 }
372 
373 /*
374  * vfio_get_iommu_ops - get a VFIOIOMMUClass associated with a type
375  */
376 static const VFIOIOMMUClass *vfio_get_iommu_class(int iommu_type, Error **errp)
377 {
378     ObjectClass *klass = NULL;
379 
380     switch (iommu_type) {
381     case VFIO_TYPE1v2_IOMMU:
382     case VFIO_TYPE1_IOMMU:
383         klass = object_class_by_name(TYPE_VFIO_IOMMU_LEGACY);
384         break;
385     case VFIO_SPAPR_TCE_v2_IOMMU:
386     case VFIO_SPAPR_TCE_IOMMU:
387         klass = object_class_by_name(TYPE_VFIO_IOMMU_SPAPR);
388         break;
389     default:
390         g_assert_not_reached();
391     };
392 
393     return VFIO_IOMMU_CLASS(klass);
394 }
395 
396 static bool vfio_set_iommu(VFIOContainer *container, int group_fd,
397                            VFIOAddressSpace *space, Error **errp)
398 {
399     int iommu_type;
400     const VFIOIOMMUClass *vioc;
401 
402     iommu_type = vfio_get_iommu_type(container, errp);
403     if (iommu_type < 0) {
404         return false;
405     }
406 
407     if (ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
408         error_setg_errno(errp, errno, "Failed to set group container");
409         return false;
410     }
411 
412     while (ioctl(container->fd, VFIO_SET_IOMMU, iommu_type)) {
413         if (iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
414             /*
415              * On sPAPR, despite the IOMMU subdriver always advertises v1 and
416              * v2, the running platform may not support v2 and there is no
417              * way to guess it until an IOMMU group gets added to the container.
418              * So in case it fails with v2, try v1 as a fallback.
419              */
420             iommu_type = VFIO_SPAPR_TCE_IOMMU;
421             continue;
422         }
423         error_setg_errno(errp, errno, "Failed to set iommu for container");
424         return false;
425     }
426 
427     container->iommu_type = iommu_type;
428 
429     vioc = vfio_get_iommu_class(iommu_type, errp);
430     if (!vioc) {
431         error_setg(errp, "No available IOMMU models");
432         return false;
433     }
434 
435     vfio_container_init(&container->bcontainer, space, vioc);
436     return true;
437 }
438 
439 static int vfio_get_iommu_info(VFIOContainer *container,
440                                struct vfio_iommu_type1_info **info)
441 {
442 
443     size_t argsz = sizeof(struct vfio_iommu_type1_info);
444 
445     *info = g_new0(struct vfio_iommu_type1_info, 1);
446 again:
447     (*info)->argsz = argsz;
448 
449     if (ioctl(container->fd, VFIO_IOMMU_GET_INFO, *info)) {
450         g_free(*info);
451         *info = NULL;
452         return -errno;
453     }
454 
455     if (((*info)->argsz > argsz)) {
456         argsz = (*info)->argsz;
457         *info = g_realloc(*info, argsz);
458         goto again;
459     }
460 
461     return 0;
462 }
463 
464 static struct vfio_info_cap_header *
465 vfio_get_iommu_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
466 {
467     struct vfio_info_cap_header *hdr;
468     void *ptr = info;
469 
470     if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
471         return NULL;
472     }
473 
474     for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
475         if (hdr->id == id) {
476             return hdr;
477         }
478     }
479 
480     return NULL;
481 }
482 
483 static void vfio_get_iommu_info_migration(VFIOContainer *container,
484                                           struct vfio_iommu_type1_info *info)
485 {
486     struct vfio_info_cap_header *hdr;
487     struct vfio_iommu_type1_info_cap_migration *cap_mig;
488     VFIOContainerBase *bcontainer = &container->bcontainer;
489 
490     hdr = vfio_get_iommu_info_cap(info, VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION);
491     if (!hdr) {
492         return;
493     }
494 
495     cap_mig = container_of(hdr, struct vfio_iommu_type1_info_cap_migration,
496                             header);
497 
498     /*
499      * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
500      * qemu_real_host_page_size to mark those dirty.
501      */
502     if (cap_mig->pgsize_bitmap & qemu_real_host_page_size()) {
503         bcontainer->dirty_pages_supported = true;
504         bcontainer->max_dirty_bitmap_size = cap_mig->max_dirty_bitmap_size;
505         bcontainer->dirty_pgsizes = cap_mig->pgsize_bitmap;
506     }
507 }
508 
509 static bool vfio_legacy_setup(VFIOContainerBase *bcontainer, Error **errp)
510 {
511     VFIOContainer *container = container_of(bcontainer, VFIOContainer,
512                                             bcontainer);
513     g_autofree struct vfio_iommu_type1_info *info = NULL;
514     int ret;
515 
516     ret = vfio_get_iommu_info(container, &info);
517     if (ret) {
518         error_setg_errno(errp, -ret, "Failed to get VFIO IOMMU info");
519         return false;
520     }
521 
522     if (info->flags & VFIO_IOMMU_INFO_PGSIZES) {
523         bcontainer->pgsizes = info->iova_pgsizes;
524     } else {
525         bcontainer->pgsizes = qemu_real_host_page_size();
526     }
527 
528     if (!vfio_get_info_dma_avail(info, &bcontainer->dma_max_mappings)) {
529         bcontainer->dma_max_mappings = 65535;
530     }
531 
532     vfio_get_info_iova_range(info, bcontainer);
533 
534     vfio_get_iommu_info_migration(container, info);
535     return true;
536 }
537 
538 static bool vfio_connect_container(VFIOGroup *group, AddressSpace *as,
539                                    Error **errp)
540 {
541     VFIOContainer *container;
542     VFIOContainerBase *bcontainer;
543     int ret, fd;
544     VFIOAddressSpace *space;
545 
546     space = vfio_get_address_space(as);
547 
548     /*
549      * VFIO is currently incompatible with discarding of RAM insofar as the
550      * madvise to purge (zap) the page from QEMU's address space does not
551      * interact with the memory API and therefore leaves stale virtual to
552      * physical mappings in the IOMMU if the page was previously pinned.  We
553      * therefore set discarding broken for each group added to a container,
554      * whether the container is used individually or shared.  This provides
555      * us with options to allow devices within a group to opt-in and allow
556      * discarding, so long as it is done consistently for a group (for instance
557      * if the device is an mdev device where it is known that the host vendor
558      * driver will never pin pages outside of the working set of the guest
559      * driver, which would thus not be discarding candidates).
560      *
561      * The first opportunity to induce pinning occurs here where we attempt to
562      * attach the group to existing containers within the AddressSpace.  If any
563      * pages are already zapped from the virtual address space, such as from
564      * previous discards, new pinning will cause valid mappings to be
565      * re-established.  Likewise, when the overall MemoryListener for a new
566      * container is registered, a replay of mappings within the AddressSpace
567      * will occur, re-establishing any previously zapped pages as well.
568      *
569      * Especially virtio-balloon is currently only prevented from discarding
570      * new memory, it will not yet set ram_block_discard_set_required() and
571      * therefore, neither stops us here or deals with the sudden memory
572      * consumption of inflated memory.
573      *
574      * We do support discarding of memory coordinated via the RamDiscardManager
575      * with some IOMMU types. vfio_ram_block_discard_disable() handles the
576      * details once we know which type of IOMMU we are using.
577      */
578 
579     QLIST_FOREACH(bcontainer, &space->containers, next) {
580         container = container_of(bcontainer, VFIOContainer, bcontainer);
581         if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
582             ret = vfio_ram_block_discard_disable(container, true);
583             if (ret) {
584                 error_setg_errno(errp, -ret,
585                                  "Cannot set discarding of RAM broken");
586                 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER,
587                           &container->fd)) {
588                     error_report("vfio: error disconnecting group %d from"
589                                  " container", group->groupid);
590                 }
591                 return false;
592             }
593             group->container = container;
594             QLIST_INSERT_HEAD(&container->group_list, group, container_next);
595             vfio_kvm_device_add_group(group);
596             return true;
597         }
598     }
599 
600     fd = qemu_open_old("/dev/vfio/vfio", O_RDWR);
601     if (fd < 0) {
602         error_setg_errno(errp, errno, "failed to open /dev/vfio/vfio");
603         goto put_space_exit;
604     }
605 
606     ret = ioctl(fd, VFIO_GET_API_VERSION);
607     if (ret != VFIO_API_VERSION) {
608         error_setg(errp, "supported vfio version: %d, "
609                    "reported version: %d", VFIO_API_VERSION, ret);
610         goto close_fd_exit;
611     }
612 
613     container = g_malloc0(sizeof(*container));
614     container->fd = fd;
615     bcontainer = &container->bcontainer;
616 
617     if (!vfio_set_iommu(container, group->fd, space, errp)) {
618         goto free_container_exit;
619     }
620 
621     if (!vfio_cpr_register_container(bcontainer, errp)) {
622         goto free_container_exit;
623     }
624 
625     ret = vfio_ram_block_discard_disable(container, true);
626     if (ret) {
627         error_setg_errno(errp, -ret, "Cannot set discarding of RAM broken");
628         goto unregister_container_exit;
629     }
630 
631     assert(bcontainer->ops->setup);
632 
633     if (!bcontainer->ops->setup(bcontainer, errp)) {
634         goto enable_discards_exit;
635     }
636 
637     vfio_kvm_device_add_group(group);
638 
639     QLIST_INIT(&container->group_list);
640     QLIST_INSERT_HEAD(&space->containers, bcontainer, next);
641 
642     group->container = container;
643     QLIST_INSERT_HEAD(&container->group_list, group, container_next);
644 
645     bcontainer->listener = vfio_memory_listener;
646     memory_listener_register(&bcontainer->listener, bcontainer->space->as);
647 
648     if (bcontainer->error) {
649         error_propagate_prepend(errp, bcontainer->error,
650             "memory listener initialization failed: ");
651         goto listener_release_exit;
652     }
653 
654     bcontainer->initialized = true;
655 
656     return true;
657 listener_release_exit:
658     QLIST_REMOVE(group, container_next);
659     QLIST_REMOVE(bcontainer, next);
660     vfio_kvm_device_del_group(group);
661     memory_listener_unregister(&bcontainer->listener);
662     if (bcontainer->ops->release) {
663         bcontainer->ops->release(bcontainer);
664     }
665 
666 enable_discards_exit:
667     vfio_ram_block_discard_disable(container, false);
668 
669 unregister_container_exit:
670     vfio_cpr_unregister_container(bcontainer);
671 
672 free_container_exit:
673     g_free(container);
674 
675 close_fd_exit:
676     close(fd);
677 
678 put_space_exit:
679     vfio_put_address_space(space);
680 
681     return false;
682 }
683 
684 static void vfio_disconnect_container(VFIOGroup *group)
685 {
686     VFIOContainer *container = group->container;
687     VFIOContainerBase *bcontainer = &container->bcontainer;
688 
689     QLIST_REMOVE(group, container_next);
690     group->container = NULL;
691 
692     /*
693      * Explicitly release the listener first before unset container,
694      * since unset may destroy the backend container if it's the last
695      * group.
696      */
697     if (QLIST_EMPTY(&container->group_list)) {
698         memory_listener_unregister(&bcontainer->listener);
699         if (bcontainer->ops->release) {
700             bcontainer->ops->release(bcontainer);
701         }
702     }
703 
704     if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
705         error_report("vfio: error disconnecting group %d from container",
706                      group->groupid);
707     }
708 
709     if (QLIST_EMPTY(&container->group_list)) {
710         VFIOAddressSpace *space = bcontainer->space;
711 
712         vfio_container_destroy(bcontainer);
713 
714         trace_vfio_disconnect_container(container->fd);
715         vfio_cpr_unregister_container(bcontainer);
716         close(container->fd);
717         g_free(container);
718 
719         vfio_put_address_space(space);
720     }
721 }
722 
723 static VFIOGroup *vfio_get_group(int groupid, AddressSpace *as, Error **errp)
724 {
725     ERRP_GUARD();
726     VFIOGroup *group;
727     char path[32];
728     struct vfio_group_status status = { .argsz = sizeof(status) };
729 
730     QLIST_FOREACH(group, &vfio_group_list, next) {
731         if (group->groupid == groupid) {
732             /* Found it.  Now is it already in the right context? */
733             if (group->container->bcontainer.space->as == as) {
734                 return group;
735             } else {
736                 error_setg(errp, "group %d used in multiple address spaces",
737                            group->groupid);
738                 return NULL;
739             }
740         }
741     }
742 
743     group = g_malloc0(sizeof(*group));
744 
745     snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
746     group->fd = qemu_open_old(path, O_RDWR);
747     if (group->fd < 0) {
748         error_setg_errno(errp, errno, "failed to open %s", path);
749         goto free_group_exit;
750     }
751 
752     if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
753         error_setg_errno(errp, errno, "failed to get group %d status", groupid);
754         goto close_fd_exit;
755     }
756 
757     if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
758         error_setg(errp, "group %d is not viable", groupid);
759         error_append_hint(errp,
760                           "Please ensure all devices within the iommu_group "
761                           "are bound to their vfio bus driver.\n");
762         goto close_fd_exit;
763     }
764 
765     group->groupid = groupid;
766     QLIST_INIT(&group->device_list);
767 
768     if (!vfio_connect_container(group, as, errp)) {
769         error_prepend(errp, "failed to setup container for group %d: ",
770                       groupid);
771         goto close_fd_exit;
772     }
773 
774     QLIST_INSERT_HEAD(&vfio_group_list, group, next);
775 
776     return group;
777 
778 close_fd_exit:
779     close(group->fd);
780 
781 free_group_exit:
782     g_free(group);
783 
784     return NULL;
785 }
786 
787 static void vfio_put_group(VFIOGroup *group)
788 {
789     if (!group || !QLIST_EMPTY(&group->device_list)) {
790         return;
791     }
792 
793     if (!group->ram_block_discard_allowed) {
794         vfio_ram_block_discard_disable(group->container, false);
795     }
796     vfio_kvm_device_del_group(group);
797     vfio_disconnect_container(group);
798     QLIST_REMOVE(group, next);
799     trace_vfio_put_group(group->fd);
800     close(group->fd);
801     g_free(group);
802 }
803 
804 static bool vfio_get_device(VFIOGroup *group, const char *name,
805                             VFIODevice *vbasedev, Error **errp)
806 {
807     g_autofree struct vfio_device_info *info = NULL;
808     int fd;
809 
810     fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
811     if (fd < 0) {
812         error_setg_errno(errp, errno, "error getting device from group %d",
813                          group->groupid);
814         error_append_hint(errp,
815                       "Verify all devices in group %d are bound to vfio-<bus> "
816                       "or pci-stub and not already in use\n", group->groupid);
817         return false;
818     }
819 
820     info = vfio_get_device_info(fd);
821     if (!info) {
822         error_setg_errno(errp, errno, "error getting device info");
823         close(fd);
824         return false;
825     }
826 
827     /*
828      * Set discarding of RAM as not broken for this group if the driver knows
829      * the device operates compatibly with discarding.  Setting must be
830      * consistent per group, but since compatibility is really only possible
831      * with mdev currently, we expect singleton groups.
832      */
833     if (vbasedev->ram_block_discard_allowed !=
834         group->ram_block_discard_allowed) {
835         if (!QLIST_EMPTY(&group->device_list)) {
836             error_setg(errp, "Inconsistent setting of support for discarding "
837                        "RAM (e.g., balloon) within group");
838             close(fd);
839             return false;
840         }
841 
842         if (!group->ram_block_discard_allowed) {
843             group->ram_block_discard_allowed = true;
844             vfio_ram_block_discard_disable(group->container, false);
845         }
846     }
847 
848     vbasedev->fd = fd;
849     vbasedev->group = group;
850     QLIST_INSERT_HEAD(&group->device_list, vbasedev, next);
851 
852     vbasedev->num_irqs = info->num_irqs;
853     vbasedev->num_regions = info->num_regions;
854     vbasedev->flags = info->flags;
855 
856     trace_vfio_get_device(name, info->flags, info->num_regions, info->num_irqs);
857 
858     vbasedev->reset_works = !!(info->flags & VFIO_DEVICE_FLAGS_RESET);
859 
860     return true;
861 }
862 
863 static void vfio_put_base_device(VFIODevice *vbasedev)
864 {
865     if (!vbasedev->group) {
866         return;
867     }
868     QLIST_REMOVE(vbasedev, next);
869     vbasedev->group = NULL;
870     trace_vfio_put_base_device(vbasedev->fd);
871     close(vbasedev->fd);
872 }
873 
874 static int vfio_device_groupid(VFIODevice *vbasedev, Error **errp)
875 {
876     char *tmp, group_path[PATH_MAX];
877     g_autofree char *group_name = NULL;
878     int ret, groupid;
879     ssize_t len;
880 
881     tmp = g_strdup_printf("%s/iommu_group", vbasedev->sysfsdev);
882     len = readlink(tmp, group_path, sizeof(group_path));
883     g_free(tmp);
884 
885     if (len <= 0 || len >= sizeof(group_path)) {
886         ret = len < 0 ? -errno : -ENAMETOOLONG;
887         error_setg_errno(errp, -ret, "no iommu_group found");
888         return ret;
889     }
890 
891     group_path[len] = 0;
892 
893     group_name = g_path_get_basename(group_path);
894     if (sscanf(group_name, "%d", &groupid) != 1) {
895         error_setg_errno(errp, errno, "failed to read %s", group_path);
896         return -errno;
897     }
898     return groupid;
899 }
900 
901 /*
902  * vfio_attach_device: attach a device to a security context
903  * @name and @vbasedev->name are likely to be different depending
904  * on the type of the device, hence the need for passing @name
905  */
906 static bool vfio_legacy_attach_device(const char *name, VFIODevice *vbasedev,
907                                       AddressSpace *as, Error **errp)
908 {
909     int groupid = vfio_device_groupid(vbasedev, errp);
910     VFIODevice *vbasedev_iter;
911     VFIOGroup *group;
912     VFIOContainerBase *bcontainer;
913 
914     if (groupid < 0) {
915         return false;
916     }
917 
918     trace_vfio_attach_device(vbasedev->name, groupid);
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->setup = vfio_legacy_setup;
1130     vioc->dma_map = vfio_legacy_dma_map;
1131     vioc->dma_unmap = vfio_legacy_dma_unmap;
1132     vioc->attach_device = vfio_legacy_attach_device;
1133     vioc->detach_device = vfio_legacy_detach_device;
1134     vioc->set_dirty_page_tracking = vfio_legacy_set_dirty_page_tracking;
1135     vioc->query_dirty_bitmap = vfio_legacy_query_dirty_bitmap;
1136     vioc->pci_hot_reset = vfio_legacy_pci_hot_reset;
1137 };
1138 
1139 static const TypeInfo types[] = {
1140     {
1141         .name = TYPE_VFIO_IOMMU_LEGACY,
1142         .parent = TYPE_VFIO_IOMMU,
1143         .class_init = vfio_iommu_legacy_class_init,
1144     },
1145 };
1146 
1147 DEFINE_TYPES(types)
1148