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