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