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