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