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