vfio/container: Remove VFIOContainerBase::ops
[qemu/armbru.git] / hw / vfio / container.c
bloba2f5fbad00cd228e27a47df5cd683dbb34296113
1 /*
2 * generic functions used by VFIO devices
4 * Copyright Red Hat, Inc. 2012
6 * Authors:
7 * Alex Williamson <alex.williamson@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
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)
21 #include "qemu/osdep.h"
22 #include <sys/ioctl.h>
23 #include <linux/vfio.h>
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"
37 VFIOGroupList vfio_group_list =
38 QLIST_HEAD_INITIALIZER(vfio_group_list);
40 static int vfio_ram_block_discard_disable(VFIOContainer *container, bool state)
42 switch (container->iommu_type) {
43 case VFIO_TYPE1v2_IOMMU:
44 case VFIO_TYPE1_IOMMU:
46 * We support coordinated discarding of RAM via the RamDiscardManager.
48 return ram_block_uncoordinated_discard_disable(state);
49 default:
51 * VFIO_SPAPR_TCE_IOMMU most probably works just fine with
52 * RamDiscardManager, however, it is completely untested.
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.
59 return ram_block_discard_disable(state);
63 static int vfio_dma_unmap_bitmap(const VFIOContainer *container,
64 hwaddr iova, ram_addr_t size,
65 IOMMUTLBEntry *iotlb)
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;
73 ret = vfio_bitmap_alloc(&vbmap, size);
74 if (ret) {
75 return ret;
78 unmap = g_malloc0(sizeof(*unmap) + sizeof(*bitmap));
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;
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.
91 bitmap->pgsize = qemu_real_host_page_size();
92 bitmap->size = vbmap.size;
93 bitmap->data = (__u64 *)vbmap.bitmap;
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;
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");
109 unmap_exit:
110 g_free(unmap);
111 g_free(vbmap.bitmap);
113 return ret;
117 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
119 static int vfio_legacy_dma_unmap(const VFIOContainerBase *bcontainer,
120 hwaddr iova, ram_addr_t size,
121 IOMMUTLBEntry *iotlb)
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,
131 bool need_dirty_sync = false;
132 int ret;
133 Error *local_err = NULL;
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);
141 need_dirty_sync = true;
144 while (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
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.
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;
163 error_report("VFIO_UNMAP_DMA failed: %s", strerror(errno));
164 return -errno;
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;
176 return 0;
179 static int vfio_legacy_dma_map(const VFIOContainerBase *bcontainer, hwaddr iova,
180 ram_addr_t size, void *vaddr, bool readonly)
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,
192 if (!readonly) {
193 map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
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.
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;
208 error_report("VFIO_MAP_DMA failed: %s", strerror(errno));
209 return -errno;
212 static int
213 vfio_legacy_set_dirty_page_tracking(const VFIOContainerBase *bcontainer,
214 bool start, Error **errp)
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),
223 if (start) {
224 dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_START;
225 } else {
226 dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP;
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);
236 return ret;
239 static int vfio_legacy_query_dirty_bitmap(const VFIOContainerBase *bcontainer,
240 VFIOBitmap *vbmap, hwaddr iova, hwaddr size, Error **errp)
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;
248 dbitmap = g_malloc0(sizeof(*dbitmap) + sizeof(*range));
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;
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.
261 range->bitmap.pgsize = qemu_real_host_page_size();
262 range->bitmap.size = vbmap->size;
263 range->bitmap.data = (__u64 *)vbmap->bitmap;
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);
274 g_free(dbitmap);
276 return ret;
279 static struct vfio_info_cap_header *
280 vfio_get_iommu_type1_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
282 if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
283 return NULL;
286 return vfio_get_cap((void *)info, info->cap_offset, id);
289 bool vfio_get_info_dma_avail(struct vfio_iommu_type1_info *info,
290 unsigned int *avail)
292 struct vfio_info_cap_header *hdr;
293 struct vfio_iommu_type1_info_dma_avail *cap;
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;
302 if (avail != NULL) {
303 cap = (void *) hdr;
304 *avail = cap->avail;
307 return true;
310 static bool vfio_get_info_iova_range(struct vfio_iommu_type1_info *info,
311 VFIOContainerBase *bcontainer)
313 struct vfio_info_cap_header *hdr;
314 struct vfio_iommu_type1_info_cap_iova_range *cap;
316 hdr = vfio_get_iommu_type1_info_cap(info,
317 VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE);
318 if (!hdr) {
319 return false;
322 cap = (void *)hdr;
324 for (int i = 0; i < cap->nr_iovas; i++) {
325 Range *range = g_new(Range, 1);
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);
333 return true;
336 static void vfio_kvm_device_add_group(VFIOGroup *group)
338 Error *err = NULL;
340 if (vfio_kvm_device_add_fd(group->fd, &err)) {
341 error_reportf_err(err, "group ID %d: ", group->groupid);
345 static void vfio_kvm_device_del_group(VFIOGroup *group)
347 Error *err = NULL;
349 if (vfio_kvm_device_del_fd(group->fd, &err)) {
350 error_reportf_err(err, "group ID %d: ", group->groupid);
355 * vfio_get_iommu_type - selects the richest iommu_type (v2 first)
357 static int vfio_get_iommu_type(int container_fd,
358 Error **errp)
360 int iommu_types[] = { VFIO_TYPE1v2_IOMMU, VFIO_TYPE1_IOMMU,
361 VFIO_SPAPR_TCE_v2_IOMMU, VFIO_SPAPR_TCE_IOMMU };
362 int i;
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];
369 error_setg(errp, "No available IOMMU models");
370 return -EINVAL;
374 * vfio_get_iommu_ops - get a VFIOIOMMUClass associated with a type
376 static const char *vfio_get_iommu_class_name(int iommu_type)
378 switch (iommu_type) {
379 case VFIO_TYPE1v2_IOMMU:
380 case VFIO_TYPE1_IOMMU:
381 return TYPE_VFIO_IOMMU_LEGACY;
382 break;
383 case VFIO_SPAPR_TCE_v2_IOMMU:
384 case VFIO_SPAPR_TCE_IOMMU:
385 return TYPE_VFIO_IOMMU_SPAPR;
386 break;
387 default:
388 g_assert_not_reached();
392 static bool vfio_set_iommu(int container_fd, int group_fd,
393 int *iommu_type, Error **errp)
395 if (ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container_fd)) {
396 error_setg_errno(errp, errno, "Failed to set group container");
397 return false;
400 while (ioctl(container_fd, VFIO_SET_IOMMU, *iommu_type)) {
401 if (*iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
403 * On sPAPR, despite the IOMMU subdriver always advertises v1 and
404 * v2, the running platform may not support v2 and there is no
405 * way to guess it until an IOMMU group gets added to the container.
406 * So in case it fails with v2, try v1 as a fallback.
408 *iommu_type = VFIO_SPAPR_TCE_IOMMU;
409 continue;
411 error_setg_errno(errp, errno, "Failed to set iommu for container");
412 return false;
415 return true;
418 static VFIOContainer *vfio_create_container(int fd, VFIOGroup *group,
419 Error **errp)
421 int iommu_type;
422 const VFIOIOMMUClass *vioc;
423 const char *vioc_name;
424 VFIOContainer *container;
426 iommu_type = vfio_get_iommu_type(fd, errp);
427 if (iommu_type < 0) {
428 return NULL;
431 if (!vfio_set_iommu(fd, group->fd, &iommu_type, errp)) {
432 return NULL;
435 vioc_name = vfio_get_iommu_class_name(iommu_type);
436 vioc = VFIO_IOMMU_CLASS(object_class_by_name(vioc_name));
438 container = VFIO_IOMMU_LEGACY(object_new(vioc_name));
439 container->fd = fd;
440 container->iommu_type = iommu_type;
441 vfio_container_init(&container->bcontainer, vioc);
442 return container;
445 static int vfio_get_iommu_info(VFIOContainer *container,
446 struct vfio_iommu_type1_info **info)
449 size_t argsz = sizeof(struct vfio_iommu_type1_info);
451 *info = g_new0(struct vfio_iommu_type1_info, 1);
452 again:
453 (*info)->argsz = argsz;
455 if (ioctl(container->fd, VFIO_IOMMU_GET_INFO, *info)) {
456 g_free(*info);
457 *info = NULL;
458 return -errno;
461 if (((*info)->argsz > argsz)) {
462 argsz = (*info)->argsz;
463 *info = g_realloc(*info, argsz);
464 goto again;
467 return 0;
470 static struct vfio_info_cap_header *
471 vfio_get_iommu_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
473 struct vfio_info_cap_header *hdr;
474 void *ptr = info;
476 if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
477 return NULL;
480 for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
481 if (hdr->id == id) {
482 return hdr;
486 return NULL;
489 static void vfio_get_iommu_info_migration(VFIOContainer *container,
490 struct vfio_iommu_type1_info *info)
492 struct vfio_info_cap_header *hdr;
493 struct vfio_iommu_type1_info_cap_migration *cap_mig;
494 VFIOContainerBase *bcontainer = &container->bcontainer;
496 hdr = vfio_get_iommu_info_cap(info, VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION);
497 if (!hdr) {
498 return;
501 cap_mig = container_of(hdr, struct vfio_iommu_type1_info_cap_migration,
502 header);
505 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
506 * qemu_real_host_page_size to mark those dirty.
508 if (cap_mig->pgsize_bitmap & qemu_real_host_page_size()) {
509 bcontainer->dirty_pages_supported = true;
510 bcontainer->max_dirty_bitmap_size = cap_mig->max_dirty_bitmap_size;
511 bcontainer->dirty_pgsizes = cap_mig->pgsize_bitmap;
515 static bool vfio_legacy_setup(VFIOContainerBase *bcontainer, Error **errp)
517 VFIOContainer *container = container_of(bcontainer, VFIOContainer,
518 bcontainer);
519 g_autofree struct vfio_iommu_type1_info *info = NULL;
520 int ret;
522 ret = vfio_get_iommu_info(container, &info);
523 if (ret) {
524 error_setg_errno(errp, -ret, "Failed to get VFIO IOMMU info");
525 return false;
528 if (info->flags & VFIO_IOMMU_INFO_PGSIZES) {
529 bcontainer->pgsizes = info->iova_pgsizes;
530 } else {
531 bcontainer->pgsizes = qemu_real_host_page_size();
534 if (!vfio_get_info_dma_avail(info, &bcontainer->dma_max_mappings)) {
535 bcontainer->dma_max_mappings = 65535;
538 vfio_get_info_iova_range(info, bcontainer);
540 vfio_get_iommu_info_migration(container, info);
541 return true;
544 static bool vfio_connect_container(VFIOGroup *group, AddressSpace *as,
545 Error **errp)
547 VFIOContainer *container;
548 VFIOContainerBase *bcontainer;
549 int ret, fd;
550 VFIOAddressSpace *space;
551 VFIOIOMMUClass *vioc;
553 space = vfio_get_address_space(as);
556 * VFIO is currently incompatible with discarding of RAM insofar as the
557 * madvise to purge (zap) the page from QEMU's address space does not
558 * interact with the memory API and therefore leaves stale virtual to
559 * physical mappings in the IOMMU if the page was previously pinned. We
560 * therefore set discarding broken for each group added to a container,
561 * whether the container is used individually or shared. This provides
562 * us with options to allow devices within a group to opt-in and allow
563 * discarding, so long as it is done consistently for a group (for instance
564 * if the device is an mdev device where it is known that the host vendor
565 * driver will never pin pages outside of the working set of the guest
566 * driver, which would thus not be discarding candidates).
568 * The first opportunity to induce pinning occurs here where we attempt to
569 * attach the group to existing containers within the AddressSpace. If any
570 * pages are already zapped from the virtual address space, such as from
571 * previous discards, new pinning will cause valid mappings to be
572 * re-established. Likewise, when the overall MemoryListener for a new
573 * container is registered, a replay of mappings within the AddressSpace
574 * will occur, re-establishing any previously zapped pages as well.
576 * Especially virtio-balloon is currently only prevented from discarding
577 * new memory, it will not yet set ram_block_discard_set_required() and
578 * therefore, neither stops us here or deals with the sudden memory
579 * consumption of inflated memory.
581 * We do support discarding of memory coordinated via the RamDiscardManager
582 * with some IOMMU types. vfio_ram_block_discard_disable() handles the
583 * details once we know which type of IOMMU we are using.
586 QLIST_FOREACH(bcontainer, &space->containers, next) {
587 container = container_of(bcontainer, VFIOContainer, bcontainer);
588 if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
589 ret = vfio_ram_block_discard_disable(container, true);
590 if (ret) {
591 error_setg_errno(errp, -ret,
592 "Cannot set discarding of RAM broken");
593 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER,
594 &container->fd)) {
595 error_report("vfio: error disconnecting group %d from"
596 " container", group->groupid);
598 return false;
600 group->container = container;
601 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
602 vfio_kvm_device_add_group(group);
603 return true;
607 fd = qemu_open_old("/dev/vfio/vfio", O_RDWR);
608 if (fd < 0) {
609 error_setg_errno(errp, errno, "failed to open /dev/vfio/vfio");
610 goto put_space_exit;
613 ret = ioctl(fd, VFIO_GET_API_VERSION);
614 if (ret != VFIO_API_VERSION) {
615 error_setg(errp, "supported vfio version: %d, "
616 "reported version: %d", VFIO_API_VERSION, ret);
617 goto close_fd_exit;
620 container = vfio_create_container(fd, group, errp);
621 if (!container) {
622 goto close_fd_exit;
624 bcontainer = &container->bcontainer;
626 if (!vfio_cpr_register_container(bcontainer, errp)) {
627 goto free_container_exit;
630 ret = vfio_ram_block_discard_disable(container, true);
631 if (ret) {
632 error_setg_errno(errp, -ret, "Cannot set discarding of RAM broken");
633 goto unregister_container_exit;
636 vioc = VFIO_IOMMU_GET_CLASS(bcontainer);
637 assert(vioc->setup);
639 if (!vioc->setup(bcontainer, errp)) {
640 goto enable_discards_exit;
643 vfio_kvm_device_add_group(group);
645 QLIST_INIT(&container->group_list);
646 vfio_address_space_insert(space, bcontainer);
648 group->container = container;
649 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
651 bcontainer->listener = vfio_memory_listener;
652 memory_listener_register(&bcontainer->listener, bcontainer->space->as);
654 if (bcontainer->error) {
655 error_propagate_prepend(errp, bcontainer->error,
656 "memory listener initialization failed: ");
657 goto listener_release_exit;
660 bcontainer->initialized = true;
662 return true;
663 listener_release_exit:
664 QLIST_REMOVE(group, container_next);
665 QLIST_REMOVE(bcontainer, next);
666 vfio_kvm_device_del_group(group);
667 memory_listener_unregister(&bcontainer->listener);
668 if (vioc->release) {
669 vioc->release(bcontainer);
672 enable_discards_exit:
673 vfio_ram_block_discard_disable(container, false);
675 unregister_container_exit:
676 vfio_cpr_unregister_container(bcontainer);
678 free_container_exit:
679 object_unref(container);
681 close_fd_exit:
682 close(fd);
684 put_space_exit:
685 vfio_put_address_space(space);
687 return false;
690 static void vfio_disconnect_container(VFIOGroup *group)
692 VFIOContainer *container = group->container;
693 VFIOContainerBase *bcontainer = &container->bcontainer;
694 VFIOIOMMUClass *vioc = VFIO_IOMMU_GET_CLASS(bcontainer);
696 QLIST_REMOVE(group, container_next);
697 group->container = NULL;
700 * Explicitly release the listener first before unset container,
701 * since unset may destroy the backend container if it's the last
702 * group.
704 if (QLIST_EMPTY(&container->group_list)) {
705 memory_listener_unregister(&bcontainer->listener);
706 if (vioc->release) {
707 vioc->release(bcontainer);
711 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
712 error_report("vfio: error disconnecting group %d from container",
713 group->groupid);
716 if (QLIST_EMPTY(&container->group_list)) {
717 VFIOAddressSpace *space = bcontainer->space;
719 vfio_container_destroy(bcontainer);
721 trace_vfio_disconnect_container(container->fd);
722 vfio_cpr_unregister_container(bcontainer);
723 close(container->fd);
724 object_unref(container);
726 vfio_put_address_space(space);
730 static VFIOGroup *vfio_get_group(int groupid, AddressSpace *as, Error **errp)
732 ERRP_GUARD();
733 VFIOGroup *group;
734 char path[32];
735 struct vfio_group_status status = { .argsz = sizeof(status) };
737 QLIST_FOREACH(group, &vfio_group_list, next) {
738 if (group->groupid == groupid) {
739 /* Found it. Now is it already in the right context? */
740 if (group->container->bcontainer.space->as == as) {
741 return group;
742 } else {
743 error_setg(errp, "group %d used in multiple address spaces",
744 group->groupid);
745 return NULL;
750 group = g_malloc0(sizeof(*group));
752 snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
753 group->fd = qemu_open_old(path, O_RDWR);
754 if (group->fd < 0) {
755 error_setg_errno(errp, errno, "failed to open %s", path);
756 goto free_group_exit;
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;
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;
772 group->groupid = groupid;
773 QLIST_INIT(&group->device_list);
775 if (!vfio_connect_container(group, as, errp)) {
776 error_prepend(errp, "failed to setup container for group %d: ",
777 groupid);
778 goto close_fd_exit;
781 QLIST_INSERT_HEAD(&vfio_group_list, group, next);
783 return group;
785 close_fd_exit:
786 close(group->fd);
788 free_group_exit:
789 g_free(group);
791 return NULL;
794 static void vfio_put_group(VFIOGroup *group)
796 if (!group || !QLIST_EMPTY(&group->device_list)) {
797 return;
800 if (!group->ram_block_discard_allowed) {
801 vfio_ram_block_discard_disable(group->container, false);
803 vfio_kvm_device_del_group(group);
804 vfio_disconnect_container(group);
805 QLIST_REMOVE(group, next);
806 trace_vfio_put_group(group->fd);
807 close(group->fd);
808 g_free(group);
811 static bool vfio_get_device(VFIOGroup *group, const char *name,
812 VFIODevice *vbasedev, Error **errp)
814 g_autofree struct vfio_device_info *info = NULL;
815 int fd;
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;
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;
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.
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;
849 if (!group->ram_block_discard_allowed) {
850 group->ram_block_discard_allowed = true;
851 vfio_ram_block_discard_disable(group->container, false);
855 vbasedev->fd = fd;
856 vbasedev->group = group;
857 QLIST_INSERT_HEAD(&group->device_list, vbasedev, next);
859 vbasedev->num_irqs = info->num_irqs;
860 vbasedev->num_regions = info->num_regions;
861 vbasedev->flags = info->flags;
863 trace_vfio_get_device(name, info->flags, info->num_regions, info->num_irqs);
865 vbasedev->reset_works = !!(info->flags & VFIO_DEVICE_FLAGS_RESET);
867 return true;
870 static void vfio_put_base_device(VFIODevice *vbasedev)
872 if (!vbasedev->group) {
873 return;
875 QLIST_REMOVE(vbasedev, next);
876 vbasedev->group = NULL;
877 trace_vfio_put_base_device(vbasedev->fd);
878 close(vbasedev->fd);
881 static int vfio_device_groupid(VFIODevice *vbasedev, Error **errp)
883 char *tmp, group_path[PATH_MAX];
884 g_autofree char *group_name = NULL;
885 int ret, groupid;
886 ssize_t len;
888 tmp = g_strdup_printf("%s/iommu_group", vbasedev->sysfsdev);
889 len = readlink(tmp, group_path, sizeof(group_path));
890 g_free(tmp);
892 if (len <= 0 || len >= sizeof(group_path)) {
893 ret = len < 0 ? -errno : -ENAMETOOLONG;
894 error_setg_errno(errp, -ret, "no iommu_group found");
895 return ret;
898 group_path[len] = 0;
900 group_name = g_path_get_basename(group_path);
901 if (sscanf(group_name, "%d", &groupid) != 1) {
902 error_setg_errno(errp, errno, "failed to read %s", group_path);
903 return -errno;
905 return groupid;
909 * vfio_attach_device: attach a device to a security context
910 * @name and @vbasedev->name are likely to be different depending
911 * on the type of the device, hence the need for passing @name
913 static bool vfio_legacy_attach_device(const char *name, VFIODevice *vbasedev,
914 AddressSpace *as, Error **errp)
916 int groupid = vfio_device_groupid(vbasedev, errp);
917 VFIODevice *vbasedev_iter;
918 VFIOGroup *group;
919 VFIOContainerBase *bcontainer;
921 if (groupid < 0) {
922 return false;
925 trace_vfio_attach_device(vbasedev->name, groupid);
927 group = vfio_get_group(groupid, as, errp);
928 if (!group) {
929 return false;
932 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
933 if (strcmp(vbasedev_iter->name, vbasedev->name) == 0) {
934 error_setg(errp, "device is already attached");
935 vfio_put_group(group);
936 return false;
939 if (!vfio_get_device(group, name, vbasedev, errp)) {
940 vfio_put_group(group);
941 return false;
944 bcontainer = &group->container->bcontainer;
945 vbasedev->bcontainer = bcontainer;
946 QLIST_INSERT_HEAD(&bcontainer->device_list, vbasedev, container_next);
947 QLIST_INSERT_HEAD(&vfio_device_list, vbasedev, global_next);
949 return true;
952 static void vfio_legacy_detach_device(VFIODevice *vbasedev)
954 VFIOGroup *group = vbasedev->group;
956 QLIST_REMOVE(vbasedev, global_next);
957 QLIST_REMOVE(vbasedev, container_next);
958 vbasedev->bcontainer = NULL;
959 trace_vfio_detach_device(vbasedev->name, group->groupid);
960 vfio_put_base_device(vbasedev);
961 vfio_put_group(group);
964 static int vfio_legacy_pci_hot_reset(VFIODevice *vbasedev, bool single)
966 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
967 VFIOGroup *group;
968 struct vfio_pci_hot_reset_info *info = NULL;
969 struct vfio_pci_dependent_device *devices;
970 struct vfio_pci_hot_reset *reset;
971 int32_t *fds;
972 int ret, i, count;
973 bool multi = false;
975 trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
977 if (!single) {
978 vfio_pci_pre_reset(vdev);
980 vdev->vbasedev.needs_reset = false;
982 ret = vfio_pci_get_pci_hot_reset_info(vdev, &info);
984 if (ret) {
985 goto out_single;
987 devices = &info->devices[0];
989 trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
991 /* Verify that we have all the groups required */
992 for (i = 0; i < info->count; i++) {
993 PCIHostDeviceAddress host;
994 VFIOPCIDevice *tmp;
995 VFIODevice *vbasedev_iter;
997 host.domain = devices[i].segment;
998 host.bus = devices[i].bus;
999 host.slot = PCI_SLOT(devices[i].devfn);
1000 host.function = PCI_FUNC(devices[i].devfn);
1002 trace_vfio_pci_hot_reset_dep_devices(host.domain,
1003 host.bus, host.slot, host.function, devices[i].group_id);
1005 if (vfio_pci_host_match(&host, vdev->vbasedev.name)) {
1006 continue;
1009 QLIST_FOREACH(group, &vfio_group_list, next) {
1010 if (group->groupid == devices[i].group_id) {
1011 break;
1015 if (!group) {
1016 if (!vdev->has_pm_reset) {
1017 error_report("vfio: Cannot reset device %s, "
1018 "depends on group %d which is not owned.",
1019 vdev->vbasedev.name, devices[i].group_id);
1021 ret = -EPERM;
1022 goto out;
1025 /* Prep dependent devices for reset and clear our marker. */
1026 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
1027 if (!vbasedev_iter->dev->realized ||
1028 vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
1029 continue;
1031 tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
1032 if (vfio_pci_host_match(&host, tmp->vbasedev.name)) {
1033 if (single) {
1034 ret = -EINVAL;
1035 goto out_single;
1037 vfio_pci_pre_reset(tmp);
1038 tmp->vbasedev.needs_reset = false;
1039 multi = true;
1040 break;
1045 if (!single && !multi) {
1046 ret = -EINVAL;
1047 goto out_single;
1050 /* Determine how many group fds need to be passed */
1051 count = 0;
1052 QLIST_FOREACH(group, &vfio_group_list, next) {
1053 for (i = 0; i < info->count; i++) {
1054 if (group->groupid == devices[i].group_id) {
1055 count++;
1056 break;
1061 reset = g_malloc0(sizeof(*reset) + (count * sizeof(*fds)));
1062 reset->argsz = sizeof(*reset) + (count * sizeof(*fds));
1063 fds = &reset->group_fds[0];
1065 /* Fill in group fds */
1066 QLIST_FOREACH(group, &vfio_group_list, next) {
1067 for (i = 0; i < info->count; i++) {
1068 if (group->groupid == devices[i].group_id) {
1069 fds[reset->count++] = group->fd;
1070 break;
1075 /* Bus reset! */
1076 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
1077 g_free(reset);
1078 if (ret) {
1079 ret = -errno;
1082 trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
1083 ret ? strerror(errno) : "Success");
1085 out:
1086 /* Re-enable INTx on affected devices */
1087 for (i = 0; i < info->count; i++) {
1088 PCIHostDeviceAddress host;
1089 VFIOPCIDevice *tmp;
1090 VFIODevice *vbasedev_iter;
1092 host.domain = devices[i].segment;
1093 host.bus = devices[i].bus;
1094 host.slot = PCI_SLOT(devices[i].devfn);
1095 host.function = PCI_FUNC(devices[i].devfn);
1097 if (vfio_pci_host_match(&host, vdev->vbasedev.name)) {
1098 continue;
1101 QLIST_FOREACH(group, &vfio_group_list, next) {
1102 if (group->groupid == devices[i].group_id) {
1103 break;
1107 if (!group) {
1108 break;
1111 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
1112 if (!vbasedev_iter->dev->realized ||
1113 vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
1114 continue;
1116 tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
1117 if (vfio_pci_host_match(&host, tmp->vbasedev.name)) {
1118 vfio_pci_post_reset(tmp);
1119 break;
1123 out_single:
1124 if (!single) {
1125 vfio_pci_post_reset(vdev);
1127 g_free(info);
1129 return ret;
1132 static void vfio_iommu_legacy_class_init(ObjectClass *klass, void *data)
1134 VFIOIOMMUClass *vioc = VFIO_IOMMU_CLASS(klass);
1136 vioc->hiod_typename = TYPE_HOST_IOMMU_DEVICE_LEGACY_VFIO;
1138 vioc->setup = vfio_legacy_setup;
1139 vioc->dma_map = vfio_legacy_dma_map;
1140 vioc->dma_unmap = vfio_legacy_dma_unmap;
1141 vioc->attach_device = vfio_legacy_attach_device;
1142 vioc->detach_device = vfio_legacy_detach_device;
1143 vioc->set_dirty_page_tracking = vfio_legacy_set_dirty_page_tracking;
1144 vioc->query_dirty_bitmap = vfio_legacy_query_dirty_bitmap;
1145 vioc->pci_hot_reset = vfio_legacy_pci_hot_reset;
1148 static bool hiod_legacy_vfio_realize(HostIOMMUDevice *hiod, void *opaque,
1149 Error **errp)
1151 VFIODevice *vdev = opaque;
1153 hiod->name = g_strdup(vdev->name);
1154 hiod->caps.aw_bits = vfio_device_get_aw_bits(vdev);
1155 hiod->agent = opaque;
1157 return true;
1160 static int hiod_legacy_vfio_get_cap(HostIOMMUDevice *hiod, int cap,
1161 Error **errp)
1163 HostIOMMUDeviceCaps *caps = &hiod->caps;
1165 switch (cap) {
1166 case HOST_IOMMU_DEVICE_CAP_AW_BITS:
1167 return caps->aw_bits;
1168 default:
1169 error_setg(errp, "%s: unsupported capability %x", hiod->name, cap);
1170 return -EINVAL;
1174 static GList *
1175 hiod_legacy_vfio_get_iova_ranges(HostIOMMUDevice *hiod, Error **errp)
1177 VFIODevice *vdev = hiod->agent;
1178 GList *l = NULL;
1180 g_assert(vdev);
1182 if (vdev->bcontainer) {
1183 l = g_list_copy(vdev->bcontainer->iova_ranges);
1186 return l;
1189 static void hiod_legacy_vfio_class_init(ObjectClass *oc, void *data)
1191 HostIOMMUDeviceClass *hioc = HOST_IOMMU_DEVICE_CLASS(oc);
1193 hioc->realize = hiod_legacy_vfio_realize;
1194 hioc->get_cap = hiod_legacy_vfio_get_cap;
1195 hioc->get_iova_ranges = hiod_legacy_vfio_get_iova_ranges;
1198 static const TypeInfo types[] = {
1200 .name = TYPE_VFIO_IOMMU_LEGACY,
1201 .parent = TYPE_VFIO_IOMMU,
1202 .instance_size = sizeof(VFIOContainer),
1203 .class_init = vfio_iommu_legacy_class_init,
1204 }, {
1205 .name = TYPE_HOST_IOMMU_DEVICE_LEGACY_VFIO,
1206 .parent = TYPE_HOST_IOMMU_DEVICE,
1207 .class_init = hiod_legacy_vfio_class_init,
1211 DEFINE_TYPES(types)