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