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