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-device.h" 29 #include "hw/vfio/pci.h" 30 #include "system/address-spaces.h" 31 #include "system/memory.h" 32 #include "system/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 "system/kvm.h" 38 #include "system/reset.h" 39 #include "system/runstate.h" 40 #include "trace.h" 41 #include "qapi/error.h" 42 #include "migration/misc.h" 43 #include "migration/qemu-file.h" 44 #include "system/tcg.h" 45 #include "system/tpm.h" 46 #include "vfio-migration-internal.h" 47 #include "vfio-helpers.h" 48 #include "vfio-listener.h" 49 50 /* 51 * Device state interfaces 52 */ 53 54 55 static bool vfio_log_sync_needed(const VFIOContainerBase *bcontainer) 56 { 57 VFIODevice *vbasedev; 58 59 if (!vfio_container_dirty_tracking_is_started(bcontainer)) { 60 return false; 61 } 62 63 QLIST_FOREACH(vbasedev, &bcontainer->device_list, container_next) { 64 VFIOMigration *migration = vbasedev->migration; 65 66 if (!migration) { 67 return false; 68 } 69 70 if (vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF && 71 (vfio_device_state_is_running(vbasedev) || 72 vfio_device_state_is_precopy(vbasedev))) { 73 return false; 74 } 75 } 76 return true; 77 } 78 79 static bool vfio_listener_skipped_section(MemoryRegionSection *section) 80 { 81 return (!memory_region_is_ram(section->mr) && 82 !memory_region_is_iommu(section->mr)) || 83 memory_region_is_protected(section->mr) || 84 /* 85 * Sizing an enabled 64-bit BAR can cause spurious mappings to 86 * addresses in the upper part of the 64-bit address space. These 87 * are never accessed by the CPU and beyond the address width of 88 * some IOMMU hardware. TODO: VFIO should tell us the IOMMU width. 89 */ 90 section->offset_within_address_space & (1ULL << 63); 91 } 92 93 /* Called with rcu_read_lock held. */ 94 static bool vfio_get_xlat_addr(IOMMUTLBEntry *iotlb, void **vaddr, 95 ram_addr_t *ram_addr, bool *read_only, 96 Error **errp) 97 { 98 bool ret, mr_has_discard_manager; 99 100 ret = memory_get_xlat_addr(iotlb, vaddr, ram_addr, read_only, 101 &mr_has_discard_manager, errp); 102 if (ret && mr_has_discard_manager) { 103 /* 104 * Malicious VMs might trigger discarding of IOMMU-mapped memory. The 105 * pages will remain pinned inside vfio until unmapped, resulting in a 106 * higher memory consumption than expected. If memory would get 107 * populated again later, there would be an inconsistency between pages 108 * pinned by vfio and pages seen by QEMU. This is the case until 109 * unmapped from the IOMMU (e.g., during device reset). 110 * 111 * With malicious guests, we really only care about pinning more memory 112 * than expected. RLIMIT_MEMLOCK set for the user/process can never be 113 * exceeded and can be used to mitigate this problem. 114 */ 115 warn_report_once("Using vfio with vIOMMUs and coordinated discarding of" 116 " RAM (e.g., virtio-mem) works, however, malicious" 117 " guests can trigger pinning of more memory than" 118 " intended via an IOMMU. It's possible to mitigate " 119 " by setting/adjusting RLIMIT_MEMLOCK."); 120 } 121 return ret; 122 } 123 124 static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb) 125 { 126 VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n); 127 VFIOContainerBase *bcontainer = giommu->bcontainer; 128 hwaddr iova = iotlb->iova + giommu->iommu_offset; 129 void *vaddr; 130 int ret; 131 Error *local_err = NULL; 132 133 trace_vfio_iommu_map_notify(iotlb->perm == IOMMU_NONE ? "UNMAP" : "MAP", 134 iova, iova + iotlb->addr_mask); 135 136 if (iotlb->target_as != &address_space_memory) { 137 error_setg(&local_err, 138 "Wrong target AS \"%s\", only system memory is allowed", 139 iotlb->target_as->name ? iotlb->target_as->name : "none"); 140 if (migration_is_running()) { 141 migration_file_set_error(-EINVAL, local_err); 142 } else { 143 error_report_err(local_err); 144 } 145 return; 146 } 147 148 rcu_read_lock(); 149 150 if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) { 151 bool read_only; 152 153 if (!vfio_get_xlat_addr(iotlb, &vaddr, NULL, &read_only, &local_err)) { 154 error_report_err(local_err); 155 goto out; 156 } 157 /* 158 * vaddr is only valid until rcu_read_unlock(). But after 159 * vfio_dma_map has set up the mapping the pages will be 160 * pinned by the kernel. This makes sure that the RAM backend 161 * of vaddr will always be there, even if the memory object is 162 * destroyed and its backing memory munmap-ed. 163 */ 164 ret = vfio_container_dma_map(bcontainer, iova, 165 iotlb->addr_mask + 1, vaddr, 166 read_only); 167 if (ret) { 168 error_report("vfio_container_dma_map(%p, 0x%"HWADDR_PRIx", " 169 "0x%"HWADDR_PRIx", %p) = %d (%s)", 170 bcontainer, iova, 171 iotlb->addr_mask + 1, vaddr, ret, strerror(-ret)); 172 } 173 } else { 174 ret = vfio_container_dma_unmap(bcontainer, iova, 175 iotlb->addr_mask + 1, iotlb); 176 if (ret) { 177 error_setg(&local_err, 178 "vfio_container_dma_unmap(%p, 0x%"HWADDR_PRIx", " 179 "0x%"HWADDR_PRIx") = %d (%s)", 180 bcontainer, iova, 181 iotlb->addr_mask + 1, ret, strerror(-ret)); 182 if (migration_is_running()) { 183 migration_file_set_error(ret, local_err); 184 } else { 185 error_report_err(local_err); 186 } 187 } 188 } 189 out: 190 rcu_read_unlock(); 191 } 192 193 static void vfio_ram_discard_notify_discard(RamDiscardListener *rdl, 194 MemoryRegionSection *section) 195 { 196 VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener, 197 listener); 198 VFIOContainerBase *bcontainer = vrdl->bcontainer; 199 const hwaddr size = int128_get64(section->size); 200 const hwaddr iova = section->offset_within_address_space; 201 int ret; 202 203 /* Unmap with a single call. */ 204 ret = vfio_container_dma_unmap(bcontainer, iova, size , NULL); 205 if (ret) { 206 error_report("%s: vfio_container_dma_unmap() failed: %s", __func__, 207 strerror(-ret)); 208 } 209 } 210 211 static int vfio_ram_discard_notify_populate(RamDiscardListener *rdl, 212 MemoryRegionSection *section) 213 { 214 VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener, 215 listener); 216 VFIOContainerBase *bcontainer = vrdl->bcontainer; 217 const hwaddr end = section->offset_within_region + 218 int128_get64(section->size); 219 hwaddr start, next, iova; 220 void *vaddr; 221 int ret; 222 223 /* 224 * Map in (aligned within memory region) minimum granularity, so we can 225 * unmap in minimum granularity later. 226 */ 227 for (start = section->offset_within_region; start < end; start = next) { 228 next = ROUND_UP(start + 1, vrdl->granularity); 229 next = MIN(next, end); 230 231 iova = start - section->offset_within_region + 232 section->offset_within_address_space; 233 vaddr = memory_region_get_ram_ptr(section->mr) + start; 234 235 ret = vfio_container_dma_map(bcontainer, iova, next - start, 236 vaddr, section->readonly); 237 if (ret) { 238 /* Rollback */ 239 vfio_ram_discard_notify_discard(rdl, section); 240 return ret; 241 } 242 } 243 return 0; 244 } 245 246 static void vfio_ram_discard_register_listener(VFIOContainerBase *bcontainer, 247 MemoryRegionSection *section) 248 { 249 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr); 250 int target_page_size = qemu_target_page_size(); 251 VFIORamDiscardListener *vrdl; 252 253 /* Ignore some corner cases not relevant in practice. */ 254 g_assert(QEMU_IS_ALIGNED(section->offset_within_region, target_page_size)); 255 g_assert(QEMU_IS_ALIGNED(section->offset_within_address_space, 256 target_page_size)); 257 g_assert(QEMU_IS_ALIGNED(int128_get64(section->size), target_page_size)); 258 259 vrdl = g_new0(VFIORamDiscardListener, 1); 260 vrdl->bcontainer = bcontainer; 261 vrdl->mr = section->mr; 262 vrdl->offset_within_address_space = section->offset_within_address_space; 263 vrdl->size = int128_get64(section->size); 264 vrdl->granularity = ram_discard_manager_get_min_granularity(rdm, 265 section->mr); 266 267 g_assert(vrdl->granularity && is_power_of_2(vrdl->granularity)); 268 g_assert(bcontainer->pgsizes && 269 vrdl->granularity >= 1ULL << ctz64(bcontainer->pgsizes)); 270 271 ram_discard_listener_init(&vrdl->listener, 272 vfio_ram_discard_notify_populate, 273 vfio_ram_discard_notify_discard, true); 274 ram_discard_manager_register_listener(rdm, &vrdl->listener, section); 275 QLIST_INSERT_HEAD(&bcontainer->vrdl_list, vrdl, next); 276 277 /* 278 * Sanity-check if we have a theoretically problematic setup where we could 279 * exceed the maximum number of possible DMA mappings over time. We assume 280 * that each mapped section in the same address space as a RamDiscardManager 281 * section consumes exactly one DMA mapping, with the exception of 282 * RamDiscardManager sections; i.e., we don't expect to have gIOMMU sections 283 * in the same address space as RamDiscardManager sections. 284 * 285 * We assume that each section in the address space consumes one memslot. 286 * We take the number of KVM memory slots as a best guess for the maximum 287 * number of sections in the address space we could have over time, 288 * also consuming DMA mappings. 289 */ 290 if (bcontainer->dma_max_mappings) { 291 unsigned int vrdl_count = 0, vrdl_mappings = 0, max_memslots = 512; 292 293 #ifdef CONFIG_KVM 294 if (kvm_enabled()) { 295 max_memslots = kvm_get_max_memslots(); 296 } 297 #endif 298 299 QLIST_FOREACH(vrdl, &bcontainer->vrdl_list, next) { 300 hwaddr start, end; 301 302 start = QEMU_ALIGN_DOWN(vrdl->offset_within_address_space, 303 vrdl->granularity); 304 end = ROUND_UP(vrdl->offset_within_address_space + vrdl->size, 305 vrdl->granularity); 306 vrdl_mappings += (end - start) / vrdl->granularity; 307 vrdl_count++; 308 } 309 310 if (vrdl_mappings + max_memslots - vrdl_count > 311 bcontainer->dma_max_mappings) { 312 warn_report("%s: possibly running out of DMA mappings. E.g., try" 313 " increasing the 'block-size' of virtio-mem devies." 314 " Maximum possible DMA mappings: %d, Maximum possible" 315 " memslots: %d", __func__, bcontainer->dma_max_mappings, 316 max_memslots); 317 } 318 } 319 } 320 321 static void vfio_ram_discard_unregister_listener(VFIOContainerBase *bcontainer, 322 MemoryRegionSection *section) 323 { 324 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr); 325 VFIORamDiscardListener *vrdl = NULL; 326 327 QLIST_FOREACH(vrdl, &bcontainer->vrdl_list, next) { 328 if (vrdl->mr == section->mr && 329 vrdl->offset_within_address_space == 330 section->offset_within_address_space) { 331 break; 332 } 333 } 334 335 if (!vrdl) { 336 hw_error("vfio: Trying to unregister missing RAM discard listener"); 337 } 338 339 ram_discard_manager_unregister_listener(rdm, &vrdl->listener); 340 QLIST_REMOVE(vrdl, next); 341 g_free(vrdl); 342 } 343 344 static bool vfio_known_safe_misalignment(MemoryRegionSection *section) 345 { 346 MemoryRegion *mr = section->mr; 347 348 if (!TPM_IS_CRB(mr->owner)) { 349 return false; 350 } 351 352 /* this is a known safe misaligned region, just trace for debug purpose */ 353 trace_vfio_known_safe_misalignment(memory_region_name(mr), 354 section->offset_within_address_space, 355 section->offset_within_region, 356 qemu_real_host_page_size()); 357 return true; 358 } 359 360 static bool vfio_listener_valid_section(MemoryRegionSection *section, 361 const char *name) 362 { 363 if (vfio_listener_skipped_section(section)) { 364 trace_vfio_listener_region_skip(name, 365 section->offset_within_address_space, 366 section->offset_within_address_space + 367 int128_get64(int128_sub(section->size, int128_one()))); 368 return false; 369 } 370 371 if (unlikely((section->offset_within_address_space & 372 ~qemu_real_host_page_mask()) != 373 (section->offset_within_region & ~qemu_real_host_page_mask()))) { 374 if (!vfio_known_safe_misalignment(section)) { 375 error_report("%s received unaligned region %s iova=0x%"PRIx64 376 " offset_within_region=0x%"PRIx64 377 " qemu_real_host_page_size=0x%"PRIxPTR, 378 __func__, memory_region_name(section->mr), 379 section->offset_within_address_space, 380 section->offset_within_region, 381 qemu_real_host_page_size()); 382 } 383 return false; 384 } 385 386 return true; 387 } 388 389 static bool vfio_get_section_iova_range(VFIOContainerBase *bcontainer, 390 MemoryRegionSection *section, 391 hwaddr *out_iova, hwaddr *out_end, 392 Int128 *out_llend) 393 { 394 Int128 llend; 395 hwaddr iova; 396 397 iova = REAL_HOST_PAGE_ALIGN(section->offset_within_address_space); 398 llend = int128_make64(section->offset_within_address_space); 399 llend = int128_add(llend, section->size); 400 llend = int128_and(llend, int128_exts64(qemu_real_host_page_mask())); 401 402 if (int128_ge(int128_make64(iova), llend)) { 403 return false; 404 } 405 406 *out_iova = iova; 407 *out_end = int128_get64(int128_sub(llend, int128_one())); 408 if (out_llend) { 409 *out_llend = llend; 410 } 411 return true; 412 } 413 414 static void vfio_device_error_append(VFIODevice *vbasedev, Error **errp) 415 { 416 /* 417 * MMIO region mapping failures are not fatal but in this case PCI 418 * peer-to-peer transactions are broken. 419 */ 420 if (vbasedev && vbasedev->type == VFIO_DEVICE_TYPE_PCI) { 421 error_append_hint(errp, "%s: PCI peer-to-peer transactions " 422 "on BARs are not supported.\n", vbasedev->name); 423 } 424 } 425 426 static void vfio_listener_region_add(MemoryListener *listener, 427 MemoryRegionSection *section) 428 { 429 VFIOContainerBase *bcontainer = container_of(listener, VFIOContainerBase, 430 listener); 431 hwaddr iova, end; 432 Int128 llend, llsize; 433 void *vaddr; 434 int ret; 435 Error *err = NULL; 436 437 if (!vfio_listener_valid_section(section, "region_add")) { 438 return; 439 } 440 441 if (!vfio_get_section_iova_range(bcontainer, section, &iova, &end, 442 &llend)) { 443 if (memory_region_is_ram_device(section->mr)) { 444 trace_vfio_listener_region_add_no_dma_map( 445 memory_region_name(section->mr), 446 section->offset_within_address_space, 447 int128_getlo(section->size), 448 qemu_real_host_page_size()); 449 } 450 return; 451 } 452 453 /* PPC64/pseries machine only */ 454 if (!vfio_container_add_section_window(bcontainer, section, &err)) { 455 goto mmio_dma_error; 456 } 457 458 memory_region_ref(section->mr); 459 460 if (memory_region_is_iommu(section->mr)) { 461 VFIOGuestIOMMU *giommu; 462 IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr); 463 int iommu_idx; 464 465 trace_vfio_listener_region_add_iommu(section->mr->name, iova, end); 466 /* 467 * FIXME: For VFIO iommu types which have KVM acceleration to 468 * avoid bouncing all map/unmaps through qemu this way, this 469 * would be the right place to wire that up (tell the KVM 470 * device emulation the VFIO iommu handles to use). 471 */ 472 giommu = g_malloc0(sizeof(*giommu)); 473 giommu->iommu_mr = iommu_mr; 474 giommu->iommu_offset = section->offset_within_address_space - 475 section->offset_within_region; 476 giommu->bcontainer = bcontainer; 477 llend = int128_add(int128_make64(section->offset_within_region), 478 section->size); 479 llend = int128_sub(llend, int128_one()); 480 iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr, 481 MEMTXATTRS_UNSPECIFIED); 482 iommu_notifier_init(&giommu->n, vfio_iommu_map_notify, 483 IOMMU_NOTIFIER_IOTLB_EVENTS, 484 section->offset_within_region, 485 int128_get64(llend), 486 iommu_idx); 487 488 ret = memory_region_register_iommu_notifier(section->mr, &giommu->n, 489 &err); 490 if (ret) { 491 g_free(giommu); 492 goto fail; 493 } 494 QLIST_INSERT_HEAD(&bcontainer->giommu_list, giommu, giommu_next); 495 memory_region_iommu_replay(giommu->iommu_mr, &giommu->n); 496 497 return; 498 } 499 500 /* Here we assume that memory_region_is_ram(section->mr)==true */ 501 502 /* 503 * For RAM memory regions with a RamDiscardManager, we only want to map the 504 * actually populated parts - and update the mapping whenever we're notified 505 * about changes. 506 */ 507 if (memory_region_has_ram_discard_manager(section->mr)) { 508 vfio_ram_discard_register_listener(bcontainer, section); 509 return; 510 } 511 512 vaddr = memory_region_get_ram_ptr(section->mr) + 513 section->offset_within_region + 514 (iova - section->offset_within_address_space); 515 516 trace_vfio_listener_region_add_ram(iova, end, vaddr); 517 518 llsize = int128_sub(llend, int128_make64(iova)); 519 520 if (memory_region_is_ram_device(section->mr)) { 521 hwaddr pgmask = (1ULL << ctz64(bcontainer->pgsizes)) - 1; 522 523 if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) { 524 trace_vfio_listener_region_add_no_dma_map( 525 memory_region_name(section->mr), 526 section->offset_within_address_space, 527 int128_getlo(section->size), 528 pgmask + 1); 529 return; 530 } 531 } 532 533 ret = vfio_container_dma_map(bcontainer, iova, int128_get64(llsize), 534 vaddr, section->readonly); 535 if (ret) { 536 error_setg(&err, "vfio_container_dma_map(%p, 0x%"HWADDR_PRIx", " 537 "0x%"HWADDR_PRIx", %p) = %d (%s)", 538 bcontainer, iova, int128_get64(llsize), vaddr, ret, 539 strerror(-ret)); 540 mmio_dma_error: 541 if (memory_region_is_ram_device(section->mr)) { 542 /* Allow unexpected mappings not to be fatal for RAM devices */ 543 VFIODevice *vbasedev = 544 vfio_get_vfio_device(memory_region_owner(section->mr)); 545 vfio_device_error_append(vbasedev, &err); 546 warn_report_err_once(err); 547 return; 548 } 549 goto fail; 550 } 551 552 return; 553 554 fail: 555 if (!bcontainer->initialized) { 556 /* 557 * At machine init time or when the device is attached to the 558 * VM, store the first error in the container so we can 559 * gracefully fail the device realize routine. 560 */ 561 if (!bcontainer->error) { 562 error_propagate_prepend(&bcontainer->error, err, 563 "Region %s: ", 564 memory_region_name(section->mr)); 565 } else { 566 error_free(err); 567 } 568 } else { 569 /* 570 * At runtime, there's not much we can do other than throw a 571 * hardware error. 572 */ 573 error_report_err(err); 574 hw_error("vfio: DMA mapping failed, unable to continue"); 575 } 576 } 577 578 static void vfio_listener_region_del(MemoryListener *listener, 579 MemoryRegionSection *section) 580 { 581 VFIOContainerBase *bcontainer = container_of(listener, VFIOContainerBase, 582 listener); 583 hwaddr iova, end; 584 Int128 llend, llsize; 585 int ret; 586 bool try_unmap = true; 587 588 if (!vfio_listener_valid_section(section, "region_del")) { 589 return; 590 } 591 592 if (memory_region_is_iommu(section->mr)) { 593 VFIOGuestIOMMU *giommu; 594 595 trace_vfio_listener_region_del_iommu(section->mr->name); 596 QLIST_FOREACH(giommu, &bcontainer->giommu_list, giommu_next) { 597 if (MEMORY_REGION(giommu->iommu_mr) == section->mr && 598 giommu->n.start == section->offset_within_region) { 599 memory_region_unregister_iommu_notifier(section->mr, 600 &giommu->n); 601 QLIST_REMOVE(giommu, giommu_next); 602 g_free(giommu); 603 break; 604 } 605 } 606 607 /* 608 * FIXME: We assume the one big unmap below is adequate to 609 * remove any individual page mappings in the IOMMU which 610 * might have been copied into VFIO. This works for a page table 611 * based IOMMU where a big unmap flattens a large range of IO-PTEs. 612 * That may not be true for all IOMMU types. 613 */ 614 } 615 616 if (!vfio_get_section_iova_range(bcontainer, section, &iova, &end, 617 &llend)) { 618 return; 619 } 620 621 llsize = int128_sub(llend, int128_make64(iova)); 622 623 trace_vfio_listener_region_del(iova, end); 624 625 if (memory_region_is_ram_device(section->mr)) { 626 hwaddr pgmask; 627 628 pgmask = (1ULL << ctz64(bcontainer->pgsizes)) - 1; 629 try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask)); 630 } else if (memory_region_has_ram_discard_manager(section->mr)) { 631 vfio_ram_discard_unregister_listener(bcontainer, section); 632 /* Unregistering will trigger an unmap. */ 633 try_unmap = false; 634 } 635 636 if (try_unmap) { 637 if (int128_eq(llsize, int128_2_64())) { 638 /* The unmap ioctl doesn't accept a full 64-bit span. */ 639 llsize = int128_rshift(llsize, 1); 640 ret = vfio_container_dma_unmap(bcontainer, iova, 641 int128_get64(llsize), NULL); 642 if (ret) { 643 error_report("vfio_container_dma_unmap(%p, 0x%"HWADDR_PRIx", " 644 "0x%"HWADDR_PRIx") = %d (%s)", 645 bcontainer, iova, int128_get64(llsize), ret, 646 strerror(-ret)); 647 } 648 iova += int128_get64(llsize); 649 } 650 ret = vfio_container_dma_unmap(bcontainer, iova, 651 int128_get64(llsize), NULL); 652 if (ret) { 653 error_report("vfio_container_dma_unmap(%p, 0x%"HWADDR_PRIx", " 654 "0x%"HWADDR_PRIx") = %d (%s)", 655 bcontainer, iova, int128_get64(llsize), ret, 656 strerror(-ret)); 657 } 658 } 659 660 memory_region_unref(section->mr); 661 662 /* PPC64/pseries machine only */ 663 vfio_container_del_section_window(bcontainer, section); 664 } 665 666 typedef struct VFIODirtyRanges { 667 hwaddr min32; 668 hwaddr max32; 669 hwaddr min64; 670 hwaddr max64; 671 hwaddr minpci64; 672 hwaddr maxpci64; 673 } VFIODirtyRanges; 674 675 typedef struct VFIODirtyRangesListener { 676 VFIOContainerBase *bcontainer; 677 VFIODirtyRanges ranges; 678 MemoryListener listener; 679 } VFIODirtyRangesListener; 680 681 static bool vfio_section_is_vfio_pci(MemoryRegionSection *section, 682 VFIOContainerBase *bcontainer) 683 { 684 VFIOPCIDevice *pcidev; 685 VFIODevice *vbasedev; 686 Object *owner; 687 688 owner = memory_region_owner(section->mr); 689 690 QLIST_FOREACH(vbasedev, &bcontainer->device_list, container_next) { 691 if (vbasedev->type != VFIO_DEVICE_TYPE_PCI) { 692 continue; 693 } 694 pcidev = container_of(vbasedev, VFIOPCIDevice, vbasedev); 695 if (OBJECT(pcidev) == owner) { 696 return true; 697 } 698 } 699 700 return false; 701 } 702 703 static void vfio_dirty_tracking_update_range(VFIODirtyRanges *range, 704 hwaddr iova, hwaddr end, 705 bool update_pci) 706 { 707 hwaddr *min, *max; 708 709 /* 710 * The address space passed to the dirty tracker is reduced to three ranges: 711 * one for 32-bit DMA ranges, one for 64-bit DMA ranges and one for the 712 * PCI 64-bit hole. 713 * 714 * The underlying reports of dirty will query a sub-interval of each of 715 * these ranges. 716 * 717 * The purpose of the three range handling is to handle known cases of big 718 * holes in the address space, like the x86 AMD 1T hole, and firmware (like 719 * OVMF) which may relocate the pci-hole64 to the end of the address space. 720 * The latter would otherwise generate large ranges for tracking, stressing 721 * the limits of supported hardware. The pci-hole32 will always be below 4G 722 * (overlapping or not) so it doesn't need special handling and is part of 723 * the 32-bit range. 724 * 725 * The alternative would be an IOVATree but that has a much bigger runtime 726 * overhead and unnecessary complexity. 727 */ 728 if (update_pci && iova >= UINT32_MAX) { 729 min = &range->minpci64; 730 max = &range->maxpci64; 731 } else { 732 min = (end <= UINT32_MAX) ? &range->min32 : &range->min64; 733 max = (end <= UINT32_MAX) ? &range->max32 : &range->max64; 734 } 735 if (*min > iova) { 736 *min = iova; 737 } 738 if (*max < end) { 739 *max = end; 740 } 741 742 trace_vfio_device_dirty_tracking_update(iova, end, *min, *max); 743 } 744 745 static void vfio_dirty_tracking_update(MemoryListener *listener, 746 MemoryRegionSection *section) 747 { 748 VFIODirtyRangesListener *dirty = 749 container_of(listener, VFIODirtyRangesListener, listener); 750 hwaddr iova, end; 751 752 if (!vfio_listener_valid_section(section, "tracking_update") || 753 !vfio_get_section_iova_range(dirty->bcontainer, section, 754 &iova, &end, NULL)) { 755 return; 756 } 757 758 vfio_dirty_tracking_update_range(&dirty->ranges, iova, end, 759 vfio_section_is_vfio_pci(section, dirty->bcontainer)); 760 } 761 762 static const MemoryListener vfio_dirty_tracking_listener = { 763 .name = "vfio-tracking", 764 .region_add = vfio_dirty_tracking_update, 765 }; 766 767 static void vfio_dirty_tracking_init(VFIOContainerBase *bcontainer, 768 VFIODirtyRanges *ranges) 769 { 770 VFIODirtyRangesListener dirty; 771 772 memset(&dirty, 0, sizeof(dirty)); 773 dirty.ranges.min32 = UINT32_MAX; 774 dirty.ranges.min64 = UINT64_MAX; 775 dirty.ranges.minpci64 = UINT64_MAX; 776 dirty.listener = vfio_dirty_tracking_listener; 777 dirty.bcontainer = bcontainer; 778 779 memory_listener_register(&dirty.listener, 780 bcontainer->space->as); 781 782 *ranges = dirty.ranges; 783 784 /* 785 * The memory listener is synchronous, and used to calculate the range 786 * to dirty tracking. Unregister it after we are done as we are not 787 * interested in any follow-up updates. 788 */ 789 memory_listener_unregister(&dirty.listener); 790 } 791 792 static void vfio_devices_dma_logging_stop(VFIOContainerBase *bcontainer) 793 { 794 uint64_t buf[DIV_ROUND_UP(sizeof(struct vfio_device_feature), 795 sizeof(uint64_t))] = {}; 796 struct vfio_device_feature *feature = (struct vfio_device_feature *)buf; 797 VFIODevice *vbasedev; 798 799 feature->argsz = sizeof(buf); 800 feature->flags = VFIO_DEVICE_FEATURE_SET | 801 VFIO_DEVICE_FEATURE_DMA_LOGGING_STOP; 802 803 QLIST_FOREACH(vbasedev, &bcontainer->device_list, container_next) { 804 if (!vbasedev->dirty_tracking) { 805 continue; 806 } 807 808 if (ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature)) { 809 warn_report("%s: Failed to stop DMA logging, err %d (%s)", 810 vbasedev->name, -errno, strerror(errno)); 811 } 812 vbasedev->dirty_tracking = false; 813 } 814 } 815 816 static struct vfio_device_feature * 817 vfio_device_feature_dma_logging_start_create(VFIOContainerBase *bcontainer, 818 VFIODirtyRanges *tracking) 819 { 820 struct vfio_device_feature *feature; 821 size_t feature_size; 822 struct vfio_device_feature_dma_logging_control *control; 823 struct vfio_device_feature_dma_logging_range *ranges; 824 825 feature_size = sizeof(struct vfio_device_feature) + 826 sizeof(struct vfio_device_feature_dma_logging_control); 827 feature = g_try_malloc0(feature_size); 828 if (!feature) { 829 errno = ENOMEM; 830 return NULL; 831 } 832 feature->argsz = feature_size; 833 feature->flags = VFIO_DEVICE_FEATURE_SET | 834 VFIO_DEVICE_FEATURE_DMA_LOGGING_START; 835 836 control = (struct vfio_device_feature_dma_logging_control *)feature->data; 837 control->page_size = qemu_real_host_page_size(); 838 839 /* 840 * DMA logging uAPI guarantees to support at least a number of ranges that 841 * fits into a single host kernel base page. 842 */ 843 control->num_ranges = !!tracking->max32 + !!tracking->max64 + 844 !!tracking->maxpci64; 845 ranges = g_try_new0(struct vfio_device_feature_dma_logging_range, 846 control->num_ranges); 847 if (!ranges) { 848 g_free(feature); 849 errno = ENOMEM; 850 851 return NULL; 852 } 853 854 control->ranges = (uintptr_t)ranges; 855 if (tracking->max32) { 856 ranges->iova = tracking->min32; 857 ranges->length = (tracking->max32 - tracking->min32) + 1; 858 ranges++; 859 } 860 if (tracking->max64) { 861 ranges->iova = tracking->min64; 862 ranges->length = (tracking->max64 - tracking->min64) + 1; 863 ranges++; 864 } 865 if (tracking->maxpci64) { 866 ranges->iova = tracking->minpci64; 867 ranges->length = (tracking->maxpci64 - tracking->minpci64) + 1; 868 } 869 870 trace_vfio_device_dirty_tracking_start(control->num_ranges, 871 tracking->min32, tracking->max32, 872 tracking->min64, tracking->max64, 873 tracking->minpci64, tracking->maxpci64); 874 875 return feature; 876 } 877 878 static void vfio_device_feature_dma_logging_start_destroy( 879 struct vfio_device_feature *feature) 880 { 881 struct vfio_device_feature_dma_logging_control *control = 882 (struct vfio_device_feature_dma_logging_control *)feature->data; 883 struct vfio_device_feature_dma_logging_range *ranges = 884 (struct vfio_device_feature_dma_logging_range *)(uintptr_t)control->ranges; 885 886 g_free(ranges); 887 g_free(feature); 888 } 889 890 static bool vfio_devices_dma_logging_start(VFIOContainerBase *bcontainer, 891 Error **errp) 892 { 893 struct vfio_device_feature *feature; 894 VFIODirtyRanges ranges; 895 VFIODevice *vbasedev; 896 int ret = 0; 897 898 vfio_dirty_tracking_init(bcontainer, &ranges); 899 feature = vfio_device_feature_dma_logging_start_create(bcontainer, 900 &ranges); 901 if (!feature) { 902 error_setg_errno(errp, errno, "Failed to prepare DMA logging"); 903 return false; 904 } 905 906 QLIST_FOREACH(vbasedev, &bcontainer->device_list, container_next) { 907 if (vbasedev->dirty_tracking) { 908 continue; 909 } 910 911 ret = ioctl(vbasedev->fd, VFIO_DEVICE_FEATURE, feature); 912 if (ret) { 913 ret = -errno; 914 error_setg_errno(errp, errno, "%s: Failed to start DMA logging", 915 vbasedev->name); 916 goto out; 917 } 918 vbasedev->dirty_tracking = true; 919 } 920 921 out: 922 if (ret) { 923 vfio_devices_dma_logging_stop(bcontainer); 924 } 925 926 vfio_device_feature_dma_logging_start_destroy(feature); 927 928 return ret == 0; 929 } 930 931 static bool vfio_listener_log_global_start(MemoryListener *listener, 932 Error **errp) 933 { 934 ERRP_GUARD(); 935 VFIOContainerBase *bcontainer = container_of(listener, VFIOContainerBase, 936 listener); 937 bool ret; 938 939 if (vfio_container_devices_dirty_tracking_is_supported(bcontainer)) { 940 ret = vfio_devices_dma_logging_start(bcontainer, errp); 941 } else { 942 ret = vfio_container_set_dirty_page_tracking(bcontainer, true, errp) == 0; 943 } 944 945 if (!ret) { 946 error_prepend(errp, "vfio: Could not start dirty page tracking - "); 947 } 948 return ret; 949 } 950 951 static void vfio_listener_log_global_stop(MemoryListener *listener) 952 { 953 VFIOContainerBase *bcontainer = container_of(listener, VFIOContainerBase, 954 listener); 955 Error *local_err = NULL; 956 int ret = 0; 957 958 if (vfio_container_devices_dirty_tracking_is_supported(bcontainer)) { 959 vfio_devices_dma_logging_stop(bcontainer); 960 } else { 961 ret = vfio_container_set_dirty_page_tracking(bcontainer, false, 962 &local_err); 963 } 964 965 if (ret) { 966 error_prepend(&local_err, 967 "vfio: Could not stop dirty page tracking - "); 968 if (migration_is_running()) { 969 migration_file_set_error(ret, local_err); 970 } else { 971 error_report_err(local_err); 972 } 973 } 974 } 975 976 typedef struct { 977 IOMMUNotifier n; 978 VFIOGuestIOMMU *giommu; 979 } vfio_giommu_dirty_notifier; 980 981 static void vfio_iommu_map_dirty_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb) 982 { 983 vfio_giommu_dirty_notifier *gdn = container_of(n, 984 vfio_giommu_dirty_notifier, n); 985 VFIOGuestIOMMU *giommu = gdn->giommu; 986 VFIOContainerBase *bcontainer = giommu->bcontainer; 987 hwaddr iova = iotlb->iova + giommu->iommu_offset; 988 ram_addr_t translated_addr; 989 Error *local_err = NULL; 990 int ret = -EINVAL; 991 992 trace_vfio_iommu_map_dirty_notify(iova, iova + iotlb->addr_mask); 993 994 if (iotlb->target_as != &address_space_memory) { 995 error_setg(&local_err, 996 "Wrong target AS \"%s\", only system memory is allowed", 997 iotlb->target_as->name ? iotlb->target_as->name : "none"); 998 goto out; 999 } 1000 1001 rcu_read_lock(); 1002 if (!vfio_get_xlat_addr(iotlb, NULL, &translated_addr, NULL, &local_err)) { 1003 goto out_unlock; 1004 } 1005 1006 ret = vfio_container_query_dirty_bitmap(bcontainer, iova, iotlb->addr_mask + 1, 1007 translated_addr, &local_err); 1008 if (ret) { 1009 error_prepend(&local_err, 1010 "vfio_iommu_map_dirty_notify(%p, 0x%"HWADDR_PRIx", " 1011 "0x%"HWADDR_PRIx") failed - ", bcontainer, iova, 1012 iotlb->addr_mask + 1); 1013 } 1014 1015 out_unlock: 1016 rcu_read_unlock(); 1017 1018 out: 1019 if (ret) { 1020 if (migration_is_running()) { 1021 migration_file_set_error(ret, local_err); 1022 } else { 1023 error_report_err(local_err); 1024 } 1025 } 1026 } 1027 1028 static int vfio_ram_discard_query_dirty_bitmap(MemoryRegionSection *section, 1029 void *opaque) 1030 { 1031 const hwaddr size = int128_get64(section->size); 1032 const hwaddr iova = section->offset_within_address_space; 1033 const ram_addr_t ram_addr = memory_region_get_ram_addr(section->mr) + 1034 section->offset_within_region; 1035 VFIORamDiscardListener *vrdl = opaque; 1036 Error *local_err = NULL; 1037 int ret; 1038 1039 /* 1040 * Sync the whole mapped region (spanning multiple individual mappings) 1041 * in one go. 1042 */ 1043 ret = vfio_container_query_dirty_bitmap(vrdl->bcontainer, iova, size, ram_addr, 1044 &local_err); 1045 if (ret) { 1046 error_report_err(local_err); 1047 } 1048 return ret; 1049 } 1050 1051 static int 1052 vfio_sync_ram_discard_listener_dirty_bitmap(VFIOContainerBase *bcontainer, 1053 MemoryRegionSection *section) 1054 { 1055 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr); 1056 VFIORamDiscardListener *vrdl = NULL; 1057 1058 QLIST_FOREACH(vrdl, &bcontainer->vrdl_list, next) { 1059 if (vrdl->mr == section->mr && 1060 vrdl->offset_within_address_space == 1061 section->offset_within_address_space) { 1062 break; 1063 } 1064 } 1065 1066 if (!vrdl) { 1067 hw_error("vfio: Trying to sync missing RAM discard listener"); 1068 } 1069 1070 /* 1071 * We only want/can synchronize the bitmap for actually mapped parts - 1072 * which correspond to populated parts. Replay all populated parts. 1073 */ 1074 return ram_discard_manager_replay_populated(rdm, section, 1075 vfio_ram_discard_query_dirty_bitmap, 1076 &vrdl); 1077 } 1078 1079 static int vfio_sync_iommu_dirty_bitmap(VFIOContainerBase *bcontainer, 1080 MemoryRegionSection *section) 1081 { 1082 VFIOGuestIOMMU *giommu; 1083 bool found = false; 1084 Int128 llend; 1085 vfio_giommu_dirty_notifier gdn; 1086 int idx; 1087 1088 QLIST_FOREACH(giommu, &bcontainer->giommu_list, giommu_next) { 1089 if (MEMORY_REGION(giommu->iommu_mr) == section->mr && 1090 giommu->n.start == section->offset_within_region) { 1091 found = true; 1092 break; 1093 } 1094 } 1095 1096 if (!found) { 1097 return 0; 1098 } 1099 1100 gdn.giommu = giommu; 1101 idx = memory_region_iommu_attrs_to_index(giommu->iommu_mr, 1102 MEMTXATTRS_UNSPECIFIED); 1103 1104 llend = int128_add(int128_make64(section->offset_within_region), 1105 section->size); 1106 llend = int128_sub(llend, int128_one()); 1107 1108 iommu_notifier_init(&gdn.n, vfio_iommu_map_dirty_notify, IOMMU_NOTIFIER_MAP, 1109 section->offset_within_region, int128_get64(llend), 1110 idx); 1111 memory_region_iommu_replay(giommu->iommu_mr, &gdn.n); 1112 1113 return 0; 1114 } 1115 1116 static int vfio_sync_dirty_bitmap(VFIOContainerBase *bcontainer, 1117 MemoryRegionSection *section, Error **errp) 1118 { 1119 ram_addr_t ram_addr; 1120 1121 if (memory_region_is_iommu(section->mr)) { 1122 return vfio_sync_iommu_dirty_bitmap(bcontainer, section); 1123 } else if (memory_region_has_ram_discard_manager(section->mr)) { 1124 int ret; 1125 1126 ret = vfio_sync_ram_discard_listener_dirty_bitmap(bcontainer, section); 1127 if (ret) { 1128 error_setg(errp, 1129 "Failed to sync dirty bitmap with RAM discard listener"); 1130 } 1131 return ret; 1132 } 1133 1134 ram_addr = memory_region_get_ram_addr(section->mr) + 1135 section->offset_within_region; 1136 1137 return vfio_container_query_dirty_bitmap(bcontainer, 1138 REAL_HOST_PAGE_ALIGN(section->offset_within_address_space), 1139 int128_get64(section->size), ram_addr, errp); 1140 } 1141 1142 static void vfio_listener_log_sync(MemoryListener *listener, 1143 MemoryRegionSection *section) 1144 { 1145 VFIOContainerBase *bcontainer = container_of(listener, VFIOContainerBase, 1146 listener); 1147 int ret; 1148 Error *local_err = NULL; 1149 1150 if (vfio_listener_skipped_section(section)) { 1151 return; 1152 } 1153 1154 if (vfio_log_sync_needed(bcontainer)) { 1155 ret = vfio_sync_dirty_bitmap(bcontainer, section, &local_err); 1156 if (ret) { 1157 if (migration_is_running()) { 1158 migration_file_set_error(ret, local_err); 1159 } else { 1160 error_report_err(local_err); 1161 } 1162 } 1163 } 1164 } 1165 1166 static const MemoryListener vfio_memory_listener = { 1167 .name = "vfio", 1168 .region_add = vfio_listener_region_add, 1169 .region_del = vfio_listener_region_del, 1170 .log_global_start = vfio_listener_log_global_start, 1171 .log_global_stop = vfio_listener_log_global_stop, 1172 .log_sync = vfio_listener_log_sync, 1173 }; 1174 1175 bool vfio_listener_register(VFIOContainerBase *bcontainer, Error **errp) 1176 { 1177 bcontainer->listener = vfio_memory_listener; 1178 memory_listener_register(&bcontainer->listener, bcontainer->space->as); 1179 1180 if (bcontainer->error) { 1181 error_propagate_prepend(errp, bcontainer->error, 1182 "memory listener initialization failed: "); 1183 return false; 1184 } 1185 1186 return true; 1187 } 1188 1189 void vfio_listener_unregister(VFIOContainerBase *bcontainer) 1190 { 1191 memory_listener_unregister(&bcontainer->listener); 1192 } 1193