xref: /openbmc/qemu/hw/vfio/pci.c (revision 21f5826a)
1 /*
2  * vfio based device assignment support
3  *
4  * Copyright Red Hat, Inc. 2012
5  *
6  * Authors:
7  *  Alex Williamson <alex.williamson@redhat.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
12  * Based on qemu-kvm device-assignment:
13  *  Adapted for KVM by Qumranet.
14  *  Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
15  *  Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
16  *  Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
17  *  Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
18  *  Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
19  */
20 
21 #include <dirent.h>
22 #include <linux/vfio.h>
23 #include <sys/ioctl.h>
24 #include <sys/mman.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <unistd.h>
28 
29 #include "config.h"
30 #include "exec/address-spaces.h"
31 #include "exec/memory.h"
32 #include "hw/pci/msi.h"
33 #include "hw/pci/msix.h"
34 #include "hw/pci/pci.h"
35 #include "qemu-common.h"
36 #include "qemu/error-report.h"
37 #include "qemu/event_notifier.h"
38 #include "qemu/queue.h"
39 #include "qemu/range.h"
40 #include "sysemu/kvm.h"
41 #include "sysemu/sysemu.h"
42 #include "trace.h"
43 #include "hw/vfio/vfio.h"
44 #include "hw/vfio/vfio-common.h"
45 
46 struct VFIOPCIDevice;
47 
48 typedef struct VFIOQuirk {
49     MemoryRegion mem;
50     struct VFIOPCIDevice *vdev;
51     QLIST_ENTRY(VFIOQuirk) next;
52     struct {
53         uint32_t base_offset:TARGET_PAGE_BITS;
54         uint32_t address_offset:TARGET_PAGE_BITS;
55         uint32_t address_size:3;
56         uint32_t bar:3;
57 
58         uint32_t address_match;
59         uint32_t address_mask;
60 
61         uint32_t address_val:TARGET_PAGE_BITS;
62         uint32_t data_offset:TARGET_PAGE_BITS;
63         uint32_t data_size:3;
64 
65         uint8_t flags;
66         uint8_t read_flags;
67         uint8_t write_flags;
68     } data;
69 } VFIOQuirk;
70 
71 typedef struct VFIOBAR {
72     VFIORegion region;
73     bool ioport;
74     bool mem64;
75     QLIST_HEAD(, VFIOQuirk) quirks;
76 } VFIOBAR;
77 
78 typedef struct VFIOVGARegion {
79     MemoryRegion mem;
80     off_t offset;
81     int nr;
82     QLIST_HEAD(, VFIOQuirk) quirks;
83 } VFIOVGARegion;
84 
85 typedef struct VFIOVGA {
86     off_t fd_offset;
87     int fd;
88     VFIOVGARegion region[QEMU_PCI_VGA_NUM_REGIONS];
89 } VFIOVGA;
90 
91 typedef struct VFIOINTx {
92     bool pending; /* interrupt pending */
93     bool kvm_accel; /* set when QEMU bypass through KVM enabled */
94     uint8_t pin; /* which pin to pull for qemu_set_irq */
95     EventNotifier interrupt; /* eventfd triggered on interrupt */
96     EventNotifier unmask; /* eventfd for unmask on QEMU bypass */
97     PCIINTxRoute route; /* routing info for QEMU bypass */
98     uint32_t mmap_timeout; /* delay to re-enable mmaps after interrupt */
99     QEMUTimer *mmap_timer; /* enable mmaps after periods w/o interrupts */
100 } VFIOINTx;
101 
102 typedef struct VFIOMSIVector {
103     /*
104      * Two interrupt paths are configured per vector.  The first, is only used
105      * for interrupts injected via QEMU.  This is typically the non-accel path,
106      * but may also be used when we want QEMU to handle masking and pending
107      * bits.  The KVM path bypasses QEMU and is therefore higher performance,
108      * but requires masking at the device.  virq is used to track the MSI route
109      * through KVM, thus kvm_interrupt is only available when virq is set to a
110      * valid (>= 0) value.
111      */
112     EventNotifier interrupt;
113     EventNotifier kvm_interrupt;
114     struct VFIOPCIDevice *vdev; /* back pointer to device */
115     int virq;
116     bool use;
117 } VFIOMSIVector;
118 
119 enum {
120     VFIO_INT_NONE = 0,
121     VFIO_INT_INTx = 1,
122     VFIO_INT_MSI  = 2,
123     VFIO_INT_MSIX = 3,
124 };
125 
126 /* Cache of MSI-X setup plus extra mmap and memory region for split BAR map */
127 typedef struct VFIOMSIXInfo {
128     uint8_t table_bar;
129     uint8_t pba_bar;
130     uint16_t entries;
131     uint32_t table_offset;
132     uint32_t pba_offset;
133     MemoryRegion mmap_mem;
134     void *mmap;
135 } VFIOMSIXInfo;
136 
137 typedef struct VFIOPCIDevice {
138     PCIDevice pdev;
139     VFIODevice vbasedev;
140     VFIOINTx intx;
141     unsigned int config_size;
142     uint8_t *emulated_config_bits; /* QEMU emulated bits, little-endian */
143     off_t config_offset; /* Offset of config space region within device fd */
144     unsigned int rom_size;
145     off_t rom_offset; /* Offset of ROM region within device fd */
146     void *rom;
147     int msi_cap_size;
148     VFIOMSIVector *msi_vectors;
149     VFIOMSIXInfo *msix;
150     int nr_vectors; /* Number of MSI/MSIX vectors currently in use */
151     int interrupt; /* Current interrupt type */
152     VFIOBAR bars[PCI_NUM_REGIONS - 1]; /* No ROM */
153     VFIOVGA vga; /* 0xa0000, 0x3b0, 0x3c0 */
154     PCIHostDeviceAddress host;
155     EventNotifier err_notifier;
156     uint32_t features;
157 #define VFIO_FEATURE_ENABLE_VGA_BIT 0
158 #define VFIO_FEATURE_ENABLE_VGA (1 << VFIO_FEATURE_ENABLE_VGA_BIT)
159     int32_t bootindex;
160     uint8_t pm_cap;
161     bool has_vga;
162     bool pci_aer;
163     bool has_flr;
164     bool has_pm_reset;
165     bool rom_read_failed;
166 } VFIOPCIDevice;
167 
168 typedef struct VFIORomBlacklistEntry {
169     uint16_t vendor_id;
170     uint16_t device_id;
171 } VFIORomBlacklistEntry;
172 
173 /*
174  * List of device ids/vendor ids for which to disable
175  * option rom loading. This avoids the guest hangs during rom
176  * execution as noticed with the BCM 57810 card for lack of a
177  * more better way to handle such issues.
178  * The  user can still override by specifying a romfile or
179  * rombar=1.
180  * Please see https://bugs.launchpad.net/qemu/+bug/1284874
181  * for an analysis of the 57810 card hang. When adding
182  * a new vendor id/device id combination below, please also add
183  * your card/environment details and information that could
184  * help in debugging to the bug tracking this issue
185  */
186 static const VFIORomBlacklistEntry romblacklist[] = {
187     /* Broadcom BCM 57810 */
188     { 0x14e4, 0x168e }
189 };
190 
191 #define MSIX_CAP_LENGTH 12
192 
193 static void vfio_disable_interrupts(VFIOPCIDevice *vdev);
194 static uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len);
195 static void vfio_pci_write_config(PCIDevice *pdev, uint32_t addr,
196                                   uint32_t val, int len);
197 static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled);
198 
199 /*
200  * Disabling BAR mmaping can be slow, but toggling it around INTx can
201  * also be a huge overhead.  We try to get the best of both worlds by
202  * waiting until an interrupt to disable mmaps (subsequent transitions
203  * to the same state are effectively no overhead).  If the interrupt has
204  * been serviced and the time gap is long enough, we re-enable mmaps for
205  * performance.  This works well for things like graphics cards, which
206  * may not use their interrupt at all and are penalized to an unusable
207  * level by read/write BAR traps.  Other devices, like NICs, have more
208  * regular interrupts and see much better latency by staying in non-mmap
209  * mode.  We therefore set the default mmap_timeout such that a ping
210  * is just enough to keep the mmap disabled.  Users can experiment with
211  * other options with the x-intx-mmap-timeout-ms parameter (a value of
212  * zero disables the timer).
213  */
214 static void vfio_intx_mmap_enable(void *opaque)
215 {
216     VFIOPCIDevice *vdev = opaque;
217 
218     if (vdev->intx.pending) {
219         timer_mod(vdev->intx.mmap_timer,
220                        qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
221         return;
222     }
223 
224     vfio_mmap_set_enabled(vdev, true);
225 }
226 
227 static void vfio_intx_interrupt(void *opaque)
228 {
229     VFIOPCIDevice *vdev = opaque;
230 
231     if (!event_notifier_test_and_clear(&vdev->intx.interrupt)) {
232         return;
233     }
234 
235     trace_vfio_intx_interrupt(vdev->vbasedev.name, 'A' + vdev->intx.pin);
236 
237     vdev->intx.pending = true;
238     pci_irq_assert(&vdev->pdev);
239     vfio_mmap_set_enabled(vdev, false);
240     if (vdev->intx.mmap_timeout) {
241         timer_mod(vdev->intx.mmap_timer,
242                        qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
243     }
244 }
245 
246 static void vfio_eoi(VFIODevice *vbasedev)
247 {
248     VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
249 
250     if (!vdev->intx.pending) {
251         return;
252     }
253 
254     trace_vfio_eoi(vbasedev->name);
255 
256     vdev->intx.pending = false;
257     pci_irq_deassert(&vdev->pdev);
258     vfio_unmask_single_irqindex(vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
259 }
260 
261 static void vfio_enable_intx_kvm(VFIOPCIDevice *vdev)
262 {
263 #ifdef CONFIG_KVM
264     struct kvm_irqfd irqfd = {
265         .fd = event_notifier_get_fd(&vdev->intx.interrupt),
266         .gsi = vdev->intx.route.irq,
267         .flags = KVM_IRQFD_FLAG_RESAMPLE,
268     };
269     struct vfio_irq_set *irq_set;
270     int ret, argsz;
271     int32_t *pfd;
272 
273     if (!VFIO_ALLOW_KVM_INTX || !kvm_irqfds_enabled() ||
274         vdev->intx.route.mode != PCI_INTX_ENABLED ||
275         !kvm_resamplefds_enabled()) {
276         return;
277     }
278 
279     /* Get to a known interrupt state */
280     qemu_set_fd_handler(irqfd.fd, NULL, NULL, vdev);
281     vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
282     vdev->intx.pending = false;
283     pci_irq_deassert(&vdev->pdev);
284 
285     /* Get an eventfd for resample/unmask */
286     if (event_notifier_init(&vdev->intx.unmask, 0)) {
287         error_report("vfio: Error: event_notifier_init failed eoi");
288         goto fail;
289     }
290 
291     /* KVM triggers it, VFIO listens for it */
292     irqfd.resamplefd = event_notifier_get_fd(&vdev->intx.unmask);
293 
294     if (kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd)) {
295         error_report("vfio: Error: Failed to setup resample irqfd: %m");
296         goto fail_irqfd;
297     }
298 
299     argsz = sizeof(*irq_set) + sizeof(*pfd);
300 
301     irq_set = g_malloc0(argsz);
302     irq_set->argsz = argsz;
303     irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_UNMASK;
304     irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
305     irq_set->start = 0;
306     irq_set->count = 1;
307     pfd = (int32_t *)&irq_set->data;
308 
309     *pfd = irqfd.resamplefd;
310 
311     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
312     g_free(irq_set);
313     if (ret) {
314         error_report("vfio: Error: Failed to setup INTx unmask fd: %m");
315         goto fail_vfio;
316     }
317 
318     /* Let'em rip */
319     vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
320 
321     vdev->intx.kvm_accel = true;
322 
323     trace_vfio_enable_intx_kvm(vdev->vbasedev.name);
324 
325     return;
326 
327 fail_vfio:
328     irqfd.flags = KVM_IRQFD_FLAG_DEASSIGN;
329     kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd);
330 fail_irqfd:
331     event_notifier_cleanup(&vdev->intx.unmask);
332 fail:
333     qemu_set_fd_handler(irqfd.fd, vfio_intx_interrupt, NULL, vdev);
334     vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
335 #endif
336 }
337 
338 static void vfio_disable_intx_kvm(VFIOPCIDevice *vdev)
339 {
340 #ifdef CONFIG_KVM
341     struct kvm_irqfd irqfd = {
342         .fd = event_notifier_get_fd(&vdev->intx.interrupt),
343         .gsi = vdev->intx.route.irq,
344         .flags = KVM_IRQFD_FLAG_DEASSIGN,
345     };
346 
347     if (!vdev->intx.kvm_accel) {
348         return;
349     }
350 
351     /*
352      * Get to a known state, hardware masked, QEMU ready to accept new
353      * interrupts, QEMU IRQ de-asserted.
354      */
355     vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
356     vdev->intx.pending = false;
357     pci_irq_deassert(&vdev->pdev);
358 
359     /* Tell KVM to stop listening for an INTx irqfd */
360     if (kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd)) {
361         error_report("vfio: Error: Failed to disable INTx irqfd: %m");
362     }
363 
364     /* We only need to close the eventfd for VFIO to cleanup the kernel side */
365     event_notifier_cleanup(&vdev->intx.unmask);
366 
367     /* QEMU starts listening for interrupt events. */
368     qemu_set_fd_handler(irqfd.fd, vfio_intx_interrupt, NULL, vdev);
369 
370     vdev->intx.kvm_accel = false;
371 
372     /* If we've missed an event, let it re-fire through QEMU */
373     vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
374 
375     trace_vfio_disable_intx_kvm(vdev->vbasedev.name);
376 #endif
377 }
378 
379 static void vfio_update_irq(PCIDevice *pdev)
380 {
381     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
382     PCIINTxRoute route;
383 
384     if (vdev->interrupt != VFIO_INT_INTx) {
385         return;
386     }
387 
388     route = pci_device_route_intx_to_irq(&vdev->pdev, vdev->intx.pin);
389 
390     if (!pci_intx_route_changed(&vdev->intx.route, &route)) {
391         return; /* Nothing changed */
392     }
393 
394     trace_vfio_update_irq(vdev->vbasedev.name,
395                           vdev->intx.route.irq, route.irq);
396 
397     vfio_disable_intx_kvm(vdev);
398 
399     vdev->intx.route = route;
400 
401     if (route.mode != PCI_INTX_ENABLED) {
402         return;
403     }
404 
405     vfio_enable_intx_kvm(vdev);
406 
407     /* Re-enable the interrupt in cased we missed an EOI */
408     vfio_eoi(&vdev->vbasedev);
409 }
410 
411 static int vfio_enable_intx(VFIOPCIDevice *vdev)
412 {
413     uint8_t pin = vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1);
414     int ret, argsz;
415     struct vfio_irq_set *irq_set;
416     int32_t *pfd;
417 
418     if (!pin) {
419         return 0;
420     }
421 
422     vfio_disable_interrupts(vdev);
423 
424     vdev->intx.pin = pin - 1; /* Pin A (1) -> irq[0] */
425     pci_config_set_interrupt_pin(vdev->pdev.config, pin);
426 
427 #ifdef CONFIG_KVM
428     /*
429      * Only conditional to avoid generating error messages on platforms
430      * where we won't actually use the result anyway.
431      */
432     if (kvm_irqfds_enabled() && kvm_resamplefds_enabled()) {
433         vdev->intx.route = pci_device_route_intx_to_irq(&vdev->pdev,
434                                                         vdev->intx.pin);
435     }
436 #endif
437 
438     ret = event_notifier_init(&vdev->intx.interrupt, 0);
439     if (ret) {
440         error_report("vfio: Error: event_notifier_init failed");
441         return ret;
442     }
443 
444     argsz = sizeof(*irq_set) + sizeof(*pfd);
445 
446     irq_set = g_malloc0(argsz);
447     irq_set->argsz = argsz;
448     irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
449     irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
450     irq_set->start = 0;
451     irq_set->count = 1;
452     pfd = (int32_t *)&irq_set->data;
453 
454     *pfd = event_notifier_get_fd(&vdev->intx.interrupt);
455     qemu_set_fd_handler(*pfd, vfio_intx_interrupt, NULL, vdev);
456 
457     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
458     g_free(irq_set);
459     if (ret) {
460         error_report("vfio: Error: Failed to setup INTx fd: %m");
461         qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
462         event_notifier_cleanup(&vdev->intx.interrupt);
463         return -errno;
464     }
465 
466     vfio_enable_intx_kvm(vdev);
467 
468     vdev->interrupt = VFIO_INT_INTx;
469 
470     trace_vfio_enable_intx(vdev->vbasedev.name);
471 
472     return 0;
473 }
474 
475 static void vfio_disable_intx(VFIOPCIDevice *vdev)
476 {
477     int fd;
478 
479     timer_del(vdev->intx.mmap_timer);
480     vfio_disable_intx_kvm(vdev);
481     vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
482     vdev->intx.pending = false;
483     pci_irq_deassert(&vdev->pdev);
484     vfio_mmap_set_enabled(vdev, true);
485 
486     fd = event_notifier_get_fd(&vdev->intx.interrupt);
487     qemu_set_fd_handler(fd, NULL, NULL, vdev);
488     event_notifier_cleanup(&vdev->intx.interrupt);
489 
490     vdev->interrupt = VFIO_INT_NONE;
491 
492     trace_vfio_disable_intx(vdev->vbasedev.name);
493 }
494 
495 /*
496  * MSI/X
497  */
498 static void vfio_msi_interrupt(void *opaque)
499 {
500     VFIOMSIVector *vector = opaque;
501     VFIOPCIDevice *vdev = vector->vdev;
502     int nr = vector - vdev->msi_vectors;
503 
504     if (!event_notifier_test_and_clear(&vector->interrupt)) {
505         return;
506     }
507 
508 #ifdef DEBUG_VFIO
509     MSIMessage msg;
510 
511     if (vdev->interrupt == VFIO_INT_MSIX) {
512         msg = msix_get_message(&vdev->pdev, nr);
513     } else if (vdev->interrupt == VFIO_INT_MSI) {
514         msg = msi_get_message(&vdev->pdev, nr);
515     } else {
516         abort();
517     }
518 
519     trace_vfio_msi_interrupt(vdev->vbasedev.name, nr, msg.address, msg.data);
520 #endif
521 
522     if (vdev->interrupt == VFIO_INT_MSIX) {
523         msix_notify(&vdev->pdev, nr);
524     } else if (vdev->interrupt == VFIO_INT_MSI) {
525         msi_notify(&vdev->pdev, nr);
526     } else {
527         error_report("vfio: MSI interrupt receieved, but not enabled?");
528     }
529 }
530 
531 static int vfio_enable_vectors(VFIOPCIDevice *vdev, bool msix)
532 {
533     struct vfio_irq_set *irq_set;
534     int ret = 0, i, argsz;
535     int32_t *fds;
536 
537     argsz = sizeof(*irq_set) + (vdev->nr_vectors * sizeof(*fds));
538 
539     irq_set = g_malloc0(argsz);
540     irq_set->argsz = argsz;
541     irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
542     irq_set->index = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX;
543     irq_set->start = 0;
544     irq_set->count = vdev->nr_vectors;
545     fds = (int32_t *)&irq_set->data;
546 
547     for (i = 0; i < vdev->nr_vectors; i++) {
548         int fd = -1;
549 
550         /*
551          * MSI vs MSI-X - The guest has direct access to MSI mask and pending
552          * bits, therefore we always use the KVM signaling path when setup.
553          * MSI-X mask and pending bits are emulated, so we want to use the
554          * KVM signaling path only when configured and unmasked.
555          */
556         if (vdev->msi_vectors[i].use) {
557             if (vdev->msi_vectors[i].virq < 0 ||
558                 (msix && msix_is_masked(&vdev->pdev, i))) {
559                 fd = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt);
560             } else {
561                 fd = event_notifier_get_fd(&vdev->msi_vectors[i].kvm_interrupt);
562             }
563         }
564 
565         fds[i] = fd;
566     }
567 
568     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
569 
570     g_free(irq_set);
571 
572     return ret;
573 }
574 
575 static void vfio_add_kvm_msi_virq(VFIOMSIVector *vector, MSIMessage *msg,
576                                   bool msix)
577 {
578     int virq;
579 
580     if ((msix && !VFIO_ALLOW_KVM_MSIX) ||
581         (!msix && !VFIO_ALLOW_KVM_MSI) || !msg) {
582         return;
583     }
584 
585     if (event_notifier_init(&vector->kvm_interrupt, 0)) {
586         return;
587     }
588 
589     virq = kvm_irqchip_add_msi_route(kvm_state, *msg);
590     if (virq < 0) {
591         event_notifier_cleanup(&vector->kvm_interrupt);
592         return;
593     }
594 
595     if (kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->kvm_interrupt,
596                                        NULL, virq) < 0) {
597         kvm_irqchip_release_virq(kvm_state, virq);
598         event_notifier_cleanup(&vector->kvm_interrupt);
599         return;
600     }
601 
602     vector->virq = virq;
603 }
604 
605 static void vfio_remove_kvm_msi_virq(VFIOMSIVector *vector)
606 {
607     kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->kvm_interrupt,
608                                       vector->virq);
609     kvm_irqchip_release_virq(kvm_state, vector->virq);
610     vector->virq = -1;
611     event_notifier_cleanup(&vector->kvm_interrupt);
612 }
613 
614 static void vfio_update_kvm_msi_virq(VFIOMSIVector *vector, MSIMessage msg)
615 {
616     kvm_irqchip_update_msi_route(kvm_state, vector->virq, msg);
617 }
618 
619 static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr,
620                                    MSIMessage *msg, IOHandler *handler)
621 {
622     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
623     VFIOMSIVector *vector;
624     int ret;
625 
626     trace_vfio_msix_vector_do_use(vdev->vbasedev.name, nr);
627 
628     vector = &vdev->msi_vectors[nr];
629 
630     if (!vector->use) {
631         vector->vdev = vdev;
632         vector->virq = -1;
633         if (event_notifier_init(&vector->interrupt, 0)) {
634             error_report("vfio: Error: event_notifier_init failed");
635         }
636         vector->use = true;
637         msix_vector_use(pdev, nr);
638     }
639 
640     qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
641                         handler, NULL, vector);
642 
643     /*
644      * Attempt to enable route through KVM irqchip,
645      * default to userspace handling if unavailable.
646      */
647     if (vector->virq >= 0) {
648         if (!msg) {
649             vfio_remove_kvm_msi_virq(vector);
650         } else {
651             vfio_update_kvm_msi_virq(vector, *msg);
652         }
653     } else {
654         vfio_add_kvm_msi_virq(vector, msg, true);
655     }
656 
657     /*
658      * We don't want to have the host allocate all possible MSI vectors
659      * for a device if they're not in use, so we shutdown and incrementally
660      * increase them as needed.
661      */
662     if (vdev->nr_vectors < nr + 1) {
663         vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
664         vdev->nr_vectors = nr + 1;
665         ret = vfio_enable_vectors(vdev, true);
666         if (ret) {
667             error_report("vfio: failed to enable vectors, %d", ret);
668         }
669     } else {
670         int argsz;
671         struct vfio_irq_set *irq_set;
672         int32_t *pfd;
673 
674         argsz = sizeof(*irq_set) + sizeof(*pfd);
675 
676         irq_set = g_malloc0(argsz);
677         irq_set->argsz = argsz;
678         irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
679                          VFIO_IRQ_SET_ACTION_TRIGGER;
680         irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
681         irq_set->start = nr;
682         irq_set->count = 1;
683         pfd = (int32_t *)&irq_set->data;
684 
685         if (vector->virq >= 0) {
686             *pfd = event_notifier_get_fd(&vector->kvm_interrupt);
687         } else {
688             *pfd = event_notifier_get_fd(&vector->interrupt);
689         }
690 
691         ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
692         g_free(irq_set);
693         if (ret) {
694             error_report("vfio: failed to modify vector, %d", ret);
695         }
696     }
697 
698     return 0;
699 }
700 
701 static int vfio_msix_vector_use(PCIDevice *pdev,
702                                 unsigned int nr, MSIMessage msg)
703 {
704     return vfio_msix_vector_do_use(pdev, nr, &msg, vfio_msi_interrupt);
705 }
706 
707 static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr)
708 {
709     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
710     VFIOMSIVector *vector = &vdev->msi_vectors[nr];
711 
712     trace_vfio_msix_vector_release(vdev->vbasedev.name, nr);
713 
714     /*
715      * There are still old guests that mask and unmask vectors on every
716      * interrupt.  If we're using QEMU bypass with a KVM irqfd, leave all of
717      * the KVM setup in place, simply switch VFIO to use the non-bypass
718      * eventfd.  We'll then fire the interrupt through QEMU and the MSI-X
719      * core will mask the interrupt and set pending bits, allowing it to
720      * be re-asserted on unmask.  Nothing to do if already using QEMU mode.
721      */
722     if (vector->virq >= 0) {
723         int argsz;
724         struct vfio_irq_set *irq_set;
725         int32_t *pfd;
726 
727         argsz = sizeof(*irq_set) + sizeof(*pfd);
728 
729         irq_set = g_malloc0(argsz);
730         irq_set->argsz = argsz;
731         irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
732                          VFIO_IRQ_SET_ACTION_TRIGGER;
733         irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
734         irq_set->start = nr;
735         irq_set->count = 1;
736         pfd = (int32_t *)&irq_set->data;
737 
738         *pfd = event_notifier_get_fd(&vector->interrupt);
739 
740         ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
741 
742         g_free(irq_set);
743     }
744 }
745 
746 static void vfio_enable_msix(VFIOPCIDevice *vdev)
747 {
748     vfio_disable_interrupts(vdev);
749 
750     vdev->msi_vectors = g_malloc0(vdev->msix->entries * sizeof(VFIOMSIVector));
751 
752     vdev->interrupt = VFIO_INT_MSIX;
753 
754     /*
755      * Some communication channels between VF & PF or PF & fw rely on the
756      * physical state of the device and expect that enabling MSI-X from the
757      * guest enables the same on the host.  When our guest is Linux, the
758      * guest driver call to pci_enable_msix() sets the enabling bit in the
759      * MSI-X capability, but leaves the vector table masked.  We therefore
760      * can't rely on a vector_use callback (from request_irq() in the guest)
761      * to switch the physical device into MSI-X mode because that may come a
762      * long time after pci_enable_msix().  This code enables vector 0 with
763      * triggering to userspace, then immediately release the vector, leaving
764      * the physical device with no vectors enabled, but MSI-X enabled, just
765      * like the guest view.
766      */
767     vfio_msix_vector_do_use(&vdev->pdev, 0, NULL, NULL);
768     vfio_msix_vector_release(&vdev->pdev, 0);
769 
770     if (msix_set_vector_notifiers(&vdev->pdev, vfio_msix_vector_use,
771                                   vfio_msix_vector_release, NULL)) {
772         error_report("vfio: msix_set_vector_notifiers failed");
773     }
774 
775     trace_vfio_enable_msix(vdev->vbasedev.name);
776 }
777 
778 static void vfio_enable_msi(VFIOPCIDevice *vdev)
779 {
780     int ret, i;
781 
782     vfio_disable_interrupts(vdev);
783 
784     vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev);
785 retry:
786     vdev->msi_vectors = g_malloc0(vdev->nr_vectors * sizeof(VFIOMSIVector));
787 
788     for (i = 0; i < vdev->nr_vectors; i++) {
789         VFIOMSIVector *vector = &vdev->msi_vectors[i];
790         MSIMessage msg = msi_get_message(&vdev->pdev, i);
791 
792         vector->vdev = vdev;
793         vector->virq = -1;
794         vector->use = true;
795 
796         if (event_notifier_init(&vector->interrupt, 0)) {
797             error_report("vfio: Error: event_notifier_init failed");
798         }
799 
800         qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
801                             vfio_msi_interrupt, NULL, vector);
802 
803         /*
804          * Attempt to enable route through KVM irqchip,
805          * default to userspace handling if unavailable.
806          */
807         vfio_add_kvm_msi_virq(vector, &msg, false);
808     }
809 
810     /* Set interrupt type prior to possible interrupts */
811     vdev->interrupt = VFIO_INT_MSI;
812 
813     ret = vfio_enable_vectors(vdev, false);
814     if (ret) {
815         if (ret < 0) {
816             error_report("vfio: Error: Failed to setup MSI fds: %m");
817         } else if (ret != vdev->nr_vectors) {
818             error_report("vfio: Error: Failed to enable %d "
819                          "MSI vectors, retry with %d", vdev->nr_vectors, ret);
820         }
821 
822         for (i = 0; i < vdev->nr_vectors; i++) {
823             VFIOMSIVector *vector = &vdev->msi_vectors[i];
824             if (vector->virq >= 0) {
825                 vfio_remove_kvm_msi_virq(vector);
826             }
827             qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
828                                 NULL, NULL, NULL);
829             event_notifier_cleanup(&vector->interrupt);
830         }
831 
832         g_free(vdev->msi_vectors);
833 
834         if (ret > 0 && ret != vdev->nr_vectors) {
835             vdev->nr_vectors = ret;
836             goto retry;
837         }
838         vdev->nr_vectors = 0;
839 
840         /*
841          * Failing to setup MSI doesn't really fall within any specification.
842          * Let's try leaving interrupts disabled and hope the guest figures
843          * out to fall back to INTx for this device.
844          */
845         error_report("vfio: Error: Failed to enable MSI");
846         vdev->interrupt = VFIO_INT_NONE;
847 
848         return;
849     }
850 
851     trace_vfio_enable_msi(vdev->vbasedev.name, vdev->nr_vectors);
852 }
853 
854 static void vfio_disable_msi_common(VFIOPCIDevice *vdev)
855 {
856     int i;
857 
858     for (i = 0; i < vdev->nr_vectors; i++) {
859         VFIOMSIVector *vector = &vdev->msi_vectors[i];
860         if (vdev->msi_vectors[i].use) {
861             if (vector->virq >= 0) {
862                 vfio_remove_kvm_msi_virq(vector);
863             }
864             qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
865                                 NULL, NULL, NULL);
866             event_notifier_cleanup(&vector->interrupt);
867         }
868     }
869 
870     g_free(vdev->msi_vectors);
871     vdev->msi_vectors = NULL;
872     vdev->nr_vectors = 0;
873     vdev->interrupt = VFIO_INT_NONE;
874 
875     vfio_enable_intx(vdev);
876 }
877 
878 static void vfio_disable_msix(VFIOPCIDevice *vdev)
879 {
880     int i;
881 
882     msix_unset_vector_notifiers(&vdev->pdev);
883 
884     /*
885      * MSI-X will only release vectors if MSI-X is still enabled on the
886      * device, check through the rest and release it ourselves if necessary.
887      */
888     for (i = 0; i < vdev->nr_vectors; i++) {
889         if (vdev->msi_vectors[i].use) {
890             vfio_msix_vector_release(&vdev->pdev, i);
891             msix_vector_unuse(&vdev->pdev, i);
892         }
893     }
894 
895     if (vdev->nr_vectors) {
896         vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
897     }
898 
899     vfio_disable_msi_common(vdev);
900 
901     trace_vfio_disable_msix(vdev->vbasedev.name);
902 }
903 
904 static void vfio_disable_msi(VFIOPCIDevice *vdev)
905 {
906     vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSI_IRQ_INDEX);
907     vfio_disable_msi_common(vdev);
908 
909     trace_vfio_disable_msi(vdev->vbasedev.name);
910 }
911 
912 static void vfio_update_msi(VFIOPCIDevice *vdev)
913 {
914     int i;
915 
916     for (i = 0; i < vdev->nr_vectors; i++) {
917         VFIOMSIVector *vector = &vdev->msi_vectors[i];
918         MSIMessage msg;
919 
920         if (!vector->use || vector->virq < 0) {
921             continue;
922         }
923 
924         msg = msi_get_message(&vdev->pdev, i);
925         vfio_update_kvm_msi_virq(vector, msg);
926     }
927 }
928 
929 static void vfio_pci_load_rom(VFIOPCIDevice *vdev)
930 {
931     struct vfio_region_info reg_info = {
932         .argsz = sizeof(reg_info),
933         .index = VFIO_PCI_ROM_REGION_INDEX
934     };
935     uint64_t size;
936     off_t off = 0;
937     size_t bytes;
938 
939     if (ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info)) {
940         error_report("vfio: Error getting ROM info: %m");
941         return;
942     }
943 
944     trace_vfio_pci_load_rom(vdev->vbasedev.name, (unsigned long)reg_info.size,
945                             (unsigned long)reg_info.offset,
946                             (unsigned long)reg_info.flags);
947 
948     vdev->rom_size = size = reg_info.size;
949     vdev->rom_offset = reg_info.offset;
950 
951     if (!vdev->rom_size) {
952         vdev->rom_read_failed = true;
953         error_report("vfio-pci: Cannot read device rom at "
954                     "%s", vdev->vbasedev.name);
955         error_printf("Device option ROM contents are probably invalid "
956                     "(check dmesg).\nSkip option ROM probe with rombar=0, "
957                     "or load from file with romfile=\n");
958         return;
959     }
960 
961     vdev->rom = g_malloc(size);
962     memset(vdev->rom, 0xff, size);
963 
964     while (size) {
965         bytes = pread(vdev->vbasedev.fd, vdev->rom + off,
966                       size, vdev->rom_offset + off);
967         if (bytes == 0) {
968             break;
969         } else if (bytes > 0) {
970             off += bytes;
971             size -= bytes;
972         } else {
973             if (errno == EINTR || errno == EAGAIN) {
974                 continue;
975             }
976             error_report("vfio: Error reading device ROM: %m");
977             break;
978         }
979     }
980 }
981 
982 static uint64_t vfio_rom_read(void *opaque, hwaddr addr, unsigned size)
983 {
984     VFIOPCIDevice *vdev = opaque;
985     union {
986         uint8_t byte;
987         uint16_t word;
988         uint32_t dword;
989         uint64_t qword;
990     } val;
991     uint64_t data = 0;
992 
993     /* Load the ROM lazily when the guest tries to read it */
994     if (unlikely(!vdev->rom && !vdev->rom_read_failed)) {
995         vfio_pci_load_rom(vdev);
996     }
997 
998     memcpy(&val, vdev->rom + addr,
999            (addr < vdev->rom_size) ? MIN(size, vdev->rom_size - addr) : 0);
1000 
1001     switch (size) {
1002     case 1:
1003         data = val.byte;
1004         break;
1005     case 2:
1006         data = le16_to_cpu(val.word);
1007         break;
1008     case 4:
1009         data = le32_to_cpu(val.dword);
1010         break;
1011     default:
1012         hw_error("vfio: unsupported read size, %d bytes\n", size);
1013         break;
1014     }
1015 
1016     trace_vfio_rom_read(vdev->vbasedev.name, addr, size, data);
1017 
1018     return data;
1019 }
1020 
1021 static void vfio_rom_write(void *opaque, hwaddr addr,
1022                            uint64_t data, unsigned size)
1023 {
1024 }
1025 
1026 static const MemoryRegionOps vfio_rom_ops = {
1027     .read = vfio_rom_read,
1028     .write = vfio_rom_write,
1029     .endianness = DEVICE_LITTLE_ENDIAN,
1030 };
1031 
1032 static bool vfio_blacklist_opt_rom(VFIOPCIDevice *vdev)
1033 {
1034     PCIDevice *pdev = &vdev->pdev;
1035     uint16_t vendor_id, device_id;
1036     int count = 0;
1037 
1038     vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
1039     device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
1040 
1041     while (count < ARRAY_SIZE(romblacklist)) {
1042         if (romblacklist[count].vendor_id == vendor_id &&
1043             romblacklist[count].device_id == device_id) {
1044                 return true;
1045         }
1046         count++;
1047     }
1048 
1049     return false;
1050 }
1051 
1052 static void vfio_pci_size_rom(VFIOPCIDevice *vdev)
1053 {
1054     uint32_t orig, size = cpu_to_le32((uint32_t)PCI_ROM_ADDRESS_MASK);
1055     off_t offset = vdev->config_offset + PCI_ROM_ADDRESS;
1056     DeviceState *dev = DEVICE(vdev);
1057     char name[32];
1058     int fd = vdev->vbasedev.fd;
1059 
1060     if (vdev->pdev.romfile || !vdev->pdev.rom_bar) {
1061         /* Since pci handles romfile, just print a message and return */
1062         if (vfio_blacklist_opt_rom(vdev) && vdev->pdev.romfile) {
1063             error_printf("Warning : Device at %04x:%02x:%02x.%x "
1064                          "is known to cause system instability issues during "
1065                          "option rom execution. "
1066                          "Proceeding anyway since user specified romfile\n",
1067                          vdev->host.domain, vdev->host.bus, vdev->host.slot,
1068                          vdev->host.function);
1069         }
1070         return;
1071     }
1072 
1073     /*
1074      * Use the same size ROM BAR as the physical device.  The contents
1075      * will get filled in later when the guest tries to read it.
1076      */
1077     if (pread(fd, &orig, 4, offset) != 4 ||
1078         pwrite(fd, &size, 4, offset) != 4 ||
1079         pread(fd, &size, 4, offset) != 4 ||
1080         pwrite(fd, &orig, 4, offset) != 4) {
1081         error_report("%s(%04x:%02x:%02x.%x) failed: %m",
1082                      __func__, vdev->host.domain, vdev->host.bus,
1083                      vdev->host.slot, vdev->host.function);
1084         return;
1085     }
1086 
1087     size = ~(le32_to_cpu(size) & PCI_ROM_ADDRESS_MASK) + 1;
1088 
1089     if (!size) {
1090         return;
1091     }
1092 
1093     if (vfio_blacklist_opt_rom(vdev)) {
1094         if (dev->opts && qemu_opt_get(dev->opts, "rombar")) {
1095             error_printf("Warning : Device at %04x:%02x:%02x.%x "
1096                          "is known to cause system instability issues during "
1097                          "option rom execution. "
1098                          "Proceeding anyway since user specified non zero value for "
1099                          "rombar\n",
1100                          vdev->host.domain, vdev->host.bus, vdev->host.slot,
1101                          vdev->host.function);
1102         } else {
1103             error_printf("Warning : Rom loading for device at "
1104                          "%04x:%02x:%02x.%x has been disabled due to "
1105                          "system instability issues. "
1106                          "Specify rombar=1 or romfile to force\n",
1107                          vdev->host.domain, vdev->host.bus, vdev->host.slot,
1108                          vdev->host.function);
1109             return;
1110         }
1111     }
1112 
1113     trace_vfio_pci_size_rom(vdev->vbasedev.name, size);
1114 
1115     snprintf(name, sizeof(name), "vfio[%04x:%02x:%02x.%x].rom",
1116              vdev->host.domain, vdev->host.bus, vdev->host.slot,
1117              vdev->host.function);
1118 
1119     memory_region_init_io(&vdev->pdev.rom, OBJECT(vdev),
1120                           &vfio_rom_ops, vdev, name, size);
1121 
1122     pci_register_bar(&vdev->pdev, PCI_ROM_SLOT,
1123                      PCI_BASE_ADDRESS_SPACE_MEMORY, &vdev->pdev.rom);
1124 
1125     vdev->pdev.has_rom = true;
1126     vdev->rom_read_failed = false;
1127 }
1128 
1129 static void vfio_vga_write(void *opaque, hwaddr addr,
1130                            uint64_t data, unsigned size)
1131 {
1132     VFIOVGARegion *region = opaque;
1133     VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
1134     union {
1135         uint8_t byte;
1136         uint16_t word;
1137         uint32_t dword;
1138         uint64_t qword;
1139     } buf;
1140     off_t offset = vga->fd_offset + region->offset + addr;
1141 
1142     switch (size) {
1143     case 1:
1144         buf.byte = data;
1145         break;
1146     case 2:
1147         buf.word = cpu_to_le16(data);
1148         break;
1149     case 4:
1150         buf.dword = cpu_to_le32(data);
1151         break;
1152     default:
1153         hw_error("vfio: unsupported write size, %d bytes", size);
1154         break;
1155     }
1156 
1157     if (pwrite(vga->fd, &buf, size, offset) != size) {
1158         error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m",
1159                      __func__, region->offset + addr, data, size);
1160     }
1161 
1162     trace_vfio_vga_write(region->offset + addr, data, size);
1163 }
1164 
1165 static uint64_t vfio_vga_read(void *opaque, hwaddr addr, unsigned size)
1166 {
1167     VFIOVGARegion *region = opaque;
1168     VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
1169     union {
1170         uint8_t byte;
1171         uint16_t word;
1172         uint32_t dword;
1173         uint64_t qword;
1174     } buf;
1175     uint64_t data = 0;
1176     off_t offset = vga->fd_offset + region->offset + addr;
1177 
1178     if (pread(vga->fd, &buf, size, offset) != size) {
1179         error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m",
1180                      __func__, region->offset + addr, size);
1181         return (uint64_t)-1;
1182     }
1183 
1184     switch (size) {
1185     case 1:
1186         data = buf.byte;
1187         break;
1188     case 2:
1189         data = le16_to_cpu(buf.word);
1190         break;
1191     case 4:
1192         data = le32_to_cpu(buf.dword);
1193         break;
1194     default:
1195         hw_error("vfio: unsupported read size, %d bytes", size);
1196         break;
1197     }
1198 
1199     trace_vfio_vga_read(region->offset + addr, size, data);
1200 
1201     return data;
1202 }
1203 
1204 static const MemoryRegionOps vfio_vga_ops = {
1205     .read = vfio_vga_read,
1206     .write = vfio_vga_write,
1207     .endianness = DEVICE_LITTLE_ENDIAN,
1208 };
1209 
1210 /*
1211  * Device specific quirks
1212  */
1213 
1214 /* Is range1 fully contained within range2?  */
1215 static bool vfio_range_contained(uint64_t first1, uint64_t len1,
1216                                  uint64_t first2, uint64_t len2) {
1217     return (first1 >= first2 && first1 + len1 <= first2 + len2);
1218 }
1219 
1220 static bool vfio_flags_enabled(uint8_t flags, uint8_t mask)
1221 {
1222     return (mask && (flags & mask) == mask);
1223 }
1224 
1225 static uint64_t vfio_generic_window_quirk_read(void *opaque,
1226                                                hwaddr addr, unsigned size)
1227 {
1228     VFIOQuirk *quirk = opaque;
1229     VFIOPCIDevice *vdev = quirk->vdev;
1230     uint64_t data;
1231 
1232     if (vfio_flags_enabled(quirk->data.flags, quirk->data.read_flags) &&
1233         ranges_overlap(addr, size,
1234                        quirk->data.data_offset, quirk->data.data_size)) {
1235         hwaddr offset = addr - quirk->data.data_offset;
1236 
1237         if (!vfio_range_contained(addr, size, quirk->data.data_offset,
1238                                   quirk->data.data_size)) {
1239             hw_error("%s: window data read not fully contained: %s",
1240                      __func__, memory_region_name(&quirk->mem));
1241         }
1242 
1243         data = vfio_pci_read_config(&vdev->pdev,
1244                                     quirk->data.address_val + offset, size);
1245 
1246         trace_vfio_generic_window_quirk_read(memory_region_name(&quirk->mem),
1247                                              vdev->vbasedev.name,
1248                                              quirk->data.bar,
1249                                              addr, size, data);
1250     } else {
1251         data = vfio_region_read(&vdev->bars[quirk->data.bar].region,
1252                                 addr + quirk->data.base_offset, size);
1253     }
1254 
1255     return data;
1256 }
1257 
1258 static void vfio_generic_window_quirk_write(void *opaque, hwaddr addr,
1259                                             uint64_t data, unsigned size)
1260 {
1261     VFIOQuirk *quirk = opaque;
1262     VFIOPCIDevice *vdev = quirk->vdev;
1263 
1264     if (ranges_overlap(addr, size,
1265                        quirk->data.address_offset, quirk->data.address_size)) {
1266 
1267         if (addr != quirk->data.address_offset) {
1268             hw_error("%s: offset write into address window: %s",
1269                      __func__, memory_region_name(&quirk->mem));
1270         }
1271 
1272         if ((data & ~quirk->data.address_mask) == quirk->data.address_match) {
1273             quirk->data.flags |= quirk->data.write_flags |
1274                                  quirk->data.read_flags;
1275             quirk->data.address_val = data & quirk->data.address_mask;
1276         } else {
1277             quirk->data.flags &= ~(quirk->data.write_flags |
1278                                    quirk->data.read_flags);
1279         }
1280     }
1281 
1282     if (vfio_flags_enabled(quirk->data.flags, quirk->data.write_flags) &&
1283         ranges_overlap(addr, size,
1284                        quirk->data.data_offset, quirk->data.data_size)) {
1285         hwaddr offset = addr - quirk->data.data_offset;
1286 
1287         if (!vfio_range_contained(addr, size, quirk->data.data_offset,
1288                                   quirk->data.data_size)) {
1289             hw_error("%s: window data write not fully contained: %s",
1290                      __func__, memory_region_name(&quirk->mem));
1291         }
1292 
1293         vfio_pci_write_config(&vdev->pdev,
1294                               quirk->data.address_val + offset, data, size);
1295         trace_vfio_generic_window_quirk_write(memory_region_name(&quirk->mem),
1296                                               vdev->vbasedev.name,
1297                                               quirk->data.bar,
1298                                               addr, data, size);
1299         return;
1300     }
1301 
1302     vfio_region_write(&vdev->bars[quirk->data.bar].region,
1303                    addr + quirk->data.base_offset, data, size);
1304 }
1305 
1306 static const MemoryRegionOps vfio_generic_window_quirk = {
1307     .read = vfio_generic_window_quirk_read,
1308     .write = vfio_generic_window_quirk_write,
1309     .endianness = DEVICE_LITTLE_ENDIAN,
1310 };
1311 
1312 static uint64_t vfio_generic_quirk_read(void *opaque,
1313                                         hwaddr addr, unsigned size)
1314 {
1315     VFIOQuirk *quirk = opaque;
1316     VFIOPCIDevice *vdev = quirk->vdev;
1317     hwaddr base = quirk->data.address_match & TARGET_PAGE_MASK;
1318     hwaddr offset = quirk->data.address_match & ~TARGET_PAGE_MASK;
1319     uint64_t data;
1320 
1321     if (vfio_flags_enabled(quirk->data.flags, quirk->data.read_flags) &&
1322         ranges_overlap(addr, size, offset, quirk->data.address_mask + 1)) {
1323         if (!vfio_range_contained(addr, size, offset,
1324                                   quirk->data.address_mask + 1)) {
1325             hw_error("%s: read not fully contained: %s",
1326                      __func__, memory_region_name(&quirk->mem));
1327         }
1328 
1329         data = vfio_pci_read_config(&vdev->pdev, addr - offset, size);
1330 
1331         trace_vfio_generic_quirk_read(memory_region_name(&quirk->mem),
1332                                       vdev->vbasedev.name, quirk->data.bar,
1333                                       addr + base, size, data);
1334     } else {
1335         data = vfio_region_read(&vdev->bars[quirk->data.bar].region,
1336                                 addr + base, size);
1337     }
1338 
1339     return data;
1340 }
1341 
1342 static void vfio_generic_quirk_write(void *opaque, hwaddr addr,
1343                                      uint64_t data, unsigned size)
1344 {
1345     VFIOQuirk *quirk = opaque;
1346     VFIOPCIDevice *vdev = quirk->vdev;
1347     hwaddr base = quirk->data.address_match & TARGET_PAGE_MASK;
1348     hwaddr offset = quirk->data.address_match & ~TARGET_PAGE_MASK;
1349 
1350     if (vfio_flags_enabled(quirk->data.flags, quirk->data.write_flags) &&
1351         ranges_overlap(addr, size, offset, quirk->data.address_mask + 1)) {
1352         if (!vfio_range_contained(addr, size, offset,
1353                                   quirk->data.address_mask + 1)) {
1354             hw_error("%s: write not fully contained: %s",
1355                      __func__, memory_region_name(&quirk->mem));
1356         }
1357 
1358         vfio_pci_write_config(&vdev->pdev, addr - offset, data, size);
1359 
1360         trace_vfio_generic_quirk_write(memory_region_name(&quirk->mem),
1361                                        vdev->vbasedev.name, quirk->data.bar,
1362                                        addr + base, data, size);
1363     } else {
1364         vfio_region_write(&vdev->bars[quirk->data.bar].region,
1365                           addr + base, data, size);
1366     }
1367 }
1368 
1369 static const MemoryRegionOps vfio_generic_quirk = {
1370     .read = vfio_generic_quirk_read,
1371     .write = vfio_generic_quirk_write,
1372     .endianness = DEVICE_LITTLE_ENDIAN,
1373 };
1374 
1375 #define PCI_VENDOR_ID_ATI               0x1002
1376 
1377 /*
1378  * Radeon HD cards (HD5450 & HD7850) report the upper byte of the I/O port BAR
1379  * through VGA register 0x3c3.  On newer cards, the I/O port BAR is always
1380  * BAR4 (older cards like the X550 used BAR1, but we don't care to support
1381  * those).  Note that on bare metal, a read of 0x3c3 doesn't always return the
1382  * I/O port BAR address.  Originally this was coded to return the virtual BAR
1383  * address only if the physical register read returns the actual BAR address,
1384  * but users have reported greater success if we return the virtual address
1385  * unconditionally.
1386  */
1387 static uint64_t vfio_ati_3c3_quirk_read(void *opaque,
1388                                         hwaddr addr, unsigned size)
1389 {
1390     VFIOQuirk *quirk = opaque;
1391     VFIOPCIDevice *vdev = quirk->vdev;
1392     uint64_t data = vfio_pci_read_config(&vdev->pdev,
1393                                          PCI_BASE_ADDRESS_0 + (4 * 4) + 1,
1394                                          size);
1395     trace_vfio_ati_3c3_quirk_read(data);
1396 
1397     return data;
1398 }
1399 
1400 static const MemoryRegionOps vfio_ati_3c3_quirk = {
1401     .read = vfio_ati_3c3_quirk_read,
1402     .endianness = DEVICE_LITTLE_ENDIAN,
1403 };
1404 
1405 static void vfio_vga_probe_ati_3c3_quirk(VFIOPCIDevice *vdev)
1406 {
1407     PCIDevice *pdev = &vdev->pdev;
1408     VFIOQuirk *quirk;
1409 
1410     if (pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_ATI) {
1411         return;
1412     }
1413 
1414     /*
1415      * As long as the BAR is >= 256 bytes it will be aligned such that the
1416      * lower byte is always zero.  Filter out anything else, if it exists.
1417      */
1418     if (!vdev->bars[4].ioport || vdev->bars[4].region.size < 256) {
1419         return;
1420     }
1421 
1422     quirk = g_malloc0(sizeof(*quirk));
1423     quirk->vdev = vdev;
1424 
1425     memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_ati_3c3_quirk, quirk,
1426                           "vfio-ati-3c3-quirk", 1);
1427     memory_region_add_subregion(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem,
1428                                 3 /* offset 3 bytes from 0x3c0 */, &quirk->mem);
1429 
1430     QLIST_INSERT_HEAD(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].quirks,
1431                       quirk, next);
1432 
1433     trace_vfio_vga_probe_ati_3c3_quirk(vdev->vbasedev.name);
1434 }
1435 
1436 /*
1437  * Newer ATI/AMD devices, including HD5450 and HD7850, have a window to PCI
1438  * config space through MMIO BAR2 at offset 0x4000.  Nothing seems to access
1439  * the MMIO space directly, but a window to this space is provided through
1440  * I/O port BAR4.  Offset 0x0 is the address register and offset 0x4 is the
1441  * data register.  When the address is programmed to a range of 0x4000-0x4fff
1442  * PCI configuration space is available.  Experimentation seems to indicate
1443  * that only read-only access is provided, but we drop writes when the window
1444  * is enabled to config space nonetheless.
1445  */
1446 static void vfio_probe_ati_bar4_window_quirk(VFIOPCIDevice *vdev, int nr)
1447 {
1448     PCIDevice *pdev = &vdev->pdev;
1449     VFIOQuirk *quirk;
1450 
1451     if (!vdev->has_vga || nr != 4 ||
1452         pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_ATI) {
1453         return;
1454     }
1455 
1456     quirk = g_malloc0(sizeof(*quirk));
1457     quirk->vdev = vdev;
1458     quirk->data.address_size = 4;
1459     quirk->data.data_offset = 4;
1460     quirk->data.data_size = 4;
1461     quirk->data.address_match = 0x4000;
1462     quirk->data.address_mask = PCIE_CONFIG_SPACE_SIZE - 1;
1463     quirk->data.bar = nr;
1464     quirk->data.read_flags = quirk->data.write_flags = 1;
1465 
1466     memory_region_init_io(&quirk->mem, OBJECT(vdev),
1467                           &vfio_generic_window_quirk, quirk,
1468                           "vfio-ati-bar4-window-quirk", 8);
1469     memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
1470                           quirk->data.base_offset, &quirk->mem, 1);
1471 
1472     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1473 
1474     trace_vfio_probe_ati_bar4_window_quirk(vdev->vbasedev.name);
1475 }
1476 
1477 #define PCI_VENDOR_ID_REALTEK 0x10ec
1478 
1479 /*
1480  * RTL8168 devices have a backdoor that can access the MSI-X table.  At BAR2
1481  * offset 0x70 there is a dword data register, offset 0x74 is a dword address
1482  * register.  According to the Linux r8169 driver, the MSI-X table is addressed
1483  * when the "type" portion of the address register is set to 0x1.  This appears
1484  * to be bits 16:30.  Bit 31 is both a write indicator and some sort of
1485  * "address latched" indicator.  Bits 12:15 are a mask field, which we can
1486  * ignore because the MSI-X table should always be accessed as a dword (full
1487  * mask).  Bits 0:11 is offset within the type.
1488  *
1489  * Example trace:
1490  *
1491  * Read from MSI-X table offset 0
1492  * vfio: vfio_bar_write(0000:05:00.0:BAR2+0x74, 0x1f000, 4) // store read addr
1493  * vfio: vfio_bar_read(0000:05:00.0:BAR2+0x74, 4) = 0x8001f000 // latch
1494  * vfio: vfio_bar_read(0000:05:00.0:BAR2+0x70, 4) = 0xfee00398 // read data
1495  *
1496  * Write 0xfee00000 to MSI-X table offset 0
1497  * vfio: vfio_bar_write(0000:05:00.0:BAR2+0x70, 0xfee00000, 4) // write data
1498  * vfio: vfio_bar_write(0000:05:00.0:BAR2+0x74, 0x8001f000, 4) // do write
1499  * vfio: vfio_bar_read(0000:05:00.0:BAR2+0x74, 4) = 0x1f000 // complete
1500  */
1501 
1502 static uint64_t vfio_rtl8168_window_quirk_read(void *opaque,
1503                                                hwaddr addr, unsigned size)
1504 {
1505     VFIOQuirk *quirk = opaque;
1506     VFIOPCIDevice *vdev = quirk->vdev;
1507 
1508     switch (addr) {
1509     case 4: /* address */
1510         if (quirk->data.flags) {
1511             trace_vfio_rtl8168_window_quirk_read_fake(
1512                     memory_region_name(&quirk->mem),
1513                     vdev->vbasedev.name);
1514 
1515             return quirk->data.address_match ^ 0x10000000U;
1516         }
1517         break;
1518     case 0: /* data */
1519         if (quirk->data.flags) {
1520             uint64_t val;
1521 
1522             trace_vfio_rtl8168_window_quirk_read_table(
1523                     memory_region_name(&quirk->mem),
1524                     vdev->vbasedev.name);
1525 
1526             if (!(vdev->pdev.cap_present & QEMU_PCI_CAP_MSIX)) {
1527                 return 0;
1528             }
1529 
1530             io_mem_read(&vdev->pdev.msix_table_mmio,
1531                         (hwaddr)(quirk->data.address_match & 0xfff),
1532                         &val, size);
1533             return val;
1534         }
1535     }
1536 
1537     trace_vfio_rtl8168_window_quirk_read_direct(memory_region_name(&quirk->mem),
1538                                                 vdev->vbasedev.name);
1539 
1540     return vfio_region_read(&vdev->bars[quirk->data.bar].region,
1541                             addr + 0x70, size);
1542 }
1543 
1544 static void vfio_rtl8168_window_quirk_write(void *opaque, hwaddr addr,
1545                                             uint64_t data, unsigned size)
1546 {
1547     VFIOQuirk *quirk = opaque;
1548     VFIOPCIDevice *vdev = quirk->vdev;
1549 
1550     switch (addr) {
1551     case 4: /* address */
1552         if ((data & 0x7fff0000) == 0x10000) {
1553             if (data & 0x10000000U &&
1554                 vdev->pdev.cap_present & QEMU_PCI_CAP_MSIX) {
1555 
1556                 trace_vfio_rtl8168_window_quirk_write_table(
1557                         memory_region_name(&quirk->mem),
1558                         vdev->vbasedev.name);
1559 
1560                 io_mem_write(&vdev->pdev.msix_table_mmio,
1561                              (hwaddr)(quirk->data.address_match & 0xfff),
1562                              data, size);
1563             }
1564 
1565             quirk->data.flags = 1;
1566             quirk->data.address_match = data;
1567 
1568             return;
1569         }
1570         quirk->data.flags = 0;
1571         break;
1572     case 0: /* data */
1573         quirk->data.address_mask = data;
1574         break;
1575     }
1576 
1577     trace_vfio_rtl8168_window_quirk_write_direct(
1578             memory_region_name(&quirk->mem),
1579             vdev->vbasedev.name);
1580 
1581     vfio_region_write(&vdev->bars[quirk->data.bar].region,
1582                       addr + 0x70, data, size);
1583 }
1584 
1585 static const MemoryRegionOps vfio_rtl8168_window_quirk = {
1586     .read = vfio_rtl8168_window_quirk_read,
1587     .write = vfio_rtl8168_window_quirk_write,
1588     .valid = {
1589         .min_access_size = 4,
1590         .max_access_size = 4,
1591         .unaligned = false,
1592     },
1593     .endianness = DEVICE_LITTLE_ENDIAN,
1594 };
1595 
1596 static void vfio_probe_rtl8168_bar2_window_quirk(VFIOPCIDevice *vdev, int nr)
1597 {
1598     PCIDevice *pdev = &vdev->pdev;
1599     VFIOQuirk *quirk;
1600 
1601     if (pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_REALTEK ||
1602         pci_get_word(pdev->config + PCI_DEVICE_ID) != 0x8168 || nr != 2) {
1603         return;
1604     }
1605 
1606     quirk = g_malloc0(sizeof(*quirk));
1607     quirk->vdev = vdev;
1608     quirk->data.bar = nr;
1609 
1610     memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_rtl8168_window_quirk,
1611                           quirk, "vfio-rtl8168-window-quirk", 8);
1612     memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
1613                                         0x70, &quirk->mem, 1);
1614 
1615     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1616 
1617     trace_vfio_probe_rtl8168_bar2_window_quirk(vdev->vbasedev.name);
1618 }
1619 /*
1620  * Trap the BAR2 MMIO window to config space as well.
1621  */
1622 static void vfio_probe_ati_bar2_4000_quirk(VFIOPCIDevice *vdev, int nr)
1623 {
1624     PCIDevice *pdev = &vdev->pdev;
1625     VFIOQuirk *quirk;
1626 
1627     /* Only enable on newer devices where BAR2 is 64bit */
1628     if (!vdev->has_vga || nr != 2 || !vdev->bars[2].mem64 ||
1629         pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_ATI) {
1630         return;
1631     }
1632 
1633     quirk = g_malloc0(sizeof(*quirk));
1634     quirk->vdev = vdev;
1635     quirk->data.flags = quirk->data.read_flags = quirk->data.write_flags = 1;
1636     quirk->data.address_match = 0x4000;
1637     quirk->data.address_mask = PCIE_CONFIG_SPACE_SIZE - 1;
1638     quirk->data.bar = nr;
1639 
1640     memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_generic_quirk, quirk,
1641                           "vfio-ati-bar2-4000-quirk",
1642                           TARGET_PAGE_ALIGN(quirk->data.address_mask + 1));
1643     memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
1644                           quirk->data.address_match & TARGET_PAGE_MASK,
1645                           &quirk->mem, 1);
1646 
1647     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1648 
1649     trace_vfio_probe_ati_bar2_4000_quirk(vdev->vbasedev.name);
1650 }
1651 
1652 /*
1653  * Older ATI/AMD cards like the X550 have a similar window to that above.
1654  * I/O port BAR1 provides a window to a mirror of PCI config space located
1655  * in BAR2 at offset 0xf00.  We don't care to support such older cards, but
1656  * note it for future reference.
1657  */
1658 
1659 #define PCI_VENDOR_ID_NVIDIA                    0x10de
1660 
1661 /*
1662  * Nvidia has several different methods to get to config space, the
1663  * nouveu project has several of these documented here:
1664  * https://github.com/pathscale/envytools/tree/master/hwdocs
1665  *
1666  * The first quirk is actually not documented in envytools and is found
1667  * on 10de:01d1 (NVIDIA Corporation G72 [GeForce 7300 LE]).  This is an
1668  * NV46 chipset.  The backdoor uses the legacy VGA I/O ports to access
1669  * the mirror of PCI config space found at BAR0 offset 0x1800.  The access
1670  * sequence first writes 0x338 to I/O port 0x3d4.  The target offset is
1671  * then written to 0x3d0.  Finally 0x538 is written for a read and 0x738
1672  * is written for a write to 0x3d4.  The BAR0 offset is then accessible
1673  * through 0x3d0.  This quirk doesn't seem to be necessary on newer cards
1674  * that use the I/O port BAR5 window but it doesn't hurt to leave it.
1675  */
1676 enum {
1677     NV_3D0_NONE = 0,
1678     NV_3D0_SELECT,
1679     NV_3D0_WINDOW,
1680     NV_3D0_READ,
1681     NV_3D0_WRITE,
1682 };
1683 
1684 static uint64_t vfio_nvidia_3d0_quirk_read(void *opaque,
1685                                            hwaddr addr, unsigned size)
1686 {
1687     VFIOQuirk *quirk = opaque;
1688     VFIOPCIDevice *vdev = quirk->vdev;
1689     PCIDevice *pdev = &vdev->pdev;
1690     uint64_t data = vfio_vga_read(&vdev->vga.region[QEMU_PCI_VGA_IO_HI],
1691                                   addr + quirk->data.base_offset, size);
1692 
1693     if (quirk->data.flags == NV_3D0_READ && addr == quirk->data.data_offset) {
1694         data = vfio_pci_read_config(pdev, quirk->data.address_val, size);
1695         trace_vfio_nvidia_3d0_quirk_read(size, data);
1696     }
1697 
1698     quirk->data.flags = NV_3D0_NONE;
1699 
1700     return data;
1701 }
1702 
1703 static void vfio_nvidia_3d0_quirk_write(void *opaque, hwaddr addr,
1704                                         uint64_t data, unsigned size)
1705 {
1706     VFIOQuirk *quirk = opaque;
1707     VFIOPCIDevice *vdev = quirk->vdev;
1708     PCIDevice *pdev = &vdev->pdev;
1709 
1710     switch (quirk->data.flags) {
1711     case NV_3D0_NONE:
1712         if (addr == quirk->data.address_offset && data == 0x338) {
1713             quirk->data.flags = NV_3D0_SELECT;
1714         }
1715         break;
1716     case NV_3D0_SELECT:
1717         quirk->data.flags = NV_3D0_NONE;
1718         if (addr == quirk->data.data_offset &&
1719             (data & ~quirk->data.address_mask) == quirk->data.address_match) {
1720             quirk->data.flags = NV_3D0_WINDOW;
1721             quirk->data.address_val = data & quirk->data.address_mask;
1722         }
1723         break;
1724     case NV_3D0_WINDOW:
1725         quirk->data.flags = NV_3D0_NONE;
1726         if (addr == quirk->data.address_offset) {
1727             if (data == 0x538) {
1728                 quirk->data.flags = NV_3D0_READ;
1729             } else if (data == 0x738) {
1730                 quirk->data.flags = NV_3D0_WRITE;
1731             }
1732         }
1733         break;
1734     case NV_3D0_WRITE:
1735         quirk->data.flags = NV_3D0_NONE;
1736         if (addr == quirk->data.data_offset) {
1737             vfio_pci_write_config(pdev, quirk->data.address_val, data, size);
1738             trace_vfio_nvidia_3d0_quirk_write(data, size);
1739             return;
1740         }
1741         break;
1742     }
1743 
1744     vfio_vga_write(&vdev->vga.region[QEMU_PCI_VGA_IO_HI],
1745                    addr + quirk->data.base_offset, data, size);
1746 }
1747 
1748 static const MemoryRegionOps vfio_nvidia_3d0_quirk = {
1749     .read = vfio_nvidia_3d0_quirk_read,
1750     .write = vfio_nvidia_3d0_quirk_write,
1751     .endianness = DEVICE_LITTLE_ENDIAN,
1752 };
1753 
1754 static void vfio_vga_probe_nvidia_3d0_quirk(VFIOPCIDevice *vdev)
1755 {
1756     PCIDevice *pdev = &vdev->pdev;
1757     VFIOQuirk *quirk;
1758 
1759     if (pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_NVIDIA ||
1760         !vdev->bars[1].region.size) {
1761         return;
1762     }
1763 
1764     quirk = g_malloc0(sizeof(*quirk));
1765     quirk->vdev = vdev;
1766     quirk->data.base_offset = 0x10;
1767     quirk->data.address_offset = 4;
1768     quirk->data.address_size = 2;
1769     quirk->data.address_match = 0x1800;
1770     quirk->data.address_mask = PCI_CONFIG_SPACE_SIZE - 1;
1771     quirk->data.data_offset = 0;
1772     quirk->data.data_size = 4;
1773 
1774     memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_nvidia_3d0_quirk,
1775                           quirk, "vfio-nvidia-3d0-quirk", 6);
1776     memory_region_add_subregion(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem,
1777                                 quirk->data.base_offset, &quirk->mem);
1778 
1779     QLIST_INSERT_HEAD(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].quirks,
1780                       quirk, next);
1781 
1782     trace_vfio_vga_probe_nvidia_3d0_quirk(vdev->vbasedev.name);
1783 }
1784 
1785 /*
1786  * The second quirk is documented in envytools.  The I/O port BAR5 is just
1787  * a set of address/data ports to the MMIO BARs.  The BAR we care about is
1788  * again BAR0.  This backdoor is apparently a bit newer than the one above
1789  * so we need to not only trap 256 bytes @0x1800, but all of PCI config
1790  * space, including extended space is available at the 4k @0x88000.
1791  */
1792 enum {
1793     NV_BAR5_ADDRESS = 0x1,
1794     NV_BAR5_ENABLE = 0x2,
1795     NV_BAR5_MASTER = 0x4,
1796     NV_BAR5_VALID = 0x7,
1797 };
1798 
1799 static void vfio_nvidia_bar5_window_quirk_write(void *opaque, hwaddr addr,
1800                                                 uint64_t data, unsigned size)
1801 {
1802     VFIOQuirk *quirk = opaque;
1803 
1804     switch (addr) {
1805     case 0x0:
1806         if (data & 0x1) {
1807             quirk->data.flags |= NV_BAR5_MASTER;
1808         } else {
1809             quirk->data.flags &= ~NV_BAR5_MASTER;
1810         }
1811         break;
1812     case 0x4:
1813         if (data & 0x1) {
1814             quirk->data.flags |= NV_BAR5_ENABLE;
1815         } else {
1816             quirk->data.flags &= ~NV_BAR5_ENABLE;
1817         }
1818         break;
1819     case 0x8:
1820         if (quirk->data.flags & NV_BAR5_MASTER) {
1821             if ((data & ~0xfff) == 0x88000) {
1822                 quirk->data.flags |= NV_BAR5_ADDRESS;
1823                 quirk->data.address_val = data & 0xfff;
1824             } else if ((data & ~0xff) == 0x1800) {
1825                 quirk->data.flags |= NV_BAR5_ADDRESS;
1826                 quirk->data.address_val = data & 0xff;
1827             } else {
1828                 quirk->data.flags &= ~NV_BAR5_ADDRESS;
1829             }
1830         }
1831         break;
1832     }
1833 
1834     vfio_generic_window_quirk_write(opaque, addr, data, size);
1835 }
1836 
1837 static const MemoryRegionOps vfio_nvidia_bar5_window_quirk = {
1838     .read = vfio_generic_window_quirk_read,
1839     .write = vfio_nvidia_bar5_window_quirk_write,
1840     .valid.min_access_size = 4,
1841     .endianness = DEVICE_LITTLE_ENDIAN,
1842 };
1843 
1844 static void vfio_probe_nvidia_bar5_window_quirk(VFIOPCIDevice *vdev, int nr)
1845 {
1846     PCIDevice *pdev = &vdev->pdev;
1847     VFIOQuirk *quirk;
1848 
1849     if (!vdev->has_vga || nr != 5 ||
1850         pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_NVIDIA) {
1851         return;
1852     }
1853 
1854     quirk = g_malloc0(sizeof(*quirk));
1855     quirk->vdev = vdev;
1856     quirk->data.read_flags = quirk->data.write_flags = NV_BAR5_VALID;
1857     quirk->data.address_offset = 0x8;
1858     quirk->data.address_size = 0; /* actually 4, but avoids generic code */
1859     quirk->data.data_offset = 0xc;
1860     quirk->data.data_size = 4;
1861     quirk->data.bar = nr;
1862 
1863     memory_region_init_io(&quirk->mem, OBJECT(vdev),
1864                           &vfio_nvidia_bar5_window_quirk, quirk,
1865                           "vfio-nvidia-bar5-window-quirk", 16);
1866     memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
1867                                         0, &quirk->mem, 1);
1868 
1869     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1870 
1871     trace_vfio_probe_nvidia_bar5_window_quirk(vdev->vbasedev.name);
1872 }
1873 
1874 static void vfio_nvidia_88000_quirk_write(void *opaque, hwaddr addr,
1875                                           uint64_t data, unsigned size)
1876 {
1877     VFIOQuirk *quirk = opaque;
1878     VFIOPCIDevice *vdev = quirk->vdev;
1879     PCIDevice *pdev = &vdev->pdev;
1880     hwaddr base = quirk->data.address_match & TARGET_PAGE_MASK;
1881 
1882     vfio_generic_quirk_write(opaque, addr, data, size);
1883 
1884     /*
1885      * Nvidia seems to acknowledge MSI interrupts by writing 0xff to the
1886      * MSI capability ID register.  Both the ID and next register are
1887      * read-only, so we allow writes covering either of those to real hw.
1888      * NB - only fixed for the 0x88000 MMIO window.
1889      */
1890     if ((pdev->cap_present & QEMU_PCI_CAP_MSI) &&
1891         vfio_range_contained(addr, size, pdev->msi_cap, PCI_MSI_FLAGS)) {
1892         vfio_region_write(&vdev->bars[quirk->data.bar].region,
1893                           addr + base, data, size);
1894     }
1895 }
1896 
1897 static const MemoryRegionOps vfio_nvidia_88000_quirk = {
1898     .read = vfio_generic_quirk_read,
1899     .write = vfio_nvidia_88000_quirk_write,
1900     .endianness = DEVICE_LITTLE_ENDIAN,
1901 };
1902 
1903 /*
1904  * Finally, BAR0 itself.  We want to redirect any accesses to either
1905  * 0x1800 or 0x88000 through the PCI config space access functions.
1906  *
1907  * NB - quirk at a page granularity or else they don't seem to work when
1908  *      BARs are mmap'd
1909  *
1910  * Here's offset 0x88000...
1911  */
1912 static void vfio_probe_nvidia_bar0_88000_quirk(VFIOPCIDevice *vdev, int nr)
1913 {
1914     PCIDevice *pdev = &vdev->pdev;
1915     VFIOQuirk *quirk;
1916     uint16_t vendor, class;
1917 
1918     vendor = pci_get_word(pdev->config + PCI_VENDOR_ID);
1919     class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
1920 
1921     if (nr != 0 || vendor != PCI_VENDOR_ID_NVIDIA ||
1922         class != PCI_CLASS_DISPLAY_VGA) {
1923         return;
1924     }
1925 
1926     quirk = g_malloc0(sizeof(*quirk));
1927     quirk->vdev = vdev;
1928     quirk->data.flags = quirk->data.read_flags = quirk->data.write_flags = 1;
1929     quirk->data.address_match = 0x88000;
1930     quirk->data.address_mask = PCIE_CONFIG_SPACE_SIZE - 1;
1931     quirk->data.bar = nr;
1932 
1933     memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_nvidia_88000_quirk,
1934                           quirk, "vfio-nvidia-bar0-88000-quirk",
1935                           TARGET_PAGE_ALIGN(quirk->data.address_mask + 1));
1936     memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
1937                           quirk->data.address_match & TARGET_PAGE_MASK,
1938                           &quirk->mem, 1);
1939 
1940     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1941 
1942     trace_vfio_probe_nvidia_bar0_88000_quirk(vdev->vbasedev.name);
1943 }
1944 
1945 /*
1946  * And here's the same for BAR0 offset 0x1800...
1947  */
1948 static void vfio_probe_nvidia_bar0_1800_quirk(VFIOPCIDevice *vdev, int nr)
1949 {
1950     PCIDevice *pdev = &vdev->pdev;
1951     VFIOQuirk *quirk;
1952 
1953     if (!vdev->has_vga || nr != 0 ||
1954         pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_NVIDIA) {
1955         return;
1956     }
1957 
1958     /* Log the chipset ID */
1959     trace_vfio_probe_nvidia_bar0_1800_quirk_id(
1960             (unsigned int)(vfio_region_read(&vdev->bars[0].region, 0, 4) >> 20)
1961             & 0xff);
1962 
1963     quirk = g_malloc0(sizeof(*quirk));
1964     quirk->vdev = vdev;
1965     quirk->data.flags = quirk->data.read_flags = quirk->data.write_flags = 1;
1966     quirk->data.address_match = 0x1800;
1967     quirk->data.address_mask = PCI_CONFIG_SPACE_SIZE - 1;
1968     quirk->data.bar = nr;
1969 
1970     memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_generic_quirk, quirk,
1971                           "vfio-nvidia-bar0-1800-quirk",
1972                           TARGET_PAGE_ALIGN(quirk->data.address_mask + 1));
1973     memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,
1974                           quirk->data.address_match & TARGET_PAGE_MASK,
1975                           &quirk->mem, 1);
1976 
1977     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1978 
1979     trace_vfio_probe_nvidia_bar0_1800_quirk(vdev->vbasedev.name);
1980 }
1981 
1982 /*
1983  * TODO - Some Nvidia devices provide config access to their companion HDA
1984  * device and even to their parent bridge via these config space mirrors.
1985  * Add quirks for those regions.
1986  */
1987 
1988 /*
1989  * Common quirk probe entry points.
1990  */
1991 static void vfio_vga_quirk_setup(VFIOPCIDevice *vdev)
1992 {
1993     vfio_vga_probe_ati_3c3_quirk(vdev);
1994     vfio_vga_probe_nvidia_3d0_quirk(vdev);
1995 }
1996 
1997 static void vfio_vga_quirk_teardown(VFIOPCIDevice *vdev)
1998 {
1999     VFIOQuirk *quirk;
2000     int i;
2001 
2002     for (i = 0; i < ARRAY_SIZE(vdev->vga.region); i++) {
2003         QLIST_FOREACH(quirk, &vdev->vga.region[i].quirks, next) {
2004             memory_region_del_subregion(&vdev->vga.region[i].mem, &quirk->mem);
2005         }
2006     }
2007 }
2008 
2009 static void vfio_vga_quirk_free(VFIOPCIDevice *vdev)
2010 {
2011     int i;
2012 
2013     for (i = 0; i < ARRAY_SIZE(vdev->vga.region); i++) {
2014         while (!QLIST_EMPTY(&vdev->vga.region[i].quirks)) {
2015             VFIOQuirk *quirk = QLIST_FIRST(&vdev->vga.region[i].quirks);
2016             object_unparent(OBJECT(&quirk->mem));
2017             QLIST_REMOVE(quirk, next);
2018             g_free(quirk);
2019         }
2020     }
2021 }
2022 
2023 static void vfio_bar_quirk_setup(VFIOPCIDevice *vdev, int nr)
2024 {
2025     vfio_probe_ati_bar4_window_quirk(vdev, nr);
2026     vfio_probe_ati_bar2_4000_quirk(vdev, nr);
2027     vfio_probe_nvidia_bar5_window_quirk(vdev, nr);
2028     vfio_probe_nvidia_bar0_88000_quirk(vdev, nr);
2029     vfio_probe_nvidia_bar0_1800_quirk(vdev, nr);
2030     vfio_probe_rtl8168_bar2_window_quirk(vdev, nr);
2031 }
2032 
2033 static void vfio_bar_quirk_teardown(VFIOPCIDevice *vdev, int nr)
2034 {
2035     VFIOBAR *bar = &vdev->bars[nr];
2036     VFIOQuirk *quirk;
2037 
2038     QLIST_FOREACH(quirk, &bar->quirks, next) {
2039         memory_region_del_subregion(&bar->region.mem, &quirk->mem);
2040     }
2041 }
2042 
2043 static void vfio_bar_quirk_free(VFIOPCIDevice *vdev, int nr)
2044 {
2045     VFIOBAR *bar = &vdev->bars[nr];
2046 
2047     while (!QLIST_EMPTY(&bar->quirks)) {
2048         VFIOQuirk *quirk = QLIST_FIRST(&bar->quirks);
2049         object_unparent(OBJECT(&quirk->mem));
2050         QLIST_REMOVE(quirk, next);
2051         g_free(quirk);
2052     }
2053 }
2054 
2055 /*
2056  * PCI config space
2057  */
2058 static uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len)
2059 {
2060     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
2061     uint32_t emu_bits = 0, emu_val = 0, phys_val = 0, val;
2062 
2063     memcpy(&emu_bits, vdev->emulated_config_bits + addr, len);
2064     emu_bits = le32_to_cpu(emu_bits);
2065 
2066     if (emu_bits) {
2067         emu_val = pci_default_read_config(pdev, addr, len);
2068     }
2069 
2070     if (~emu_bits & (0xffffffffU >> (32 - len * 8))) {
2071         ssize_t ret;
2072 
2073         ret = pread(vdev->vbasedev.fd, &phys_val, len,
2074                     vdev->config_offset + addr);
2075         if (ret != len) {
2076             error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x) failed: %m",
2077                          __func__, vdev->host.domain, vdev->host.bus,
2078                          vdev->host.slot, vdev->host.function, addr, len);
2079             return -errno;
2080         }
2081         phys_val = le32_to_cpu(phys_val);
2082     }
2083 
2084     val = (emu_val & emu_bits) | (phys_val & ~emu_bits);
2085 
2086     trace_vfio_pci_read_config(vdev->vbasedev.name, addr, len, val);
2087 
2088     return val;
2089 }
2090 
2091 static void vfio_pci_write_config(PCIDevice *pdev, uint32_t addr,
2092                                   uint32_t val, int len)
2093 {
2094     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
2095     uint32_t val_le = cpu_to_le32(val);
2096 
2097     trace_vfio_pci_write_config(vdev->vbasedev.name, addr, val, len);
2098 
2099     /* Write everything to VFIO, let it filter out what we can't write */
2100     if (pwrite(vdev->vbasedev.fd, &val_le, len, vdev->config_offset + addr)
2101                 != len) {
2102         error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x, 0x%x) failed: %m",
2103                      __func__, vdev->host.domain, vdev->host.bus,
2104                      vdev->host.slot, vdev->host.function, addr, val, len);
2105     }
2106 
2107     /* MSI/MSI-X Enabling/Disabling */
2108     if (pdev->cap_present & QEMU_PCI_CAP_MSI &&
2109         ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {
2110         int is_enabled, was_enabled = msi_enabled(pdev);
2111 
2112         pci_default_write_config(pdev, addr, val, len);
2113 
2114         is_enabled = msi_enabled(pdev);
2115 
2116         if (!was_enabled) {
2117             if (is_enabled) {
2118                 vfio_enable_msi(vdev);
2119             }
2120         } else {
2121             if (!is_enabled) {
2122                 vfio_disable_msi(vdev);
2123             } else {
2124                 vfio_update_msi(vdev);
2125             }
2126         }
2127     } else if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
2128         ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {
2129         int is_enabled, was_enabled = msix_enabled(pdev);
2130 
2131         pci_default_write_config(pdev, addr, val, len);
2132 
2133         is_enabled = msix_enabled(pdev);
2134 
2135         if (!was_enabled && is_enabled) {
2136             vfio_enable_msix(vdev);
2137         } else if (was_enabled && !is_enabled) {
2138             vfio_disable_msix(vdev);
2139         }
2140     } else {
2141         /* Write everything to QEMU to keep emulated bits correct */
2142         pci_default_write_config(pdev, addr, val, len);
2143     }
2144 }
2145 
2146 /*
2147  * Interrupt setup
2148  */
2149 static void vfio_disable_interrupts(VFIOPCIDevice *vdev)
2150 {
2151     /*
2152      * More complicated than it looks.  Disabling MSI/X transitions the
2153      * device to INTx mode (if supported).  Therefore we need to first
2154      * disable MSI/X and then cleanup by disabling INTx.
2155      */
2156     if (vdev->interrupt == VFIO_INT_MSIX) {
2157         vfio_disable_msix(vdev);
2158     } else if (vdev->interrupt == VFIO_INT_MSI) {
2159         vfio_disable_msi(vdev);
2160     }
2161 
2162     if (vdev->interrupt == VFIO_INT_INTx) {
2163         vfio_disable_intx(vdev);
2164     }
2165 }
2166 
2167 static int vfio_setup_msi(VFIOPCIDevice *vdev, int pos)
2168 {
2169     uint16_t ctrl;
2170     bool msi_64bit, msi_maskbit;
2171     int ret, entries;
2172 
2173     if (pread(vdev->vbasedev.fd, &ctrl, sizeof(ctrl),
2174               vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
2175         return -errno;
2176     }
2177     ctrl = le16_to_cpu(ctrl);
2178 
2179     msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT);
2180     msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT);
2181     entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1);
2182 
2183     trace_vfio_setup_msi(vdev->vbasedev.name, pos);
2184 
2185     ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit);
2186     if (ret < 0) {
2187         if (ret == -ENOTSUP) {
2188             return 0;
2189         }
2190         error_report("vfio: msi_init failed");
2191         return ret;
2192     }
2193     vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0);
2194 
2195     return 0;
2196 }
2197 
2198 /*
2199  * We don't have any control over how pci_add_capability() inserts
2200  * capabilities into the chain.  In order to setup MSI-X we need a
2201  * MemoryRegion for the BAR.  In order to setup the BAR and not
2202  * attempt to mmap the MSI-X table area, which VFIO won't allow, we
2203  * need to first look for where the MSI-X table lives.  So we
2204  * unfortunately split MSI-X setup across two functions.
2205  */
2206 static int vfio_early_setup_msix(VFIOPCIDevice *vdev)
2207 {
2208     uint8_t pos;
2209     uint16_t ctrl;
2210     uint32_t table, pba;
2211     int fd = vdev->vbasedev.fd;
2212 
2213     pos = pci_find_capability(&vdev->pdev, PCI_CAP_ID_MSIX);
2214     if (!pos) {
2215         return 0;
2216     }
2217 
2218     if (pread(fd, &ctrl, sizeof(ctrl),
2219               vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
2220         return -errno;
2221     }
2222 
2223     if (pread(fd, &table, sizeof(table),
2224               vdev->config_offset + pos + PCI_MSIX_TABLE) != sizeof(table)) {
2225         return -errno;
2226     }
2227 
2228     if (pread(fd, &pba, sizeof(pba),
2229               vdev->config_offset + pos + PCI_MSIX_PBA) != sizeof(pba)) {
2230         return -errno;
2231     }
2232 
2233     ctrl = le16_to_cpu(ctrl);
2234     table = le32_to_cpu(table);
2235     pba = le32_to_cpu(pba);
2236 
2237     vdev->msix = g_malloc0(sizeof(*(vdev->msix)));
2238     vdev->msix->table_bar = table & PCI_MSIX_FLAGS_BIRMASK;
2239     vdev->msix->table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
2240     vdev->msix->pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK;
2241     vdev->msix->pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
2242     vdev->msix->entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
2243 
2244     trace_vfio_early_setup_msix(vdev->vbasedev.name, pos,
2245                                 vdev->msix->table_bar,
2246                                 vdev->msix->table_offset,
2247                                 vdev->msix->entries);
2248 
2249     return 0;
2250 }
2251 
2252 static int vfio_setup_msix(VFIOPCIDevice *vdev, int pos)
2253 {
2254     int ret;
2255 
2256     ret = msix_init(&vdev->pdev, vdev->msix->entries,
2257                     &vdev->bars[vdev->msix->table_bar].region.mem,
2258                     vdev->msix->table_bar, vdev->msix->table_offset,
2259                     &vdev->bars[vdev->msix->pba_bar].region.mem,
2260                     vdev->msix->pba_bar, vdev->msix->pba_offset, pos);
2261     if (ret < 0) {
2262         if (ret == -ENOTSUP) {
2263             return 0;
2264         }
2265         error_report("vfio: msix_init failed");
2266         return ret;
2267     }
2268 
2269     return 0;
2270 }
2271 
2272 static void vfio_teardown_msi(VFIOPCIDevice *vdev)
2273 {
2274     msi_uninit(&vdev->pdev);
2275 
2276     if (vdev->msix) {
2277         msix_uninit(&vdev->pdev,
2278                     &vdev->bars[vdev->msix->table_bar].region.mem,
2279                     &vdev->bars[vdev->msix->pba_bar].region.mem);
2280     }
2281 }
2282 
2283 /*
2284  * Resource setup
2285  */
2286 static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled)
2287 {
2288     int i;
2289 
2290     for (i = 0; i < PCI_ROM_SLOT; i++) {
2291         VFIOBAR *bar = &vdev->bars[i];
2292 
2293         if (!bar->region.size) {
2294             continue;
2295         }
2296 
2297         memory_region_set_enabled(&bar->region.mmap_mem, enabled);
2298         if (vdev->msix && vdev->msix->table_bar == i) {
2299             memory_region_set_enabled(&vdev->msix->mmap_mem, enabled);
2300         }
2301     }
2302 }
2303 
2304 static void vfio_unregister_bar(VFIOPCIDevice *vdev, int nr)
2305 {
2306     VFIOBAR *bar = &vdev->bars[nr];
2307 
2308     if (!bar->region.size) {
2309         return;
2310     }
2311 
2312     vfio_bar_quirk_teardown(vdev, nr);
2313 
2314     memory_region_del_subregion(&bar->region.mem, &bar->region.mmap_mem);
2315 
2316     if (vdev->msix && vdev->msix->table_bar == nr) {
2317         memory_region_del_subregion(&bar->region.mem, &vdev->msix->mmap_mem);
2318     }
2319 }
2320 
2321 static void vfio_unmap_bar(VFIOPCIDevice *vdev, int nr)
2322 {
2323     VFIOBAR *bar = &vdev->bars[nr];
2324 
2325     if (!bar->region.size) {
2326         return;
2327     }
2328 
2329     vfio_bar_quirk_free(vdev, nr);
2330 
2331     munmap(bar->region.mmap, memory_region_size(&bar->region.mmap_mem));
2332 
2333     if (vdev->msix && vdev->msix->table_bar == nr) {
2334         munmap(vdev->msix->mmap, memory_region_size(&vdev->msix->mmap_mem));
2335     }
2336 }
2337 
2338 static void vfio_map_bar(VFIOPCIDevice *vdev, int nr)
2339 {
2340     VFIOBAR *bar = &vdev->bars[nr];
2341     uint64_t size = bar->region.size;
2342     char name[64];
2343     uint32_t pci_bar;
2344     uint8_t type;
2345     int ret;
2346 
2347     /* Skip both unimplemented BARs and the upper half of 64bit BARS. */
2348     if (!size) {
2349         return;
2350     }
2351 
2352     snprintf(name, sizeof(name), "VFIO %04x:%02x:%02x.%x BAR %d",
2353              vdev->host.domain, vdev->host.bus, vdev->host.slot,
2354              vdev->host.function, nr);
2355 
2356     /* Determine what type of BAR this is for registration */
2357     ret = pread(vdev->vbasedev.fd, &pci_bar, sizeof(pci_bar),
2358                 vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));
2359     if (ret != sizeof(pci_bar)) {
2360         error_report("vfio: Failed to read BAR %d (%m)", nr);
2361         return;
2362     }
2363 
2364     pci_bar = le32_to_cpu(pci_bar);
2365     bar->ioport = (pci_bar & PCI_BASE_ADDRESS_SPACE_IO);
2366     bar->mem64 = bar->ioport ? 0 : (pci_bar & PCI_BASE_ADDRESS_MEM_TYPE_64);
2367     type = pci_bar & (bar->ioport ? ~PCI_BASE_ADDRESS_IO_MASK :
2368                                     ~PCI_BASE_ADDRESS_MEM_MASK);
2369 
2370     /* A "slow" read/write mapping underlies all BARs */
2371     memory_region_init_io(&bar->region.mem, OBJECT(vdev), &vfio_region_ops,
2372                           bar, name, size);
2373     pci_register_bar(&vdev->pdev, nr, type, &bar->region.mem);
2374 
2375     /*
2376      * We can't mmap areas overlapping the MSIX vector table, so we
2377      * potentially insert a direct-mapped subregion before and after it.
2378      */
2379     if (vdev->msix && vdev->msix->table_bar == nr) {
2380         size = vdev->msix->table_offset & qemu_host_page_mask;
2381     }
2382 
2383     strncat(name, " mmap", sizeof(name) - strlen(name) - 1);
2384     if (vfio_mmap_region(OBJECT(vdev), &bar->region, &bar->region.mem,
2385                       &bar->region.mmap_mem, &bar->region.mmap,
2386                       size, 0, name)) {
2387         error_report("%s unsupported. Performance may be slow", name);
2388     }
2389 
2390     if (vdev->msix && vdev->msix->table_bar == nr) {
2391         uint64_t start;
2392 
2393         start = HOST_PAGE_ALIGN(vdev->msix->table_offset +
2394                                 (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE));
2395 
2396         size = start < bar->region.size ? bar->region.size - start : 0;
2397         strncat(name, " msix-hi", sizeof(name) - strlen(name) - 1);
2398         /* VFIOMSIXInfo contains another MemoryRegion for this mapping */
2399         if (vfio_mmap_region(OBJECT(vdev), &bar->region, &bar->region.mem,
2400                           &vdev->msix->mmap_mem,
2401                           &vdev->msix->mmap, size, start, name)) {
2402             error_report("%s unsupported. Performance may be slow", name);
2403         }
2404     }
2405 
2406     vfio_bar_quirk_setup(vdev, nr);
2407 }
2408 
2409 static void vfio_map_bars(VFIOPCIDevice *vdev)
2410 {
2411     int i;
2412 
2413     for (i = 0; i < PCI_ROM_SLOT; i++) {
2414         vfio_map_bar(vdev, i);
2415     }
2416 
2417     if (vdev->has_vga) {
2418         memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_MEM].mem,
2419                               OBJECT(vdev), &vfio_vga_ops,
2420                               &vdev->vga.region[QEMU_PCI_VGA_MEM],
2421                               "vfio-vga-mmio@0xa0000",
2422                               QEMU_PCI_VGA_MEM_SIZE);
2423         memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_IO_LO].mem,
2424                               OBJECT(vdev), &vfio_vga_ops,
2425                               &vdev->vga.region[QEMU_PCI_VGA_IO_LO],
2426                               "vfio-vga-io@0x3b0",
2427                               QEMU_PCI_VGA_IO_LO_SIZE);
2428         memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem,
2429                               OBJECT(vdev), &vfio_vga_ops,
2430                               &vdev->vga.region[QEMU_PCI_VGA_IO_HI],
2431                               "vfio-vga-io@0x3c0",
2432                               QEMU_PCI_VGA_IO_HI_SIZE);
2433 
2434         pci_register_vga(&vdev->pdev, &vdev->vga.region[QEMU_PCI_VGA_MEM].mem,
2435                          &vdev->vga.region[QEMU_PCI_VGA_IO_LO].mem,
2436                          &vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem);
2437         vfio_vga_quirk_setup(vdev);
2438     }
2439 }
2440 
2441 static void vfio_unregister_bars(VFIOPCIDevice *vdev)
2442 {
2443     int i;
2444 
2445     for (i = 0; i < PCI_ROM_SLOT; i++) {
2446         vfio_unregister_bar(vdev, i);
2447     }
2448 
2449     if (vdev->has_vga) {
2450         vfio_vga_quirk_teardown(vdev);
2451         pci_unregister_vga(&vdev->pdev);
2452     }
2453 }
2454 
2455 static void vfio_unmap_bars(VFIOPCIDevice *vdev)
2456 {
2457     int i;
2458 
2459     for (i = 0; i < PCI_ROM_SLOT; i++) {
2460         vfio_unmap_bar(vdev, i);
2461     }
2462 
2463     if (vdev->has_vga) {
2464         vfio_vga_quirk_free(vdev);
2465     }
2466 }
2467 
2468 /*
2469  * General setup
2470  */
2471 static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos)
2472 {
2473     uint8_t tmp, next = 0xff;
2474 
2475     for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp;
2476          tmp = pdev->config[tmp + 1]) {
2477         if (tmp > pos && tmp < next) {
2478             next = tmp;
2479         }
2480     }
2481 
2482     return next - pos;
2483 }
2484 
2485 static void vfio_set_word_bits(uint8_t *buf, uint16_t val, uint16_t mask)
2486 {
2487     pci_set_word(buf, (pci_get_word(buf) & ~mask) | val);
2488 }
2489 
2490 static void vfio_add_emulated_word(VFIOPCIDevice *vdev, int pos,
2491                                    uint16_t val, uint16_t mask)
2492 {
2493     vfio_set_word_bits(vdev->pdev.config + pos, val, mask);
2494     vfio_set_word_bits(vdev->pdev.wmask + pos, ~mask, mask);
2495     vfio_set_word_bits(vdev->emulated_config_bits + pos, mask, mask);
2496 }
2497 
2498 static void vfio_set_long_bits(uint8_t *buf, uint32_t val, uint32_t mask)
2499 {
2500     pci_set_long(buf, (pci_get_long(buf) & ~mask) | val);
2501 }
2502 
2503 static void vfio_add_emulated_long(VFIOPCIDevice *vdev, int pos,
2504                                    uint32_t val, uint32_t mask)
2505 {
2506     vfio_set_long_bits(vdev->pdev.config + pos, val, mask);
2507     vfio_set_long_bits(vdev->pdev.wmask + pos, ~mask, mask);
2508     vfio_set_long_bits(vdev->emulated_config_bits + pos, mask, mask);
2509 }
2510 
2511 static int vfio_setup_pcie_cap(VFIOPCIDevice *vdev, int pos, uint8_t size)
2512 {
2513     uint16_t flags;
2514     uint8_t type;
2515 
2516     flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS);
2517     type = (flags & PCI_EXP_FLAGS_TYPE) >> 4;
2518 
2519     if (type != PCI_EXP_TYPE_ENDPOINT &&
2520         type != PCI_EXP_TYPE_LEG_END &&
2521         type != PCI_EXP_TYPE_RC_END) {
2522 
2523         error_report("vfio: Assignment of PCIe type 0x%x "
2524                      "devices is not currently supported", type);
2525         return -EINVAL;
2526     }
2527 
2528     if (!pci_bus_is_express(vdev->pdev.bus)) {
2529         /*
2530          * Use express capability as-is on PCI bus.  It doesn't make much
2531          * sense to even expose, but some drivers (ex. tg3) depend on it
2532          * and guests don't seem to be particular about it.  We'll need
2533          * to revist this or force express devices to express buses if we
2534          * ever expose an IOMMU to the guest.
2535          */
2536     } else if (pci_bus_is_root(vdev->pdev.bus)) {
2537         /*
2538          * On a Root Complex bus Endpoints become Root Complex Integrated
2539          * Endpoints, which changes the type and clears the LNK & LNK2 fields.
2540          */
2541         if (type == PCI_EXP_TYPE_ENDPOINT) {
2542             vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
2543                                    PCI_EXP_TYPE_RC_END << 4,
2544                                    PCI_EXP_FLAGS_TYPE);
2545 
2546             /* Link Capabilities, Status, and Control goes away */
2547             if (size > PCI_EXP_LNKCTL) {
2548                 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0);
2549                 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
2550                 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0);
2551 
2552 #ifndef PCI_EXP_LNKCAP2
2553 #define PCI_EXP_LNKCAP2 44
2554 #endif
2555 #ifndef PCI_EXP_LNKSTA2
2556 #define PCI_EXP_LNKSTA2 50
2557 #endif
2558                 /* Link 2 Capabilities, Status, and Control goes away */
2559                 if (size > PCI_EXP_LNKCAP2) {
2560                     vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0);
2561                     vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0);
2562                     vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0);
2563                 }
2564             }
2565 
2566         } else if (type == PCI_EXP_TYPE_LEG_END) {
2567             /*
2568              * Legacy endpoints don't belong on the root complex.  Windows
2569              * seems to be happier with devices if we skip the capability.
2570              */
2571             return 0;
2572         }
2573 
2574     } else {
2575         /*
2576          * Convert Root Complex Integrated Endpoints to regular endpoints.
2577          * These devices don't support LNK/LNK2 capabilities, so make them up.
2578          */
2579         if (type == PCI_EXP_TYPE_RC_END) {
2580             vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
2581                                    PCI_EXP_TYPE_ENDPOINT << 4,
2582                                    PCI_EXP_FLAGS_TYPE);
2583             vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP,
2584                                    PCI_EXP_LNK_MLW_1 | PCI_EXP_LNK_LS_25, ~0);
2585             vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
2586         }
2587 
2588         /* Mark the Link Status bits as emulated to allow virtual negotiation */
2589         vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA,
2590                                pci_get_word(vdev->pdev.config + pos +
2591                                             PCI_EXP_LNKSTA),
2592                                PCI_EXP_LNKCAP_MLW | PCI_EXP_LNKCAP_SLS);
2593     }
2594 
2595     pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size);
2596     if (pos >= 0) {
2597         vdev->pdev.exp.exp_cap = pos;
2598     }
2599 
2600     return pos;
2601 }
2602 
2603 static void vfio_check_pcie_flr(VFIOPCIDevice *vdev, uint8_t pos)
2604 {
2605     uint32_t cap = pci_get_long(vdev->pdev.config + pos + PCI_EXP_DEVCAP);
2606 
2607     if (cap & PCI_EXP_DEVCAP_FLR) {
2608         trace_vfio_check_pcie_flr(vdev->vbasedev.name);
2609         vdev->has_flr = true;
2610     }
2611 }
2612 
2613 static void vfio_check_pm_reset(VFIOPCIDevice *vdev, uint8_t pos)
2614 {
2615     uint16_t csr = pci_get_word(vdev->pdev.config + pos + PCI_PM_CTRL);
2616 
2617     if (!(csr & PCI_PM_CTRL_NO_SOFT_RESET)) {
2618         trace_vfio_check_pm_reset(vdev->vbasedev.name);
2619         vdev->has_pm_reset = true;
2620     }
2621 }
2622 
2623 static void vfio_check_af_flr(VFIOPCIDevice *vdev, uint8_t pos)
2624 {
2625     uint8_t cap = pci_get_byte(vdev->pdev.config + pos + PCI_AF_CAP);
2626 
2627     if ((cap & PCI_AF_CAP_TP) && (cap & PCI_AF_CAP_FLR)) {
2628         trace_vfio_check_af_flr(vdev->vbasedev.name);
2629         vdev->has_flr = true;
2630     }
2631 }
2632 
2633 static int vfio_add_std_cap(VFIOPCIDevice *vdev, uint8_t pos)
2634 {
2635     PCIDevice *pdev = &vdev->pdev;
2636     uint8_t cap_id, next, size;
2637     int ret;
2638 
2639     cap_id = pdev->config[pos];
2640     next = pdev->config[pos + 1];
2641 
2642     /*
2643      * If it becomes important to configure capabilities to their actual
2644      * size, use this as the default when it's something we don't recognize.
2645      * Since QEMU doesn't actually handle many of the config accesses,
2646      * exact size doesn't seem worthwhile.
2647      */
2648     size = vfio_std_cap_max_size(pdev, pos);
2649 
2650     /*
2651      * pci_add_capability always inserts the new capability at the head
2652      * of the chain.  Therefore to end up with a chain that matches the
2653      * physical device, we insert from the end by making this recursive.
2654      * This is also why we pre-caclulate size above as cached config space
2655      * will be changed as we unwind the stack.
2656      */
2657     if (next) {
2658         ret = vfio_add_std_cap(vdev, next);
2659         if (ret) {
2660             return ret;
2661         }
2662     } else {
2663         /* Begin the rebuild, use QEMU emulated list bits */
2664         pdev->config[PCI_CAPABILITY_LIST] = 0;
2665         vdev->emulated_config_bits[PCI_CAPABILITY_LIST] = 0xff;
2666         vdev->emulated_config_bits[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2667     }
2668 
2669     /* Use emulated next pointer to allow dropping caps */
2670     pci_set_byte(vdev->emulated_config_bits + pos + 1, 0xff);
2671 
2672     switch (cap_id) {
2673     case PCI_CAP_ID_MSI:
2674         ret = vfio_setup_msi(vdev, pos);
2675         break;
2676     case PCI_CAP_ID_EXP:
2677         vfio_check_pcie_flr(vdev, pos);
2678         ret = vfio_setup_pcie_cap(vdev, pos, size);
2679         break;
2680     case PCI_CAP_ID_MSIX:
2681         ret = vfio_setup_msix(vdev, pos);
2682         break;
2683     case PCI_CAP_ID_PM:
2684         vfio_check_pm_reset(vdev, pos);
2685         vdev->pm_cap = pos;
2686         ret = pci_add_capability(pdev, cap_id, pos, size);
2687         break;
2688     case PCI_CAP_ID_AF:
2689         vfio_check_af_flr(vdev, pos);
2690         ret = pci_add_capability(pdev, cap_id, pos, size);
2691         break;
2692     default:
2693         ret = pci_add_capability(pdev, cap_id, pos, size);
2694         break;
2695     }
2696 
2697     if (ret < 0) {
2698         error_report("vfio: %04x:%02x:%02x.%x Error adding PCI capability "
2699                      "0x%x[0x%x]@0x%x: %d", vdev->host.domain,
2700                      vdev->host.bus, vdev->host.slot, vdev->host.function,
2701                      cap_id, size, pos, ret);
2702         return ret;
2703     }
2704 
2705     return 0;
2706 }
2707 
2708 static int vfio_add_capabilities(VFIOPCIDevice *vdev)
2709 {
2710     PCIDevice *pdev = &vdev->pdev;
2711 
2712     if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
2713         !pdev->config[PCI_CAPABILITY_LIST]) {
2714         return 0; /* Nothing to add */
2715     }
2716 
2717     return vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST]);
2718 }
2719 
2720 static void vfio_pci_pre_reset(VFIOPCIDevice *vdev)
2721 {
2722     PCIDevice *pdev = &vdev->pdev;
2723     uint16_t cmd;
2724 
2725     vfio_disable_interrupts(vdev);
2726 
2727     /* Make sure the device is in D0 */
2728     if (vdev->pm_cap) {
2729         uint16_t pmcsr;
2730         uint8_t state;
2731 
2732         pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2733         state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2734         if (state) {
2735             pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
2736             vfio_pci_write_config(pdev, vdev->pm_cap + PCI_PM_CTRL, pmcsr, 2);
2737             /* vfio handles the necessary delay here */
2738             pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2739             state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2740             if (state) {
2741                 error_report("vfio: Unable to power on device, stuck in D%d",
2742                              state);
2743             }
2744         }
2745     }
2746 
2747     /*
2748      * Stop any ongoing DMA by disconecting I/O, MMIO, and bus master.
2749      * Also put INTx Disable in known state.
2750      */
2751     cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2);
2752     cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
2753              PCI_COMMAND_INTX_DISABLE);
2754     vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2);
2755 }
2756 
2757 static void vfio_pci_post_reset(VFIOPCIDevice *vdev)
2758 {
2759     vfio_enable_intx(vdev);
2760 }
2761 
2762 static bool vfio_pci_host_match(PCIHostDeviceAddress *host1,
2763                                 PCIHostDeviceAddress *host2)
2764 {
2765     return (host1->domain == host2->domain && host1->bus == host2->bus &&
2766             host1->slot == host2->slot && host1->function == host2->function);
2767 }
2768 
2769 static int vfio_pci_hot_reset(VFIOPCIDevice *vdev, bool single)
2770 {
2771     VFIOGroup *group;
2772     struct vfio_pci_hot_reset_info *info;
2773     struct vfio_pci_dependent_device *devices;
2774     struct vfio_pci_hot_reset *reset;
2775     int32_t *fds;
2776     int ret, i, count;
2777     bool multi = false;
2778 
2779     trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
2780 
2781     vfio_pci_pre_reset(vdev);
2782     vdev->vbasedev.needs_reset = false;
2783 
2784     info = g_malloc0(sizeof(*info));
2785     info->argsz = sizeof(*info);
2786 
2787     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
2788     if (ret && errno != ENOSPC) {
2789         ret = -errno;
2790         if (!vdev->has_pm_reset) {
2791             error_report("vfio: Cannot reset device %04x:%02x:%02x.%x, "
2792                          "no available reset mechanism.", vdev->host.domain,
2793                          vdev->host.bus, vdev->host.slot, vdev->host.function);
2794         }
2795         goto out_single;
2796     }
2797 
2798     count = info->count;
2799     info = g_realloc(info, sizeof(*info) + (count * sizeof(*devices)));
2800     info->argsz = sizeof(*info) + (count * sizeof(*devices));
2801     devices = &info->devices[0];
2802 
2803     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
2804     if (ret) {
2805         ret = -errno;
2806         error_report("vfio: hot reset info failed: %m");
2807         goto out_single;
2808     }
2809 
2810     trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
2811 
2812     /* Verify that we have all the groups required */
2813     for (i = 0; i < info->count; i++) {
2814         PCIHostDeviceAddress host;
2815         VFIOPCIDevice *tmp;
2816         VFIODevice *vbasedev_iter;
2817 
2818         host.domain = devices[i].segment;
2819         host.bus = devices[i].bus;
2820         host.slot = PCI_SLOT(devices[i].devfn);
2821         host.function = PCI_FUNC(devices[i].devfn);
2822 
2823         trace_vfio_pci_hot_reset_dep_devices(host.domain,
2824                 host.bus, host.slot, host.function, devices[i].group_id);
2825 
2826         if (vfio_pci_host_match(&host, &vdev->host)) {
2827             continue;
2828         }
2829 
2830         QLIST_FOREACH(group, &vfio_group_list, next) {
2831             if (group->groupid == devices[i].group_id) {
2832                 break;
2833             }
2834         }
2835 
2836         if (!group) {
2837             if (!vdev->has_pm_reset) {
2838                 error_report("vfio: Cannot reset device %s, "
2839                              "depends on group %d which is not owned.",
2840                              vdev->vbasedev.name, devices[i].group_id);
2841             }
2842             ret = -EPERM;
2843             goto out;
2844         }
2845 
2846         /* Prep dependent devices for reset and clear our marker. */
2847         QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2848             if (vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
2849                 continue;
2850             }
2851             tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
2852             if (vfio_pci_host_match(&host, &tmp->host)) {
2853                 if (single) {
2854                     ret = -EINVAL;
2855                     goto out_single;
2856                 }
2857                 vfio_pci_pre_reset(tmp);
2858                 tmp->vbasedev.needs_reset = false;
2859                 multi = true;
2860                 break;
2861             }
2862         }
2863     }
2864 
2865     if (!single && !multi) {
2866         ret = -EINVAL;
2867         goto out_single;
2868     }
2869 
2870     /* Determine how many group fds need to be passed */
2871     count = 0;
2872     QLIST_FOREACH(group, &vfio_group_list, next) {
2873         for (i = 0; i < info->count; i++) {
2874             if (group->groupid == devices[i].group_id) {
2875                 count++;
2876                 break;
2877             }
2878         }
2879     }
2880 
2881     reset = g_malloc0(sizeof(*reset) + (count * sizeof(*fds)));
2882     reset->argsz = sizeof(*reset) + (count * sizeof(*fds));
2883     fds = &reset->group_fds[0];
2884 
2885     /* Fill in group fds */
2886     QLIST_FOREACH(group, &vfio_group_list, next) {
2887         for (i = 0; i < info->count; i++) {
2888             if (group->groupid == devices[i].group_id) {
2889                 fds[reset->count++] = group->fd;
2890                 break;
2891             }
2892         }
2893     }
2894 
2895     /* Bus reset! */
2896     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
2897     g_free(reset);
2898 
2899     trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
2900                                     ret ? "%m" : "Success");
2901 
2902 out:
2903     /* Re-enable INTx on affected devices */
2904     for (i = 0; i < info->count; i++) {
2905         PCIHostDeviceAddress host;
2906         VFIOPCIDevice *tmp;
2907         VFIODevice *vbasedev_iter;
2908 
2909         host.domain = devices[i].segment;
2910         host.bus = devices[i].bus;
2911         host.slot = PCI_SLOT(devices[i].devfn);
2912         host.function = PCI_FUNC(devices[i].devfn);
2913 
2914         if (vfio_pci_host_match(&host, &vdev->host)) {
2915             continue;
2916         }
2917 
2918         QLIST_FOREACH(group, &vfio_group_list, next) {
2919             if (group->groupid == devices[i].group_id) {
2920                 break;
2921             }
2922         }
2923 
2924         if (!group) {
2925             break;
2926         }
2927 
2928         QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2929             if (vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
2930                 continue;
2931             }
2932             tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
2933             if (vfio_pci_host_match(&host, &tmp->host)) {
2934                 vfio_pci_post_reset(tmp);
2935                 break;
2936             }
2937         }
2938     }
2939 out_single:
2940     vfio_pci_post_reset(vdev);
2941     g_free(info);
2942 
2943     return ret;
2944 }
2945 
2946 /*
2947  * We want to differentiate hot reset of mulitple in-use devices vs hot reset
2948  * of a single in-use device.  VFIO_DEVICE_RESET will already handle the case
2949  * of doing hot resets when there is only a single device per bus.  The in-use
2950  * here refers to how many VFIODevices are affected.  A hot reset that affects
2951  * multiple devices, but only a single in-use device, means that we can call
2952  * it from our bus ->reset() callback since the extent is effectively a single
2953  * device.  This allows us to make use of it in the hotplug path.  When there
2954  * are multiple in-use devices, we can only trigger the hot reset during a
2955  * system reset and thus from our reset handler.  We separate _one vs _multi
2956  * here so that we don't overlap and do a double reset on the system reset
2957  * path where both our reset handler and ->reset() callback are used.  Calling
2958  * _one() will only do a hot reset for the one in-use devices case, calling
2959  * _multi() will do nothing if a _one() would have been sufficient.
2960  */
2961 static int vfio_pci_hot_reset_one(VFIOPCIDevice *vdev)
2962 {
2963     return vfio_pci_hot_reset(vdev, true);
2964 }
2965 
2966 static int vfio_pci_hot_reset_multi(VFIODevice *vbasedev)
2967 {
2968     VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2969     return vfio_pci_hot_reset(vdev, false);
2970 }
2971 
2972 static void vfio_pci_compute_needs_reset(VFIODevice *vbasedev)
2973 {
2974     VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2975     if (!vbasedev->reset_works || (!vdev->has_flr && vdev->has_pm_reset)) {
2976         vbasedev->needs_reset = true;
2977     }
2978 }
2979 
2980 static VFIODeviceOps vfio_pci_ops = {
2981     .vfio_compute_needs_reset = vfio_pci_compute_needs_reset,
2982     .vfio_hot_reset_multi = vfio_pci_hot_reset_multi,
2983     .vfio_eoi = vfio_eoi,
2984 };
2985 
2986 static int vfio_populate_device(VFIOPCIDevice *vdev)
2987 {
2988     VFIODevice *vbasedev = &vdev->vbasedev;
2989     struct vfio_region_info reg_info = { .argsz = sizeof(reg_info) };
2990     struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };
2991     int i, ret = -1;
2992 
2993     /* Sanity check device */
2994     if (!(vbasedev->flags & VFIO_DEVICE_FLAGS_PCI)) {
2995         error_report("vfio: Um, this isn't a PCI device");
2996         goto error;
2997     }
2998 
2999     if (vbasedev->num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) {
3000         error_report("vfio: unexpected number of io regions %u",
3001                      vbasedev->num_regions);
3002         goto error;
3003     }
3004 
3005     if (vbasedev->num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) {
3006         error_report("vfio: unexpected number of irqs %u", vbasedev->num_irqs);
3007         goto error;
3008     }
3009 
3010     for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
3011         reg_info.index = i;
3012 
3013         ret = ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
3014         if (ret) {
3015             error_report("vfio: Error getting region %d info: %m", i);
3016             goto error;
3017         }
3018 
3019         trace_vfio_populate_device_region(vbasedev->name, i,
3020                                           (unsigned long)reg_info.size,
3021                                           (unsigned long)reg_info.offset,
3022                                           (unsigned long)reg_info.flags);
3023 
3024         vdev->bars[i].region.vbasedev = vbasedev;
3025         vdev->bars[i].region.flags = reg_info.flags;
3026         vdev->bars[i].region.size = reg_info.size;
3027         vdev->bars[i].region.fd_offset = reg_info.offset;
3028         vdev->bars[i].region.nr = i;
3029         QLIST_INIT(&vdev->bars[i].quirks);
3030     }
3031 
3032     reg_info.index = VFIO_PCI_CONFIG_REGION_INDEX;
3033 
3034     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
3035     if (ret) {
3036         error_report("vfio: Error getting config info: %m");
3037         goto error;
3038     }
3039 
3040     trace_vfio_populate_device_config(vdev->vbasedev.name,
3041                                       (unsigned long)reg_info.size,
3042                                       (unsigned long)reg_info.offset,
3043                                       (unsigned long)reg_info.flags);
3044 
3045     vdev->config_size = reg_info.size;
3046     if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) {
3047         vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS;
3048     }
3049     vdev->config_offset = reg_info.offset;
3050 
3051     if ((vdev->features & VFIO_FEATURE_ENABLE_VGA) &&
3052         vbasedev->num_regions > VFIO_PCI_VGA_REGION_INDEX) {
3053         struct vfio_region_info vga_info = {
3054             .argsz = sizeof(vga_info),
3055             .index = VFIO_PCI_VGA_REGION_INDEX,
3056          };
3057 
3058         ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &vga_info);
3059         if (ret) {
3060             error_report(
3061                 "vfio: Device does not support requested feature x-vga");
3062             goto error;
3063         }
3064 
3065         if (!(vga_info.flags & VFIO_REGION_INFO_FLAG_READ) ||
3066             !(vga_info.flags & VFIO_REGION_INFO_FLAG_WRITE) ||
3067             vga_info.size < 0xbffff + 1) {
3068             error_report("vfio: Unexpected VGA info, flags 0x%lx, size 0x%lx",
3069                          (unsigned long)vga_info.flags,
3070                          (unsigned long)vga_info.size);
3071             goto error;
3072         }
3073 
3074         vdev->vga.fd_offset = vga_info.offset;
3075         vdev->vga.fd = vdev->vbasedev.fd;
3076 
3077         vdev->vga.region[QEMU_PCI_VGA_MEM].offset = QEMU_PCI_VGA_MEM_BASE;
3078         vdev->vga.region[QEMU_PCI_VGA_MEM].nr = QEMU_PCI_VGA_MEM;
3079         QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_MEM].quirks);
3080 
3081         vdev->vga.region[QEMU_PCI_VGA_IO_LO].offset = QEMU_PCI_VGA_IO_LO_BASE;
3082         vdev->vga.region[QEMU_PCI_VGA_IO_LO].nr = QEMU_PCI_VGA_IO_LO;
3083         QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_IO_LO].quirks);
3084 
3085         vdev->vga.region[QEMU_PCI_VGA_IO_HI].offset = QEMU_PCI_VGA_IO_HI_BASE;
3086         vdev->vga.region[QEMU_PCI_VGA_IO_HI].nr = QEMU_PCI_VGA_IO_HI;
3087         QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].quirks);
3088 
3089         vdev->has_vga = true;
3090     }
3091     irq_info.index = VFIO_PCI_ERR_IRQ_INDEX;
3092 
3093     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);
3094     if (ret) {
3095         /* This can fail for an old kernel or legacy PCI dev */
3096         trace_vfio_populate_device_get_irq_info_failure();
3097         ret = 0;
3098     } else if (irq_info.count == 1) {
3099         vdev->pci_aer = true;
3100     } else {
3101         error_report("vfio: %s "
3102                      "Could not enable error recovery for the device",
3103                      vbasedev->name);
3104     }
3105 
3106 error:
3107     return ret;
3108 }
3109 
3110 static void vfio_put_device(VFIOPCIDevice *vdev)
3111 {
3112     g_free(vdev->vbasedev.name);
3113     if (vdev->msix) {
3114         object_unparent(OBJECT(&vdev->msix->mmap_mem));
3115         g_free(vdev->msix);
3116         vdev->msix = NULL;
3117     }
3118     vfio_put_base_device(&vdev->vbasedev);
3119 }
3120 
3121 static void vfio_err_notifier_handler(void *opaque)
3122 {
3123     VFIOPCIDevice *vdev = opaque;
3124 
3125     if (!event_notifier_test_and_clear(&vdev->err_notifier)) {
3126         return;
3127     }
3128 
3129     /*
3130      * TBD. Retrieve the error details and decide what action
3131      * needs to be taken. One of the actions could be to pass
3132      * the error to the guest and have the guest driver recover
3133      * from the error. This requires that PCIe capabilities be
3134      * exposed to the guest. For now, we just terminate the
3135      * guest to contain the error.
3136      */
3137 
3138     error_report("%s(%04x:%02x:%02x.%x) Unrecoverable error detected.  "
3139                  "Please collect any data possible and then kill the guest",
3140                  __func__, vdev->host.domain, vdev->host.bus,
3141                  vdev->host.slot, vdev->host.function);
3142 
3143     vm_stop(RUN_STATE_INTERNAL_ERROR);
3144 }
3145 
3146 /*
3147  * Registers error notifier for devices supporting error recovery.
3148  * If we encounter a failure in this function, we report an error
3149  * and continue after disabling error recovery support for the
3150  * device.
3151  */
3152 static void vfio_register_err_notifier(VFIOPCIDevice *vdev)
3153 {
3154     int ret;
3155     int argsz;
3156     struct vfio_irq_set *irq_set;
3157     int32_t *pfd;
3158 
3159     if (!vdev->pci_aer) {
3160         return;
3161     }
3162 
3163     if (event_notifier_init(&vdev->err_notifier, 0)) {
3164         error_report("vfio: Unable to init event notifier for error detection");
3165         vdev->pci_aer = false;
3166         return;
3167     }
3168 
3169     argsz = sizeof(*irq_set) + sizeof(*pfd);
3170 
3171     irq_set = g_malloc0(argsz);
3172     irq_set->argsz = argsz;
3173     irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
3174                      VFIO_IRQ_SET_ACTION_TRIGGER;
3175     irq_set->index = VFIO_PCI_ERR_IRQ_INDEX;
3176     irq_set->start = 0;
3177     irq_set->count = 1;
3178     pfd = (int32_t *)&irq_set->data;
3179 
3180     *pfd = event_notifier_get_fd(&vdev->err_notifier);
3181     qemu_set_fd_handler(*pfd, vfio_err_notifier_handler, NULL, vdev);
3182 
3183     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
3184     if (ret) {
3185         error_report("vfio: Failed to set up error notification");
3186         qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
3187         event_notifier_cleanup(&vdev->err_notifier);
3188         vdev->pci_aer = false;
3189     }
3190     g_free(irq_set);
3191 }
3192 
3193 static void vfio_unregister_err_notifier(VFIOPCIDevice *vdev)
3194 {
3195     int argsz;
3196     struct vfio_irq_set *irq_set;
3197     int32_t *pfd;
3198     int ret;
3199 
3200     if (!vdev->pci_aer) {
3201         return;
3202     }
3203 
3204     argsz = sizeof(*irq_set) + sizeof(*pfd);
3205 
3206     irq_set = g_malloc0(argsz);
3207     irq_set->argsz = argsz;
3208     irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
3209                      VFIO_IRQ_SET_ACTION_TRIGGER;
3210     irq_set->index = VFIO_PCI_ERR_IRQ_INDEX;
3211     irq_set->start = 0;
3212     irq_set->count = 1;
3213     pfd = (int32_t *)&irq_set->data;
3214     *pfd = -1;
3215 
3216     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
3217     if (ret) {
3218         error_report("vfio: Failed to de-assign error fd: %m");
3219     }
3220     g_free(irq_set);
3221     qemu_set_fd_handler(event_notifier_get_fd(&vdev->err_notifier),
3222                         NULL, NULL, vdev);
3223     event_notifier_cleanup(&vdev->err_notifier);
3224 }
3225 
3226 static int vfio_initfn(PCIDevice *pdev)
3227 {
3228     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
3229     VFIODevice *vbasedev_iter;
3230     VFIOGroup *group;
3231     char path[PATH_MAX], iommu_group_path[PATH_MAX], *group_name;
3232     ssize_t len;
3233     struct stat st;
3234     int groupid;
3235     int ret;
3236 
3237     /* Check that the host device exists */
3238     snprintf(path, sizeof(path),
3239              "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/",
3240              vdev->host.domain, vdev->host.bus, vdev->host.slot,
3241              vdev->host.function);
3242     if (stat(path, &st) < 0) {
3243         error_report("vfio: error: no such host device: %s", path);
3244         return -errno;
3245     }
3246 
3247     vdev->vbasedev.ops = &vfio_pci_ops;
3248 
3249     vdev->vbasedev.type = VFIO_DEVICE_TYPE_PCI;
3250     vdev->vbasedev.name = g_strdup_printf("%04x:%02x:%02x.%01x",
3251                                           vdev->host.domain, vdev->host.bus,
3252                                           vdev->host.slot, vdev->host.function);
3253 
3254     strncat(path, "iommu_group", sizeof(path) - strlen(path) - 1);
3255 
3256     len = readlink(path, iommu_group_path, sizeof(path));
3257     if (len <= 0 || len >= sizeof(path)) {
3258         error_report("vfio: error no iommu_group for device");
3259         return len < 0 ? -errno : ENAMETOOLONG;
3260     }
3261 
3262     iommu_group_path[len] = 0;
3263     group_name = basename(iommu_group_path);
3264 
3265     if (sscanf(group_name, "%d", &groupid) != 1) {
3266         error_report("vfio: error reading %s: %m", path);
3267         return -errno;
3268     }
3269 
3270     trace_vfio_initfn(vdev->vbasedev.name, groupid);
3271 
3272     group = vfio_get_group(groupid, pci_device_iommu_address_space(pdev));
3273     if (!group) {
3274         error_report("vfio: failed to get group %d", groupid);
3275         return -ENOENT;
3276     }
3277 
3278     snprintf(path, sizeof(path), "%04x:%02x:%02x.%01x",
3279             vdev->host.domain, vdev->host.bus, vdev->host.slot,
3280             vdev->host.function);
3281 
3282     QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
3283         if (strcmp(vbasedev_iter->name, vdev->vbasedev.name) == 0) {
3284             error_report("vfio: error: device %s is already attached", path);
3285             vfio_put_group(group);
3286             return -EBUSY;
3287         }
3288     }
3289 
3290     ret = vfio_get_device(group, path, &vdev->vbasedev);
3291     if (ret) {
3292         error_report("vfio: failed to get device %s", path);
3293         vfio_put_group(group);
3294         return ret;
3295     }
3296 
3297     ret = vfio_populate_device(vdev);
3298     if (ret) {
3299         return ret;
3300     }
3301 
3302     /* Get a copy of config space */
3303     ret = pread(vdev->vbasedev.fd, vdev->pdev.config,
3304                 MIN(pci_config_size(&vdev->pdev), vdev->config_size),
3305                 vdev->config_offset);
3306     if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
3307         ret = ret < 0 ? -errno : -EFAULT;
3308         error_report("vfio: Failed to read device config space");
3309         return ret;
3310     }
3311 
3312     /* vfio emulates a lot for us, but some bits need extra love */
3313     vdev->emulated_config_bits = g_malloc0(vdev->config_size);
3314 
3315     /* QEMU can choose to expose the ROM or not */
3316     memset(vdev->emulated_config_bits + PCI_ROM_ADDRESS, 0xff, 4);
3317 
3318     /* QEMU can change multi-function devices to single function, or reverse */
3319     vdev->emulated_config_bits[PCI_HEADER_TYPE] =
3320                                               PCI_HEADER_TYPE_MULTI_FUNCTION;
3321 
3322     /* Restore or clear multifunction, this is always controlled by QEMU */
3323     if (vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
3324         vdev->pdev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
3325     } else {
3326         vdev->pdev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
3327     }
3328 
3329     /*
3330      * Clear host resource mapping info.  If we choose not to register a
3331      * BAR, such as might be the case with the option ROM, we can get
3332      * confusing, unwritable, residual addresses from the host here.
3333      */
3334     memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
3335     memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
3336 
3337     vfio_pci_size_rom(vdev);
3338 
3339     ret = vfio_early_setup_msix(vdev);
3340     if (ret) {
3341         return ret;
3342     }
3343 
3344     vfio_map_bars(vdev);
3345 
3346     ret = vfio_add_capabilities(vdev);
3347     if (ret) {
3348         goto out_teardown;
3349     }
3350 
3351     /* QEMU emulates all of MSI & MSIX */
3352     if (pdev->cap_present & QEMU_PCI_CAP_MSIX) {
3353         memset(vdev->emulated_config_bits + pdev->msix_cap, 0xff,
3354                MSIX_CAP_LENGTH);
3355     }
3356 
3357     if (pdev->cap_present & QEMU_PCI_CAP_MSI) {
3358         memset(vdev->emulated_config_bits + pdev->msi_cap, 0xff,
3359                vdev->msi_cap_size);
3360     }
3361 
3362     if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
3363         vdev->intx.mmap_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
3364                                                   vfio_intx_mmap_enable, vdev);
3365         pci_device_set_intx_routing_notifier(&vdev->pdev, vfio_update_irq);
3366         ret = vfio_enable_intx(vdev);
3367         if (ret) {
3368             goto out_teardown;
3369         }
3370     }
3371 
3372     vfio_register_err_notifier(vdev);
3373 
3374     return 0;
3375 
3376 out_teardown:
3377     pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3378     vfio_teardown_msi(vdev);
3379     vfio_unregister_bars(vdev);
3380     return ret;
3381 }
3382 
3383 static void vfio_instance_finalize(Object *obj)
3384 {
3385     PCIDevice *pci_dev = PCI_DEVICE(obj);
3386     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pci_dev);
3387     VFIOGroup *group = vdev->vbasedev.group;
3388 
3389     vfio_unmap_bars(vdev);
3390     g_free(vdev->emulated_config_bits);
3391     g_free(vdev->rom);
3392     vfio_put_device(vdev);
3393     vfio_put_group(group);
3394 }
3395 
3396 static void vfio_exitfn(PCIDevice *pdev)
3397 {
3398     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
3399 
3400     vfio_unregister_err_notifier(vdev);
3401     pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3402     vfio_disable_interrupts(vdev);
3403     if (vdev->intx.mmap_timer) {
3404         timer_free(vdev->intx.mmap_timer);
3405     }
3406     vfio_teardown_msi(vdev);
3407     vfio_unregister_bars(vdev);
3408 }
3409 
3410 static void vfio_pci_reset(DeviceState *dev)
3411 {
3412     PCIDevice *pdev = DO_UPCAST(PCIDevice, qdev, dev);
3413     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
3414 
3415     trace_vfio_pci_reset(vdev->vbasedev.name);
3416 
3417     vfio_pci_pre_reset(vdev);
3418 
3419     if (vdev->vbasedev.reset_works &&
3420         (vdev->has_flr || !vdev->has_pm_reset) &&
3421         !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
3422         trace_vfio_pci_reset_flr(vdev->vbasedev.name);
3423         goto post_reset;
3424     }
3425 
3426     /* See if we can do our own bus reset */
3427     if (!vfio_pci_hot_reset_one(vdev)) {
3428         goto post_reset;
3429     }
3430 
3431     /* If nothing else works and the device supports PM reset, use it */
3432     if (vdev->vbasedev.reset_works && vdev->has_pm_reset &&
3433         !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
3434         trace_vfio_pci_reset_pm(vdev->vbasedev.name);
3435         goto post_reset;
3436     }
3437 
3438 post_reset:
3439     vfio_pci_post_reset(vdev);
3440 }
3441 
3442 static void vfio_instance_init(Object *obj)
3443 {
3444     PCIDevice *pci_dev = PCI_DEVICE(obj);
3445     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, PCI_DEVICE(obj));
3446 
3447     device_add_bootindex_property(obj, &vdev->bootindex,
3448                                   "bootindex", NULL,
3449                                   &pci_dev->qdev, NULL);
3450 }
3451 
3452 static Property vfio_pci_dev_properties[] = {
3453     DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIOPCIDevice, host),
3454     DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIOPCIDevice,
3455                        intx.mmap_timeout, 1100),
3456     DEFINE_PROP_BIT("x-vga", VFIOPCIDevice, features,
3457                     VFIO_FEATURE_ENABLE_VGA_BIT, false),
3458     DEFINE_PROP_INT32("bootindex", VFIOPCIDevice, bootindex, -1),
3459     /*
3460      * TODO - support passed fds... is this necessary?
3461      * DEFINE_PROP_STRING("vfiofd", VFIOPCIDevice, vfiofd_name),
3462      * DEFINE_PROP_STRING("vfiogroupfd, VFIOPCIDevice, vfiogroupfd_name),
3463      */
3464     DEFINE_PROP_END_OF_LIST(),
3465 };
3466 
3467 static const VMStateDescription vfio_pci_vmstate = {
3468     .name = "vfio-pci",
3469     .unmigratable = 1,
3470 };
3471 
3472 static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
3473 {
3474     DeviceClass *dc = DEVICE_CLASS(klass);
3475     PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
3476 
3477     dc->reset = vfio_pci_reset;
3478     dc->props = vfio_pci_dev_properties;
3479     dc->vmsd = &vfio_pci_vmstate;
3480     dc->desc = "VFIO-based PCI device assignment";
3481     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
3482     pdc->init = vfio_initfn;
3483     pdc->exit = vfio_exitfn;
3484     pdc->config_read = vfio_pci_read_config;
3485     pdc->config_write = vfio_pci_write_config;
3486     pdc->is_express = 1; /* We might be */
3487 }
3488 
3489 static const TypeInfo vfio_pci_dev_info = {
3490     .name = "vfio-pci",
3491     .parent = TYPE_PCI_DEVICE,
3492     .instance_size = sizeof(VFIOPCIDevice),
3493     .class_init = vfio_pci_dev_class_init,
3494     .instance_init = vfio_instance_init,
3495     .instance_finalize = vfio_instance_finalize,
3496 };
3497 
3498 static void register_vfio_pci_dev_type(void)
3499 {
3500     type_register_static(&vfio_pci_dev_info);
3501 }
3502 
3503 type_init(register_vfio_pci_dev_type)
3504