1 /* 2 * vfio based device assignment support 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 CONFIG_DEVICES /* CONFIG_IOMMUFD */ 23 #include <linux/vfio.h> 24 #include <sys/ioctl.h> 25 26 #include "hw/hw.h" 27 #include "hw/pci/msi.h" 28 #include "hw/pci/msix.h" 29 #include "hw/pci/pci_bridge.h" 30 #include "hw/qdev-properties.h" 31 #include "hw/qdev-properties-system.h" 32 #include "migration/vmstate.h" 33 #include "qobject/qdict.h" 34 #include "qemu/error-report.h" 35 #include "qemu/main-loop.h" 36 #include "qemu/module.h" 37 #include "qemu/range.h" 38 #include "qemu/units.h" 39 #include "system/kvm.h" 40 #include "system/runstate.h" 41 #include "pci.h" 42 #include "trace.h" 43 #include "qapi/error.h" 44 #include "migration/blocker.h" 45 #include "migration/qemu-file.h" 46 #include "system/iommufd.h" 47 #include "vfio-migration-internal.h" 48 #include "vfio-helpers.h" 49 50 #define TYPE_VFIO_PCI_NOHOTPLUG "vfio-pci-nohotplug" 51 52 /* Protected by BQL */ 53 static KVMRouteChange vfio_route_change; 54 55 static void vfio_disable_interrupts(VFIOPCIDevice *vdev); 56 static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled); 57 static void vfio_msi_disable_common(VFIOPCIDevice *vdev); 58 59 /* 60 * Disabling BAR mmaping can be slow, but toggling it around INTx can 61 * also be a huge overhead. We try to get the best of both worlds by 62 * waiting until an interrupt to disable mmaps (subsequent transitions 63 * to the same state are effectively no overhead). If the interrupt has 64 * been serviced and the time gap is long enough, we re-enable mmaps for 65 * performance. This works well for things like graphics cards, which 66 * may not use their interrupt at all and are penalized to an unusable 67 * level by read/write BAR traps. Other devices, like NICs, have more 68 * regular interrupts and see much better latency by staying in non-mmap 69 * mode. We therefore set the default mmap_timeout such that a ping 70 * is just enough to keep the mmap disabled. Users can experiment with 71 * other options with the x-intx-mmap-timeout-ms parameter (a value of 72 * zero disables the timer). 73 */ 74 static void vfio_intx_mmap_enable(void *opaque) 75 { 76 VFIOPCIDevice *vdev = opaque; 77 78 if (vdev->intx.pending) { 79 timer_mod(vdev->intx.mmap_timer, 80 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout); 81 return; 82 } 83 84 vfio_mmap_set_enabled(vdev, true); 85 } 86 87 static void vfio_intx_interrupt(void *opaque) 88 { 89 VFIOPCIDevice *vdev = opaque; 90 91 if (!event_notifier_test_and_clear(&vdev->intx.interrupt)) { 92 return; 93 } 94 95 trace_vfio_intx_interrupt(vdev->vbasedev.name, 'A' + vdev->intx.pin); 96 97 vdev->intx.pending = true; 98 pci_irq_assert(&vdev->pdev); 99 vfio_mmap_set_enabled(vdev, false); 100 if (vdev->intx.mmap_timeout) { 101 timer_mod(vdev->intx.mmap_timer, 102 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout); 103 } 104 } 105 106 void vfio_pci_intx_eoi(VFIODevice *vbasedev) 107 { 108 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev); 109 110 if (!vdev->intx.pending) { 111 return; 112 } 113 114 trace_vfio_pci_intx_eoi(vbasedev->name); 115 116 vdev->intx.pending = false; 117 pci_irq_deassert(&vdev->pdev); 118 vfio_device_irq_unmask(vbasedev, VFIO_PCI_INTX_IRQ_INDEX); 119 } 120 121 static bool vfio_intx_enable_kvm(VFIOPCIDevice *vdev, Error **errp) 122 { 123 #ifdef CONFIG_KVM 124 int irq_fd = event_notifier_get_fd(&vdev->intx.interrupt); 125 126 if (vdev->no_kvm_intx || !kvm_irqfds_enabled() || 127 vdev->intx.route.mode != PCI_INTX_ENABLED || 128 !kvm_resamplefds_enabled()) { 129 return true; 130 } 131 132 /* Get to a known interrupt state */ 133 qemu_set_fd_handler(irq_fd, NULL, NULL, vdev); 134 vfio_device_irq_mask(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX); 135 vdev->intx.pending = false; 136 pci_irq_deassert(&vdev->pdev); 137 138 /* Get an eventfd for resample/unmask */ 139 if (event_notifier_init(&vdev->intx.unmask, 0)) { 140 error_setg(errp, "event_notifier_init failed eoi"); 141 goto fail; 142 } 143 144 if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, 145 &vdev->intx.interrupt, 146 &vdev->intx.unmask, 147 vdev->intx.route.irq)) { 148 error_setg_errno(errp, errno, "failed to setup resample irqfd"); 149 goto fail_irqfd; 150 } 151 152 if (!vfio_device_irq_set_signaling(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX, 0, 153 VFIO_IRQ_SET_ACTION_UNMASK, 154 event_notifier_get_fd(&vdev->intx.unmask), 155 errp)) { 156 goto fail_vfio; 157 } 158 159 /* Let'em rip */ 160 vfio_device_irq_unmask(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX); 161 162 vdev->intx.kvm_accel = true; 163 164 trace_vfio_intx_enable_kvm(vdev->vbasedev.name); 165 166 return true; 167 168 fail_vfio: 169 kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vdev->intx.interrupt, 170 vdev->intx.route.irq); 171 fail_irqfd: 172 event_notifier_cleanup(&vdev->intx.unmask); 173 fail: 174 qemu_set_fd_handler(irq_fd, vfio_intx_interrupt, NULL, vdev); 175 vfio_device_irq_unmask(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX); 176 return false; 177 #else 178 return true; 179 #endif 180 } 181 182 static void vfio_intx_disable_kvm(VFIOPCIDevice *vdev) 183 { 184 #ifdef CONFIG_KVM 185 if (!vdev->intx.kvm_accel) { 186 return; 187 } 188 189 /* 190 * Get to a known state, hardware masked, QEMU ready to accept new 191 * interrupts, QEMU IRQ de-asserted. 192 */ 193 vfio_device_irq_mask(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX); 194 vdev->intx.pending = false; 195 pci_irq_deassert(&vdev->pdev); 196 197 /* Tell KVM to stop listening for an INTx irqfd */ 198 if (kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vdev->intx.interrupt, 199 vdev->intx.route.irq)) { 200 error_report("vfio: Error: Failed to disable INTx irqfd: %m"); 201 } 202 203 /* We only need to close the eventfd for VFIO to cleanup the kernel side */ 204 event_notifier_cleanup(&vdev->intx.unmask); 205 206 /* QEMU starts listening for interrupt events. */ 207 qemu_set_fd_handler(event_notifier_get_fd(&vdev->intx.interrupt), 208 vfio_intx_interrupt, NULL, vdev); 209 210 vdev->intx.kvm_accel = false; 211 212 /* If we've missed an event, let it re-fire through QEMU */ 213 vfio_device_irq_unmask(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX); 214 215 trace_vfio_intx_disable_kvm(vdev->vbasedev.name); 216 #endif 217 } 218 219 static void vfio_intx_update(VFIOPCIDevice *vdev, PCIINTxRoute *route) 220 { 221 Error *err = NULL; 222 223 trace_vfio_intx_update(vdev->vbasedev.name, 224 vdev->intx.route.irq, route->irq); 225 226 vfio_intx_disable_kvm(vdev); 227 228 vdev->intx.route = *route; 229 230 if (route->mode != PCI_INTX_ENABLED) { 231 return; 232 } 233 234 if (!vfio_intx_enable_kvm(vdev, &err)) { 235 warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name); 236 } 237 238 /* Re-enable the interrupt in cased we missed an EOI */ 239 vfio_pci_intx_eoi(&vdev->vbasedev); 240 } 241 242 static void vfio_intx_routing_notifier(PCIDevice *pdev) 243 { 244 VFIOPCIDevice *vdev = VFIO_PCI_BASE(pdev); 245 PCIINTxRoute route; 246 247 if (vdev->interrupt != VFIO_INT_INTx) { 248 return; 249 } 250 251 route = pci_device_route_intx_to_irq(&vdev->pdev, vdev->intx.pin); 252 253 if (pci_intx_route_changed(&vdev->intx.route, &route)) { 254 vfio_intx_update(vdev, &route); 255 } 256 } 257 258 static void vfio_irqchip_change(Notifier *notify, void *data) 259 { 260 VFIOPCIDevice *vdev = container_of(notify, VFIOPCIDevice, 261 irqchip_change_notifier); 262 263 vfio_intx_update(vdev, &vdev->intx.route); 264 } 265 266 static bool vfio_intx_enable(VFIOPCIDevice *vdev, Error **errp) 267 { 268 uint8_t pin = vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1); 269 Error *err = NULL; 270 int32_t fd; 271 int ret; 272 273 274 if (!pin) { 275 return true; 276 } 277 278 vfio_disable_interrupts(vdev); 279 280 vdev->intx.pin = pin - 1; /* Pin A (1) -> irq[0] */ 281 pci_config_set_interrupt_pin(vdev->pdev.config, pin); 282 283 #ifdef CONFIG_KVM 284 /* 285 * Only conditional to avoid generating error messages on platforms 286 * where we won't actually use the result anyway. 287 */ 288 if (kvm_irqfds_enabled() && kvm_resamplefds_enabled()) { 289 vdev->intx.route = pci_device_route_intx_to_irq(&vdev->pdev, 290 vdev->intx.pin); 291 } 292 #endif 293 294 ret = event_notifier_init(&vdev->intx.interrupt, 0); 295 if (ret) { 296 error_setg_errno(errp, -ret, "event_notifier_init failed"); 297 return false; 298 } 299 fd = event_notifier_get_fd(&vdev->intx.interrupt); 300 qemu_set_fd_handler(fd, vfio_intx_interrupt, NULL, vdev); 301 302 if (!vfio_device_irq_set_signaling(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX, 0, 303 VFIO_IRQ_SET_ACTION_TRIGGER, fd, errp)) { 304 qemu_set_fd_handler(fd, NULL, NULL, vdev); 305 event_notifier_cleanup(&vdev->intx.interrupt); 306 return false; 307 } 308 309 if (!vfio_intx_enable_kvm(vdev, &err)) { 310 warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name); 311 } 312 313 vdev->interrupt = VFIO_INT_INTx; 314 315 trace_vfio_intx_enable(vdev->vbasedev.name); 316 return true; 317 } 318 319 static void vfio_intx_disable(VFIOPCIDevice *vdev) 320 { 321 int fd; 322 323 timer_del(vdev->intx.mmap_timer); 324 vfio_intx_disable_kvm(vdev); 325 vfio_device_irq_disable(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX); 326 vdev->intx.pending = false; 327 pci_irq_deassert(&vdev->pdev); 328 vfio_mmap_set_enabled(vdev, true); 329 330 fd = event_notifier_get_fd(&vdev->intx.interrupt); 331 qemu_set_fd_handler(fd, NULL, NULL, vdev); 332 event_notifier_cleanup(&vdev->intx.interrupt); 333 334 vdev->interrupt = VFIO_INT_NONE; 335 336 trace_vfio_intx_disable(vdev->vbasedev.name); 337 } 338 339 /* 340 * MSI/X 341 */ 342 static void vfio_msi_interrupt(void *opaque) 343 { 344 VFIOMSIVector *vector = opaque; 345 VFIOPCIDevice *vdev = vector->vdev; 346 MSIMessage (*get_msg)(PCIDevice *dev, unsigned vector); 347 void (*notify)(PCIDevice *dev, unsigned vector); 348 MSIMessage msg; 349 int nr = vector - vdev->msi_vectors; 350 351 if (!event_notifier_test_and_clear(&vector->interrupt)) { 352 return; 353 } 354 355 if (vdev->interrupt == VFIO_INT_MSIX) { 356 get_msg = msix_get_message; 357 notify = msix_notify; 358 359 /* A masked vector firing needs to use the PBA, enable it */ 360 if (msix_is_masked(&vdev->pdev, nr)) { 361 set_bit(nr, vdev->msix->pending); 362 memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, true); 363 trace_vfio_msix_pba_enable(vdev->vbasedev.name); 364 } 365 } else if (vdev->interrupt == VFIO_INT_MSI) { 366 get_msg = msi_get_message; 367 notify = msi_notify; 368 } else { 369 abort(); 370 } 371 372 msg = get_msg(&vdev->pdev, nr); 373 trace_vfio_msi_interrupt(vdev->vbasedev.name, nr, msg.address, msg.data); 374 notify(&vdev->pdev, nr); 375 } 376 377 /* 378 * Get MSI-X enabled, but no vector enabled, by setting vector 0 with an invalid 379 * fd to kernel. 380 */ 381 static int vfio_enable_msix_no_vec(VFIOPCIDevice *vdev) 382 { 383 g_autofree struct vfio_irq_set *irq_set = NULL; 384 int argsz; 385 int32_t *fd; 386 387 argsz = sizeof(*irq_set) + sizeof(*fd); 388 389 irq_set = g_malloc0(argsz); 390 irq_set->argsz = argsz; 391 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | 392 VFIO_IRQ_SET_ACTION_TRIGGER; 393 irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX; 394 irq_set->start = 0; 395 irq_set->count = 1; 396 fd = (int32_t *)&irq_set->data; 397 *fd = -1; 398 399 return vdev->vbasedev.io_ops->set_irqs(&vdev->vbasedev, irq_set); 400 } 401 402 static int vfio_enable_vectors(VFIOPCIDevice *vdev, bool msix) 403 { 404 struct vfio_irq_set *irq_set; 405 int ret = 0, i, argsz; 406 int32_t *fds; 407 408 /* 409 * If dynamic MSI-X allocation is supported, the vectors to be allocated 410 * and enabled can be scattered. Before kernel enabling MSI-X, setting 411 * nr_vectors causes all these vectors to be allocated on host. 412 * 413 * To keep allocation as needed, use vector 0 with an invalid fd to get 414 * MSI-X enabled first, then set vectors with a potentially sparse set of 415 * eventfds to enable interrupts only when enabled in guest. 416 */ 417 if (msix && !vdev->msix->noresize) { 418 ret = vfio_enable_msix_no_vec(vdev); 419 420 if (ret) { 421 return ret; 422 } 423 } 424 425 argsz = sizeof(*irq_set) + (vdev->nr_vectors * sizeof(*fds)); 426 427 irq_set = g_malloc0(argsz); 428 irq_set->argsz = argsz; 429 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER; 430 irq_set->index = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX; 431 irq_set->start = 0; 432 irq_set->count = vdev->nr_vectors; 433 fds = (int32_t *)&irq_set->data; 434 435 for (i = 0; i < vdev->nr_vectors; i++) { 436 int fd = -1; 437 438 /* 439 * MSI vs MSI-X - The guest has direct access to MSI mask and pending 440 * bits, therefore we always use the KVM signaling path when setup. 441 * MSI-X mask and pending bits are emulated, so we want to use the 442 * KVM signaling path only when configured and unmasked. 443 */ 444 if (vdev->msi_vectors[i].use) { 445 if (vdev->msi_vectors[i].virq < 0 || 446 (msix && msix_is_masked(&vdev->pdev, i))) { 447 fd = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt); 448 } else { 449 fd = event_notifier_get_fd(&vdev->msi_vectors[i].kvm_interrupt); 450 } 451 } 452 453 fds[i] = fd; 454 } 455 456 ret = vdev->vbasedev.io_ops->set_irqs(&vdev->vbasedev, irq_set); 457 458 g_free(irq_set); 459 460 return ret; 461 } 462 463 static void vfio_add_kvm_msi_virq(VFIOPCIDevice *vdev, VFIOMSIVector *vector, 464 int vector_n, bool msix) 465 { 466 if ((msix && vdev->no_kvm_msix) || (!msix && vdev->no_kvm_msi)) { 467 return; 468 } 469 470 vector->virq = kvm_irqchip_add_msi_route(&vfio_route_change, 471 vector_n, &vdev->pdev); 472 } 473 474 static void vfio_connect_kvm_msi_virq(VFIOMSIVector *vector) 475 { 476 if (vector->virq < 0) { 477 return; 478 } 479 480 if (event_notifier_init(&vector->kvm_interrupt, 0)) { 481 goto fail_notifier; 482 } 483 484 if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt, 485 NULL, vector->virq) < 0) { 486 goto fail_kvm; 487 } 488 489 return; 490 491 fail_kvm: 492 event_notifier_cleanup(&vector->kvm_interrupt); 493 fail_notifier: 494 kvm_irqchip_release_virq(kvm_state, vector->virq); 495 vector->virq = -1; 496 } 497 498 static void vfio_remove_kvm_msi_virq(VFIOMSIVector *vector) 499 { 500 kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt, 501 vector->virq); 502 kvm_irqchip_release_virq(kvm_state, vector->virq); 503 vector->virq = -1; 504 event_notifier_cleanup(&vector->kvm_interrupt); 505 } 506 507 static void vfio_update_kvm_msi_virq(VFIOMSIVector *vector, MSIMessage msg, 508 PCIDevice *pdev) 509 { 510 kvm_irqchip_update_msi_route(kvm_state, vector->virq, msg, pdev); 511 kvm_irqchip_commit_routes(kvm_state); 512 } 513 514 static void set_irq_signalling(VFIODevice *vbasedev, VFIOMSIVector *vector, 515 unsigned int nr) 516 { 517 Error *err = NULL; 518 int32_t fd; 519 520 if (vector->virq >= 0) { 521 fd = event_notifier_get_fd(&vector->kvm_interrupt); 522 } else { 523 fd = event_notifier_get_fd(&vector->interrupt); 524 } 525 526 if (!vfio_device_irq_set_signaling(vbasedev, VFIO_PCI_MSIX_IRQ_INDEX, nr, 527 VFIO_IRQ_SET_ACTION_TRIGGER, 528 fd, &err)) { 529 error_reportf_err(err, VFIO_MSG_PREFIX, vbasedev->name); 530 } 531 } 532 533 static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr, 534 MSIMessage *msg, IOHandler *handler) 535 { 536 VFIOPCIDevice *vdev = VFIO_PCI_BASE(pdev); 537 VFIOMSIVector *vector; 538 int ret; 539 bool resizing = !!(vdev->nr_vectors < nr + 1); 540 541 trace_vfio_msix_vector_do_use(vdev->vbasedev.name, nr); 542 543 vector = &vdev->msi_vectors[nr]; 544 545 if (!vector->use) { 546 vector->vdev = vdev; 547 vector->virq = -1; 548 if (event_notifier_init(&vector->interrupt, 0)) { 549 error_report("vfio: Error: event_notifier_init failed"); 550 } 551 vector->use = true; 552 msix_vector_use(pdev, nr); 553 } 554 555 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), 556 handler, NULL, vector); 557 558 /* 559 * Attempt to enable route through KVM irqchip, 560 * default to userspace handling if unavailable. 561 */ 562 if (vector->virq >= 0) { 563 if (!msg) { 564 vfio_remove_kvm_msi_virq(vector); 565 } else { 566 vfio_update_kvm_msi_virq(vector, *msg, pdev); 567 } 568 } else { 569 if (msg) { 570 if (vdev->defer_kvm_irq_routing) { 571 vfio_add_kvm_msi_virq(vdev, vector, nr, true); 572 } else { 573 vfio_route_change = kvm_irqchip_begin_route_changes(kvm_state); 574 vfio_add_kvm_msi_virq(vdev, vector, nr, true); 575 kvm_irqchip_commit_route_changes(&vfio_route_change); 576 vfio_connect_kvm_msi_virq(vector); 577 } 578 } 579 } 580 581 /* 582 * When dynamic allocation is not supported, we don't want to have the 583 * host allocate all possible MSI vectors for a device if they're not 584 * in use, so we shutdown and incrementally increase them as needed. 585 * nr_vectors represents the total number of vectors allocated. 586 * 587 * When dynamic allocation is supported, let the host only allocate 588 * and enable a vector when it is in use in guest. nr_vectors represents 589 * the upper bound of vectors being enabled (but not all of the ranges 590 * is allocated or enabled). 591 */ 592 if (resizing) { 593 vdev->nr_vectors = nr + 1; 594 } 595 596 if (!vdev->defer_kvm_irq_routing) { 597 if (vdev->msix->noresize && resizing) { 598 vfio_device_irq_disable(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX); 599 ret = vfio_enable_vectors(vdev, true); 600 if (ret) { 601 error_report("vfio: failed to enable vectors, %s", 602 strerror(-ret)); 603 } 604 } else { 605 set_irq_signalling(&vdev->vbasedev, vector, nr); 606 } 607 } 608 609 /* Disable PBA emulation when nothing more is pending. */ 610 clear_bit(nr, vdev->msix->pending); 611 if (find_first_bit(vdev->msix->pending, 612 vdev->nr_vectors) == vdev->nr_vectors) { 613 memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, false); 614 trace_vfio_msix_pba_disable(vdev->vbasedev.name); 615 } 616 617 return 0; 618 } 619 620 static int vfio_msix_vector_use(PCIDevice *pdev, 621 unsigned int nr, MSIMessage msg) 622 { 623 return vfio_msix_vector_do_use(pdev, nr, &msg, vfio_msi_interrupt); 624 } 625 626 static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr) 627 { 628 VFIOPCIDevice *vdev = VFIO_PCI_BASE(pdev); 629 VFIOMSIVector *vector = &vdev->msi_vectors[nr]; 630 631 trace_vfio_msix_vector_release(vdev->vbasedev.name, nr); 632 633 /* 634 * There are still old guests that mask and unmask vectors on every 635 * interrupt. If we're using QEMU bypass with a KVM irqfd, leave all of 636 * the KVM setup in place, simply switch VFIO to use the non-bypass 637 * eventfd. We'll then fire the interrupt through QEMU and the MSI-X 638 * core will mask the interrupt and set pending bits, allowing it to 639 * be re-asserted on unmask. Nothing to do if already using QEMU mode. 640 */ 641 if (vector->virq >= 0) { 642 int32_t fd = event_notifier_get_fd(&vector->interrupt); 643 Error *err = NULL; 644 645 if (!vfio_device_irq_set_signaling(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX, 646 nr, VFIO_IRQ_SET_ACTION_TRIGGER, fd, 647 &err)) { 648 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name); 649 } 650 } 651 } 652 653 static void vfio_prepare_kvm_msi_virq_batch(VFIOPCIDevice *vdev) 654 { 655 assert(!vdev->defer_kvm_irq_routing); 656 vdev->defer_kvm_irq_routing = true; 657 vfio_route_change = kvm_irqchip_begin_route_changes(kvm_state); 658 } 659 660 static void vfio_commit_kvm_msi_virq_batch(VFIOPCIDevice *vdev) 661 { 662 int i; 663 664 assert(vdev->defer_kvm_irq_routing); 665 vdev->defer_kvm_irq_routing = false; 666 667 kvm_irqchip_commit_route_changes(&vfio_route_change); 668 669 for (i = 0; i < vdev->nr_vectors; i++) { 670 vfio_connect_kvm_msi_virq(&vdev->msi_vectors[i]); 671 } 672 } 673 674 static void vfio_msix_enable(VFIOPCIDevice *vdev) 675 { 676 int ret; 677 678 vfio_disable_interrupts(vdev); 679 680 vdev->msi_vectors = g_new0(VFIOMSIVector, vdev->msix->entries); 681 682 vdev->interrupt = VFIO_INT_MSIX; 683 684 /* 685 * Setting vector notifiers triggers synchronous vector-use 686 * callbacks for each active vector. Deferring to commit the KVM 687 * routes once rather than per vector provides a substantial 688 * performance improvement. 689 */ 690 vfio_prepare_kvm_msi_virq_batch(vdev); 691 692 if (msix_set_vector_notifiers(&vdev->pdev, vfio_msix_vector_use, 693 vfio_msix_vector_release, NULL)) { 694 error_report("vfio: msix_set_vector_notifiers failed"); 695 } 696 697 vfio_commit_kvm_msi_virq_batch(vdev); 698 699 if (vdev->nr_vectors) { 700 ret = vfio_enable_vectors(vdev, true); 701 if (ret) { 702 error_report("vfio: failed to enable vectors, %s", 703 strerror(-ret)); 704 } 705 } else { 706 /* 707 * Some communication channels between VF & PF or PF & fw rely on the 708 * physical state of the device and expect that enabling MSI-X from the 709 * guest enables the same on the host. When our guest is Linux, the 710 * guest driver call to pci_enable_msix() sets the enabling bit in the 711 * MSI-X capability, but leaves the vector table masked. We therefore 712 * can't rely on a vector_use callback (from request_irq() in the guest) 713 * to switch the physical device into MSI-X mode because that may come a 714 * long time after pci_enable_msix(). This code sets vector 0 with an 715 * invalid fd to make the physical device MSI-X enabled, but with no 716 * vectors enabled, just like the guest view. 717 */ 718 ret = vfio_enable_msix_no_vec(vdev); 719 if (ret) { 720 error_report("vfio: failed to enable MSI-X, %s", 721 strerror(-ret)); 722 } 723 } 724 725 trace_vfio_msix_enable(vdev->vbasedev.name); 726 } 727 728 static void vfio_msi_enable(VFIOPCIDevice *vdev) 729 { 730 int ret, i; 731 732 vfio_disable_interrupts(vdev); 733 734 vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev); 735 retry: 736 /* 737 * Setting vector notifiers needs to enable route for each vector. 738 * Deferring to commit the KVM routes once rather than per vector 739 * provides a substantial performance improvement. 740 */ 741 vfio_prepare_kvm_msi_virq_batch(vdev); 742 743 vdev->msi_vectors = g_new0(VFIOMSIVector, vdev->nr_vectors); 744 745 for (i = 0; i < vdev->nr_vectors; i++) { 746 VFIOMSIVector *vector = &vdev->msi_vectors[i]; 747 748 vector->vdev = vdev; 749 vector->virq = -1; 750 vector->use = true; 751 752 if (event_notifier_init(&vector->interrupt, 0)) { 753 error_report("vfio: Error: event_notifier_init failed"); 754 } 755 756 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), 757 vfio_msi_interrupt, NULL, vector); 758 759 /* 760 * Attempt to enable route through KVM irqchip, 761 * default to userspace handling if unavailable. 762 */ 763 vfio_add_kvm_msi_virq(vdev, vector, i, false); 764 } 765 766 vfio_commit_kvm_msi_virq_batch(vdev); 767 768 /* Set interrupt type prior to possible interrupts */ 769 vdev->interrupt = VFIO_INT_MSI; 770 771 ret = vfio_enable_vectors(vdev, false); 772 if (ret) { 773 if (ret < 0) { 774 error_report("vfio: Error: Failed to setup MSI fds: %s", 775 strerror(-ret)); 776 } else { 777 error_report("vfio: Error: Failed to enable %d " 778 "MSI vectors, retry with %d", vdev->nr_vectors, ret); 779 } 780 781 vfio_msi_disable_common(vdev); 782 783 if (ret > 0) { 784 vdev->nr_vectors = ret; 785 goto retry; 786 } 787 788 /* 789 * Failing to setup MSI doesn't really fall within any specification. 790 * Let's try leaving interrupts disabled and hope the guest figures 791 * out to fall back to INTx for this device. 792 */ 793 error_report("vfio: Error: Failed to enable MSI"); 794 795 return; 796 } 797 798 trace_vfio_msi_enable(vdev->vbasedev.name, vdev->nr_vectors); 799 } 800 801 static void vfio_msi_disable_common(VFIOPCIDevice *vdev) 802 { 803 int i; 804 805 for (i = 0; i < vdev->nr_vectors; i++) { 806 VFIOMSIVector *vector = &vdev->msi_vectors[i]; 807 if (vdev->msi_vectors[i].use) { 808 if (vector->virq >= 0) { 809 vfio_remove_kvm_msi_virq(vector); 810 } 811 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt), 812 NULL, NULL, NULL); 813 event_notifier_cleanup(&vector->interrupt); 814 } 815 } 816 817 g_free(vdev->msi_vectors); 818 vdev->msi_vectors = NULL; 819 vdev->nr_vectors = 0; 820 vdev->interrupt = VFIO_INT_NONE; 821 } 822 823 static void vfio_msix_disable(VFIOPCIDevice *vdev) 824 { 825 Error *err = NULL; 826 int i; 827 828 msix_unset_vector_notifiers(&vdev->pdev); 829 830 /* 831 * MSI-X will only release vectors if MSI-X is still enabled on the 832 * device, check through the rest and release it ourselves if necessary. 833 */ 834 for (i = 0; i < vdev->nr_vectors; i++) { 835 if (vdev->msi_vectors[i].use) { 836 vfio_msix_vector_release(&vdev->pdev, i); 837 msix_vector_unuse(&vdev->pdev, i); 838 } 839 } 840 841 /* 842 * Always clear MSI-X IRQ index. A PF device could have enabled 843 * MSI-X with no vectors. See vfio_msix_enable(). 844 */ 845 vfio_device_irq_disable(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX); 846 847 vfio_msi_disable_common(vdev); 848 if (!vfio_intx_enable(vdev, &err)) { 849 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name); 850 } 851 852 memset(vdev->msix->pending, 0, 853 BITS_TO_LONGS(vdev->msix->entries) * sizeof(unsigned long)); 854 855 trace_vfio_msix_disable(vdev->vbasedev.name); 856 } 857 858 static void vfio_msi_disable(VFIOPCIDevice *vdev) 859 { 860 Error *err = NULL; 861 862 vfio_device_irq_disable(&vdev->vbasedev, VFIO_PCI_MSI_IRQ_INDEX); 863 vfio_msi_disable_common(vdev); 864 vfio_intx_enable(vdev, &err); 865 if (err) { 866 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name); 867 } 868 869 trace_vfio_msi_disable(vdev->vbasedev.name); 870 } 871 872 static void vfio_update_msi(VFIOPCIDevice *vdev) 873 { 874 int i; 875 876 for (i = 0; i < vdev->nr_vectors; i++) { 877 VFIOMSIVector *vector = &vdev->msi_vectors[i]; 878 MSIMessage msg; 879 880 if (!vector->use || vector->virq < 0) { 881 continue; 882 } 883 884 msg = msi_get_message(&vdev->pdev, i); 885 vfio_update_kvm_msi_virq(vector, msg, &vdev->pdev); 886 } 887 } 888 889 static void vfio_pci_load_rom(VFIOPCIDevice *vdev) 890 { 891 VFIODevice *vbasedev = &vdev->vbasedev; 892 struct vfio_region_info *reg_info = NULL; 893 uint64_t size; 894 off_t off = 0; 895 ssize_t bytes; 896 int ret; 897 898 ret = vfio_device_get_region_info(vbasedev, VFIO_PCI_ROM_REGION_INDEX, 899 ®_info); 900 901 if (ret != 0) { 902 error_report("vfio: Error getting ROM info: %s", strerror(-ret)); 903 return; 904 } 905 906 trace_vfio_pci_load_rom(vbasedev->name, (unsigned long)reg_info->size, 907 (unsigned long)reg_info->offset, 908 (unsigned long)reg_info->flags); 909 910 vdev->rom_size = size = reg_info->size; 911 vdev->rom_offset = reg_info->offset; 912 913 if (!vdev->rom_size) { 914 vdev->rom_read_failed = true; 915 error_report("vfio-pci: Cannot read device rom at %s", vbasedev->name); 916 error_printf("Device option ROM contents are probably invalid " 917 "(check dmesg).\nSkip option ROM probe with rombar=0, " 918 "or load from file with romfile=\n"); 919 return; 920 } 921 922 vdev->rom = g_malloc(size); 923 memset(vdev->rom, 0xff, size); 924 925 while (size) { 926 bytes = vbasedev->io_ops->region_read(vbasedev, 927 VFIO_PCI_ROM_REGION_INDEX, 928 off, size, vdev->rom + off); 929 930 if (bytes == 0) { 931 break; 932 } else if (bytes > 0) { 933 off += bytes; 934 size -= bytes; 935 } else { 936 if (bytes == -EINTR || bytes == -EAGAIN) { 937 continue; 938 } 939 error_report("vfio: Error reading device ROM: %s", 940 strreaderror(bytes)); 941 942 break; 943 } 944 } 945 946 /* 947 * Test the ROM signature against our device, if the vendor is correct 948 * but the device ID doesn't match, store the correct device ID and 949 * recompute the checksum. Intel IGD devices need this and are known 950 * to have bogus checksums so we can't simply adjust the checksum. 951 */ 952 if (pci_get_word(vdev->rom) == 0xaa55 && 953 pci_get_word(vdev->rom + 0x18) + 8 < vdev->rom_size && 954 !memcmp(vdev->rom + pci_get_word(vdev->rom + 0x18), "PCIR", 4)) { 955 uint16_t vid, did; 956 957 vid = pci_get_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 4); 958 did = pci_get_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 6); 959 960 if (vid == vdev->vendor_id && did != vdev->device_id) { 961 int i; 962 uint8_t csum, *data = vdev->rom; 963 964 pci_set_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 6, 965 vdev->device_id); 966 data[6] = 0; 967 968 for (csum = 0, i = 0; i < vdev->rom_size; i++) { 969 csum += data[i]; 970 } 971 972 data[6] = -csum; 973 } 974 } 975 } 976 977 /* "Raw" read of underlying config space. */ 978 static int vfio_pci_config_space_read(VFIOPCIDevice *vdev, off_t offset, 979 uint32_t size, void *data) 980 { 981 return vdev->vbasedev.io_ops->region_read(&vdev->vbasedev, 982 VFIO_PCI_CONFIG_REGION_INDEX, 983 offset, size, data); 984 } 985 986 /* "Raw" write of underlying config space. */ 987 static int vfio_pci_config_space_write(VFIOPCIDevice *vdev, off_t offset, 988 uint32_t size, void *data) 989 { 990 return vdev->vbasedev.io_ops->region_write(&vdev->vbasedev, 991 VFIO_PCI_CONFIG_REGION_INDEX, 992 offset, size, data, false); 993 } 994 995 static uint64_t vfio_rom_read(void *opaque, hwaddr addr, unsigned size) 996 { 997 VFIOPCIDevice *vdev = opaque; 998 union { 999 uint8_t byte; 1000 uint16_t word; 1001 uint32_t dword; 1002 uint64_t qword; 1003 } val; 1004 uint64_t data = 0; 1005 1006 /* Load the ROM lazily when the guest tries to read it */ 1007 if (unlikely(!vdev->rom && !vdev->rom_read_failed)) { 1008 vfio_pci_load_rom(vdev); 1009 } 1010 1011 memcpy(&val, vdev->rom + addr, 1012 (addr < vdev->rom_size) ? MIN(size, vdev->rom_size - addr) : 0); 1013 1014 switch (size) { 1015 case 1: 1016 data = val.byte; 1017 break; 1018 case 2: 1019 data = le16_to_cpu(val.word); 1020 break; 1021 case 4: 1022 data = le32_to_cpu(val.dword); 1023 break; 1024 default: 1025 hw_error("vfio: unsupported read size, %d bytes\n", size); 1026 break; 1027 } 1028 1029 trace_vfio_rom_read(vdev->vbasedev.name, addr, size, data); 1030 1031 return data; 1032 } 1033 1034 static void vfio_rom_write(void *opaque, hwaddr addr, 1035 uint64_t data, unsigned size) 1036 { 1037 } 1038 1039 static const MemoryRegionOps vfio_rom_ops = { 1040 .read = vfio_rom_read, 1041 .write = vfio_rom_write, 1042 .endianness = DEVICE_LITTLE_ENDIAN, 1043 }; 1044 1045 static void vfio_pci_size_rom(VFIOPCIDevice *vdev) 1046 { 1047 VFIODevice *vbasedev = &vdev->vbasedev; 1048 uint32_t orig, size = cpu_to_le32((uint32_t)PCI_ROM_ADDRESS_MASK); 1049 char *name; 1050 1051 if (vdev->pdev.romfile || !vdev->pdev.rom_bar) { 1052 /* Since pci handles romfile, just print a message and return */ 1053 if (vfio_opt_rom_in_denylist(vdev) && vdev->pdev.romfile) { 1054 warn_report("Device at %s is known to cause system instability" 1055 " issues during option rom execution", 1056 vdev->vbasedev.name); 1057 error_printf("Proceeding anyway since user specified romfile\n"); 1058 } 1059 return; 1060 } 1061 1062 /* 1063 * Use the same size ROM BAR as the physical device. The contents 1064 * will get filled in later when the guest tries to read it. 1065 */ 1066 if (vfio_pci_config_space_read(vdev, PCI_ROM_ADDRESS, 4, &orig) != 4 || 1067 vfio_pci_config_space_write(vdev, PCI_ROM_ADDRESS, 4, &size) != 4 || 1068 vfio_pci_config_space_read(vdev, PCI_ROM_ADDRESS, 4, &size) != 4 || 1069 vfio_pci_config_space_write(vdev, PCI_ROM_ADDRESS, 4, &orig) != 4) { 1070 1071 error_report("%s(%s) ROM access failed", __func__, vbasedev->name); 1072 return; 1073 } 1074 1075 size = ~(le32_to_cpu(size) & PCI_ROM_ADDRESS_MASK) + 1; 1076 1077 if (!size) { 1078 return; 1079 } 1080 1081 if (vfio_opt_rom_in_denylist(vdev)) { 1082 if (vdev->pdev.rom_bar > 0) { 1083 warn_report("Device at %s is known to cause system instability" 1084 " issues during option rom execution", 1085 vdev->vbasedev.name); 1086 error_printf("Proceeding anyway since user specified" 1087 " positive value for rombar\n"); 1088 } else { 1089 warn_report("Rom loading for device at %s has been disabled" 1090 " due to system instability issues", 1091 vdev->vbasedev.name); 1092 error_printf("Specify rombar=1 or romfile to force\n"); 1093 return; 1094 } 1095 } 1096 1097 trace_vfio_pci_size_rom(vdev->vbasedev.name, size); 1098 1099 name = g_strdup_printf("vfio[%s].rom", vdev->vbasedev.name); 1100 1101 memory_region_init_io(&vdev->pdev.rom, OBJECT(vdev), 1102 &vfio_rom_ops, vdev, name, size); 1103 g_free(name); 1104 1105 pci_register_bar(&vdev->pdev, PCI_ROM_SLOT, 1106 PCI_BASE_ADDRESS_SPACE_MEMORY, &vdev->pdev.rom); 1107 1108 vdev->rom_read_failed = false; 1109 } 1110 1111 void vfio_vga_write(void *opaque, hwaddr addr, 1112 uint64_t data, unsigned size) 1113 { 1114 VFIOVGARegion *region = opaque; 1115 VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]); 1116 union { 1117 uint8_t byte; 1118 uint16_t word; 1119 uint32_t dword; 1120 uint64_t qword; 1121 } buf; 1122 off_t offset = vga->fd_offset + region->offset + addr; 1123 1124 switch (size) { 1125 case 1: 1126 buf.byte = data; 1127 break; 1128 case 2: 1129 buf.word = cpu_to_le16(data); 1130 break; 1131 case 4: 1132 buf.dword = cpu_to_le32(data); 1133 break; 1134 default: 1135 hw_error("vfio: unsupported write size, %d bytes", size); 1136 break; 1137 } 1138 1139 if (pwrite(vga->fd, &buf, size, offset) != size) { 1140 error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m", 1141 __func__, region->offset + addr, data, size); 1142 } 1143 1144 trace_vfio_vga_write(region->offset + addr, data, size); 1145 } 1146 1147 uint64_t vfio_vga_read(void *opaque, hwaddr addr, unsigned size) 1148 { 1149 VFIOVGARegion *region = opaque; 1150 VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]); 1151 union { 1152 uint8_t byte; 1153 uint16_t word; 1154 uint32_t dword; 1155 uint64_t qword; 1156 } buf; 1157 uint64_t data = 0; 1158 off_t offset = vga->fd_offset + region->offset + addr; 1159 1160 if (pread(vga->fd, &buf, size, offset) != size) { 1161 error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m", 1162 __func__, region->offset + addr, size); 1163 return (uint64_t)-1; 1164 } 1165 1166 switch (size) { 1167 case 1: 1168 data = buf.byte; 1169 break; 1170 case 2: 1171 data = le16_to_cpu(buf.word); 1172 break; 1173 case 4: 1174 data = le32_to_cpu(buf.dword); 1175 break; 1176 default: 1177 hw_error("vfio: unsupported read size, %d bytes", size); 1178 break; 1179 } 1180 1181 trace_vfio_vga_read(region->offset + addr, size, data); 1182 1183 return data; 1184 } 1185 1186 static const MemoryRegionOps vfio_vga_ops = { 1187 .read = vfio_vga_read, 1188 .write = vfio_vga_write, 1189 .endianness = DEVICE_LITTLE_ENDIAN, 1190 }; 1191 1192 /* 1193 * Expand memory region of sub-page(size < PAGE_SIZE) MMIO BAR to page 1194 * size if the BAR is in an exclusive page in host so that we could map 1195 * this BAR to guest. But this sub-page BAR may not occupy an exclusive 1196 * page in guest. So we should set the priority of the expanded memory 1197 * region to zero in case of overlap with BARs which share the same page 1198 * with the sub-page BAR in guest. Besides, we should also recover the 1199 * size of this sub-page BAR when its base address is changed in guest 1200 * and not page aligned any more. 1201 */ 1202 static void vfio_sub_page_bar_update_mapping(PCIDevice *pdev, int bar) 1203 { 1204 VFIOPCIDevice *vdev = VFIO_PCI_BASE(pdev); 1205 VFIORegion *region = &vdev->bars[bar].region; 1206 MemoryRegion *mmap_mr, *region_mr, *base_mr; 1207 PCIIORegion *r; 1208 pcibus_t bar_addr; 1209 uint64_t size = region->size; 1210 1211 /* Make sure that the whole region is allowed to be mmapped */ 1212 if (region->nr_mmaps != 1 || !region->mmaps[0].mmap || 1213 region->mmaps[0].size != region->size) { 1214 return; 1215 } 1216 1217 r = &pdev->io_regions[bar]; 1218 bar_addr = r->addr; 1219 base_mr = vdev->bars[bar].mr; 1220 region_mr = region->mem; 1221 mmap_mr = ®ion->mmaps[0].mem; 1222 1223 /* If BAR is mapped and page aligned, update to fill PAGE_SIZE */ 1224 if (bar_addr != PCI_BAR_UNMAPPED && 1225 !(bar_addr & ~qemu_real_host_page_mask())) { 1226 size = qemu_real_host_page_size(); 1227 } 1228 1229 memory_region_transaction_begin(); 1230 1231 if (vdev->bars[bar].size < size) { 1232 memory_region_set_size(base_mr, size); 1233 } 1234 memory_region_set_size(region_mr, size); 1235 memory_region_set_size(mmap_mr, size); 1236 if (size != vdev->bars[bar].size && memory_region_is_mapped(base_mr)) { 1237 memory_region_del_subregion(r->address_space, base_mr); 1238 memory_region_add_subregion_overlap(r->address_space, 1239 bar_addr, base_mr, 0); 1240 } 1241 1242 memory_region_transaction_commit(); 1243 } 1244 1245 /* 1246 * PCI config space 1247 */ 1248 uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len) 1249 { 1250 VFIOPCIDevice *vdev = VFIO_PCI_BASE(pdev); 1251 VFIODevice *vbasedev = &vdev->vbasedev; 1252 uint32_t emu_bits = 0, emu_val = 0, phys_val = 0, val; 1253 1254 memcpy(&emu_bits, vdev->emulated_config_bits + addr, len); 1255 emu_bits = le32_to_cpu(emu_bits); 1256 1257 if (emu_bits) { 1258 emu_val = pci_default_read_config(pdev, addr, len); 1259 } 1260 1261 if (~emu_bits & (0xffffffffU >> (32 - len * 8))) { 1262 ssize_t ret; 1263 1264 ret = vfio_pci_config_space_read(vdev, addr, len, &phys_val); 1265 if (ret != len) { 1266 error_report("%s(%s, 0x%x, 0x%x) failed: %s", 1267 __func__, vbasedev->name, addr, len, 1268 strreaderror(ret)); 1269 return -1; 1270 } 1271 phys_val = le32_to_cpu(phys_val); 1272 } 1273 1274 val = (emu_val & emu_bits) | (phys_val & ~emu_bits); 1275 1276 trace_vfio_pci_read_config(vdev->vbasedev.name, addr, len, val); 1277 1278 return val; 1279 } 1280 1281 void vfio_pci_write_config(PCIDevice *pdev, 1282 uint32_t addr, uint32_t val, int len) 1283 { 1284 VFIOPCIDevice *vdev = VFIO_PCI_BASE(pdev); 1285 VFIODevice *vbasedev = &vdev->vbasedev; 1286 uint32_t val_le = cpu_to_le32(val); 1287 int ret; 1288 1289 trace_vfio_pci_write_config(vdev->vbasedev.name, addr, val, len); 1290 1291 /* Write everything to VFIO, let it filter out what we can't write */ 1292 ret = vfio_pci_config_space_write(vdev, addr, len, &val_le); 1293 if (ret != len) { 1294 error_report("%s(%s, 0x%x, 0x%x, 0x%x) failed: %s", 1295 __func__, vbasedev->name, addr, val, len, 1296 strwriteerror(ret)); 1297 } 1298 1299 /* MSI/MSI-X Enabling/Disabling */ 1300 if (pdev->cap_present & QEMU_PCI_CAP_MSI && 1301 ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) { 1302 int is_enabled, was_enabled = msi_enabled(pdev); 1303 1304 pci_default_write_config(pdev, addr, val, len); 1305 1306 is_enabled = msi_enabled(pdev); 1307 1308 if (!was_enabled) { 1309 if (is_enabled) { 1310 vfio_msi_enable(vdev); 1311 } 1312 } else { 1313 if (!is_enabled) { 1314 vfio_msi_disable(vdev); 1315 } else { 1316 vfio_update_msi(vdev); 1317 } 1318 } 1319 } else if (pdev->cap_present & QEMU_PCI_CAP_MSIX && 1320 ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) { 1321 int is_enabled, was_enabled = msix_enabled(pdev); 1322 1323 pci_default_write_config(pdev, addr, val, len); 1324 1325 is_enabled = msix_enabled(pdev); 1326 1327 if (!was_enabled && is_enabled) { 1328 vfio_msix_enable(vdev); 1329 } else if (was_enabled && !is_enabled) { 1330 vfio_msix_disable(vdev); 1331 } 1332 } else if (ranges_overlap(addr, len, PCI_BASE_ADDRESS_0, 24) || 1333 range_covers_byte(addr, len, PCI_COMMAND)) { 1334 pcibus_t old_addr[PCI_NUM_REGIONS - 1]; 1335 int bar; 1336 1337 for (bar = 0; bar < PCI_ROM_SLOT; bar++) { 1338 old_addr[bar] = pdev->io_regions[bar].addr; 1339 } 1340 1341 pci_default_write_config(pdev, addr, val, len); 1342 1343 for (bar = 0; bar < PCI_ROM_SLOT; bar++) { 1344 if (old_addr[bar] != pdev->io_regions[bar].addr && 1345 vdev->bars[bar].region.size > 0 && 1346 vdev->bars[bar].region.size < qemu_real_host_page_size()) { 1347 vfio_sub_page_bar_update_mapping(pdev, bar); 1348 } 1349 } 1350 } else { 1351 /* Write everything to QEMU to keep emulated bits correct */ 1352 pci_default_write_config(pdev, addr, val, len); 1353 } 1354 } 1355 1356 /* 1357 * Interrupt setup 1358 */ 1359 static void vfio_disable_interrupts(VFIOPCIDevice *vdev) 1360 { 1361 /* 1362 * More complicated than it looks. Disabling MSI/X transitions the 1363 * device to INTx mode (if supported). Therefore we need to first 1364 * disable MSI/X and then cleanup by disabling INTx. 1365 */ 1366 if (vdev->interrupt == VFIO_INT_MSIX) { 1367 vfio_msix_disable(vdev); 1368 } else if (vdev->interrupt == VFIO_INT_MSI) { 1369 vfio_msi_disable(vdev); 1370 } 1371 1372 if (vdev->interrupt == VFIO_INT_INTx) { 1373 vfio_intx_disable(vdev); 1374 } 1375 } 1376 1377 static bool vfio_msi_setup(VFIOPCIDevice *vdev, int pos, Error **errp) 1378 { 1379 uint16_t ctrl; 1380 bool msi_64bit, msi_maskbit; 1381 int ret, entries; 1382 Error *err = NULL; 1383 1384 ret = vfio_pci_config_space_read(vdev, pos + PCI_CAP_FLAGS, 1385 sizeof(ctrl), &ctrl); 1386 if (ret != sizeof(ctrl)) { 1387 error_setg(errp, "failed reading MSI PCI_CAP_FLAGS: %s", 1388 strreaderror(ret)); 1389 return false; 1390 } 1391 ctrl = le16_to_cpu(ctrl); 1392 1393 msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT); 1394 msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT); 1395 entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1); 1396 1397 trace_vfio_msi_setup(vdev->vbasedev.name, pos); 1398 1399 ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit, &err); 1400 if (ret < 0) { 1401 if (ret == -ENOTSUP) { 1402 return true; 1403 } 1404 error_propagate_prepend(errp, err, "msi_init failed: "); 1405 return false; 1406 } 1407 vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0); 1408 1409 return true; 1410 } 1411 1412 static void vfio_pci_fixup_msix_region(VFIOPCIDevice *vdev) 1413 { 1414 off_t start, end; 1415 VFIORegion *region = &vdev->bars[vdev->msix->table_bar].region; 1416 1417 /* 1418 * If the host driver allows mapping of a MSIX data, we are going to 1419 * do map the entire BAR and emulate MSIX table on top of that. 1420 */ 1421 if (vfio_device_has_region_cap(&vdev->vbasedev, region->nr, 1422 VFIO_REGION_INFO_CAP_MSIX_MAPPABLE)) { 1423 return; 1424 } 1425 1426 /* 1427 * We expect to find a single mmap covering the whole BAR, anything else 1428 * means it's either unsupported or already setup. 1429 */ 1430 if (region->nr_mmaps != 1 || region->mmaps[0].offset || 1431 region->size != region->mmaps[0].size) { 1432 return; 1433 } 1434 1435 /* MSI-X table start and end aligned to host page size */ 1436 start = vdev->msix->table_offset & qemu_real_host_page_mask(); 1437 end = REAL_HOST_PAGE_ALIGN((uint64_t)vdev->msix->table_offset + 1438 (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE)); 1439 1440 /* 1441 * Does the MSI-X table cover the beginning of the BAR? The whole BAR? 1442 * NB - Host page size is necessarily a power of two and so is the PCI 1443 * BAR (not counting EA yet), therefore if we have host page aligned 1444 * @start and @end, then any remainder of the BAR before or after those 1445 * must be at least host page sized and therefore mmap'able. 1446 */ 1447 if (!start) { 1448 if (end >= region->size) { 1449 region->nr_mmaps = 0; 1450 g_free(region->mmaps); 1451 region->mmaps = NULL; 1452 trace_vfio_msix_fixup(vdev->vbasedev.name, 1453 vdev->msix->table_bar, 0, 0); 1454 } else { 1455 region->mmaps[0].offset = end; 1456 region->mmaps[0].size = region->size - end; 1457 trace_vfio_msix_fixup(vdev->vbasedev.name, 1458 vdev->msix->table_bar, region->mmaps[0].offset, 1459 region->mmaps[0].offset + region->mmaps[0].size); 1460 } 1461 1462 /* Maybe it's aligned at the end of the BAR */ 1463 } else if (end >= region->size) { 1464 region->mmaps[0].size = start; 1465 trace_vfio_msix_fixup(vdev->vbasedev.name, 1466 vdev->msix->table_bar, region->mmaps[0].offset, 1467 region->mmaps[0].offset + region->mmaps[0].size); 1468 1469 /* Otherwise it must split the BAR */ 1470 } else { 1471 region->nr_mmaps = 2; 1472 region->mmaps = g_renew(VFIOMmap, region->mmaps, 2); 1473 1474 memcpy(®ion->mmaps[1], ®ion->mmaps[0], sizeof(VFIOMmap)); 1475 1476 region->mmaps[0].size = start; 1477 trace_vfio_msix_fixup(vdev->vbasedev.name, 1478 vdev->msix->table_bar, region->mmaps[0].offset, 1479 region->mmaps[0].offset + region->mmaps[0].size); 1480 1481 region->mmaps[1].offset = end; 1482 region->mmaps[1].size = region->size - end; 1483 trace_vfio_msix_fixup(vdev->vbasedev.name, 1484 vdev->msix->table_bar, region->mmaps[1].offset, 1485 region->mmaps[1].offset + region->mmaps[1].size); 1486 } 1487 } 1488 1489 static bool vfio_pci_relocate_msix(VFIOPCIDevice *vdev, Error **errp) 1490 { 1491 int target_bar = -1; 1492 size_t msix_sz; 1493 1494 if (!vdev->msix || vdev->msix_relo == OFF_AUTO_PCIBAR_OFF) { 1495 return true; 1496 } 1497 1498 /* The actual minimum size of MSI-X structures */ 1499 msix_sz = (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE) + 1500 (QEMU_ALIGN_UP(vdev->msix->entries, 64) / 8); 1501 /* Round up to host pages, we don't want to share a page */ 1502 msix_sz = REAL_HOST_PAGE_ALIGN(msix_sz); 1503 /* PCI BARs must be a power of 2 */ 1504 msix_sz = pow2ceil(msix_sz); 1505 1506 if (vdev->msix_relo == OFF_AUTO_PCIBAR_AUTO) { 1507 /* 1508 * TODO: Lookup table for known devices. 1509 * 1510 * Logically we might use an algorithm here to select the BAR adding 1511 * the least additional MMIO space, but we cannot programmatically 1512 * predict the driver dependency on BAR ordering or sizing, therefore 1513 * 'auto' becomes a lookup for combinations reported to work. 1514 */ 1515 if (target_bar < 0) { 1516 error_setg(errp, "No automatic MSI-X relocation available for " 1517 "device %04x:%04x", vdev->vendor_id, vdev->device_id); 1518 return false; 1519 } 1520 } else { 1521 target_bar = (int)(vdev->msix_relo - OFF_AUTO_PCIBAR_BAR0); 1522 } 1523 1524 /* I/O port BARs cannot host MSI-X structures */ 1525 if (vdev->bars[target_bar].ioport) { 1526 error_setg(errp, "Invalid MSI-X relocation BAR %d, " 1527 "I/O port BAR", target_bar); 1528 return false; 1529 } 1530 1531 /* Cannot use a BAR in the "shadow" of a 64-bit BAR */ 1532 if (!vdev->bars[target_bar].size && 1533 target_bar > 0 && vdev->bars[target_bar - 1].mem64) { 1534 error_setg(errp, "Invalid MSI-X relocation BAR %d, " 1535 "consumed by 64-bit BAR %d", target_bar, target_bar - 1); 1536 return false; 1537 } 1538 1539 /* 2GB max size for 32-bit BARs, cannot double if already > 1G */ 1540 if (vdev->bars[target_bar].size > 1 * GiB && 1541 !vdev->bars[target_bar].mem64) { 1542 error_setg(errp, "Invalid MSI-X relocation BAR %d, " 1543 "no space to extend 32-bit BAR", target_bar); 1544 return false; 1545 } 1546 1547 /* 1548 * If adding a new BAR, test if we can make it 64bit. We make it 1549 * prefetchable since QEMU MSI-X emulation has no read side effects 1550 * and doing so makes mapping more flexible. 1551 */ 1552 if (!vdev->bars[target_bar].size) { 1553 if (target_bar < (PCI_ROM_SLOT - 1) && 1554 !vdev->bars[target_bar + 1].size) { 1555 vdev->bars[target_bar].mem64 = true; 1556 vdev->bars[target_bar].type = PCI_BASE_ADDRESS_MEM_TYPE_64; 1557 } 1558 vdev->bars[target_bar].type |= PCI_BASE_ADDRESS_MEM_PREFETCH; 1559 vdev->bars[target_bar].size = msix_sz; 1560 vdev->msix->table_offset = 0; 1561 } else { 1562 vdev->bars[target_bar].size = MAX(vdev->bars[target_bar].size * 2, 1563 msix_sz * 2); 1564 /* 1565 * Due to above size calc, MSI-X always starts halfway into the BAR, 1566 * which will always be a separate host page. 1567 */ 1568 vdev->msix->table_offset = vdev->bars[target_bar].size / 2; 1569 } 1570 1571 vdev->msix->table_bar = target_bar; 1572 vdev->msix->pba_bar = target_bar; 1573 /* Requires 8-byte alignment, but PCI_MSIX_ENTRY_SIZE guarantees that */ 1574 vdev->msix->pba_offset = vdev->msix->table_offset + 1575 (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE); 1576 1577 trace_vfio_msix_relo(vdev->vbasedev.name, 1578 vdev->msix->table_bar, vdev->msix->table_offset); 1579 return true; 1580 } 1581 1582 /* 1583 * We don't have any control over how pci_add_capability() inserts 1584 * capabilities into the chain. In order to setup MSI-X we need a 1585 * MemoryRegion for the BAR. In order to setup the BAR and not 1586 * attempt to mmap the MSI-X table area, which VFIO won't allow, we 1587 * need to first look for where the MSI-X table lives. So we 1588 * unfortunately split MSI-X setup across two functions. 1589 */ 1590 static bool vfio_msix_early_setup(VFIOPCIDevice *vdev, Error **errp) 1591 { 1592 uint8_t pos; 1593 uint16_t ctrl; 1594 uint32_t table, pba; 1595 struct vfio_irq_info irq_info; 1596 VFIOMSIXInfo *msix; 1597 int ret; 1598 1599 pos = pci_find_capability(&vdev->pdev, PCI_CAP_ID_MSIX); 1600 if (!pos) { 1601 return true; 1602 } 1603 1604 ret = vfio_pci_config_space_read(vdev, pos + PCI_MSIX_FLAGS, 1605 sizeof(ctrl), &ctrl); 1606 if (ret != sizeof(ctrl)) { 1607 error_setg(errp, "failed to read PCI MSIX FLAGS: %s", 1608 strreaderror(ret)); 1609 return false; 1610 } 1611 1612 ret = vfio_pci_config_space_read(vdev, pos + PCI_MSIX_TABLE, 1613 sizeof(table), &table); 1614 if (ret != sizeof(table)) { 1615 error_setg(errp, "failed to read PCI MSIX TABLE: %s", 1616 strreaderror(ret)); 1617 return false; 1618 } 1619 1620 ret = vfio_pci_config_space_read(vdev, pos + PCI_MSIX_PBA, 1621 sizeof(pba), &pba); 1622 if (ret != sizeof(pba)) { 1623 error_setg(errp, "failed to read PCI MSIX PBA: %s", strreaderror(ret)); 1624 return false; 1625 } 1626 1627 ctrl = le16_to_cpu(ctrl); 1628 table = le32_to_cpu(table); 1629 pba = le32_to_cpu(pba); 1630 1631 msix = g_malloc0(sizeof(*msix)); 1632 msix->table_bar = table & PCI_MSIX_FLAGS_BIRMASK; 1633 msix->table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK; 1634 msix->pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK; 1635 msix->pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK; 1636 msix->entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1; 1637 1638 ret = vfio_device_get_irq_info(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX, 1639 &irq_info); 1640 if (ret < 0) { 1641 error_setg_errno(errp, -ret, "failed to get MSI-X irq info"); 1642 g_free(msix); 1643 return false; 1644 } 1645 1646 msix->noresize = !!(irq_info.flags & VFIO_IRQ_INFO_NORESIZE); 1647 1648 /* 1649 * Test the size of the pba_offset variable and catch if it extends outside 1650 * of the specified BAR. If it is the case, we need to apply a hardware 1651 * specific quirk if the device is known or we have a broken configuration. 1652 */ 1653 if (msix->pba_offset >= vdev->bars[msix->pba_bar].region.size) { 1654 /* 1655 * Chelsio T5 Virtual Function devices are encoded as 0x58xx for T5 1656 * adapters. The T5 hardware returns an incorrect value of 0x8000 for 1657 * the VF PBA offset while the BAR itself is only 8k. The correct value 1658 * is 0x1000, so we hard code that here. 1659 */ 1660 if (vdev->vendor_id == PCI_VENDOR_ID_CHELSIO && 1661 (vdev->device_id & 0xff00) == 0x5800) { 1662 msix->pba_offset = 0x1000; 1663 /* 1664 * BAIDU KUNLUN Virtual Function devices for KUNLUN AI processor 1665 * return an incorrect value of 0x460000 for the VF PBA offset while 1666 * the BAR itself is only 0x10000. The correct value is 0xb400. 1667 */ 1668 } else if (vfio_pci_is(vdev, PCI_VENDOR_ID_BAIDU, 1669 PCI_DEVICE_ID_KUNLUN_VF)) { 1670 msix->pba_offset = 0xb400; 1671 } else if (vdev->msix_relo == OFF_AUTO_PCIBAR_OFF) { 1672 error_setg(errp, "hardware reports invalid configuration, " 1673 "MSIX PBA outside of specified BAR"); 1674 g_free(msix); 1675 return false; 1676 } 1677 } 1678 1679 trace_vfio_msix_early_setup(vdev->vbasedev.name, pos, msix->table_bar, 1680 msix->table_offset, msix->entries, 1681 msix->noresize); 1682 vdev->msix = msix; 1683 1684 vfio_pci_fixup_msix_region(vdev); 1685 1686 return vfio_pci_relocate_msix(vdev, errp); 1687 } 1688 1689 static bool vfio_msix_setup(VFIOPCIDevice *vdev, int pos, Error **errp) 1690 { 1691 int ret; 1692 Error *err = NULL; 1693 1694 vdev->msix->pending = g_new0(unsigned long, 1695 BITS_TO_LONGS(vdev->msix->entries)); 1696 ret = msix_init(&vdev->pdev, vdev->msix->entries, 1697 vdev->bars[vdev->msix->table_bar].mr, 1698 vdev->msix->table_bar, vdev->msix->table_offset, 1699 vdev->bars[vdev->msix->pba_bar].mr, 1700 vdev->msix->pba_bar, vdev->msix->pba_offset, pos, 1701 &err); 1702 if (ret < 0) { 1703 if (ret == -ENOTSUP) { 1704 warn_report_err(err); 1705 return true; 1706 } 1707 1708 error_propagate(errp, err); 1709 return false; 1710 } 1711 1712 /* 1713 * The PCI spec suggests that devices provide additional alignment for 1714 * MSI-X structures and avoid overlapping non-MSI-X related registers. 1715 * For an assigned device, this hopefully means that emulation of MSI-X 1716 * structures does not affect the performance of the device. If devices 1717 * fail to provide that alignment, a significant performance penalty may 1718 * result, for instance Mellanox MT27500 VFs: 1719 * http://www.spinics.net/lists/kvm/msg125881.html 1720 * 1721 * The PBA is simply not that important for such a serious regression and 1722 * most drivers do not appear to look at it. The solution for this is to 1723 * disable the PBA MemoryRegion unless it's being used. We disable it 1724 * here and only enable it if a masked vector fires through QEMU. As the 1725 * vector-use notifier is called, which occurs on unmask, we test whether 1726 * PBA emulation is needed and again disable if not. 1727 */ 1728 memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, false); 1729 1730 /* 1731 * The emulated machine may provide a paravirt interface for MSIX setup 1732 * so it is not strictly necessary to emulate MSIX here. This becomes 1733 * helpful when frequently accessed MMIO registers are located in 1734 * subpages adjacent to the MSIX table but the MSIX data containing page 1735 * cannot be mapped because of a host page size bigger than the MSIX table 1736 * alignment. 1737 */ 1738 if (object_property_get_bool(OBJECT(qdev_get_machine()), 1739 "vfio-no-msix-emulation", NULL)) { 1740 memory_region_set_enabled(&vdev->pdev.msix_table_mmio, false); 1741 } 1742 1743 return true; 1744 } 1745 1746 void vfio_pci_teardown_msi(VFIOPCIDevice *vdev) 1747 { 1748 msi_uninit(&vdev->pdev); 1749 1750 if (vdev->msix) { 1751 msix_uninit(&vdev->pdev, 1752 vdev->bars[vdev->msix->table_bar].mr, 1753 vdev->bars[vdev->msix->pba_bar].mr); 1754 g_free(vdev->msix->pending); 1755 } 1756 } 1757 1758 /* 1759 * Resource setup 1760 */ 1761 static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled) 1762 { 1763 int i; 1764 1765 for (i = 0; i < PCI_ROM_SLOT; i++) { 1766 vfio_region_mmaps_set_enabled(&vdev->bars[i].region, enabled); 1767 } 1768 } 1769 1770 static void vfio_bar_prepare(VFIOPCIDevice *vdev, int nr) 1771 { 1772 VFIOBAR *bar = &vdev->bars[nr]; 1773 1774 uint32_t pci_bar; 1775 int ret; 1776 1777 /* Skip both unimplemented BARs and the upper half of 64bit BARS. */ 1778 if (!bar->region.size) { 1779 return; 1780 } 1781 1782 /* Determine what type of BAR this is for registration */ 1783 ret = vfio_pci_config_space_read(vdev, PCI_BASE_ADDRESS_0 + (4 * nr), 1784 sizeof(pci_bar), &pci_bar); 1785 if (ret != sizeof(pci_bar)) { 1786 error_report("vfio: Failed to read BAR %d: %s", nr, strreaderror(ret)); 1787 return; 1788 } 1789 1790 pci_bar = le32_to_cpu(pci_bar); 1791 bar->ioport = (pci_bar & PCI_BASE_ADDRESS_SPACE_IO); 1792 bar->mem64 = bar->ioport ? 0 : (pci_bar & PCI_BASE_ADDRESS_MEM_TYPE_64); 1793 bar->type = pci_bar & (bar->ioport ? ~PCI_BASE_ADDRESS_IO_MASK : 1794 ~PCI_BASE_ADDRESS_MEM_MASK); 1795 bar->size = bar->region.size; 1796 1797 /* IO regions are sync, memory can be async */ 1798 bar->region.post_wr = (bar->ioport == 0); 1799 } 1800 1801 static void vfio_bars_prepare(VFIOPCIDevice *vdev) 1802 { 1803 int i; 1804 1805 for (i = 0; i < PCI_ROM_SLOT; i++) { 1806 vfio_bar_prepare(vdev, i); 1807 } 1808 } 1809 1810 static void vfio_bar_register(VFIOPCIDevice *vdev, int nr) 1811 { 1812 VFIOBAR *bar = &vdev->bars[nr]; 1813 char *name; 1814 1815 if (!bar->size) { 1816 return; 1817 } 1818 1819 bar->mr = g_new0(MemoryRegion, 1); 1820 name = g_strdup_printf("%s base BAR %d", vdev->vbasedev.name, nr); 1821 memory_region_init_io(bar->mr, OBJECT(vdev), NULL, NULL, name, bar->size); 1822 g_free(name); 1823 1824 if (bar->region.size) { 1825 memory_region_add_subregion(bar->mr, 0, bar->region.mem); 1826 1827 if (vfio_region_mmap(&bar->region)) { 1828 error_report("Failed to mmap %s BAR %d. Performance may be slow", 1829 vdev->vbasedev.name, nr); 1830 } 1831 } 1832 1833 pci_register_bar(&vdev->pdev, nr, bar->type, bar->mr); 1834 } 1835 1836 static void vfio_bars_register(VFIOPCIDevice *vdev) 1837 { 1838 int i; 1839 1840 for (i = 0; i < PCI_ROM_SLOT; i++) { 1841 vfio_bar_register(vdev, i); 1842 } 1843 } 1844 1845 void vfio_pci_bars_exit(VFIOPCIDevice *vdev) 1846 { 1847 int i; 1848 1849 for (i = 0; i < PCI_ROM_SLOT; i++) { 1850 VFIOBAR *bar = &vdev->bars[i]; 1851 1852 vfio_bar_quirk_exit(vdev, i); 1853 vfio_region_exit(&bar->region); 1854 if (bar->region.size) { 1855 memory_region_del_subregion(bar->mr, bar->region.mem); 1856 } 1857 } 1858 1859 if (vdev->vga) { 1860 pci_unregister_vga(&vdev->pdev); 1861 vfio_vga_quirk_exit(vdev); 1862 } 1863 } 1864 1865 static void vfio_bars_finalize(VFIOPCIDevice *vdev) 1866 { 1867 int i; 1868 1869 for (i = 0; i < PCI_ROM_SLOT; i++) { 1870 VFIOBAR *bar = &vdev->bars[i]; 1871 1872 vfio_bar_quirk_finalize(vdev, i); 1873 vfio_region_finalize(&bar->region); 1874 if (bar->mr) { 1875 assert(bar->size); 1876 object_unparent(OBJECT(bar->mr)); 1877 g_free(bar->mr); 1878 bar->mr = NULL; 1879 } 1880 } 1881 1882 if (vdev->vga) { 1883 vfio_vga_quirk_finalize(vdev); 1884 for (i = 0; i < ARRAY_SIZE(vdev->vga->region); i++) { 1885 object_unparent(OBJECT(&vdev->vga->region[i].mem)); 1886 } 1887 g_free(vdev->vga); 1888 } 1889 } 1890 1891 /* 1892 * General setup 1893 */ 1894 static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos) 1895 { 1896 uint8_t tmp; 1897 uint16_t next = PCI_CONFIG_SPACE_SIZE; 1898 1899 for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp; 1900 tmp = pdev->config[tmp + PCI_CAP_LIST_NEXT]) { 1901 if (tmp > pos && tmp < next) { 1902 next = tmp; 1903 } 1904 } 1905 1906 return next - pos; 1907 } 1908 1909 1910 static uint16_t vfio_ext_cap_max_size(const uint8_t *config, uint16_t pos) 1911 { 1912 uint16_t tmp, next = PCIE_CONFIG_SPACE_SIZE; 1913 1914 for (tmp = PCI_CONFIG_SPACE_SIZE; tmp; 1915 tmp = PCI_EXT_CAP_NEXT(pci_get_long(config + tmp))) { 1916 if (tmp > pos && tmp < next) { 1917 next = tmp; 1918 } 1919 } 1920 1921 return next - pos; 1922 } 1923 1924 static void vfio_set_word_bits(uint8_t *buf, uint16_t val, uint16_t mask) 1925 { 1926 pci_set_word(buf, (pci_get_word(buf) & ~mask) | val); 1927 } 1928 1929 static void vfio_add_emulated_word(VFIOPCIDevice *vdev, int pos, 1930 uint16_t val, uint16_t mask) 1931 { 1932 vfio_set_word_bits(vdev->pdev.config + pos, val, mask); 1933 vfio_set_word_bits(vdev->pdev.wmask + pos, ~mask, mask); 1934 vfio_set_word_bits(vdev->emulated_config_bits + pos, mask, mask); 1935 } 1936 1937 static void vfio_set_long_bits(uint8_t *buf, uint32_t val, uint32_t mask) 1938 { 1939 pci_set_long(buf, (pci_get_long(buf) & ~mask) | val); 1940 } 1941 1942 static void vfio_add_emulated_long(VFIOPCIDevice *vdev, int pos, 1943 uint32_t val, uint32_t mask) 1944 { 1945 vfio_set_long_bits(vdev->pdev.config + pos, val, mask); 1946 vfio_set_long_bits(vdev->pdev.wmask + pos, ~mask, mask); 1947 vfio_set_long_bits(vdev->emulated_config_bits + pos, mask, mask); 1948 } 1949 1950 static void vfio_pci_enable_rp_atomics(VFIOPCIDevice *vdev) 1951 { 1952 struct vfio_device_info_cap_pci_atomic_comp *cap; 1953 g_autofree struct vfio_device_info *info = NULL; 1954 PCIBus *bus = pci_get_bus(&vdev->pdev); 1955 PCIDevice *parent = bus->parent_dev; 1956 struct vfio_info_cap_header *hdr; 1957 uint32_t mask = 0; 1958 uint8_t *pos; 1959 1960 /* 1961 * PCIe Atomic Ops completer support is only added automatically for single 1962 * function devices downstream of a root port supporting DEVCAP2. Support 1963 * is added during realize and, if added, removed during device exit. The 1964 * single function requirement avoids conflicting requirements should a 1965 * slot be composed of multiple devices with differing capabilities. 1966 */ 1967 if (pci_bus_is_root(bus) || !parent || !parent->exp.exp_cap || 1968 pcie_cap_get_type(parent) != PCI_EXP_TYPE_ROOT_PORT || 1969 pcie_cap_get_version(parent) != PCI_EXP_FLAGS_VER2 || 1970 vdev->pdev.devfn || 1971 vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) { 1972 return; 1973 } 1974 1975 pos = parent->config + parent->exp.exp_cap + PCI_EXP_DEVCAP2; 1976 1977 /* Abort if there'a already an Atomic Ops configuration on the root port */ 1978 if (pci_get_long(pos) & (PCI_EXP_DEVCAP2_ATOMIC_COMP32 | 1979 PCI_EXP_DEVCAP2_ATOMIC_COMP64 | 1980 PCI_EXP_DEVCAP2_ATOMIC_COMP128)) { 1981 return; 1982 } 1983 1984 info = vfio_get_device_info(vdev->vbasedev.fd); 1985 if (!info) { 1986 return; 1987 } 1988 1989 hdr = vfio_get_device_info_cap(info, VFIO_DEVICE_INFO_CAP_PCI_ATOMIC_COMP); 1990 if (!hdr) { 1991 return; 1992 } 1993 1994 cap = (void *)hdr; 1995 if (cap->flags & VFIO_PCI_ATOMIC_COMP32) { 1996 mask |= PCI_EXP_DEVCAP2_ATOMIC_COMP32; 1997 } 1998 if (cap->flags & VFIO_PCI_ATOMIC_COMP64) { 1999 mask |= PCI_EXP_DEVCAP2_ATOMIC_COMP64; 2000 } 2001 if (cap->flags & VFIO_PCI_ATOMIC_COMP128) { 2002 mask |= PCI_EXP_DEVCAP2_ATOMIC_COMP128; 2003 } 2004 2005 if (!mask) { 2006 return; 2007 } 2008 2009 pci_long_test_and_set_mask(pos, mask); 2010 vdev->clear_parent_atomics_on_exit = true; 2011 } 2012 2013 static void vfio_pci_disable_rp_atomics(VFIOPCIDevice *vdev) 2014 { 2015 if (vdev->clear_parent_atomics_on_exit) { 2016 PCIDevice *parent = pci_get_bus(&vdev->pdev)->parent_dev; 2017 uint8_t *pos = parent->config + parent->exp.exp_cap + PCI_EXP_DEVCAP2; 2018 2019 pci_long_test_and_clear_mask(pos, PCI_EXP_DEVCAP2_ATOMIC_COMP32 | 2020 PCI_EXP_DEVCAP2_ATOMIC_COMP64 | 2021 PCI_EXP_DEVCAP2_ATOMIC_COMP128); 2022 } 2023 } 2024 2025 static bool vfio_setup_pcie_cap(VFIOPCIDevice *vdev, int pos, uint8_t size, 2026 Error **errp) 2027 { 2028 uint16_t flags; 2029 uint8_t type; 2030 2031 flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS); 2032 type = (flags & PCI_EXP_FLAGS_TYPE) >> 4; 2033 2034 if (type != PCI_EXP_TYPE_ENDPOINT && 2035 type != PCI_EXP_TYPE_LEG_END && 2036 type != PCI_EXP_TYPE_RC_END) { 2037 2038 error_setg(errp, "assignment of PCIe type 0x%x " 2039 "devices is not currently supported", type); 2040 return false; 2041 } 2042 2043 if (!pci_bus_is_express(pci_get_bus(&vdev->pdev))) { 2044 PCIBus *bus = pci_get_bus(&vdev->pdev); 2045 PCIDevice *bridge; 2046 2047 /* 2048 * Traditionally PCI device assignment exposes the PCIe capability 2049 * as-is on non-express buses. The reason being that some drivers 2050 * simply assume that it's there, for example tg3. However when 2051 * we're running on a native PCIe machine type, like Q35, we need 2052 * to hide the PCIe capability. The reason for this is twofold; 2053 * first Windows guests get a Code 10 error when the PCIe capability 2054 * is exposed in this configuration. Therefore express devices won't 2055 * work at all unless they're attached to express buses in the VM. 2056 * Second, a native PCIe machine introduces the possibility of fine 2057 * granularity IOMMUs supporting both translation and isolation. 2058 * Guest code to discover the IOMMU visibility of a device, such as 2059 * IOMMU grouping code on Linux, is very aware of device types and 2060 * valid transitions between bus types. An express device on a non- 2061 * express bus is not a valid combination on bare metal systems. 2062 * 2063 * Drivers that require a PCIe capability to make the device 2064 * functional are simply going to need to have their devices placed 2065 * on a PCIe bus in the VM. 2066 */ 2067 while (!pci_bus_is_root(bus)) { 2068 bridge = pci_bridge_get_device(bus); 2069 bus = pci_get_bus(bridge); 2070 } 2071 2072 if (pci_bus_is_express(bus)) { 2073 return true; 2074 } 2075 2076 } else if (pci_bus_is_root(pci_get_bus(&vdev->pdev))) { 2077 /* 2078 * On a Root Complex bus Endpoints become Root Complex Integrated 2079 * Endpoints, which changes the type and clears the LNK & LNK2 fields. 2080 */ 2081 if (type == PCI_EXP_TYPE_ENDPOINT) { 2082 vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS, 2083 PCI_EXP_TYPE_RC_END << 4, 2084 PCI_EXP_FLAGS_TYPE); 2085 2086 /* Link Capabilities, Status, and Control goes away */ 2087 if (size > PCI_EXP_LNKCTL) { 2088 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0); 2089 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0); 2090 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0); 2091 2092 #ifndef PCI_EXP_LNKCAP2 2093 #define PCI_EXP_LNKCAP2 44 2094 #endif 2095 #ifndef PCI_EXP_LNKSTA2 2096 #define PCI_EXP_LNKSTA2 50 2097 #endif 2098 /* Link 2 Capabilities, Status, and Control goes away */ 2099 if (size > PCI_EXP_LNKCAP2) { 2100 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0); 2101 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0); 2102 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0); 2103 } 2104 } 2105 2106 } else if (type == PCI_EXP_TYPE_LEG_END) { 2107 /* 2108 * Legacy endpoints don't belong on the root complex. Windows 2109 * seems to be happier with devices if we skip the capability. 2110 */ 2111 return true; 2112 } 2113 2114 } else { 2115 /* 2116 * Convert Root Complex Integrated Endpoints to regular endpoints. 2117 * These devices don't support LNK/LNK2 capabilities, so make them up. 2118 */ 2119 if (type == PCI_EXP_TYPE_RC_END) { 2120 vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS, 2121 PCI_EXP_TYPE_ENDPOINT << 4, 2122 PCI_EXP_FLAGS_TYPE); 2123 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 2124 QEMU_PCI_EXP_LNKCAP_MLW(QEMU_PCI_EXP_LNK_X1) | 2125 QEMU_PCI_EXP_LNKCAP_MLS(QEMU_PCI_EXP_LNK_2_5GT), ~0); 2126 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0); 2127 } 2128 2129 vfio_pci_enable_rp_atomics(vdev); 2130 } 2131 2132 /* 2133 * Intel 82599 SR-IOV VFs report an invalid PCIe capability version 0 2134 * (Niantic errate #35) causing Windows to error with a Code 10 for the 2135 * device on Q35. Fixup any such devices to report version 1. If we 2136 * were to remove the capability entirely the guest would lose extended 2137 * config space. 2138 */ 2139 if ((flags & PCI_EXP_FLAGS_VERS) == 0) { 2140 vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS, 2141 1, PCI_EXP_FLAGS_VERS); 2142 } 2143 2144 pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size, 2145 errp); 2146 if (pos < 0) { 2147 return false; 2148 } 2149 2150 vdev->pdev.exp.exp_cap = pos; 2151 2152 return true; 2153 } 2154 2155 static void vfio_check_pcie_flr(VFIOPCIDevice *vdev, uint8_t pos) 2156 { 2157 uint32_t cap = pci_get_long(vdev->pdev.config + pos + PCI_EXP_DEVCAP); 2158 2159 if (cap & PCI_EXP_DEVCAP_FLR) { 2160 trace_vfio_check_pcie_flr(vdev->vbasedev.name); 2161 vdev->has_flr = true; 2162 } 2163 } 2164 2165 static void vfio_check_pm_reset(VFIOPCIDevice *vdev, uint8_t pos) 2166 { 2167 uint16_t csr = pci_get_word(vdev->pdev.config + pos + PCI_PM_CTRL); 2168 2169 if (!(csr & PCI_PM_CTRL_NO_SOFT_RESET)) { 2170 trace_vfio_check_pm_reset(vdev->vbasedev.name); 2171 vdev->has_pm_reset = true; 2172 } 2173 } 2174 2175 static void vfio_check_af_flr(VFIOPCIDevice *vdev, uint8_t pos) 2176 { 2177 uint8_t cap = pci_get_byte(vdev->pdev.config + pos + PCI_AF_CAP); 2178 2179 if ((cap & PCI_AF_CAP_TP) && (cap & PCI_AF_CAP_FLR)) { 2180 trace_vfio_check_af_flr(vdev->vbasedev.name); 2181 vdev->has_flr = true; 2182 } 2183 } 2184 2185 static bool vfio_add_vendor_specific_cap(VFIOPCIDevice *vdev, int pos, 2186 uint8_t size, Error **errp) 2187 { 2188 PCIDevice *pdev = &vdev->pdev; 2189 2190 pos = pci_add_capability(pdev, PCI_CAP_ID_VNDR, pos, size, errp); 2191 if (pos < 0) { 2192 return false; 2193 } 2194 2195 /* 2196 * Exempt config space check for Vendor Specific Information during 2197 * restore/load. 2198 * Config space check is still enforced for 3 byte VSC header. 2199 */ 2200 if (vdev->skip_vsc_check && size > 3) { 2201 memset(pdev->cmask + pos + 3, 0, size - 3); 2202 } 2203 2204 return true; 2205 } 2206 2207 static bool vfio_add_std_cap(VFIOPCIDevice *vdev, uint8_t pos, Error **errp) 2208 { 2209 ERRP_GUARD(); 2210 PCIDevice *pdev = &vdev->pdev; 2211 uint8_t cap_id, next, size; 2212 bool ret; 2213 2214 cap_id = pdev->config[pos]; 2215 next = pdev->config[pos + PCI_CAP_LIST_NEXT]; 2216 2217 /* 2218 * If it becomes important to configure capabilities to their actual 2219 * size, use this as the default when it's something we don't recognize. 2220 * Since QEMU doesn't actually handle many of the config accesses, 2221 * exact size doesn't seem worthwhile. 2222 */ 2223 size = vfio_std_cap_max_size(pdev, pos); 2224 2225 /* 2226 * pci_add_capability always inserts the new capability at the head 2227 * of the chain. Therefore to end up with a chain that matches the 2228 * physical device, we insert from the end by making this recursive. 2229 * This is also why we pre-calculate size above as cached config space 2230 * will be changed as we unwind the stack. 2231 */ 2232 if (next) { 2233 if (!vfio_add_std_cap(vdev, next, errp)) { 2234 return false; 2235 } 2236 } else { 2237 /* Begin the rebuild, use QEMU emulated list bits */ 2238 pdev->config[PCI_CAPABILITY_LIST] = 0; 2239 vdev->emulated_config_bits[PCI_CAPABILITY_LIST] = 0xff; 2240 vdev->emulated_config_bits[PCI_STATUS] |= PCI_STATUS_CAP_LIST; 2241 2242 if (!vfio_add_virt_caps(vdev, errp)) { 2243 return false; 2244 } 2245 } 2246 2247 /* Scale down size, esp in case virt caps were added above */ 2248 size = MIN(size, vfio_std_cap_max_size(pdev, pos)); 2249 2250 /* Use emulated next pointer to allow dropping caps */ 2251 pci_set_byte(vdev->emulated_config_bits + pos + PCI_CAP_LIST_NEXT, 0xff); 2252 2253 switch (cap_id) { 2254 case PCI_CAP_ID_MSI: 2255 ret = vfio_msi_setup(vdev, pos, errp); 2256 break; 2257 case PCI_CAP_ID_EXP: 2258 vfio_check_pcie_flr(vdev, pos); 2259 ret = vfio_setup_pcie_cap(vdev, pos, size, errp); 2260 break; 2261 case PCI_CAP_ID_MSIX: 2262 ret = vfio_msix_setup(vdev, pos, errp); 2263 break; 2264 case PCI_CAP_ID_PM: 2265 vfio_check_pm_reset(vdev, pos); 2266 ret = pci_pm_init(pdev, pos, errp) >= 0; 2267 /* 2268 * PCI-core config space emulation needs write access to the power 2269 * state enabled for tracking BAR mapping relative to PM state. 2270 */ 2271 pci_set_word(pdev->wmask + pos + PCI_PM_CTRL, PCI_PM_CTRL_STATE_MASK); 2272 break; 2273 case PCI_CAP_ID_AF: 2274 vfio_check_af_flr(vdev, pos); 2275 ret = pci_add_capability(pdev, cap_id, pos, size, errp) >= 0; 2276 break; 2277 case PCI_CAP_ID_VNDR: 2278 ret = vfio_add_vendor_specific_cap(vdev, pos, size, errp); 2279 break; 2280 default: 2281 ret = pci_add_capability(pdev, cap_id, pos, size, errp) >= 0; 2282 break; 2283 } 2284 2285 if (!ret) { 2286 error_prepend(errp, 2287 "failed to add PCI capability 0x%x[0x%x]@0x%x: ", 2288 cap_id, size, pos); 2289 } 2290 2291 return ret; 2292 } 2293 2294 static int vfio_setup_rebar_ecap(VFIOPCIDevice *vdev, uint16_t pos) 2295 { 2296 uint32_t ctrl; 2297 int i, nbar; 2298 2299 ctrl = pci_get_long(vdev->pdev.config + pos + PCI_REBAR_CTRL); 2300 nbar = (ctrl & PCI_REBAR_CTRL_NBAR_MASK) >> PCI_REBAR_CTRL_NBAR_SHIFT; 2301 2302 for (i = 0; i < nbar; i++) { 2303 uint32_t cap; 2304 int size; 2305 2306 ctrl = pci_get_long(vdev->pdev.config + pos + PCI_REBAR_CTRL + (i * 8)); 2307 size = (ctrl & PCI_REBAR_CTRL_BAR_SIZE) >> PCI_REBAR_CTRL_BAR_SHIFT; 2308 2309 /* The cap register reports sizes 1MB to 128TB, with 4 reserved bits */ 2310 cap = size <= 27 ? 1U << (size + 4) : 0; 2311 2312 /* 2313 * The PCIe spec (v6.0.1, 7.8.6) requires HW to support at least one 2314 * size in the range 1MB to 512GB. We intend to mask all sizes except 2315 * the one currently enabled in the size field, therefore if it's 2316 * outside the range, hide the whole capability as this virtualization 2317 * trick won't work. If >512GB resizable BARs start to appear, we 2318 * might need an opt-in or reservation scheme in the kernel. 2319 */ 2320 if (!(cap & PCI_REBAR_CAP_SIZES)) { 2321 return -EINVAL; 2322 } 2323 2324 /* Hide all sizes reported in the ctrl reg per above requirement. */ 2325 ctrl &= (PCI_REBAR_CTRL_BAR_SIZE | 2326 PCI_REBAR_CTRL_NBAR_MASK | 2327 PCI_REBAR_CTRL_BAR_IDX); 2328 2329 /* 2330 * The BAR size field is RW, however we've mangled the capability 2331 * register such that we only report a single size, ie. the current 2332 * BAR size. A write of an unsupported value is undefined, therefore 2333 * the register field is essentially RO. 2334 */ 2335 vfio_add_emulated_long(vdev, pos + PCI_REBAR_CAP + (i * 8), cap, ~0); 2336 vfio_add_emulated_long(vdev, pos + PCI_REBAR_CTRL + (i * 8), ctrl, ~0); 2337 } 2338 2339 return 0; 2340 } 2341 2342 static void vfio_add_ext_cap(VFIOPCIDevice *vdev) 2343 { 2344 PCIDevice *pdev = &vdev->pdev; 2345 uint32_t header; 2346 uint16_t cap_id, next, size; 2347 uint8_t cap_ver; 2348 uint8_t *config; 2349 2350 /* Only add extended caps if we have them and the guest can see them */ 2351 if (!pci_is_express(pdev) || !pci_bus_is_express(pci_get_bus(pdev)) || 2352 !pci_get_long(pdev->config + PCI_CONFIG_SPACE_SIZE)) { 2353 return; 2354 } 2355 2356 /* 2357 * pcie_add_capability always inserts the new capability at the tail 2358 * of the chain. Therefore to end up with a chain that matches the 2359 * physical device, we cache the config space to avoid overwriting 2360 * the original config space when we parse the extended capabilities. 2361 */ 2362 config = g_memdup(pdev->config, vdev->config_size); 2363 2364 /* 2365 * Extended capabilities are chained with each pointing to the next, so we 2366 * can drop anything other than the head of the chain simply by modifying 2367 * the previous next pointer. Seed the head of the chain here such that 2368 * we can simply skip any capabilities we want to drop below, regardless 2369 * of their position in the chain. If this stub capability still exists 2370 * after we add the capabilities we want to expose, update the capability 2371 * ID to zero. Note that we cannot seed with the capability header being 2372 * zero as this conflicts with definition of an absent capability chain 2373 * and prevents capabilities beyond the head of the list from being added. 2374 * By replacing the dummy capability ID with zero after walking the device 2375 * chain, we also transparently mark extended capabilities as absent if 2376 * no capabilities were added. Note that the PCIe spec defines an absence 2377 * of extended capabilities to be determined by a value of zero for the 2378 * capability ID, version, AND next pointer. A non-zero next pointer 2379 * should be sufficient to indicate additional capabilities are present, 2380 * which will occur if we call pcie_add_capability() below. The entire 2381 * first dword is emulated to support this. 2382 * 2383 * NB. The kernel side does similar masking, so be prepared that our 2384 * view of the device may also contain a capability ID zero in the head 2385 * of the chain. Skip it for the same reason that we cannot seed the 2386 * chain with a zero capability. 2387 */ 2388 pci_set_long(pdev->config + PCI_CONFIG_SPACE_SIZE, 2389 PCI_EXT_CAP(0xFFFF, 0, 0)); 2390 pci_set_long(pdev->wmask + PCI_CONFIG_SPACE_SIZE, 0); 2391 pci_set_long(vdev->emulated_config_bits + PCI_CONFIG_SPACE_SIZE, ~0); 2392 2393 for (next = PCI_CONFIG_SPACE_SIZE; next; 2394 next = PCI_EXT_CAP_NEXT(pci_get_long(config + next))) { 2395 header = pci_get_long(config + next); 2396 cap_id = PCI_EXT_CAP_ID(header); 2397 cap_ver = PCI_EXT_CAP_VER(header); 2398 2399 /* 2400 * If it becomes important to configure extended capabilities to their 2401 * actual size, use this as the default when it's something we don't 2402 * recognize. Since QEMU doesn't actually handle many of the config 2403 * accesses, exact size doesn't seem worthwhile. 2404 */ 2405 size = vfio_ext_cap_max_size(config, next); 2406 2407 /* Use emulated next pointer to allow dropping extended caps */ 2408 pci_long_test_and_set_mask(vdev->emulated_config_bits + next, 2409 PCI_EXT_CAP_NEXT_MASK); 2410 2411 switch (cap_id) { 2412 case 0: /* kernel masked capability */ 2413 case PCI_EXT_CAP_ID_SRIOV: /* Read-only VF BARs confuse OVMF */ 2414 case PCI_EXT_CAP_ID_ARI: /* XXX Needs next function virtualization */ 2415 trace_vfio_add_ext_cap_dropped(vdev->vbasedev.name, cap_id, next); 2416 break; 2417 case PCI_EXT_CAP_ID_REBAR: 2418 if (!vfio_setup_rebar_ecap(vdev, next)) { 2419 pcie_add_capability(pdev, cap_id, cap_ver, next, size); 2420 } 2421 break; 2422 default: 2423 pcie_add_capability(pdev, cap_id, cap_ver, next, size); 2424 } 2425 2426 } 2427 2428 /* Cleanup chain head ID if necessary */ 2429 if (pci_get_word(pdev->config + PCI_CONFIG_SPACE_SIZE) == 0xFFFF) { 2430 pci_set_word(pdev->config + PCI_CONFIG_SPACE_SIZE, 0); 2431 } 2432 2433 g_free(config); 2434 } 2435 2436 bool vfio_pci_add_capabilities(VFIOPCIDevice *vdev, Error **errp) 2437 { 2438 PCIDevice *pdev = &vdev->pdev; 2439 2440 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) || 2441 !pdev->config[PCI_CAPABILITY_LIST]) { 2442 return true; /* Nothing to add */ 2443 } 2444 2445 if (!vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST], errp)) { 2446 return false; 2447 } 2448 2449 vfio_add_ext_cap(vdev); 2450 return true; 2451 } 2452 2453 void vfio_pci_pre_reset(VFIOPCIDevice *vdev) 2454 { 2455 PCIDevice *pdev = &vdev->pdev; 2456 uint16_t cmd; 2457 2458 vfio_disable_interrupts(vdev); 2459 2460 /* 2461 * Stop any ongoing DMA by disconnecting I/O, MMIO, and bus master. 2462 * Also put INTx Disable in known state. 2463 */ 2464 cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2); 2465 cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER | 2466 PCI_COMMAND_INTX_DISABLE); 2467 vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2); 2468 2469 /* Make sure the device is in D0 */ 2470 if (pdev->pm_cap) { 2471 uint16_t pmcsr; 2472 uint8_t state; 2473 2474 pmcsr = vfio_pci_read_config(pdev, pdev->pm_cap + PCI_PM_CTRL, 2); 2475 state = pmcsr & PCI_PM_CTRL_STATE_MASK; 2476 if (state) { 2477 pmcsr &= ~PCI_PM_CTRL_STATE_MASK; 2478 vfio_pci_write_config(pdev, pdev->pm_cap + PCI_PM_CTRL, pmcsr, 2); 2479 /* vfio handles the necessary delay here */ 2480 pmcsr = vfio_pci_read_config(pdev, pdev->pm_cap + PCI_PM_CTRL, 2); 2481 state = pmcsr & PCI_PM_CTRL_STATE_MASK; 2482 if (state) { 2483 error_report("vfio: Unable to power on device, stuck in D%d", 2484 state); 2485 } 2486 } 2487 } 2488 } 2489 2490 void vfio_pci_post_reset(VFIOPCIDevice *vdev) 2491 { 2492 VFIODevice *vbasedev = &vdev->vbasedev; 2493 Error *err = NULL; 2494 int ret, nr; 2495 2496 if (!vfio_intx_enable(vdev, &err)) { 2497 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name); 2498 } 2499 2500 for (nr = 0; nr < PCI_NUM_REGIONS - 1; ++nr) { 2501 off_t addr = PCI_BASE_ADDRESS_0 + (4 * nr); 2502 uint32_t val = 0; 2503 uint32_t len = sizeof(val); 2504 2505 ret = vfio_pci_config_space_write(vdev, addr, len, &val); 2506 if (ret != len) { 2507 error_report("%s(%s) reset bar %d failed: %s", __func__, 2508 vbasedev->name, nr, strwriteerror(ret)); 2509 } 2510 } 2511 2512 vfio_quirk_reset(vdev); 2513 } 2514 2515 bool vfio_pci_host_match(PCIHostDeviceAddress *addr, const char *name) 2516 { 2517 char tmp[13]; 2518 2519 sprintf(tmp, "%04x:%02x:%02x.%1x", addr->domain, 2520 addr->bus, addr->slot, addr->function); 2521 2522 return (strcmp(tmp, name) == 0); 2523 } 2524 2525 int vfio_pci_get_pci_hot_reset_info(VFIOPCIDevice *vdev, 2526 struct vfio_pci_hot_reset_info **info_p) 2527 { 2528 struct vfio_pci_hot_reset_info *info; 2529 int ret, count; 2530 2531 assert(info_p && !*info_p); 2532 2533 info = g_malloc0(sizeof(*info)); 2534 info->argsz = sizeof(*info); 2535 2536 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info); 2537 if (ret && errno != ENOSPC) { 2538 ret = -errno; 2539 g_free(info); 2540 if (!vdev->has_pm_reset) { 2541 error_report("vfio: Cannot reset device %s, " 2542 "no available reset mechanism.", vdev->vbasedev.name); 2543 } 2544 return ret; 2545 } 2546 2547 count = info->count; 2548 info = g_realloc(info, sizeof(*info) + (count * sizeof(info->devices[0]))); 2549 info->argsz = sizeof(*info) + (count * sizeof(info->devices[0])); 2550 2551 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info); 2552 if (ret) { 2553 ret = -errno; 2554 g_free(info); 2555 error_report("vfio: hot reset info failed: %m"); 2556 return ret; 2557 } 2558 2559 *info_p = info; 2560 return 0; 2561 } 2562 2563 static int vfio_pci_hot_reset(VFIOPCIDevice *vdev, bool single) 2564 { 2565 VFIODevice *vbasedev = &vdev->vbasedev; 2566 const VFIOIOMMUClass *vioc = VFIO_IOMMU_GET_CLASS(vbasedev->bcontainer); 2567 2568 return vioc->pci_hot_reset(vbasedev, single); 2569 } 2570 2571 /* 2572 * We want to differentiate hot reset of multiple in-use devices vs hot reset 2573 * of a single in-use device. VFIO_DEVICE_RESET will already handle the case 2574 * of doing hot resets when there is only a single device per bus. The in-use 2575 * here refers to how many VFIODevices are affected. A hot reset that affects 2576 * multiple devices, but only a single in-use device, means that we can call 2577 * it from our bus ->reset() callback since the extent is effectively a single 2578 * device. This allows us to make use of it in the hotplug path. When there 2579 * are multiple in-use devices, we can only trigger the hot reset during a 2580 * system reset and thus from our reset handler. We separate _one vs _multi 2581 * here so that we don't overlap and do a double reset on the system reset 2582 * path where both our reset handler and ->reset() callback are used. Calling 2583 * _one() will only do a hot reset for the one in-use devices case, calling 2584 * _multi() will do nothing if a _one() would have been sufficient. 2585 */ 2586 static int vfio_pci_hot_reset_one(VFIOPCIDevice *vdev) 2587 { 2588 return vfio_pci_hot_reset(vdev, true); 2589 } 2590 2591 static int vfio_pci_hot_reset_multi(VFIODevice *vbasedev) 2592 { 2593 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev); 2594 return vfio_pci_hot_reset(vdev, false); 2595 } 2596 2597 static void vfio_pci_compute_needs_reset(VFIODevice *vbasedev) 2598 { 2599 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev); 2600 if (!vbasedev->reset_works || (!vdev->has_flr && vdev->has_pm_reset)) { 2601 vbasedev->needs_reset = true; 2602 } 2603 } 2604 2605 static Object *vfio_pci_get_object(VFIODevice *vbasedev) 2606 { 2607 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev); 2608 2609 return OBJECT(vdev); 2610 } 2611 2612 static bool vfio_msix_present(void *opaque, int version_id) 2613 { 2614 PCIDevice *pdev = opaque; 2615 2616 return msix_present(pdev); 2617 } 2618 2619 static bool vfio_display_migration_needed(void *opaque) 2620 { 2621 VFIOPCIDevice *vdev = opaque; 2622 2623 /* 2624 * We need to migrate the VFIODisplay object if ramfb *migration* was 2625 * explicitly requested (in which case we enforced both ramfb=on and 2626 * display=on), or ramfb migration was left at the default "auto" 2627 * setting, and *ramfb* was explicitly requested (in which case we 2628 * enforced display=on). 2629 */ 2630 return vdev->ramfb_migrate == ON_OFF_AUTO_ON || 2631 (vdev->ramfb_migrate == ON_OFF_AUTO_AUTO && vdev->enable_ramfb); 2632 } 2633 2634 static const VMStateDescription vmstate_vfio_display = { 2635 .name = "VFIOPCIDevice/VFIODisplay", 2636 .version_id = 1, 2637 .minimum_version_id = 1, 2638 .needed = vfio_display_migration_needed, 2639 .fields = (const VMStateField[]){ 2640 VMSTATE_STRUCT_POINTER(dpy, VFIOPCIDevice, vfio_display_vmstate, 2641 VFIODisplay), 2642 VMSTATE_END_OF_LIST() 2643 } 2644 }; 2645 2646 static const VMStateDescription vmstate_vfio_pci_config = { 2647 .name = "VFIOPCIDevice", 2648 .version_id = 1, 2649 .minimum_version_id = 1, 2650 .fields = (const VMStateField[]) { 2651 VMSTATE_PCI_DEVICE(pdev, VFIOPCIDevice), 2652 VMSTATE_MSIX_TEST(pdev, VFIOPCIDevice, vfio_msix_present), 2653 VMSTATE_END_OF_LIST() 2654 }, 2655 .subsections = (const VMStateDescription * const []) { 2656 &vmstate_vfio_display, 2657 NULL 2658 } 2659 }; 2660 2661 static int vfio_pci_save_config(VFIODevice *vbasedev, QEMUFile *f, Error **errp) 2662 { 2663 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev); 2664 2665 return vmstate_save_state_with_err(f, &vmstate_vfio_pci_config, vdev, NULL, 2666 errp); 2667 } 2668 2669 static int vfio_pci_load_config(VFIODevice *vbasedev, QEMUFile *f) 2670 { 2671 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev); 2672 PCIDevice *pdev = &vdev->pdev; 2673 pcibus_t old_addr[PCI_NUM_REGIONS - 1]; 2674 int bar, ret; 2675 2676 for (bar = 0; bar < PCI_ROM_SLOT; bar++) { 2677 old_addr[bar] = pdev->io_regions[bar].addr; 2678 } 2679 2680 ret = vmstate_load_state(f, &vmstate_vfio_pci_config, vdev, 1); 2681 if (ret) { 2682 return ret; 2683 } 2684 2685 vfio_pci_write_config(pdev, PCI_COMMAND, 2686 pci_get_word(pdev->config + PCI_COMMAND), 2); 2687 2688 for (bar = 0; bar < PCI_ROM_SLOT; bar++) { 2689 /* 2690 * The address may not be changed in some scenarios 2691 * (e.g. the VF driver isn't loaded in VM). 2692 */ 2693 if (old_addr[bar] != pdev->io_regions[bar].addr && 2694 vdev->bars[bar].region.size > 0 && 2695 vdev->bars[bar].region.size < qemu_real_host_page_size()) { 2696 vfio_sub_page_bar_update_mapping(pdev, bar); 2697 } 2698 } 2699 2700 if (msi_enabled(pdev)) { 2701 vfio_msi_enable(vdev); 2702 } else if (msix_enabled(pdev)) { 2703 vfio_msix_enable(vdev); 2704 } 2705 2706 return ret; 2707 } 2708 2709 static VFIODeviceOps vfio_pci_ops = { 2710 .vfio_compute_needs_reset = vfio_pci_compute_needs_reset, 2711 .vfio_hot_reset_multi = vfio_pci_hot_reset_multi, 2712 .vfio_eoi = vfio_pci_intx_eoi, 2713 .vfio_get_object = vfio_pci_get_object, 2714 .vfio_save_config = vfio_pci_save_config, 2715 .vfio_load_config = vfio_pci_load_config, 2716 }; 2717 2718 bool vfio_populate_vga(VFIOPCIDevice *vdev, Error **errp) 2719 { 2720 VFIODevice *vbasedev = &vdev->vbasedev; 2721 struct vfio_region_info *reg_info = NULL; 2722 int ret; 2723 2724 ret = vfio_device_get_region_info(vbasedev, VFIO_PCI_VGA_REGION_INDEX, ®_info); 2725 if (ret) { 2726 error_setg_errno(errp, -ret, 2727 "failed getting region info for VGA region index %d", 2728 VFIO_PCI_VGA_REGION_INDEX); 2729 return false; 2730 } 2731 2732 if (!(reg_info->flags & VFIO_REGION_INFO_FLAG_READ) || 2733 !(reg_info->flags & VFIO_REGION_INFO_FLAG_WRITE) || 2734 reg_info->size < 0xbffff + 1) { 2735 error_setg(errp, "unexpected VGA info, flags 0x%lx, size 0x%lx", 2736 (unsigned long)reg_info->flags, 2737 (unsigned long)reg_info->size); 2738 return false; 2739 } 2740 2741 vdev->vga = g_new0(VFIOVGA, 1); 2742 2743 vdev->vga->fd_offset = reg_info->offset; 2744 vdev->vga->fd = vdev->vbasedev.fd; 2745 2746 vdev->vga->region[QEMU_PCI_VGA_MEM].offset = QEMU_PCI_VGA_MEM_BASE; 2747 vdev->vga->region[QEMU_PCI_VGA_MEM].nr = QEMU_PCI_VGA_MEM; 2748 QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_MEM].quirks); 2749 2750 memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_MEM].mem, 2751 OBJECT(vdev), &vfio_vga_ops, 2752 &vdev->vga->region[QEMU_PCI_VGA_MEM], 2753 "vfio-vga-mmio@0xa0000", 2754 QEMU_PCI_VGA_MEM_SIZE); 2755 2756 vdev->vga->region[QEMU_PCI_VGA_IO_LO].offset = QEMU_PCI_VGA_IO_LO_BASE; 2757 vdev->vga->region[QEMU_PCI_VGA_IO_LO].nr = QEMU_PCI_VGA_IO_LO; 2758 QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].quirks); 2759 2760 memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem, 2761 OBJECT(vdev), &vfio_vga_ops, 2762 &vdev->vga->region[QEMU_PCI_VGA_IO_LO], 2763 "vfio-vga-io@0x3b0", 2764 QEMU_PCI_VGA_IO_LO_SIZE); 2765 2766 vdev->vga->region[QEMU_PCI_VGA_IO_HI].offset = QEMU_PCI_VGA_IO_HI_BASE; 2767 vdev->vga->region[QEMU_PCI_VGA_IO_HI].nr = QEMU_PCI_VGA_IO_HI; 2768 QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].quirks); 2769 2770 memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem, 2771 OBJECT(vdev), &vfio_vga_ops, 2772 &vdev->vga->region[QEMU_PCI_VGA_IO_HI], 2773 "vfio-vga-io@0x3c0", 2774 QEMU_PCI_VGA_IO_HI_SIZE); 2775 2776 pci_register_vga(&vdev->pdev, &vdev->vga->region[QEMU_PCI_VGA_MEM].mem, 2777 &vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem, 2778 &vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem); 2779 2780 return true; 2781 } 2782 2783 bool vfio_pci_populate_device(VFIOPCIDevice *vdev, Error **errp) 2784 { 2785 VFIODevice *vbasedev = &vdev->vbasedev; 2786 struct vfio_region_info *reg_info = NULL; 2787 struct vfio_irq_info irq_info; 2788 int i, ret = -1; 2789 2790 /* Sanity check device */ 2791 if (!(vbasedev->flags & VFIO_DEVICE_FLAGS_PCI)) { 2792 error_setg(errp, "this isn't a PCI device"); 2793 return false; 2794 } 2795 2796 if (vbasedev->num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) { 2797 error_setg(errp, "unexpected number of io regions %u", 2798 vbasedev->num_regions); 2799 return false; 2800 } 2801 2802 if (vbasedev->num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) { 2803 error_setg(errp, "unexpected number of irqs %u", vbasedev->num_irqs); 2804 return false; 2805 } 2806 2807 for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) { 2808 char *name = g_strdup_printf("%s BAR %d", vbasedev->name, i); 2809 2810 ret = vfio_region_setup(OBJECT(vdev), vbasedev, 2811 &vdev->bars[i].region, i, name); 2812 g_free(name); 2813 2814 if (ret) { 2815 error_setg_errno(errp, -ret, "failed to get region %d info", i); 2816 return false; 2817 } 2818 2819 QLIST_INIT(&vdev->bars[i].quirks); 2820 } 2821 2822 ret = vfio_device_get_region_info(vbasedev, 2823 VFIO_PCI_CONFIG_REGION_INDEX, ®_info); 2824 if (ret) { 2825 error_setg_errno(errp, -ret, "failed to get config info"); 2826 return false; 2827 } 2828 2829 trace_vfio_pci_populate_device_config(vdev->vbasedev.name, 2830 (unsigned long)reg_info->size, 2831 (unsigned long)reg_info->offset, 2832 (unsigned long)reg_info->flags); 2833 2834 vdev->config_size = reg_info->size; 2835 if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) { 2836 vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS; 2837 } 2838 vdev->config_offset = reg_info->offset; 2839 2840 if (vdev->features & VFIO_FEATURE_ENABLE_VGA) { 2841 if (!vfio_populate_vga(vdev, errp)) { 2842 error_append_hint(errp, "device does not support " 2843 "requested feature x-vga\n"); 2844 return false; 2845 } 2846 } 2847 2848 ret = vfio_device_get_irq_info(vbasedev, VFIO_PCI_ERR_IRQ_INDEX, &irq_info); 2849 if (ret) { 2850 /* This can fail for an old kernel or legacy PCI dev */ 2851 trace_vfio_pci_populate_device_get_irq_info_failure(strerror(-ret)); 2852 } else if (irq_info.count == 1) { 2853 vdev->pci_aer = true; 2854 } else { 2855 warn_report(VFIO_MSG_PREFIX 2856 "Could not enable error recovery for the device", 2857 vbasedev->name); 2858 } 2859 2860 return true; 2861 } 2862 2863 void vfio_pci_put_device(VFIOPCIDevice *vdev) 2864 { 2865 vfio_display_finalize(vdev); 2866 vfio_bars_finalize(vdev); 2867 g_free(vdev->emulated_config_bits); 2868 g_free(vdev->rom); 2869 /* 2870 * XXX Leaking igd_opregion is not an oversight, we can't remove the 2871 * fw_cfg entry therefore leaking this allocation seems like the safest 2872 * option. 2873 * 2874 * g_free(vdev->igd_opregion); 2875 */ 2876 2877 vfio_device_detach(&vdev->vbasedev); 2878 2879 g_free(vdev->vbasedev.name); 2880 g_free(vdev->msix); 2881 } 2882 2883 static void vfio_err_notifier_handler(void *opaque) 2884 { 2885 VFIOPCIDevice *vdev = opaque; 2886 2887 if (!event_notifier_test_and_clear(&vdev->err_notifier)) { 2888 return; 2889 } 2890 2891 /* 2892 * TBD. Retrieve the error details and decide what action 2893 * needs to be taken. One of the actions could be to pass 2894 * the error to the guest and have the guest driver recover 2895 * from the error. This requires that PCIe capabilities be 2896 * exposed to the guest. For now, we just terminate the 2897 * guest to contain the error. 2898 */ 2899 2900 error_report("%s(%s) Unrecoverable error detected. Please collect any data possible and then kill the guest", __func__, vdev->vbasedev.name); 2901 2902 vm_stop(RUN_STATE_INTERNAL_ERROR); 2903 } 2904 2905 /* 2906 * Registers error notifier for devices supporting error recovery. 2907 * If we encounter a failure in this function, we report an error 2908 * and continue after disabling error recovery support for the 2909 * device. 2910 */ 2911 void vfio_pci_register_err_notifier(VFIOPCIDevice *vdev) 2912 { 2913 Error *err = NULL; 2914 int32_t fd; 2915 2916 if (!vdev->pci_aer) { 2917 return; 2918 } 2919 2920 if (event_notifier_init(&vdev->err_notifier, 0)) { 2921 error_report("vfio: Unable to init event notifier for error detection"); 2922 vdev->pci_aer = false; 2923 return; 2924 } 2925 2926 fd = event_notifier_get_fd(&vdev->err_notifier); 2927 qemu_set_fd_handler(fd, vfio_err_notifier_handler, NULL, vdev); 2928 2929 if (!vfio_device_irq_set_signaling(&vdev->vbasedev, VFIO_PCI_ERR_IRQ_INDEX, 0, 2930 VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) { 2931 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name); 2932 qemu_set_fd_handler(fd, NULL, NULL, vdev); 2933 event_notifier_cleanup(&vdev->err_notifier); 2934 vdev->pci_aer = false; 2935 } 2936 } 2937 2938 static void vfio_unregister_err_notifier(VFIOPCIDevice *vdev) 2939 { 2940 Error *err = NULL; 2941 2942 if (!vdev->pci_aer) { 2943 return; 2944 } 2945 2946 if (!vfio_device_irq_set_signaling(&vdev->vbasedev, VFIO_PCI_ERR_IRQ_INDEX, 0, 2947 VFIO_IRQ_SET_ACTION_TRIGGER, -1, &err)) { 2948 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name); 2949 } 2950 qemu_set_fd_handler(event_notifier_get_fd(&vdev->err_notifier), 2951 NULL, NULL, vdev); 2952 event_notifier_cleanup(&vdev->err_notifier); 2953 } 2954 2955 static void vfio_req_notifier_handler(void *opaque) 2956 { 2957 VFIOPCIDevice *vdev = opaque; 2958 Error *err = NULL; 2959 2960 if (!event_notifier_test_and_clear(&vdev->req_notifier)) { 2961 return; 2962 } 2963 2964 qdev_unplug(DEVICE(vdev), &err); 2965 if (err) { 2966 warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name); 2967 } 2968 } 2969 2970 void vfio_pci_register_req_notifier(VFIOPCIDevice *vdev) 2971 { 2972 struct vfio_irq_info irq_info; 2973 Error *err = NULL; 2974 int32_t fd; 2975 int ret; 2976 2977 if (!(vdev->features & VFIO_FEATURE_ENABLE_REQ)) { 2978 return; 2979 } 2980 2981 ret = vfio_device_get_irq_info(&vdev->vbasedev, VFIO_PCI_REQ_IRQ_INDEX, 2982 &irq_info); 2983 if (ret < 0 || irq_info.count < 1) { 2984 return; 2985 } 2986 2987 if (event_notifier_init(&vdev->req_notifier, 0)) { 2988 error_report("vfio: Unable to init event notifier for device request"); 2989 return; 2990 } 2991 2992 fd = event_notifier_get_fd(&vdev->req_notifier); 2993 qemu_set_fd_handler(fd, vfio_req_notifier_handler, NULL, vdev); 2994 2995 if (!vfio_device_irq_set_signaling(&vdev->vbasedev, VFIO_PCI_REQ_IRQ_INDEX, 0, 2996 VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) { 2997 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name); 2998 qemu_set_fd_handler(fd, NULL, NULL, vdev); 2999 event_notifier_cleanup(&vdev->req_notifier); 3000 } else { 3001 vdev->req_enabled = true; 3002 } 3003 } 3004 3005 static void vfio_unregister_req_notifier(VFIOPCIDevice *vdev) 3006 { 3007 Error *err = NULL; 3008 3009 if (!vdev->req_enabled) { 3010 return; 3011 } 3012 3013 if (!vfio_device_irq_set_signaling(&vdev->vbasedev, VFIO_PCI_REQ_IRQ_INDEX, 0, 3014 VFIO_IRQ_SET_ACTION_TRIGGER, -1, &err)) { 3015 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name); 3016 } 3017 qemu_set_fd_handler(event_notifier_get_fd(&vdev->req_notifier), 3018 NULL, NULL, vdev); 3019 event_notifier_cleanup(&vdev->req_notifier); 3020 3021 vdev->req_enabled = false; 3022 } 3023 3024 bool vfio_pci_config_setup(VFIOPCIDevice *vdev, Error **errp) 3025 { 3026 PCIDevice *pdev = &vdev->pdev; 3027 VFIODevice *vbasedev = &vdev->vbasedev; 3028 uint32_t config_space_size; 3029 int ret; 3030 3031 config_space_size = MIN(pci_config_size(&vdev->pdev), vdev->config_size); 3032 3033 /* Get a copy of config space */ 3034 ret = vfio_pci_config_space_read(vdev, 0, config_space_size, 3035 vdev->pdev.config); 3036 if (ret < (int)config_space_size) { 3037 ret = ret < 0 ? -ret : EFAULT; 3038 error_setg_errno(errp, ret, "failed to read device config space"); 3039 return false; 3040 } 3041 3042 /* vfio emulates a lot for us, but some bits need extra love */ 3043 vdev->emulated_config_bits = g_malloc0(vdev->config_size); 3044 3045 /* QEMU can choose to expose the ROM or not */ 3046 memset(vdev->emulated_config_bits + PCI_ROM_ADDRESS, 0xff, 4); 3047 /* QEMU can also add or extend BARs */ 3048 memset(vdev->emulated_config_bits + PCI_BASE_ADDRESS_0, 0xff, 6 * 4); 3049 3050 /* 3051 * The PCI spec reserves vendor ID 0xffff as an invalid value. The 3052 * device ID is managed by the vendor and need only be a 16-bit value. 3053 * Allow any 16-bit value for subsystem so they can be hidden or changed. 3054 */ 3055 if (vdev->vendor_id != PCI_ANY_ID) { 3056 if (vdev->vendor_id >= 0xffff) { 3057 error_setg(errp, "invalid PCI vendor ID provided"); 3058 return false; 3059 } 3060 vfio_add_emulated_word(vdev, PCI_VENDOR_ID, vdev->vendor_id, ~0); 3061 trace_vfio_pci_emulated_vendor_id(vbasedev->name, vdev->vendor_id); 3062 } else { 3063 vdev->vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID); 3064 } 3065 3066 if (vdev->device_id != PCI_ANY_ID) { 3067 if (vdev->device_id > 0xffff) { 3068 error_setg(errp, "invalid PCI device ID provided"); 3069 return false; 3070 } 3071 vfio_add_emulated_word(vdev, PCI_DEVICE_ID, vdev->device_id, ~0); 3072 trace_vfio_pci_emulated_device_id(vbasedev->name, vdev->device_id); 3073 } else { 3074 vdev->device_id = pci_get_word(pdev->config + PCI_DEVICE_ID); 3075 } 3076 3077 if (vdev->sub_vendor_id != PCI_ANY_ID) { 3078 if (vdev->sub_vendor_id > 0xffff) { 3079 error_setg(errp, "invalid PCI subsystem vendor ID provided"); 3080 return false; 3081 } 3082 vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_VENDOR_ID, 3083 vdev->sub_vendor_id, ~0); 3084 trace_vfio_pci_emulated_sub_vendor_id(vbasedev->name, 3085 vdev->sub_vendor_id); 3086 } 3087 3088 if (vdev->sub_device_id != PCI_ANY_ID) { 3089 if (vdev->sub_device_id > 0xffff) { 3090 error_setg(errp, "invalid PCI subsystem device ID provided"); 3091 return false; 3092 } 3093 vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_ID, vdev->sub_device_id, ~0); 3094 trace_vfio_pci_emulated_sub_device_id(vbasedev->name, 3095 vdev->sub_device_id); 3096 } 3097 3098 /* QEMU can change multi-function devices to single function, or reverse */ 3099 vdev->emulated_config_bits[PCI_HEADER_TYPE] = 3100 PCI_HEADER_TYPE_MULTI_FUNCTION; 3101 3102 /* Restore or clear multifunction, this is always controlled by QEMU */ 3103 if (vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) { 3104 vdev->pdev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION; 3105 } else { 3106 vdev->pdev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION; 3107 } 3108 3109 /* 3110 * Clear host resource mapping info. If we choose not to register a 3111 * BAR, such as might be the case with the option ROM, we can get 3112 * confusing, unwritable, residual addresses from the host here. 3113 */ 3114 memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24); 3115 memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4); 3116 3117 vfio_pci_size_rom(vdev); 3118 3119 vfio_bars_prepare(vdev); 3120 3121 if (!vfio_msix_early_setup(vdev, errp)) { 3122 return false; 3123 } 3124 3125 vfio_bars_register(vdev); 3126 3127 return true; 3128 } 3129 3130 bool vfio_pci_interrupt_setup(VFIOPCIDevice *vdev, Error **errp) 3131 { 3132 PCIDevice *pdev = &vdev->pdev; 3133 3134 /* QEMU emulates all of MSI & MSIX */ 3135 if (pdev->cap_present & QEMU_PCI_CAP_MSIX) { 3136 memset(vdev->emulated_config_bits + pdev->msix_cap, 0xff, 3137 MSIX_CAP_LENGTH); 3138 } 3139 3140 if (pdev->cap_present & QEMU_PCI_CAP_MSI) { 3141 memset(vdev->emulated_config_bits + pdev->msi_cap, 0xff, 3142 vdev->msi_cap_size); 3143 } 3144 3145 if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) { 3146 vdev->intx.mmap_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, 3147 vfio_intx_mmap_enable, vdev); 3148 pci_device_set_intx_routing_notifier(&vdev->pdev, 3149 vfio_intx_routing_notifier); 3150 vdev->irqchip_change_notifier.notify = vfio_irqchip_change; 3151 kvm_irqchip_add_change_notifier(&vdev->irqchip_change_notifier); 3152 if (!vfio_intx_enable(vdev, errp)) { 3153 timer_free(vdev->intx.mmap_timer); 3154 pci_device_set_intx_routing_notifier(&vdev->pdev, NULL); 3155 kvm_irqchip_remove_change_notifier(&vdev->irqchip_change_notifier); 3156 return false; 3157 } 3158 } 3159 return true; 3160 } 3161 3162 static void vfio_pci_realize(PCIDevice *pdev, Error **errp) 3163 { 3164 ERRP_GUARD(); 3165 VFIOPCIDevice *vdev = VFIO_PCI_BASE(pdev); 3166 VFIODevice *vbasedev = &vdev->vbasedev; 3167 int i; 3168 char uuid[UUID_STR_LEN]; 3169 g_autofree char *name = NULL; 3170 3171 if (vbasedev->fd < 0 && !vbasedev->sysfsdev) { 3172 if (!(~vdev->host.domain || ~vdev->host.bus || 3173 ~vdev->host.slot || ~vdev->host.function)) { 3174 error_setg(errp, "No provided host device"); 3175 error_append_hint(errp, "Use -device vfio-pci,host=DDDD:BB:DD.F " 3176 #ifdef CONFIG_IOMMUFD 3177 "or -device vfio-pci,fd=DEVICE_FD " 3178 #endif 3179 "or -device vfio-pci,sysfsdev=PATH_TO_DEVICE\n"); 3180 return; 3181 } 3182 vbasedev->sysfsdev = 3183 g_strdup_printf("/sys/bus/pci/devices/%04x:%02x:%02x.%01x", 3184 vdev->host.domain, vdev->host.bus, 3185 vdev->host.slot, vdev->host.function); 3186 } 3187 3188 if (!vfio_device_get_name(vbasedev, errp)) { 3189 return; 3190 } 3191 3192 /* 3193 * Mediated devices *might* operate compatibly with discarding of RAM, but 3194 * we cannot know for certain, it depends on whether the mdev vendor driver 3195 * stays in sync with the active working set of the guest driver. Prevent 3196 * the x-balloon-allowed option unless this is minimally an mdev device. 3197 */ 3198 vbasedev->mdev = vfio_device_is_mdev(vbasedev); 3199 3200 trace_vfio_mdev(vbasedev->name, vbasedev->mdev); 3201 3202 if (vbasedev->ram_block_discard_allowed && !vbasedev->mdev) { 3203 error_setg(errp, "x-balloon-allowed only potentially compatible " 3204 "with mdev devices"); 3205 goto error; 3206 } 3207 3208 if (!qemu_uuid_is_null(&vdev->vf_token)) { 3209 qemu_uuid_unparse(&vdev->vf_token, uuid); 3210 name = g_strdup_printf("%s vf_token=%s", vbasedev->name, uuid); 3211 } else { 3212 name = g_strdup(vbasedev->name); 3213 } 3214 3215 if (!vfio_device_attach(name, vbasedev, 3216 pci_device_iommu_address_space(pdev), errp)) { 3217 goto error; 3218 } 3219 3220 if (!vfio_pci_populate_device(vdev, errp)) { 3221 goto error; 3222 } 3223 3224 if (!vfio_pci_config_setup(vdev, errp)) { 3225 goto error; 3226 } 3227 3228 if (!vbasedev->mdev && 3229 !pci_device_set_iommu_device(pdev, vbasedev->hiod, errp)) { 3230 error_prepend(errp, "Failed to set vIOMMU: "); 3231 goto out_teardown; 3232 } 3233 3234 if (!vfio_pci_add_capabilities(vdev, errp)) { 3235 goto out_unset_idev; 3236 } 3237 3238 if (!vfio_config_quirk_setup(vdev, errp)) { 3239 goto out_unset_idev; 3240 } 3241 3242 if (vdev->vga) { 3243 vfio_vga_quirk_setup(vdev); 3244 } 3245 3246 for (i = 0; i < PCI_ROM_SLOT; i++) { 3247 vfio_bar_quirk_setup(vdev, i); 3248 } 3249 3250 if (!vfio_pci_interrupt_setup(vdev, errp)) { 3251 goto out_unset_idev; 3252 } 3253 3254 if (vdev->display != ON_OFF_AUTO_OFF) { 3255 if (!vfio_display_probe(vdev, errp)) { 3256 goto out_deregister; 3257 } 3258 } 3259 if (vdev->enable_ramfb && vdev->dpy == NULL) { 3260 error_setg(errp, "ramfb=on requires display=on"); 3261 goto out_deregister; 3262 } 3263 if (vdev->display_xres || vdev->display_yres) { 3264 if (vdev->dpy == NULL) { 3265 error_setg(errp, "xres and yres properties require display=on"); 3266 goto out_deregister; 3267 } 3268 if (vdev->dpy->edid_regs == NULL) { 3269 error_setg(errp, "xres and yres properties need edid support"); 3270 goto out_deregister; 3271 } 3272 } 3273 3274 if (vdev->ramfb_migrate == ON_OFF_AUTO_ON && !vdev->enable_ramfb) { 3275 warn_report("x-ramfb-migrate=on but ramfb=off. " 3276 "Forcing x-ramfb-migrate to off."); 3277 vdev->ramfb_migrate = ON_OFF_AUTO_OFF; 3278 } 3279 if (vbasedev->enable_migration == ON_OFF_AUTO_OFF) { 3280 if (vdev->ramfb_migrate == ON_OFF_AUTO_AUTO) { 3281 vdev->ramfb_migrate = ON_OFF_AUTO_OFF; 3282 } else if (vdev->ramfb_migrate == ON_OFF_AUTO_ON) { 3283 error_setg(errp, "x-ramfb-migrate requires enable-migration"); 3284 goto out_deregister; 3285 } 3286 } 3287 3288 if (!pdev->failover_pair_id) { 3289 if (!vfio_migration_realize(vbasedev, errp)) { 3290 goto out_deregister; 3291 } 3292 } 3293 3294 vfio_pci_register_err_notifier(vdev); 3295 vfio_pci_register_req_notifier(vdev); 3296 vfio_setup_resetfn_quirk(vdev); 3297 3298 return; 3299 3300 out_deregister: 3301 if (vdev->interrupt == VFIO_INT_INTx) { 3302 vfio_intx_disable(vdev); 3303 } 3304 pci_device_set_intx_routing_notifier(&vdev->pdev, NULL); 3305 if (vdev->irqchip_change_notifier.notify) { 3306 kvm_irqchip_remove_change_notifier(&vdev->irqchip_change_notifier); 3307 } 3308 if (vdev->intx.mmap_timer) { 3309 timer_free(vdev->intx.mmap_timer); 3310 } 3311 out_unset_idev: 3312 if (!vbasedev->mdev) { 3313 pci_device_unset_iommu_device(pdev); 3314 } 3315 out_teardown: 3316 vfio_pci_teardown_msi(vdev); 3317 vfio_pci_bars_exit(vdev); 3318 error: 3319 error_prepend(errp, VFIO_MSG_PREFIX, vbasedev->name); 3320 } 3321 3322 static void vfio_instance_finalize(Object *obj) 3323 { 3324 VFIOPCIDevice *vdev = VFIO_PCI_BASE(obj); 3325 3326 vfio_pci_put_device(vdev); 3327 } 3328 3329 static void vfio_exitfn(PCIDevice *pdev) 3330 { 3331 VFIOPCIDevice *vdev = VFIO_PCI_BASE(pdev); 3332 VFIODevice *vbasedev = &vdev->vbasedev; 3333 3334 vfio_unregister_req_notifier(vdev); 3335 vfio_unregister_err_notifier(vdev); 3336 pci_device_set_intx_routing_notifier(&vdev->pdev, NULL); 3337 if (vdev->irqchip_change_notifier.notify) { 3338 kvm_irqchip_remove_change_notifier(&vdev->irqchip_change_notifier); 3339 } 3340 vfio_disable_interrupts(vdev); 3341 if (vdev->intx.mmap_timer) { 3342 timer_free(vdev->intx.mmap_timer); 3343 } 3344 vfio_pci_teardown_msi(vdev); 3345 vfio_pci_disable_rp_atomics(vdev); 3346 vfio_pci_bars_exit(vdev); 3347 vfio_migration_exit(vbasedev); 3348 if (!vbasedev->mdev) { 3349 pci_device_unset_iommu_device(pdev); 3350 } 3351 } 3352 3353 static void vfio_pci_reset(DeviceState *dev) 3354 { 3355 VFIOPCIDevice *vdev = VFIO_PCI_BASE(dev); 3356 3357 trace_vfio_pci_reset(vdev->vbasedev.name); 3358 3359 vfio_pci_pre_reset(vdev); 3360 3361 if (vdev->display != ON_OFF_AUTO_OFF) { 3362 vfio_display_reset(vdev); 3363 } 3364 3365 if (vdev->resetfn && !vdev->resetfn(vdev)) { 3366 goto post_reset; 3367 } 3368 3369 if (vdev->vbasedev.reset_works && 3370 (vdev->has_flr || !vdev->has_pm_reset) && 3371 !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) { 3372 trace_vfio_pci_reset_flr(vdev->vbasedev.name); 3373 goto post_reset; 3374 } 3375 3376 /* See if we can do our own bus reset */ 3377 if (!vfio_pci_hot_reset_one(vdev)) { 3378 goto post_reset; 3379 } 3380 3381 /* If nothing else works and the device supports PM reset, use it */ 3382 if (vdev->vbasedev.reset_works && vdev->has_pm_reset && 3383 !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) { 3384 trace_vfio_pci_reset_pm(vdev->vbasedev.name); 3385 goto post_reset; 3386 } 3387 3388 post_reset: 3389 vfio_pci_post_reset(vdev); 3390 } 3391 3392 static void vfio_instance_init(Object *obj) 3393 { 3394 PCIDevice *pci_dev = PCI_DEVICE(obj); 3395 VFIOPCIDevice *vdev = VFIO_PCI_BASE(obj); 3396 VFIODevice *vbasedev = &vdev->vbasedev; 3397 3398 device_add_bootindex_property(obj, &vdev->bootindex, 3399 "bootindex", NULL, 3400 &pci_dev->qdev); 3401 vdev->host.domain = ~0U; 3402 vdev->host.bus = ~0U; 3403 vdev->host.slot = ~0U; 3404 vdev->host.function = ~0U; 3405 3406 vfio_device_init(vbasedev, VFIO_DEVICE_TYPE_PCI, &vfio_pci_ops, 3407 DEVICE(vdev), false); 3408 3409 vdev->nv_gpudirect_clique = 0xFF; 3410 3411 /* QEMU_PCI_CAP_EXPRESS initialization does not depend on QEMU command 3412 * line, therefore, no need to wait to realize like other devices */ 3413 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS; 3414 3415 /* 3416 * A device that is resuming for cpr is already configured, so do not 3417 * reset it during qemu_system_reset prior to cpr load, else interrupts 3418 * may be lost. 3419 */ 3420 pci_dev->cap_present |= QEMU_PCI_SKIP_RESET_ON_CPR; 3421 } 3422 3423 static void vfio_pci_base_dev_class_init(ObjectClass *klass, const void *data) 3424 { 3425 DeviceClass *dc = DEVICE_CLASS(klass); 3426 PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass); 3427 3428 dc->desc = "VFIO PCI base device"; 3429 set_bit(DEVICE_CATEGORY_MISC, dc->categories); 3430 pdc->exit = vfio_exitfn; 3431 pdc->config_read = vfio_pci_read_config; 3432 pdc->config_write = vfio_pci_write_config; 3433 } 3434 3435 static const TypeInfo vfio_pci_base_dev_info = { 3436 .name = TYPE_VFIO_PCI_BASE, 3437 .parent = TYPE_PCI_DEVICE, 3438 .instance_size = sizeof(VFIOPCIDevice), 3439 .abstract = true, 3440 .class_init = vfio_pci_base_dev_class_init, 3441 .interfaces = (const InterfaceInfo[]) { 3442 { INTERFACE_PCIE_DEVICE }, 3443 { INTERFACE_CONVENTIONAL_PCI_DEVICE }, 3444 { } 3445 }, 3446 }; 3447 3448 static PropertyInfo vfio_pci_migration_multifd_transfer_prop; 3449 3450 static const Property vfio_pci_dev_properties[] = { 3451 DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIOPCIDevice, host), 3452 DEFINE_PROP_UUID_NODEFAULT("vf-token", VFIOPCIDevice, vf_token), 3453 DEFINE_PROP_STRING("sysfsdev", VFIOPCIDevice, vbasedev.sysfsdev), 3454 DEFINE_PROP_ON_OFF_AUTO("x-pre-copy-dirty-page-tracking", VFIOPCIDevice, 3455 vbasedev.pre_copy_dirty_page_tracking, 3456 ON_OFF_AUTO_ON), 3457 DEFINE_PROP_ON_OFF_AUTO("x-device-dirty-page-tracking", VFIOPCIDevice, 3458 vbasedev.device_dirty_page_tracking, 3459 ON_OFF_AUTO_ON), 3460 DEFINE_PROP_ON_OFF_AUTO("display", VFIOPCIDevice, 3461 display, ON_OFF_AUTO_OFF), 3462 DEFINE_PROP_UINT32("xres", VFIOPCIDevice, display_xres, 0), 3463 DEFINE_PROP_UINT32("yres", VFIOPCIDevice, display_yres, 0), 3464 DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIOPCIDevice, 3465 intx.mmap_timeout, 1100), 3466 DEFINE_PROP_BIT("x-vga", VFIOPCIDevice, features, 3467 VFIO_FEATURE_ENABLE_VGA_BIT, false), 3468 DEFINE_PROP_BIT("x-req", VFIOPCIDevice, features, 3469 VFIO_FEATURE_ENABLE_REQ_BIT, true), 3470 DEFINE_PROP_BIT("x-igd-opregion", VFIOPCIDevice, features, 3471 VFIO_FEATURE_ENABLE_IGD_OPREGION_BIT, true), 3472 DEFINE_PROP_BIT("x-igd-lpc", VFIOPCIDevice, features, 3473 VFIO_FEATURE_ENABLE_IGD_LPC_BIT, false), 3474 DEFINE_PROP_ON_OFF_AUTO("x-igd-legacy-mode", VFIOPCIDevice, 3475 igd_legacy_mode, ON_OFF_AUTO_AUTO), 3476 DEFINE_PROP_ON_OFF_AUTO("enable-migration", VFIOPCIDevice, 3477 vbasedev.enable_migration, ON_OFF_AUTO_AUTO), 3478 DEFINE_PROP("x-migration-multifd-transfer", VFIOPCIDevice, 3479 vbasedev.migration_multifd_transfer, 3480 vfio_pci_migration_multifd_transfer_prop, OnOffAuto, 3481 .set_default = true, .defval.i = ON_OFF_AUTO_AUTO), 3482 DEFINE_PROP_BOOL("migration-events", VFIOPCIDevice, 3483 vbasedev.migration_events, false), 3484 DEFINE_PROP_BOOL("x-no-mmap", VFIOPCIDevice, vbasedev.no_mmap, false), 3485 DEFINE_PROP_BOOL("x-balloon-allowed", VFIOPCIDevice, 3486 vbasedev.ram_block_discard_allowed, false), 3487 DEFINE_PROP_BOOL("x-no-kvm-intx", VFIOPCIDevice, no_kvm_intx, false), 3488 DEFINE_PROP_BOOL("x-no-kvm-msi", VFIOPCIDevice, no_kvm_msi, false), 3489 DEFINE_PROP_BOOL("x-no-kvm-msix", VFIOPCIDevice, no_kvm_msix, false), 3490 DEFINE_PROP_BOOL("x-no-geforce-quirks", VFIOPCIDevice, 3491 no_geforce_quirks, false), 3492 DEFINE_PROP_BOOL("x-no-kvm-ioeventfd", VFIOPCIDevice, no_kvm_ioeventfd, 3493 false), 3494 DEFINE_PROP_BOOL("x-no-vfio-ioeventfd", VFIOPCIDevice, no_vfio_ioeventfd, 3495 false), 3496 DEFINE_PROP_UINT32("x-pci-vendor-id", VFIOPCIDevice, vendor_id, PCI_ANY_ID), 3497 DEFINE_PROP_UINT32("x-pci-device-id", VFIOPCIDevice, device_id, PCI_ANY_ID), 3498 DEFINE_PROP_UINT32("x-pci-sub-vendor-id", VFIOPCIDevice, 3499 sub_vendor_id, PCI_ANY_ID), 3500 DEFINE_PROP_UINT32("x-pci-sub-device-id", VFIOPCIDevice, 3501 sub_device_id, PCI_ANY_ID), 3502 DEFINE_PROP_UINT32("x-igd-gms", VFIOPCIDevice, igd_gms, 0), 3503 DEFINE_PROP_UNSIGNED_NODEFAULT("x-nv-gpudirect-clique", VFIOPCIDevice, 3504 nv_gpudirect_clique, 3505 qdev_prop_nv_gpudirect_clique, uint8_t), 3506 DEFINE_PROP_OFF_AUTO_PCIBAR("x-msix-relocation", VFIOPCIDevice, msix_relo, 3507 OFF_AUTO_PCIBAR_OFF), 3508 #ifdef CONFIG_IOMMUFD 3509 DEFINE_PROP_LINK("iommufd", VFIOPCIDevice, vbasedev.iommufd, 3510 TYPE_IOMMUFD_BACKEND, IOMMUFDBackend *), 3511 #endif 3512 DEFINE_PROP_BOOL("skip-vsc-check", VFIOPCIDevice, skip_vsc_check, true), 3513 }; 3514 3515 #ifdef CONFIG_IOMMUFD 3516 static void vfio_pci_set_fd(Object *obj, const char *str, Error **errp) 3517 { 3518 VFIOPCIDevice *vdev = VFIO_PCI_BASE(obj); 3519 vfio_device_set_fd(&vdev->vbasedev, str, errp); 3520 } 3521 #endif 3522 3523 static void vfio_pci_dev_class_init(ObjectClass *klass, const void *data) 3524 { 3525 DeviceClass *dc = DEVICE_CLASS(klass); 3526 PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass); 3527 3528 device_class_set_legacy_reset(dc, vfio_pci_reset); 3529 device_class_set_props(dc, vfio_pci_dev_properties); 3530 #ifdef CONFIG_IOMMUFD 3531 object_class_property_add_str(klass, "fd", NULL, vfio_pci_set_fd); 3532 #endif 3533 dc->desc = "VFIO-based PCI device assignment"; 3534 pdc->realize = vfio_pci_realize; 3535 3536 object_class_property_set_description(klass, /* 1.3 */ 3537 "host", 3538 "Host PCI address [domain:]<bus:slot.function> of assigned device"); 3539 object_class_property_set_description(klass, /* 1.3 */ 3540 "x-intx-mmap-timeout-ms", 3541 "When EOI is not provided by KVM/QEMU, wait time " 3542 "(milliseconds) to re-enable device direct access " 3543 "after INTx (DEBUG)"); 3544 object_class_property_set_description(klass, /* 1.5 */ 3545 "x-vga", 3546 "Expose VGA address spaces for device"); 3547 object_class_property_set_description(klass, /* 2.3 */ 3548 "x-req", 3549 "Disable device request notification support (DEBUG)"); 3550 object_class_property_set_description(klass, /* 2.4 and 2.5 */ 3551 "x-no-mmap", 3552 "Disable MMAP for device. Allows to trace MMIO " 3553 "accesses (DEBUG)"); 3554 object_class_property_set_description(klass, /* 2.5 */ 3555 "x-no-kvm-intx", 3556 "Disable direct VFIO->KVM INTx injection. Allows to " 3557 "trace INTx interrupts (DEBUG)"); 3558 object_class_property_set_description(klass, /* 2.5 */ 3559 "x-no-kvm-msi", 3560 "Disable direct VFIO->KVM MSI injection. Allows to " 3561 "trace MSI interrupts (DEBUG)"); 3562 object_class_property_set_description(klass, /* 2.5 */ 3563 "x-no-kvm-msix", 3564 "Disable direct VFIO->KVM MSIx injection. Allows to " 3565 "trace MSIx interrupts (DEBUG)"); 3566 object_class_property_set_description(klass, /* 2.5 */ 3567 "x-pci-vendor-id", 3568 "Override PCI Vendor ID with provided value (DEBUG)"); 3569 object_class_property_set_description(klass, /* 2.5 */ 3570 "x-pci-device-id", 3571 "Override PCI device ID with provided value (DEBUG)"); 3572 object_class_property_set_description(klass, /* 2.5 */ 3573 "x-pci-sub-vendor-id", 3574 "Override PCI Subsystem Vendor ID with provided value " 3575 "(DEBUG)"); 3576 object_class_property_set_description(klass, /* 2.5 */ 3577 "x-pci-sub-device-id", 3578 "Override PCI Subsystem Device ID with provided value " 3579 "(DEBUG)"); 3580 object_class_property_set_description(klass, /* 2.6 */ 3581 "sysfsdev", 3582 "Host sysfs path of assigned device"); 3583 object_class_property_set_description(klass, /* 2.7 */ 3584 "x-igd-opregion", 3585 "Expose host IGD OpRegion to guest"); 3586 object_class_property_set_description(klass, /* 2.7 (See c4c45e943e51) */ 3587 "x-igd-gms", 3588 "Override IGD data stolen memory size (32MiB units)"); 3589 object_class_property_set_description(klass, /* 2.11 */ 3590 "x-nv-gpudirect-clique", 3591 "Add NVIDIA GPUDirect capability indicating P2P DMA " 3592 "clique for device [0-15]"); 3593 object_class_property_set_description(klass, /* 2.12 */ 3594 "x-no-geforce-quirks", 3595 "Disable GeForce quirks (for NVIDIA Quadro/GRID/Tesla). " 3596 "Improves performance"); 3597 object_class_property_set_description(klass, /* 2.12 */ 3598 "display", 3599 "Enable display support for device, ex. vGPU"); 3600 object_class_property_set_description(klass, /* 2.12 */ 3601 "x-msix-relocation", 3602 "Specify MSI-X MMIO relocation to the end of specified " 3603 "existing BAR or new BAR to avoid virtualization overhead " 3604 "due to adjacent device registers"); 3605 object_class_property_set_description(klass, /* 3.0 */ 3606 "x-no-kvm-ioeventfd", 3607 "Disable registration of ioeventfds with KVM (DEBUG)"); 3608 object_class_property_set_description(klass, /* 3.0 */ 3609 "x-no-vfio-ioeventfd", 3610 "Disable linking of KVM ioeventfds to VFIO ioeventfds " 3611 "(DEBUG)"); 3612 object_class_property_set_description(klass, /* 3.1 */ 3613 "x-balloon-allowed", 3614 "Override allowing ballooning with device (DEBUG, DANGER)"); 3615 object_class_property_set_description(klass, /* 3.2 */ 3616 "xres", 3617 "Set X display resolution the vGPU should use"); 3618 object_class_property_set_description(klass, /* 3.2 */ 3619 "yres", 3620 "Set Y display resolution the vGPU should use"); 3621 object_class_property_set_description(klass, /* 5.2 */ 3622 "x-pre-copy-dirty-page-tracking", 3623 "Disable dirty pages tracking during iterative phase " 3624 "(DEBUG)"); 3625 object_class_property_set_description(klass, /* 5.2, 8.0 non-experimetal */ 3626 "enable-migration", 3627 "Enale device migration. Also requires a host VFIO PCI " 3628 "variant or mdev driver with migration support enabled"); 3629 object_class_property_set_description(klass, /* 8.1 */ 3630 "vf-token", 3631 "Specify UUID VF token. Required for VF when PF is owned " 3632 "by another VFIO driver"); 3633 #ifdef CONFIG_IOMMUFD 3634 object_class_property_set_description(klass, /* 9.0 */ 3635 "iommufd", 3636 "Set host IOMMUFD backend device"); 3637 #endif 3638 object_class_property_set_description(klass, /* 9.1 */ 3639 "x-device-dirty-page-tracking", 3640 "Disable device dirty page tracking and use " 3641 "container-based dirty page tracking"); 3642 object_class_property_set_description(klass, /* 9.1 */ 3643 "migration-events", 3644 "Emit VFIO migration QAPI event when a VFIO device " 3645 "changes its migration state. For management applications"); 3646 object_class_property_set_description(klass, /* 9.1 */ 3647 "skip-vsc-check", 3648 "Skip config space check for Vendor Specific Capability. " 3649 "Setting to false will enforce strict checking of VSC content " 3650 "(DEBUG)"); 3651 object_class_property_set_description(klass, /* 10.0 */ 3652 "x-migration-multifd-transfer", 3653 "Transfer this device state via " 3654 "multifd channels when live migrating it"); 3655 } 3656 3657 static const TypeInfo vfio_pci_dev_info = { 3658 .name = TYPE_VFIO_PCI, 3659 .parent = TYPE_VFIO_PCI_BASE, 3660 .class_init = vfio_pci_dev_class_init, 3661 .instance_init = vfio_instance_init, 3662 .instance_finalize = vfio_instance_finalize, 3663 }; 3664 3665 static const Property vfio_pci_dev_nohotplug_properties[] = { 3666 DEFINE_PROP_BOOL("ramfb", VFIOPCIDevice, enable_ramfb, false), 3667 DEFINE_PROP_ON_OFF_AUTO("x-ramfb-migrate", VFIOPCIDevice, ramfb_migrate, 3668 ON_OFF_AUTO_AUTO), 3669 }; 3670 3671 static void vfio_pci_nohotplug_dev_class_init(ObjectClass *klass, 3672 const void *data) 3673 { 3674 DeviceClass *dc = DEVICE_CLASS(klass); 3675 3676 device_class_set_props(dc, vfio_pci_dev_nohotplug_properties); 3677 dc->hotpluggable = false; 3678 3679 object_class_property_set_description(klass, /* 3.1 */ 3680 "ramfb", 3681 "Enable ramfb to provide pre-boot graphics for devices " 3682 "enabling display option"); 3683 object_class_property_set_description(klass, /* 8.2 */ 3684 "x-ramfb-migrate", 3685 "Override default migration support for ramfb support " 3686 "(DEBUG)"); 3687 } 3688 3689 static const TypeInfo vfio_pci_nohotplug_dev_info = { 3690 .name = TYPE_VFIO_PCI_NOHOTPLUG, 3691 .parent = TYPE_VFIO_PCI, 3692 .instance_size = sizeof(VFIOPCIDevice), 3693 .class_init = vfio_pci_nohotplug_dev_class_init, 3694 }; 3695 3696 static void register_vfio_pci_dev_type(void) 3697 { 3698 /* 3699 * Ordinary ON_OFF_AUTO property isn't runtime-mutable, but source VM can 3700 * run for a long time before being migrated so it is desirable to have a 3701 * fallback mechanism to the old way of transferring VFIO device state if 3702 * it turns to be necessary. 3703 * The following makes this type of property have the same mutability level 3704 * as ordinary migration parameters. 3705 */ 3706 vfio_pci_migration_multifd_transfer_prop = qdev_prop_on_off_auto; 3707 vfio_pci_migration_multifd_transfer_prop.realized_set_allowed = true; 3708 3709 type_register_static(&vfio_pci_base_dev_info); 3710 type_register_static(&vfio_pci_dev_info); 3711 type_register_static(&vfio_pci_nohotplug_dev_info); 3712 } 3713 3714 type_init(register_vfio_pci_dev_type) 3715