2 * vfio based device assignment support
4 * Copyright Red Hat, Inc. 2012
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>
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"
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 /* Protected by BQL */
49 static KVMRouteChange vfio_route_change
;
51 static void vfio_disable_interrupts(VFIOPCIDevice
*vdev
);
52 static void vfio_mmap_set_enabled(VFIOPCIDevice
*vdev
, bool enabled
);
53 static void vfio_msi_disable_common(VFIOPCIDevice
*vdev
);
56 * Disabling BAR mmaping can be slow, but toggling it around INTx can
57 * also be a huge overhead. We try to get the best of both worlds by
58 * waiting until an interrupt to disable mmaps (subsequent transitions
59 * to the same state are effectively no overhead). If the interrupt has
60 * been serviced and the time gap is long enough, we re-enable mmaps for
61 * performance. This works well for things like graphics cards, which
62 * may not use their interrupt at all and are penalized to an unusable
63 * level by read/write BAR traps. Other devices, like NICs, have more
64 * regular interrupts and see much better latency by staying in non-mmap
65 * mode. We therefore set the default mmap_timeout such that a ping
66 * is just enough to keep the mmap disabled. Users can experiment with
67 * other options with the x-intx-mmap-timeout-ms parameter (a value of
68 * zero disables the timer).
70 static void vfio_intx_mmap_enable(void *opaque
)
72 VFIOPCIDevice
*vdev
= opaque
;
74 if (vdev
->intx
.pending
) {
75 timer_mod(vdev
->intx
.mmap_timer
,
76 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) + vdev
->intx
.mmap_timeout
);
80 vfio_mmap_set_enabled(vdev
, true);
83 static void vfio_intx_interrupt(void *opaque
)
85 VFIOPCIDevice
*vdev
= opaque
;
87 if (!event_notifier_test_and_clear(&vdev
->intx
.interrupt
)) {
91 trace_vfio_intx_interrupt(vdev
->vbasedev
.name
, 'A' + vdev
->intx
.pin
);
93 vdev
->intx
.pending
= true;
94 pci_irq_assert(&vdev
->pdev
);
95 vfio_mmap_set_enabled(vdev
, false);
96 if (vdev
->intx
.mmap_timeout
) {
97 timer_mod(vdev
->intx
.mmap_timer
,
98 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) + vdev
->intx
.mmap_timeout
);
102 static void vfio_intx_eoi(VFIODevice
*vbasedev
)
104 VFIOPCIDevice
*vdev
= container_of(vbasedev
, VFIOPCIDevice
, vbasedev
);
106 if (!vdev
->intx
.pending
) {
110 trace_vfio_intx_eoi(vbasedev
->name
);
112 vdev
->intx
.pending
= false;
113 pci_irq_deassert(&vdev
->pdev
);
114 vfio_unmask_single_irqindex(vbasedev
, VFIO_PCI_INTX_IRQ_INDEX
);
117 static void vfio_intx_enable_kvm(VFIOPCIDevice
*vdev
, Error
**errp
)
120 int irq_fd
= event_notifier_get_fd(&vdev
->intx
.interrupt
);
122 if (vdev
->no_kvm_intx
|| !kvm_irqfds_enabled() ||
123 vdev
->intx
.route
.mode
!= PCI_INTX_ENABLED
||
124 !kvm_resamplefds_enabled()) {
128 /* Get to a known interrupt state */
129 qemu_set_fd_handler(irq_fd
, NULL
, NULL
, vdev
);
130 vfio_mask_single_irqindex(&vdev
->vbasedev
, VFIO_PCI_INTX_IRQ_INDEX
);
131 vdev
->intx
.pending
= false;
132 pci_irq_deassert(&vdev
->pdev
);
134 /* Get an eventfd for resample/unmask */
135 if (event_notifier_init(&vdev
->intx
.unmask
, 0)) {
136 error_setg(errp
, "event_notifier_init failed eoi");
140 if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state
,
141 &vdev
->intx
.interrupt
,
143 vdev
->intx
.route
.irq
)) {
144 error_setg_errno(errp
, errno
, "failed to setup resample irqfd");
148 if (vfio_set_irq_signaling(&vdev
->vbasedev
, VFIO_PCI_INTX_IRQ_INDEX
, 0,
149 VFIO_IRQ_SET_ACTION_UNMASK
,
150 event_notifier_get_fd(&vdev
->intx
.unmask
),
156 vfio_unmask_single_irqindex(&vdev
->vbasedev
, VFIO_PCI_INTX_IRQ_INDEX
);
158 vdev
->intx
.kvm_accel
= true;
160 trace_vfio_intx_enable_kvm(vdev
->vbasedev
.name
);
165 kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state
, &vdev
->intx
.interrupt
,
166 vdev
->intx
.route
.irq
);
168 event_notifier_cleanup(&vdev
->intx
.unmask
);
170 qemu_set_fd_handler(irq_fd
, vfio_intx_interrupt
, NULL
, vdev
);
171 vfio_unmask_single_irqindex(&vdev
->vbasedev
, VFIO_PCI_INTX_IRQ_INDEX
);
175 static void vfio_intx_disable_kvm(VFIOPCIDevice
*vdev
)
178 if (!vdev
->intx
.kvm_accel
) {
183 * Get to a known state, hardware masked, QEMU ready to accept new
184 * interrupts, QEMU IRQ de-asserted.
186 vfio_mask_single_irqindex(&vdev
->vbasedev
, VFIO_PCI_INTX_IRQ_INDEX
);
187 vdev
->intx
.pending
= false;
188 pci_irq_deassert(&vdev
->pdev
);
190 /* Tell KVM to stop listening for an INTx irqfd */
191 if (kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state
, &vdev
->intx
.interrupt
,
192 vdev
->intx
.route
.irq
)) {
193 error_report("vfio: Error: Failed to disable INTx irqfd: %m");
196 /* We only need to close the eventfd for VFIO to cleanup the kernel side */
197 event_notifier_cleanup(&vdev
->intx
.unmask
);
199 /* QEMU starts listening for interrupt events. */
200 qemu_set_fd_handler(event_notifier_get_fd(&vdev
->intx
.interrupt
),
201 vfio_intx_interrupt
, NULL
, vdev
);
203 vdev
->intx
.kvm_accel
= false;
205 /* If we've missed an event, let it re-fire through QEMU */
206 vfio_unmask_single_irqindex(&vdev
->vbasedev
, VFIO_PCI_INTX_IRQ_INDEX
);
208 trace_vfio_intx_disable_kvm(vdev
->vbasedev
.name
);
212 static void vfio_intx_update(VFIOPCIDevice
*vdev
, PCIINTxRoute
*route
)
216 trace_vfio_intx_update(vdev
->vbasedev
.name
,
217 vdev
->intx
.route
.irq
, route
->irq
);
219 vfio_intx_disable_kvm(vdev
);
221 vdev
->intx
.route
= *route
;
223 if (route
->mode
!= PCI_INTX_ENABLED
) {
227 vfio_intx_enable_kvm(vdev
, &err
);
229 warn_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
232 /* Re-enable the interrupt in cased we missed an EOI */
233 vfio_intx_eoi(&vdev
->vbasedev
);
236 static void vfio_intx_routing_notifier(PCIDevice
*pdev
)
238 VFIOPCIDevice
*vdev
= VFIO_PCI(pdev
);
241 if (vdev
->interrupt
!= VFIO_INT_INTx
) {
245 route
= pci_device_route_intx_to_irq(&vdev
->pdev
, vdev
->intx
.pin
);
247 if (pci_intx_route_changed(&vdev
->intx
.route
, &route
)) {
248 vfio_intx_update(vdev
, &route
);
252 static void vfio_irqchip_change(Notifier
*notify
, void *data
)
254 VFIOPCIDevice
*vdev
= container_of(notify
, VFIOPCIDevice
,
255 irqchip_change_notifier
);
257 vfio_intx_update(vdev
, &vdev
->intx
.route
);
260 static int vfio_intx_enable(VFIOPCIDevice
*vdev
, Error
**errp
)
262 uint8_t pin
= vfio_pci_read_config(&vdev
->pdev
, PCI_INTERRUPT_PIN
, 1);
272 vfio_disable_interrupts(vdev
);
274 vdev
->intx
.pin
= pin
- 1; /* Pin A (1) -> irq[0] */
275 pci_config_set_interrupt_pin(vdev
->pdev
.config
, pin
);
279 * Only conditional to avoid generating error messages on platforms
280 * where we won't actually use the result anyway.
282 if (kvm_irqfds_enabled() && kvm_resamplefds_enabled()) {
283 vdev
->intx
.route
= pci_device_route_intx_to_irq(&vdev
->pdev
,
288 ret
= event_notifier_init(&vdev
->intx
.interrupt
, 0);
290 error_setg_errno(errp
, -ret
, "event_notifier_init failed");
293 fd
= event_notifier_get_fd(&vdev
->intx
.interrupt
);
294 qemu_set_fd_handler(fd
, vfio_intx_interrupt
, NULL
, vdev
);
296 if (vfio_set_irq_signaling(&vdev
->vbasedev
, VFIO_PCI_INTX_IRQ_INDEX
, 0,
297 VFIO_IRQ_SET_ACTION_TRIGGER
, fd
, errp
)) {
298 qemu_set_fd_handler(fd
, NULL
, NULL
, vdev
);
299 event_notifier_cleanup(&vdev
->intx
.interrupt
);
303 vfio_intx_enable_kvm(vdev
, &err
);
305 warn_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
308 vdev
->interrupt
= VFIO_INT_INTx
;
310 trace_vfio_intx_enable(vdev
->vbasedev
.name
);
314 static void vfio_intx_disable(VFIOPCIDevice
*vdev
)
318 timer_del(vdev
->intx
.mmap_timer
);
319 vfio_intx_disable_kvm(vdev
);
320 vfio_disable_irqindex(&vdev
->vbasedev
, VFIO_PCI_INTX_IRQ_INDEX
);
321 vdev
->intx
.pending
= false;
322 pci_irq_deassert(&vdev
->pdev
);
323 vfio_mmap_set_enabled(vdev
, true);
325 fd
= event_notifier_get_fd(&vdev
->intx
.interrupt
);
326 qemu_set_fd_handler(fd
, NULL
, NULL
, vdev
);
327 event_notifier_cleanup(&vdev
->intx
.interrupt
);
329 vdev
->interrupt
= VFIO_INT_NONE
;
331 trace_vfio_intx_disable(vdev
->vbasedev
.name
);
337 static void vfio_msi_interrupt(void *opaque
)
339 VFIOMSIVector
*vector
= opaque
;
340 VFIOPCIDevice
*vdev
= vector
->vdev
;
341 MSIMessage (*get_msg
)(PCIDevice
*dev
, unsigned vector
);
342 void (*notify
)(PCIDevice
*dev
, unsigned vector
);
344 int nr
= vector
- vdev
->msi_vectors
;
346 if (!event_notifier_test_and_clear(&vector
->interrupt
)) {
350 if (vdev
->interrupt
== VFIO_INT_MSIX
) {
351 get_msg
= msix_get_message
;
352 notify
= msix_notify
;
354 /* A masked vector firing needs to use the PBA, enable it */
355 if (msix_is_masked(&vdev
->pdev
, nr
)) {
356 set_bit(nr
, vdev
->msix
->pending
);
357 memory_region_set_enabled(&vdev
->pdev
.msix_pba_mmio
, true);
358 trace_vfio_msix_pba_enable(vdev
->vbasedev
.name
);
360 } else if (vdev
->interrupt
== VFIO_INT_MSI
) {
361 get_msg
= msi_get_message
;
367 msg
= get_msg(&vdev
->pdev
, nr
);
368 trace_vfio_msi_interrupt(vdev
->vbasedev
.name
, nr
, msg
.address
, msg
.data
);
369 notify(&vdev
->pdev
, nr
);
372 static int vfio_enable_vectors(VFIOPCIDevice
*vdev
, bool msix
)
374 struct vfio_irq_set
*irq_set
;
375 int ret
= 0, i
, argsz
;
378 argsz
= sizeof(*irq_set
) + (vdev
->nr_vectors
* sizeof(*fds
));
380 irq_set
= g_malloc0(argsz
);
381 irq_set
->argsz
= argsz
;
382 irq_set
->flags
= VFIO_IRQ_SET_DATA_EVENTFD
| VFIO_IRQ_SET_ACTION_TRIGGER
;
383 irq_set
->index
= msix
? VFIO_PCI_MSIX_IRQ_INDEX
: VFIO_PCI_MSI_IRQ_INDEX
;
385 irq_set
->count
= vdev
->nr_vectors
;
386 fds
= (int32_t *)&irq_set
->data
;
388 for (i
= 0; i
< vdev
->nr_vectors
; i
++) {
392 * MSI vs MSI-X - The guest has direct access to MSI mask and pending
393 * bits, therefore we always use the KVM signaling path when setup.
394 * MSI-X mask and pending bits are emulated, so we want to use the
395 * KVM signaling path only when configured and unmasked.
397 if (vdev
->msi_vectors
[i
].use
) {
398 if (vdev
->msi_vectors
[i
].virq
< 0 ||
399 (msix
&& msix_is_masked(&vdev
->pdev
, i
))) {
400 fd
= event_notifier_get_fd(&vdev
->msi_vectors
[i
].interrupt
);
402 fd
= event_notifier_get_fd(&vdev
->msi_vectors
[i
].kvm_interrupt
);
409 ret
= ioctl(vdev
->vbasedev
.fd
, VFIO_DEVICE_SET_IRQS
, irq_set
);
416 static void vfio_add_kvm_msi_virq(VFIOPCIDevice
*vdev
, VFIOMSIVector
*vector
,
417 int vector_n
, bool msix
)
419 if ((msix
&& vdev
->no_kvm_msix
) || (!msix
&& vdev
->no_kvm_msi
)) {
423 vector
->virq
= kvm_irqchip_add_msi_route(&vfio_route_change
,
424 vector_n
, &vdev
->pdev
);
427 static void vfio_connect_kvm_msi_virq(VFIOMSIVector
*vector
)
429 if (vector
->virq
< 0) {
433 if (event_notifier_init(&vector
->kvm_interrupt
, 0)) {
437 if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state
, &vector
->kvm_interrupt
,
438 NULL
, vector
->virq
) < 0) {
445 event_notifier_cleanup(&vector
->kvm_interrupt
);
447 kvm_irqchip_release_virq(kvm_state
, vector
->virq
);
451 static void vfio_remove_kvm_msi_virq(VFIOMSIVector
*vector
)
453 kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state
, &vector
->kvm_interrupt
,
455 kvm_irqchip_release_virq(kvm_state
, vector
->virq
);
457 event_notifier_cleanup(&vector
->kvm_interrupt
);
460 static void vfio_update_kvm_msi_virq(VFIOMSIVector
*vector
, MSIMessage msg
,
463 kvm_irqchip_update_msi_route(kvm_state
, vector
->virq
, msg
, pdev
);
464 kvm_irqchip_commit_routes(kvm_state
);
467 static int vfio_msix_vector_do_use(PCIDevice
*pdev
, unsigned int nr
,
468 MSIMessage
*msg
, IOHandler
*handler
)
470 VFIOPCIDevice
*vdev
= VFIO_PCI(pdev
);
471 VFIOMSIVector
*vector
;
474 trace_vfio_msix_vector_do_use(vdev
->vbasedev
.name
, nr
);
476 vector
= &vdev
->msi_vectors
[nr
];
481 if (event_notifier_init(&vector
->interrupt
, 0)) {
482 error_report("vfio: Error: event_notifier_init failed");
485 msix_vector_use(pdev
, nr
);
488 qemu_set_fd_handler(event_notifier_get_fd(&vector
->interrupt
),
489 handler
, NULL
, vector
);
492 * Attempt to enable route through KVM irqchip,
493 * default to userspace handling if unavailable.
495 if (vector
->virq
>= 0) {
497 vfio_remove_kvm_msi_virq(vector
);
499 vfio_update_kvm_msi_virq(vector
, *msg
, pdev
);
503 if (vdev
->defer_kvm_irq_routing
) {
504 vfio_add_kvm_msi_virq(vdev
, vector
, nr
, true);
506 vfio_route_change
= kvm_irqchip_begin_route_changes(kvm_state
);
507 vfio_add_kvm_msi_virq(vdev
, vector
, nr
, true);
508 kvm_irqchip_commit_route_changes(&vfio_route_change
);
509 vfio_connect_kvm_msi_virq(vector
);
515 * We don't want to have the host allocate all possible MSI vectors
516 * for a device if they're not in use, so we shutdown and incrementally
517 * increase them as needed.
519 if (vdev
->nr_vectors
< nr
+ 1) {
520 vdev
->nr_vectors
= nr
+ 1;
521 if (!vdev
->defer_kvm_irq_routing
) {
522 vfio_disable_irqindex(&vdev
->vbasedev
, VFIO_PCI_MSIX_IRQ_INDEX
);
523 ret
= vfio_enable_vectors(vdev
, true);
525 error_report("vfio: failed to enable vectors, %d", ret
);
532 if (vector
->virq
>= 0) {
533 fd
= event_notifier_get_fd(&vector
->kvm_interrupt
);
535 fd
= event_notifier_get_fd(&vector
->interrupt
);
538 if (vfio_set_irq_signaling(&vdev
->vbasedev
,
539 VFIO_PCI_MSIX_IRQ_INDEX
, nr
,
540 VFIO_IRQ_SET_ACTION_TRIGGER
, fd
, &err
)) {
541 error_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
545 /* Disable PBA emulation when nothing more is pending. */
546 clear_bit(nr
, vdev
->msix
->pending
);
547 if (find_first_bit(vdev
->msix
->pending
,
548 vdev
->nr_vectors
) == vdev
->nr_vectors
) {
549 memory_region_set_enabled(&vdev
->pdev
.msix_pba_mmio
, false);
550 trace_vfio_msix_pba_disable(vdev
->vbasedev
.name
);
556 static int vfio_msix_vector_use(PCIDevice
*pdev
,
557 unsigned int nr
, MSIMessage msg
)
559 return vfio_msix_vector_do_use(pdev
, nr
, &msg
, vfio_msi_interrupt
);
562 static void vfio_msix_vector_release(PCIDevice
*pdev
, unsigned int nr
)
564 VFIOPCIDevice
*vdev
= VFIO_PCI(pdev
);
565 VFIOMSIVector
*vector
= &vdev
->msi_vectors
[nr
];
567 trace_vfio_msix_vector_release(vdev
->vbasedev
.name
, nr
);
570 * There are still old guests that mask and unmask vectors on every
571 * interrupt. If we're using QEMU bypass with a KVM irqfd, leave all of
572 * the KVM setup in place, simply switch VFIO to use the non-bypass
573 * eventfd. We'll then fire the interrupt through QEMU and the MSI-X
574 * core will mask the interrupt and set pending bits, allowing it to
575 * be re-asserted on unmask. Nothing to do if already using QEMU mode.
577 if (vector
->virq
>= 0) {
578 int32_t fd
= event_notifier_get_fd(&vector
->interrupt
);
581 if (vfio_set_irq_signaling(&vdev
->vbasedev
, VFIO_PCI_MSIX_IRQ_INDEX
, nr
,
582 VFIO_IRQ_SET_ACTION_TRIGGER
, fd
, &err
)) {
583 error_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
588 static void vfio_prepare_kvm_msi_virq_batch(VFIOPCIDevice
*vdev
)
590 assert(!vdev
->defer_kvm_irq_routing
);
591 vdev
->defer_kvm_irq_routing
= true;
592 vfio_route_change
= kvm_irqchip_begin_route_changes(kvm_state
);
595 static void vfio_commit_kvm_msi_virq_batch(VFIOPCIDevice
*vdev
)
599 assert(vdev
->defer_kvm_irq_routing
);
600 vdev
->defer_kvm_irq_routing
= false;
602 kvm_irqchip_commit_route_changes(&vfio_route_change
);
604 for (i
= 0; i
< vdev
->nr_vectors
; i
++) {
605 vfio_connect_kvm_msi_virq(&vdev
->msi_vectors
[i
]);
609 static void vfio_msix_enable(VFIOPCIDevice
*vdev
)
611 vfio_disable_interrupts(vdev
);
613 vdev
->msi_vectors
= g_new0(VFIOMSIVector
, vdev
->msix
->entries
);
615 vdev
->interrupt
= VFIO_INT_MSIX
;
618 * Setting vector notifiers triggers synchronous vector-use
619 * callbacks for each active vector. Deferring to commit the KVM
620 * routes once rather than per vector provides a substantial
621 * performance improvement.
623 vfio_prepare_kvm_msi_virq_batch(vdev
);
625 if (msix_set_vector_notifiers(&vdev
->pdev
, vfio_msix_vector_use
,
626 vfio_msix_vector_release
, NULL
)) {
627 error_report("vfio: msix_set_vector_notifiers failed");
630 vfio_commit_kvm_msi_virq_batch(vdev
);
632 if (vdev
->nr_vectors
) {
635 ret
= vfio_enable_vectors(vdev
, true);
637 error_report("vfio: failed to enable vectors, %d", ret
);
641 * Some communication channels between VF & PF or PF & fw rely on the
642 * physical state of the device and expect that enabling MSI-X from the
643 * guest enables the same on the host. When our guest is Linux, the
644 * guest driver call to pci_enable_msix() sets the enabling bit in the
645 * MSI-X capability, but leaves the vector table masked. We therefore
646 * can't rely on a vector_use callback (from request_irq() in the guest)
647 * to switch the physical device into MSI-X mode because that may come a
648 * long time after pci_enable_msix(). This code enables vector 0 with
649 * triggering to userspace, then immediately release the vector, leaving
650 * the physical device with no vectors enabled, but MSI-X enabled, just
651 * like the guest view.
653 vfio_msix_vector_do_use(&vdev
->pdev
, 0, NULL
, NULL
);
654 vfio_msix_vector_release(&vdev
->pdev
, 0);
657 trace_vfio_msix_enable(vdev
->vbasedev
.name
);
660 static void vfio_msi_enable(VFIOPCIDevice
*vdev
)
664 vfio_disable_interrupts(vdev
);
666 vdev
->nr_vectors
= msi_nr_vectors_allocated(&vdev
->pdev
);
669 * Setting vector notifiers needs to enable route for each vector.
670 * Deferring to commit the KVM routes once rather than per vector
671 * provides a substantial performance improvement.
673 vfio_prepare_kvm_msi_virq_batch(vdev
);
675 vdev
->msi_vectors
= g_new0(VFIOMSIVector
, vdev
->nr_vectors
);
677 for (i
= 0; i
< vdev
->nr_vectors
; i
++) {
678 VFIOMSIVector
*vector
= &vdev
->msi_vectors
[i
];
684 if (event_notifier_init(&vector
->interrupt
, 0)) {
685 error_report("vfio: Error: event_notifier_init failed");
688 qemu_set_fd_handler(event_notifier_get_fd(&vector
->interrupt
),
689 vfio_msi_interrupt
, NULL
, vector
);
692 * Attempt to enable route through KVM irqchip,
693 * default to userspace handling if unavailable.
695 vfio_add_kvm_msi_virq(vdev
, vector
, i
, false);
698 vfio_commit_kvm_msi_virq_batch(vdev
);
700 /* Set interrupt type prior to possible interrupts */
701 vdev
->interrupt
= VFIO_INT_MSI
;
703 ret
= vfio_enable_vectors(vdev
, false);
706 error_report("vfio: Error: Failed to setup MSI fds: %m");
708 error_report("vfio: Error: Failed to enable %d "
709 "MSI vectors, retry with %d", vdev
->nr_vectors
, ret
);
712 vfio_msi_disable_common(vdev
);
715 vdev
->nr_vectors
= ret
;
720 * Failing to setup MSI doesn't really fall within any specification.
721 * Let's try leaving interrupts disabled and hope the guest figures
722 * out to fall back to INTx for this device.
724 error_report("vfio: Error: Failed to enable MSI");
729 trace_vfio_msi_enable(vdev
->vbasedev
.name
, vdev
->nr_vectors
);
732 static void vfio_msi_disable_common(VFIOPCIDevice
*vdev
)
736 for (i
= 0; i
< vdev
->nr_vectors
; i
++) {
737 VFIOMSIVector
*vector
= &vdev
->msi_vectors
[i
];
738 if (vdev
->msi_vectors
[i
].use
) {
739 if (vector
->virq
>= 0) {
740 vfio_remove_kvm_msi_virq(vector
);
742 qemu_set_fd_handler(event_notifier_get_fd(&vector
->interrupt
),
744 event_notifier_cleanup(&vector
->interrupt
);
748 g_free(vdev
->msi_vectors
);
749 vdev
->msi_vectors
= NULL
;
750 vdev
->nr_vectors
= 0;
751 vdev
->interrupt
= VFIO_INT_NONE
;
754 static void vfio_msix_disable(VFIOPCIDevice
*vdev
)
759 msix_unset_vector_notifiers(&vdev
->pdev
);
762 * MSI-X will only release vectors if MSI-X is still enabled on the
763 * device, check through the rest and release it ourselves if necessary.
765 for (i
= 0; i
< vdev
->nr_vectors
; i
++) {
766 if (vdev
->msi_vectors
[i
].use
) {
767 vfio_msix_vector_release(&vdev
->pdev
, i
);
768 msix_vector_unuse(&vdev
->pdev
, i
);
772 if (vdev
->nr_vectors
) {
773 vfio_disable_irqindex(&vdev
->vbasedev
, VFIO_PCI_MSIX_IRQ_INDEX
);
776 vfio_msi_disable_common(vdev
);
777 vfio_intx_enable(vdev
, &err
);
779 error_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
782 memset(vdev
->msix
->pending
, 0,
783 BITS_TO_LONGS(vdev
->msix
->entries
) * sizeof(unsigned long));
785 trace_vfio_msix_disable(vdev
->vbasedev
.name
);
788 static void vfio_msi_disable(VFIOPCIDevice
*vdev
)
792 vfio_disable_irqindex(&vdev
->vbasedev
, VFIO_PCI_MSI_IRQ_INDEX
);
793 vfio_msi_disable_common(vdev
);
794 vfio_intx_enable(vdev
, &err
);
796 error_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
799 trace_vfio_msi_disable(vdev
->vbasedev
.name
);
802 static void vfio_update_msi(VFIOPCIDevice
*vdev
)
806 for (i
= 0; i
< vdev
->nr_vectors
; i
++) {
807 VFIOMSIVector
*vector
= &vdev
->msi_vectors
[i
];
810 if (!vector
->use
|| vector
->virq
< 0) {
814 msg
= msi_get_message(&vdev
->pdev
, i
);
815 vfio_update_kvm_msi_virq(vector
, msg
, &vdev
->pdev
);
819 static void vfio_pci_load_rom(VFIOPCIDevice
*vdev
)
821 struct vfio_region_info
*reg_info
;
826 if (vfio_get_region_info(&vdev
->vbasedev
,
827 VFIO_PCI_ROM_REGION_INDEX
, ®_info
)) {
828 error_report("vfio: Error getting ROM info: %m");
832 trace_vfio_pci_load_rom(vdev
->vbasedev
.name
, (unsigned long)reg_info
->size
,
833 (unsigned long)reg_info
->offset
,
834 (unsigned long)reg_info
->flags
);
836 vdev
->rom_size
= size
= reg_info
->size
;
837 vdev
->rom_offset
= reg_info
->offset
;
841 if (!vdev
->rom_size
) {
842 vdev
->rom_read_failed
= true;
843 error_report("vfio-pci: Cannot read device rom at "
844 "%s", vdev
->vbasedev
.name
);
845 error_printf("Device option ROM contents are probably invalid "
846 "(check dmesg).\nSkip option ROM probe with rombar=0, "
847 "or load from file with romfile=\n");
851 vdev
->rom
= g_malloc(size
);
852 memset(vdev
->rom
, 0xff, size
);
855 bytes
= pread(vdev
->vbasedev
.fd
, vdev
->rom
+ off
,
856 size
, vdev
->rom_offset
+ off
);
859 } else if (bytes
> 0) {
863 if (errno
== EINTR
|| errno
== EAGAIN
) {
866 error_report("vfio: Error reading device ROM: %m");
872 * Test the ROM signature against our device, if the vendor is correct
873 * but the device ID doesn't match, store the correct device ID and
874 * recompute the checksum. Intel IGD devices need this and are known
875 * to have bogus checksums so we can't simply adjust the checksum.
877 if (pci_get_word(vdev
->rom
) == 0xaa55 &&
878 pci_get_word(vdev
->rom
+ 0x18) + 8 < vdev
->rom_size
&&
879 !memcmp(vdev
->rom
+ pci_get_word(vdev
->rom
+ 0x18), "PCIR", 4)) {
882 vid
= pci_get_word(vdev
->rom
+ pci_get_word(vdev
->rom
+ 0x18) + 4);
883 did
= pci_get_word(vdev
->rom
+ pci_get_word(vdev
->rom
+ 0x18) + 6);
885 if (vid
== vdev
->vendor_id
&& did
!= vdev
->device_id
) {
887 uint8_t csum
, *data
= vdev
->rom
;
889 pci_set_word(vdev
->rom
+ pci_get_word(vdev
->rom
+ 0x18) + 6,
893 for (csum
= 0, i
= 0; i
< vdev
->rom_size
; i
++) {
902 static uint64_t vfio_rom_read(void *opaque
, hwaddr addr
, unsigned size
)
904 VFIOPCIDevice
*vdev
= opaque
;
913 /* Load the ROM lazily when the guest tries to read it */
914 if (unlikely(!vdev
->rom
&& !vdev
->rom_read_failed
)) {
915 vfio_pci_load_rom(vdev
);
918 memcpy(&val
, vdev
->rom
+ addr
,
919 (addr
< vdev
->rom_size
) ? MIN(size
, vdev
->rom_size
- addr
) : 0);
926 data
= le16_to_cpu(val
.word
);
929 data
= le32_to_cpu(val
.dword
);
932 hw_error("vfio: unsupported read size, %d bytes\n", size
);
936 trace_vfio_rom_read(vdev
->vbasedev
.name
, addr
, size
, data
);
941 static void vfio_rom_write(void *opaque
, hwaddr addr
,
942 uint64_t data
, unsigned size
)
946 static const MemoryRegionOps vfio_rom_ops
= {
947 .read
= vfio_rom_read
,
948 .write
= vfio_rom_write
,
949 .endianness
= DEVICE_LITTLE_ENDIAN
,
952 static void vfio_pci_size_rom(VFIOPCIDevice
*vdev
)
954 uint32_t orig
, size
= cpu_to_le32((uint32_t)PCI_ROM_ADDRESS_MASK
);
955 off_t offset
= vdev
->config_offset
+ PCI_ROM_ADDRESS
;
956 DeviceState
*dev
= DEVICE(vdev
);
958 int fd
= vdev
->vbasedev
.fd
;
960 if (vdev
->pdev
.romfile
|| !vdev
->pdev
.rom_bar
) {
961 /* Since pci handles romfile, just print a message and return */
962 if (vfio_opt_rom_in_denylist(vdev
) && vdev
->pdev
.romfile
) {
963 warn_report("Device at %s is known to cause system instability"
964 " issues during option rom execution",
965 vdev
->vbasedev
.name
);
966 error_printf("Proceeding anyway since user specified romfile\n");
972 * Use the same size ROM BAR as the physical device. The contents
973 * will get filled in later when the guest tries to read it.
975 if (pread(fd
, &orig
, 4, offset
) != 4 ||
976 pwrite(fd
, &size
, 4, offset
) != 4 ||
977 pread(fd
, &size
, 4, offset
) != 4 ||
978 pwrite(fd
, &orig
, 4, offset
) != 4) {
979 error_report("%s(%s) failed: %m", __func__
, vdev
->vbasedev
.name
);
983 size
= ~(le32_to_cpu(size
) & PCI_ROM_ADDRESS_MASK
) + 1;
989 if (vfio_opt_rom_in_denylist(vdev
)) {
990 if (dev
->opts
&& qdict_haskey(dev
->opts
, "rombar")) {
991 warn_report("Device at %s is known to cause system instability"
992 " issues during option rom execution",
993 vdev
->vbasedev
.name
);
994 error_printf("Proceeding anyway since user specified"
995 " non zero value for rombar\n");
997 warn_report("Rom loading for device at %s has been disabled"
998 " due to system instability issues",
999 vdev
->vbasedev
.name
);
1000 error_printf("Specify rombar=1 or romfile to force\n");
1005 trace_vfio_pci_size_rom(vdev
->vbasedev
.name
, size
);
1007 name
= g_strdup_printf("vfio[%s].rom", vdev
->vbasedev
.name
);
1009 memory_region_init_io(&vdev
->pdev
.rom
, OBJECT(vdev
),
1010 &vfio_rom_ops
, vdev
, name
, size
);
1013 pci_register_bar(&vdev
->pdev
, PCI_ROM_SLOT
,
1014 PCI_BASE_ADDRESS_SPACE_MEMORY
, &vdev
->pdev
.rom
);
1016 vdev
->rom_read_failed
= false;
1019 void vfio_vga_write(void *opaque
, hwaddr addr
,
1020 uint64_t data
, unsigned size
)
1022 VFIOVGARegion
*region
= opaque
;
1023 VFIOVGA
*vga
= container_of(region
, VFIOVGA
, region
[region
->nr
]);
1030 off_t offset
= vga
->fd_offset
+ region
->offset
+ addr
;
1037 buf
.word
= cpu_to_le16(data
);
1040 buf
.dword
= cpu_to_le32(data
);
1043 hw_error("vfio: unsupported write size, %d bytes", size
);
1047 if (pwrite(vga
->fd
, &buf
, size
, offset
) != size
) {
1048 error_report("%s(,0x%"HWADDR_PRIx
", 0x%"PRIx64
", %d) failed: %m",
1049 __func__
, region
->offset
+ addr
, data
, size
);
1052 trace_vfio_vga_write(region
->offset
+ addr
, data
, size
);
1055 uint64_t vfio_vga_read(void *opaque
, hwaddr addr
, unsigned size
)
1057 VFIOVGARegion
*region
= opaque
;
1058 VFIOVGA
*vga
= container_of(region
, VFIOVGA
, region
[region
->nr
]);
1066 off_t offset
= vga
->fd_offset
+ region
->offset
+ addr
;
1068 if (pread(vga
->fd
, &buf
, size
, offset
) != size
) {
1069 error_report("%s(,0x%"HWADDR_PRIx
", %d) failed: %m",
1070 __func__
, region
->offset
+ addr
, size
);
1071 return (uint64_t)-1;
1079 data
= le16_to_cpu(buf
.word
);
1082 data
= le32_to_cpu(buf
.dword
);
1085 hw_error("vfio: unsupported read size, %d bytes", size
);
1089 trace_vfio_vga_read(region
->offset
+ addr
, size
, data
);
1094 static const MemoryRegionOps vfio_vga_ops
= {
1095 .read
= vfio_vga_read
,
1096 .write
= vfio_vga_write
,
1097 .endianness
= DEVICE_LITTLE_ENDIAN
,
1101 * Expand memory region of sub-page(size < PAGE_SIZE) MMIO BAR to page
1102 * size if the BAR is in an exclusive page in host so that we could map
1103 * this BAR to guest. But this sub-page BAR may not occupy an exclusive
1104 * page in guest. So we should set the priority of the expanded memory
1105 * region to zero in case of overlap with BARs which share the same page
1106 * with the sub-page BAR in guest. Besides, we should also recover the
1107 * size of this sub-page BAR when its base address is changed in guest
1108 * and not page aligned any more.
1110 static void vfio_sub_page_bar_update_mapping(PCIDevice
*pdev
, int bar
)
1112 VFIOPCIDevice
*vdev
= VFIO_PCI(pdev
);
1113 VFIORegion
*region
= &vdev
->bars
[bar
].region
;
1114 MemoryRegion
*mmap_mr
, *region_mr
, *base_mr
;
1117 uint64_t size
= region
->size
;
1119 /* Make sure that the whole region is allowed to be mmapped */
1120 if (region
->nr_mmaps
!= 1 || !region
->mmaps
[0].mmap
||
1121 region
->mmaps
[0].size
!= region
->size
) {
1125 r
= &pdev
->io_regions
[bar
];
1127 base_mr
= vdev
->bars
[bar
].mr
;
1128 region_mr
= region
->mem
;
1129 mmap_mr
= ®ion
->mmaps
[0].mem
;
1131 /* If BAR is mapped and page aligned, update to fill PAGE_SIZE */
1132 if (bar_addr
!= PCI_BAR_UNMAPPED
&&
1133 !(bar_addr
& ~qemu_real_host_page_mask())) {
1134 size
= qemu_real_host_page_size();
1137 memory_region_transaction_begin();
1139 if (vdev
->bars
[bar
].size
< size
) {
1140 memory_region_set_size(base_mr
, size
);
1142 memory_region_set_size(region_mr
, size
);
1143 memory_region_set_size(mmap_mr
, size
);
1144 if (size
!= vdev
->bars
[bar
].size
&& memory_region_is_mapped(base_mr
)) {
1145 memory_region_del_subregion(r
->address_space
, base_mr
);
1146 memory_region_add_subregion_overlap(r
->address_space
,
1147 bar_addr
, base_mr
, 0);
1150 memory_region_transaction_commit();
1156 uint32_t vfio_pci_read_config(PCIDevice
*pdev
, uint32_t addr
, int len
)
1158 VFIOPCIDevice
*vdev
= VFIO_PCI(pdev
);
1159 uint32_t emu_bits
= 0, emu_val
= 0, phys_val
= 0, val
;
1161 memcpy(&emu_bits
, vdev
->emulated_config_bits
+ addr
, len
);
1162 emu_bits
= le32_to_cpu(emu_bits
);
1165 emu_val
= pci_default_read_config(pdev
, addr
, len
);
1168 if (~emu_bits
& (0xffffffffU
>> (32 - len
* 8))) {
1171 ret
= pread(vdev
->vbasedev
.fd
, &phys_val
, len
,
1172 vdev
->config_offset
+ addr
);
1174 error_report("%s(%s, 0x%x, 0x%x) failed: %m",
1175 __func__
, vdev
->vbasedev
.name
, addr
, len
);
1178 phys_val
= le32_to_cpu(phys_val
);
1181 val
= (emu_val
& emu_bits
) | (phys_val
& ~emu_bits
);
1183 trace_vfio_pci_read_config(vdev
->vbasedev
.name
, addr
, len
, val
);
1188 void vfio_pci_write_config(PCIDevice
*pdev
,
1189 uint32_t addr
, uint32_t val
, int len
)
1191 VFIOPCIDevice
*vdev
= VFIO_PCI(pdev
);
1192 uint32_t val_le
= cpu_to_le32(val
);
1194 trace_vfio_pci_write_config(vdev
->vbasedev
.name
, addr
, val
, len
);
1196 /* Write everything to VFIO, let it filter out what we can't write */
1197 if (pwrite(vdev
->vbasedev
.fd
, &val_le
, len
, vdev
->config_offset
+ addr
)
1199 error_report("%s(%s, 0x%x, 0x%x, 0x%x) failed: %m",
1200 __func__
, vdev
->vbasedev
.name
, addr
, val
, len
);
1203 /* MSI/MSI-X Enabling/Disabling */
1204 if (pdev
->cap_present
& QEMU_PCI_CAP_MSI
&&
1205 ranges_overlap(addr
, len
, pdev
->msi_cap
, vdev
->msi_cap_size
)) {
1206 int is_enabled
, was_enabled
= msi_enabled(pdev
);
1208 pci_default_write_config(pdev
, addr
, val
, len
);
1210 is_enabled
= msi_enabled(pdev
);
1214 vfio_msi_enable(vdev
);
1218 vfio_msi_disable(vdev
);
1220 vfio_update_msi(vdev
);
1223 } else if (pdev
->cap_present
& QEMU_PCI_CAP_MSIX
&&
1224 ranges_overlap(addr
, len
, pdev
->msix_cap
, MSIX_CAP_LENGTH
)) {
1225 int is_enabled
, was_enabled
= msix_enabled(pdev
);
1227 pci_default_write_config(pdev
, addr
, val
, len
);
1229 is_enabled
= msix_enabled(pdev
);
1231 if (!was_enabled
&& is_enabled
) {
1232 vfio_msix_enable(vdev
);
1233 } else if (was_enabled
&& !is_enabled
) {
1234 vfio_msix_disable(vdev
);
1236 } else if (ranges_overlap(addr
, len
, PCI_BASE_ADDRESS_0
, 24) ||
1237 range_covers_byte(addr
, len
, PCI_COMMAND
)) {
1238 pcibus_t old_addr
[PCI_NUM_REGIONS
- 1];
1241 for (bar
= 0; bar
< PCI_ROM_SLOT
; bar
++) {
1242 old_addr
[bar
] = pdev
->io_regions
[bar
].addr
;
1245 pci_default_write_config(pdev
, addr
, val
, len
);
1247 for (bar
= 0; bar
< PCI_ROM_SLOT
; bar
++) {
1248 if (old_addr
[bar
] != pdev
->io_regions
[bar
].addr
&&
1249 vdev
->bars
[bar
].region
.size
> 0 &&
1250 vdev
->bars
[bar
].region
.size
< qemu_real_host_page_size()) {
1251 vfio_sub_page_bar_update_mapping(pdev
, bar
);
1255 /* Write everything to QEMU to keep emulated bits correct */
1256 pci_default_write_config(pdev
, addr
, val
, len
);
1263 static void vfio_disable_interrupts(VFIOPCIDevice
*vdev
)
1266 * More complicated than it looks. Disabling MSI/X transitions the
1267 * device to INTx mode (if supported). Therefore we need to first
1268 * disable MSI/X and then cleanup by disabling INTx.
1270 if (vdev
->interrupt
== VFIO_INT_MSIX
) {
1271 vfio_msix_disable(vdev
);
1272 } else if (vdev
->interrupt
== VFIO_INT_MSI
) {
1273 vfio_msi_disable(vdev
);
1276 if (vdev
->interrupt
== VFIO_INT_INTx
) {
1277 vfio_intx_disable(vdev
);
1281 static int vfio_msi_setup(VFIOPCIDevice
*vdev
, int pos
, Error
**errp
)
1284 bool msi_64bit
, msi_maskbit
;
1288 if (pread(vdev
->vbasedev
.fd
, &ctrl
, sizeof(ctrl
),
1289 vdev
->config_offset
+ pos
+ PCI_CAP_FLAGS
) != sizeof(ctrl
)) {
1290 error_setg_errno(errp
, errno
, "failed reading MSI PCI_CAP_FLAGS");
1293 ctrl
= le16_to_cpu(ctrl
);
1295 msi_64bit
= !!(ctrl
& PCI_MSI_FLAGS_64BIT
);
1296 msi_maskbit
= !!(ctrl
& PCI_MSI_FLAGS_MASKBIT
);
1297 entries
= 1 << ((ctrl
& PCI_MSI_FLAGS_QMASK
) >> 1);
1299 trace_vfio_msi_setup(vdev
->vbasedev
.name
, pos
);
1301 ret
= msi_init(&vdev
->pdev
, pos
, entries
, msi_64bit
, msi_maskbit
, &err
);
1303 if (ret
== -ENOTSUP
) {
1306 error_propagate_prepend(errp
, err
, "msi_init failed: ");
1309 vdev
->msi_cap_size
= 0xa + (msi_maskbit
? 0xa : 0) + (msi_64bit
? 0x4 : 0);
1314 static void vfio_pci_fixup_msix_region(VFIOPCIDevice
*vdev
)
1317 VFIORegion
*region
= &vdev
->bars
[vdev
->msix
->table_bar
].region
;
1320 * If the host driver allows mapping of a MSIX data, we are going to
1321 * do map the entire BAR and emulate MSIX table on top of that.
1323 if (vfio_has_region_cap(&vdev
->vbasedev
, region
->nr
,
1324 VFIO_REGION_INFO_CAP_MSIX_MAPPABLE
)) {
1329 * We expect to find a single mmap covering the whole BAR, anything else
1330 * means it's either unsupported or already setup.
1332 if (region
->nr_mmaps
!= 1 || region
->mmaps
[0].offset
||
1333 region
->size
!= region
->mmaps
[0].size
) {
1337 /* MSI-X table start and end aligned to host page size */
1338 start
= vdev
->msix
->table_offset
& qemu_real_host_page_mask();
1339 end
= REAL_HOST_PAGE_ALIGN((uint64_t)vdev
->msix
->table_offset
+
1340 (vdev
->msix
->entries
* PCI_MSIX_ENTRY_SIZE
));
1343 * Does the MSI-X table cover the beginning of the BAR? The whole BAR?
1344 * NB - Host page size is necessarily a power of two and so is the PCI
1345 * BAR (not counting EA yet), therefore if we have host page aligned
1346 * @start and @end, then any remainder of the BAR before or after those
1347 * must be at least host page sized and therefore mmap'able.
1350 if (end
>= region
->size
) {
1351 region
->nr_mmaps
= 0;
1352 g_free(region
->mmaps
);
1353 region
->mmaps
= NULL
;
1354 trace_vfio_msix_fixup(vdev
->vbasedev
.name
,
1355 vdev
->msix
->table_bar
, 0, 0);
1357 region
->mmaps
[0].offset
= end
;
1358 region
->mmaps
[0].size
= region
->size
- end
;
1359 trace_vfio_msix_fixup(vdev
->vbasedev
.name
,
1360 vdev
->msix
->table_bar
, region
->mmaps
[0].offset
,
1361 region
->mmaps
[0].offset
+ region
->mmaps
[0].size
);
1364 /* Maybe it's aligned at the end of the BAR */
1365 } else if (end
>= region
->size
) {
1366 region
->mmaps
[0].size
= start
;
1367 trace_vfio_msix_fixup(vdev
->vbasedev
.name
,
1368 vdev
->msix
->table_bar
, region
->mmaps
[0].offset
,
1369 region
->mmaps
[0].offset
+ region
->mmaps
[0].size
);
1371 /* Otherwise it must split the BAR */
1373 region
->nr_mmaps
= 2;
1374 region
->mmaps
= g_renew(VFIOMmap
, region
->mmaps
, 2);
1376 memcpy(®ion
->mmaps
[1], ®ion
->mmaps
[0], sizeof(VFIOMmap
));
1378 region
->mmaps
[0].size
= start
;
1379 trace_vfio_msix_fixup(vdev
->vbasedev
.name
,
1380 vdev
->msix
->table_bar
, region
->mmaps
[0].offset
,
1381 region
->mmaps
[0].offset
+ region
->mmaps
[0].size
);
1383 region
->mmaps
[1].offset
= end
;
1384 region
->mmaps
[1].size
= region
->size
- end
;
1385 trace_vfio_msix_fixup(vdev
->vbasedev
.name
,
1386 vdev
->msix
->table_bar
, region
->mmaps
[1].offset
,
1387 region
->mmaps
[1].offset
+ region
->mmaps
[1].size
);
1391 static void vfio_pci_relocate_msix(VFIOPCIDevice
*vdev
, Error
**errp
)
1393 int target_bar
= -1;
1396 if (!vdev
->msix
|| vdev
->msix_relo
== OFF_AUTOPCIBAR_OFF
) {
1400 /* The actual minimum size of MSI-X structures */
1401 msix_sz
= (vdev
->msix
->entries
* PCI_MSIX_ENTRY_SIZE
) +
1402 (QEMU_ALIGN_UP(vdev
->msix
->entries
, 64) / 8);
1403 /* Round up to host pages, we don't want to share a page */
1404 msix_sz
= REAL_HOST_PAGE_ALIGN(msix_sz
);
1405 /* PCI BARs must be a power of 2 */
1406 msix_sz
= pow2ceil(msix_sz
);
1408 if (vdev
->msix_relo
== OFF_AUTOPCIBAR_AUTO
) {
1410 * TODO: Lookup table for known devices.
1412 * Logically we might use an algorithm here to select the BAR adding
1413 * the least additional MMIO space, but we cannot programmatically
1414 * predict the driver dependency on BAR ordering or sizing, therefore
1415 * 'auto' becomes a lookup for combinations reported to work.
1417 if (target_bar
< 0) {
1418 error_setg(errp
, "No automatic MSI-X relocation available for "
1419 "device %04x:%04x", vdev
->vendor_id
, vdev
->device_id
);
1423 target_bar
= (int)(vdev
->msix_relo
- OFF_AUTOPCIBAR_BAR0
);
1426 /* I/O port BARs cannot host MSI-X structures */
1427 if (vdev
->bars
[target_bar
].ioport
) {
1428 error_setg(errp
, "Invalid MSI-X relocation BAR %d, "
1429 "I/O port BAR", target_bar
);
1433 /* Cannot use a BAR in the "shadow" of a 64-bit BAR */
1434 if (!vdev
->bars
[target_bar
].size
&&
1435 target_bar
> 0 && vdev
->bars
[target_bar
- 1].mem64
) {
1436 error_setg(errp
, "Invalid MSI-X relocation BAR %d, "
1437 "consumed by 64-bit BAR %d", target_bar
, target_bar
- 1);
1441 /* 2GB max size for 32-bit BARs, cannot double if already > 1G */
1442 if (vdev
->bars
[target_bar
].size
> 1 * GiB
&&
1443 !vdev
->bars
[target_bar
].mem64
) {
1444 error_setg(errp
, "Invalid MSI-X relocation BAR %d, "
1445 "no space to extend 32-bit BAR", target_bar
);
1450 * If adding a new BAR, test if we can make it 64bit. We make it
1451 * prefetchable since QEMU MSI-X emulation has no read side effects
1452 * and doing so makes mapping more flexible.
1454 if (!vdev
->bars
[target_bar
].size
) {
1455 if (target_bar
< (PCI_ROM_SLOT
- 1) &&
1456 !vdev
->bars
[target_bar
+ 1].size
) {
1457 vdev
->bars
[target_bar
].mem64
= true;
1458 vdev
->bars
[target_bar
].type
= PCI_BASE_ADDRESS_MEM_TYPE_64
;
1460 vdev
->bars
[target_bar
].type
|= PCI_BASE_ADDRESS_MEM_PREFETCH
;
1461 vdev
->bars
[target_bar
].size
= msix_sz
;
1462 vdev
->msix
->table_offset
= 0;
1464 vdev
->bars
[target_bar
].size
= MAX(vdev
->bars
[target_bar
].size
* 2,
1467 * Due to above size calc, MSI-X always starts halfway into the BAR,
1468 * which will always be a separate host page.
1470 vdev
->msix
->table_offset
= vdev
->bars
[target_bar
].size
/ 2;
1473 vdev
->msix
->table_bar
= target_bar
;
1474 vdev
->msix
->pba_bar
= target_bar
;
1475 /* Requires 8-byte alignment, but PCI_MSIX_ENTRY_SIZE guarantees that */
1476 vdev
->msix
->pba_offset
= vdev
->msix
->table_offset
+
1477 (vdev
->msix
->entries
* PCI_MSIX_ENTRY_SIZE
);
1479 trace_vfio_msix_relo(vdev
->vbasedev
.name
,
1480 vdev
->msix
->table_bar
, vdev
->msix
->table_offset
);
1484 * We don't have any control over how pci_add_capability() inserts
1485 * capabilities into the chain. In order to setup MSI-X we need a
1486 * MemoryRegion for the BAR. In order to setup the BAR and not
1487 * attempt to mmap the MSI-X table area, which VFIO won't allow, we
1488 * need to first look for where the MSI-X table lives. So we
1489 * unfortunately split MSI-X setup across two functions.
1491 static void vfio_msix_early_setup(VFIOPCIDevice
*vdev
, Error
**errp
)
1495 uint32_t table
, pba
;
1496 int fd
= vdev
->vbasedev
.fd
;
1499 pos
= pci_find_capability(&vdev
->pdev
, PCI_CAP_ID_MSIX
);
1504 if (pread(fd
, &ctrl
, sizeof(ctrl
),
1505 vdev
->config_offset
+ pos
+ PCI_MSIX_FLAGS
) != sizeof(ctrl
)) {
1506 error_setg_errno(errp
, errno
, "failed to read PCI MSIX FLAGS");
1510 if (pread(fd
, &table
, sizeof(table
),
1511 vdev
->config_offset
+ pos
+ PCI_MSIX_TABLE
) != sizeof(table
)) {
1512 error_setg_errno(errp
, errno
, "failed to read PCI MSIX TABLE");
1516 if (pread(fd
, &pba
, sizeof(pba
),
1517 vdev
->config_offset
+ pos
+ PCI_MSIX_PBA
) != sizeof(pba
)) {
1518 error_setg_errno(errp
, errno
, "failed to read PCI MSIX PBA");
1522 ctrl
= le16_to_cpu(ctrl
);
1523 table
= le32_to_cpu(table
);
1524 pba
= le32_to_cpu(pba
);
1526 msix
= g_malloc0(sizeof(*msix
));
1527 msix
->table_bar
= table
& PCI_MSIX_FLAGS_BIRMASK
;
1528 msix
->table_offset
= table
& ~PCI_MSIX_FLAGS_BIRMASK
;
1529 msix
->pba_bar
= pba
& PCI_MSIX_FLAGS_BIRMASK
;
1530 msix
->pba_offset
= pba
& ~PCI_MSIX_FLAGS_BIRMASK
;
1531 msix
->entries
= (ctrl
& PCI_MSIX_FLAGS_QSIZE
) + 1;
1534 * Test the size of the pba_offset variable and catch if it extends outside
1535 * of the specified BAR. If it is the case, we need to apply a hardware
1536 * specific quirk if the device is known or we have a broken configuration.
1538 if (msix
->pba_offset
>= vdev
->bars
[msix
->pba_bar
].region
.size
) {
1540 * Chelsio T5 Virtual Function devices are encoded as 0x58xx for T5
1541 * adapters. The T5 hardware returns an incorrect value of 0x8000 for
1542 * the VF PBA offset while the BAR itself is only 8k. The correct value
1543 * is 0x1000, so we hard code that here.
1545 if (vdev
->vendor_id
== PCI_VENDOR_ID_CHELSIO
&&
1546 (vdev
->device_id
& 0xff00) == 0x5800) {
1547 msix
->pba_offset
= 0x1000;
1549 * BAIDU KUNLUN Virtual Function devices for KUNLUN AI processor
1550 * return an incorrect value of 0x460000 for the VF PBA offset while
1551 * the BAR itself is only 0x10000. The correct value is 0xb400.
1553 } else if (vfio_pci_is(vdev
, PCI_VENDOR_ID_BAIDU
,
1554 PCI_DEVICE_ID_KUNLUN_VF
)) {
1555 msix
->pba_offset
= 0xb400;
1556 } else if (vdev
->msix_relo
== OFF_AUTOPCIBAR_OFF
) {
1557 error_setg(errp
, "hardware reports invalid configuration, "
1558 "MSIX PBA outside of specified BAR");
1564 trace_vfio_msix_early_setup(vdev
->vbasedev
.name
, pos
, msix
->table_bar
,
1565 msix
->table_offset
, msix
->entries
);
1568 vfio_pci_fixup_msix_region(vdev
);
1570 vfio_pci_relocate_msix(vdev
, errp
);
1573 static int vfio_msix_setup(VFIOPCIDevice
*vdev
, int pos
, Error
**errp
)
1578 vdev
->msix
->pending
= g_new0(unsigned long,
1579 BITS_TO_LONGS(vdev
->msix
->entries
));
1580 ret
= msix_init(&vdev
->pdev
, vdev
->msix
->entries
,
1581 vdev
->bars
[vdev
->msix
->table_bar
].mr
,
1582 vdev
->msix
->table_bar
, vdev
->msix
->table_offset
,
1583 vdev
->bars
[vdev
->msix
->pba_bar
].mr
,
1584 vdev
->msix
->pba_bar
, vdev
->msix
->pba_offset
, pos
,
1587 if (ret
== -ENOTSUP
) {
1588 warn_report_err(err
);
1592 error_propagate(errp
, err
);
1597 * The PCI spec suggests that devices provide additional alignment for
1598 * MSI-X structures and avoid overlapping non-MSI-X related registers.
1599 * For an assigned device, this hopefully means that emulation of MSI-X
1600 * structures does not affect the performance of the device. If devices
1601 * fail to provide that alignment, a significant performance penalty may
1602 * result, for instance Mellanox MT27500 VFs:
1603 * http://www.spinics.net/lists/kvm/msg125881.html
1605 * The PBA is simply not that important for such a serious regression and
1606 * most drivers do not appear to look at it. The solution for this is to
1607 * disable the PBA MemoryRegion unless it's being used. We disable it
1608 * here and only enable it if a masked vector fires through QEMU. As the
1609 * vector-use notifier is called, which occurs on unmask, we test whether
1610 * PBA emulation is needed and again disable if not.
1612 memory_region_set_enabled(&vdev
->pdev
.msix_pba_mmio
, false);
1615 * The emulated machine may provide a paravirt interface for MSIX setup
1616 * so it is not strictly necessary to emulate MSIX here. This becomes
1617 * helpful when frequently accessed MMIO registers are located in
1618 * subpages adjacent to the MSIX table but the MSIX data containing page
1619 * cannot be mapped because of a host page size bigger than the MSIX table
1622 if (object_property_get_bool(OBJECT(qdev_get_machine()),
1623 "vfio-no-msix-emulation", NULL
)) {
1624 memory_region_set_enabled(&vdev
->pdev
.msix_table_mmio
, false);
1630 static void vfio_teardown_msi(VFIOPCIDevice
*vdev
)
1632 msi_uninit(&vdev
->pdev
);
1635 msix_uninit(&vdev
->pdev
,
1636 vdev
->bars
[vdev
->msix
->table_bar
].mr
,
1637 vdev
->bars
[vdev
->msix
->pba_bar
].mr
);
1638 g_free(vdev
->msix
->pending
);
1645 static void vfio_mmap_set_enabled(VFIOPCIDevice
*vdev
, bool enabled
)
1649 for (i
= 0; i
< PCI_ROM_SLOT
; i
++) {
1650 vfio_region_mmaps_set_enabled(&vdev
->bars
[i
].region
, enabled
);
1654 static void vfio_bar_prepare(VFIOPCIDevice
*vdev
, int nr
)
1656 VFIOBAR
*bar
= &vdev
->bars
[nr
];
1661 /* Skip both unimplemented BARs and the upper half of 64bit BARS. */
1662 if (!bar
->region
.size
) {
1666 /* Determine what type of BAR this is for registration */
1667 ret
= pread(vdev
->vbasedev
.fd
, &pci_bar
, sizeof(pci_bar
),
1668 vdev
->config_offset
+ PCI_BASE_ADDRESS_0
+ (4 * nr
));
1669 if (ret
!= sizeof(pci_bar
)) {
1670 error_report("vfio: Failed to read BAR %d (%m)", nr
);
1674 pci_bar
= le32_to_cpu(pci_bar
);
1675 bar
->ioport
= (pci_bar
& PCI_BASE_ADDRESS_SPACE_IO
);
1676 bar
->mem64
= bar
->ioport
? 0 : (pci_bar
& PCI_BASE_ADDRESS_MEM_TYPE_64
);
1677 bar
->type
= pci_bar
& (bar
->ioport
? ~PCI_BASE_ADDRESS_IO_MASK
:
1678 ~PCI_BASE_ADDRESS_MEM_MASK
);
1679 bar
->size
= bar
->region
.size
;
1682 static void vfio_bars_prepare(VFIOPCIDevice
*vdev
)
1686 for (i
= 0; i
< PCI_ROM_SLOT
; i
++) {
1687 vfio_bar_prepare(vdev
, i
);
1691 static void vfio_bar_register(VFIOPCIDevice
*vdev
, int nr
)
1693 VFIOBAR
*bar
= &vdev
->bars
[nr
];
1700 bar
->mr
= g_new0(MemoryRegion
, 1);
1701 name
= g_strdup_printf("%s base BAR %d", vdev
->vbasedev
.name
, nr
);
1702 memory_region_init_io(bar
->mr
, OBJECT(vdev
), NULL
, NULL
, name
, bar
->size
);
1705 if (bar
->region
.size
) {
1706 memory_region_add_subregion(bar
->mr
, 0, bar
->region
.mem
);
1708 if (vfio_region_mmap(&bar
->region
)) {
1709 error_report("Failed to mmap %s BAR %d. Performance may be slow",
1710 vdev
->vbasedev
.name
, nr
);
1714 pci_register_bar(&vdev
->pdev
, nr
, bar
->type
, bar
->mr
);
1717 static void vfio_bars_register(VFIOPCIDevice
*vdev
)
1721 for (i
= 0; i
< PCI_ROM_SLOT
; i
++) {
1722 vfio_bar_register(vdev
, i
);
1726 static void vfio_bars_exit(VFIOPCIDevice
*vdev
)
1730 for (i
= 0; i
< PCI_ROM_SLOT
; i
++) {
1731 VFIOBAR
*bar
= &vdev
->bars
[i
];
1733 vfio_bar_quirk_exit(vdev
, i
);
1734 vfio_region_exit(&bar
->region
);
1735 if (bar
->region
.size
) {
1736 memory_region_del_subregion(bar
->mr
, bar
->region
.mem
);
1741 pci_unregister_vga(&vdev
->pdev
);
1742 vfio_vga_quirk_exit(vdev
);
1746 static void vfio_bars_finalize(VFIOPCIDevice
*vdev
)
1750 for (i
= 0; i
< PCI_ROM_SLOT
; i
++) {
1751 VFIOBAR
*bar
= &vdev
->bars
[i
];
1753 vfio_bar_quirk_finalize(vdev
, i
);
1754 vfio_region_finalize(&bar
->region
);
1757 object_unparent(OBJECT(bar
->mr
));
1764 vfio_vga_quirk_finalize(vdev
);
1765 for (i
= 0; i
< ARRAY_SIZE(vdev
->vga
->region
); i
++) {
1766 object_unparent(OBJECT(&vdev
->vga
->region
[i
].mem
));
1775 static uint8_t vfio_std_cap_max_size(PCIDevice
*pdev
, uint8_t pos
)
1778 uint16_t next
= PCI_CONFIG_SPACE_SIZE
;
1780 for (tmp
= pdev
->config
[PCI_CAPABILITY_LIST
]; tmp
;
1781 tmp
= pdev
->config
[tmp
+ PCI_CAP_LIST_NEXT
]) {
1782 if (tmp
> pos
&& tmp
< next
) {
1791 static uint16_t vfio_ext_cap_max_size(const uint8_t *config
, uint16_t pos
)
1793 uint16_t tmp
, next
= PCIE_CONFIG_SPACE_SIZE
;
1795 for (tmp
= PCI_CONFIG_SPACE_SIZE
; tmp
;
1796 tmp
= PCI_EXT_CAP_NEXT(pci_get_long(config
+ tmp
))) {
1797 if (tmp
> pos
&& tmp
< next
) {
1805 static void vfio_set_word_bits(uint8_t *buf
, uint16_t val
, uint16_t mask
)
1807 pci_set_word(buf
, (pci_get_word(buf
) & ~mask
) | val
);
1810 static void vfio_add_emulated_word(VFIOPCIDevice
*vdev
, int pos
,
1811 uint16_t val
, uint16_t mask
)
1813 vfio_set_word_bits(vdev
->pdev
.config
+ pos
, val
, mask
);
1814 vfio_set_word_bits(vdev
->pdev
.wmask
+ pos
, ~mask
, mask
);
1815 vfio_set_word_bits(vdev
->emulated_config_bits
+ pos
, mask
, mask
);
1818 static void vfio_set_long_bits(uint8_t *buf
, uint32_t val
, uint32_t mask
)
1820 pci_set_long(buf
, (pci_get_long(buf
) & ~mask
) | val
);
1823 static void vfio_add_emulated_long(VFIOPCIDevice
*vdev
, int pos
,
1824 uint32_t val
, uint32_t mask
)
1826 vfio_set_long_bits(vdev
->pdev
.config
+ pos
, val
, mask
);
1827 vfio_set_long_bits(vdev
->pdev
.wmask
+ pos
, ~mask
, mask
);
1828 vfio_set_long_bits(vdev
->emulated_config_bits
+ pos
, mask
, mask
);
1831 static void vfio_pci_enable_rp_atomics(VFIOPCIDevice
*vdev
)
1833 struct vfio_device_info_cap_pci_atomic_comp
*cap
;
1834 g_autofree
struct vfio_device_info
*info
= NULL
;
1835 PCIBus
*bus
= pci_get_bus(&vdev
->pdev
);
1836 PCIDevice
*parent
= bus
->parent_dev
;
1837 struct vfio_info_cap_header
*hdr
;
1842 * PCIe Atomic Ops completer support is only added automatically for single
1843 * function devices downstream of a root port supporting DEVCAP2. Support
1844 * is added during realize and, if added, removed during device exit. The
1845 * single function requirement avoids conflicting requirements should a
1846 * slot be composed of multiple devices with differing capabilities.
1848 if (pci_bus_is_root(bus
) || !parent
|| !parent
->exp
.exp_cap
||
1849 pcie_cap_get_type(parent
) != PCI_EXP_TYPE_ROOT_PORT
||
1850 pcie_cap_get_version(parent
) != PCI_EXP_FLAGS_VER2
||
1852 vdev
->pdev
.cap_present
& QEMU_PCI_CAP_MULTIFUNCTION
) {
1856 pos
= parent
->config
+ parent
->exp
.exp_cap
+ PCI_EXP_DEVCAP2
;
1858 /* Abort if there'a already an Atomic Ops configuration on the root port */
1859 if (pci_get_long(pos
) & (PCI_EXP_DEVCAP2_ATOMIC_COMP32
|
1860 PCI_EXP_DEVCAP2_ATOMIC_COMP64
|
1861 PCI_EXP_DEVCAP2_ATOMIC_COMP128
)) {
1865 info
= vfio_get_device_info(vdev
->vbasedev
.fd
);
1870 hdr
= vfio_get_device_info_cap(info
, VFIO_DEVICE_INFO_CAP_PCI_ATOMIC_COMP
);
1876 if (cap
->flags
& VFIO_PCI_ATOMIC_COMP32
) {
1877 mask
|= PCI_EXP_DEVCAP2_ATOMIC_COMP32
;
1879 if (cap
->flags
& VFIO_PCI_ATOMIC_COMP64
) {
1880 mask
|= PCI_EXP_DEVCAP2_ATOMIC_COMP64
;
1882 if (cap
->flags
& VFIO_PCI_ATOMIC_COMP128
) {
1883 mask
|= PCI_EXP_DEVCAP2_ATOMIC_COMP128
;
1890 pci_long_test_and_set_mask(pos
, mask
);
1891 vdev
->clear_parent_atomics_on_exit
= true;
1894 static void vfio_pci_disable_rp_atomics(VFIOPCIDevice
*vdev
)
1896 if (vdev
->clear_parent_atomics_on_exit
) {
1897 PCIDevice
*parent
= pci_get_bus(&vdev
->pdev
)->parent_dev
;
1898 uint8_t *pos
= parent
->config
+ parent
->exp
.exp_cap
+ PCI_EXP_DEVCAP2
;
1900 pci_long_test_and_clear_mask(pos
, PCI_EXP_DEVCAP2_ATOMIC_COMP32
|
1901 PCI_EXP_DEVCAP2_ATOMIC_COMP64
|
1902 PCI_EXP_DEVCAP2_ATOMIC_COMP128
);
1906 static int vfio_setup_pcie_cap(VFIOPCIDevice
*vdev
, int pos
, uint8_t size
,
1912 flags
= pci_get_word(vdev
->pdev
.config
+ pos
+ PCI_CAP_FLAGS
);
1913 type
= (flags
& PCI_EXP_FLAGS_TYPE
) >> 4;
1915 if (type
!= PCI_EXP_TYPE_ENDPOINT
&&
1916 type
!= PCI_EXP_TYPE_LEG_END
&&
1917 type
!= PCI_EXP_TYPE_RC_END
) {
1919 error_setg(errp
, "assignment of PCIe type 0x%x "
1920 "devices is not currently supported", type
);
1924 if (!pci_bus_is_express(pci_get_bus(&vdev
->pdev
))) {
1925 PCIBus
*bus
= pci_get_bus(&vdev
->pdev
);
1929 * Traditionally PCI device assignment exposes the PCIe capability
1930 * as-is on non-express buses. The reason being that some drivers
1931 * simply assume that it's there, for example tg3. However when
1932 * we're running on a native PCIe machine type, like Q35, we need
1933 * to hide the PCIe capability. The reason for this is twofold;
1934 * first Windows guests get a Code 10 error when the PCIe capability
1935 * is exposed in this configuration. Therefore express devices won't
1936 * work at all unless they're attached to express buses in the VM.
1937 * Second, a native PCIe machine introduces the possibility of fine
1938 * granularity IOMMUs supporting both translation and isolation.
1939 * Guest code to discover the IOMMU visibility of a device, such as
1940 * IOMMU grouping code on Linux, is very aware of device types and
1941 * valid transitions between bus types. An express device on a non-
1942 * express bus is not a valid combination on bare metal systems.
1944 * Drivers that require a PCIe capability to make the device
1945 * functional are simply going to need to have their devices placed
1946 * on a PCIe bus in the VM.
1948 while (!pci_bus_is_root(bus
)) {
1949 bridge
= pci_bridge_get_device(bus
);
1950 bus
= pci_get_bus(bridge
);
1953 if (pci_bus_is_express(bus
)) {
1957 } else if (pci_bus_is_root(pci_get_bus(&vdev
->pdev
))) {
1959 * On a Root Complex bus Endpoints become Root Complex Integrated
1960 * Endpoints, which changes the type and clears the LNK & LNK2 fields.
1962 if (type
== PCI_EXP_TYPE_ENDPOINT
) {
1963 vfio_add_emulated_word(vdev
, pos
+ PCI_CAP_FLAGS
,
1964 PCI_EXP_TYPE_RC_END
<< 4,
1965 PCI_EXP_FLAGS_TYPE
);
1967 /* Link Capabilities, Status, and Control goes away */
1968 if (size
> PCI_EXP_LNKCTL
) {
1969 vfio_add_emulated_long(vdev
, pos
+ PCI_EXP_LNKCAP
, 0, ~0);
1970 vfio_add_emulated_word(vdev
, pos
+ PCI_EXP_LNKCTL
, 0, ~0);
1971 vfio_add_emulated_word(vdev
, pos
+ PCI_EXP_LNKSTA
, 0, ~0);
1973 #ifndef PCI_EXP_LNKCAP2
1974 #define PCI_EXP_LNKCAP2 44
1976 #ifndef PCI_EXP_LNKSTA2
1977 #define PCI_EXP_LNKSTA2 50
1979 /* Link 2 Capabilities, Status, and Control goes away */
1980 if (size
> PCI_EXP_LNKCAP2
) {
1981 vfio_add_emulated_long(vdev
, pos
+ PCI_EXP_LNKCAP2
, 0, ~0);
1982 vfio_add_emulated_word(vdev
, pos
+ PCI_EXP_LNKCTL2
, 0, ~0);
1983 vfio_add_emulated_word(vdev
, pos
+ PCI_EXP_LNKSTA2
, 0, ~0);
1987 } else if (type
== PCI_EXP_TYPE_LEG_END
) {
1989 * Legacy endpoints don't belong on the root complex. Windows
1990 * seems to be happier with devices if we skip the capability.
1997 * Convert Root Complex Integrated Endpoints to regular endpoints.
1998 * These devices don't support LNK/LNK2 capabilities, so make them up.
2000 if (type
== PCI_EXP_TYPE_RC_END
) {
2001 vfio_add_emulated_word(vdev
, pos
+ PCI_CAP_FLAGS
,
2002 PCI_EXP_TYPE_ENDPOINT
<< 4,
2003 PCI_EXP_FLAGS_TYPE
);
2004 vfio_add_emulated_long(vdev
, pos
+ PCI_EXP_LNKCAP
,
2005 QEMU_PCI_EXP_LNKCAP_MLW(QEMU_PCI_EXP_LNK_X1
) |
2006 QEMU_PCI_EXP_LNKCAP_MLS(QEMU_PCI_EXP_LNK_2_5GT
), ~0);
2007 vfio_add_emulated_word(vdev
, pos
+ PCI_EXP_LNKCTL
, 0, ~0);
2010 vfio_pci_enable_rp_atomics(vdev
);
2014 * Intel 82599 SR-IOV VFs report an invalid PCIe capability version 0
2015 * (Niantic errate #35) causing Windows to error with a Code 10 for the
2016 * device on Q35. Fixup any such devices to report version 1. If we
2017 * were to remove the capability entirely the guest would lose extended
2020 if ((flags
& PCI_EXP_FLAGS_VERS
) == 0) {
2021 vfio_add_emulated_word(vdev
, pos
+ PCI_CAP_FLAGS
,
2022 1, PCI_EXP_FLAGS_VERS
);
2025 pos
= pci_add_capability(&vdev
->pdev
, PCI_CAP_ID_EXP
, pos
, size
,
2031 vdev
->pdev
.exp
.exp_cap
= pos
;
2036 static void vfio_check_pcie_flr(VFIOPCIDevice
*vdev
, uint8_t pos
)
2038 uint32_t cap
= pci_get_long(vdev
->pdev
.config
+ pos
+ PCI_EXP_DEVCAP
);
2040 if (cap
& PCI_EXP_DEVCAP_FLR
) {
2041 trace_vfio_check_pcie_flr(vdev
->vbasedev
.name
);
2042 vdev
->has_flr
= true;
2046 static void vfio_check_pm_reset(VFIOPCIDevice
*vdev
, uint8_t pos
)
2048 uint16_t csr
= pci_get_word(vdev
->pdev
.config
+ pos
+ PCI_PM_CTRL
);
2050 if (!(csr
& PCI_PM_CTRL_NO_SOFT_RESET
)) {
2051 trace_vfio_check_pm_reset(vdev
->vbasedev
.name
);
2052 vdev
->has_pm_reset
= true;
2056 static void vfio_check_af_flr(VFIOPCIDevice
*vdev
, uint8_t pos
)
2058 uint8_t cap
= pci_get_byte(vdev
->pdev
.config
+ pos
+ PCI_AF_CAP
);
2060 if ((cap
& PCI_AF_CAP_TP
) && (cap
& PCI_AF_CAP_FLR
)) {
2061 trace_vfio_check_af_flr(vdev
->vbasedev
.name
);
2062 vdev
->has_flr
= true;
2066 static int vfio_add_std_cap(VFIOPCIDevice
*vdev
, uint8_t pos
, Error
**errp
)
2068 PCIDevice
*pdev
= &vdev
->pdev
;
2069 uint8_t cap_id
, next
, size
;
2072 cap_id
= pdev
->config
[pos
];
2073 next
= pdev
->config
[pos
+ PCI_CAP_LIST_NEXT
];
2076 * If it becomes important to configure capabilities to their actual
2077 * size, use this as the default when it's something we don't recognize.
2078 * Since QEMU doesn't actually handle many of the config accesses,
2079 * exact size doesn't seem worthwhile.
2081 size
= vfio_std_cap_max_size(pdev
, pos
);
2084 * pci_add_capability always inserts the new capability at the head
2085 * of the chain. Therefore to end up with a chain that matches the
2086 * physical device, we insert from the end by making this recursive.
2087 * This is also why we pre-calculate size above as cached config space
2088 * will be changed as we unwind the stack.
2091 ret
= vfio_add_std_cap(vdev
, next
, errp
);
2096 /* Begin the rebuild, use QEMU emulated list bits */
2097 pdev
->config
[PCI_CAPABILITY_LIST
] = 0;
2098 vdev
->emulated_config_bits
[PCI_CAPABILITY_LIST
] = 0xff;
2099 vdev
->emulated_config_bits
[PCI_STATUS
] |= PCI_STATUS_CAP_LIST
;
2101 ret
= vfio_add_virt_caps(vdev
, errp
);
2107 /* Scale down size, esp in case virt caps were added above */
2108 size
= MIN(size
, vfio_std_cap_max_size(pdev
, pos
));
2110 /* Use emulated next pointer to allow dropping caps */
2111 pci_set_byte(vdev
->emulated_config_bits
+ pos
+ PCI_CAP_LIST_NEXT
, 0xff);
2114 case PCI_CAP_ID_MSI
:
2115 ret
= vfio_msi_setup(vdev
, pos
, errp
);
2117 case PCI_CAP_ID_EXP
:
2118 vfio_check_pcie_flr(vdev
, pos
);
2119 ret
= vfio_setup_pcie_cap(vdev
, pos
, size
, errp
);
2121 case PCI_CAP_ID_MSIX
:
2122 ret
= vfio_msix_setup(vdev
, pos
, errp
);
2125 vfio_check_pm_reset(vdev
, pos
);
2127 ret
= pci_add_capability(pdev
, cap_id
, pos
, size
, errp
);
2130 vfio_check_af_flr(vdev
, pos
);
2131 ret
= pci_add_capability(pdev
, cap_id
, pos
, size
, errp
);
2134 ret
= pci_add_capability(pdev
, cap_id
, pos
, size
, errp
);
2140 "failed to add PCI capability 0x%x[0x%x]@0x%x: ",
2148 static int vfio_setup_rebar_ecap(VFIOPCIDevice
*vdev
, uint16_t pos
)
2153 ctrl
= pci_get_long(vdev
->pdev
.config
+ pos
+ PCI_REBAR_CTRL
);
2154 nbar
= (ctrl
& PCI_REBAR_CTRL_NBAR_MASK
) >> PCI_REBAR_CTRL_NBAR_SHIFT
;
2156 for (i
= 0; i
< nbar
; i
++) {
2160 ctrl
= pci_get_long(vdev
->pdev
.config
+ pos
+ PCI_REBAR_CTRL
+ (i
* 8));
2161 size
= (ctrl
& PCI_REBAR_CTRL_BAR_SIZE
) >> PCI_REBAR_CTRL_BAR_SHIFT
;
2163 /* The cap register reports sizes 1MB to 128TB, with 4 reserved bits */
2164 cap
= size
<= 27 ? 1U << (size
+ 4) : 0;
2167 * The PCIe spec (v6.0.1, 7.8.6) requires HW to support at least one
2168 * size in the range 1MB to 512GB. We intend to mask all sizes except
2169 * the one currently enabled in the size field, therefore if it's
2170 * outside the range, hide the whole capability as this virtualization
2171 * trick won't work. If >512GB resizable BARs start to appear, we
2172 * might need an opt-in or reservation scheme in the kernel.
2174 if (!(cap
& PCI_REBAR_CAP_SIZES
)) {
2178 /* Hide all sizes reported in the ctrl reg per above requirement. */
2179 ctrl
&= (PCI_REBAR_CTRL_BAR_SIZE
|
2180 PCI_REBAR_CTRL_NBAR_MASK
|
2181 PCI_REBAR_CTRL_BAR_IDX
);
2184 * The BAR size field is RW, however we've mangled the capability
2185 * register such that we only report a single size, ie. the current
2186 * BAR size. A write of an unsupported value is undefined, therefore
2187 * the register field is essentially RO.
2189 vfio_add_emulated_long(vdev
, pos
+ PCI_REBAR_CAP
+ (i
* 8), cap
, ~0);
2190 vfio_add_emulated_long(vdev
, pos
+ PCI_REBAR_CTRL
+ (i
* 8), ctrl
, ~0);
2196 static void vfio_add_ext_cap(VFIOPCIDevice
*vdev
)
2198 PCIDevice
*pdev
= &vdev
->pdev
;
2200 uint16_t cap_id
, next
, size
;
2204 /* Only add extended caps if we have them and the guest can see them */
2205 if (!pci_is_express(pdev
) || !pci_bus_is_express(pci_get_bus(pdev
)) ||
2206 !pci_get_long(pdev
->config
+ PCI_CONFIG_SPACE_SIZE
)) {
2211 * pcie_add_capability always inserts the new capability at the tail
2212 * of the chain. Therefore to end up with a chain that matches the
2213 * physical device, we cache the config space to avoid overwriting
2214 * the original config space when we parse the extended capabilities.
2216 config
= g_memdup(pdev
->config
, vdev
->config_size
);
2219 * Extended capabilities are chained with each pointing to the next, so we
2220 * can drop anything other than the head of the chain simply by modifying
2221 * the previous next pointer. Seed the head of the chain here such that
2222 * we can simply skip any capabilities we want to drop below, regardless
2223 * of their position in the chain. If this stub capability still exists
2224 * after we add the capabilities we want to expose, update the capability
2225 * ID to zero. Note that we cannot seed with the capability header being
2226 * zero as this conflicts with definition of an absent capability chain
2227 * and prevents capabilities beyond the head of the list from being added.
2228 * By replacing the dummy capability ID with zero after walking the device
2229 * chain, we also transparently mark extended capabilities as absent if
2230 * no capabilities were added. Note that the PCIe spec defines an absence
2231 * of extended capabilities to be determined by a value of zero for the
2232 * capability ID, version, AND next pointer. A non-zero next pointer
2233 * should be sufficient to indicate additional capabilities are present,
2234 * which will occur if we call pcie_add_capability() below. The entire
2235 * first dword is emulated to support this.
2237 * NB. The kernel side does similar masking, so be prepared that our
2238 * view of the device may also contain a capability ID zero in the head
2239 * of the chain. Skip it for the same reason that we cannot seed the
2240 * chain with a zero capability.
2242 pci_set_long(pdev
->config
+ PCI_CONFIG_SPACE_SIZE
,
2243 PCI_EXT_CAP(0xFFFF, 0, 0));
2244 pci_set_long(pdev
->wmask
+ PCI_CONFIG_SPACE_SIZE
, 0);
2245 pci_set_long(vdev
->emulated_config_bits
+ PCI_CONFIG_SPACE_SIZE
, ~0);
2247 for (next
= PCI_CONFIG_SPACE_SIZE
; next
;
2248 next
= PCI_EXT_CAP_NEXT(pci_get_long(config
+ next
))) {
2249 header
= pci_get_long(config
+ next
);
2250 cap_id
= PCI_EXT_CAP_ID(header
);
2251 cap_ver
= PCI_EXT_CAP_VER(header
);
2254 * If it becomes important to configure extended capabilities to their
2255 * actual size, use this as the default when it's something we don't
2256 * recognize. Since QEMU doesn't actually handle many of the config
2257 * accesses, exact size doesn't seem worthwhile.
2259 size
= vfio_ext_cap_max_size(config
, next
);
2261 /* Use emulated next pointer to allow dropping extended caps */
2262 pci_long_test_and_set_mask(vdev
->emulated_config_bits
+ next
,
2263 PCI_EXT_CAP_NEXT_MASK
);
2266 case 0: /* kernel masked capability */
2267 case PCI_EXT_CAP_ID_SRIOV
: /* Read-only VF BARs confuse OVMF */
2268 case PCI_EXT_CAP_ID_ARI
: /* XXX Needs next function virtualization */
2269 trace_vfio_add_ext_cap_dropped(vdev
->vbasedev
.name
, cap_id
, next
);
2271 case PCI_EXT_CAP_ID_REBAR
:
2272 if (!vfio_setup_rebar_ecap(vdev
, next
)) {
2273 pcie_add_capability(pdev
, cap_id
, cap_ver
, next
, size
);
2277 pcie_add_capability(pdev
, cap_id
, cap_ver
, next
, size
);
2282 /* Cleanup chain head ID if necessary */
2283 if (pci_get_word(pdev
->config
+ PCI_CONFIG_SPACE_SIZE
) == 0xFFFF) {
2284 pci_set_word(pdev
->config
+ PCI_CONFIG_SPACE_SIZE
, 0);
2291 static int vfio_add_capabilities(VFIOPCIDevice
*vdev
, Error
**errp
)
2293 PCIDevice
*pdev
= &vdev
->pdev
;
2296 if (!(pdev
->config
[PCI_STATUS
] & PCI_STATUS_CAP_LIST
) ||
2297 !pdev
->config
[PCI_CAPABILITY_LIST
]) {
2298 return 0; /* Nothing to add */
2301 ret
= vfio_add_std_cap(vdev
, pdev
->config
[PCI_CAPABILITY_LIST
], errp
);
2306 vfio_add_ext_cap(vdev
);
2310 static void vfio_pci_pre_reset(VFIOPCIDevice
*vdev
)
2312 PCIDevice
*pdev
= &vdev
->pdev
;
2315 vfio_disable_interrupts(vdev
);
2317 /* Make sure the device is in D0 */
2322 pmcsr
= vfio_pci_read_config(pdev
, vdev
->pm_cap
+ PCI_PM_CTRL
, 2);
2323 state
= pmcsr
& PCI_PM_CTRL_STATE_MASK
;
2325 pmcsr
&= ~PCI_PM_CTRL_STATE_MASK
;
2326 vfio_pci_write_config(pdev
, vdev
->pm_cap
+ PCI_PM_CTRL
, pmcsr
, 2);
2327 /* vfio handles the necessary delay here */
2328 pmcsr
= vfio_pci_read_config(pdev
, vdev
->pm_cap
+ PCI_PM_CTRL
, 2);
2329 state
= pmcsr
& PCI_PM_CTRL_STATE_MASK
;
2331 error_report("vfio: Unable to power on device, stuck in D%d",
2338 * Stop any ongoing DMA by disconnecting I/O, MMIO, and bus master.
2339 * Also put INTx Disable in known state.
2341 cmd
= vfio_pci_read_config(pdev
, PCI_COMMAND
, 2);
2342 cmd
&= ~(PCI_COMMAND_IO
| PCI_COMMAND_MEMORY
| PCI_COMMAND_MASTER
|
2343 PCI_COMMAND_INTX_DISABLE
);
2344 vfio_pci_write_config(pdev
, PCI_COMMAND
, cmd
, 2);
2347 static void vfio_pci_post_reset(VFIOPCIDevice
*vdev
)
2352 vfio_intx_enable(vdev
, &err
);
2354 error_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
2357 for (nr
= 0; nr
< PCI_NUM_REGIONS
- 1; ++nr
) {
2358 off_t addr
= vdev
->config_offset
+ PCI_BASE_ADDRESS_0
+ (4 * nr
);
2360 uint32_t len
= sizeof(val
);
2362 if (pwrite(vdev
->vbasedev
.fd
, &val
, len
, addr
) != len
) {
2363 error_report("%s(%s) reset bar %d failed: %m", __func__
,
2364 vdev
->vbasedev
.name
, nr
);
2368 vfio_quirk_reset(vdev
);
2371 static bool vfio_pci_host_match(PCIHostDeviceAddress
*addr
, const char *name
)
2375 sprintf(tmp
, "%04x:%02x:%02x.%1x", addr
->domain
,
2376 addr
->bus
, addr
->slot
, addr
->function
);
2378 return (strcmp(tmp
, name
) == 0);
2381 static int vfio_pci_hot_reset(VFIOPCIDevice
*vdev
, bool single
)
2384 struct vfio_pci_hot_reset_info
*info
;
2385 struct vfio_pci_dependent_device
*devices
;
2386 struct vfio_pci_hot_reset
*reset
;
2391 trace_vfio_pci_hot_reset(vdev
->vbasedev
.name
, single
? "one" : "multi");
2394 vfio_pci_pre_reset(vdev
);
2396 vdev
->vbasedev
.needs_reset
= false;
2398 info
= g_malloc0(sizeof(*info
));
2399 info
->argsz
= sizeof(*info
);
2401 ret
= ioctl(vdev
->vbasedev
.fd
, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO
, info
);
2402 if (ret
&& errno
!= ENOSPC
) {
2404 if (!vdev
->has_pm_reset
) {
2405 error_report("vfio: Cannot reset device %s, "
2406 "no available reset mechanism.", vdev
->vbasedev
.name
);
2411 count
= info
->count
;
2412 info
= g_realloc(info
, sizeof(*info
) + (count
* sizeof(*devices
)));
2413 info
->argsz
= sizeof(*info
) + (count
* sizeof(*devices
));
2414 devices
= &info
->devices
[0];
2416 ret
= ioctl(vdev
->vbasedev
.fd
, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO
, info
);
2419 error_report("vfio: hot reset info failed: %m");
2423 trace_vfio_pci_hot_reset_has_dep_devices(vdev
->vbasedev
.name
);
2425 /* Verify that we have all the groups required */
2426 for (i
= 0; i
< info
->count
; i
++) {
2427 PCIHostDeviceAddress host
;
2429 VFIODevice
*vbasedev_iter
;
2431 host
.domain
= devices
[i
].segment
;
2432 host
.bus
= devices
[i
].bus
;
2433 host
.slot
= PCI_SLOT(devices
[i
].devfn
);
2434 host
.function
= PCI_FUNC(devices
[i
].devfn
);
2436 trace_vfio_pci_hot_reset_dep_devices(host
.domain
,
2437 host
.bus
, host
.slot
, host
.function
, devices
[i
].group_id
);
2439 if (vfio_pci_host_match(&host
, vdev
->vbasedev
.name
)) {
2443 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
2444 if (group
->groupid
== devices
[i
].group_id
) {
2450 if (!vdev
->has_pm_reset
) {
2451 error_report("vfio: Cannot reset device %s, "
2452 "depends on group %d which is not owned.",
2453 vdev
->vbasedev
.name
, devices
[i
].group_id
);
2459 /* Prep dependent devices for reset and clear our marker. */
2460 QLIST_FOREACH(vbasedev_iter
, &group
->device_list
, next
) {
2461 if (!vbasedev_iter
->dev
->realized
||
2462 vbasedev_iter
->type
!= VFIO_DEVICE_TYPE_PCI
) {
2465 tmp
= container_of(vbasedev_iter
, VFIOPCIDevice
, vbasedev
);
2466 if (vfio_pci_host_match(&host
, tmp
->vbasedev
.name
)) {
2471 vfio_pci_pre_reset(tmp
);
2472 tmp
->vbasedev
.needs_reset
= false;
2479 if (!single
&& !multi
) {
2484 /* Determine how many group fds need to be passed */
2486 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
2487 for (i
= 0; i
< info
->count
; i
++) {
2488 if (group
->groupid
== devices
[i
].group_id
) {
2495 reset
= g_malloc0(sizeof(*reset
) + (count
* sizeof(*fds
)));
2496 reset
->argsz
= sizeof(*reset
) + (count
* sizeof(*fds
));
2497 fds
= &reset
->group_fds
[0];
2499 /* Fill in group fds */
2500 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
2501 for (i
= 0; i
< info
->count
; i
++) {
2502 if (group
->groupid
== devices
[i
].group_id
) {
2503 fds
[reset
->count
++] = group
->fd
;
2510 ret
= ioctl(vdev
->vbasedev
.fd
, VFIO_DEVICE_PCI_HOT_RESET
, reset
);
2513 trace_vfio_pci_hot_reset_result(vdev
->vbasedev
.name
,
2514 ret
? strerror(errno
) : "Success");
2517 /* Re-enable INTx on affected devices */
2518 for (i
= 0; i
< info
->count
; i
++) {
2519 PCIHostDeviceAddress host
;
2521 VFIODevice
*vbasedev_iter
;
2523 host
.domain
= devices
[i
].segment
;
2524 host
.bus
= devices
[i
].bus
;
2525 host
.slot
= PCI_SLOT(devices
[i
].devfn
);
2526 host
.function
= PCI_FUNC(devices
[i
].devfn
);
2528 if (vfio_pci_host_match(&host
, vdev
->vbasedev
.name
)) {
2532 QLIST_FOREACH(group
, &vfio_group_list
, next
) {
2533 if (group
->groupid
== devices
[i
].group_id
) {
2542 QLIST_FOREACH(vbasedev_iter
, &group
->device_list
, next
) {
2543 if (!vbasedev_iter
->dev
->realized
||
2544 vbasedev_iter
->type
!= VFIO_DEVICE_TYPE_PCI
) {
2547 tmp
= container_of(vbasedev_iter
, VFIOPCIDevice
, vbasedev
);
2548 if (vfio_pci_host_match(&host
, tmp
->vbasedev
.name
)) {
2549 vfio_pci_post_reset(tmp
);
2556 vfio_pci_post_reset(vdev
);
2564 * We want to differentiate hot reset of multiple in-use devices vs hot reset
2565 * of a single in-use device. VFIO_DEVICE_RESET will already handle the case
2566 * of doing hot resets when there is only a single device per bus. The in-use
2567 * here refers to how many VFIODevices are affected. A hot reset that affects
2568 * multiple devices, but only a single in-use device, means that we can call
2569 * it from our bus ->reset() callback since the extent is effectively a single
2570 * device. This allows us to make use of it in the hotplug path. When there
2571 * are multiple in-use devices, we can only trigger the hot reset during a
2572 * system reset and thus from our reset handler. We separate _one vs _multi
2573 * here so that we don't overlap and do a double reset on the system reset
2574 * path where both our reset handler and ->reset() callback are used. Calling
2575 * _one() will only do a hot reset for the one in-use devices case, calling
2576 * _multi() will do nothing if a _one() would have been sufficient.
2578 static int vfio_pci_hot_reset_one(VFIOPCIDevice
*vdev
)
2580 return vfio_pci_hot_reset(vdev
, true);
2583 static int vfio_pci_hot_reset_multi(VFIODevice
*vbasedev
)
2585 VFIOPCIDevice
*vdev
= container_of(vbasedev
, VFIOPCIDevice
, vbasedev
);
2586 return vfio_pci_hot_reset(vdev
, false);
2589 static void vfio_pci_compute_needs_reset(VFIODevice
*vbasedev
)
2591 VFIOPCIDevice
*vdev
= container_of(vbasedev
, VFIOPCIDevice
, vbasedev
);
2592 if (!vbasedev
->reset_works
|| (!vdev
->has_flr
&& vdev
->has_pm_reset
)) {
2593 vbasedev
->needs_reset
= true;
2597 static Object
*vfio_pci_get_object(VFIODevice
*vbasedev
)
2599 VFIOPCIDevice
*vdev
= container_of(vbasedev
, VFIOPCIDevice
, vbasedev
);
2601 return OBJECT(vdev
);
2604 static bool vfio_msix_present(void *opaque
, int version_id
)
2606 PCIDevice
*pdev
= opaque
;
2608 return msix_present(pdev
);
2611 const VMStateDescription vmstate_vfio_pci_config
= {
2612 .name
= "VFIOPCIDevice",
2614 .minimum_version_id
= 1,
2615 .fields
= (VMStateField
[]) {
2616 VMSTATE_PCI_DEVICE(pdev
, VFIOPCIDevice
),
2617 VMSTATE_MSIX_TEST(pdev
, VFIOPCIDevice
, vfio_msix_present
),
2618 VMSTATE_END_OF_LIST()
2622 static void vfio_pci_save_config(VFIODevice
*vbasedev
, QEMUFile
*f
)
2624 VFIOPCIDevice
*vdev
= container_of(vbasedev
, VFIOPCIDevice
, vbasedev
);
2626 vmstate_save_state(f
, &vmstate_vfio_pci_config
, vdev
, NULL
);
2629 static int vfio_pci_load_config(VFIODevice
*vbasedev
, QEMUFile
*f
)
2631 VFIOPCIDevice
*vdev
= container_of(vbasedev
, VFIOPCIDevice
, vbasedev
);
2632 PCIDevice
*pdev
= &vdev
->pdev
;
2633 pcibus_t old_addr
[PCI_NUM_REGIONS
- 1];
2636 for (bar
= 0; bar
< PCI_ROM_SLOT
; bar
++) {
2637 old_addr
[bar
] = pdev
->io_regions
[bar
].addr
;
2640 ret
= vmstate_load_state(f
, &vmstate_vfio_pci_config
, vdev
, 1);
2645 vfio_pci_write_config(pdev
, PCI_COMMAND
,
2646 pci_get_word(pdev
->config
+ PCI_COMMAND
), 2);
2648 for (bar
= 0; bar
< PCI_ROM_SLOT
; bar
++) {
2650 * The address may not be changed in some scenarios
2651 * (e.g. the VF driver isn't loaded in VM).
2653 if (old_addr
[bar
] != pdev
->io_regions
[bar
].addr
&&
2654 vdev
->bars
[bar
].region
.size
> 0 &&
2655 vdev
->bars
[bar
].region
.size
< qemu_real_host_page_size()) {
2656 vfio_sub_page_bar_update_mapping(pdev
, bar
);
2660 if (msi_enabled(pdev
)) {
2661 vfio_msi_enable(vdev
);
2662 } else if (msix_enabled(pdev
)) {
2663 vfio_msix_enable(vdev
);
2669 static VFIODeviceOps vfio_pci_ops
= {
2670 .vfio_compute_needs_reset
= vfio_pci_compute_needs_reset
,
2671 .vfio_hot_reset_multi
= vfio_pci_hot_reset_multi
,
2672 .vfio_eoi
= vfio_intx_eoi
,
2673 .vfio_get_object
= vfio_pci_get_object
,
2674 .vfio_save_config
= vfio_pci_save_config
,
2675 .vfio_load_config
= vfio_pci_load_config
,
2678 int vfio_populate_vga(VFIOPCIDevice
*vdev
, Error
**errp
)
2680 VFIODevice
*vbasedev
= &vdev
->vbasedev
;
2681 struct vfio_region_info
*reg_info
;
2684 ret
= vfio_get_region_info(vbasedev
, VFIO_PCI_VGA_REGION_INDEX
, ®_info
);
2686 error_setg_errno(errp
, -ret
,
2687 "failed getting region info for VGA region index %d",
2688 VFIO_PCI_VGA_REGION_INDEX
);
2692 if (!(reg_info
->flags
& VFIO_REGION_INFO_FLAG_READ
) ||
2693 !(reg_info
->flags
& VFIO_REGION_INFO_FLAG_WRITE
) ||
2694 reg_info
->size
< 0xbffff + 1) {
2695 error_setg(errp
, "unexpected VGA info, flags 0x%lx, size 0x%lx",
2696 (unsigned long)reg_info
->flags
,
2697 (unsigned long)reg_info
->size
);
2702 vdev
->vga
= g_new0(VFIOVGA
, 1);
2704 vdev
->vga
->fd_offset
= reg_info
->offset
;
2705 vdev
->vga
->fd
= vdev
->vbasedev
.fd
;
2709 vdev
->vga
->region
[QEMU_PCI_VGA_MEM
].offset
= QEMU_PCI_VGA_MEM_BASE
;
2710 vdev
->vga
->region
[QEMU_PCI_VGA_MEM
].nr
= QEMU_PCI_VGA_MEM
;
2711 QLIST_INIT(&vdev
->vga
->region
[QEMU_PCI_VGA_MEM
].quirks
);
2713 memory_region_init_io(&vdev
->vga
->region
[QEMU_PCI_VGA_MEM
].mem
,
2714 OBJECT(vdev
), &vfio_vga_ops
,
2715 &vdev
->vga
->region
[QEMU_PCI_VGA_MEM
],
2716 "vfio-vga-mmio@0xa0000",
2717 QEMU_PCI_VGA_MEM_SIZE
);
2719 vdev
->vga
->region
[QEMU_PCI_VGA_IO_LO
].offset
= QEMU_PCI_VGA_IO_LO_BASE
;
2720 vdev
->vga
->region
[QEMU_PCI_VGA_IO_LO
].nr
= QEMU_PCI_VGA_IO_LO
;
2721 QLIST_INIT(&vdev
->vga
->region
[QEMU_PCI_VGA_IO_LO
].quirks
);
2723 memory_region_init_io(&vdev
->vga
->region
[QEMU_PCI_VGA_IO_LO
].mem
,
2724 OBJECT(vdev
), &vfio_vga_ops
,
2725 &vdev
->vga
->region
[QEMU_PCI_VGA_IO_LO
],
2726 "vfio-vga-io@0x3b0",
2727 QEMU_PCI_VGA_IO_LO_SIZE
);
2729 vdev
->vga
->region
[QEMU_PCI_VGA_IO_HI
].offset
= QEMU_PCI_VGA_IO_HI_BASE
;
2730 vdev
->vga
->region
[QEMU_PCI_VGA_IO_HI
].nr
= QEMU_PCI_VGA_IO_HI
;
2731 QLIST_INIT(&vdev
->vga
->region
[QEMU_PCI_VGA_IO_HI
].quirks
);
2733 memory_region_init_io(&vdev
->vga
->region
[QEMU_PCI_VGA_IO_HI
].mem
,
2734 OBJECT(vdev
), &vfio_vga_ops
,
2735 &vdev
->vga
->region
[QEMU_PCI_VGA_IO_HI
],
2736 "vfio-vga-io@0x3c0",
2737 QEMU_PCI_VGA_IO_HI_SIZE
);
2739 pci_register_vga(&vdev
->pdev
, &vdev
->vga
->region
[QEMU_PCI_VGA_MEM
].mem
,
2740 &vdev
->vga
->region
[QEMU_PCI_VGA_IO_LO
].mem
,
2741 &vdev
->vga
->region
[QEMU_PCI_VGA_IO_HI
].mem
);
2746 static void vfio_populate_device(VFIOPCIDevice
*vdev
, Error
**errp
)
2748 VFIODevice
*vbasedev
= &vdev
->vbasedev
;
2749 struct vfio_region_info
*reg_info
;
2750 struct vfio_irq_info irq_info
= { .argsz
= sizeof(irq_info
) };
2753 /* Sanity check device */
2754 if (!(vbasedev
->flags
& VFIO_DEVICE_FLAGS_PCI
)) {
2755 error_setg(errp
, "this isn't a PCI device");
2759 if (vbasedev
->num_regions
< VFIO_PCI_CONFIG_REGION_INDEX
+ 1) {
2760 error_setg(errp
, "unexpected number of io regions %u",
2761 vbasedev
->num_regions
);
2765 if (vbasedev
->num_irqs
< VFIO_PCI_MSIX_IRQ_INDEX
+ 1) {
2766 error_setg(errp
, "unexpected number of irqs %u", vbasedev
->num_irqs
);
2770 for (i
= VFIO_PCI_BAR0_REGION_INDEX
; i
< VFIO_PCI_ROM_REGION_INDEX
; i
++) {
2771 char *name
= g_strdup_printf("%s BAR %d", vbasedev
->name
, i
);
2773 ret
= vfio_region_setup(OBJECT(vdev
), vbasedev
,
2774 &vdev
->bars
[i
].region
, i
, name
);
2778 error_setg_errno(errp
, -ret
, "failed to get region %d info", i
);
2782 QLIST_INIT(&vdev
->bars
[i
].quirks
);
2785 ret
= vfio_get_region_info(vbasedev
,
2786 VFIO_PCI_CONFIG_REGION_INDEX
, ®_info
);
2788 error_setg_errno(errp
, -ret
, "failed to get config info");
2792 trace_vfio_populate_device_config(vdev
->vbasedev
.name
,
2793 (unsigned long)reg_info
->size
,
2794 (unsigned long)reg_info
->offset
,
2795 (unsigned long)reg_info
->flags
);
2797 vdev
->config_size
= reg_info
->size
;
2798 if (vdev
->config_size
== PCI_CONFIG_SPACE_SIZE
) {
2799 vdev
->pdev
.cap_present
&= ~QEMU_PCI_CAP_EXPRESS
;
2801 vdev
->config_offset
= reg_info
->offset
;
2805 if (vdev
->features
& VFIO_FEATURE_ENABLE_VGA
) {
2806 ret
= vfio_populate_vga(vdev
, errp
);
2808 error_append_hint(errp
, "device does not support "
2809 "requested feature x-vga\n");
2814 irq_info
.index
= VFIO_PCI_ERR_IRQ_INDEX
;
2816 ret
= ioctl(vdev
->vbasedev
.fd
, VFIO_DEVICE_GET_IRQ_INFO
, &irq_info
);
2818 /* This can fail for an old kernel or legacy PCI dev */
2819 trace_vfio_populate_device_get_irq_info_failure(strerror(errno
));
2820 } else if (irq_info
.count
== 1) {
2821 vdev
->pci_aer
= true;
2823 warn_report(VFIO_MSG_PREFIX
2824 "Could not enable error recovery for the device",
2829 static void vfio_put_device(VFIOPCIDevice
*vdev
)
2831 g_free(vdev
->vbasedev
.name
);
2834 vfio_put_base_device(&vdev
->vbasedev
);
2837 static void vfio_err_notifier_handler(void *opaque
)
2839 VFIOPCIDevice
*vdev
= opaque
;
2841 if (!event_notifier_test_and_clear(&vdev
->err_notifier
)) {
2846 * TBD. Retrieve the error details and decide what action
2847 * needs to be taken. One of the actions could be to pass
2848 * the error to the guest and have the guest driver recover
2849 * from the error. This requires that PCIe capabilities be
2850 * exposed to the guest. For now, we just terminate the
2851 * guest to contain the error.
2854 error_report("%s(%s) Unrecoverable error detected. Please collect any data possible and then kill the guest", __func__
, vdev
->vbasedev
.name
);
2856 vm_stop(RUN_STATE_INTERNAL_ERROR
);
2860 * Registers error notifier for devices supporting error recovery.
2861 * If we encounter a failure in this function, we report an error
2862 * and continue after disabling error recovery support for the
2865 static void vfio_register_err_notifier(VFIOPCIDevice
*vdev
)
2870 if (!vdev
->pci_aer
) {
2874 if (event_notifier_init(&vdev
->err_notifier
, 0)) {
2875 error_report("vfio: Unable to init event notifier for error detection");
2876 vdev
->pci_aer
= false;
2880 fd
= event_notifier_get_fd(&vdev
->err_notifier
);
2881 qemu_set_fd_handler(fd
, vfio_err_notifier_handler
, NULL
, vdev
);
2883 if (vfio_set_irq_signaling(&vdev
->vbasedev
, VFIO_PCI_ERR_IRQ_INDEX
, 0,
2884 VFIO_IRQ_SET_ACTION_TRIGGER
, fd
, &err
)) {
2885 error_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
2886 qemu_set_fd_handler(fd
, NULL
, NULL
, vdev
);
2887 event_notifier_cleanup(&vdev
->err_notifier
);
2888 vdev
->pci_aer
= false;
2892 static void vfio_unregister_err_notifier(VFIOPCIDevice
*vdev
)
2896 if (!vdev
->pci_aer
) {
2900 if (vfio_set_irq_signaling(&vdev
->vbasedev
, VFIO_PCI_ERR_IRQ_INDEX
, 0,
2901 VFIO_IRQ_SET_ACTION_TRIGGER
, -1, &err
)) {
2902 error_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
2904 qemu_set_fd_handler(event_notifier_get_fd(&vdev
->err_notifier
),
2906 event_notifier_cleanup(&vdev
->err_notifier
);
2909 static void vfio_req_notifier_handler(void *opaque
)
2911 VFIOPCIDevice
*vdev
= opaque
;
2914 if (!event_notifier_test_and_clear(&vdev
->req_notifier
)) {
2918 qdev_unplug(DEVICE(vdev
), &err
);
2920 warn_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
2924 static void vfio_register_req_notifier(VFIOPCIDevice
*vdev
)
2926 struct vfio_irq_info irq_info
= { .argsz
= sizeof(irq_info
),
2927 .index
= VFIO_PCI_REQ_IRQ_INDEX
};
2931 if (!(vdev
->features
& VFIO_FEATURE_ENABLE_REQ
)) {
2935 if (ioctl(vdev
->vbasedev
.fd
,
2936 VFIO_DEVICE_GET_IRQ_INFO
, &irq_info
) < 0 || irq_info
.count
< 1) {
2940 if (event_notifier_init(&vdev
->req_notifier
, 0)) {
2941 error_report("vfio: Unable to init event notifier for device request");
2945 fd
= event_notifier_get_fd(&vdev
->req_notifier
);
2946 qemu_set_fd_handler(fd
, vfio_req_notifier_handler
, NULL
, vdev
);
2948 if (vfio_set_irq_signaling(&vdev
->vbasedev
, VFIO_PCI_REQ_IRQ_INDEX
, 0,
2949 VFIO_IRQ_SET_ACTION_TRIGGER
, fd
, &err
)) {
2950 error_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
2951 qemu_set_fd_handler(fd
, NULL
, NULL
, vdev
);
2952 event_notifier_cleanup(&vdev
->req_notifier
);
2954 vdev
->req_enabled
= true;
2958 static void vfio_unregister_req_notifier(VFIOPCIDevice
*vdev
)
2962 if (!vdev
->req_enabled
) {
2966 if (vfio_set_irq_signaling(&vdev
->vbasedev
, VFIO_PCI_REQ_IRQ_INDEX
, 0,
2967 VFIO_IRQ_SET_ACTION_TRIGGER
, -1, &err
)) {
2968 error_reportf_err(err
, VFIO_MSG_PREFIX
, vdev
->vbasedev
.name
);
2970 qemu_set_fd_handler(event_notifier_get_fd(&vdev
->req_notifier
),
2972 event_notifier_cleanup(&vdev
->req_notifier
);
2974 vdev
->req_enabled
= false;
2977 static void vfio_realize(PCIDevice
*pdev
, Error
**errp
)
2979 VFIOPCIDevice
*vdev
= VFIO_PCI(pdev
);
2980 VFIODevice
*vbasedev
= &vdev
->vbasedev
;
2981 VFIODevice
*vbasedev_iter
;
2983 char *tmp
, *subsys
, group_path
[PATH_MAX
], *group_name
;
2990 char uuid
[UUID_FMT_LEN
];
2993 if (!vbasedev
->sysfsdev
) {
2994 if (!(~vdev
->host
.domain
|| ~vdev
->host
.bus
||
2995 ~vdev
->host
.slot
|| ~vdev
->host
.function
)) {
2996 error_setg(errp
, "No provided host device");
2997 error_append_hint(errp
, "Use -device vfio-pci,host=DDDD:BB:DD.F "
2998 "or -device vfio-pci,sysfsdev=PATH_TO_DEVICE\n");
3001 vbasedev
->sysfsdev
=
3002 g_strdup_printf("/sys/bus/pci/devices/%04x:%02x:%02x.%01x",
3003 vdev
->host
.domain
, vdev
->host
.bus
,
3004 vdev
->host
.slot
, vdev
->host
.function
);
3007 if (stat(vbasedev
->sysfsdev
, &st
) < 0) {
3008 error_setg_errno(errp
, errno
, "no such host device");
3009 error_prepend(errp
, VFIO_MSG_PREFIX
, vbasedev
->sysfsdev
);
3013 vbasedev
->name
= g_path_get_basename(vbasedev
->sysfsdev
);
3014 vbasedev
->ops
= &vfio_pci_ops
;
3015 vbasedev
->type
= VFIO_DEVICE_TYPE_PCI
;
3016 vbasedev
->dev
= DEVICE(vdev
);
3018 tmp
= g_strdup_printf("%s/iommu_group", vbasedev
->sysfsdev
);
3019 len
= readlink(tmp
, group_path
, sizeof(group_path
));
3022 if (len
<= 0 || len
>= sizeof(group_path
)) {
3023 error_setg_errno(errp
, len
< 0 ? errno
: ENAMETOOLONG
,
3024 "no iommu_group found");
3028 group_path
[len
] = 0;
3030 group_name
= basename(group_path
);
3031 if (sscanf(group_name
, "%d", &groupid
) != 1) {
3032 error_setg_errno(errp
, errno
, "failed to read %s", group_path
);
3036 trace_vfio_realize(vbasedev
->name
, groupid
);
3038 group
= vfio_get_group(groupid
, pci_device_iommu_address_space(pdev
), errp
);
3043 QLIST_FOREACH(vbasedev_iter
, &group
->device_list
, next
) {
3044 if (strcmp(vbasedev_iter
->name
, vbasedev
->name
) == 0) {
3045 error_setg(errp
, "device is already attached");
3046 vfio_put_group(group
);
3052 * Mediated devices *might* operate compatibly with discarding of RAM, but
3053 * we cannot know for certain, it depends on whether the mdev vendor driver
3054 * stays in sync with the active working set of the guest driver. Prevent
3055 * the x-balloon-allowed option unless this is minimally an mdev device.
3057 tmp
= g_strdup_printf("%s/subsystem", vbasedev
->sysfsdev
);
3058 subsys
= realpath(tmp
, NULL
);
3060 is_mdev
= subsys
&& (strcmp(subsys
, "/sys/bus/mdev") == 0);
3063 trace_vfio_mdev(vbasedev
->name
, is_mdev
);
3065 if (vbasedev
->ram_block_discard_allowed
&& !is_mdev
) {
3066 error_setg(errp
, "x-balloon-allowed only potentially compatible "
3067 "with mdev devices");
3068 vfio_put_group(group
);
3072 if (!qemu_uuid_is_null(&vdev
->vf_token
)) {
3073 qemu_uuid_unparse(&vdev
->vf_token
, uuid
);
3074 name
= g_strdup_printf("%s vf_token=%s", vbasedev
->name
, uuid
);
3076 name
= g_strdup(vbasedev
->name
);
3079 ret
= vfio_get_device(group
, name
, vbasedev
, errp
);
3082 vfio_put_group(group
);
3086 vfio_populate_device(vdev
, &err
);
3088 error_propagate(errp
, err
);
3092 /* Get a copy of config space */
3093 ret
= pread(vbasedev
->fd
, vdev
->pdev
.config
,
3094 MIN(pci_config_size(&vdev
->pdev
), vdev
->config_size
),
3095 vdev
->config_offset
);
3096 if (ret
< (int)MIN(pci_config_size(&vdev
->pdev
), vdev
->config_size
)) {
3097 ret
= ret
< 0 ? -errno
: -EFAULT
;
3098 error_setg_errno(errp
, -ret
, "failed to read device config space");
3102 /* vfio emulates a lot for us, but some bits need extra love */
3103 vdev
->emulated_config_bits
= g_malloc0(vdev
->config_size
);
3105 /* QEMU can choose to expose the ROM or not */
3106 memset(vdev
->emulated_config_bits
+ PCI_ROM_ADDRESS
, 0xff, 4);
3107 /* QEMU can also add or extend BARs */
3108 memset(vdev
->emulated_config_bits
+ PCI_BASE_ADDRESS_0
, 0xff, 6 * 4);
3111 * The PCI spec reserves vendor ID 0xffff as an invalid value. The
3112 * device ID is managed by the vendor and need only be a 16-bit value.
3113 * Allow any 16-bit value for subsystem so they can be hidden or changed.
3115 if (vdev
->vendor_id
!= PCI_ANY_ID
) {
3116 if (vdev
->vendor_id
>= 0xffff) {
3117 error_setg(errp
, "invalid PCI vendor ID provided");
3120 vfio_add_emulated_word(vdev
, PCI_VENDOR_ID
, vdev
->vendor_id
, ~0);
3121 trace_vfio_pci_emulated_vendor_id(vbasedev
->name
, vdev
->vendor_id
);
3123 vdev
->vendor_id
= pci_get_word(pdev
->config
+ PCI_VENDOR_ID
);
3126 if (vdev
->device_id
!= PCI_ANY_ID
) {
3127 if (vdev
->device_id
> 0xffff) {
3128 error_setg(errp
, "invalid PCI device ID provided");
3131 vfio_add_emulated_word(vdev
, PCI_DEVICE_ID
, vdev
->device_id
, ~0);
3132 trace_vfio_pci_emulated_device_id(vbasedev
->name
, vdev
->device_id
);
3134 vdev
->device_id
= pci_get_word(pdev
->config
+ PCI_DEVICE_ID
);
3137 if (vdev
->sub_vendor_id
!= PCI_ANY_ID
) {
3138 if (vdev
->sub_vendor_id
> 0xffff) {
3139 error_setg(errp
, "invalid PCI subsystem vendor ID provided");
3142 vfio_add_emulated_word(vdev
, PCI_SUBSYSTEM_VENDOR_ID
,
3143 vdev
->sub_vendor_id
, ~0);
3144 trace_vfio_pci_emulated_sub_vendor_id(vbasedev
->name
,
3145 vdev
->sub_vendor_id
);
3148 if (vdev
->sub_device_id
!= PCI_ANY_ID
) {
3149 if (vdev
->sub_device_id
> 0xffff) {
3150 error_setg(errp
, "invalid PCI subsystem device ID provided");
3153 vfio_add_emulated_word(vdev
, PCI_SUBSYSTEM_ID
, vdev
->sub_device_id
, ~0);
3154 trace_vfio_pci_emulated_sub_device_id(vbasedev
->name
,
3155 vdev
->sub_device_id
);
3158 /* QEMU can change multi-function devices to single function, or reverse */
3159 vdev
->emulated_config_bits
[PCI_HEADER_TYPE
] =
3160 PCI_HEADER_TYPE_MULTI_FUNCTION
;
3162 /* Restore or clear multifunction, this is always controlled by QEMU */
3163 if (vdev
->pdev
.cap_present
& QEMU_PCI_CAP_MULTIFUNCTION
) {
3164 vdev
->pdev
.config
[PCI_HEADER_TYPE
] |= PCI_HEADER_TYPE_MULTI_FUNCTION
;
3166 vdev
->pdev
.config
[PCI_HEADER_TYPE
] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION
;
3170 * Clear host resource mapping info. If we choose not to register a
3171 * BAR, such as might be the case with the option ROM, we can get
3172 * confusing, unwritable, residual addresses from the host here.
3174 memset(&vdev
->pdev
.config
[PCI_BASE_ADDRESS_0
], 0, 24);
3175 memset(&vdev
->pdev
.config
[PCI_ROM_ADDRESS
], 0, 4);
3177 vfio_pci_size_rom(vdev
);
3179 vfio_bars_prepare(vdev
);
3181 vfio_msix_early_setup(vdev
, &err
);
3183 error_propagate(errp
, err
);
3187 vfio_bars_register(vdev
);
3189 ret
= vfio_add_capabilities(vdev
, errp
);
3195 vfio_vga_quirk_setup(vdev
);
3198 for (i
= 0; i
< PCI_ROM_SLOT
; i
++) {
3199 vfio_bar_quirk_setup(vdev
, i
);
3202 if (!vdev
->igd_opregion
&&
3203 vdev
->features
& VFIO_FEATURE_ENABLE_IGD_OPREGION
) {
3204 struct vfio_region_info
*opregion
;
3206 if (vdev
->pdev
.qdev
.hotplugged
) {
3208 "cannot support IGD OpRegion feature on hotplugged "
3213 ret
= vfio_get_dev_region_info(vbasedev
,
3214 VFIO_REGION_TYPE_PCI_VENDOR_TYPE
| PCI_VENDOR_ID_INTEL
,
3215 VFIO_REGION_SUBTYPE_INTEL_IGD_OPREGION
, &opregion
);
3217 error_setg_errno(errp
, -ret
,
3218 "does not support requested IGD OpRegion feature");
3222 ret
= vfio_pci_igd_opregion_init(vdev
, opregion
, errp
);
3229 /* QEMU emulates all of MSI & MSIX */
3230 if (pdev
->cap_present
& QEMU_PCI_CAP_MSIX
) {
3231 memset(vdev
->emulated_config_bits
+ pdev
->msix_cap
, 0xff,
3235 if (pdev
->cap_present
& QEMU_PCI_CAP_MSI
) {
3236 memset(vdev
->emulated_config_bits
+ pdev
->msi_cap
, 0xff,
3237 vdev
->msi_cap_size
);
3240 if (vfio_pci_read_config(&vdev
->pdev
, PCI_INTERRUPT_PIN
, 1)) {
3241 vdev
->intx
.mmap_timer
= timer_new_ms(QEMU_CLOCK_VIRTUAL
,
3242 vfio_intx_mmap_enable
, vdev
);
3243 pci_device_set_intx_routing_notifier(&vdev
->pdev
,
3244 vfio_intx_routing_notifier
);
3245 vdev
->irqchip_change_notifier
.notify
= vfio_irqchip_change
;
3246 kvm_irqchip_add_change_notifier(&vdev
->irqchip_change_notifier
);
3247 ret
= vfio_intx_enable(vdev
, errp
);
3249 goto out_deregister
;
3253 if (vdev
->display
!= ON_OFF_AUTO_OFF
) {
3254 ret
= vfio_display_probe(vdev
, errp
);
3256 goto out_deregister
;
3259 if (vdev
->enable_ramfb
&& vdev
->dpy
== NULL
) {
3260 error_setg(errp
, "ramfb=on requires display=on");
3261 goto out_deregister
;
3263 if (vdev
->display_xres
|| vdev
->display_yres
) {
3264 if (vdev
->dpy
== NULL
) {
3265 error_setg(errp
, "xres and yres properties require display=on");
3266 goto out_deregister
;
3268 if (vdev
->dpy
->edid_regs
== NULL
) {
3269 error_setg(errp
, "xres and yres properties need edid support");
3270 goto out_deregister
;
3274 if (!pdev
->failover_pair_id
) {
3275 if (!vfio_migration_realize(vbasedev
, errp
)) {
3276 goto out_deregister
;
3280 vfio_register_err_notifier(vdev
);
3281 vfio_register_req_notifier(vdev
);
3282 vfio_setup_resetfn_quirk(vdev
);
3287 if (vdev
->interrupt
== VFIO_INT_INTx
) {
3288 vfio_intx_disable(vdev
);
3290 pci_device_set_intx_routing_notifier(&vdev
->pdev
, NULL
);
3291 if (vdev
->irqchip_change_notifier
.notify
) {
3292 kvm_irqchip_remove_change_notifier(&vdev
->irqchip_change_notifier
);
3294 if (vdev
->intx
.mmap_timer
) {
3295 timer_free(vdev
->intx
.mmap_timer
);
3298 vfio_teardown_msi(vdev
);
3299 vfio_bars_exit(vdev
);
3301 error_prepend(errp
, VFIO_MSG_PREFIX
, vbasedev
->name
);
3304 static void vfio_instance_finalize(Object
*obj
)
3306 VFIOPCIDevice
*vdev
= VFIO_PCI(obj
);
3307 VFIOGroup
*group
= vdev
->vbasedev
.group
;
3309 vfio_display_finalize(vdev
);
3310 vfio_bars_finalize(vdev
);
3311 g_free(vdev
->emulated_config_bits
);
3314 * XXX Leaking igd_opregion is not an oversight, we can't remove the
3315 * fw_cfg entry therefore leaking this allocation seems like the safest
3318 * g_free(vdev->igd_opregion);
3320 vfio_put_device(vdev
);
3321 vfio_put_group(group
);
3324 static void vfio_exitfn(PCIDevice
*pdev
)
3326 VFIOPCIDevice
*vdev
= VFIO_PCI(pdev
);
3328 vfio_unregister_req_notifier(vdev
);
3329 vfio_unregister_err_notifier(vdev
);
3330 pci_device_set_intx_routing_notifier(&vdev
->pdev
, NULL
);
3331 if (vdev
->irqchip_change_notifier
.notify
) {
3332 kvm_irqchip_remove_change_notifier(&vdev
->irqchip_change_notifier
);
3334 vfio_disable_interrupts(vdev
);
3335 if (vdev
->intx
.mmap_timer
) {
3336 timer_free(vdev
->intx
.mmap_timer
);
3338 vfio_teardown_msi(vdev
);
3339 vfio_pci_disable_rp_atomics(vdev
);
3340 vfio_bars_exit(vdev
);
3341 vfio_migration_exit(&vdev
->vbasedev
);
3344 static void vfio_pci_reset(DeviceState
*dev
)
3346 VFIOPCIDevice
*vdev
= VFIO_PCI(dev
);
3348 trace_vfio_pci_reset(vdev
->vbasedev
.name
);
3350 vfio_pci_pre_reset(vdev
);
3352 if (vdev
->display
!= ON_OFF_AUTO_OFF
) {
3353 vfio_display_reset(vdev
);
3356 if (vdev
->resetfn
&& !vdev
->resetfn(vdev
)) {
3360 if (vdev
->vbasedev
.reset_works
&&
3361 (vdev
->has_flr
|| !vdev
->has_pm_reset
) &&
3362 !ioctl(vdev
->vbasedev
.fd
, VFIO_DEVICE_RESET
)) {
3363 trace_vfio_pci_reset_flr(vdev
->vbasedev
.name
);
3367 /* See if we can do our own bus reset */
3368 if (!vfio_pci_hot_reset_one(vdev
)) {
3372 /* If nothing else works and the device supports PM reset, use it */
3373 if (vdev
->vbasedev
.reset_works
&& vdev
->has_pm_reset
&&
3374 !ioctl(vdev
->vbasedev
.fd
, VFIO_DEVICE_RESET
)) {
3375 trace_vfio_pci_reset_pm(vdev
->vbasedev
.name
);
3380 vfio_pci_post_reset(vdev
);
3383 static void vfio_instance_init(Object
*obj
)
3385 PCIDevice
*pci_dev
= PCI_DEVICE(obj
);
3386 VFIOPCIDevice
*vdev
= VFIO_PCI(obj
);
3388 device_add_bootindex_property(obj
, &vdev
->bootindex
,
3391 vdev
->host
.domain
= ~0U;
3392 vdev
->host
.bus
= ~0U;
3393 vdev
->host
.slot
= ~0U;
3394 vdev
->host
.function
= ~0U;
3396 vdev
->nv_gpudirect_clique
= 0xFF;
3398 /* QEMU_PCI_CAP_EXPRESS initialization does not depend on QEMU command
3399 * line, therefore, no need to wait to realize like other devices */
3400 pci_dev
->cap_present
|= QEMU_PCI_CAP_EXPRESS
;
3403 static Property vfio_pci_dev_properties
[] = {
3404 DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIOPCIDevice
, host
),
3405 DEFINE_PROP_UUID_NODEFAULT("vf-token", VFIOPCIDevice
, vf_token
),
3406 DEFINE_PROP_STRING("sysfsdev", VFIOPCIDevice
, vbasedev
.sysfsdev
),
3407 DEFINE_PROP_ON_OFF_AUTO("x-pre-copy-dirty-page-tracking", VFIOPCIDevice
,
3408 vbasedev
.pre_copy_dirty_page_tracking
,
3410 DEFINE_PROP_ON_OFF_AUTO("display", VFIOPCIDevice
,
3411 display
, ON_OFF_AUTO_OFF
),
3412 DEFINE_PROP_UINT32("xres", VFIOPCIDevice
, display_xres
, 0),
3413 DEFINE_PROP_UINT32("yres", VFIOPCIDevice
, display_yres
, 0),
3414 DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIOPCIDevice
,
3415 intx
.mmap_timeout
, 1100),
3416 DEFINE_PROP_BIT("x-vga", VFIOPCIDevice
, features
,
3417 VFIO_FEATURE_ENABLE_VGA_BIT
, false),
3418 DEFINE_PROP_BIT("x-req", VFIOPCIDevice
, features
,
3419 VFIO_FEATURE_ENABLE_REQ_BIT
, true),
3420 DEFINE_PROP_BIT("x-igd-opregion", VFIOPCIDevice
, features
,
3421 VFIO_FEATURE_ENABLE_IGD_OPREGION_BIT
, false),
3422 DEFINE_PROP_ON_OFF_AUTO("enable-migration", VFIOPCIDevice
,
3423 vbasedev
.enable_migration
, ON_OFF_AUTO_AUTO
),
3424 DEFINE_PROP_BOOL("x-no-mmap", VFIOPCIDevice
, vbasedev
.no_mmap
, false),
3425 DEFINE_PROP_BOOL("x-balloon-allowed", VFIOPCIDevice
,
3426 vbasedev
.ram_block_discard_allowed
, false),
3427 DEFINE_PROP_BOOL("x-no-kvm-intx", VFIOPCIDevice
, no_kvm_intx
, false),
3428 DEFINE_PROP_BOOL("x-no-kvm-msi", VFIOPCIDevice
, no_kvm_msi
, false),
3429 DEFINE_PROP_BOOL("x-no-kvm-msix", VFIOPCIDevice
, no_kvm_msix
, false),
3430 DEFINE_PROP_BOOL("x-no-geforce-quirks", VFIOPCIDevice
,
3431 no_geforce_quirks
, false),
3432 DEFINE_PROP_BOOL("x-no-kvm-ioeventfd", VFIOPCIDevice
, no_kvm_ioeventfd
,
3434 DEFINE_PROP_BOOL("x-no-vfio-ioeventfd", VFIOPCIDevice
, no_vfio_ioeventfd
,
3436 DEFINE_PROP_UINT32("x-pci-vendor-id", VFIOPCIDevice
, vendor_id
, PCI_ANY_ID
),
3437 DEFINE_PROP_UINT32("x-pci-device-id", VFIOPCIDevice
, device_id
, PCI_ANY_ID
),
3438 DEFINE_PROP_UINT32("x-pci-sub-vendor-id", VFIOPCIDevice
,
3439 sub_vendor_id
, PCI_ANY_ID
),
3440 DEFINE_PROP_UINT32("x-pci-sub-device-id", VFIOPCIDevice
,
3441 sub_device_id
, PCI_ANY_ID
),
3442 DEFINE_PROP_UINT32("x-igd-gms", VFIOPCIDevice
, igd_gms
, 0),
3443 DEFINE_PROP_UNSIGNED_NODEFAULT("x-nv-gpudirect-clique", VFIOPCIDevice
,
3444 nv_gpudirect_clique
,
3445 qdev_prop_nv_gpudirect_clique
, uint8_t),
3446 DEFINE_PROP_OFF_AUTO_PCIBAR("x-msix-relocation", VFIOPCIDevice
, msix_relo
,
3447 OFF_AUTOPCIBAR_OFF
),
3449 * TODO - support passed fds... is this necessary?
3450 * DEFINE_PROP_STRING("vfiofd", VFIOPCIDevice, vfiofd_name),
3451 * DEFINE_PROP_STRING("vfiogroupfd, VFIOPCIDevice, vfiogroupfd_name),
3453 DEFINE_PROP_END_OF_LIST(),
3456 static void vfio_pci_dev_class_init(ObjectClass
*klass
, void *data
)
3458 DeviceClass
*dc
= DEVICE_CLASS(klass
);
3459 PCIDeviceClass
*pdc
= PCI_DEVICE_CLASS(klass
);
3461 dc
->reset
= vfio_pci_reset
;
3462 device_class_set_props(dc
, vfio_pci_dev_properties
);
3463 dc
->desc
= "VFIO-based PCI device assignment";
3464 set_bit(DEVICE_CATEGORY_MISC
, dc
->categories
);
3465 pdc
->realize
= vfio_realize
;
3466 pdc
->exit
= vfio_exitfn
;
3467 pdc
->config_read
= vfio_pci_read_config
;
3468 pdc
->config_write
= vfio_pci_write_config
;
3471 static const TypeInfo vfio_pci_dev_info
= {
3472 .name
= TYPE_VFIO_PCI
,
3473 .parent
= TYPE_PCI_DEVICE
,
3474 .instance_size
= sizeof(VFIOPCIDevice
),
3475 .class_init
= vfio_pci_dev_class_init
,
3476 .instance_init
= vfio_instance_init
,
3477 .instance_finalize
= vfio_instance_finalize
,
3478 .interfaces
= (InterfaceInfo
[]) {
3479 { INTERFACE_PCIE_DEVICE
},
3480 { INTERFACE_CONVENTIONAL_PCI_DEVICE
},
3485 static Property vfio_pci_dev_nohotplug_properties
[] = {
3486 DEFINE_PROP_BOOL("ramfb", VFIOPCIDevice
, enable_ramfb
, false),
3487 DEFINE_PROP_END_OF_LIST(),
3490 static void vfio_pci_nohotplug_dev_class_init(ObjectClass
*klass
, void *data
)
3492 DeviceClass
*dc
= DEVICE_CLASS(klass
);
3494 device_class_set_props(dc
, vfio_pci_dev_nohotplug_properties
);
3495 dc
->hotpluggable
= false;
3498 static const TypeInfo vfio_pci_nohotplug_dev_info
= {
3499 .name
= TYPE_VFIO_PCI_NOHOTPLUG
,
3500 .parent
= TYPE_VFIO_PCI
,
3501 .instance_size
= sizeof(VFIOPCIDevice
),
3502 .class_init
= vfio_pci_nohotplug_dev_class_init
,
3505 static void register_vfio_pci_dev_type(void)
3507 type_register_static(&vfio_pci_dev_info
);
3508 type_register_static(&vfio_pci_nohotplug_dev_info
);
3511 type_init(register_vfio_pci_dev_type
)