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 #ifdef CONFIG_KVM 24 #include <linux/kvm.h> 25 #endif 26 #include <linux/vfio.h> 27 28 #include "hw/vfio/vfio-common.h" 29 #include "hw/vfio/vfio.h" 30 #include "exec/address-spaces.h" 31 #include "exec/memory.h" 32 #include "exec/ram_addr.h" 33 #include "hw/hw.h" 34 #include "qemu/error-report.h" 35 #include "qemu/main-loop.h" 36 #include "qemu/range.h" 37 #include "sysemu/kvm.h" 38 #include "sysemu/reset.h" 39 #include "sysemu/runstate.h" 40 #include "trace.h" 41 #include "qapi/error.h" 42 #include "migration/migration.h" 43 #include "sysemu/tpm.h" 44 45 VFIOGroupList vfio_group_list = 46 QLIST_HEAD_INITIALIZER(vfio_group_list); 47 static QLIST_HEAD(, VFIOAddressSpace) vfio_address_spaces = 48 QLIST_HEAD_INITIALIZER(vfio_address_spaces); 49 50 #ifdef CONFIG_KVM 51 /* 52 * We have a single VFIO pseudo device per KVM VM. Once created it lives 53 * for the life of the VM. Closing the file descriptor only drops our 54 * reference to it and the device's reference to kvm. Therefore once 55 * initialized, this file descriptor is only released on QEMU exit and 56 * we'll re-use it should another vfio device be attached before then. 57 */ 58 static int vfio_kvm_device_fd = -1; 59 #endif 60 61 /* 62 * Common VFIO interrupt disable 63 */ 64 void vfio_disable_irqindex(VFIODevice *vbasedev, int index) 65 { 66 struct vfio_irq_set irq_set = { 67 .argsz = sizeof(irq_set), 68 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER, 69 .index = index, 70 .start = 0, 71 .count = 0, 72 }; 73 74 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set); 75 } 76 77 void vfio_unmask_single_irqindex(VFIODevice *vbasedev, int index) 78 { 79 struct vfio_irq_set irq_set = { 80 .argsz = sizeof(irq_set), 81 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK, 82 .index = index, 83 .start = 0, 84 .count = 1, 85 }; 86 87 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set); 88 } 89 90 void vfio_mask_single_irqindex(VFIODevice *vbasedev, int index) 91 { 92 struct vfio_irq_set irq_set = { 93 .argsz = sizeof(irq_set), 94 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK, 95 .index = index, 96 .start = 0, 97 .count = 1, 98 }; 99 100 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set); 101 } 102 103 static inline const char *action_to_str(int action) 104 { 105 switch (action) { 106 case VFIO_IRQ_SET_ACTION_MASK: 107 return "MASK"; 108 case VFIO_IRQ_SET_ACTION_UNMASK: 109 return "UNMASK"; 110 case VFIO_IRQ_SET_ACTION_TRIGGER: 111 return "TRIGGER"; 112 default: 113 return "UNKNOWN ACTION"; 114 } 115 } 116 117 static const char *index_to_str(VFIODevice *vbasedev, int index) 118 { 119 if (vbasedev->type != VFIO_DEVICE_TYPE_PCI) { 120 return NULL; 121 } 122 123 switch (index) { 124 case VFIO_PCI_INTX_IRQ_INDEX: 125 return "INTX"; 126 case VFIO_PCI_MSI_IRQ_INDEX: 127 return "MSI"; 128 case VFIO_PCI_MSIX_IRQ_INDEX: 129 return "MSIX"; 130 case VFIO_PCI_ERR_IRQ_INDEX: 131 return "ERR"; 132 case VFIO_PCI_REQ_IRQ_INDEX: 133 return "REQ"; 134 default: 135 return NULL; 136 } 137 } 138 139 static int vfio_ram_block_discard_disable(VFIOContainer *container, bool state) 140 { 141 switch (container->iommu_type) { 142 case VFIO_TYPE1v2_IOMMU: 143 case VFIO_TYPE1_IOMMU: 144 /* 145 * We support coordinated discarding of RAM via the RamDiscardManager. 146 */ 147 return ram_block_uncoordinated_discard_disable(state); 148 default: 149 /* 150 * VFIO_SPAPR_TCE_IOMMU most probably works just fine with 151 * RamDiscardManager, however, it is completely untested. 152 * 153 * VFIO_SPAPR_TCE_v2_IOMMU with "DMA memory preregistering" does 154 * completely the opposite of managing mapping/pinning dynamically as 155 * required by RamDiscardManager. We would have to special-case sections 156 * with a RamDiscardManager. 157 */ 158 return ram_block_discard_disable(state); 159 } 160 } 161 162 int vfio_set_irq_signaling(VFIODevice *vbasedev, int index, int subindex, 163 int action, int fd, Error **errp) 164 { 165 struct vfio_irq_set *irq_set; 166 int argsz, ret = 0; 167 const char *name; 168 int32_t *pfd; 169 170 argsz = sizeof(*irq_set) + sizeof(*pfd); 171 172 irq_set = g_malloc0(argsz); 173 irq_set->argsz = argsz; 174 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | action; 175 irq_set->index = index; 176 irq_set->start = subindex; 177 irq_set->count = 1; 178 pfd = (int32_t *)&irq_set->data; 179 *pfd = fd; 180 181 if (ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, irq_set)) { 182 ret = -errno; 183 } 184 g_free(irq_set); 185 186 if (!ret) { 187 return 0; 188 } 189 190 error_setg_errno(errp, -ret, "VFIO_DEVICE_SET_IRQS failure"); 191 192 name = index_to_str(vbasedev, index); 193 if (name) { 194 error_prepend(errp, "%s-%d: ", name, subindex); 195 } else { 196 error_prepend(errp, "index %d-%d: ", index, subindex); 197 } 198 error_prepend(errp, 199 "Failed to %s %s eventfd signaling for interrupt ", 200 fd < 0 ? "tear down" : "set up", action_to_str(action)); 201 return ret; 202 } 203 204 /* 205 * IO Port/MMIO - Beware of the endians, VFIO is always little endian 206 */ 207 void vfio_region_write(void *opaque, hwaddr addr, 208 uint64_t data, unsigned size) 209 { 210 VFIORegion *region = opaque; 211 VFIODevice *vbasedev = region->vbasedev; 212 union { 213 uint8_t byte; 214 uint16_t word; 215 uint32_t dword; 216 uint64_t qword; 217 } buf; 218 219 switch (size) { 220 case 1: 221 buf.byte = data; 222 break; 223 case 2: 224 buf.word = cpu_to_le16(data); 225 break; 226 case 4: 227 buf.dword = cpu_to_le32(data); 228 break; 229 case 8: 230 buf.qword = cpu_to_le64(data); 231 break; 232 default: 233 hw_error("vfio: unsupported write size, %u bytes", size); 234 break; 235 } 236 237 if (pwrite(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) { 238 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", 0x%"PRIx64 239 ",%d) failed: %m", 240 __func__, vbasedev->name, region->nr, 241 addr, data, size); 242 } 243 244 trace_vfio_region_write(vbasedev->name, region->nr, addr, data, size); 245 246 /* 247 * A read or write to a BAR always signals an INTx EOI. This will 248 * do nothing if not pending (including not in INTx mode). We assume 249 * that a BAR access is in response to an interrupt and that BAR 250 * accesses will service the interrupt. Unfortunately, we don't know 251 * which access will service the interrupt, so we're potentially 252 * getting quite a few host interrupts per guest interrupt. 253 */ 254 vbasedev->ops->vfio_eoi(vbasedev); 255 } 256 257 uint64_t vfio_region_read(void *opaque, 258 hwaddr addr, unsigned size) 259 { 260 VFIORegion *region = opaque; 261 VFIODevice *vbasedev = region->vbasedev; 262 union { 263 uint8_t byte; 264 uint16_t word; 265 uint32_t dword; 266 uint64_t qword; 267 } buf; 268 uint64_t data = 0; 269 270 if (pread(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) { 271 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", %d) failed: %m", 272 __func__, vbasedev->name, region->nr, 273 addr, size); 274 return (uint64_t)-1; 275 } 276 switch (size) { 277 case 1: 278 data = buf.byte; 279 break; 280 case 2: 281 data = le16_to_cpu(buf.word); 282 break; 283 case 4: 284 data = le32_to_cpu(buf.dword); 285 break; 286 case 8: 287 data = le64_to_cpu(buf.qword); 288 break; 289 default: 290 hw_error("vfio: unsupported read size, %u bytes", size); 291 break; 292 } 293 294 trace_vfio_region_read(vbasedev->name, region->nr, addr, size, data); 295 296 /* Same as write above */ 297 vbasedev->ops->vfio_eoi(vbasedev); 298 299 return data; 300 } 301 302 const MemoryRegionOps vfio_region_ops = { 303 .read = vfio_region_read, 304 .write = vfio_region_write, 305 .endianness = DEVICE_LITTLE_ENDIAN, 306 .valid = { 307 .min_access_size = 1, 308 .max_access_size = 8, 309 }, 310 .impl = { 311 .min_access_size = 1, 312 .max_access_size = 8, 313 }, 314 }; 315 316 /* 317 * Device state interfaces 318 */ 319 320 bool vfio_mig_active(void) 321 { 322 VFIOGroup *group; 323 VFIODevice *vbasedev; 324 325 if (QLIST_EMPTY(&vfio_group_list)) { 326 return false; 327 } 328 329 QLIST_FOREACH(group, &vfio_group_list, next) { 330 QLIST_FOREACH(vbasedev, &group->device_list, next) { 331 if (vbasedev->migration_blocker) { 332 return false; 333 } 334 } 335 } 336 return true; 337 } 338 339 static bool vfio_devices_all_dirty_tracking(VFIOContainer *container) 340 { 341 VFIOGroup *group; 342 VFIODevice *vbasedev; 343 MigrationState *ms = migrate_get_current(); 344 345 if (!migration_is_setup_or_active(ms->state)) { 346 return false; 347 } 348 349 QLIST_FOREACH(group, &container->group_list, container_next) { 350 QLIST_FOREACH(vbasedev, &group->device_list, next) { 351 VFIOMigration *migration = vbasedev->migration; 352 353 if (!migration) { 354 return false; 355 } 356 357 if ((vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF) 358 && (migration->device_state & VFIO_DEVICE_STATE_V1_RUNNING)) { 359 return false; 360 } 361 } 362 } 363 return true; 364 } 365 366 static bool vfio_devices_all_running_and_saving(VFIOContainer *container) 367 { 368 VFIOGroup *group; 369 VFIODevice *vbasedev; 370 MigrationState *ms = migrate_get_current(); 371 372 if (!migration_is_setup_or_active(ms->state)) { 373 return false; 374 } 375 376 QLIST_FOREACH(group, &container->group_list, container_next) { 377 QLIST_FOREACH(vbasedev, &group->device_list, next) { 378 VFIOMigration *migration = vbasedev->migration; 379 380 if (!migration) { 381 return false; 382 } 383 384 if ((migration->device_state & VFIO_DEVICE_STATE_V1_SAVING) && 385 (migration->device_state & VFIO_DEVICE_STATE_V1_RUNNING)) { 386 continue; 387 } else { 388 return false; 389 } 390 } 391 } 392 return true; 393 } 394 395 static int vfio_dma_unmap_bitmap(VFIOContainer *container, 396 hwaddr iova, ram_addr_t size, 397 IOMMUTLBEntry *iotlb) 398 { 399 struct vfio_iommu_type1_dma_unmap *unmap; 400 struct vfio_bitmap *bitmap; 401 uint64_t pages = REAL_HOST_PAGE_ALIGN(size) / qemu_real_host_page_size(); 402 int ret; 403 404 unmap = g_malloc0(sizeof(*unmap) + sizeof(*bitmap)); 405 406 unmap->argsz = sizeof(*unmap) + sizeof(*bitmap); 407 unmap->iova = iova; 408 unmap->size = size; 409 unmap->flags |= VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP; 410 bitmap = (struct vfio_bitmap *)&unmap->data; 411 412 /* 413 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of 414 * qemu_real_host_page_size to mark those dirty. Hence set bitmap_pgsize 415 * to qemu_real_host_page_size. 416 */ 417 418 bitmap->pgsize = qemu_real_host_page_size(); 419 bitmap->size = ROUND_UP(pages, sizeof(__u64) * BITS_PER_BYTE) / 420 BITS_PER_BYTE; 421 422 if (bitmap->size > container->max_dirty_bitmap_size) { 423 error_report("UNMAP: Size of bitmap too big 0x%"PRIx64, 424 (uint64_t)bitmap->size); 425 ret = -E2BIG; 426 goto unmap_exit; 427 } 428 429 bitmap->data = g_try_malloc0(bitmap->size); 430 if (!bitmap->data) { 431 ret = -ENOMEM; 432 goto unmap_exit; 433 } 434 435 ret = ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, unmap); 436 if (!ret) { 437 cpu_physical_memory_set_dirty_lebitmap((unsigned long *)bitmap->data, 438 iotlb->translated_addr, pages); 439 } else { 440 error_report("VFIO_UNMAP_DMA with DIRTY_BITMAP : %m"); 441 } 442 443 g_free(bitmap->data); 444 unmap_exit: 445 g_free(unmap); 446 return ret; 447 } 448 449 /* 450 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86 451 */ 452 static int vfio_dma_unmap(VFIOContainer *container, 453 hwaddr iova, ram_addr_t size, 454 IOMMUTLBEntry *iotlb) 455 { 456 struct vfio_iommu_type1_dma_unmap unmap = { 457 .argsz = sizeof(unmap), 458 .flags = 0, 459 .iova = iova, 460 .size = size, 461 }; 462 463 if (iotlb && container->dirty_pages_supported && 464 vfio_devices_all_running_and_saving(container)) { 465 return vfio_dma_unmap_bitmap(container, iova, size, iotlb); 466 } 467 468 while (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) { 469 /* 470 * The type1 backend has an off-by-one bug in the kernel (71a7d3d78e3c 471 * v4.15) where an overflow in its wrap-around check prevents us from 472 * unmapping the last page of the address space. Test for the error 473 * condition and re-try the unmap excluding the last page. The 474 * expectation is that we've never mapped the last page anyway and this 475 * unmap request comes via vIOMMU support which also makes it unlikely 476 * that this page is used. This bug was introduced well after type1 v2 477 * support was introduced, so we shouldn't need to test for v1. A fix 478 * is queued for kernel v5.0 so this workaround can be removed once 479 * affected kernels are sufficiently deprecated. 480 */ 481 if (errno == EINVAL && unmap.size && !(unmap.iova + unmap.size) && 482 container->iommu_type == VFIO_TYPE1v2_IOMMU) { 483 trace_vfio_dma_unmap_overflow_workaround(); 484 unmap.size -= 1ULL << ctz64(container->pgsizes); 485 continue; 486 } 487 error_report("VFIO_UNMAP_DMA failed: %s", strerror(errno)); 488 return -errno; 489 } 490 491 return 0; 492 } 493 494 static int vfio_dma_map(VFIOContainer *container, hwaddr iova, 495 ram_addr_t size, void *vaddr, bool readonly) 496 { 497 struct vfio_iommu_type1_dma_map map = { 498 .argsz = sizeof(map), 499 .flags = VFIO_DMA_MAP_FLAG_READ, 500 .vaddr = (__u64)(uintptr_t)vaddr, 501 .iova = iova, 502 .size = size, 503 }; 504 505 if (!readonly) { 506 map.flags |= VFIO_DMA_MAP_FLAG_WRITE; 507 } 508 509 /* 510 * Try the mapping, if it fails with EBUSY, unmap the region and try 511 * again. This shouldn't be necessary, but we sometimes see it in 512 * the VGA ROM space. 513 */ 514 if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 || 515 (errno == EBUSY && vfio_dma_unmap(container, iova, size, NULL) == 0 && 516 ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) { 517 return 0; 518 } 519 520 error_report("VFIO_MAP_DMA failed: %s", strerror(errno)); 521 return -errno; 522 } 523 524 static void vfio_host_win_add(VFIOContainer *container, 525 hwaddr min_iova, hwaddr max_iova, 526 uint64_t iova_pgsizes) 527 { 528 VFIOHostDMAWindow *hostwin; 529 530 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) { 531 if (ranges_overlap(hostwin->min_iova, 532 hostwin->max_iova - hostwin->min_iova + 1, 533 min_iova, 534 max_iova - min_iova + 1)) { 535 hw_error("%s: Overlapped IOMMU are not enabled", __func__); 536 } 537 } 538 539 hostwin = g_malloc0(sizeof(*hostwin)); 540 541 hostwin->min_iova = min_iova; 542 hostwin->max_iova = max_iova; 543 hostwin->iova_pgsizes = iova_pgsizes; 544 QLIST_INSERT_HEAD(&container->hostwin_list, hostwin, hostwin_next); 545 } 546 547 static int vfio_host_win_del(VFIOContainer *container, hwaddr min_iova, 548 hwaddr max_iova) 549 { 550 VFIOHostDMAWindow *hostwin; 551 552 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) { 553 if (hostwin->min_iova == min_iova && hostwin->max_iova == max_iova) { 554 QLIST_REMOVE(hostwin, hostwin_next); 555 g_free(hostwin); 556 return 0; 557 } 558 } 559 560 return -1; 561 } 562 563 static bool vfio_listener_skipped_section(MemoryRegionSection *section) 564 { 565 return (!memory_region_is_ram(section->mr) && 566 !memory_region_is_iommu(section->mr)) || 567 memory_region_is_protected(section->mr) || 568 /* 569 * Sizing an enabled 64-bit BAR can cause spurious mappings to 570 * addresses in the upper part of the 64-bit address space. These 571 * are never accessed by the CPU and beyond the address width of 572 * some IOMMU hardware. TODO: VFIO should tell us the IOMMU width. 573 */ 574 section->offset_within_address_space & (1ULL << 63); 575 } 576 577 /* Called with rcu_read_lock held. */ 578 static bool vfio_get_xlat_addr(IOMMUTLBEntry *iotlb, void **vaddr, 579 ram_addr_t *ram_addr, bool *read_only) 580 { 581 MemoryRegion *mr; 582 hwaddr xlat; 583 hwaddr len = iotlb->addr_mask + 1; 584 bool writable = iotlb->perm & IOMMU_WO; 585 586 /* 587 * The IOMMU TLB entry we have just covers translation through 588 * this IOMMU to its immediate target. We need to translate 589 * it the rest of the way through to memory. 590 */ 591 mr = address_space_translate(&address_space_memory, 592 iotlb->translated_addr, 593 &xlat, &len, writable, 594 MEMTXATTRS_UNSPECIFIED); 595 if (!memory_region_is_ram(mr)) { 596 error_report("iommu map to non memory area %"HWADDR_PRIx"", 597 xlat); 598 return false; 599 } else if (memory_region_has_ram_discard_manager(mr)) { 600 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(mr); 601 MemoryRegionSection tmp = { 602 .mr = mr, 603 .offset_within_region = xlat, 604 .size = int128_make64(len), 605 }; 606 607 /* 608 * Malicious VMs can map memory into the IOMMU, which is expected 609 * to remain discarded. vfio will pin all pages, populating memory. 610 * Disallow that. vmstate priorities make sure any RamDiscardManager 611 * were already restored before IOMMUs are restored. 612 */ 613 if (!ram_discard_manager_is_populated(rdm, &tmp)) { 614 error_report("iommu map to discarded memory (e.g., unplugged via" 615 " virtio-mem): %"HWADDR_PRIx"", 616 iotlb->translated_addr); 617 return false; 618 } 619 620 /* 621 * Malicious VMs might trigger discarding of IOMMU-mapped memory. The 622 * pages will remain pinned inside vfio until unmapped, resulting in a 623 * higher memory consumption than expected. If memory would get 624 * populated again later, there would be an inconsistency between pages 625 * pinned by vfio and pages seen by QEMU. This is the case until 626 * unmapped from the IOMMU (e.g., during device reset). 627 * 628 * With malicious guests, we really only care about pinning more memory 629 * than expected. RLIMIT_MEMLOCK set for the user/process can never be 630 * exceeded and can be used to mitigate this problem. 631 */ 632 warn_report_once("Using vfio with vIOMMUs and coordinated discarding of" 633 " RAM (e.g., virtio-mem) works, however, malicious" 634 " guests can trigger pinning of more memory than" 635 " intended via an IOMMU. It's possible to mitigate " 636 " by setting/adjusting RLIMIT_MEMLOCK."); 637 } 638 639 /* 640 * Translation truncates length to the IOMMU page size, 641 * check that it did not truncate too much. 642 */ 643 if (len & iotlb->addr_mask) { 644 error_report("iommu has granularity incompatible with target AS"); 645 return false; 646 } 647 648 if (vaddr) { 649 *vaddr = memory_region_get_ram_ptr(mr) + xlat; 650 } 651 652 if (ram_addr) { 653 *ram_addr = memory_region_get_ram_addr(mr) + xlat; 654 } 655 656 if (read_only) { 657 *read_only = !writable || mr->readonly; 658 } 659 660 return true; 661 } 662 663 static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb) 664 { 665 VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n); 666 VFIOContainer *container = giommu->container; 667 hwaddr iova = iotlb->iova + giommu->iommu_offset; 668 void *vaddr; 669 int ret; 670 671 trace_vfio_iommu_map_notify(iotlb->perm == IOMMU_NONE ? "UNMAP" : "MAP", 672 iova, iova + iotlb->addr_mask); 673 674 if (iotlb->target_as != &address_space_memory) { 675 error_report("Wrong target AS \"%s\", only system memory is allowed", 676 iotlb->target_as->name ? iotlb->target_as->name : "none"); 677 return; 678 } 679 680 rcu_read_lock(); 681 682 if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) { 683 bool read_only; 684 685 if (!vfio_get_xlat_addr(iotlb, &vaddr, NULL, &read_only)) { 686 goto out; 687 } 688 /* 689 * vaddr is only valid until rcu_read_unlock(). But after 690 * vfio_dma_map has set up the mapping the pages will be 691 * pinned by the kernel. This makes sure that the RAM backend 692 * of vaddr will always be there, even if the memory object is 693 * destroyed and its backing memory munmap-ed. 694 */ 695 ret = vfio_dma_map(container, iova, 696 iotlb->addr_mask + 1, vaddr, 697 read_only); 698 if (ret) { 699 error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", " 700 "0x%"HWADDR_PRIx", %p) = %d (%m)", 701 container, iova, 702 iotlb->addr_mask + 1, vaddr, ret); 703 } 704 } else { 705 ret = vfio_dma_unmap(container, iova, iotlb->addr_mask + 1, iotlb); 706 if (ret) { 707 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", " 708 "0x%"HWADDR_PRIx") = %d (%m)", 709 container, iova, 710 iotlb->addr_mask + 1, ret); 711 } 712 } 713 out: 714 rcu_read_unlock(); 715 } 716 717 static void vfio_ram_discard_notify_discard(RamDiscardListener *rdl, 718 MemoryRegionSection *section) 719 { 720 VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener, 721 listener); 722 const hwaddr size = int128_get64(section->size); 723 const hwaddr iova = section->offset_within_address_space; 724 int ret; 725 726 /* Unmap with a single call. */ 727 ret = vfio_dma_unmap(vrdl->container, iova, size , NULL); 728 if (ret) { 729 error_report("%s: vfio_dma_unmap() failed: %s", __func__, 730 strerror(-ret)); 731 } 732 } 733 734 static int vfio_ram_discard_notify_populate(RamDiscardListener *rdl, 735 MemoryRegionSection *section) 736 { 737 VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener, 738 listener); 739 const hwaddr end = section->offset_within_region + 740 int128_get64(section->size); 741 hwaddr start, next, iova; 742 void *vaddr; 743 int ret; 744 745 /* 746 * Map in (aligned within memory region) minimum granularity, so we can 747 * unmap in minimum granularity later. 748 */ 749 for (start = section->offset_within_region; start < end; start = next) { 750 next = ROUND_UP(start + 1, vrdl->granularity); 751 next = MIN(next, end); 752 753 iova = start - section->offset_within_region + 754 section->offset_within_address_space; 755 vaddr = memory_region_get_ram_ptr(section->mr) + start; 756 757 ret = vfio_dma_map(vrdl->container, iova, next - start, 758 vaddr, section->readonly); 759 if (ret) { 760 /* Rollback */ 761 vfio_ram_discard_notify_discard(rdl, section); 762 return ret; 763 } 764 } 765 return 0; 766 } 767 768 static void vfio_register_ram_discard_listener(VFIOContainer *container, 769 MemoryRegionSection *section) 770 { 771 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr); 772 VFIORamDiscardListener *vrdl; 773 774 /* Ignore some corner cases not relevant in practice. */ 775 g_assert(QEMU_IS_ALIGNED(section->offset_within_region, TARGET_PAGE_SIZE)); 776 g_assert(QEMU_IS_ALIGNED(section->offset_within_address_space, 777 TARGET_PAGE_SIZE)); 778 g_assert(QEMU_IS_ALIGNED(int128_get64(section->size), TARGET_PAGE_SIZE)); 779 780 vrdl = g_new0(VFIORamDiscardListener, 1); 781 vrdl->container = container; 782 vrdl->mr = section->mr; 783 vrdl->offset_within_address_space = section->offset_within_address_space; 784 vrdl->size = int128_get64(section->size); 785 vrdl->granularity = ram_discard_manager_get_min_granularity(rdm, 786 section->mr); 787 788 g_assert(vrdl->granularity && is_power_of_2(vrdl->granularity)); 789 g_assert(container->pgsizes && 790 vrdl->granularity >= 1ULL << ctz64(container->pgsizes)); 791 792 ram_discard_listener_init(&vrdl->listener, 793 vfio_ram_discard_notify_populate, 794 vfio_ram_discard_notify_discard, true); 795 ram_discard_manager_register_listener(rdm, &vrdl->listener, section); 796 QLIST_INSERT_HEAD(&container->vrdl_list, vrdl, next); 797 798 /* 799 * Sanity-check if we have a theoretically problematic setup where we could 800 * exceed the maximum number of possible DMA mappings over time. We assume 801 * that each mapped section in the same address space as a RamDiscardManager 802 * section consumes exactly one DMA mapping, with the exception of 803 * RamDiscardManager sections; i.e., we don't expect to have gIOMMU sections 804 * in the same address space as RamDiscardManager sections. 805 * 806 * We assume that each section in the address space consumes one memslot. 807 * We take the number of KVM memory slots as a best guess for the maximum 808 * number of sections in the address space we could have over time, 809 * also consuming DMA mappings. 810 */ 811 if (container->dma_max_mappings) { 812 unsigned int vrdl_count = 0, vrdl_mappings = 0, max_memslots = 512; 813 814 #ifdef CONFIG_KVM 815 if (kvm_enabled()) { 816 max_memslots = kvm_get_max_memslots(); 817 } 818 #endif 819 820 QLIST_FOREACH(vrdl, &container->vrdl_list, next) { 821 hwaddr start, end; 822 823 start = QEMU_ALIGN_DOWN(vrdl->offset_within_address_space, 824 vrdl->granularity); 825 end = ROUND_UP(vrdl->offset_within_address_space + vrdl->size, 826 vrdl->granularity); 827 vrdl_mappings += (end - start) / vrdl->granularity; 828 vrdl_count++; 829 } 830 831 if (vrdl_mappings + max_memslots - vrdl_count > 832 container->dma_max_mappings) { 833 warn_report("%s: possibly running out of DMA mappings. E.g., try" 834 " increasing the 'block-size' of virtio-mem devies." 835 " Maximum possible DMA mappings: %d, Maximum possible" 836 " memslots: %d", __func__, container->dma_max_mappings, 837 max_memslots); 838 } 839 } 840 } 841 842 static void vfio_unregister_ram_discard_listener(VFIOContainer *container, 843 MemoryRegionSection *section) 844 { 845 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr); 846 VFIORamDiscardListener *vrdl = NULL; 847 848 QLIST_FOREACH(vrdl, &container->vrdl_list, next) { 849 if (vrdl->mr == section->mr && 850 vrdl->offset_within_address_space == 851 section->offset_within_address_space) { 852 break; 853 } 854 } 855 856 if (!vrdl) { 857 hw_error("vfio: Trying to unregister missing RAM discard listener"); 858 } 859 860 ram_discard_manager_unregister_listener(rdm, &vrdl->listener); 861 QLIST_REMOVE(vrdl, next); 862 g_free(vrdl); 863 } 864 865 static bool vfio_known_safe_misalignment(MemoryRegionSection *section) 866 { 867 MemoryRegion *mr = section->mr; 868 869 if (!TPM_IS_CRB(mr->owner)) { 870 return false; 871 } 872 873 /* this is a known safe misaligned region, just trace for debug purpose */ 874 trace_vfio_known_safe_misalignment(memory_region_name(mr), 875 section->offset_within_address_space, 876 section->offset_within_region, 877 qemu_real_host_page_size()); 878 return true; 879 } 880 881 static void vfio_listener_region_add(MemoryListener *listener, 882 MemoryRegionSection *section) 883 { 884 VFIOContainer *container = container_of(listener, VFIOContainer, listener); 885 hwaddr iova, end; 886 Int128 llend, llsize; 887 void *vaddr; 888 int ret; 889 VFIOHostDMAWindow *hostwin; 890 bool hostwin_found; 891 Error *err = NULL; 892 893 if (vfio_listener_skipped_section(section)) { 894 trace_vfio_listener_region_add_skip( 895 section->offset_within_address_space, 896 section->offset_within_address_space + 897 int128_get64(int128_sub(section->size, int128_one()))); 898 return; 899 } 900 901 if (unlikely((section->offset_within_address_space & 902 ~qemu_real_host_page_mask()) != 903 (section->offset_within_region & ~qemu_real_host_page_mask()))) { 904 if (!vfio_known_safe_misalignment(section)) { 905 error_report("%s received unaligned region %s iova=0x%"PRIx64 906 " offset_within_region=0x%"PRIx64 907 " qemu_real_host_page_size=0x%"PRIxPTR, 908 __func__, memory_region_name(section->mr), 909 section->offset_within_address_space, 910 section->offset_within_region, 911 qemu_real_host_page_size()); 912 } 913 return; 914 } 915 916 iova = REAL_HOST_PAGE_ALIGN(section->offset_within_address_space); 917 llend = int128_make64(section->offset_within_address_space); 918 llend = int128_add(llend, section->size); 919 llend = int128_and(llend, int128_exts64(qemu_real_host_page_mask())); 920 921 if (int128_ge(int128_make64(iova), llend)) { 922 if (memory_region_is_ram_device(section->mr)) { 923 trace_vfio_listener_region_add_no_dma_map( 924 memory_region_name(section->mr), 925 section->offset_within_address_space, 926 int128_getlo(section->size), 927 qemu_real_host_page_size()); 928 } 929 return; 930 } 931 end = int128_get64(int128_sub(llend, int128_one())); 932 933 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) { 934 hwaddr pgsize = 0; 935 936 /* For now intersections are not allowed, we may relax this later */ 937 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) { 938 if (ranges_overlap(hostwin->min_iova, 939 hostwin->max_iova - hostwin->min_iova + 1, 940 section->offset_within_address_space, 941 int128_get64(section->size))) { 942 error_setg(&err, 943 "region [0x%"PRIx64",0x%"PRIx64"] overlaps with existing" 944 "host DMA window [0x%"PRIx64",0x%"PRIx64"]", 945 section->offset_within_address_space, 946 section->offset_within_address_space + 947 int128_get64(section->size) - 1, 948 hostwin->min_iova, hostwin->max_iova); 949 goto fail; 950 } 951 } 952 953 ret = vfio_spapr_create_window(container, section, &pgsize); 954 if (ret) { 955 error_setg_errno(&err, -ret, "Failed to create SPAPR window"); 956 goto fail; 957 } 958 959 vfio_host_win_add(container, section->offset_within_address_space, 960 section->offset_within_address_space + 961 int128_get64(section->size) - 1, pgsize); 962 #ifdef CONFIG_KVM 963 if (kvm_enabled()) { 964 VFIOGroup *group; 965 IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr); 966 struct kvm_vfio_spapr_tce param; 967 struct kvm_device_attr attr = { 968 .group = KVM_DEV_VFIO_GROUP, 969 .attr = KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE, 970 .addr = (uint64_t)(unsigned long)¶m, 971 }; 972 973 if (!memory_region_iommu_get_attr(iommu_mr, IOMMU_ATTR_SPAPR_TCE_FD, 974 ¶m.tablefd)) { 975 QLIST_FOREACH(group, &container->group_list, container_next) { 976 param.groupfd = group->fd; 977 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) { 978 error_report("vfio: failed to setup fd %d " 979 "for a group with fd %d: %s", 980 param.tablefd, param.groupfd, 981 strerror(errno)); 982 return; 983 } 984 trace_vfio_spapr_group_attach(param.groupfd, param.tablefd); 985 } 986 } 987 } 988 #endif 989 } 990 991 hostwin_found = false; 992 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) { 993 if (hostwin->min_iova <= iova && end <= hostwin->max_iova) { 994 hostwin_found = true; 995 break; 996 } 997 } 998 999 if (!hostwin_found) { 1000 error_setg(&err, "Container %p can't map guest IOVA region" 1001 " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx, container, iova, end); 1002 goto fail; 1003 } 1004 1005 memory_region_ref(section->mr); 1006 1007 if (memory_region_is_iommu(section->mr)) { 1008 VFIOGuestIOMMU *giommu; 1009 IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr); 1010 int iommu_idx; 1011 1012 trace_vfio_listener_region_add_iommu(iova, end); 1013 /* 1014 * FIXME: For VFIO iommu types which have KVM acceleration to 1015 * avoid bouncing all map/unmaps through qemu this way, this 1016 * would be the right place to wire that up (tell the KVM 1017 * device emulation the VFIO iommu handles to use). 1018 */ 1019 giommu = g_malloc0(sizeof(*giommu)); 1020 giommu->iommu_mr = iommu_mr; 1021 giommu->iommu_offset = section->offset_within_address_space - 1022 section->offset_within_region; 1023 giommu->container = container; 1024 llend = int128_add(int128_make64(section->offset_within_region), 1025 section->size); 1026 llend = int128_sub(llend, int128_one()); 1027 iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr, 1028 MEMTXATTRS_UNSPECIFIED); 1029 iommu_notifier_init(&giommu->n, vfio_iommu_map_notify, 1030 IOMMU_NOTIFIER_IOTLB_EVENTS, 1031 section->offset_within_region, 1032 int128_get64(llend), 1033 iommu_idx); 1034 1035 ret = memory_region_iommu_set_page_size_mask(giommu->iommu_mr, 1036 container->pgsizes, 1037 &err); 1038 if (ret) { 1039 g_free(giommu); 1040 goto fail; 1041 } 1042 1043 ret = memory_region_register_iommu_notifier(section->mr, &giommu->n, 1044 &err); 1045 if (ret) { 1046 g_free(giommu); 1047 goto fail; 1048 } 1049 QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next); 1050 memory_region_iommu_replay(giommu->iommu_mr, &giommu->n); 1051 1052 return; 1053 } 1054 1055 /* Here we assume that memory_region_is_ram(section->mr)==true */ 1056 1057 /* 1058 * For RAM memory regions with a RamDiscardManager, we only want to map the 1059 * actually populated parts - and update the mapping whenever we're notified 1060 * about changes. 1061 */ 1062 if (memory_region_has_ram_discard_manager(section->mr)) { 1063 vfio_register_ram_discard_listener(container, section); 1064 return; 1065 } 1066 1067 vaddr = memory_region_get_ram_ptr(section->mr) + 1068 section->offset_within_region + 1069 (iova - section->offset_within_address_space); 1070 1071 trace_vfio_listener_region_add_ram(iova, end, vaddr); 1072 1073 llsize = int128_sub(llend, int128_make64(iova)); 1074 1075 if (memory_region_is_ram_device(section->mr)) { 1076 hwaddr pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1; 1077 1078 if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) { 1079 trace_vfio_listener_region_add_no_dma_map( 1080 memory_region_name(section->mr), 1081 section->offset_within_address_space, 1082 int128_getlo(section->size), 1083 pgmask + 1); 1084 return; 1085 } 1086 } 1087 1088 ret = vfio_dma_map(container, iova, int128_get64(llsize), 1089 vaddr, section->readonly); 1090 if (ret) { 1091 error_setg(&err, "vfio_dma_map(%p, 0x%"HWADDR_PRIx", " 1092 "0x%"HWADDR_PRIx", %p) = %d (%m)", 1093 container, iova, int128_get64(llsize), vaddr, ret); 1094 if (memory_region_is_ram_device(section->mr)) { 1095 /* Allow unexpected mappings not to be fatal for RAM devices */ 1096 error_report_err(err); 1097 return; 1098 } 1099 goto fail; 1100 } 1101 1102 return; 1103 1104 fail: 1105 if (memory_region_is_ram_device(section->mr)) { 1106 error_report("failed to vfio_dma_map. pci p2p may not work"); 1107 return; 1108 } 1109 /* 1110 * On the initfn path, store the first error in the container so we 1111 * can gracefully fail. Runtime, there's not much we can do other 1112 * than throw a hardware error. 1113 */ 1114 if (!container->initialized) { 1115 if (!container->error) { 1116 error_propagate_prepend(&container->error, err, 1117 "Region %s: ", 1118 memory_region_name(section->mr)); 1119 } else { 1120 error_free(err); 1121 } 1122 } else { 1123 error_report_err(err); 1124 hw_error("vfio: DMA mapping failed, unable to continue"); 1125 } 1126 } 1127 1128 static void vfio_listener_region_del(MemoryListener *listener, 1129 MemoryRegionSection *section) 1130 { 1131 VFIOContainer *container = container_of(listener, VFIOContainer, listener); 1132 hwaddr iova, end; 1133 Int128 llend, llsize; 1134 int ret; 1135 bool try_unmap = true; 1136 1137 if (vfio_listener_skipped_section(section)) { 1138 trace_vfio_listener_region_del_skip( 1139 section->offset_within_address_space, 1140 section->offset_within_address_space + 1141 int128_get64(int128_sub(section->size, int128_one()))); 1142 return; 1143 } 1144 1145 if (unlikely((section->offset_within_address_space & 1146 ~qemu_real_host_page_mask()) != 1147 (section->offset_within_region & ~qemu_real_host_page_mask()))) { 1148 error_report("%s received unaligned region", __func__); 1149 return; 1150 } 1151 1152 if (memory_region_is_iommu(section->mr)) { 1153 VFIOGuestIOMMU *giommu; 1154 1155 QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) { 1156 if (MEMORY_REGION(giommu->iommu_mr) == section->mr && 1157 giommu->n.start == section->offset_within_region) { 1158 memory_region_unregister_iommu_notifier(section->mr, 1159 &giommu->n); 1160 QLIST_REMOVE(giommu, giommu_next); 1161 g_free(giommu); 1162 break; 1163 } 1164 } 1165 1166 /* 1167 * FIXME: We assume the one big unmap below is adequate to 1168 * remove any individual page mappings in the IOMMU which 1169 * might have been copied into VFIO. This works for a page table 1170 * based IOMMU where a big unmap flattens a large range of IO-PTEs. 1171 * That may not be true for all IOMMU types. 1172 */ 1173 } 1174 1175 iova = REAL_HOST_PAGE_ALIGN(section->offset_within_address_space); 1176 llend = int128_make64(section->offset_within_address_space); 1177 llend = int128_add(llend, section->size); 1178 llend = int128_and(llend, int128_exts64(qemu_real_host_page_mask())); 1179 1180 if (int128_ge(int128_make64(iova), llend)) { 1181 return; 1182 } 1183 end = int128_get64(int128_sub(llend, int128_one())); 1184 1185 llsize = int128_sub(llend, int128_make64(iova)); 1186 1187 trace_vfio_listener_region_del(iova, end); 1188 1189 if (memory_region_is_ram_device(section->mr)) { 1190 hwaddr pgmask; 1191 VFIOHostDMAWindow *hostwin; 1192 bool hostwin_found = false; 1193 1194 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) { 1195 if (hostwin->min_iova <= iova && end <= hostwin->max_iova) { 1196 hostwin_found = true; 1197 break; 1198 } 1199 } 1200 assert(hostwin_found); /* or region_add() would have failed */ 1201 1202 pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1; 1203 try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask)); 1204 } else if (memory_region_has_ram_discard_manager(section->mr)) { 1205 vfio_unregister_ram_discard_listener(container, section); 1206 /* Unregistering will trigger an unmap. */ 1207 try_unmap = false; 1208 } 1209 1210 if (try_unmap) { 1211 if (int128_eq(llsize, int128_2_64())) { 1212 /* The unmap ioctl doesn't accept a full 64-bit span. */ 1213 llsize = int128_rshift(llsize, 1); 1214 ret = vfio_dma_unmap(container, iova, int128_get64(llsize), NULL); 1215 if (ret) { 1216 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", " 1217 "0x%"HWADDR_PRIx") = %d (%m)", 1218 container, iova, int128_get64(llsize), ret); 1219 } 1220 iova += int128_get64(llsize); 1221 } 1222 ret = vfio_dma_unmap(container, iova, int128_get64(llsize), NULL); 1223 if (ret) { 1224 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", " 1225 "0x%"HWADDR_PRIx") = %d (%m)", 1226 container, iova, int128_get64(llsize), ret); 1227 } 1228 } 1229 1230 memory_region_unref(section->mr); 1231 1232 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) { 1233 vfio_spapr_remove_window(container, 1234 section->offset_within_address_space); 1235 if (vfio_host_win_del(container, 1236 section->offset_within_address_space, 1237 section->offset_within_address_space + 1238 int128_get64(section->size) - 1) < 0) { 1239 hw_error("%s: Cannot delete missing window at %"HWADDR_PRIx, 1240 __func__, section->offset_within_address_space); 1241 } 1242 } 1243 } 1244 1245 static void vfio_set_dirty_page_tracking(VFIOContainer *container, bool start) 1246 { 1247 int ret; 1248 struct vfio_iommu_type1_dirty_bitmap dirty = { 1249 .argsz = sizeof(dirty), 1250 }; 1251 1252 if (start) { 1253 dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_START; 1254 } else { 1255 dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP; 1256 } 1257 1258 ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, &dirty); 1259 if (ret) { 1260 error_report("Failed to set dirty tracking flag 0x%x errno: %d", 1261 dirty.flags, errno); 1262 } 1263 } 1264 1265 static void vfio_listener_log_global_start(MemoryListener *listener) 1266 { 1267 VFIOContainer *container = container_of(listener, VFIOContainer, listener); 1268 1269 vfio_set_dirty_page_tracking(container, true); 1270 } 1271 1272 static void vfio_listener_log_global_stop(MemoryListener *listener) 1273 { 1274 VFIOContainer *container = container_of(listener, VFIOContainer, listener); 1275 1276 vfio_set_dirty_page_tracking(container, false); 1277 } 1278 1279 static int vfio_get_dirty_bitmap(VFIOContainer *container, uint64_t iova, 1280 uint64_t size, ram_addr_t ram_addr) 1281 { 1282 struct vfio_iommu_type1_dirty_bitmap *dbitmap; 1283 struct vfio_iommu_type1_dirty_bitmap_get *range; 1284 uint64_t pages; 1285 int ret; 1286 1287 dbitmap = g_malloc0(sizeof(*dbitmap) + sizeof(*range)); 1288 1289 dbitmap->argsz = sizeof(*dbitmap) + sizeof(*range); 1290 dbitmap->flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP; 1291 range = (struct vfio_iommu_type1_dirty_bitmap_get *)&dbitmap->data; 1292 range->iova = iova; 1293 range->size = size; 1294 1295 /* 1296 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of 1297 * qemu_real_host_page_size to mark those dirty. Hence set bitmap's pgsize 1298 * to qemu_real_host_page_size. 1299 */ 1300 range->bitmap.pgsize = qemu_real_host_page_size(); 1301 1302 pages = REAL_HOST_PAGE_ALIGN(range->size) / qemu_real_host_page_size(); 1303 range->bitmap.size = ROUND_UP(pages, sizeof(__u64) * BITS_PER_BYTE) / 1304 BITS_PER_BYTE; 1305 range->bitmap.data = g_try_malloc0(range->bitmap.size); 1306 if (!range->bitmap.data) { 1307 ret = -ENOMEM; 1308 goto err_out; 1309 } 1310 1311 ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, dbitmap); 1312 if (ret) { 1313 error_report("Failed to get dirty bitmap for iova: 0x%"PRIx64 1314 " size: 0x%"PRIx64" err: %d", (uint64_t)range->iova, 1315 (uint64_t)range->size, errno); 1316 goto err_out; 1317 } 1318 1319 cpu_physical_memory_set_dirty_lebitmap((unsigned long *)range->bitmap.data, 1320 ram_addr, pages); 1321 1322 trace_vfio_get_dirty_bitmap(container->fd, range->iova, range->size, 1323 range->bitmap.size, ram_addr); 1324 err_out: 1325 g_free(range->bitmap.data); 1326 g_free(dbitmap); 1327 1328 return ret; 1329 } 1330 1331 typedef struct { 1332 IOMMUNotifier n; 1333 VFIOGuestIOMMU *giommu; 1334 } vfio_giommu_dirty_notifier; 1335 1336 static void vfio_iommu_map_dirty_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb) 1337 { 1338 vfio_giommu_dirty_notifier *gdn = container_of(n, 1339 vfio_giommu_dirty_notifier, n); 1340 VFIOGuestIOMMU *giommu = gdn->giommu; 1341 VFIOContainer *container = giommu->container; 1342 hwaddr iova = iotlb->iova + giommu->iommu_offset; 1343 ram_addr_t translated_addr; 1344 1345 trace_vfio_iommu_map_dirty_notify(iova, iova + iotlb->addr_mask); 1346 1347 if (iotlb->target_as != &address_space_memory) { 1348 error_report("Wrong target AS \"%s\", only system memory is allowed", 1349 iotlb->target_as->name ? iotlb->target_as->name : "none"); 1350 return; 1351 } 1352 1353 rcu_read_lock(); 1354 if (vfio_get_xlat_addr(iotlb, NULL, &translated_addr, NULL)) { 1355 int ret; 1356 1357 ret = vfio_get_dirty_bitmap(container, iova, iotlb->addr_mask + 1, 1358 translated_addr); 1359 if (ret) { 1360 error_report("vfio_iommu_map_dirty_notify(%p, 0x%"HWADDR_PRIx", " 1361 "0x%"HWADDR_PRIx") = %d (%m)", 1362 container, iova, 1363 iotlb->addr_mask + 1, ret); 1364 } 1365 } 1366 rcu_read_unlock(); 1367 } 1368 1369 static int vfio_ram_discard_get_dirty_bitmap(MemoryRegionSection *section, 1370 void *opaque) 1371 { 1372 const hwaddr size = int128_get64(section->size); 1373 const hwaddr iova = section->offset_within_address_space; 1374 const ram_addr_t ram_addr = memory_region_get_ram_addr(section->mr) + 1375 section->offset_within_region; 1376 VFIORamDiscardListener *vrdl = opaque; 1377 1378 /* 1379 * Sync the whole mapped region (spanning multiple individual mappings) 1380 * in one go. 1381 */ 1382 return vfio_get_dirty_bitmap(vrdl->container, iova, size, ram_addr); 1383 } 1384 1385 static int vfio_sync_ram_discard_listener_dirty_bitmap(VFIOContainer *container, 1386 MemoryRegionSection *section) 1387 { 1388 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr); 1389 VFIORamDiscardListener *vrdl = NULL; 1390 1391 QLIST_FOREACH(vrdl, &container->vrdl_list, next) { 1392 if (vrdl->mr == section->mr && 1393 vrdl->offset_within_address_space == 1394 section->offset_within_address_space) { 1395 break; 1396 } 1397 } 1398 1399 if (!vrdl) { 1400 hw_error("vfio: Trying to sync missing RAM discard listener"); 1401 } 1402 1403 /* 1404 * We only want/can synchronize the bitmap for actually mapped parts - 1405 * which correspond to populated parts. Replay all populated parts. 1406 */ 1407 return ram_discard_manager_replay_populated(rdm, section, 1408 vfio_ram_discard_get_dirty_bitmap, 1409 &vrdl); 1410 } 1411 1412 static int vfio_sync_dirty_bitmap(VFIOContainer *container, 1413 MemoryRegionSection *section) 1414 { 1415 ram_addr_t ram_addr; 1416 1417 if (memory_region_is_iommu(section->mr)) { 1418 VFIOGuestIOMMU *giommu; 1419 1420 QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) { 1421 if (MEMORY_REGION(giommu->iommu_mr) == section->mr && 1422 giommu->n.start == section->offset_within_region) { 1423 Int128 llend; 1424 vfio_giommu_dirty_notifier gdn = { .giommu = giommu }; 1425 int idx = memory_region_iommu_attrs_to_index(giommu->iommu_mr, 1426 MEMTXATTRS_UNSPECIFIED); 1427 1428 llend = int128_add(int128_make64(section->offset_within_region), 1429 section->size); 1430 llend = int128_sub(llend, int128_one()); 1431 1432 iommu_notifier_init(&gdn.n, 1433 vfio_iommu_map_dirty_notify, 1434 IOMMU_NOTIFIER_MAP, 1435 section->offset_within_region, 1436 int128_get64(llend), 1437 idx); 1438 memory_region_iommu_replay(giommu->iommu_mr, &gdn.n); 1439 break; 1440 } 1441 } 1442 return 0; 1443 } else if (memory_region_has_ram_discard_manager(section->mr)) { 1444 return vfio_sync_ram_discard_listener_dirty_bitmap(container, section); 1445 } 1446 1447 ram_addr = memory_region_get_ram_addr(section->mr) + 1448 section->offset_within_region; 1449 1450 return vfio_get_dirty_bitmap(container, 1451 REAL_HOST_PAGE_ALIGN(section->offset_within_address_space), 1452 int128_get64(section->size), ram_addr); 1453 } 1454 1455 static void vfio_listener_log_sync(MemoryListener *listener, 1456 MemoryRegionSection *section) 1457 { 1458 VFIOContainer *container = container_of(listener, VFIOContainer, listener); 1459 1460 if (vfio_listener_skipped_section(section) || 1461 !container->dirty_pages_supported) { 1462 return; 1463 } 1464 1465 if (vfio_devices_all_dirty_tracking(container)) { 1466 vfio_sync_dirty_bitmap(container, section); 1467 } 1468 } 1469 1470 static const MemoryListener vfio_memory_listener = { 1471 .name = "vfio", 1472 .region_add = vfio_listener_region_add, 1473 .region_del = vfio_listener_region_del, 1474 .log_global_start = vfio_listener_log_global_start, 1475 .log_global_stop = vfio_listener_log_global_stop, 1476 .log_sync = vfio_listener_log_sync, 1477 }; 1478 1479 static void vfio_listener_release(VFIOContainer *container) 1480 { 1481 memory_listener_unregister(&container->listener); 1482 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) { 1483 memory_listener_unregister(&container->prereg_listener); 1484 } 1485 } 1486 1487 static struct vfio_info_cap_header * 1488 vfio_get_cap(void *ptr, uint32_t cap_offset, uint16_t id) 1489 { 1490 struct vfio_info_cap_header *hdr; 1491 1492 for (hdr = ptr + cap_offset; hdr != ptr; hdr = ptr + hdr->next) { 1493 if (hdr->id == id) { 1494 return hdr; 1495 } 1496 } 1497 1498 return NULL; 1499 } 1500 1501 struct vfio_info_cap_header * 1502 vfio_get_region_info_cap(struct vfio_region_info *info, uint16_t id) 1503 { 1504 if (!(info->flags & VFIO_REGION_INFO_FLAG_CAPS)) { 1505 return NULL; 1506 } 1507 1508 return vfio_get_cap((void *)info, info->cap_offset, id); 1509 } 1510 1511 static struct vfio_info_cap_header * 1512 vfio_get_iommu_type1_info_cap(struct vfio_iommu_type1_info *info, uint16_t id) 1513 { 1514 if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) { 1515 return NULL; 1516 } 1517 1518 return vfio_get_cap((void *)info, info->cap_offset, id); 1519 } 1520 1521 struct vfio_info_cap_header * 1522 vfio_get_device_info_cap(struct vfio_device_info *info, uint16_t id) 1523 { 1524 if (!(info->flags & VFIO_DEVICE_FLAGS_CAPS)) { 1525 return NULL; 1526 } 1527 1528 return vfio_get_cap((void *)info, info->cap_offset, id); 1529 } 1530 1531 bool vfio_get_info_dma_avail(struct vfio_iommu_type1_info *info, 1532 unsigned int *avail) 1533 { 1534 struct vfio_info_cap_header *hdr; 1535 struct vfio_iommu_type1_info_dma_avail *cap; 1536 1537 /* If the capability cannot be found, assume no DMA limiting */ 1538 hdr = vfio_get_iommu_type1_info_cap(info, 1539 VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL); 1540 if (hdr == NULL) { 1541 return false; 1542 } 1543 1544 if (avail != NULL) { 1545 cap = (void *) hdr; 1546 *avail = cap->avail; 1547 } 1548 1549 return true; 1550 } 1551 1552 static int vfio_setup_region_sparse_mmaps(VFIORegion *region, 1553 struct vfio_region_info *info) 1554 { 1555 struct vfio_info_cap_header *hdr; 1556 struct vfio_region_info_cap_sparse_mmap *sparse; 1557 int i, j; 1558 1559 hdr = vfio_get_region_info_cap(info, VFIO_REGION_INFO_CAP_SPARSE_MMAP); 1560 if (!hdr) { 1561 return -ENODEV; 1562 } 1563 1564 sparse = container_of(hdr, struct vfio_region_info_cap_sparse_mmap, header); 1565 1566 trace_vfio_region_sparse_mmap_header(region->vbasedev->name, 1567 region->nr, sparse->nr_areas); 1568 1569 region->mmaps = g_new0(VFIOMmap, sparse->nr_areas); 1570 1571 for (i = 0, j = 0; i < sparse->nr_areas; i++) { 1572 if (sparse->areas[i].size) { 1573 trace_vfio_region_sparse_mmap_entry(i, sparse->areas[i].offset, 1574 sparse->areas[i].offset + 1575 sparse->areas[i].size - 1); 1576 region->mmaps[j].offset = sparse->areas[i].offset; 1577 region->mmaps[j].size = sparse->areas[i].size; 1578 j++; 1579 } 1580 } 1581 1582 region->nr_mmaps = j; 1583 region->mmaps = g_realloc(region->mmaps, j * sizeof(VFIOMmap)); 1584 1585 return 0; 1586 } 1587 1588 int vfio_region_setup(Object *obj, VFIODevice *vbasedev, VFIORegion *region, 1589 int index, const char *name) 1590 { 1591 struct vfio_region_info *info; 1592 int ret; 1593 1594 ret = vfio_get_region_info(vbasedev, index, &info); 1595 if (ret) { 1596 return ret; 1597 } 1598 1599 region->vbasedev = vbasedev; 1600 region->flags = info->flags; 1601 region->size = info->size; 1602 region->fd_offset = info->offset; 1603 region->nr = index; 1604 1605 if (region->size) { 1606 region->mem = g_new0(MemoryRegion, 1); 1607 memory_region_init_io(region->mem, obj, &vfio_region_ops, 1608 region, name, region->size); 1609 1610 if (!vbasedev->no_mmap && 1611 region->flags & VFIO_REGION_INFO_FLAG_MMAP) { 1612 1613 ret = vfio_setup_region_sparse_mmaps(region, info); 1614 1615 if (ret) { 1616 region->nr_mmaps = 1; 1617 region->mmaps = g_new0(VFIOMmap, region->nr_mmaps); 1618 region->mmaps[0].offset = 0; 1619 region->mmaps[0].size = region->size; 1620 } 1621 } 1622 } 1623 1624 g_free(info); 1625 1626 trace_vfio_region_setup(vbasedev->name, index, name, 1627 region->flags, region->fd_offset, region->size); 1628 return 0; 1629 } 1630 1631 static void vfio_subregion_unmap(VFIORegion *region, int index) 1632 { 1633 trace_vfio_region_unmap(memory_region_name(®ion->mmaps[index].mem), 1634 region->mmaps[index].offset, 1635 region->mmaps[index].offset + 1636 region->mmaps[index].size - 1); 1637 memory_region_del_subregion(region->mem, ®ion->mmaps[index].mem); 1638 munmap(region->mmaps[index].mmap, region->mmaps[index].size); 1639 object_unparent(OBJECT(®ion->mmaps[index].mem)); 1640 region->mmaps[index].mmap = NULL; 1641 } 1642 1643 int vfio_region_mmap(VFIORegion *region) 1644 { 1645 int i, prot = 0; 1646 char *name; 1647 1648 if (!region->mem) { 1649 return 0; 1650 } 1651 1652 prot |= region->flags & VFIO_REGION_INFO_FLAG_READ ? PROT_READ : 0; 1653 prot |= region->flags & VFIO_REGION_INFO_FLAG_WRITE ? PROT_WRITE : 0; 1654 1655 for (i = 0; i < region->nr_mmaps; i++) { 1656 region->mmaps[i].mmap = mmap(NULL, region->mmaps[i].size, prot, 1657 MAP_SHARED, region->vbasedev->fd, 1658 region->fd_offset + 1659 region->mmaps[i].offset); 1660 if (region->mmaps[i].mmap == MAP_FAILED) { 1661 int ret = -errno; 1662 1663 trace_vfio_region_mmap_fault(memory_region_name(region->mem), i, 1664 region->fd_offset + 1665 region->mmaps[i].offset, 1666 region->fd_offset + 1667 region->mmaps[i].offset + 1668 region->mmaps[i].size - 1, ret); 1669 1670 region->mmaps[i].mmap = NULL; 1671 1672 for (i--; i >= 0; i--) { 1673 vfio_subregion_unmap(region, i); 1674 } 1675 1676 return ret; 1677 } 1678 1679 name = g_strdup_printf("%s mmaps[%d]", 1680 memory_region_name(region->mem), i); 1681 memory_region_init_ram_device_ptr(®ion->mmaps[i].mem, 1682 memory_region_owner(region->mem), 1683 name, region->mmaps[i].size, 1684 region->mmaps[i].mmap); 1685 g_free(name); 1686 memory_region_add_subregion(region->mem, region->mmaps[i].offset, 1687 ®ion->mmaps[i].mem); 1688 1689 trace_vfio_region_mmap(memory_region_name(®ion->mmaps[i].mem), 1690 region->mmaps[i].offset, 1691 region->mmaps[i].offset + 1692 region->mmaps[i].size - 1); 1693 } 1694 1695 return 0; 1696 } 1697 1698 void vfio_region_unmap(VFIORegion *region) 1699 { 1700 int i; 1701 1702 if (!region->mem) { 1703 return; 1704 } 1705 1706 for (i = 0; i < region->nr_mmaps; i++) { 1707 if (region->mmaps[i].mmap) { 1708 vfio_subregion_unmap(region, i); 1709 } 1710 } 1711 } 1712 1713 void vfio_region_exit(VFIORegion *region) 1714 { 1715 int i; 1716 1717 if (!region->mem) { 1718 return; 1719 } 1720 1721 for (i = 0; i < region->nr_mmaps; i++) { 1722 if (region->mmaps[i].mmap) { 1723 memory_region_del_subregion(region->mem, ®ion->mmaps[i].mem); 1724 } 1725 } 1726 1727 trace_vfio_region_exit(region->vbasedev->name, region->nr); 1728 } 1729 1730 void vfio_region_finalize(VFIORegion *region) 1731 { 1732 int i; 1733 1734 if (!region->mem) { 1735 return; 1736 } 1737 1738 for (i = 0; i < region->nr_mmaps; i++) { 1739 if (region->mmaps[i].mmap) { 1740 munmap(region->mmaps[i].mmap, region->mmaps[i].size); 1741 object_unparent(OBJECT(®ion->mmaps[i].mem)); 1742 } 1743 } 1744 1745 object_unparent(OBJECT(region->mem)); 1746 1747 g_free(region->mem); 1748 g_free(region->mmaps); 1749 1750 trace_vfio_region_finalize(region->vbasedev->name, region->nr); 1751 1752 region->mem = NULL; 1753 region->mmaps = NULL; 1754 region->nr_mmaps = 0; 1755 region->size = 0; 1756 region->flags = 0; 1757 region->nr = 0; 1758 } 1759 1760 void vfio_region_mmaps_set_enabled(VFIORegion *region, bool enabled) 1761 { 1762 int i; 1763 1764 if (!region->mem) { 1765 return; 1766 } 1767 1768 for (i = 0; i < region->nr_mmaps; i++) { 1769 if (region->mmaps[i].mmap) { 1770 memory_region_set_enabled(®ion->mmaps[i].mem, enabled); 1771 } 1772 } 1773 1774 trace_vfio_region_mmaps_set_enabled(memory_region_name(region->mem), 1775 enabled); 1776 } 1777 1778 void vfio_reset_handler(void *opaque) 1779 { 1780 VFIOGroup *group; 1781 VFIODevice *vbasedev; 1782 1783 QLIST_FOREACH(group, &vfio_group_list, next) { 1784 QLIST_FOREACH(vbasedev, &group->device_list, next) { 1785 if (vbasedev->dev->realized) { 1786 vbasedev->ops->vfio_compute_needs_reset(vbasedev); 1787 } 1788 } 1789 } 1790 1791 QLIST_FOREACH(group, &vfio_group_list, next) { 1792 QLIST_FOREACH(vbasedev, &group->device_list, next) { 1793 if (vbasedev->dev->realized && vbasedev->needs_reset) { 1794 vbasedev->ops->vfio_hot_reset_multi(vbasedev); 1795 } 1796 } 1797 } 1798 } 1799 1800 static void vfio_kvm_device_add_group(VFIOGroup *group) 1801 { 1802 #ifdef CONFIG_KVM 1803 struct kvm_device_attr attr = { 1804 .group = KVM_DEV_VFIO_GROUP, 1805 .attr = KVM_DEV_VFIO_GROUP_ADD, 1806 .addr = (uint64_t)(unsigned long)&group->fd, 1807 }; 1808 1809 if (!kvm_enabled()) { 1810 return; 1811 } 1812 1813 if (vfio_kvm_device_fd < 0) { 1814 struct kvm_create_device cd = { 1815 .type = KVM_DEV_TYPE_VFIO, 1816 }; 1817 1818 if (kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd)) { 1819 error_report("Failed to create KVM VFIO device: %m"); 1820 return; 1821 } 1822 1823 vfio_kvm_device_fd = cd.fd; 1824 } 1825 1826 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) { 1827 error_report("Failed to add group %d to KVM VFIO device: %m", 1828 group->groupid); 1829 } 1830 #endif 1831 } 1832 1833 static void vfio_kvm_device_del_group(VFIOGroup *group) 1834 { 1835 #ifdef CONFIG_KVM 1836 struct kvm_device_attr attr = { 1837 .group = KVM_DEV_VFIO_GROUP, 1838 .attr = KVM_DEV_VFIO_GROUP_DEL, 1839 .addr = (uint64_t)(unsigned long)&group->fd, 1840 }; 1841 1842 if (vfio_kvm_device_fd < 0) { 1843 return; 1844 } 1845 1846 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) { 1847 error_report("Failed to remove group %d from KVM VFIO device: %m", 1848 group->groupid); 1849 } 1850 #endif 1851 } 1852 1853 static VFIOAddressSpace *vfio_get_address_space(AddressSpace *as) 1854 { 1855 VFIOAddressSpace *space; 1856 1857 QLIST_FOREACH(space, &vfio_address_spaces, list) { 1858 if (space->as == as) { 1859 return space; 1860 } 1861 } 1862 1863 /* No suitable VFIOAddressSpace, create a new one */ 1864 space = g_malloc0(sizeof(*space)); 1865 space->as = as; 1866 QLIST_INIT(&space->containers); 1867 1868 QLIST_INSERT_HEAD(&vfio_address_spaces, space, list); 1869 1870 return space; 1871 } 1872 1873 static void vfio_put_address_space(VFIOAddressSpace *space) 1874 { 1875 if (QLIST_EMPTY(&space->containers)) { 1876 QLIST_REMOVE(space, list); 1877 g_free(space); 1878 } 1879 } 1880 1881 /* 1882 * vfio_get_iommu_type - selects the richest iommu_type (v2 first) 1883 */ 1884 static int vfio_get_iommu_type(VFIOContainer *container, 1885 Error **errp) 1886 { 1887 int iommu_types[] = { VFIO_TYPE1v2_IOMMU, VFIO_TYPE1_IOMMU, 1888 VFIO_SPAPR_TCE_v2_IOMMU, VFIO_SPAPR_TCE_IOMMU }; 1889 int i; 1890 1891 for (i = 0; i < ARRAY_SIZE(iommu_types); i++) { 1892 if (ioctl(container->fd, VFIO_CHECK_EXTENSION, iommu_types[i])) { 1893 return iommu_types[i]; 1894 } 1895 } 1896 error_setg(errp, "No available IOMMU models"); 1897 return -EINVAL; 1898 } 1899 1900 static int vfio_init_container(VFIOContainer *container, int group_fd, 1901 Error **errp) 1902 { 1903 int iommu_type, ret; 1904 1905 iommu_type = vfio_get_iommu_type(container, errp); 1906 if (iommu_type < 0) { 1907 return iommu_type; 1908 } 1909 1910 ret = ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container->fd); 1911 if (ret) { 1912 error_setg_errno(errp, errno, "Failed to set group container"); 1913 return -errno; 1914 } 1915 1916 while (ioctl(container->fd, VFIO_SET_IOMMU, iommu_type)) { 1917 if (iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) { 1918 /* 1919 * On sPAPR, despite the IOMMU subdriver always advertises v1 and 1920 * v2, the running platform may not support v2 and there is no 1921 * way to guess it until an IOMMU group gets added to the container. 1922 * So in case it fails with v2, try v1 as a fallback. 1923 */ 1924 iommu_type = VFIO_SPAPR_TCE_IOMMU; 1925 continue; 1926 } 1927 error_setg_errno(errp, errno, "Failed to set iommu for container"); 1928 return -errno; 1929 } 1930 1931 container->iommu_type = iommu_type; 1932 return 0; 1933 } 1934 1935 static int vfio_get_iommu_info(VFIOContainer *container, 1936 struct vfio_iommu_type1_info **info) 1937 { 1938 1939 size_t argsz = sizeof(struct vfio_iommu_type1_info); 1940 1941 *info = g_new0(struct vfio_iommu_type1_info, 1); 1942 again: 1943 (*info)->argsz = argsz; 1944 1945 if (ioctl(container->fd, VFIO_IOMMU_GET_INFO, *info)) { 1946 g_free(*info); 1947 *info = NULL; 1948 return -errno; 1949 } 1950 1951 if (((*info)->argsz > argsz)) { 1952 argsz = (*info)->argsz; 1953 *info = g_realloc(*info, argsz); 1954 goto again; 1955 } 1956 1957 return 0; 1958 } 1959 1960 static struct vfio_info_cap_header * 1961 vfio_get_iommu_info_cap(struct vfio_iommu_type1_info *info, uint16_t id) 1962 { 1963 struct vfio_info_cap_header *hdr; 1964 void *ptr = info; 1965 1966 if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) { 1967 return NULL; 1968 } 1969 1970 for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) { 1971 if (hdr->id == id) { 1972 return hdr; 1973 } 1974 } 1975 1976 return NULL; 1977 } 1978 1979 static void vfio_get_iommu_info_migration(VFIOContainer *container, 1980 struct vfio_iommu_type1_info *info) 1981 { 1982 struct vfio_info_cap_header *hdr; 1983 struct vfio_iommu_type1_info_cap_migration *cap_mig; 1984 1985 hdr = vfio_get_iommu_info_cap(info, VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION); 1986 if (!hdr) { 1987 return; 1988 } 1989 1990 cap_mig = container_of(hdr, struct vfio_iommu_type1_info_cap_migration, 1991 header); 1992 1993 /* 1994 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of 1995 * qemu_real_host_page_size to mark those dirty. 1996 */ 1997 if (cap_mig->pgsize_bitmap & qemu_real_host_page_size()) { 1998 container->dirty_pages_supported = true; 1999 container->max_dirty_bitmap_size = cap_mig->max_dirty_bitmap_size; 2000 container->dirty_pgsizes = cap_mig->pgsize_bitmap; 2001 } 2002 } 2003 2004 static int vfio_connect_container(VFIOGroup *group, AddressSpace *as, 2005 Error **errp) 2006 { 2007 VFIOContainer *container; 2008 int ret, fd; 2009 VFIOAddressSpace *space; 2010 2011 space = vfio_get_address_space(as); 2012 2013 /* 2014 * VFIO is currently incompatible with discarding of RAM insofar as the 2015 * madvise to purge (zap) the page from QEMU's address space does not 2016 * interact with the memory API and therefore leaves stale virtual to 2017 * physical mappings in the IOMMU if the page was previously pinned. We 2018 * therefore set discarding broken for each group added to a container, 2019 * whether the container is used individually or shared. This provides 2020 * us with options to allow devices within a group to opt-in and allow 2021 * discarding, so long as it is done consistently for a group (for instance 2022 * if the device is an mdev device where it is known that the host vendor 2023 * driver will never pin pages outside of the working set of the guest 2024 * driver, which would thus not be discarding candidates). 2025 * 2026 * The first opportunity to induce pinning occurs here where we attempt to 2027 * attach the group to existing containers within the AddressSpace. If any 2028 * pages are already zapped from the virtual address space, such as from 2029 * previous discards, new pinning will cause valid mappings to be 2030 * re-established. Likewise, when the overall MemoryListener for a new 2031 * container is registered, a replay of mappings within the AddressSpace 2032 * will occur, re-establishing any previously zapped pages as well. 2033 * 2034 * Especially virtio-balloon is currently only prevented from discarding 2035 * new memory, it will not yet set ram_block_discard_set_required() and 2036 * therefore, neither stops us here or deals with the sudden memory 2037 * consumption of inflated memory. 2038 * 2039 * We do support discarding of memory coordinated via the RamDiscardManager 2040 * with some IOMMU types. vfio_ram_block_discard_disable() handles the 2041 * details once we know which type of IOMMU we are using. 2042 */ 2043 2044 QLIST_FOREACH(container, &space->containers, next) { 2045 if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) { 2046 ret = vfio_ram_block_discard_disable(container, true); 2047 if (ret) { 2048 error_setg_errno(errp, -ret, 2049 "Cannot set discarding of RAM broken"); 2050 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, 2051 &container->fd)) { 2052 error_report("vfio: error disconnecting group %d from" 2053 " container", group->groupid); 2054 } 2055 return ret; 2056 } 2057 group->container = container; 2058 QLIST_INSERT_HEAD(&container->group_list, group, container_next); 2059 vfio_kvm_device_add_group(group); 2060 return 0; 2061 } 2062 } 2063 2064 fd = qemu_open_old("/dev/vfio/vfio", O_RDWR); 2065 if (fd < 0) { 2066 error_setg_errno(errp, errno, "failed to open /dev/vfio/vfio"); 2067 ret = -errno; 2068 goto put_space_exit; 2069 } 2070 2071 ret = ioctl(fd, VFIO_GET_API_VERSION); 2072 if (ret != VFIO_API_VERSION) { 2073 error_setg(errp, "supported vfio version: %d, " 2074 "reported version: %d", VFIO_API_VERSION, ret); 2075 ret = -EINVAL; 2076 goto close_fd_exit; 2077 } 2078 2079 container = g_malloc0(sizeof(*container)); 2080 container->space = space; 2081 container->fd = fd; 2082 container->error = NULL; 2083 container->dirty_pages_supported = false; 2084 container->dma_max_mappings = 0; 2085 QLIST_INIT(&container->giommu_list); 2086 QLIST_INIT(&container->hostwin_list); 2087 QLIST_INIT(&container->vrdl_list); 2088 2089 ret = vfio_init_container(container, group->fd, errp); 2090 if (ret) { 2091 goto free_container_exit; 2092 } 2093 2094 ret = vfio_ram_block_discard_disable(container, true); 2095 if (ret) { 2096 error_setg_errno(errp, -ret, "Cannot set discarding of RAM broken"); 2097 goto free_container_exit; 2098 } 2099 2100 switch (container->iommu_type) { 2101 case VFIO_TYPE1v2_IOMMU: 2102 case VFIO_TYPE1_IOMMU: 2103 { 2104 struct vfio_iommu_type1_info *info; 2105 2106 /* 2107 * FIXME: This assumes that a Type1 IOMMU can map any 64-bit 2108 * IOVA whatsoever. That's not actually true, but the current 2109 * kernel interface doesn't tell us what it can map, and the 2110 * existing Type1 IOMMUs generally support any IOVA we're 2111 * going to actually try in practice. 2112 */ 2113 ret = vfio_get_iommu_info(container, &info); 2114 2115 if (ret || !(info->flags & VFIO_IOMMU_INFO_PGSIZES)) { 2116 /* Assume 4k IOVA page size */ 2117 info->iova_pgsizes = 4096; 2118 } 2119 vfio_host_win_add(container, 0, (hwaddr)-1, info->iova_pgsizes); 2120 container->pgsizes = info->iova_pgsizes; 2121 2122 /* The default in the kernel ("dma_entry_limit") is 65535. */ 2123 container->dma_max_mappings = 65535; 2124 if (!ret) { 2125 vfio_get_info_dma_avail(info, &container->dma_max_mappings); 2126 vfio_get_iommu_info_migration(container, info); 2127 } 2128 g_free(info); 2129 break; 2130 } 2131 case VFIO_SPAPR_TCE_v2_IOMMU: 2132 case VFIO_SPAPR_TCE_IOMMU: 2133 { 2134 struct vfio_iommu_spapr_tce_info info; 2135 bool v2 = container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU; 2136 2137 /* 2138 * The host kernel code implementing VFIO_IOMMU_DISABLE is called 2139 * when container fd is closed so we do not call it explicitly 2140 * in this file. 2141 */ 2142 if (!v2) { 2143 ret = ioctl(fd, VFIO_IOMMU_ENABLE); 2144 if (ret) { 2145 error_setg_errno(errp, errno, "failed to enable container"); 2146 ret = -errno; 2147 goto enable_discards_exit; 2148 } 2149 } else { 2150 container->prereg_listener = vfio_prereg_listener; 2151 2152 memory_listener_register(&container->prereg_listener, 2153 &address_space_memory); 2154 if (container->error) { 2155 memory_listener_unregister(&container->prereg_listener); 2156 ret = -1; 2157 error_propagate_prepend(errp, container->error, 2158 "RAM memory listener initialization failed: "); 2159 goto enable_discards_exit; 2160 } 2161 } 2162 2163 info.argsz = sizeof(info); 2164 ret = ioctl(fd, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info); 2165 if (ret) { 2166 error_setg_errno(errp, errno, 2167 "VFIO_IOMMU_SPAPR_TCE_GET_INFO failed"); 2168 ret = -errno; 2169 if (v2) { 2170 memory_listener_unregister(&container->prereg_listener); 2171 } 2172 goto enable_discards_exit; 2173 } 2174 2175 if (v2) { 2176 container->pgsizes = info.ddw.pgsizes; 2177 /* 2178 * There is a default window in just created container. 2179 * To make region_add/del simpler, we better remove this 2180 * window now and let those iommu_listener callbacks 2181 * create/remove them when needed. 2182 */ 2183 ret = vfio_spapr_remove_window(container, info.dma32_window_start); 2184 if (ret) { 2185 error_setg_errno(errp, -ret, 2186 "failed to remove existing window"); 2187 goto enable_discards_exit; 2188 } 2189 } else { 2190 /* The default table uses 4K pages */ 2191 container->pgsizes = 0x1000; 2192 vfio_host_win_add(container, info.dma32_window_start, 2193 info.dma32_window_start + 2194 info.dma32_window_size - 1, 2195 0x1000); 2196 } 2197 } 2198 } 2199 2200 vfio_kvm_device_add_group(group); 2201 2202 QLIST_INIT(&container->group_list); 2203 QLIST_INSERT_HEAD(&space->containers, container, next); 2204 2205 group->container = container; 2206 QLIST_INSERT_HEAD(&container->group_list, group, container_next); 2207 2208 container->listener = vfio_memory_listener; 2209 2210 memory_listener_register(&container->listener, container->space->as); 2211 2212 if (container->error) { 2213 ret = -1; 2214 error_propagate_prepend(errp, container->error, 2215 "memory listener initialization failed: "); 2216 goto listener_release_exit; 2217 } 2218 2219 container->initialized = true; 2220 2221 return 0; 2222 listener_release_exit: 2223 QLIST_REMOVE(group, container_next); 2224 QLIST_REMOVE(container, next); 2225 vfio_kvm_device_del_group(group); 2226 vfio_listener_release(container); 2227 2228 enable_discards_exit: 2229 vfio_ram_block_discard_disable(container, false); 2230 2231 free_container_exit: 2232 g_free(container); 2233 2234 close_fd_exit: 2235 close(fd); 2236 2237 put_space_exit: 2238 vfio_put_address_space(space); 2239 2240 return ret; 2241 } 2242 2243 static void vfio_disconnect_container(VFIOGroup *group) 2244 { 2245 VFIOContainer *container = group->container; 2246 2247 QLIST_REMOVE(group, container_next); 2248 group->container = NULL; 2249 2250 /* 2251 * Explicitly release the listener first before unset container, 2252 * since unset may destroy the backend container if it's the last 2253 * group. 2254 */ 2255 if (QLIST_EMPTY(&container->group_list)) { 2256 vfio_listener_release(container); 2257 } 2258 2259 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) { 2260 error_report("vfio: error disconnecting group %d from container", 2261 group->groupid); 2262 } 2263 2264 if (QLIST_EMPTY(&container->group_list)) { 2265 VFIOAddressSpace *space = container->space; 2266 VFIOGuestIOMMU *giommu, *tmp; 2267 VFIOHostDMAWindow *hostwin, *next; 2268 2269 QLIST_REMOVE(container, next); 2270 2271 QLIST_FOREACH_SAFE(giommu, &container->giommu_list, giommu_next, tmp) { 2272 memory_region_unregister_iommu_notifier( 2273 MEMORY_REGION(giommu->iommu_mr), &giommu->n); 2274 QLIST_REMOVE(giommu, giommu_next); 2275 g_free(giommu); 2276 } 2277 2278 QLIST_FOREACH_SAFE(hostwin, &container->hostwin_list, hostwin_next, 2279 next) { 2280 QLIST_REMOVE(hostwin, hostwin_next); 2281 g_free(hostwin); 2282 } 2283 2284 trace_vfio_disconnect_container(container->fd); 2285 close(container->fd); 2286 g_free(container); 2287 2288 vfio_put_address_space(space); 2289 } 2290 } 2291 2292 VFIOGroup *vfio_get_group(int groupid, AddressSpace *as, Error **errp) 2293 { 2294 VFIOGroup *group; 2295 char path[32]; 2296 struct vfio_group_status status = { .argsz = sizeof(status) }; 2297 2298 QLIST_FOREACH(group, &vfio_group_list, next) { 2299 if (group->groupid == groupid) { 2300 /* Found it. Now is it already in the right context? */ 2301 if (group->container->space->as == as) { 2302 return group; 2303 } else { 2304 error_setg(errp, "group %d used in multiple address spaces", 2305 group->groupid); 2306 return NULL; 2307 } 2308 } 2309 } 2310 2311 group = g_malloc0(sizeof(*group)); 2312 2313 snprintf(path, sizeof(path), "/dev/vfio/%d", groupid); 2314 group->fd = qemu_open_old(path, O_RDWR); 2315 if (group->fd < 0) { 2316 error_setg_errno(errp, errno, "failed to open %s", path); 2317 goto free_group_exit; 2318 } 2319 2320 if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) { 2321 error_setg_errno(errp, errno, "failed to get group %d status", groupid); 2322 goto close_fd_exit; 2323 } 2324 2325 if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) { 2326 error_setg(errp, "group %d is not viable", groupid); 2327 error_append_hint(errp, 2328 "Please ensure all devices within the iommu_group " 2329 "are bound to their vfio bus driver.\n"); 2330 goto close_fd_exit; 2331 } 2332 2333 group->groupid = groupid; 2334 QLIST_INIT(&group->device_list); 2335 2336 if (vfio_connect_container(group, as, errp)) { 2337 error_prepend(errp, "failed to setup container for group %d: ", 2338 groupid); 2339 goto close_fd_exit; 2340 } 2341 2342 if (QLIST_EMPTY(&vfio_group_list)) { 2343 qemu_register_reset(vfio_reset_handler, NULL); 2344 } 2345 2346 QLIST_INSERT_HEAD(&vfio_group_list, group, next); 2347 2348 return group; 2349 2350 close_fd_exit: 2351 close(group->fd); 2352 2353 free_group_exit: 2354 g_free(group); 2355 2356 return NULL; 2357 } 2358 2359 void vfio_put_group(VFIOGroup *group) 2360 { 2361 if (!group || !QLIST_EMPTY(&group->device_list)) { 2362 return; 2363 } 2364 2365 if (!group->ram_block_discard_allowed) { 2366 vfio_ram_block_discard_disable(group->container, false); 2367 } 2368 vfio_kvm_device_del_group(group); 2369 vfio_disconnect_container(group); 2370 QLIST_REMOVE(group, next); 2371 trace_vfio_put_group(group->fd); 2372 close(group->fd); 2373 g_free(group); 2374 2375 if (QLIST_EMPTY(&vfio_group_list)) { 2376 qemu_unregister_reset(vfio_reset_handler, NULL); 2377 } 2378 } 2379 2380 int vfio_get_device(VFIOGroup *group, const char *name, 2381 VFIODevice *vbasedev, Error **errp) 2382 { 2383 struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) }; 2384 int ret, fd; 2385 2386 fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name); 2387 if (fd < 0) { 2388 error_setg_errno(errp, errno, "error getting device from group %d", 2389 group->groupid); 2390 error_append_hint(errp, 2391 "Verify all devices in group %d are bound to vfio-<bus> " 2392 "or pci-stub and not already in use\n", group->groupid); 2393 return fd; 2394 } 2395 2396 ret = ioctl(fd, VFIO_DEVICE_GET_INFO, &dev_info); 2397 if (ret) { 2398 error_setg_errno(errp, errno, "error getting device info"); 2399 close(fd); 2400 return ret; 2401 } 2402 2403 /* 2404 * Set discarding of RAM as not broken for this group if the driver knows 2405 * the device operates compatibly with discarding. Setting must be 2406 * consistent per group, but since compatibility is really only possible 2407 * with mdev currently, we expect singleton groups. 2408 */ 2409 if (vbasedev->ram_block_discard_allowed != 2410 group->ram_block_discard_allowed) { 2411 if (!QLIST_EMPTY(&group->device_list)) { 2412 error_setg(errp, "Inconsistent setting of support for discarding " 2413 "RAM (e.g., balloon) within group"); 2414 close(fd); 2415 return -1; 2416 } 2417 2418 if (!group->ram_block_discard_allowed) { 2419 group->ram_block_discard_allowed = true; 2420 vfio_ram_block_discard_disable(group->container, false); 2421 } 2422 } 2423 2424 vbasedev->fd = fd; 2425 vbasedev->group = group; 2426 QLIST_INSERT_HEAD(&group->device_list, vbasedev, next); 2427 2428 vbasedev->num_irqs = dev_info.num_irqs; 2429 vbasedev->num_regions = dev_info.num_regions; 2430 vbasedev->flags = dev_info.flags; 2431 2432 trace_vfio_get_device(name, dev_info.flags, dev_info.num_regions, 2433 dev_info.num_irqs); 2434 2435 vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET); 2436 return 0; 2437 } 2438 2439 void vfio_put_base_device(VFIODevice *vbasedev) 2440 { 2441 if (!vbasedev->group) { 2442 return; 2443 } 2444 QLIST_REMOVE(vbasedev, next); 2445 vbasedev->group = NULL; 2446 trace_vfio_put_base_device(vbasedev->fd); 2447 close(vbasedev->fd); 2448 } 2449 2450 int vfio_get_region_info(VFIODevice *vbasedev, int index, 2451 struct vfio_region_info **info) 2452 { 2453 size_t argsz = sizeof(struct vfio_region_info); 2454 2455 *info = g_malloc0(argsz); 2456 2457 (*info)->index = index; 2458 retry: 2459 (*info)->argsz = argsz; 2460 2461 if (ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, *info)) { 2462 g_free(*info); 2463 *info = NULL; 2464 return -errno; 2465 } 2466 2467 if ((*info)->argsz > argsz) { 2468 argsz = (*info)->argsz; 2469 *info = g_realloc(*info, argsz); 2470 2471 goto retry; 2472 } 2473 2474 return 0; 2475 } 2476 2477 int vfio_get_dev_region_info(VFIODevice *vbasedev, uint32_t type, 2478 uint32_t subtype, struct vfio_region_info **info) 2479 { 2480 int i; 2481 2482 for (i = 0; i < vbasedev->num_regions; i++) { 2483 struct vfio_info_cap_header *hdr; 2484 struct vfio_region_info_cap_type *cap_type; 2485 2486 if (vfio_get_region_info(vbasedev, i, info)) { 2487 continue; 2488 } 2489 2490 hdr = vfio_get_region_info_cap(*info, VFIO_REGION_INFO_CAP_TYPE); 2491 if (!hdr) { 2492 g_free(*info); 2493 continue; 2494 } 2495 2496 cap_type = container_of(hdr, struct vfio_region_info_cap_type, header); 2497 2498 trace_vfio_get_dev_region(vbasedev->name, i, 2499 cap_type->type, cap_type->subtype); 2500 2501 if (cap_type->type == type && cap_type->subtype == subtype) { 2502 return 0; 2503 } 2504 2505 g_free(*info); 2506 } 2507 2508 *info = NULL; 2509 return -ENODEV; 2510 } 2511 2512 bool vfio_has_region_cap(VFIODevice *vbasedev, int region, uint16_t cap_type) 2513 { 2514 struct vfio_region_info *info = NULL; 2515 bool ret = false; 2516 2517 if (!vfio_get_region_info(vbasedev, region, &info)) { 2518 if (vfio_get_region_info_cap(info, cap_type)) { 2519 ret = true; 2520 } 2521 g_free(info); 2522 } 2523 2524 return ret; 2525 } 2526 2527 /* 2528 * Interfaces for IBM EEH (Enhanced Error Handling) 2529 */ 2530 static bool vfio_eeh_container_ok(VFIOContainer *container) 2531 { 2532 /* 2533 * As of 2016-03-04 (linux-4.5) the host kernel EEH/VFIO 2534 * implementation is broken if there are multiple groups in a 2535 * container. The hardware works in units of Partitionable 2536 * Endpoints (== IOMMU groups) and the EEH operations naively 2537 * iterate across all groups in the container, without any logic 2538 * to make sure the groups have their state synchronized. For 2539 * certain operations (ENABLE) that might be ok, until an error 2540 * occurs, but for others (GET_STATE) it's clearly broken. 2541 */ 2542 2543 /* 2544 * XXX Once fixed kernels exist, test for them here 2545 */ 2546 2547 if (QLIST_EMPTY(&container->group_list)) { 2548 return false; 2549 } 2550 2551 if (QLIST_NEXT(QLIST_FIRST(&container->group_list), container_next)) { 2552 return false; 2553 } 2554 2555 return true; 2556 } 2557 2558 static int vfio_eeh_container_op(VFIOContainer *container, uint32_t op) 2559 { 2560 struct vfio_eeh_pe_op pe_op = { 2561 .argsz = sizeof(pe_op), 2562 .op = op, 2563 }; 2564 int ret; 2565 2566 if (!vfio_eeh_container_ok(container)) { 2567 error_report("vfio/eeh: EEH_PE_OP 0x%x: " 2568 "kernel requires a container with exactly one group", op); 2569 return -EPERM; 2570 } 2571 2572 ret = ioctl(container->fd, VFIO_EEH_PE_OP, &pe_op); 2573 if (ret < 0) { 2574 error_report("vfio/eeh: EEH_PE_OP 0x%x failed: %m", op); 2575 return -errno; 2576 } 2577 2578 return ret; 2579 } 2580 2581 static VFIOContainer *vfio_eeh_as_container(AddressSpace *as) 2582 { 2583 VFIOAddressSpace *space = vfio_get_address_space(as); 2584 VFIOContainer *container = NULL; 2585 2586 if (QLIST_EMPTY(&space->containers)) { 2587 /* No containers to act on */ 2588 goto out; 2589 } 2590 2591 container = QLIST_FIRST(&space->containers); 2592 2593 if (QLIST_NEXT(container, next)) { 2594 /* We don't yet have logic to synchronize EEH state across 2595 * multiple containers */ 2596 container = NULL; 2597 goto out; 2598 } 2599 2600 out: 2601 vfio_put_address_space(space); 2602 return container; 2603 } 2604 2605 bool vfio_eeh_as_ok(AddressSpace *as) 2606 { 2607 VFIOContainer *container = vfio_eeh_as_container(as); 2608 2609 return (container != NULL) && vfio_eeh_container_ok(container); 2610 } 2611 2612 int vfio_eeh_as_op(AddressSpace *as, uint32_t op) 2613 { 2614 VFIOContainer *container = vfio_eeh_as_container(as); 2615 2616 if (!container) { 2617 return -ENODEV; 2618 } 2619 return vfio_eeh_container_op(container, op); 2620 } 2621