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