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