1 /* 2 * generic functions used by VFIO devices 3 * 4 * Copyright Red Hat, Inc. 2012 5 * 6 * Authors: 7 * Alex Williamson <alex.williamson@redhat.com> 8 * 9 * This work is licensed under the terms of the GNU GPL, version 2. See 10 * the COPYING file in the top-level directory. 11 * 12 * Based on qemu-kvm device-assignment: 13 * Adapted for KVM by Qumranet. 14 * Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com) 15 * Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com) 16 * Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com) 17 * Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com) 18 * Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com) 19 */ 20 21 #include "qemu/osdep.h" 22 #include <sys/ioctl.h> 23 #include <linux/vfio.h> 24 25 #include "hw/vfio/vfio-common.h" 26 #include "exec/address-spaces.h" 27 #include "exec/memory.h" 28 #include "exec/ram_addr.h" 29 #include "hw/hw.h" 30 #include "qemu/error-report.h" 31 #include "qemu/range.h" 32 #include "sysemu/reset.h" 33 #include "trace.h" 34 #include "qapi/error.h" 35 #include "migration/migration.h" 36 37 VFIOGroupList vfio_group_list = 38 QLIST_HEAD_INITIALIZER(vfio_group_list); 39 40 static int vfio_ram_block_discard_disable(VFIOContainer *container, bool state) 41 { 42 switch (container->iommu_type) { 43 case VFIO_TYPE1v2_IOMMU: 44 case VFIO_TYPE1_IOMMU: 45 /* 46 * We support coordinated discarding of RAM via the RamDiscardManager. 47 */ 48 return ram_block_uncoordinated_discard_disable(state); 49 default: 50 /* 51 * VFIO_SPAPR_TCE_IOMMU most probably works just fine with 52 * RamDiscardManager, however, it is completely untested. 53 * 54 * VFIO_SPAPR_TCE_v2_IOMMU with "DMA memory preregistering" does 55 * completely the opposite of managing mapping/pinning dynamically as 56 * required by RamDiscardManager. We would have to special-case sections 57 * with a RamDiscardManager. 58 */ 59 return ram_block_discard_disable(state); 60 } 61 } 62 63 static int vfio_dma_unmap_bitmap(VFIOContainer *container, 64 hwaddr iova, ram_addr_t size, 65 IOMMUTLBEntry *iotlb) 66 { 67 VFIOContainerBase *bcontainer = &container->bcontainer; 68 struct vfio_iommu_type1_dma_unmap *unmap; 69 struct vfio_bitmap *bitmap; 70 VFIOBitmap vbmap; 71 int ret; 72 73 ret = vfio_bitmap_alloc(&vbmap, size); 74 if (ret) { 75 return ret; 76 } 77 78 unmap = g_malloc0(sizeof(*unmap) + sizeof(*bitmap)); 79 80 unmap->argsz = sizeof(*unmap) + sizeof(*bitmap); 81 unmap->iova = iova; 82 unmap->size = size; 83 unmap->flags |= VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP; 84 bitmap = (struct vfio_bitmap *)&unmap->data; 85 86 /* 87 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of 88 * qemu_real_host_page_size to mark those dirty. Hence set bitmap_pgsize 89 * to qemu_real_host_page_size. 90 */ 91 bitmap->pgsize = qemu_real_host_page_size(); 92 bitmap->size = vbmap.size; 93 bitmap->data = (__u64 *)vbmap.bitmap; 94 95 if (vbmap.size > bcontainer->max_dirty_bitmap_size) { 96 error_report("UNMAP: Size of bitmap too big 0x%"PRIx64, vbmap.size); 97 ret = -E2BIG; 98 goto unmap_exit; 99 } 100 101 ret = ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, unmap); 102 if (!ret) { 103 cpu_physical_memory_set_dirty_lebitmap(vbmap.bitmap, 104 iotlb->translated_addr, vbmap.pages); 105 } else { 106 error_report("VFIO_UNMAP_DMA with DIRTY_BITMAP : %m"); 107 } 108 109 unmap_exit: 110 g_free(unmap); 111 g_free(vbmap.bitmap); 112 113 return ret; 114 } 115 116 /* 117 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86 118 */ 119 static int vfio_legacy_dma_unmap(VFIOContainerBase *bcontainer, hwaddr iova, 120 ram_addr_t size, IOMMUTLBEntry *iotlb) 121 { 122 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 133 if (iotlb && vfio_devices_all_running_and_mig_active(bcontainer)) { 134 if (!vfio_devices_all_device_dirty_tracking(bcontainer) && 135 bcontainer->dirty_pages_supported) { 136 return vfio_dma_unmap_bitmap(container, iova, size, iotlb); 137 } 138 139 need_dirty_sync = true; 140 } 141 142 while (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) { 143 /* 144 * The type1 backend has an off-by-one bug in the kernel (71a7d3d78e3c 145 * v4.15) where an overflow in its wrap-around check prevents us from 146 * unmapping the last page of the address space. Test for the error 147 * condition and re-try the unmap excluding the last page. The 148 * expectation is that we've never mapped the last page anyway and this 149 * unmap request comes via vIOMMU support which also makes it unlikely 150 * that this page is used. This bug was introduced well after type1 v2 151 * support was introduced, so we shouldn't need to test for v1. A fix 152 * is queued for kernel v5.0 so this workaround can be removed once 153 * affected kernels are sufficiently deprecated. 154 */ 155 if (errno == EINVAL && unmap.size && !(unmap.iova + unmap.size) && 156 container->iommu_type == VFIO_TYPE1v2_IOMMU) { 157 trace_vfio_legacy_dma_unmap_overflow_workaround(); 158 unmap.size -= 1ULL << ctz64(bcontainer->pgsizes); 159 continue; 160 } 161 error_report("VFIO_UNMAP_DMA failed: %s", strerror(errno)); 162 return -errno; 163 } 164 165 if (need_dirty_sync) { 166 ret = vfio_get_dirty_bitmap(bcontainer, iova, size, 167 iotlb->translated_addr); 168 if (ret) { 169 return ret; 170 } 171 } 172 173 return 0; 174 } 175 176 static int vfio_legacy_dma_map(VFIOContainerBase *bcontainer, hwaddr iova, 177 ram_addr_t size, void *vaddr, bool readonly) 178 { 179 VFIOContainer *container = container_of(bcontainer, VFIOContainer, 180 bcontainer); 181 struct vfio_iommu_type1_dma_map map = { 182 .argsz = sizeof(map), 183 .flags = VFIO_DMA_MAP_FLAG_READ, 184 .vaddr = (__u64)(uintptr_t)vaddr, 185 .iova = iova, 186 .size = size, 187 }; 188 189 if (!readonly) { 190 map.flags |= VFIO_DMA_MAP_FLAG_WRITE; 191 } 192 193 /* 194 * Try the mapping, if it fails with EBUSY, unmap the region and try 195 * again. This shouldn't be necessary, but we sometimes see it in 196 * the VGA ROM space. 197 */ 198 if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 || 199 (errno == EBUSY && 200 vfio_legacy_dma_unmap(bcontainer, iova, size, NULL) == 0 && 201 ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) { 202 return 0; 203 } 204 205 error_report("VFIO_MAP_DMA failed: %s", strerror(errno)); 206 return -errno; 207 } 208 209 static int vfio_legacy_set_dirty_page_tracking(VFIOContainerBase *bcontainer, 210 bool start) 211 { 212 VFIOContainer *container = container_of(bcontainer, VFIOContainer, 213 bcontainer); 214 int ret; 215 struct vfio_iommu_type1_dirty_bitmap dirty = { 216 .argsz = sizeof(dirty), 217 }; 218 219 if (!bcontainer->dirty_pages_supported) { 220 return 0; 221 } 222 223 if (start) { 224 dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_START; 225 } else { 226 dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP; 227 } 228 229 ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, &dirty); 230 if (ret) { 231 ret = -errno; 232 error_report("Failed to set dirty tracking flag 0x%x errno: %d", 233 dirty.flags, errno); 234 } 235 236 return ret; 237 } 238 239 static int vfio_legacy_query_dirty_bitmap(VFIOContainerBase *bcontainer, 240 VFIOBitmap *vbmap, 241 hwaddr iova, hwaddr size) 242 { 243 VFIOContainer *container = container_of(bcontainer, VFIOContainer, 244 bcontainer); 245 struct vfio_iommu_type1_dirty_bitmap *dbitmap; 246 struct vfio_iommu_type1_dirty_bitmap_get *range; 247 int ret; 248 249 dbitmap = g_malloc0(sizeof(*dbitmap) + sizeof(*range)); 250 251 dbitmap->argsz = sizeof(*dbitmap) + sizeof(*range); 252 dbitmap->flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP; 253 range = (struct vfio_iommu_type1_dirty_bitmap_get *)&dbitmap->data; 254 range->iova = iova; 255 range->size = size; 256 257 /* 258 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of 259 * qemu_real_host_page_size to mark those dirty. Hence set bitmap's pgsize 260 * to qemu_real_host_page_size. 261 */ 262 range->bitmap.pgsize = qemu_real_host_page_size(); 263 range->bitmap.size = vbmap->size; 264 range->bitmap.data = (__u64 *)vbmap->bitmap; 265 266 ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, dbitmap); 267 if (ret) { 268 ret = -errno; 269 error_report("Failed to get dirty bitmap for iova: 0x%"PRIx64 270 " size: 0x%"PRIx64" err: %d", (uint64_t)range->iova, 271 (uint64_t)range->size, errno); 272 } 273 274 g_free(dbitmap); 275 276 return ret; 277 } 278 279 static struct vfio_info_cap_header * 280 vfio_get_iommu_type1_info_cap(struct vfio_iommu_type1_info *info, uint16_t id) 281 { 282 if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) { 283 return NULL; 284 } 285 286 return vfio_get_cap((void *)info, info->cap_offset, id); 287 } 288 289 bool vfio_get_info_dma_avail(struct vfio_iommu_type1_info *info, 290 unsigned int *avail) 291 { 292 struct vfio_info_cap_header *hdr; 293 struct vfio_iommu_type1_info_dma_avail *cap; 294 295 /* If the capability cannot be found, assume no DMA limiting */ 296 hdr = vfio_get_iommu_type1_info_cap(info, 297 VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL); 298 if (!hdr) { 299 return false; 300 } 301 302 if (avail != NULL) { 303 cap = (void *) hdr; 304 *avail = cap->avail; 305 } 306 307 return true; 308 } 309 310 static bool vfio_get_info_iova_range(struct vfio_iommu_type1_info *info, 311 VFIOContainerBase *bcontainer) 312 { 313 struct vfio_info_cap_header *hdr; 314 struct vfio_iommu_type1_info_cap_iova_range *cap; 315 316 hdr = vfio_get_iommu_type1_info_cap(info, 317 VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE); 318 if (!hdr) { 319 return false; 320 } 321 322 cap = (void *)hdr; 323 324 for (int i = 0; i < cap->nr_iovas; i++) { 325 Range *range = g_new(Range, 1); 326 327 range_set_bounds(range, cap->iova_ranges[i].start, 328 cap->iova_ranges[i].end); 329 bcontainer->iova_ranges = 330 range_list_insert(bcontainer->iova_ranges, range); 331 } 332 333 return true; 334 } 335 336 static void vfio_kvm_device_add_group(VFIOGroup *group) 337 { 338 Error *err = NULL; 339 340 if (vfio_kvm_device_add_fd(group->fd, &err)) { 341 error_reportf_err(err, "group ID %d: ", group->groupid); 342 } 343 } 344 345 static void vfio_kvm_device_del_group(VFIOGroup *group) 346 { 347 Error *err = NULL; 348 349 if (vfio_kvm_device_del_fd(group->fd, &err)) { 350 error_reportf_err(err, "group ID %d: ", group->groupid); 351 } 352 } 353 354 /* 355 * vfio_get_iommu_type - selects the richest iommu_type (v2 first) 356 */ 357 static int vfio_get_iommu_type(VFIOContainer *container, 358 Error **errp) 359 { 360 int iommu_types[] = { VFIO_TYPE1v2_IOMMU, VFIO_TYPE1_IOMMU, 361 VFIO_SPAPR_TCE_v2_IOMMU, VFIO_SPAPR_TCE_IOMMU }; 362 int i; 363 364 for (i = 0; i < ARRAY_SIZE(iommu_types); i++) { 365 if (ioctl(container->fd, VFIO_CHECK_EXTENSION, iommu_types[i])) { 366 return iommu_types[i]; 367 } 368 } 369 error_setg(errp, "No available IOMMU models"); 370 return -EINVAL; 371 } 372 373 static int vfio_init_container(VFIOContainer *container, int group_fd, 374 Error **errp) 375 { 376 int iommu_type, ret; 377 378 iommu_type = vfio_get_iommu_type(container, errp); 379 if (iommu_type < 0) { 380 return iommu_type; 381 } 382 383 ret = ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container->fd); 384 if (ret) { 385 error_setg_errno(errp, errno, "Failed to set group container"); 386 return -errno; 387 } 388 389 while (ioctl(container->fd, VFIO_SET_IOMMU, iommu_type)) { 390 if (iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) { 391 /* 392 * On sPAPR, despite the IOMMU subdriver always advertises v1 and 393 * v2, the running platform may not support v2 and there is no 394 * way to guess it until an IOMMU group gets added to the container. 395 * So in case it fails with v2, try v1 as a fallback. 396 */ 397 iommu_type = VFIO_SPAPR_TCE_IOMMU; 398 continue; 399 } 400 error_setg_errno(errp, errno, "Failed to set iommu for container"); 401 return -errno; 402 } 403 404 container->iommu_type = iommu_type; 405 return 0; 406 } 407 408 static int vfio_get_iommu_info(VFIOContainer *container, 409 struct vfio_iommu_type1_info **info) 410 { 411 412 size_t argsz = sizeof(struct vfio_iommu_type1_info); 413 414 *info = g_new0(struct vfio_iommu_type1_info, 1); 415 again: 416 (*info)->argsz = argsz; 417 418 if (ioctl(container->fd, VFIO_IOMMU_GET_INFO, *info)) { 419 g_free(*info); 420 *info = NULL; 421 return -errno; 422 } 423 424 if (((*info)->argsz > argsz)) { 425 argsz = (*info)->argsz; 426 *info = g_realloc(*info, argsz); 427 goto again; 428 } 429 430 return 0; 431 } 432 433 static struct vfio_info_cap_header * 434 vfio_get_iommu_info_cap(struct vfio_iommu_type1_info *info, uint16_t id) 435 { 436 struct vfio_info_cap_header *hdr; 437 void *ptr = info; 438 439 if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) { 440 return NULL; 441 } 442 443 for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) { 444 if (hdr->id == id) { 445 return hdr; 446 } 447 } 448 449 return NULL; 450 } 451 452 static void vfio_get_iommu_info_migration(VFIOContainer *container, 453 struct vfio_iommu_type1_info *info) 454 { 455 struct vfio_info_cap_header *hdr; 456 struct vfio_iommu_type1_info_cap_migration *cap_mig; 457 VFIOContainerBase *bcontainer = &container->bcontainer; 458 459 hdr = vfio_get_iommu_info_cap(info, VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION); 460 if (!hdr) { 461 return; 462 } 463 464 cap_mig = container_of(hdr, struct vfio_iommu_type1_info_cap_migration, 465 header); 466 467 /* 468 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of 469 * qemu_real_host_page_size to mark those dirty. 470 */ 471 if (cap_mig->pgsize_bitmap & qemu_real_host_page_size()) { 472 bcontainer->dirty_pages_supported = true; 473 bcontainer->max_dirty_bitmap_size = cap_mig->max_dirty_bitmap_size; 474 bcontainer->dirty_pgsizes = cap_mig->pgsize_bitmap; 475 } 476 } 477 478 static int vfio_connect_container(VFIOGroup *group, AddressSpace *as, 479 Error **errp) 480 { 481 VFIOContainer *container; 482 VFIOContainerBase *bcontainer; 483 int ret, fd; 484 VFIOAddressSpace *space; 485 486 space = vfio_get_address_space(as); 487 488 /* 489 * VFIO is currently incompatible with discarding of RAM insofar as the 490 * madvise to purge (zap) the page from QEMU's address space does not 491 * interact with the memory API and therefore leaves stale virtual to 492 * physical mappings in the IOMMU if the page was previously pinned. We 493 * therefore set discarding broken for each group added to a container, 494 * whether the container is used individually or shared. This provides 495 * us with options to allow devices within a group to opt-in and allow 496 * discarding, so long as it is done consistently for a group (for instance 497 * if the device is an mdev device where it is known that the host vendor 498 * driver will never pin pages outside of the working set of the guest 499 * driver, which would thus not be discarding candidates). 500 * 501 * The first opportunity to induce pinning occurs here where we attempt to 502 * attach the group to existing containers within the AddressSpace. If any 503 * pages are already zapped from the virtual address space, such as from 504 * previous discards, new pinning will cause valid mappings to be 505 * re-established. Likewise, when the overall MemoryListener for a new 506 * container is registered, a replay of mappings within the AddressSpace 507 * will occur, re-establishing any previously zapped pages as well. 508 * 509 * Especially virtio-balloon is currently only prevented from discarding 510 * new memory, it will not yet set ram_block_discard_set_required() and 511 * therefore, neither stops us here or deals with the sudden memory 512 * consumption of inflated memory. 513 * 514 * We do support discarding of memory coordinated via the RamDiscardManager 515 * with some IOMMU types. vfio_ram_block_discard_disable() handles the 516 * details once we know which type of IOMMU we are using. 517 */ 518 519 QLIST_FOREACH(bcontainer, &space->containers, next) { 520 container = container_of(bcontainer, VFIOContainer, bcontainer); 521 if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) { 522 ret = vfio_ram_block_discard_disable(container, true); 523 if (ret) { 524 error_setg_errno(errp, -ret, 525 "Cannot set discarding of RAM broken"); 526 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, 527 &container->fd)) { 528 error_report("vfio: error disconnecting group %d from" 529 " container", group->groupid); 530 } 531 return ret; 532 } 533 group->container = container; 534 QLIST_INSERT_HEAD(&container->group_list, group, container_next); 535 vfio_kvm_device_add_group(group); 536 return 0; 537 } 538 } 539 540 fd = qemu_open_old("/dev/vfio/vfio", O_RDWR); 541 if (fd < 0) { 542 error_setg_errno(errp, errno, "failed to open /dev/vfio/vfio"); 543 ret = -errno; 544 goto put_space_exit; 545 } 546 547 ret = ioctl(fd, VFIO_GET_API_VERSION); 548 if (ret != VFIO_API_VERSION) { 549 error_setg(errp, "supported vfio version: %d, " 550 "reported version: %d", VFIO_API_VERSION, ret); 551 ret = -EINVAL; 552 goto close_fd_exit; 553 } 554 555 container = g_malloc0(sizeof(*container)); 556 container->fd = fd; 557 bcontainer = &container->bcontainer; 558 vfio_container_init(bcontainer, space, &vfio_legacy_ops); 559 560 ret = vfio_init_container(container, group->fd, errp); 561 if (ret) { 562 goto free_container_exit; 563 } 564 565 ret = vfio_ram_block_discard_disable(container, true); 566 if (ret) { 567 error_setg_errno(errp, -ret, "Cannot set discarding of RAM broken"); 568 goto free_container_exit; 569 } 570 571 switch (container->iommu_type) { 572 case VFIO_TYPE1v2_IOMMU: 573 case VFIO_TYPE1_IOMMU: 574 { 575 struct vfio_iommu_type1_info *info; 576 577 ret = vfio_get_iommu_info(container, &info); 578 if (ret) { 579 error_setg_errno(errp, -ret, "Failed to get VFIO IOMMU info"); 580 goto enable_discards_exit; 581 } 582 583 if (info->flags & VFIO_IOMMU_INFO_PGSIZES) { 584 bcontainer->pgsizes = info->iova_pgsizes; 585 } else { 586 bcontainer->pgsizes = qemu_real_host_page_size(); 587 } 588 589 if (!vfio_get_info_dma_avail(info, &bcontainer->dma_max_mappings)) { 590 bcontainer->dma_max_mappings = 65535; 591 } 592 593 vfio_get_info_iova_range(info, bcontainer); 594 595 vfio_get_iommu_info_migration(container, info); 596 g_free(info); 597 break; 598 } 599 case VFIO_SPAPR_TCE_v2_IOMMU: 600 case VFIO_SPAPR_TCE_IOMMU: 601 { 602 ret = vfio_spapr_container_init(container, errp); 603 if (ret) { 604 goto enable_discards_exit; 605 } 606 break; 607 } 608 } 609 610 vfio_kvm_device_add_group(group); 611 612 QLIST_INIT(&container->group_list); 613 QLIST_INSERT_HEAD(&space->containers, bcontainer, next); 614 615 group->container = container; 616 QLIST_INSERT_HEAD(&container->group_list, group, container_next); 617 618 bcontainer->listener = vfio_memory_listener; 619 memory_listener_register(&bcontainer->listener, bcontainer->space->as); 620 621 if (bcontainer->error) { 622 ret = -1; 623 error_propagate_prepend(errp, bcontainer->error, 624 "memory listener initialization failed: "); 625 goto listener_release_exit; 626 } 627 628 bcontainer->initialized = true; 629 630 return 0; 631 listener_release_exit: 632 QLIST_REMOVE(group, container_next); 633 QLIST_REMOVE(bcontainer, next); 634 vfio_kvm_device_del_group(group); 635 memory_listener_unregister(&bcontainer->listener); 636 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU || 637 container->iommu_type == VFIO_SPAPR_TCE_IOMMU) { 638 vfio_spapr_container_deinit(container); 639 } 640 641 enable_discards_exit: 642 vfio_ram_block_discard_disable(container, false); 643 644 free_container_exit: 645 g_free(container); 646 647 close_fd_exit: 648 close(fd); 649 650 put_space_exit: 651 vfio_put_address_space(space); 652 653 return ret; 654 } 655 656 static void vfio_disconnect_container(VFIOGroup *group) 657 { 658 VFIOContainer *container = group->container; 659 VFIOContainerBase *bcontainer = &container->bcontainer; 660 661 QLIST_REMOVE(group, container_next); 662 group->container = NULL; 663 664 /* 665 * Explicitly release the listener first before unset container, 666 * since unset may destroy the backend container if it's the last 667 * group. 668 */ 669 if (QLIST_EMPTY(&container->group_list)) { 670 memory_listener_unregister(&bcontainer->listener); 671 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU || 672 container->iommu_type == VFIO_SPAPR_TCE_IOMMU) { 673 vfio_spapr_container_deinit(container); 674 } 675 } 676 677 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) { 678 error_report("vfio: error disconnecting group %d from container", 679 group->groupid); 680 } 681 682 if (QLIST_EMPTY(&container->group_list)) { 683 VFIOAddressSpace *space = bcontainer->space; 684 685 vfio_container_destroy(bcontainer); 686 687 trace_vfio_disconnect_container(container->fd); 688 close(container->fd); 689 g_free(container); 690 691 vfio_put_address_space(space); 692 } 693 } 694 695 static VFIOGroup *vfio_get_group(int groupid, AddressSpace *as, Error **errp) 696 { 697 VFIOGroup *group; 698 char path[32]; 699 struct vfio_group_status status = { .argsz = sizeof(status) }; 700 701 QLIST_FOREACH(group, &vfio_group_list, next) { 702 if (group->groupid == groupid) { 703 /* Found it. Now is it already in the right context? */ 704 if (group->container->bcontainer.space->as == as) { 705 return group; 706 } else { 707 error_setg(errp, "group %d used in multiple address spaces", 708 group->groupid); 709 return NULL; 710 } 711 } 712 } 713 714 group = g_malloc0(sizeof(*group)); 715 716 snprintf(path, sizeof(path), "/dev/vfio/%d", groupid); 717 group->fd = qemu_open_old(path, O_RDWR); 718 if (group->fd < 0) { 719 error_setg_errno(errp, errno, "failed to open %s", path); 720 goto free_group_exit; 721 } 722 723 if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) { 724 error_setg_errno(errp, errno, "failed to get group %d status", groupid); 725 goto close_fd_exit; 726 } 727 728 if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) { 729 error_setg(errp, "group %d is not viable", groupid); 730 error_append_hint(errp, 731 "Please ensure all devices within the iommu_group " 732 "are bound to their vfio bus driver.\n"); 733 goto close_fd_exit; 734 } 735 736 group->groupid = groupid; 737 QLIST_INIT(&group->device_list); 738 739 if (vfio_connect_container(group, as, errp)) { 740 error_prepend(errp, "failed to setup container for group %d: ", 741 groupid); 742 goto close_fd_exit; 743 } 744 745 QLIST_INSERT_HEAD(&vfio_group_list, group, next); 746 747 return group; 748 749 close_fd_exit: 750 close(group->fd); 751 752 free_group_exit: 753 g_free(group); 754 755 return NULL; 756 } 757 758 static void vfio_put_group(VFIOGroup *group) 759 { 760 if (!group || !QLIST_EMPTY(&group->device_list)) { 761 return; 762 } 763 764 if (!group->ram_block_discard_allowed) { 765 vfio_ram_block_discard_disable(group->container, false); 766 } 767 vfio_kvm_device_del_group(group); 768 vfio_disconnect_container(group); 769 QLIST_REMOVE(group, next); 770 trace_vfio_put_group(group->fd); 771 close(group->fd); 772 g_free(group); 773 } 774 775 static int vfio_get_device(VFIOGroup *group, const char *name, 776 VFIODevice *vbasedev, Error **errp) 777 { 778 g_autofree struct vfio_device_info *info = NULL; 779 int fd; 780 781 fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name); 782 if (fd < 0) { 783 error_setg_errno(errp, errno, "error getting device from group %d", 784 group->groupid); 785 error_append_hint(errp, 786 "Verify all devices in group %d are bound to vfio-<bus> " 787 "or pci-stub and not already in use\n", group->groupid); 788 return fd; 789 } 790 791 info = vfio_get_device_info(fd); 792 if (!info) { 793 error_setg_errno(errp, errno, "error getting device info"); 794 close(fd); 795 return -1; 796 } 797 798 /* 799 * Set discarding of RAM as not broken for this group if the driver knows 800 * the device operates compatibly with discarding. Setting must be 801 * consistent per group, but since compatibility is really only possible 802 * with mdev currently, we expect singleton groups. 803 */ 804 if (vbasedev->ram_block_discard_allowed != 805 group->ram_block_discard_allowed) { 806 if (!QLIST_EMPTY(&group->device_list)) { 807 error_setg(errp, "Inconsistent setting of support for discarding " 808 "RAM (e.g., balloon) within group"); 809 close(fd); 810 return -1; 811 } 812 813 if (!group->ram_block_discard_allowed) { 814 group->ram_block_discard_allowed = true; 815 vfio_ram_block_discard_disable(group->container, false); 816 } 817 } 818 819 vbasedev->fd = fd; 820 vbasedev->group = group; 821 QLIST_INSERT_HEAD(&group->device_list, vbasedev, next); 822 823 vbasedev->num_irqs = info->num_irqs; 824 vbasedev->num_regions = info->num_regions; 825 vbasedev->flags = info->flags; 826 827 trace_vfio_get_device(name, info->flags, info->num_regions, info->num_irqs); 828 829 vbasedev->reset_works = !!(info->flags & VFIO_DEVICE_FLAGS_RESET); 830 831 return 0; 832 } 833 834 static void vfio_put_base_device(VFIODevice *vbasedev) 835 { 836 if (!vbasedev->group) { 837 return; 838 } 839 QLIST_REMOVE(vbasedev, next); 840 vbasedev->group = NULL; 841 trace_vfio_put_base_device(vbasedev->fd); 842 close(vbasedev->fd); 843 } 844 845 static int vfio_device_groupid(VFIODevice *vbasedev, Error **errp) 846 { 847 char *tmp, group_path[PATH_MAX], *group_name; 848 int ret, groupid; 849 ssize_t len; 850 851 tmp = g_strdup_printf("%s/iommu_group", vbasedev->sysfsdev); 852 len = readlink(tmp, group_path, sizeof(group_path)); 853 g_free(tmp); 854 855 if (len <= 0 || len >= sizeof(group_path)) { 856 ret = len < 0 ? -errno : -ENAMETOOLONG; 857 error_setg_errno(errp, -ret, "no iommu_group found"); 858 return ret; 859 } 860 861 group_path[len] = 0; 862 863 group_name = basename(group_path); 864 if (sscanf(group_name, "%d", &groupid) != 1) { 865 error_setg_errno(errp, errno, "failed to read %s", group_path); 866 return -errno; 867 } 868 return groupid; 869 } 870 871 /* 872 * vfio_attach_device: attach a device to a security context 873 * @name and @vbasedev->name are likely to be different depending 874 * on the type of the device, hence the need for passing @name 875 */ 876 static int vfio_legacy_attach_device(const char *name, VFIODevice *vbasedev, 877 AddressSpace *as, Error **errp) 878 { 879 int groupid = vfio_device_groupid(vbasedev, errp); 880 VFIODevice *vbasedev_iter; 881 VFIOGroup *group; 882 VFIOContainerBase *bcontainer; 883 int ret; 884 885 if (groupid < 0) { 886 return groupid; 887 } 888 889 trace_vfio_attach_device(vbasedev->name, groupid); 890 891 group = vfio_get_group(groupid, as, errp); 892 if (!group) { 893 return -ENOENT; 894 } 895 896 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) { 897 if (strcmp(vbasedev_iter->name, vbasedev->name) == 0) { 898 error_setg(errp, "device is already attached"); 899 vfio_put_group(group); 900 return -EBUSY; 901 } 902 } 903 ret = vfio_get_device(group, name, vbasedev, errp); 904 if (ret) { 905 vfio_put_group(group); 906 return ret; 907 } 908 909 bcontainer = &group->container->bcontainer; 910 vbasedev->bcontainer = bcontainer; 911 QLIST_INSERT_HEAD(&bcontainer->device_list, vbasedev, container_next); 912 QLIST_INSERT_HEAD(&vfio_device_list, vbasedev, global_next); 913 914 return ret; 915 } 916 917 static void vfio_legacy_detach_device(VFIODevice *vbasedev) 918 { 919 VFIOGroup *group = vbasedev->group; 920 921 QLIST_REMOVE(vbasedev, global_next); 922 QLIST_REMOVE(vbasedev, container_next); 923 vbasedev->bcontainer = NULL; 924 trace_vfio_detach_device(vbasedev->name, group->groupid); 925 vfio_put_base_device(vbasedev); 926 vfio_put_group(group); 927 } 928 929 const VFIOIOMMUOps vfio_legacy_ops = { 930 .dma_map = vfio_legacy_dma_map, 931 .dma_unmap = vfio_legacy_dma_unmap, 932 .attach_device = vfio_legacy_attach_device, 933 .detach_device = vfio_legacy_detach_device, 934 .set_dirty_page_tracking = vfio_legacy_set_dirty_page_tracking, 935 .query_dirty_bitmap = vfio_legacy_query_dirty_bitmap, 936 }; 937