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