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