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