vfio: move re-enabling INTX out of the common helper
[qemu/kevin.git] / hw / vfio / pci.c
blobb3c27c22aaeb205f46800311883d0e4da6c48bf9
1 /*
2 * vfio based device assignment support
4 * Copyright Red Hat, Inc. 2012
6 * Authors:
7 * Alex Williamson <alex.williamson@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
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)
21 #include "qemu/osdep.h"
22 #include <linux/vfio.h>
23 #include <sys/ioctl.h>
25 #include "hw/hw.h"
26 #include "hw/pci/msi.h"
27 #include "hw/pci/msix.h"
28 #include "hw/pci/pci_bridge.h"
29 #include "hw/qdev-properties.h"
30 #include "hw/qdev-properties-system.h"
31 #include "migration/vmstate.h"
32 #include "qapi/qmp/qdict.h"
33 #include "qemu/error-report.h"
34 #include "qemu/main-loop.h"
35 #include "qemu/module.h"
36 #include "qemu/range.h"
37 #include "qemu/units.h"
38 #include "sysemu/kvm.h"
39 #include "sysemu/runstate.h"
40 #include "pci.h"
41 #include "trace.h"
42 #include "qapi/error.h"
43 #include "migration/blocker.h"
44 #include "migration/qemu-file.h"
46 #define TYPE_VFIO_PCI_NOHOTPLUG "vfio-pci-nohotplug"
48 static void vfio_disable_interrupts(VFIOPCIDevice *vdev);
49 static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled);
52 * Disabling BAR mmaping can be slow, but toggling it around INTx can
53 * also be a huge overhead. We try to get the best of both worlds by
54 * waiting until an interrupt to disable mmaps (subsequent transitions
55 * to the same state are effectively no overhead). If the interrupt has
56 * been serviced and the time gap is long enough, we re-enable mmaps for
57 * performance. This works well for things like graphics cards, which
58 * may not use their interrupt at all and are penalized to an unusable
59 * level by read/write BAR traps. Other devices, like NICs, have more
60 * regular interrupts and see much better latency by staying in non-mmap
61 * mode. We therefore set the default mmap_timeout such that a ping
62 * is just enough to keep the mmap disabled. Users can experiment with
63 * other options with the x-intx-mmap-timeout-ms parameter (a value of
64 * zero disables the timer).
66 static void vfio_intx_mmap_enable(void *opaque)
68 VFIOPCIDevice *vdev = opaque;
70 if (vdev->intx.pending) {
71 timer_mod(vdev->intx.mmap_timer,
72 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
73 return;
76 vfio_mmap_set_enabled(vdev, true);
79 static void vfio_intx_interrupt(void *opaque)
81 VFIOPCIDevice *vdev = opaque;
83 if (!event_notifier_test_and_clear(&vdev->intx.interrupt)) {
84 return;
87 trace_vfio_intx_interrupt(vdev->vbasedev.name, 'A' + vdev->intx.pin);
89 vdev->intx.pending = true;
90 pci_irq_assert(&vdev->pdev);
91 vfio_mmap_set_enabled(vdev, false);
92 if (vdev->intx.mmap_timeout) {
93 timer_mod(vdev->intx.mmap_timer,
94 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
98 static void vfio_intx_eoi(VFIODevice *vbasedev)
100 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
102 if (!vdev->intx.pending) {
103 return;
106 trace_vfio_intx_eoi(vbasedev->name);
108 vdev->intx.pending = false;
109 pci_irq_deassert(&vdev->pdev);
110 vfio_unmask_single_irqindex(vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
113 static void vfio_intx_enable_kvm(VFIOPCIDevice *vdev, Error **errp)
115 #ifdef CONFIG_KVM
116 int irq_fd = event_notifier_get_fd(&vdev->intx.interrupt);
118 if (vdev->no_kvm_intx || !kvm_irqfds_enabled() ||
119 vdev->intx.route.mode != PCI_INTX_ENABLED ||
120 !kvm_resamplefds_enabled()) {
121 return;
124 /* Get to a known interrupt state */
125 qemu_set_fd_handler(irq_fd, NULL, NULL, vdev);
126 vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
127 vdev->intx.pending = false;
128 pci_irq_deassert(&vdev->pdev);
130 /* Get an eventfd for resample/unmask */
131 if (event_notifier_init(&vdev->intx.unmask, 0)) {
132 error_setg(errp, "event_notifier_init failed eoi");
133 goto fail;
136 if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state,
137 &vdev->intx.interrupt,
138 &vdev->intx.unmask,
139 vdev->intx.route.irq)) {
140 error_setg_errno(errp, errno, "failed to setup resample irqfd");
141 goto fail_irqfd;
144 if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX, 0,
145 VFIO_IRQ_SET_ACTION_UNMASK,
146 event_notifier_get_fd(&vdev->intx.unmask),
147 errp)) {
148 goto fail_vfio;
151 /* Let'em rip */
152 vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
154 vdev->intx.kvm_accel = true;
156 trace_vfio_intx_enable_kvm(vdev->vbasedev.name);
158 return;
160 fail_vfio:
161 kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vdev->intx.interrupt,
162 vdev->intx.route.irq);
163 fail_irqfd:
164 event_notifier_cleanup(&vdev->intx.unmask);
165 fail:
166 qemu_set_fd_handler(irq_fd, vfio_intx_interrupt, NULL, vdev);
167 vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
168 #endif
171 static void vfio_intx_disable_kvm(VFIOPCIDevice *vdev)
173 #ifdef CONFIG_KVM
174 if (!vdev->intx.kvm_accel) {
175 return;
179 * Get to a known state, hardware masked, QEMU ready to accept new
180 * interrupts, QEMU IRQ de-asserted.
182 vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
183 vdev->intx.pending = false;
184 pci_irq_deassert(&vdev->pdev);
186 /* Tell KVM to stop listening for an INTx irqfd */
187 if (kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vdev->intx.interrupt,
188 vdev->intx.route.irq)) {
189 error_report("vfio: Error: Failed to disable INTx irqfd: %m");
192 /* We only need to close the eventfd for VFIO to cleanup the kernel side */
193 event_notifier_cleanup(&vdev->intx.unmask);
195 /* QEMU starts listening for interrupt events. */
196 qemu_set_fd_handler(event_notifier_get_fd(&vdev->intx.interrupt),
197 vfio_intx_interrupt, NULL, vdev);
199 vdev->intx.kvm_accel = false;
201 /* If we've missed an event, let it re-fire through QEMU */
202 vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
204 trace_vfio_intx_disable_kvm(vdev->vbasedev.name);
205 #endif
208 static void vfio_intx_update(VFIOPCIDevice *vdev, PCIINTxRoute *route)
210 Error *err = NULL;
212 trace_vfio_intx_update(vdev->vbasedev.name,
213 vdev->intx.route.irq, route->irq);
215 vfio_intx_disable_kvm(vdev);
217 vdev->intx.route = *route;
219 if (route->mode != PCI_INTX_ENABLED) {
220 return;
223 vfio_intx_enable_kvm(vdev, &err);
224 if (err) {
225 warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
228 /* Re-enable the interrupt in cased we missed an EOI */
229 vfio_intx_eoi(&vdev->vbasedev);
232 static void vfio_intx_routing_notifier(PCIDevice *pdev)
234 VFIOPCIDevice *vdev = VFIO_PCI(pdev);
235 PCIINTxRoute route;
237 if (vdev->interrupt != VFIO_INT_INTx) {
238 return;
241 route = pci_device_route_intx_to_irq(&vdev->pdev, vdev->intx.pin);
243 if (pci_intx_route_changed(&vdev->intx.route, &route)) {
244 vfio_intx_update(vdev, &route);
248 static void vfio_irqchip_change(Notifier *notify, void *data)
250 VFIOPCIDevice *vdev = container_of(notify, VFIOPCIDevice,
251 irqchip_change_notifier);
253 vfio_intx_update(vdev, &vdev->intx.route);
256 static int vfio_intx_enable(VFIOPCIDevice *vdev, Error **errp)
258 uint8_t pin = vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1);
259 Error *err = NULL;
260 int32_t fd;
261 int ret;
264 if (!pin) {
265 return 0;
268 vfio_disable_interrupts(vdev);
270 vdev->intx.pin = pin - 1; /* Pin A (1) -> irq[0] */
271 pci_config_set_interrupt_pin(vdev->pdev.config, pin);
273 #ifdef CONFIG_KVM
275 * Only conditional to avoid generating error messages on platforms
276 * where we won't actually use the result anyway.
278 if (kvm_irqfds_enabled() && kvm_resamplefds_enabled()) {
279 vdev->intx.route = pci_device_route_intx_to_irq(&vdev->pdev,
280 vdev->intx.pin);
282 #endif
284 ret = event_notifier_init(&vdev->intx.interrupt, 0);
285 if (ret) {
286 error_setg_errno(errp, -ret, "event_notifier_init failed");
287 return ret;
289 fd = event_notifier_get_fd(&vdev->intx.interrupt);
290 qemu_set_fd_handler(fd, vfio_intx_interrupt, NULL, vdev);
292 if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX, 0,
293 VFIO_IRQ_SET_ACTION_TRIGGER, fd, errp)) {
294 qemu_set_fd_handler(fd, NULL, NULL, vdev);
295 event_notifier_cleanup(&vdev->intx.interrupt);
296 return -errno;
299 vfio_intx_enable_kvm(vdev, &err);
300 if (err) {
301 warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
304 vdev->interrupt = VFIO_INT_INTx;
306 trace_vfio_intx_enable(vdev->vbasedev.name);
307 return 0;
310 static void vfio_intx_disable(VFIOPCIDevice *vdev)
312 int fd;
314 timer_del(vdev->intx.mmap_timer);
315 vfio_intx_disable_kvm(vdev);
316 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
317 vdev->intx.pending = false;
318 pci_irq_deassert(&vdev->pdev);
319 vfio_mmap_set_enabled(vdev, true);
321 fd = event_notifier_get_fd(&vdev->intx.interrupt);
322 qemu_set_fd_handler(fd, NULL, NULL, vdev);
323 event_notifier_cleanup(&vdev->intx.interrupt);
325 vdev->interrupt = VFIO_INT_NONE;
327 trace_vfio_intx_disable(vdev->vbasedev.name);
331 * MSI/X
333 static void vfio_msi_interrupt(void *opaque)
335 VFIOMSIVector *vector = opaque;
336 VFIOPCIDevice *vdev = vector->vdev;
337 MSIMessage (*get_msg)(PCIDevice *dev, unsigned vector);
338 void (*notify)(PCIDevice *dev, unsigned vector);
339 MSIMessage msg;
340 int nr = vector - vdev->msi_vectors;
342 if (!event_notifier_test_and_clear(&vector->interrupt)) {
343 return;
346 if (vdev->interrupt == VFIO_INT_MSIX) {
347 get_msg = msix_get_message;
348 notify = msix_notify;
350 /* A masked vector firing needs to use the PBA, enable it */
351 if (msix_is_masked(&vdev->pdev, nr)) {
352 set_bit(nr, vdev->msix->pending);
353 memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, true);
354 trace_vfio_msix_pba_enable(vdev->vbasedev.name);
356 } else if (vdev->interrupt == VFIO_INT_MSI) {
357 get_msg = msi_get_message;
358 notify = msi_notify;
359 } else {
360 abort();
363 msg = get_msg(&vdev->pdev, nr);
364 trace_vfio_msi_interrupt(vdev->vbasedev.name, nr, msg.address, msg.data);
365 notify(&vdev->pdev, nr);
368 static int vfio_enable_vectors(VFIOPCIDevice *vdev, bool msix)
370 struct vfio_irq_set *irq_set;
371 int ret = 0, i, argsz;
372 int32_t *fds;
374 argsz = sizeof(*irq_set) + (vdev->nr_vectors * sizeof(*fds));
376 irq_set = g_malloc0(argsz);
377 irq_set->argsz = argsz;
378 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
379 irq_set->index = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX;
380 irq_set->start = 0;
381 irq_set->count = vdev->nr_vectors;
382 fds = (int32_t *)&irq_set->data;
384 for (i = 0; i < vdev->nr_vectors; i++) {
385 int fd = -1;
388 * MSI vs MSI-X - The guest has direct access to MSI mask and pending
389 * bits, therefore we always use the KVM signaling path when setup.
390 * MSI-X mask and pending bits are emulated, so we want to use the
391 * KVM signaling path only when configured and unmasked.
393 if (vdev->msi_vectors[i].use) {
394 if (vdev->msi_vectors[i].virq < 0 ||
395 (msix && msix_is_masked(&vdev->pdev, i))) {
396 fd = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt);
397 } else {
398 fd = event_notifier_get_fd(&vdev->msi_vectors[i].kvm_interrupt);
402 fds[i] = fd;
405 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
407 g_free(irq_set);
409 return ret;
412 static void vfio_add_kvm_msi_virq(VFIOPCIDevice *vdev, VFIOMSIVector *vector,
413 int vector_n, bool msix)
415 KVMRouteChange c;
416 int virq;
418 if ((msix && vdev->no_kvm_msix) || (!msix && vdev->no_kvm_msi)) {
419 return;
422 if (event_notifier_init(&vector->kvm_interrupt, 0)) {
423 return;
426 c = kvm_irqchip_begin_route_changes(kvm_state);
427 virq = kvm_irqchip_add_msi_route(&c, vector_n, &vdev->pdev);
428 if (virq < 0) {
429 event_notifier_cleanup(&vector->kvm_interrupt);
430 return;
432 kvm_irqchip_commit_route_changes(&c);
434 if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt,
435 NULL, virq) < 0) {
436 kvm_irqchip_release_virq(kvm_state, virq);
437 event_notifier_cleanup(&vector->kvm_interrupt);
438 return;
441 vector->virq = virq;
444 static void vfio_remove_kvm_msi_virq(VFIOMSIVector *vector)
446 kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt,
447 vector->virq);
448 kvm_irqchip_release_virq(kvm_state, vector->virq);
449 vector->virq = -1;
450 event_notifier_cleanup(&vector->kvm_interrupt);
453 static void vfio_update_kvm_msi_virq(VFIOMSIVector *vector, MSIMessage msg,
454 PCIDevice *pdev)
456 kvm_irqchip_update_msi_route(kvm_state, vector->virq, msg, pdev);
457 kvm_irqchip_commit_routes(kvm_state);
460 static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr,
461 MSIMessage *msg, IOHandler *handler)
463 VFIOPCIDevice *vdev = VFIO_PCI(pdev);
464 VFIOMSIVector *vector;
465 int ret;
467 trace_vfio_msix_vector_do_use(vdev->vbasedev.name, nr);
469 vector = &vdev->msi_vectors[nr];
471 if (!vector->use) {
472 vector->vdev = vdev;
473 vector->virq = -1;
474 if (event_notifier_init(&vector->interrupt, 0)) {
475 error_report("vfio: Error: event_notifier_init failed");
477 vector->use = true;
478 msix_vector_use(pdev, nr);
481 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
482 handler, NULL, vector);
485 * Attempt to enable route through KVM irqchip,
486 * default to userspace handling if unavailable.
488 if (vector->virq >= 0) {
489 if (!msg) {
490 vfio_remove_kvm_msi_virq(vector);
491 } else {
492 vfio_update_kvm_msi_virq(vector, *msg, pdev);
494 } else {
495 if (msg) {
496 vfio_add_kvm_msi_virq(vdev, vector, nr, true);
501 * We don't want to have the host allocate all possible MSI vectors
502 * for a device if they're not in use, so we shutdown and incrementally
503 * increase them as needed.
505 if (vdev->nr_vectors < nr + 1) {
506 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
507 vdev->nr_vectors = nr + 1;
508 ret = vfio_enable_vectors(vdev, true);
509 if (ret) {
510 error_report("vfio: failed to enable vectors, %d", ret);
512 } else {
513 Error *err = NULL;
514 int32_t fd;
516 if (vector->virq >= 0) {
517 fd = event_notifier_get_fd(&vector->kvm_interrupt);
518 } else {
519 fd = event_notifier_get_fd(&vector->interrupt);
522 if (vfio_set_irq_signaling(&vdev->vbasedev,
523 VFIO_PCI_MSIX_IRQ_INDEX, nr,
524 VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
525 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
529 /* Disable PBA emulation when nothing more is pending. */
530 clear_bit(nr, vdev->msix->pending);
531 if (find_first_bit(vdev->msix->pending,
532 vdev->nr_vectors) == vdev->nr_vectors) {
533 memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, false);
534 trace_vfio_msix_pba_disable(vdev->vbasedev.name);
537 return 0;
540 static int vfio_msix_vector_use(PCIDevice *pdev,
541 unsigned int nr, MSIMessage msg)
543 return vfio_msix_vector_do_use(pdev, nr, &msg, vfio_msi_interrupt);
546 static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr)
548 VFIOPCIDevice *vdev = VFIO_PCI(pdev);
549 VFIOMSIVector *vector = &vdev->msi_vectors[nr];
551 trace_vfio_msix_vector_release(vdev->vbasedev.name, nr);
554 * There are still old guests that mask and unmask vectors on every
555 * interrupt. If we're using QEMU bypass with a KVM irqfd, leave all of
556 * the KVM setup in place, simply switch VFIO to use the non-bypass
557 * eventfd. We'll then fire the interrupt through QEMU and the MSI-X
558 * core will mask the interrupt and set pending bits, allowing it to
559 * be re-asserted on unmask. Nothing to do if already using QEMU mode.
561 if (vector->virq >= 0) {
562 int32_t fd = event_notifier_get_fd(&vector->interrupt);
563 Error *err = NULL;
565 if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX, nr,
566 VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
567 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
572 static void vfio_msix_enable(VFIOPCIDevice *vdev)
574 PCIDevice *pdev = &vdev->pdev;
575 unsigned int nr, max_vec = 0;
577 vfio_disable_interrupts(vdev);
579 vdev->msi_vectors = g_new0(VFIOMSIVector, vdev->msix->entries);
581 vdev->interrupt = VFIO_INT_MSIX;
584 * Some communication channels between VF & PF or PF & fw rely on the
585 * physical state of the device and expect that enabling MSI-X from the
586 * guest enables the same on the host. When our guest is Linux, the
587 * guest driver call to pci_enable_msix() sets the enabling bit in the
588 * MSI-X capability, but leaves the vector table masked. We therefore
589 * can't rely on a vector_use callback (from request_irq() in the guest)
590 * to switch the physical device into MSI-X mode because that may come a
591 * long time after pci_enable_msix(). This code enables vector 0 with
592 * triggering to userspace, then immediately release the vector, leaving
593 * the physical device with no vectors enabled, but MSI-X enabled, just
594 * like the guest view.
595 * If there are already unmasked vectors (in migration resume phase and
596 * some guest startups) which will be enabled soon, we can allocate all
597 * of them here to avoid inefficiently disabling and enabling vectors
598 * repeatedly later.
600 if (!pdev->msix_function_masked) {
601 for (nr = 0; nr < msix_nr_vectors_allocated(pdev); nr++) {
602 if (!msix_is_masked(pdev, nr)) {
603 max_vec = nr;
607 vfio_msix_vector_do_use(pdev, max_vec, NULL, NULL);
608 vfio_msix_vector_release(pdev, max_vec);
610 if (msix_set_vector_notifiers(pdev, vfio_msix_vector_use,
611 vfio_msix_vector_release, NULL)) {
612 error_report("vfio: msix_set_vector_notifiers failed");
615 trace_vfio_msix_enable(vdev->vbasedev.name);
618 static void vfio_msi_enable(VFIOPCIDevice *vdev)
620 int ret, i;
622 vfio_disable_interrupts(vdev);
624 vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev);
625 retry:
626 vdev->msi_vectors = g_new0(VFIOMSIVector, vdev->nr_vectors);
628 for (i = 0; i < vdev->nr_vectors; i++) {
629 VFIOMSIVector *vector = &vdev->msi_vectors[i];
631 vector->vdev = vdev;
632 vector->virq = -1;
633 vector->use = true;
635 if (event_notifier_init(&vector->interrupt, 0)) {
636 error_report("vfio: Error: event_notifier_init failed");
639 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
640 vfio_msi_interrupt, NULL, vector);
643 * Attempt to enable route through KVM irqchip,
644 * default to userspace handling if unavailable.
646 vfio_add_kvm_msi_virq(vdev, vector, i, false);
649 /* Set interrupt type prior to possible interrupts */
650 vdev->interrupt = VFIO_INT_MSI;
652 ret = vfio_enable_vectors(vdev, false);
653 if (ret) {
654 if (ret < 0) {
655 error_report("vfio: Error: Failed to setup MSI fds: %m");
656 } else {
657 error_report("vfio: Error: Failed to enable %d "
658 "MSI vectors, retry with %d", vdev->nr_vectors, ret);
661 for (i = 0; i < vdev->nr_vectors; i++) {
662 VFIOMSIVector *vector = &vdev->msi_vectors[i];
663 if (vector->virq >= 0) {
664 vfio_remove_kvm_msi_virq(vector);
666 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
667 NULL, NULL, NULL);
668 event_notifier_cleanup(&vector->interrupt);
671 g_free(vdev->msi_vectors);
672 vdev->msi_vectors = NULL;
674 if (ret > 0) {
675 vdev->nr_vectors = ret;
676 goto retry;
678 vdev->nr_vectors = 0;
681 * Failing to setup MSI doesn't really fall within any specification.
682 * Let's try leaving interrupts disabled and hope the guest figures
683 * out to fall back to INTx for this device.
685 error_report("vfio: Error: Failed to enable MSI");
686 vdev->interrupt = VFIO_INT_NONE;
688 return;
691 trace_vfio_msi_enable(vdev->vbasedev.name, vdev->nr_vectors);
694 static void vfio_msi_disable_common(VFIOPCIDevice *vdev)
696 int i;
698 for (i = 0; i < vdev->nr_vectors; i++) {
699 VFIOMSIVector *vector = &vdev->msi_vectors[i];
700 if (vdev->msi_vectors[i].use) {
701 if (vector->virq >= 0) {
702 vfio_remove_kvm_msi_virq(vector);
704 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
705 NULL, NULL, NULL);
706 event_notifier_cleanup(&vector->interrupt);
710 g_free(vdev->msi_vectors);
711 vdev->msi_vectors = NULL;
712 vdev->nr_vectors = 0;
713 vdev->interrupt = VFIO_INT_NONE;
716 static void vfio_msix_disable(VFIOPCIDevice *vdev)
718 Error *err = NULL;
719 int i;
721 msix_unset_vector_notifiers(&vdev->pdev);
724 * MSI-X will only release vectors if MSI-X is still enabled on the
725 * device, check through the rest and release it ourselves if necessary.
727 for (i = 0; i < vdev->nr_vectors; i++) {
728 if (vdev->msi_vectors[i].use) {
729 vfio_msix_vector_release(&vdev->pdev, i);
730 msix_vector_unuse(&vdev->pdev, i);
734 if (vdev->nr_vectors) {
735 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
738 vfio_msi_disable_common(vdev);
739 vfio_intx_enable(vdev, &err);
740 if (err) {
741 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
744 memset(vdev->msix->pending, 0,
745 BITS_TO_LONGS(vdev->msix->entries) * sizeof(unsigned long));
747 trace_vfio_msix_disable(vdev->vbasedev.name);
750 static void vfio_msi_disable(VFIOPCIDevice *vdev)
752 Error *err = NULL;
754 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSI_IRQ_INDEX);
755 vfio_msi_disable_common(vdev);
756 vfio_intx_enable(vdev, &err);
757 if (err) {
758 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
761 trace_vfio_msi_disable(vdev->vbasedev.name);
764 static void vfio_update_msi(VFIOPCIDevice *vdev)
766 int i;
768 for (i = 0; i < vdev->nr_vectors; i++) {
769 VFIOMSIVector *vector = &vdev->msi_vectors[i];
770 MSIMessage msg;
772 if (!vector->use || vector->virq < 0) {
773 continue;
776 msg = msi_get_message(&vdev->pdev, i);
777 vfio_update_kvm_msi_virq(vector, msg, &vdev->pdev);
781 static void vfio_pci_load_rom(VFIOPCIDevice *vdev)
783 struct vfio_region_info *reg_info;
784 uint64_t size;
785 off_t off = 0;
786 ssize_t bytes;
788 if (vfio_get_region_info(&vdev->vbasedev,
789 VFIO_PCI_ROM_REGION_INDEX, &reg_info)) {
790 error_report("vfio: Error getting ROM info: %m");
791 return;
794 trace_vfio_pci_load_rom(vdev->vbasedev.name, (unsigned long)reg_info->size,
795 (unsigned long)reg_info->offset,
796 (unsigned long)reg_info->flags);
798 vdev->rom_size = size = reg_info->size;
799 vdev->rom_offset = reg_info->offset;
801 g_free(reg_info);
803 if (!vdev->rom_size) {
804 vdev->rom_read_failed = true;
805 error_report("vfio-pci: Cannot read device rom at "
806 "%s", vdev->vbasedev.name);
807 error_printf("Device option ROM contents are probably invalid "
808 "(check dmesg).\nSkip option ROM probe with rombar=0, "
809 "or load from file with romfile=\n");
810 return;
813 vdev->rom = g_malloc(size);
814 memset(vdev->rom, 0xff, size);
816 while (size) {
817 bytes = pread(vdev->vbasedev.fd, vdev->rom + off,
818 size, vdev->rom_offset + off);
819 if (bytes == 0) {
820 break;
821 } else if (bytes > 0) {
822 off += bytes;
823 size -= bytes;
824 } else {
825 if (errno == EINTR || errno == EAGAIN) {
826 continue;
828 error_report("vfio: Error reading device ROM: %m");
829 break;
834 * Test the ROM signature against our device, if the vendor is correct
835 * but the device ID doesn't match, store the correct device ID and
836 * recompute the checksum. Intel IGD devices need this and are known
837 * to have bogus checksums so we can't simply adjust the checksum.
839 if (pci_get_word(vdev->rom) == 0xaa55 &&
840 pci_get_word(vdev->rom + 0x18) + 8 < vdev->rom_size &&
841 !memcmp(vdev->rom + pci_get_word(vdev->rom + 0x18), "PCIR", 4)) {
842 uint16_t vid, did;
844 vid = pci_get_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 4);
845 did = pci_get_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 6);
847 if (vid == vdev->vendor_id && did != vdev->device_id) {
848 int i;
849 uint8_t csum, *data = vdev->rom;
851 pci_set_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 6,
852 vdev->device_id);
853 data[6] = 0;
855 for (csum = 0, i = 0; i < vdev->rom_size; i++) {
856 csum += data[i];
859 data[6] = -csum;
864 static uint64_t vfio_rom_read(void *opaque, hwaddr addr, unsigned size)
866 VFIOPCIDevice *vdev = opaque;
867 union {
868 uint8_t byte;
869 uint16_t word;
870 uint32_t dword;
871 uint64_t qword;
872 } val;
873 uint64_t data = 0;
875 /* Load the ROM lazily when the guest tries to read it */
876 if (unlikely(!vdev->rom && !vdev->rom_read_failed)) {
877 vfio_pci_load_rom(vdev);
880 memcpy(&val, vdev->rom + addr,
881 (addr < vdev->rom_size) ? MIN(size, vdev->rom_size - addr) : 0);
883 switch (size) {
884 case 1:
885 data = val.byte;
886 break;
887 case 2:
888 data = le16_to_cpu(val.word);
889 break;
890 case 4:
891 data = le32_to_cpu(val.dword);
892 break;
893 default:
894 hw_error("vfio: unsupported read size, %d bytes\n", size);
895 break;
898 trace_vfio_rom_read(vdev->vbasedev.name, addr, size, data);
900 return data;
903 static void vfio_rom_write(void *opaque, hwaddr addr,
904 uint64_t data, unsigned size)
908 static const MemoryRegionOps vfio_rom_ops = {
909 .read = vfio_rom_read,
910 .write = vfio_rom_write,
911 .endianness = DEVICE_LITTLE_ENDIAN,
914 static void vfio_pci_size_rom(VFIOPCIDevice *vdev)
916 uint32_t orig, size = cpu_to_le32((uint32_t)PCI_ROM_ADDRESS_MASK);
917 off_t offset = vdev->config_offset + PCI_ROM_ADDRESS;
918 DeviceState *dev = DEVICE(vdev);
919 char *name;
920 int fd = vdev->vbasedev.fd;
922 if (vdev->pdev.romfile || !vdev->pdev.rom_bar) {
923 /* Since pci handles romfile, just print a message and return */
924 if (vfio_opt_rom_in_denylist(vdev) && vdev->pdev.romfile) {
925 warn_report("Device at %s is known to cause system instability"
926 " issues during option rom execution",
927 vdev->vbasedev.name);
928 error_printf("Proceeding anyway since user specified romfile\n");
930 return;
934 * Use the same size ROM BAR as the physical device. The contents
935 * will get filled in later when the guest tries to read it.
937 if (pread(fd, &orig, 4, offset) != 4 ||
938 pwrite(fd, &size, 4, offset) != 4 ||
939 pread(fd, &size, 4, offset) != 4 ||
940 pwrite(fd, &orig, 4, offset) != 4) {
941 error_report("%s(%s) failed: %m", __func__, vdev->vbasedev.name);
942 return;
945 size = ~(le32_to_cpu(size) & PCI_ROM_ADDRESS_MASK) + 1;
947 if (!size) {
948 return;
951 if (vfio_opt_rom_in_denylist(vdev)) {
952 if (dev->opts && qdict_haskey(dev->opts, "rombar")) {
953 warn_report("Device at %s is known to cause system instability"
954 " issues during option rom execution",
955 vdev->vbasedev.name);
956 error_printf("Proceeding anyway since user specified"
957 " non zero value for rombar\n");
958 } else {
959 warn_report("Rom loading for device at %s has been disabled"
960 " due to system instability issues",
961 vdev->vbasedev.name);
962 error_printf("Specify rombar=1 or romfile to force\n");
963 return;
967 trace_vfio_pci_size_rom(vdev->vbasedev.name, size);
969 name = g_strdup_printf("vfio[%s].rom", vdev->vbasedev.name);
971 memory_region_init_io(&vdev->pdev.rom, OBJECT(vdev),
972 &vfio_rom_ops, vdev, name, size);
973 g_free(name);
975 pci_register_bar(&vdev->pdev, PCI_ROM_SLOT,
976 PCI_BASE_ADDRESS_SPACE_MEMORY, &vdev->pdev.rom);
978 vdev->rom_read_failed = false;
981 void vfio_vga_write(void *opaque, hwaddr addr,
982 uint64_t data, unsigned size)
984 VFIOVGARegion *region = opaque;
985 VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
986 union {
987 uint8_t byte;
988 uint16_t word;
989 uint32_t dword;
990 uint64_t qword;
991 } buf;
992 off_t offset = vga->fd_offset + region->offset + addr;
994 switch (size) {
995 case 1:
996 buf.byte = data;
997 break;
998 case 2:
999 buf.word = cpu_to_le16(data);
1000 break;
1001 case 4:
1002 buf.dword = cpu_to_le32(data);
1003 break;
1004 default:
1005 hw_error("vfio: unsupported write size, %d bytes", size);
1006 break;
1009 if (pwrite(vga->fd, &buf, size, offset) != size) {
1010 error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m",
1011 __func__, region->offset + addr, data, size);
1014 trace_vfio_vga_write(region->offset + addr, data, size);
1017 uint64_t vfio_vga_read(void *opaque, hwaddr addr, unsigned size)
1019 VFIOVGARegion *region = opaque;
1020 VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
1021 union {
1022 uint8_t byte;
1023 uint16_t word;
1024 uint32_t dword;
1025 uint64_t qword;
1026 } buf;
1027 uint64_t data = 0;
1028 off_t offset = vga->fd_offset + region->offset + addr;
1030 if (pread(vga->fd, &buf, size, offset) != size) {
1031 error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m",
1032 __func__, region->offset + addr, size);
1033 return (uint64_t)-1;
1036 switch (size) {
1037 case 1:
1038 data = buf.byte;
1039 break;
1040 case 2:
1041 data = le16_to_cpu(buf.word);
1042 break;
1043 case 4:
1044 data = le32_to_cpu(buf.dword);
1045 break;
1046 default:
1047 hw_error("vfio: unsupported read size, %d bytes", size);
1048 break;
1051 trace_vfio_vga_read(region->offset + addr, size, data);
1053 return data;
1056 static const MemoryRegionOps vfio_vga_ops = {
1057 .read = vfio_vga_read,
1058 .write = vfio_vga_write,
1059 .endianness = DEVICE_LITTLE_ENDIAN,
1063 * Expand memory region of sub-page(size < PAGE_SIZE) MMIO BAR to page
1064 * size if the BAR is in an exclusive page in host so that we could map
1065 * this BAR to guest. But this sub-page BAR may not occupy an exclusive
1066 * page in guest. So we should set the priority of the expanded memory
1067 * region to zero in case of overlap with BARs which share the same page
1068 * with the sub-page BAR in guest. Besides, we should also recover the
1069 * size of this sub-page BAR when its base address is changed in guest
1070 * and not page aligned any more.
1072 static void vfio_sub_page_bar_update_mapping(PCIDevice *pdev, int bar)
1074 VFIOPCIDevice *vdev = VFIO_PCI(pdev);
1075 VFIORegion *region = &vdev->bars[bar].region;
1076 MemoryRegion *mmap_mr, *region_mr, *base_mr;
1077 PCIIORegion *r;
1078 pcibus_t bar_addr;
1079 uint64_t size = region->size;
1081 /* Make sure that the whole region is allowed to be mmapped */
1082 if (region->nr_mmaps != 1 || !region->mmaps[0].mmap ||
1083 region->mmaps[0].size != region->size) {
1084 return;
1087 r = &pdev->io_regions[bar];
1088 bar_addr = r->addr;
1089 base_mr = vdev->bars[bar].mr;
1090 region_mr = region->mem;
1091 mmap_mr = &region->mmaps[0].mem;
1093 /* If BAR is mapped and page aligned, update to fill PAGE_SIZE */
1094 if (bar_addr != PCI_BAR_UNMAPPED &&
1095 !(bar_addr & ~qemu_real_host_page_mask())) {
1096 size = qemu_real_host_page_size();
1099 memory_region_transaction_begin();
1101 if (vdev->bars[bar].size < size) {
1102 memory_region_set_size(base_mr, size);
1104 memory_region_set_size(region_mr, size);
1105 memory_region_set_size(mmap_mr, size);
1106 if (size != vdev->bars[bar].size && memory_region_is_mapped(base_mr)) {
1107 memory_region_del_subregion(r->address_space, base_mr);
1108 memory_region_add_subregion_overlap(r->address_space,
1109 bar_addr, base_mr, 0);
1112 memory_region_transaction_commit();
1116 * PCI config space
1118 uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len)
1120 VFIOPCIDevice *vdev = VFIO_PCI(pdev);
1121 uint32_t emu_bits = 0, emu_val = 0, phys_val = 0, val;
1123 memcpy(&emu_bits, vdev->emulated_config_bits + addr, len);
1124 emu_bits = le32_to_cpu(emu_bits);
1126 if (emu_bits) {
1127 emu_val = pci_default_read_config(pdev, addr, len);
1130 if (~emu_bits & (0xffffffffU >> (32 - len * 8))) {
1131 ssize_t ret;
1133 ret = pread(vdev->vbasedev.fd, &phys_val, len,
1134 vdev->config_offset + addr);
1135 if (ret != len) {
1136 error_report("%s(%s, 0x%x, 0x%x) failed: %m",
1137 __func__, vdev->vbasedev.name, addr, len);
1138 return -errno;
1140 phys_val = le32_to_cpu(phys_val);
1143 val = (emu_val & emu_bits) | (phys_val & ~emu_bits);
1145 trace_vfio_pci_read_config(vdev->vbasedev.name, addr, len, val);
1147 return val;
1150 void vfio_pci_write_config(PCIDevice *pdev,
1151 uint32_t addr, uint32_t val, int len)
1153 VFIOPCIDevice *vdev = VFIO_PCI(pdev);
1154 uint32_t val_le = cpu_to_le32(val);
1156 trace_vfio_pci_write_config(vdev->vbasedev.name, addr, val, len);
1158 /* Write everything to VFIO, let it filter out what we can't write */
1159 if (pwrite(vdev->vbasedev.fd, &val_le, len, vdev->config_offset + addr)
1160 != len) {
1161 error_report("%s(%s, 0x%x, 0x%x, 0x%x) failed: %m",
1162 __func__, vdev->vbasedev.name, addr, val, len);
1165 /* MSI/MSI-X Enabling/Disabling */
1166 if (pdev->cap_present & QEMU_PCI_CAP_MSI &&
1167 ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {
1168 int is_enabled, was_enabled = msi_enabled(pdev);
1170 pci_default_write_config(pdev, addr, val, len);
1172 is_enabled = msi_enabled(pdev);
1174 if (!was_enabled) {
1175 if (is_enabled) {
1176 vfio_msi_enable(vdev);
1178 } else {
1179 if (!is_enabled) {
1180 vfio_msi_disable(vdev);
1181 } else {
1182 vfio_update_msi(vdev);
1185 } else if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
1186 ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {
1187 int is_enabled, was_enabled = msix_enabled(pdev);
1189 pci_default_write_config(pdev, addr, val, len);
1191 is_enabled = msix_enabled(pdev);
1193 if (!was_enabled && is_enabled) {
1194 vfio_msix_enable(vdev);
1195 } else if (was_enabled && !is_enabled) {
1196 vfio_msix_disable(vdev);
1198 } else if (ranges_overlap(addr, len, PCI_BASE_ADDRESS_0, 24) ||
1199 range_covers_byte(addr, len, PCI_COMMAND)) {
1200 pcibus_t old_addr[PCI_NUM_REGIONS - 1];
1201 int bar;
1203 for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
1204 old_addr[bar] = pdev->io_regions[bar].addr;
1207 pci_default_write_config(pdev, addr, val, len);
1209 for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
1210 if (old_addr[bar] != pdev->io_regions[bar].addr &&
1211 vdev->bars[bar].region.size > 0 &&
1212 vdev->bars[bar].region.size < qemu_real_host_page_size()) {
1213 vfio_sub_page_bar_update_mapping(pdev, bar);
1216 } else {
1217 /* Write everything to QEMU to keep emulated bits correct */
1218 pci_default_write_config(pdev, addr, val, len);
1223 * Interrupt setup
1225 static void vfio_disable_interrupts(VFIOPCIDevice *vdev)
1228 * More complicated than it looks. Disabling MSI/X transitions the
1229 * device to INTx mode (if supported). Therefore we need to first
1230 * disable MSI/X and then cleanup by disabling INTx.
1232 if (vdev->interrupt == VFIO_INT_MSIX) {
1233 vfio_msix_disable(vdev);
1234 } else if (vdev->interrupt == VFIO_INT_MSI) {
1235 vfio_msi_disable(vdev);
1238 if (vdev->interrupt == VFIO_INT_INTx) {
1239 vfio_intx_disable(vdev);
1243 static int vfio_msi_setup(VFIOPCIDevice *vdev, int pos, Error **errp)
1245 uint16_t ctrl;
1246 bool msi_64bit, msi_maskbit;
1247 int ret, entries;
1248 Error *err = NULL;
1250 if (pread(vdev->vbasedev.fd, &ctrl, sizeof(ctrl),
1251 vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
1252 error_setg_errno(errp, errno, "failed reading MSI PCI_CAP_FLAGS");
1253 return -errno;
1255 ctrl = le16_to_cpu(ctrl);
1257 msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT);
1258 msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT);
1259 entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1);
1261 trace_vfio_msi_setup(vdev->vbasedev.name, pos);
1263 ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit, &err);
1264 if (ret < 0) {
1265 if (ret == -ENOTSUP) {
1266 return 0;
1268 error_propagate_prepend(errp, err, "msi_init failed: ");
1269 return ret;
1271 vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0);
1273 return 0;
1276 static void vfio_pci_fixup_msix_region(VFIOPCIDevice *vdev)
1278 off_t start, end;
1279 VFIORegion *region = &vdev->bars[vdev->msix->table_bar].region;
1282 * If the host driver allows mapping of a MSIX data, we are going to
1283 * do map the entire BAR and emulate MSIX table on top of that.
1285 if (vfio_has_region_cap(&vdev->vbasedev, region->nr,
1286 VFIO_REGION_INFO_CAP_MSIX_MAPPABLE)) {
1287 return;
1291 * We expect to find a single mmap covering the whole BAR, anything else
1292 * means it's either unsupported or already setup.
1294 if (region->nr_mmaps != 1 || region->mmaps[0].offset ||
1295 region->size != region->mmaps[0].size) {
1296 return;
1299 /* MSI-X table start and end aligned to host page size */
1300 start = vdev->msix->table_offset & qemu_real_host_page_mask();
1301 end = REAL_HOST_PAGE_ALIGN((uint64_t)vdev->msix->table_offset +
1302 (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE));
1305 * Does the MSI-X table cover the beginning of the BAR? The whole BAR?
1306 * NB - Host page size is necessarily a power of two and so is the PCI
1307 * BAR (not counting EA yet), therefore if we have host page aligned
1308 * @start and @end, then any remainder of the BAR before or after those
1309 * must be at least host page sized and therefore mmap'able.
1311 if (!start) {
1312 if (end >= region->size) {
1313 region->nr_mmaps = 0;
1314 g_free(region->mmaps);
1315 region->mmaps = NULL;
1316 trace_vfio_msix_fixup(vdev->vbasedev.name,
1317 vdev->msix->table_bar, 0, 0);
1318 } else {
1319 region->mmaps[0].offset = end;
1320 region->mmaps[0].size = region->size - end;
1321 trace_vfio_msix_fixup(vdev->vbasedev.name,
1322 vdev->msix->table_bar, region->mmaps[0].offset,
1323 region->mmaps[0].offset + region->mmaps[0].size);
1326 /* Maybe it's aligned at the end of the BAR */
1327 } else if (end >= region->size) {
1328 region->mmaps[0].size = start;
1329 trace_vfio_msix_fixup(vdev->vbasedev.name,
1330 vdev->msix->table_bar, region->mmaps[0].offset,
1331 region->mmaps[0].offset + region->mmaps[0].size);
1333 /* Otherwise it must split the BAR */
1334 } else {
1335 region->nr_mmaps = 2;
1336 region->mmaps = g_renew(VFIOMmap, region->mmaps, 2);
1338 memcpy(&region->mmaps[1], &region->mmaps[0], sizeof(VFIOMmap));
1340 region->mmaps[0].size = start;
1341 trace_vfio_msix_fixup(vdev->vbasedev.name,
1342 vdev->msix->table_bar, region->mmaps[0].offset,
1343 region->mmaps[0].offset + region->mmaps[0].size);
1345 region->mmaps[1].offset = end;
1346 region->mmaps[1].size = region->size - end;
1347 trace_vfio_msix_fixup(vdev->vbasedev.name,
1348 vdev->msix->table_bar, region->mmaps[1].offset,
1349 region->mmaps[1].offset + region->mmaps[1].size);
1353 static void vfio_pci_relocate_msix(VFIOPCIDevice *vdev, Error **errp)
1355 int target_bar = -1;
1356 size_t msix_sz;
1358 if (!vdev->msix || vdev->msix_relo == OFF_AUTOPCIBAR_OFF) {
1359 return;
1362 /* The actual minimum size of MSI-X structures */
1363 msix_sz = (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE) +
1364 (QEMU_ALIGN_UP(vdev->msix->entries, 64) / 8);
1365 /* Round up to host pages, we don't want to share a page */
1366 msix_sz = REAL_HOST_PAGE_ALIGN(msix_sz);
1367 /* PCI BARs must be a power of 2 */
1368 msix_sz = pow2ceil(msix_sz);
1370 if (vdev->msix_relo == OFF_AUTOPCIBAR_AUTO) {
1372 * TODO: Lookup table for known devices.
1374 * Logically we might use an algorithm here to select the BAR adding
1375 * the least additional MMIO space, but we cannot programmatically
1376 * predict the driver dependency on BAR ordering or sizing, therefore
1377 * 'auto' becomes a lookup for combinations reported to work.
1379 if (target_bar < 0) {
1380 error_setg(errp, "No automatic MSI-X relocation available for "
1381 "device %04x:%04x", vdev->vendor_id, vdev->device_id);
1382 return;
1384 } else {
1385 target_bar = (int)(vdev->msix_relo - OFF_AUTOPCIBAR_BAR0);
1388 /* I/O port BARs cannot host MSI-X structures */
1389 if (vdev->bars[target_bar].ioport) {
1390 error_setg(errp, "Invalid MSI-X relocation BAR %d, "
1391 "I/O port BAR", target_bar);
1392 return;
1395 /* Cannot use a BAR in the "shadow" of a 64-bit BAR */
1396 if (!vdev->bars[target_bar].size &&
1397 target_bar > 0 && vdev->bars[target_bar - 1].mem64) {
1398 error_setg(errp, "Invalid MSI-X relocation BAR %d, "
1399 "consumed by 64-bit BAR %d", target_bar, target_bar - 1);
1400 return;
1403 /* 2GB max size for 32-bit BARs, cannot double if already > 1G */
1404 if (vdev->bars[target_bar].size > 1 * GiB &&
1405 !vdev->bars[target_bar].mem64) {
1406 error_setg(errp, "Invalid MSI-X relocation BAR %d, "
1407 "no space to extend 32-bit BAR", target_bar);
1408 return;
1412 * If adding a new BAR, test if we can make it 64bit. We make it
1413 * prefetchable since QEMU MSI-X emulation has no read side effects
1414 * and doing so makes mapping more flexible.
1416 if (!vdev->bars[target_bar].size) {
1417 if (target_bar < (PCI_ROM_SLOT - 1) &&
1418 !vdev->bars[target_bar + 1].size) {
1419 vdev->bars[target_bar].mem64 = true;
1420 vdev->bars[target_bar].type = PCI_BASE_ADDRESS_MEM_TYPE_64;
1422 vdev->bars[target_bar].type |= PCI_BASE_ADDRESS_MEM_PREFETCH;
1423 vdev->bars[target_bar].size = msix_sz;
1424 vdev->msix->table_offset = 0;
1425 } else {
1426 vdev->bars[target_bar].size = MAX(vdev->bars[target_bar].size * 2,
1427 msix_sz * 2);
1429 * Due to above size calc, MSI-X always starts halfway into the BAR,
1430 * which will always be a separate host page.
1432 vdev->msix->table_offset = vdev->bars[target_bar].size / 2;
1435 vdev->msix->table_bar = target_bar;
1436 vdev->msix->pba_bar = target_bar;
1437 /* Requires 8-byte alignment, but PCI_MSIX_ENTRY_SIZE guarantees that */
1438 vdev->msix->pba_offset = vdev->msix->table_offset +
1439 (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE);
1441 trace_vfio_msix_relo(vdev->vbasedev.name,
1442 vdev->msix->table_bar, vdev->msix->table_offset);
1446 * We don't have any control over how pci_add_capability() inserts
1447 * capabilities into the chain. In order to setup MSI-X we need a
1448 * MemoryRegion for the BAR. In order to setup the BAR and not
1449 * attempt to mmap the MSI-X table area, which VFIO won't allow, we
1450 * need to first look for where the MSI-X table lives. So we
1451 * unfortunately split MSI-X setup across two functions.
1453 static void vfio_msix_early_setup(VFIOPCIDevice *vdev, Error **errp)
1455 uint8_t pos;
1456 uint16_t ctrl;
1457 uint32_t table, pba;
1458 int fd = vdev->vbasedev.fd;
1459 VFIOMSIXInfo *msix;
1461 pos = pci_find_capability(&vdev->pdev, PCI_CAP_ID_MSIX);
1462 if (!pos) {
1463 return;
1466 if (pread(fd, &ctrl, sizeof(ctrl),
1467 vdev->config_offset + pos + PCI_MSIX_FLAGS) != sizeof(ctrl)) {
1468 error_setg_errno(errp, errno, "failed to read PCI MSIX FLAGS");
1469 return;
1472 if (pread(fd, &table, sizeof(table),
1473 vdev->config_offset + pos + PCI_MSIX_TABLE) != sizeof(table)) {
1474 error_setg_errno(errp, errno, "failed to read PCI MSIX TABLE");
1475 return;
1478 if (pread(fd, &pba, sizeof(pba),
1479 vdev->config_offset + pos + PCI_MSIX_PBA) != sizeof(pba)) {
1480 error_setg_errno(errp, errno, "failed to read PCI MSIX PBA");
1481 return;
1484 ctrl = le16_to_cpu(ctrl);
1485 table = le32_to_cpu(table);
1486 pba = le32_to_cpu(pba);
1488 msix = g_malloc0(sizeof(*msix));
1489 msix->table_bar = table & PCI_MSIX_FLAGS_BIRMASK;
1490 msix->table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
1491 msix->pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK;
1492 msix->pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
1493 msix->entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
1496 * Test the size of the pba_offset variable and catch if it extends outside
1497 * of the specified BAR. If it is the case, we need to apply a hardware
1498 * specific quirk if the device is known or we have a broken configuration.
1500 if (msix->pba_offset >= vdev->bars[msix->pba_bar].region.size) {
1502 * Chelsio T5 Virtual Function devices are encoded as 0x58xx for T5
1503 * adapters. The T5 hardware returns an incorrect value of 0x8000 for
1504 * the VF PBA offset while the BAR itself is only 8k. The correct value
1505 * is 0x1000, so we hard code that here.
1507 if (vdev->vendor_id == PCI_VENDOR_ID_CHELSIO &&
1508 (vdev->device_id & 0xff00) == 0x5800) {
1509 msix->pba_offset = 0x1000;
1511 * BAIDU KUNLUN Virtual Function devices for KUNLUN AI processor
1512 * return an incorrect value of 0x460000 for the VF PBA offset while
1513 * the BAR itself is only 0x10000. The correct value is 0xb400.
1515 } else if (vfio_pci_is(vdev, PCI_VENDOR_ID_BAIDU,
1516 PCI_DEVICE_ID_KUNLUN_VF)) {
1517 msix->pba_offset = 0xb400;
1518 } else if (vdev->msix_relo == OFF_AUTOPCIBAR_OFF) {
1519 error_setg(errp, "hardware reports invalid configuration, "
1520 "MSIX PBA outside of specified BAR");
1521 g_free(msix);
1522 return;
1526 trace_vfio_msix_early_setup(vdev->vbasedev.name, pos, msix->table_bar,
1527 msix->table_offset, msix->entries);
1528 vdev->msix = msix;
1530 vfio_pci_fixup_msix_region(vdev);
1532 vfio_pci_relocate_msix(vdev, errp);
1535 static int vfio_msix_setup(VFIOPCIDevice *vdev, int pos, Error **errp)
1537 int ret;
1538 Error *err = NULL;
1540 vdev->msix->pending = g_new0(unsigned long,
1541 BITS_TO_LONGS(vdev->msix->entries));
1542 ret = msix_init(&vdev->pdev, vdev->msix->entries,
1543 vdev->bars[vdev->msix->table_bar].mr,
1544 vdev->msix->table_bar, vdev->msix->table_offset,
1545 vdev->bars[vdev->msix->pba_bar].mr,
1546 vdev->msix->pba_bar, vdev->msix->pba_offset, pos,
1547 &err);
1548 if (ret < 0) {
1549 if (ret == -ENOTSUP) {
1550 warn_report_err(err);
1551 return 0;
1554 error_propagate(errp, err);
1555 return ret;
1559 * The PCI spec suggests that devices provide additional alignment for
1560 * MSI-X structures and avoid overlapping non-MSI-X related registers.
1561 * For an assigned device, this hopefully means that emulation of MSI-X
1562 * structures does not affect the performance of the device. If devices
1563 * fail to provide that alignment, a significant performance penalty may
1564 * result, for instance Mellanox MT27500 VFs:
1565 * http://www.spinics.net/lists/kvm/msg125881.html
1567 * The PBA is simply not that important for such a serious regression and
1568 * most drivers do not appear to look at it. The solution for this is to
1569 * disable the PBA MemoryRegion unless it's being used. We disable it
1570 * here and only enable it if a masked vector fires through QEMU. As the
1571 * vector-use notifier is called, which occurs on unmask, we test whether
1572 * PBA emulation is needed and again disable if not.
1574 memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, false);
1577 * The emulated machine may provide a paravirt interface for MSIX setup
1578 * so it is not strictly necessary to emulate MSIX here. This becomes
1579 * helpful when frequently accessed MMIO registers are located in
1580 * subpages adjacent to the MSIX table but the MSIX data containing page
1581 * cannot be mapped because of a host page size bigger than the MSIX table
1582 * alignment.
1584 if (object_property_get_bool(OBJECT(qdev_get_machine()),
1585 "vfio-no-msix-emulation", NULL)) {
1586 memory_region_set_enabled(&vdev->pdev.msix_table_mmio, false);
1589 return 0;
1592 static void vfio_teardown_msi(VFIOPCIDevice *vdev)
1594 msi_uninit(&vdev->pdev);
1596 if (vdev->msix) {
1597 msix_uninit(&vdev->pdev,
1598 vdev->bars[vdev->msix->table_bar].mr,
1599 vdev->bars[vdev->msix->pba_bar].mr);
1600 g_free(vdev->msix->pending);
1605 * Resource setup
1607 static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled)
1609 int i;
1611 for (i = 0; i < PCI_ROM_SLOT; i++) {
1612 vfio_region_mmaps_set_enabled(&vdev->bars[i].region, enabled);
1616 static void vfio_bar_prepare(VFIOPCIDevice *vdev, int nr)
1618 VFIOBAR *bar = &vdev->bars[nr];
1620 uint32_t pci_bar;
1621 int ret;
1623 /* Skip both unimplemented BARs and the upper half of 64bit BARS. */
1624 if (!bar->region.size) {
1625 return;
1628 /* Determine what type of BAR this is for registration */
1629 ret = pread(vdev->vbasedev.fd, &pci_bar, sizeof(pci_bar),
1630 vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));
1631 if (ret != sizeof(pci_bar)) {
1632 error_report("vfio: Failed to read BAR %d (%m)", nr);
1633 return;
1636 pci_bar = le32_to_cpu(pci_bar);
1637 bar->ioport = (pci_bar & PCI_BASE_ADDRESS_SPACE_IO);
1638 bar->mem64 = bar->ioport ? 0 : (pci_bar & PCI_BASE_ADDRESS_MEM_TYPE_64);
1639 bar->type = pci_bar & (bar->ioport ? ~PCI_BASE_ADDRESS_IO_MASK :
1640 ~PCI_BASE_ADDRESS_MEM_MASK);
1641 bar->size = bar->region.size;
1644 static void vfio_bars_prepare(VFIOPCIDevice *vdev)
1646 int i;
1648 for (i = 0; i < PCI_ROM_SLOT; i++) {
1649 vfio_bar_prepare(vdev, i);
1653 static void vfio_bar_register(VFIOPCIDevice *vdev, int nr)
1655 VFIOBAR *bar = &vdev->bars[nr];
1656 char *name;
1658 if (!bar->size) {
1659 return;
1662 bar->mr = g_new0(MemoryRegion, 1);
1663 name = g_strdup_printf("%s base BAR %d", vdev->vbasedev.name, nr);
1664 memory_region_init_io(bar->mr, OBJECT(vdev), NULL, NULL, name, bar->size);
1665 g_free(name);
1667 if (bar->region.size) {
1668 memory_region_add_subregion(bar->mr, 0, bar->region.mem);
1670 if (vfio_region_mmap(&bar->region)) {
1671 error_report("Failed to mmap %s BAR %d. Performance may be slow",
1672 vdev->vbasedev.name, nr);
1676 pci_register_bar(&vdev->pdev, nr, bar->type, bar->mr);
1679 static void vfio_bars_register(VFIOPCIDevice *vdev)
1681 int i;
1683 for (i = 0; i < PCI_ROM_SLOT; i++) {
1684 vfio_bar_register(vdev, i);
1688 static void vfio_bars_exit(VFIOPCIDevice *vdev)
1690 int i;
1692 for (i = 0; i < PCI_ROM_SLOT; i++) {
1693 VFIOBAR *bar = &vdev->bars[i];
1695 vfio_bar_quirk_exit(vdev, i);
1696 vfio_region_exit(&bar->region);
1697 if (bar->region.size) {
1698 memory_region_del_subregion(bar->mr, bar->region.mem);
1702 if (vdev->vga) {
1703 pci_unregister_vga(&vdev->pdev);
1704 vfio_vga_quirk_exit(vdev);
1708 static void vfio_bars_finalize(VFIOPCIDevice *vdev)
1710 int i;
1712 for (i = 0; i < PCI_ROM_SLOT; i++) {
1713 VFIOBAR *bar = &vdev->bars[i];
1715 vfio_bar_quirk_finalize(vdev, i);
1716 vfio_region_finalize(&bar->region);
1717 if (bar->size) {
1718 object_unparent(OBJECT(bar->mr));
1719 g_free(bar->mr);
1723 if (vdev->vga) {
1724 vfio_vga_quirk_finalize(vdev);
1725 for (i = 0; i < ARRAY_SIZE(vdev->vga->region); i++) {
1726 object_unparent(OBJECT(&vdev->vga->region[i].mem));
1728 g_free(vdev->vga);
1733 * General setup
1735 static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos)
1737 uint8_t tmp;
1738 uint16_t next = PCI_CONFIG_SPACE_SIZE;
1740 for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp;
1741 tmp = pdev->config[tmp + PCI_CAP_LIST_NEXT]) {
1742 if (tmp > pos && tmp < next) {
1743 next = tmp;
1747 return next - pos;
1751 static uint16_t vfio_ext_cap_max_size(const uint8_t *config, uint16_t pos)
1753 uint16_t tmp, next = PCIE_CONFIG_SPACE_SIZE;
1755 for (tmp = PCI_CONFIG_SPACE_SIZE; tmp;
1756 tmp = PCI_EXT_CAP_NEXT(pci_get_long(config + tmp))) {
1757 if (tmp > pos && tmp < next) {
1758 next = tmp;
1762 return next - pos;
1765 static void vfio_set_word_bits(uint8_t *buf, uint16_t val, uint16_t mask)
1767 pci_set_word(buf, (pci_get_word(buf) & ~mask) | val);
1770 static void vfio_add_emulated_word(VFIOPCIDevice *vdev, int pos,
1771 uint16_t val, uint16_t mask)
1773 vfio_set_word_bits(vdev->pdev.config + pos, val, mask);
1774 vfio_set_word_bits(vdev->pdev.wmask + pos, ~mask, mask);
1775 vfio_set_word_bits(vdev->emulated_config_bits + pos, mask, mask);
1778 static void vfio_set_long_bits(uint8_t *buf, uint32_t val, uint32_t mask)
1780 pci_set_long(buf, (pci_get_long(buf) & ~mask) | val);
1783 static void vfio_add_emulated_long(VFIOPCIDevice *vdev, int pos,
1784 uint32_t val, uint32_t mask)
1786 vfio_set_long_bits(vdev->pdev.config + pos, val, mask);
1787 vfio_set_long_bits(vdev->pdev.wmask + pos, ~mask, mask);
1788 vfio_set_long_bits(vdev->emulated_config_bits + pos, mask, mask);
1791 static int vfio_setup_pcie_cap(VFIOPCIDevice *vdev, int pos, uint8_t size,
1792 Error **errp)
1794 uint16_t flags;
1795 uint8_t type;
1797 flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS);
1798 type = (flags & PCI_EXP_FLAGS_TYPE) >> 4;
1800 if (type != PCI_EXP_TYPE_ENDPOINT &&
1801 type != PCI_EXP_TYPE_LEG_END &&
1802 type != PCI_EXP_TYPE_RC_END) {
1804 error_setg(errp, "assignment of PCIe type 0x%x "
1805 "devices is not currently supported", type);
1806 return -EINVAL;
1809 if (!pci_bus_is_express(pci_get_bus(&vdev->pdev))) {
1810 PCIBus *bus = pci_get_bus(&vdev->pdev);
1811 PCIDevice *bridge;
1814 * Traditionally PCI device assignment exposes the PCIe capability
1815 * as-is on non-express buses. The reason being that some drivers
1816 * simply assume that it's there, for example tg3. However when
1817 * we're running on a native PCIe machine type, like Q35, we need
1818 * to hide the PCIe capability. The reason for this is twofold;
1819 * first Windows guests get a Code 10 error when the PCIe capability
1820 * is exposed in this configuration. Therefore express devices won't
1821 * work at all unless they're attached to express buses in the VM.
1822 * Second, a native PCIe machine introduces the possibility of fine
1823 * granularity IOMMUs supporting both translation and isolation.
1824 * Guest code to discover the IOMMU visibility of a device, such as
1825 * IOMMU grouping code on Linux, is very aware of device types and
1826 * valid transitions between bus types. An express device on a non-
1827 * express bus is not a valid combination on bare metal systems.
1829 * Drivers that require a PCIe capability to make the device
1830 * functional are simply going to need to have their devices placed
1831 * on a PCIe bus in the VM.
1833 while (!pci_bus_is_root(bus)) {
1834 bridge = pci_bridge_get_device(bus);
1835 bus = pci_get_bus(bridge);
1838 if (pci_bus_is_express(bus)) {
1839 return 0;
1842 } else if (pci_bus_is_root(pci_get_bus(&vdev->pdev))) {
1844 * On a Root Complex bus Endpoints become Root Complex Integrated
1845 * Endpoints, which changes the type and clears the LNK & LNK2 fields.
1847 if (type == PCI_EXP_TYPE_ENDPOINT) {
1848 vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
1849 PCI_EXP_TYPE_RC_END << 4,
1850 PCI_EXP_FLAGS_TYPE);
1852 /* Link Capabilities, Status, and Control goes away */
1853 if (size > PCI_EXP_LNKCTL) {
1854 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0);
1855 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
1856 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0);
1858 #ifndef PCI_EXP_LNKCAP2
1859 #define PCI_EXP_LNKCAP2 44
1860 #endif
1861 #ifndef PCI_EXP_LNKSTA2
1862 #define PCI_EXP_LNKSTA2 50
1863 #endif
1864 /* Link 2 Capabilities, Status, and Control goes away */
1865 if (size > PCI_EXP_LNKCAP2) {
1866 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0);
1867 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0);
1868 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0);
1872 } else if (type == PCI_EXP_TYPE_LEG_END) {
1874 * Legacy endpoints don't belong on the root complex. Windows
1875 * seems to be happier with devices if we skip the capability.
1877 return 0;
1880 } else {
1882 * Convert Root Complex Integrated Endpoints to regular endpoints.
1883 * These devices don't support LNK/LNK2 capabilities, so make them up.
1885 if (type == PCI_EXP_TYPE_RC_END) {
1886 vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
1887 PCI_EXP_TYPE_ENDPOINT << 4,
1888 PCI_EXP_FLAGS_TYPE);
1889 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP,
1890 QEMU_PCI_EXP_LNKCAP_MLW(QEMU_PCI_EXP_LNK_X1) |
1891 QEMU_PCI_EXP_LNKCAP_MLS(QEMU_PCI_EXP_LNK_2_5GT), ~0);
1892 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
1897 * Intel 82599 SR-IOV VFs report an invalid PCIe capability version 0
1898 * (Niantic errate #35) causing Windows to error with a Code 10 for the
1899 * device on Q35. Fixup any such devices to report version 1. If we
1900 * were to remove the capability entirely the guest would lose extended
1901 * config space.
1903 if ((flags & PCI_EXP_FLAGS_VERS) == 0) {
1904 vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
1905 1, PCI_EXP_FLAGS_VERS);
1908 pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size,
1909 errp);
1910 if (pos < 0) {
1911 return pos;
1914 vdev->pdev.exp.exp_cap = pos;
1916 return pos;
1919 static void vfio_check_pcie_flr(VFIOPCIDevice *vdev, uint8_t pos)
1921 uint32_t cap = pci_get_long(vdev->pdev.config + pos + PCI_EXP_DEVCAP);
1923 if (cap & PCI_EXP_DEVCAP_FLR) {
1924 trace_vfio_check_pcie_flr(vdev->vbasedev.name);
1925 vdev->has_flr = true;
1929 static void vfio_check_pm_reset(VFIOPCIDevice *vdev, uint8_t pos)
1931 uint16_t csr = pci_get_word(vdev->pdev.config + pos + PCI_PM_CTRL);
1933 if (!(csr & PCI_PM_CTRL_NO_SOFT_RESET)) {
1934 trace_vfio_check_pm_reset(vdev->vbasedev.name);
1935 vdev->has_pm_reset = true;
1939 static void vfio_check_af_flr(VFIOPCIDevice *vdev, uint8_t pos)
1941 uint8_t cap = pci_get_byte(vdev->pdev.config + pos + PCI_AF_CAP);
1943 if ((cap & PCI_AF_CAP_TP) && (cap & PCI_AF_CAP_FLR)) {
1944 trace_vfio_check_af_flr(vdev->vbasedev.name);
1945 vdev->has_flr = true;
1949 static int vfio_add_std_cap(VFIOPCIDevice *vdev, uint8_t pos, Error **errp)
1951 PCIDevice *pdev = &vdev->pdev;
1952 uint8_t cap_id, next, size;
1953 int ret;
1955 cap_id = pdev->config[pos];
1956 next = pdev->config[pos + PCI_CAP_LIST_NEXT];
1959 * If it becomes important to configure capabilities to their actual
1960 * size, use this as the default when it's something we don't recognize.
1961 * Since QEMU doesn't actually handle many of the config accesses,
1962 * exact size doesn't seem worthwhile.
1964 size = vfio_std_cap_max_size(pdev, pos);
1967 * pci_add_capability always inserts the new capability at the head
1968 * of the chain. Therefore to end up with a chain that matches the
1969 * physical device, we insert from the end by making this recursive.
1970 * This is also why we pre-calculate size above as cached config space
1971 * will be changed as we unwind the stack.
1973 if (next) {
1974 ret = vfio_add_std_cap(vdev, next, errp);
1975 if (ret) {
1976 return ret;
1978 } else {
1979 /* Begin the rebuild, use QEMU emulated list bits */
1980 pdev->config[PCI_CAPABILITY_LIST] = 0;
1981 vdev->emulated_config_bits[PCI_CAPABILITY_LIST] = 0xff;
1982 vdev->emulated_config_bits[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1984 ret = vfio_add_virt_caps(vdev, errp);
1985 if (ret) {
1986 return ret;
1990 /* Scale down size, esp in case virt caps were added above */
1991 size = MIN(size, vfio_std_cap_max_size(pdev, pos));
1993 /* Use emulated next pointer to allow dropping caps */
1994 pci_set_byte(vdev->emulated_config_bits + pos + PCI_CAP_LIST_NEXT, 0xff);
1996 switch (cap_id) {
1997 case PCI_CAP_ID_MSI:
1998 ret = vfio_msi_setup(vdev, pos, errp);
1999 break;
2000 case PCI_CAP_ID_EXP:
2001 vfio_check_pcie_flr(vdev, pos);
2002 ret = vfio_setup_pcie_cap(vdev, pos, size, errp);
2003 break;
2004 case PCI_CAP_ID_MSIX:
2005 ret = vfio_msix_setup(vdev, pos, errp);
2006 break;
2007 case PCI_CAP_ID_PM:
2008 vfio_check_pm_reset(vdev, pos);
2009 vdev->pm_cap = pos;
2010 ret = pci_add_capability(pdev, cap_id, pos, size, errp);
2011 break;
2012 case PCI_CAP_ID_AF:
2013 vfio_check_af_flr(vdev, pos);
2014 ret = pci_add_capability(pdev, cap_id, pos, size, errp);
2015 break;
2016 default:
2017 ret = pci_add_capability(pdev, cap_id, pos, size, errp);
2018 break;
2021 if (ret < 0) {
2022 error_prepend(errp,
2023 "failed to add PCI capability 0x%x[0x%x]@0x%x: ",
2024 cap_id, size, pos);
2025 return ret;
2028 return 0;
2031 static void vfio_add_ext_cap(VFIOPCIDevice *vdev)
2033 PCIDevice *pdev = &vdev->pdev;
2034 uint32_t header;
2035 uint16_t cap_id, next, size;
2036 uint8_t cap_ver;
2037 uint8_t *config;
2039 /* Only add extended caps if we have them and the guest can see them */
2040 if (!pci_is_express(pdev) || !pci_bus_is_express(pci_get_bus(pdev)) ||
2041 !pci_get_long(pdev->config + PCI_CONFIG_SPACE_SIZE)) {
2042 return;
2046 * pcie_add_capability always inserts the new capability at the tail
2047 * of the chain. Therefore to end up with a chain that matches the
2048 * physical device, we cache the config space to avoid overwriting
2049 * the original config space when we parse the extended capabilities.
2051 config = g_memdup(pdev->config, vdev->config_size);
2054 * Extended capabilities are chained with each pointing to the next, so we
2055 * can drop anything other than the head of the chain simply by modifying
2056 * the previous next pointer. Seed the head of the chain here such that
2057 * we can simply skip any capabilities we want to drop below, regardless
2058 * of their position in the chain. If this stub capability still exists
2059 * after we add the capabilities we want to expose, update the capability
2060 * ID to zero. Note that we cannot seed with the capability header being
2061 * zero as this conflicts with definition of an absent capability chain
2062 * and prevents capabilities beyond the head of the list from being added.
2063 * By replacing the dummy capability ID with zero after walking the device
2064 * chain, we also transparently mark extended capabilities as absent if
2065 * no capabilities were added. Note that the PCIe spec defines an absence
2066 * of extended capabilities to be determined by a value of zero for the
2067 * capability ID, version, AND next pointer. A non-zero next pointer
2068 * should be sufficient to indicate additional capabilities are present,
2069 * which will occur if we call pcie_add_capability() below. The entire
2070 * first dword is emulated to support this.
2072 * NB. The kernel side does similar masking, so be prepared that our
2073 * view of the device may also contain a capability ID zero in the head
2074 * of the chain. Skip it for the same reason that we cannot seed the
2075 * chain with a zero capability.
2077 pci_set_long(pdev->config + PCI_CONFIG_SPACE_SIZE,
2078 PCI_EXT_CAP(0xFFFF, 0, 0));
2079 pci_set_long(pdev->wmask + PCI_CONFIG_SPACE_SIZE, 0);
2080 pci_set_long(vdev->emulated_config_bits + PCI_CONFIG_SPACE_SIZE, ~0);
2082 for (next = PCI_CONFIG_SPACE_SIZE; next;
2083 next = PCI_EXT_CAP_NEXT(pci_get_long(config + next))) {
2084 header = pci_get_long(config + next);
2085 cap_id = PCI_EXT_CAP_ID(header);
2086 cap_ver = PCI_EXT_CAP_VER(header);
2089 * If it becomes important to configure extended capabilities to their
2090 * actual size, use this as the default when it's something we don't
2091 * recognize. Since QEMU doesn't actually handle many of the config
2092 * accesses, exact size doesn't seem worthwhile.
2094 size = vfio_ext_cap_max_size(config, next);
2096 /* Use emulated next pointer to allow dropping extended caps */
2097 pci_long_test_and_set_mask(vdev->emulated_config_bits + next,
2098 PCI_EXT_CAP_NEXT_MASK);
2100 switch (cap_id) {
2101 case 0: /* kernel masked capability */
2102 case PCI_EXT_CAP_ID_SRIOV: /* Read-only VF BARs confuse OVMF */
2103 case PCI_EXT_CAP_ID_ARI: /* XXX Needs next function virtualization */
2104 case PCI_EXT_CAP_ID_REBAR: /* Can't expose read-only */
2105 trace_vfio_add_ext_cap_dropped(vdev->vbasedev.name, cap_id, next);
2106 break;
2107 default:
2108 pcie_add_capability(pdev, cap_id, cap_ver, next, size);
2113 /* Cleanup chain head ID if necessary */
2114 if (pci_get_word(pdev->config + PCI_CONFIG_SPACE_SIZE) == 0xFFFF) {
2115 pci_set_word(pdev->config + PCI_CONFIG_SPACE_SIZE, 0);
2118 g_free(config);
2119 return;
2122 static int vfio_add_capabilities(VFIOPCIDevice *vdev, Error **errp)
2124 PCIDevice *pdev = &vdev->pdev;
2125 int ret;
2127 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
2128 !pdev->config[PCI_CAPABILITY_LIST]) {
2129 return 0; /* Nothing to add */
2132 ret = vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST], errp);
2133 if (ret) {
2134 return ret;
2137 vfio_add_ext_cap(vdev);
2138 return 0;
2141 static void vfio_pci_pre_reset(VFIOPCIDevice *vdev)
2143 PCIDevice *pdev = &vdev->pdev;
2144 uint16_t cmd;
2146 vfio_disable_interrupts(vdev);
2148 /* Make sure the device is in D0 */
2149 if (vdev->pm_cap) {
2150 uint16_t pmcsr;
2151 uint8_t state;
2153 pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2154 state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2155 if (state) {
2156 pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
2157 vfio_pci_write_config(pdev, vdev->pm_cap + PCI_PM_CTRL, pmcsr, 2);
2158 /* vfio handles the necessary delay here */
2159 pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2160 state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2161 if (state) {
2162 error_report("vfio: Unable to power on device, stuck in D%d",
2163 state);
2169 * Stop any ongoing DMA by disconnecting I/O, MMIO, and bus master.
2170 * Also put INTx Disable in known state.
2172 cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2);
2173 cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
2174 PCI_COMMAND_INTX_DISABLE);
2175 vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2);
2178 static void vfio_pci_post_reset(VFIOPCIDevice *vdev)
2180 Error *err = NULL;
2181 int nr;
2183 vfio_intx_enable(vdev, &err);
2184 if (err) {
2185 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2188 for (nr = 0; nr < PCI_NUM_REGIONS - 1; ++nr) {
2189 off_t addr = vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr);
2190 uint32_t val = 0;
2191 uint32_t len = sizeof(val);
2193 if (pwrite(vdev->vbasedev.fd, &val, len, addr) != len) {
2194 error_report("%s(%s) reset bar %d failed: %m", __func__,
2195 vdev->vbasedev.name, nr);
2199 vfio_quirk_reset(vdev);
2202 static bool vfio_pci_host_match(PCIHostDeviceAddress *addr, const char *name)
2204 char tmp[13];
2206 sprintf(tmp, "%04x:%02x:%02x.%1x", addr->domain,
2207 addr->bus, addr->slot, addr->function);
2209 return (strcmp(tmp, name) == 0);
2212 static int vfio_pci_hot_reset(VFIOPCIDevice *vdev, bool single)
2214 VFIOGroup *group;
2215 struct vfio_pci_hot_reset_info *info;
2216 struct vfio_pci_dependent_device *devices;
2217 struct vfio_pci_hot_reset *reset;
2218 int32_t *fds;
2219 int ret, i, count;
2220 bool multi = false;
2222 trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
2224 if (!single) {
2225 vfio_pci_pre_reset(vdev);
2227 vdev->vbasedev.needs_reset = false;
2229 info = g_malloc0(sizeof(*info));
2230 info->argsz = sizeof(*info);
2232 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
2233 if (ret && errno != ENOSPC) {
2234 ret = -errno;
2235 if (!vdev->has_pm_reset) {
2236 error_report("vfio: Cannot reset device %s, "
2237 "no available reset mechanism.", vdev->vbasedev.name);
2239 goto out_single;
2242 count = info->count;
2243 info = g_realloc(info, sizeof(*info) + (count * sizeof(*devices)));
2244 info->argsz = sizeof(*info) + (count * sizeof(*devices));
2245 devices = &info->devices[0];
2247 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
2248 if (ret) {
2249 ret = -errno;
2250 error_report("vfio: hot reset info failed: %m");
2251 goto out_single;
2254 trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
2256 /* Verify that we have all the groups required */
2257 for (i = 0; i < info->count; i++) {
2258 PCIHostDeviceAddress host;
2259 VFIOPCIDevice *tmp;
2260 VFIODevice *vbasedev_iter;
2262 host.domain = devices[i].segment;
2263 host.bus = devices[i].bus;
2264 host.slot = PCI_SLOT(devices[i].devfn);
2265 host.function = PCI_FUNC(devices[i].devfn);
2267 trace_vfio_pci_hot_reset_dep_devices(host.domain,
2268 host.bus, host.slot, host.function, devices[i].group_id);
2270 if (vfio_pci_host_match(&host, vdev->vbasedev.name)) {
2271 continue;
2274 QLIST_FOREACH(group, &vfio_group_list, next) {
2275 if (group->groupid == devices[i].group_id) {
2276 break;
2280 if (!group) {
2281 if (!vdev->has_pm_reset) {
2282 error_report("vfio: Cannot reset device %s, "
2283 "depends on group %d which is not owned.",
2284 vdev->vbasedev.name, devices[i].group_id);
2286 ret = -EPERM;
2287 goto out;
2290 /* Prep dependent devices for reset and clear our marker. */
2291 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2292 if (!vbasedev_iter->dev->realized ||
2293 vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
2294 continue;
2296 tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
2297 if (vfio_pci_host_match(&host, tmp->vbasedev.name)) {
2298 if (single) {
2299 ret = -EINVAL;
2300 goto out_single;
2302 vfio_pci_pre_reset(tmp);
2303 tmp->vbasedev.needs_reset = false;
2304 multi = true;
2305 break;
2310 if (!single && !multi) {
2311 ret = -EINVAL;
2312 goto out_single;
2315 /* Determine how many group fds need to be passed */
2316 count = 0;
2317 QLIST_FOREACH(group, &vfio_group_list, next) {
2318 for (i = 0; i < info->count; i++) {
2319 if (group->groupid == devices[i].group_id) {
2320 count++;
2321 break;
2326 reset = g_malloc0(sizeof(*reset) + (count * sizeof(*fds)));
2327 reset->argsz = sizeof(*reset) + (count * sizeof(*fds));
2328 fds = &reset->group_fds[0];
2330 /* Fill in group fds */
2331 QLIST_FOREACH(group, &vfio_group_list, next) {
2332 for (i = 0; i < info->count; i++) {
2333 if (group->groupid == devices[i].group_id) {
2334 fds[reset->count++] = group->fd;
2335 break;
2340 /* Bus reset! */
2341 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
2342 g_free(reset);
2344 trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
2345 ret ? "%m" : "Success");
2347 out:
2348 /* Re-enable INTx on affected devices */
2349 for (i = 0; i < info->count; i++) {
2350 PCIHostDeviceAddress host;
2351 VFIOPCIDevice *tmp;
2352 VFIODevice *vbasedev_iter;
2354 host.domain = devices[i].segment;
2355 host.bus = devices[i].bus;
2356 host.slot = PCI_SLOT(devices[i].devfn);
2357 host.function = PCI_FUNC(devices[i].devfn);
2359 if (vfio_pci_host_match(&host, vdev->vbasedev.name)) {
2360 continue;
2363 QLIST_FOREACH(group, &vfio_group_list, next) {
2364 if (group->groupid == devices[i].group_id) {
2365 break;
2369 if (!group) {
2370 break;
2373 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2374 if (!vbasedev_iter->dev->realized ||
2375 vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
2376 continue;
2378 tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
2379 if (vfio_pci_host_match(&host, tmp->vbasedev.name)) {
2380 vfio_pci_post_reset(tmp);
2381 break;
2385 out_single:
2386 if (!single) {
2387 vfio_pci_post_reset(vdev);
2389 g_free(info);
2391 return ret;
2395 * We want to differentiate hot reset of multiple in-use devices vs hot reset
2396 * of a single in-use device. VFIO_DEVICE_RESET will already handle the case
2397 * of doing hot resets when there is only a single device per bus. The in-use
2398 * here refers to how many VFIODevices are affected. A hot reset that affects
2399 * multiple devices, but only a single in-use device, means that we can call
2400 * it from our bus ->reset() callback since the extent is effectively a single
2401 * device. This allows us to make use of it in the hotplug path. When there
2402 * are multiple in-use devices, we can only trigger the hot reset during a
2403 * system reset and thus from our reset handler. We separate _one vs _multi
2404 * here so that we don't overlap and do a double reset on the system reset
2405 * path where both our reset handler and ->reset() callback are used. Calling
2406 * _one() will only do a hot reset for the one in-use devices case, calling
2407 * _multi() will do nothing if a _one() would have been sufficient.
2409 static int vfio_pci_hot_reset_one(VFIOPCIDevice *vdev)
2411 return vfio_pci_hot_reset(vdev, true);
2414 static int vfio_pci_hot_reset_multi(VFIODevice *vbasedev)
2416 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2417 return vfio_pci_hot_reset(vdev, false);
2420 static void vfio_pci_compute_needs_reset(VFIODevice *vbasedev)
2422 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2423 if (!vbasedev->reset_works || (!vdev->has_flr && vdev->has_pm_reset)) {
2424 vbasedev->needs_reset = true;
2428 static Object *vfio_pci_get_object(VFIODevice *vbasedev)
2430 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2432 return OBJECT(vdev);
2435 static bool vfio_msix_present(void *opaque, int version_id)
2437 PCIDevice *pdev = opaque;
2439 return msix_present(pdev);
2442 const VMStateDescription vmstate_vfio_pci_config = {
2443 .name = "VFIOPCIDevice",
2444 .version_id = 1,
2445 .minimum_version_id = 1,
2446 .fields = (VMStateField[]) {
2447 VMSTATE_PCI_DEVICE(pdev, VFIOPCIDevice),
2448 VMSTATE_MSIX_TEST(pdev, VFIOPCIDevice, vfio_msix_present),
2449 VMSTATE_END_OF_LIST()
2453 static void vfio_pci_save_config(VFIODevice *vbasedev, QEMUFile *f)
2455 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2457 vmstate_save_state(f, &vmstate_vfio_pci_config, vdev, NULL);
2460 static int vfio_pci_load_config(VFIODevice *vbasedev, QEMUFile *f)
2462 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2463 PCIDevice *pdev = &vdev->pdev;
2464 pcibus_t old_addr[PCI_NUM_REGIONS - 1];
2465 int bar, ret;
2467 for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
2468 old_addr[bar] = pdev->io_regions[bar].addr;
2471 ret = vmstate_load_state(f, &vmstate_vfio_pci_config, vdev, 1);
2472 if (ret) {
2473 return ret;
2476 vfio_pci_write_config(pdev, PCI_COMMAND,
2477 pci_get_word(pdev->config + PCI_COMMAND), 2);
2479 for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
2481 * The address may not be changed in some scenarios
2482 * (e.g. the VF driver isn't loaded in VM).
2484 if (old_addr[bar] != pdev->io_regions[bar].addr &&
2485 vdev->bars[bar].region.size > 0 &&
2486 vdev->bars[bar].region.size < qemu_real_host_page_size()) {
2487 vfio_sub_page_bar_update_mapping(pdev, bar);
2491 if (msi_enabled(pdev)) {
2492 vfio_msi_enable(vdev);
2493 } else if (msix_enabled(pdev)) {
2494 vfio_msix_enable(vdev);
2497 return ret;
2500 static VFIODeviceOps vfio_pci_ops = {
2501 .vfio_compute_needs_reset = vfio_pci_compute_needs_reset,
2502 .vfio_hot_reset_multi = vfio_pci_hot_reset_multi,
2503 .vfio_eoi = vfio_intx_eoi,
2504 .vfio_get_object = vfio_pci_get_object,
2505 .vfio_save_config = vfio_pci_save_config,
2506 .vfio_load_config = vfio_pci_load_config,
2509 int vfio_populate_vga(VFIOPCIDevice *vdev, Error **errp)
2511 VFIODevice *vbasedev = &vdev->vbasedev;
2512 struct vfio_region_info *reg_info;
2513 int ret;
2515 ret = vfio_get_region_info(vbasedev, VFIO_PCI_VGA_REGION_INDEX, &reg_info);
2516 if (ret) {
2517 error_setg_errno(errp, -ret,
2518 "failed getting region info for VGA region index %d",
2519 VFIO_PCI_VGA_REGION_INDEX);
2520 return ret;
2523 if (!(reg_info->flags & VFIO_REGION_INFO_FLAG_READ) ||
2524 !(reg_info->flags & VFIO_REGION_INFO_FLAG_WRITE) ||
2525 reg_info->size < 0xbffff + 1) {
2526 error_setg(errp, "unexpected VGA info, flags 0x%lx, size 0x%lx",
2527 (unsigned long)reg_info->flags,
2528 (unsigned long)reg_info->size);
2529 g_free(reg_info);
2530 return -EINVAL;
2533 vdev->vga = g_new0(VFIOVGA, 1);
2535 vdev->vga->fd_offset = reg_info->offset;
2536 vdev->vga->fd = vdev->vbasedev.fd;
2538 g_free(reg_info);
2540 vdev->vga->region[QEMU_PCI_VGA_MEM].offset = QEMU_PCI_VGA_MEM_BASE;
2541 vdev->vga->region[QEMU_PCI_VGA_MEM].nr = QEMU_PCI_VGA_MEM;
2542 QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_MEM].quirks);
2544 memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_MEM].mem,
2545 OBJECT(vdev), &vfio_vga_ops,
2546 &vdev->vga->region[QEMU_PCI_VGA_MEM],
2547 "vfio-vga-mmio@0xa0000",
2548 QEMU_PCI_VGA_MEM_SIZE);
2550 vdev->vga->region[QEMU_PCI_VGA_IO_LO].offset = QEMU_PCI_VGA_IO_LO_BASE;
2551 vdev->vga->region[QEMU_PCI_VGA_IO_LO].nr = QEMU_PCI_VGA_IO_LO;
2552 QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].quirks);
2554 memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem,
2555 OBJECT(vdev), &vfio_vga_ops,
2556 &vdev->vga->region[QEMU_PCI_VGA_IO_LO],
2557 "vfio-vga-io@0x3b0",
2558 QEMU_PCI_VGA_IO_LO_SIZE);
2560 vdev->vga->region[QEMU_PCI_VGA_IO_HI].offset = QEMU_PCI_VGA_IO_HI_BASE;
2561 vdev->vga->region[QEMU_PCI_VGA_IO_HI].nr = QEMU_PCI_VGA_IO_HI;
2562 QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].quirks);
2564 memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem,
2565 OBJECT(vdev), &vfio_vga_ops,
2566 &vdev->vga->region[QEMU_PCI_VGA_IO_HI],
2567 "vfio-vga-io@0x3c0",
2568 QEMU_PCI_VGA_IO_HI_SIZE);
2570 pci_register_vga(&vdev->pdev, &vdev->vga->region[QEMU_PCI_VGA_MEM].mem,
2571 &vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem,
2572 &vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem);
2574 return 0;
2577 static void vfio_populate_device(VFIOPCIDevice *vdev, Error **errp)
2579 VFIODevice *vbasedev = &vdev->vbasedev;
2580 struct vfio_region_info *reg_info;
2581 struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };
2582 int i, ret = -1;
2584 /* Sanity check device */
2585 if (!(vbasedev->flags & VFIO_DEVICE_FLAGS_PCI)) {
2586 error_setg(errp, "this isn't a PCI device");
2587 return;
2590 if (vbasedev->num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) {
2591 error_setg(errp, "unexpected number of io regions %u",
2592 vbasedev->num_regions);
2593 return;
2596 if (vbasedev->num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) {
2597 error_setg(errp, "unexpected number of irqs %u", vbasedev->num_irqs);
2598 return;
2601 for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
2602 char *name = g_strdup_printf("%s BAR %d", vbasedev->name, i);
2604 ret = vfio_region_setup(OBJECT(vdev), vbasedev,
2605 &vdev->bars[i].region, i, name);
2606 g_free(name);
2608 if (ret) {
2609 error_setg_errno(errp, -ret, "failed to get region %d info", i);
2610 return;
2613 QLIST_INIT(&vdev->bars[i].quirks);
2616 ret = vfio_get_region_info(vbasedev,
2617 VFIO_PCI_CONFIG_REGION_INDEX, &reg_info);
2618 if (ret) {
2619 error_setg_errno(errp, -ret, "failed to get config info");
2620 return;
2623 trace_vfio_populate_device_config(vdev->vbasedev.name,
2624 (unsigned long)reg_info->size,
2625 (unsigned long)reg_info->offset,
2626 (unsigned long)reg_info->flags);
2628 vdev->config_size = reg_info->size;
2629 if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) {
2630 vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS;
2632 vdev->config_offset = reg_info->offset;
2634 g_free(reg_info);
2636 if (vdev->features & VFIO_FEATURE_ENABLE_VGA) {
2637 ret = vfio_populate_vga(vdev, errp);
2638 if (ret) {
2639 error_append_hint(errp, "device does not support "
2640 "requested feature x-vga\n");
2641 return;
2645 irq_info.index = VFIO_PCI_ERR_IRQ_INDEX;
2647 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);
2648 if (ret) {
2649 /* This can fail for an old kernel or legacy PCI dev */
2650 trace_vfio_populate_device_get_irq_info_failure(strerror(errno));
2651 } else if (irq_info.count == 1) {
2652 vdev->pci_aer = true;
2653 } else {
2654 warn_report(VFIO_MSG_PREFIX
2655 "Could not enable error recovery for the device",
2656 vbasedev->name);
2660 static void vfio_put_device(VFIOPCIDevice *vdev)
2662 g_free(vdev->vbasedev.name);
2663 g_free(vdev->msix);
2665 vfio_put_base_device(&vdev->vbasedev);
2668 static void vfio_err_notifier_handler(void *opaque)
2670 VFIOPCIDevice *vdev = opaque;
2672 if (!event_notifier_test_and_clear(&vdev->err_notifier)) {
2673 return;
2677 * TBD. Retrieve the error details and decide what action
2678 * needs to be taken. One of the actions could be to pass
2679 * the error to the guest and have the guest driver recover
2680 * from the error. This requires that PCIe capabilities be
2681 * exposed to the guest. For now, we just terminate the
2682 * guest to contain the error.
2685 error_report("%s(%s) Unrecoverable error detected. Please collect any data possible and then kill the guest", __func__, vdev->vbasedev.name);
2687 vm_stop(RUN_STATE_INTERNAL_ERROR);
2691 * Registers error notifier for devices supporting error recovery.
2692 * If we encounter a failure in this function, we report an error
2693 * and continue after disabling error recovery support for the
2694 * device.
2696 static void vfio_register_err_notifier(VFIOPCIDevice *vdev)
2698 Error *err = NULL;
2699 int32_t fd;
2701 if (!vdev->pci_aer) {
2702 return;
2705 if (event_notifier_init(&vdev->err_notifier, 0)) {
2706 error_report("vfio: Unable to init event notifier for error detection");
2707 vdev->pci_aer = false;
2708 return;
2711 fd = event_notifier_get_fd(&vdev->err_notifier);
2712 qemu_set_fd_handler(fd, vfio_err_notifier_handler, NULL, vdev);
2714 if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_ERR_IRQ_INDEX, 0,
2715 VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
2716 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2717 qemu_set_fd_handler(fd, NULL, NULL, vdev);
2718 event_notifier_cleanup(&vdev->err_notifier);
2719 vdev->pci_aer = false;
2723 static void vfio_unregister_err_notifier(VFIOPCIDevice *vdev)
2725 Error *err = NULL;
2727 if (!vdev->pci_aer) {
2728 return;
2731 if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_ERR_IRQ_INDEX, 0,
2732 VFIO_IRQ_SET_ACTION_TRIGGER, -1, &err)) {
2733 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2735 qemu_set_fd_handler(event_notifier_get_fd(&vdev->err_notifier),
2736 NULL, NULL, vdev);
2737 event_notifier_cleanup(&vdev->err_notifier);
2740 static void vfio_req_notifier_handler(void *opaque)
2742 VFIOPCIDevice *vdev = opaque;
2743 Error *err = NULL;
2745 if (!event_notifier_test_and_clear(&vdev->req_notifier)) {
2746 return;
2749 qdev_unplug(DEVICE(vdev), &err);
2750 if (err) {
2751 warn_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2755 static void vfio_register_req_notifier(VFIOPCIDevice *vdev)
2757 struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info),
2758 .index = VFIO_PCI_REQ_IRQ_INDEX };
2759 Error *err = NULL;
2760 int32_t fd;
2762 if (!(vdev->features & VFIO_FEATURE_ENABLE_REQ)) {
2763 return;
2766 if (ioctl(vdev->vbasedev.fd,
2767 VFIO_DEVICE_GET_IRQ_INFO, &irq_info) < 0 || irq_info.count < 1) {
2768 return;
2771 if (event_notifier_init(&vdev->req_notifier, 0)) {
2772 error_report("vfio: Unable to init event notifier for device request");
2773 return;
2776 fd = event_notifier_get_fd(&vdev->req_notifier);
2777 qemu_set_fd_handler(fd, vfio_req_notifier_handler, NULL, vdev);
2779 if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_REQ_IRQ_INDEX, 0,
2780 VFIO_IRQ_SET_ACTION_TRIGGER, fd, &err)) {
2781 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2782 qemu_set_fd_handler(fd, NULL, NULL, vdev);
2783 event_notifier_cleanup(&vdev->req_notifier);
2784 } else {
2785 vdev->req_enabled = true;
2789 static void vfio_unregister_req_notifier(VFIOPCIDevice *vdev)
2791 Error *err = NULL;
2793 if (!vdev->req_enabled) {
2794 return;
2797 if (vfio_set_irq_signaling(&vdev->vbasedev, VFIO_PCI_REQ_IRQ_INDEX, 0,
2798 VFIO_IRQ_SET_ACTION_TRIGGER, -1, &err)) {
2799 error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
2801 qemu_set_fd_handler(event_notifier_get_fd(&vdev->req_notifier),
2802 NULL, NULL, vdev);
2803 event_notifier_cleanup(&vdev->req_notifier);
2805 vdev->req_enabled = false;
2808 static void vfio_realize(PCIDevice *pdev, Error **errp)
2810 VFIOPCIDevice *vdev = VFIO_PCI(pdev);
2811 VFIODevice *vbasedev_iter;
2812 VFIOGroup *group;
2813 char *tmp, *subsys, group_path[PATH_MAX], *group_name;
2814 Error *err = NULL;
2815 ssize_t len;
2816 struct stat st;
2817 int groupid;
2818 int i, ret;
2819 bool is_mdev;
2821 if (!vdev->vbasedev.sysfsdev) {
2822 if (!(~vdev->host.domain || ~vdev->host.bus ||
2823 ~vdev->host.slot || ~vdev->host.function)) {
2824 error_setg(errp, "No provided host device");
2825 error_append_hint(errp, "Use -device vfio-pci,host=DDDD:BB:DD.F "
2826 "or -device vfio-pci,sysfsdev=PATH_TO_DEVICE\n");
2827 return;
2829 vdev->vbasedev.sysfsdev =
2830 g_strdup_printf("/sys/bus/pci/devices/%04x:%02x:%02x.%01x",
2831 vdev->host.domain, vdev->host.bus,
2832 vdev->host.slot, vdev->host.function);
2835 if (stat(vdev->vbasedev.sysfsdev, &st) < 0) {
2836 error_setg_errno(errp, errno, "no such host device");
2837 error_prepend(errp, VFIO_MSG_PREFIX, vdev->vbasedev.sysfsdev);
2838 return;
2841 vdev->vbasedev.name = g_path_get_basename(vdev->vbasedev.sysfsdev);
2842 vdev->vbasedev.ops = &vfio_pci_ops;
2843 vdev->vbasedev.type = VFIO_DEVICE_TYPE_PCI;
2844 vdev->vbasedev.dev = DEVICE(vdev);
2846 tmp = g_strdup_printf("%s/iommu_group", vdev->vbasedev.sysfsdev);
2847 len = readlink(tmp, group_path, sizeof(group_path));
2848 g_free(tmp);
2850 if (len <= 0 || len >= sizeof(group_path)) {
2851 error_setg_errno(errp, len < 0 ? errno : ENAMETOOLONG,
2852 "no iommu_group found");
2853 goto error;
2856 group_path[len] = 0;
2858 group_name = basename(group_path);
2859 if (sscanf(group_name, "%d", &groupid) != 1) {
2860 error_setg_errno(errp, errno, "failed to read %s", group_path);
2861 goto error;
2864 trace_vfio_realize(vdev->vbasedev.name, groupid);
2866 group = vfio_get_group(groupid, pci_device_iommu_address_space(pdev), errp);
2867 if (!group) {
2868 goto error;
2871 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2872 if (strcmp(vbasedev_iter->name, vdev->vbasedev.name) == 0) {
2873 error_setg(errp, "device is already attached");
2874 vfio_put_group(group);
2875 goto error;
2880 * Mediated devices *might* operate compatibly with discarding of RAM, but
2881 * we cannot know for certain, it depends on whether the mdev vendor driver
2882 * stays in sync with the active working set of the guest driver. Prevent
2883 * the x-balloon-allowed option unless this is minimally an mdev device.
2885 tmp = g_strdup_printf("%s/subsystem", vdev->vbasedev.sysfsdev);
2886 subsys = realpath(tmp, NULL);
2887 g_free(tmp);
2888 is_mdev = subsys && (strcmp(subsys, "/sys/bus/mdev") == 0);
2889 free(subsys);
2891 trace_vfio_mdev(vdev->vbasedev.name, is_mdev);
2893 if (vdev->vbasedev.ram_block_discard_allowed && !is_mdev) {
2894 error_setg(errp, "x-balloon-allowed only potentially compatible "
2895 "with mdev devices");
2896 vfio_put_group(group);
2897 goto error;
2900 ret = vfio_get_device(group, vdev->vbasedev.name, &vdev->vbasedev, errp);
2901 if (ret) {
2902 vfio_put_group(group);
2903 goto error;
2906 vfio_populate_device(vdev, &err);
2907 if (err) {
2908 error_propagate(errp, err);
2909 goto error;
2912 /* Get a copy of config space */
2913 ret = pread(vdev->vbasedev.fd, vdev->pdev.config,
2914 MIN(pci_config_size(&vdev->pdev), vdev->config_size),
2915 vdev->config_offset);
2916 if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
2917 ret = ret < 0 ? -errno : -EFAULT;
2918 error_setg_errno(errp, -ret, "failed to read device config space");
2919 goto error;
2922 /* vfio emulates a lot for us, but some bits need extra love */
2923 vdev->emulated_config_bits = g_malloc0(vdev->config_size);
2925 /* QEMU can choose to expose the ROM or not */
2926 memset(vdev->emulated_config_bits + PCI_ROM_ADDRESS, 0xff, 4);
2927 /* QEMU can also add or extend BARs */
2928 memset(vdev->emulated_config_bits + PCI_BASE_ADDRESS_0, 0xff, 6 * 4);
2931 * The PCI spec reserves vendor ID 0xffff as an invalid value. The
2932 * device ID is managed by the vendor and need only be a 16-bit value.
2933 * Allow any 16-bit value for subsystem so they can be hidden or changed.
2935 if (vdev->vendor_id != PCI_ANY_ID) {
2936 if (vdev->vendor_id >= 0xffff) {
2937 error_setg(errp, "invalid PCI vendor ID provided");
2938 goto error;
2940 vfio_add_emulated_word(vdev, PCI_VENDOR_ID, vdev->vendor_id, ~0);
2941 trace_vfio_pci_emulated_vendor_id(vdev->vbasedev.name, vdev->vendor_id);
2942 } else {
2943 vdev->vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2946 if (vdev->device_id != PCI_ANY_ID) {
2947 if (vdev->device_id > 0xffff) {
2948 error_setg(errp, "invalid PCI device ID provided");
2949 goto error;
2951 vfio_add_emulated_word(vdev, PCI_DEVICE_ID, vdev->device_id, ~0);
2952 trace_vfio_pci_emulated_device_id(vdev->vbasedev.name, vdev->device_id);
2953 } else {
2954 vdev->device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2957 if (vdev->sub_vendor_id != PCI_ANY_ID) {
2958 if (vdev->sub_vendor_id > 0xffff) {
2959 error_setg(errp, "invalid PCI subsystem vendor ID provided");
2960 goto error;
2962 vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_VENDOR_ID,
2963 vdev->sub_vendor_id, ~0);
2964 trace_vfio_pci_emulated_sub_vendor_id(vdev->vbasedev.name,
2965 vdev->sub_vendor_id);
2968 if (vdev->sub_device_id != PCI_ANY_ID) {
2969 if (vdev->sub_device_id > 0xffff) {
2970 error_setg(errp, "invalid PCI subsystem device ID provided");
2971 goto error;
2973 vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_ID, vdev->sub_device_id, ~0);
2974 trace_vfio_pci_emulated_sub_device_id(vdev->vbasedev.name,
2975 vdev->sub_device_id);
2978 /* QEMU can change multi-function devices to single function, or reverse */
2979 vdev->emulated_config_bits[PCI_HEADER_TYPE] =
2980 PCI_HEADER_TYPE_MULTI_FUNCTION;
2982 /* Restore or clear multifunction, this is always controlled by QEMU */
2983 if (vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
2984 vdev->pdev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
2985 } else {
2986 vdev->pdev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
2990 * Clear host resource mapping info. If we choose not to register a
2991 * BAR, such as might be the case with the option ROM, we can get
2992 * confusing, unwritable, residual addresses from the host here.
2994 memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
2995 memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
2997 vfio_pci_size_rom(vdev);
2999 vfio_bars_prepare(vdev);
3001 vfio_msix_early_setup(vdev, &err);
3002 if (err) {
3003 error_propagate(errp, err);
3004 goto error;
3007 vfio_bars_register(vdev);
3009 ret = vfio_add_capabilities(vdev, errp);
3010 if (ret) {
3011 goto out_teardown;
3014 if (vdev->vga) {
3015 vfio_vga_quirk_setup(vdev);
3018 for (i = 0; i < PCI_ROM_SLOT; i++) {
3019 vfio_bar_quirk_setup(vdev, i);
3022 if (!vdev->igd_opregion &&
3023 vdev->features & VFIO_FEATURE_ENABLE_IGD_OPREGION) {
3024 struct vfio_region_info *opregion;
3026 if (vdev->pdev.qdev.hotplugged) {
3027 error_setg(errp,
3028 "cannot support IGD OpRegion feature on hotplugged "
3029 "device");
3030 goto out_teardown;
3033 ret = vfio_get_dev_region_info(&vdev->vbasedev,
3034 VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL,
3035 VFIO_REGION_SUBTYPE_INTEL_IGD_OPREGION, &opregion);
3036 if (ret) {
3037 error_setg_errno(errp, -ret,
3038 "does not support requested IGD OpRegion feature");
3039 goto out_teardown;
3042 ret = vfio_pci_igd_opregion_init(vdev, opregion, errp);
3043 g_free(opregion);
3044 if (ret) {
3045 goto out_teardown;
3049 /* QEMU emulates all of MSI & MSIX */
3050 if (pdev->cap_present & QEMU_PCI_CAP_MSIX) {
3051 memset(vdev->emulated_config_bits + pdev->msix_cap, 0xff,
3052 MSIX_CAP_LENGTH);
3055 if (pdev->cap_present & QEMU_PCI_CAP_MSI) {
3056 memset(vdev->emulated_config_bits + pdev->msi_cap, 0xff,
3057 vdev->msi_cap_size);
3060 if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
3061 vdev->intx.mmap_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
3062 vfio_intx_mmap_enable, vdev);
3063 pci_device_set_intx_routing_notifier(&vdev->pdev,
3064 vfio_intx_routing_notifier);
3065 vdev->irqchip_change_notifier.notify = vfio_irqchip_change;
3066 kvm_irqchip_add_change_notifier(&vdev->irqchip_change_notifier);
3067 ret = vfio_intx_enable(vdev, errp);
3068 if (ret) {
3069 goto out_deregister;
3073 if (vdev->display != ON_OFF_AUTO_OFF) {
3074 ret = vfio_display_probe(vdev, errp);
3075 if (ret) {
3076 goto out_deregister;
3079 if (vdev->enable_ramfb && vdev->dpy == NULL) {
3080 error_setg(errp, "ramfb=on requires display=on");
3081 goto out_deregister;
3083 if (vdev->display_xres || vdev->display_yres) {
3084 if (vdev->dpy == NULL) {
3085 error_setg(errp, "xres and yres properties require display=on");
3086 goto out_deregister;
3088 if (vdev->dpy->edid_regs == NULL) {
3089 error_setg(errp, "xres and yres properties need edid support");
3090 goto out_deregister;
3094 if (vfio_pci_is(vdev, PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID)) {
3095 ret = vfio_pci_nvidia_v100_ram_init(vdev, errp);
3096 if (ret && ret != -ENODEV) {
3097 error_report("Failed to setup NVIDIA V100 GPU RAM");
3101 if (vfio_pci_is(vdev, PCI_VENDOR_ID_IBM, PCI_ANY_ID)) {
3102 ret = vfio_pci_nvlink2_init(vdev, errp);
3103 if (ret && ret != -ENODEV) {
3104 error_report("Failed to setup NVlink2 bridge");
3108 if (!pdev->failover_pair_id) {
3109 ret = vfio_migration_probe(&vdev->vbasedev, errp);
3110 if (ret) {
3111 error_report("%s: Migration disabled", vdev->vbasedev.name);
3115 vfio_register_err_notifier(vdev);
3116 vfio_register_req_notifier(vdev);
3117 vfio_setup_resetfn_quirk(vdev);
3119 return;
3121 out_deregister:
3122 pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3123 kvm_irqchip_remove_change_notifier(&vdev->irqchip_change_notifier);
3124 out_teardown:
3125 vfio_teardown_msi(vdev);
3126 vfio_bars_exit(vdev);
3127 error:
3128 error_prepend(errp, VFIO_MSG_PREFIX, vdev->vbasedev.name);
3131 static void vfio_instance_finalize(Object *obj)
3133 VFIOPCIDevice *vdev = VFIO_PCI(obj);
3134 VFIOGroup *group = vdev->vbasedev.group;
3136 vfio_display_finalize(vdev);
3137 vfio_bars_finalize(vdev);
3138 g_free(vdev->emulated_config_bits);
3139 g_free(vdev->rom);
3141 * XXX Leaking igd_opregion is not an oversight, we can't remove the
3142 * fw_cfg entry therefore leaking this allocation seems like the safest
3143 * option.
3145 * g_free(vdev->igd_opregion);
3147 vfio_put_device(vdev);
3148 vfio_put_group(group);
3151 static void vfio_exitfn(PCIDevice *pdev)
3153 VFIOPCIDevice *vdev = VFIO_PCI(pdev);
3155 vfio_unregister_req_notifier(vdev);
3156 vfio_unregister_err_notifier(vdev);
3157 pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3158 if (vdev->irqchip_change_notifier.notify) {
3159 kvm_irqchip_remove_change_notifier(&vdev->irqchip_change_notifier);
3161 vfio_disable_interrupts(vdev);
3162 if (vdev->intx.mmap_timer) {
3163 timer_free(vdev->intx.mmap_timer);
3165 vfio_teardown_msi(vdev);
3166 vfio_bars_exit(vdev);
3167 vfio_migration_finalize(&vdev->vbasedev);
3170 static void vfio_pci_reset(DeviceState *dev)
3172 VFIOPCIDevice *vdev = VFIO_PCI(dev);
3174 trace_vfio_pci_reset(vdev->vbasedev.name);
3176 vfio_pci_pre_reset(vdev);
3178 if (vdev->display != ON_OFF_AUTO_OFF) {
3179 vfio_display_reset(vdev);
3182 if (vdev->resetfn && !vdev->resetfn(vdev)) {
3183 goto post_reset;
3186 if (vdev->vbasedev.reset_works &&
3187 (vdev->has_flr || !vdev->has_pm_reset) &&
3188 !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
3189 trace_vfio_pci_reset_flr(vdev->vbasedev.name);
3190 goto post_reset;
3193 /* See if we can do our own bus reset */
3194 if (!vfio_pci_hot_reset_one(vdev)) {
3195 goto post_reset;
3198 /* If nothing else works and the device supports PM reset, use it */
3199 if (vdev->vbasedev.reset_works && vdev->has_pm_reset &&
3200 !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
3201 trace_vfio_pci_reset_pm(vdev->vbasedev.name);
3202 goto post_reset;
3205 post_reset:
3206 vfio_pci_post_reset(vdev);
3209 static void vfio_instance_init(Object *obj)
3211 PCIDevice *pci_dev = PCI_DEVICE(obj);
3212 VFIOPCIDevice *vdev = VFIO_PCI(obj);
3214 device_add_bootindex_property(obj, &vdev->bootindex,
3215 "bootindex", NULL,
3216 &pci_dev->qdev);
3217 vdev->host.domain = ~0U;
3218 vdev->host.bus = ~0U;
3219 vdev->host.slot = ~0U;
3220 vdev->host.function = ~0U;
3222 vdev->nv_gpudirect_clique = 0xFF;
3224 /* QEMU_PCI_CAP_EXPRESS initialization does not depend on QEMU command
3225 * line, therefore, no need to wait to realize like other devices */
3226 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
3229 static Property vfio_pci_dev_properties[] = {
3230 DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIOPCIDevice, host),
3231 DEFINE_PROP_STRING("sysfsdev", VFIOPCIDevice, vbasedev.sysfsdev),
3232 DEFINE_PROP_ON_OFF_AUTO("x-pre-copy-dirty-page-tracking", VFIOPCIDevice,
3233 vbasedev.pre_copy_dirty_page_tracking,
3234 ON_OFF_AUTO_ON),
3235 DEFINE_PROP_ON_OFF_AUTO("display", VFIOPCIDevice,
3236 display, ON_OFF_AUTO_OFF),
3237 DEFINE_PROP_UINT32("xres", VFIOPCIDevice, display_xres, 0),
3238 DEFINE_PROP_UINT32("yres", VFIOPCIDevice, display_yres, 0),
3239 DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIOPCIDevice,
3240 intx.mmap_timeout, 1100),
3241 DEFINE_PROP_BIT("x-vga", VFIOPCIDevice, features,
3242 VFIO_FEATURE_ENABLE_VGA_BIT, false),
3243 DEFINE_PROP_BIT("x-req", VFIOPCIDevice, features,
3244 VFIO_FEATURE_ENABLE_REQ_BIT, true),
3245 DEFINE_PROP_BIT("x-igd-opregion", VFIOPCIDevice, features,
3246 VFIO_FEATURE_ENABLE_IGD_OPREGION_BIT, false),
3247 DEFINE_PROP_BOOL("x-enable-migration", VFIOPCIDevice,
3248 vbasedev.enable_migration, false),
3249 DEFINE_PROP_BOOL("x-no-mmap", VFIOPCIDevice, vbasedev.no_mmap, false),
3250 DEFINE_PROP_BOOL("x-balloon-allowed", VFIOPCIDevice,
3251 vbasedev.ram_block_discard_allowed, false),
3252 DEFINE_PROP_BOOL("x-no-kvm-intx", VFIOPCIDevice, no_kvm_intx, false),
3253 DEFINE_PROP_BOOL("x-no-kvm-msi", VFIOPCIDevice, no_kvm_msi, false),
3254 DEFINE_PROP_BOOL("x-no-kvm-msix", VFIOPCIDevice, no_kvm_msix, false),
3255 DEFINE_PROP_BOOL("x-no-geforce-quirks", VFIOPCIDevice,
3256 no_geforce_quirks, false),
3257 DEFINE_PROP_BOOL("x-no-kvm-ioeventfd", VFIOPCIDevice, no_kvm_ioeventfd,
3258 false),
3259 DEFINE_PROP_BOOL("x-no-vfio-ioeventfd", VFIOPCIDevice, no_vfio_ioeventfd,
3260 false),
3261 DEFINE_PROP_UINT32("x-pci-vendor-id", VFIOPCIDevice, vendor_id, PCI_ANY_ID),
3262 DEFINE_PROP_UINT32("x-pci-device-id", VFIOPCIDevice, device_id, PCI_ANY_ID),
3263 DEFINE_PROP_UINT32("x-pci-sub-vendor-id", VFIOPCIDevice,
3264 sub_vendor_id, PCI_ANY_ID),
3265 DEFINE_PROP_UINT32("x-pci-sub-device-id", VFIOPCIDevice,
3266 sub_device_id, PCI_ANY_ID),
3267 DEFINE_PROP_UINT32("x-igd-gms", VFIOPCIDevice, igd_gms, 0),
3268 DEFINE_PROP_UNSIGNED_NODEFAULT("x-nv-gpudirect-clique", VFIOPCIDevice,
3269 nv_gpudirect_clique,
3270 qdev_prop_nv_gpudirect_clique, uint8_t),
3271 DEFINE_PROP_OFF_AUTO_PCIBAR("x-msix-relocation", VFIOPCIDevice, msix_relo,
3272 OFF_AUTOPCIBAR_OFF),
3274 * TODO - support passed fds... is this necessary?
3275 * DEFINE_PROP_STRING("vfiofd", VFIOPCIDevice, vfiofd_name),
3276 * DEFINE_PROP_STRING("vfiogroupfd, VFIOPCIDevice, vfiogroupfd_name),
3278 DEFINE_PROP_END_OF_LIST(),
3281 static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
3283 DeviceClass *dc = DEVICE_CLASS(klass);
3284 PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
3286 dc->reset = vfio_pci_reset;
3287 device_class_set_props(dc, vfio_pci_dev_properties);
3288 dc->desc = "VFIO-based PCI device assignment";
3289 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
3290 pdc->realize = vfio_realize;
3291 pdc->exit = vfio_exitfn;
3292 pdc->config_read = vfio_pci_read_config;
3293 pdc->config_write = vfio_pci_write_config;
3296 static const TypeInfo vfio_pci_dev_info = {
3297 .name = TYPE_VFIO_PCI,
3298 .parent = TYPE_PCI_DEVICE,
3299 .instance_size = sizeof(VFIOPCIDevice),
3300 .class_init = vfio_pci_dev_class_init,
3301 .instance_init = vfio_instance_init,
3302 .instance_finalize = vfio_instance_finalize,
3303 .interfaces = (InterfaceInfo[]) {
3304 { INTERFACE_PCIE_DEVICE },
3305 { INTERFACE_CONVENTIONAL_PCI_DEVICE },
3310 static Property vfio_pci_dev_nohotplug_properties[] = {
3311 DEFINE_PROP_BOOL("ramfb", VFIOPCIDevice, enable_ramfb, false),
3312 DEFINE_PROP_END_OF_LIST(),
3315 static void vfio_pci_nohotplug_dev_class_init(ObjectClass *klass, void *data)
3317 DeviceClass *dc = DEVICE_CLASS(klass);
3319 device_class_set_props(dc, vfio_pci_dev_nohotplug_properties);
3320 dc->hotpluggable = false;
3323 static const TypeInfo vfio_pci_nohotplug_dev_info = {
3324 .name = TYPE_VFIO_PCI_NOHOTPLUG,
3325 .parent = TYPE_VFIO_PCI,
3326 .instance_size = sizeof(VFIOPCIDevice),
3327 .class_init = vfio_pci_nohotplug_dev_class_init,
3330 static void register_vfio_pci_dev_type(void)
3332 type_register_static(&vfio_pci_dev_info);
3333 type_register_static(&vfio_pci_nohotplug_dev_info);
3336 type_init(register_vfio_pci_dev_type)