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