xref: /openbmc/qemu/hw/vfio/pci.c (revision 489653b5)
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(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(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     size_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_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 = HOST_PAGE_ALIGN((uint64_t)vdev->msix->table_offset +
2405                                 (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE));
2406 
2407         size = start < bar->region.size ? bar->region.size - start : 0;
2408         strncat(name, " msix-hi", sizeof(name) - strlen(name) - 1);
2409         /* VFIOMSIXInfo contains another MemoryRegion for this mapping */
2410         if (vfio_mmap_region(OBJECT(vdev), &bar->region, &bar->region.mem,
2411                           &vdev->msix->mmap_mem,
2412                           &vdev->msix->mmap, size, start, name)) {
2413             error_report("%s unsupported. Performance may be slow", name);
2414         }
2415     }
2416 
2417     vfio_bar_quirk_setup(vdev, nr);
2418 }
2419 
2420 static void vfio_map_bars(VFIOPCIDevice *vdev)
2421 {
2422     int i;
2423 
2424     for (i = 0; i < PCI_ROM_SLOT; i++) {
2425         vfio_map_bar(vdev, i);
2426     }
2427 
2428     if (vdev->has_vga) {
2429         memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_MEM].mem,
2430                               OBJECT(vdev), &vfio_vga_ops,
2431                               &vdev->vga.region[QEMU_PCI_VGA_MEM],
2432                               "vfio-vga-mmio@0xa0000",
2433                               QEMU_PCI_VGA_MEM_SIZE);
2434         memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_IO_LO].mem,
2435                               OBJECT(vdev), &vfio_vga_ops,
2436                               &vdev->vga.region[QEMU_PCI_VGA_IO_LO],
2437                               "vfio-vga-io@0x3b0",
2438                               QEMU_PCI_VGA_IO_LO_SIZE);
2439         memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem,
2440                               OBJECT(vdev), &vfio_vga_ops,
2441                               &vdev->vga.region[QEMU_PCI_VGA_IO_HI],
2442                               "vfio-vga-io@0x3c0",
2443                               QEMU_PCI_VGA_IO_HI_SIZE);
2444 
2445         pci_register_vga(&vdev->pdev, &vdev->vga.region[QEMU_PCI_VGA_MEM].mem,
2446                          &vdev->vga.region[QEMU_PCI_VGA_IO_LO].mem,
2447                          &vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem);
2448         vfio_vga_quirk_setup(vdev);
2449     }
2450 }
2451 
2452 static void vfio_unregister_bars(VFIOPCIDevice *vdev)
2453 {
2454     int i;
2455 
2456     for (i = 0; i < PCI_ROM_SLOT; i++) {
2457         vfio_unregister_bar(vdev, i);
2458     }
2459 
2460     if (vdev->has_vga) {
2461         vfio_vga_quirk_teardown(vdev);
2462         pci_unregister_vga(&vdev->pdev);
2463     }
2464 }
2465 
2466 static void vfio_unmap_bars(VFIOPCIDevice *vdev)
2467 {
2468     int i;
2469 
2470     for (i = 0; i < PCI_ROM_SLOT; i++) {
2471         vfio_unmap_bar(vdev, i);
2472     }
2473 
2474     if (vdev->has_vga) {
2475         vfio_vga_quirk_free(vdev);
2476     }
2477 }
2478 
2479 /*
2480  * General setup
2481  */
2482 static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos)
2483 {
2484     uint8_t tmp, next = 0xff;
2485 
2486     for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp;
2487          tmp = pdev->config[tmp + 1]) {
2488         if (tmp > pos && tmp < next) {
2489             next = tmp;
2490         }
2491     }
2492 
2493     return next - pos;
2494 }
2495 
2496 static void vfio_set_word_bits(uint8_t *buf, uint16_t val, uint16_t mask)
2497 {
2498     pci_set_word(buf, (pci_get_word(buf) & ~mask) | val);
2499 }
2500 
2501 static void vfio_add_emulated_word(VFIOPCIDevice *vdev, int pos,
2502                                    uint16_t val, uint16_t mask)
2503 {
2504     vfio_set_word_bits(vdev->pdev.config + pos, val, mask);
2505     vfio_set_word_bits(vdev->pdev.wmask + pos, ~mask, mask);
2506     vfio_set_word_bits(vdev->emulated_config_bits + pos, mask, mask);
2507 }
2508 
2509 static void vfio_set_long_bits(uint8_t *buf, uint32_t val, uint32_t mask)
2510 {
2511     pci_set_long(buf, (pci_get_long(buf) & ~mask) | val);
2512 }
2513 
2514 static void vfio_add_emulated_long(VFIOPCIDevice *vdev, int pos,
2515                                    uint32_t val, uint32_t mask)
2516 {
2517     vfio_set_long_bits(vdev->pdev.config + pos, val, mask);
2518     vfio_set_long_bits(vdev->pdev.wmask + pos, ~mask, mask);
2519     vfio_set_long_bits(vdev->emulated_config_bits + pos, mask, mask);
2520 }
2521 
2522 static int vfio_setup_pcie_cap(VFIOPCIDevice *vdev, int pos, uint8_t size)
2523 {
2524     uint16_t flags;
2525     uint8_t type;
2526 
2527     flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS);
2528     type = (flags & PCI_EXP_FLAGS_TYPE) >> 4;
2529 
2530     if (type != PCI_EXP_TYPE_ENDPOINT &&
2531         type != PCI_EXP_TYPE_LEG_END &&
2532         type != PCI_EXP_TYPE_RC_END) {
2533 
2534         error_report("vfio: Assignment of PCIe type 0x%x "
2535                      "devices is not currently supported", type);
2536         return -EINVAL;
2537     }
2538 
2539     if (!pci_bus_is_express(vdev->pdev.bus)) {
2540         /*
2541          * Use express capability as-is on PCI bus.  It doesn't make much
2542          * sense to even expose, but some drivers (ex. tg3) depend on it
2543          * and guests don't seem to be particular about it.  We'll need
2544          * to revist this or force express devices to express buses if we
2545          * ever expose an IOMMU to the guest.
2546          */
2547     } else if (pci_bus_is_root(vdev->pdev.bus)) {
2548         /*
2549          * On a Root Complex bus Endpoints become Root Complex Integrated
2550          * Endpoints, which changes the type and clears the LNK & LNK2 fields.
2551          */
2552         if (type == PCI_EXP_TYPE_ENDPOINT) {
2553             vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
2554                                    PCI_EXP_TYPE_RC_END << 4,
2555                                    PCI_EXP_FLAGS_TYPE);
2556 
2557             /* Link Capabilities, Status, and Control goes away */
2558             if (size > PCI_EXP_LNKCTL) {
2559                 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0);
2560                 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
2561                 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0);
2562 
2563 #ifndef PCI_EXP_LNKCAP2
2564 #define PCI_EXP_LNKCAP2 44
2565 #endif
2566 #ifndef PCI_EXP_LNKSTA2
2567 #define PCI_EXP_LNKSTA2 50
2568 #endif
2569                 /* Link 2 Capabilities, Status, and Control goes away */
2570                 if (size > PCI_EXP_LNKCAP2) {
2571                     vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0);
2572                     vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0);
2573                     vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0);
2574                 }
2575             }
2576 
2577         } else if (type == PCI_EXP_TYPE_LEG_END) {
2578             /*
2579              * Legacy endpoints don't belong on the root complex.  Windows
2580              * seems to be happier with devices if we skip the capability.
2581              */
2582             return 0;
2583         }
2584 
2585     } else {
2586         /*
2587          * Convert Root Complex Integrated Endpoints to regular endpoints.
2588          * These devices don't support LNK/LNK2 capabilities, so make them up.
2589          */
2590         if (type == PCI_EXP_TYPE_RC_END) {
2591             vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
2592                                    PCI_EXP_TYPE_ENDPOINT << 4,
2593                                    PCI_EXP_FLAGS_TYPE);
2594             vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP,
2595                                    PCI_EXP_LNK_MLW_1 | PCI_EXP_LNK_LS_25, ~0);
2596             vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
2597         }
2598 
2599         /* Mark the Link Status bits as emulated to allow virtual negotiation */
2600         vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA,
2601                                pci_get_word(vdev->pdev.config + pos +
2602                                             PCI_EXP_LNKSTA),
2603                                PCI_EXP_LNKCAP_MLW | PCI_EXP_LNKCAP_SLS);
2604     }
2605 
2606     pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size);
2607     if (pos >= 0) {
2608         vdev->pdev.exp.exp_cap = pos;
2609     }
2610 
2611     return pos;
2612 }
2613 
2614 static void vfio_check_pcie_flr(VFIOPCIDevice *vdev, uint8_t pos)
2615 {
2616     uint32_t cap = pci_get_long(vdev->pdev.config + pos + PCI_EXP_DEVCAP);
2617 
2618     if (cap & PCI_EXP_DEVCAP_FLR) {
2619         trace_vfio_check_pcie_flr(vdev->vbasedev.name);
2620         vdev->has_flr = true;
2621     }
2622 }
2623 
2624 static void vfio_check_pm_reset(VFIOPCIDevice *vdev, uint8_t pos)
2625 {
2626     uint16_t csr = pci_get_word(vdev->pdev.config + pos + PCI_PM_CTRL);
2627 
2628     if (!(csr & PCI_PM_CTRL_NO_SOFT_RESET)) {
2629         trace_vfio_check_pm_reset(vdev->vbasedev.name);
2630         vdev->has_pm_reset = true;
2631     }
2632 }
2633 
2634 static void vfio_check_af_flr(VFIOPCIDevice *vdev, uint8_t pos)
2635 {
2636     uint8_t cap = pci_get_byte(vdev->pdev.config + pos + PCI_AF_CAP);
2637 
2638     if ((cap & PCI_AF_CAP_TP) && (cap & PCI_AF_CAP_FLR)) {
2639         trace_vfio_check_af_flr(vdev->vbasedev.name);
2640         vdev->has_flr = true;
2641     }
2642 }
2643 
2644 static int vfio_add_std_cap(VFIOPCIDevice *vdev, uint8_t pos)
2645 {
2646     PCIDevice *pdev = &vdev->pdev;
2647     uint8_t cap_id, next, size;
2648     int ret;
2649 
2650     cap_id = pdev->config[pos];
2651     next = pdev->config[pos + 1];
2652 
2653     /*
2654      * If it becomes important to configure capabilities to their actual
2655      * size, use this as the default when it's something we don't recognize.
2656      * Since QEMU doesn't actually handle many of the config accesses,
2657      * exact size doesn't seem worthwhile.
2658      */
2659     size = vfio_std_cap_max_size(pdev, pos);
2660 
2661     /*
2662      * pci_add_capability always inserts the new capability at the head
2663      * of the chain.  Therefore to end up with a chain that matches the
2664      * physical device, we insert from the end by making this recursive.
2665      * This is also why we pre-caclulate size above as cached config space
2666      * will be changed as we unwind the stack.
2667      */
2668     if (next) {
2669         ret = vfio_add_std_cap(vdev, next);
2670         if (ret) {
2671             return ret;
2672         }
2673     } else {
2674         /* Begin the rebuild, use QEMU emulated list bits */
2675         pdev->config[PCI_CAPABILITY_LIST] = 0;
2676         vdev->emulated_config_bits[PCI_CAPABILITY_LIST] = 0xff;
2677         vdev->emulated_config_bits[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2678     }
2679 
2680     /* Use emulated next pointer to allow dropping caps */
2681     pci_set_byte(vdev->emulated_config_bits + pos + 1, 0xff);
2682 
2683     switch (cap_id) {
2684     case PCI_CAP_ID_MSI:
2685         ret = vfio_setup_msi(vdev, pos);
2686         break;
2687     case PCI_CAP_ID_EXP:
2688         vfio_check_pcie_flr(vdev, pos);
2689         ret = vfio_setup_pcie_cap(vdev, pos, size);
2690         break;
2691     case PCI_CAP_ID_MSIX:
2692         ret = vfio_setup_msix(vdev, pos);
2693         break;
2694     case PCI_CAP_ID_PM:
2695         vfio_check_pm_reset(vdev, pos);
2696         vdev->pm_cap = pos;
2697         ret = pci_add_capability(pdev, cap_id, pos, size);
2698         break;
2699     case PCI_CAP_ID_AF:
2700         vfio_check_af_flr(vdev, pos);
2701         ret = pci_add_capability(pdev, cap_id, pos, size);
2702         break;
2703     default:
2704         ret = pci_add_capability(pdev, cap_id, pos, size);
2705         break;
2706     }
2707 
2708     if (ret < 0) {
2709         error_report("vfio: %04x:%02x:%02x.%x Error adding PCI capability "
2710                      "0x%x[0x%x]@0x%x: %d", vdev->host.domain,
2711                      vdev->host.bus, vdev->host.slot, vdev->host.function,
2712                      cap_id, size, pos, ret);
2713         return ret;
2714     }
2715 
2716     return 0;
2717 }
2718 
2719 static int vfio_add_capabilities(VFIOPCIDevice *vdev)
2720 {
2721     PCIDevice *pdev = &vdev->pdev;
2722 
2723     if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
2724         !pdev->config[PCI_CAPABILITY_LIST]) {
2725         return 0; /* Nothing to add */
2726     }
2727 
2728     return vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST]);
2729 }
2730 
2731 static void vfio_pci_pre_reset(VFIOPCIDevice *vdev)
2732 {
2733     PCIDevice *pdev = &vdev->pdev;
2734     uint16_t cmd;
2735 
2736     vfio_disable_interrupts(vdev);
2737 
2738     /* Make sure the device is in D0 */
2739     if (vdev->pm_cap) {
2740         uint16_t pmcsr;
2741         uint8_t state;
2742 
2743         pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2744         state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2745         if (state) {
2746             pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
2747             vfio_pci_write_config(pdev, vdev->pm_cap + PCI_PM_CTRL, pmcsr, 2);
2748             /* vfio handles the necessary delay here */
2749             pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2750             state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2751             if (state) {
2752                 error_report("vfio: Unable to power on device, stuck in D%d",
2753                              state);
2754             }
2755         }
2756     }
2757 
2758     /*
2759      * Stop any ongoing DMA by disconecting I/O, MMIO, and bus master.
2760      * Also put INTx Disable in known state.
2761      */
2762     cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2);
2763     cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
2764              PCI_COMMAND_INTX_DISABLE);
2765     vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2);
2766 }
2767 
2768 static void vfio_pci_post_reset(VFIOPCIDevice *vdev)
2769 {
2770     vfio_enable_intx(vdev);
2771 }
2772 
2773 static bool vfio_pci_host_match(PCIHostDeviceAddress *host1,
2774                                 PCIHostDeviceAddress *host2)
2775 {
2776     return (host1->domain == host2->domain && host1->bus == host2->bus &&
2777             host1->slot == host2->slot && host1->function == host2->function);
2778 }
2779 
2780 static int vfio_pci_hot_reset(VFIOPCIDevice *vdev, bool single)
2781 {
2782     VFIOGroup *group;
2783     struct vfio_pci_hot_reset_info *info;
2784     struct vfio_pci_dependent_device *devices;
2785     struct vfio_pci_hot_reset *reset;
2786     int32_t *fds;
2787     int ret, i, count;
2788     bool multi = false;
2789 
2790     trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
2791 
2792     vfio_pci_pre_reset(vdev);
2793     vdev->vbasedev.needs_reset = false;
2794 
2795     info = g_malloc0(sizeof(*info));
2796     info->argsz = sizeof(*info);
2797 
2798     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
2799     if (ret && errno != ENOSPC) {
2800         ret = -errno;
2801         if (!vdev->has_pm_reset) {
2802             error_report("vfio: Cannot reset device %04x:%02x:%02x.%x, "
2803                          "no available reset mechanism.", vdev->host.domain,
2804                          vdev->host.bus, vdev->host.slot, vdev->host.function);
2805         }
2806         goto out_single;
2807     }
2808 
2809     count = info->count;
2810     info = g_realloc(info, sizeof(*info) + (count * sizeof(*devices)));
2811     info->argsz = sizeof(*info) + (count * sizeof(*devices));
2812     devices = &info->devices[0];
2813 
2814     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
2815     if (ret) {
2816         ret = -errno;
2817         error_report("vfio: hot reset info failed: %m");
2818         goto out_single;
2819     }
2820 
2821     trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
2822 
2823     /* Verify that we have all the groups required */
2824     for (i = 0; i < info->count; i++) {
2825         PCIHostDeviceAddress host;
2826         VFIOPCIDevice *tmp;
2827         VFIODevice *vbasedev_iter;
2828 
2829         host.domain = devices[i].segment;
2830         host.bus = devices[i].bus;
2831         host.slot = PCI_SLOT(devices[i].devfn);
2832         host.function = PCI_FUNC(devices[i].devfn);
2833 
2834         trace_vfio_pci_hot_reset_dep_devices(host.domain,
2835                 host.bus, host.slot, host.function, devices[i].group_id);
2836 
2837         if (vfio_pci_host_match(&host, &vdev->host)) {
2838             continue;
2839         }
2840 
2841         QLIST_FOREACH(group, &vfio_group_list, next) {
2842             if (group->groupid == devices[i].group_id) {
2843                 break;
2844             }
2845         }
2846 
2847         if (!group) {
2848             if (!vdev->has_pm_reset) {
2849                 error_report("vfio: Cannot reset device %s, "
2850                              "depends on group %d which is not owned.",
2851                              vdev->vbasedev.name, devices[i].group_id);
2852             }
2853             ret = -EPERM;
2854             goto out;
2855         }
2856 
2857         /* Prep dependent devices for reset and clear our marker. */
2858         QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2859             if (vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
2860                 continue;
2861             }
2862             tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
2863             if (vfio_pci_host_match(&host, &tmp->host)) {
2864                 if (single) {
2865                     ret = -EINVAL;
2866                     goto out_single;
2867                 }
2868                 vfio_pci_pre_reset(tmp);
2869                 tmp->vbasedev.needs_reset = false;
2870                 multi = true;
2871                 break;
2872             }
2873         }
2874     }
2875 
2876     if (!single && !multi) {
2877         ret = -EINVAL;
2878         goto out_single;
2879     }
2880 
2881     /* Determine how many group fds need to be passed */
2882     count = 0;
2883     QLIST_FOREACH(group, &vfio_group_list, next) {
2884         for (i = 0; i < info->count; i++) {
2885             if (group->groupid == devices[i].group_id) {
2886                 count++;
2887                 break;
2888             }
2889         }
2890     }
2891 
2892     reset = g_malloc0(sizeof(*reset) + (count * sizeof(*fds)));
2893     reset->argsz = sizeof(*reset) + (count * sizeof(*fds));
2894     fds = &reset->group_fds[0];
2895 
2896     /* Fill in group fds */
2897     QLIST_FOREACH(group, &vfio_group_list, next) {
2898         for (i = 0; i < info->count; i++) {
2899             if (group->groupid == devices[i].group_id) {
2900                 fds[reset->count++] = group->fd;
2901                 break;
2902             }
2903         }
2904     }
2905 
2906     /* Bus reset! */
2907     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
2908     g_free(reset);
2909 
2910     trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
2911                                     ret ? "%m" : "Success");
2912 
2913 out:
2914     /* Re-enable INTx on affected devices */
2915     for (i = 0; i < info->count; i++) {
2916         PCIHostDeviceAddress host;
2917         VFIOPCIDevice *tmp;
2918         VFIODevice *vbasedev_iter;
2919 
2920         host.domain = devices[i].segment;
2921         host.bus = devices[i].bus;
2922         host.slot = PCI_SLOT(devices[i].devfn);
2923         host.function = PCI_FUNC(devices[i].devfn);
2924 
2925         if (vfio_pci_host_match(&host, &vdev->host)) {
2926             continue;
2927         }
2928 
2929         QLIST_FOREACH(group, &vfio_group_list, next) {
2930             if (group->groupid == devices[i].group_id) {
2931                 break;
2932             }
2933         }
2934 
2935         if (!group) {
2936             break;
2937         }
2938 
2939         QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2940             if (vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
2941                 continue;
2942             }
2943             tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
2944             if (vfio_pci_host_match(&host, &tmp->host)) {
2945                 vfio_pci_post_reset(tmp);
2946                 break;
2947             }
2948         }
2949     }
2950 out_single:
2951     vfio_pci_post_reset(vdev);
2952     g_free(info);
2953 
2954     return ret;
2955 }
2956 
2957 /*
2958  * We want to differentiate hot reset of mulitple in-use devices vs hot reset
2959  * of a single in-use device.  VFIO_DEVICE_RESET will already handle the case
2960  * of doing hot resets when there is only a single device per bus.  The in-use
2961  * here refers to how many VFIODevices are affected.  A hot reset that affects
2962  * multiple devices, but only a single in-use device, means that we can call
2963  * it from our bus ->reset() callback since the extent is effectively a single
2964  * device.  This allows us to make use of it in the hotplug path.  When there
2965  * are multiple in-use devices, we can only trigger the hot reset during a
2966  * system reset and thus from our reset handler.  We separate _one vs _multi
2967  * here so that we don't overlap and do a double reset on the system reset
2968  * path where both our reset handler and ->reset() callback are used.  Calling
2969  * _one() will only do a hot reset for the one in-use devices case, calling
2970  * _multi() will do nothing if a _one() would have been sufficient.
2971  */
2972 static int vfio_pci_hot_reset_one(VFIOPCIDevice *vdev)
2973 {
2974     return vfio_pci_hot_reset(vdev, true);
2975 }
2976 
2977 static int vfio_pci_hot_reset_multi(VFIODevice *vbasedev)
2978 {
2979     VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2980     return vfio_pci_hot_reset(vdev, false);
2981 }
2982 
2983 static void vfio_pci_compute_needs_reset(VFIODevice *vbasedev)
2984 {
2985     VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2986     if (!vbasedev->reset_works || (!vdev->has_flr && vdev->has_pm_reset)) {
2987         vbasedev->needs_reset = true;
2988     }
2989 }
2990 
2991 static VFIODeviceOps vfio_pci_ops = {
2992     .vfio_compute_needs_reset = vfio_pci_compute_needs_reset,
2993     .vfio_hot_reset_multi = vfio_pci_hot_reset_multi,
2994     .vfio_eoi = vfio_eoi,
2995 };
2996 
2997 static int vfio_populate_device(VFIOPCIDevice *vdev)
2998 {
2999     VFIODevice *vbasedev = &vdev->vbasedev;
3000     struct vfio_region_info reg_info = { .argsz = sizeof(reg_info) };
3001     struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };
3002     int i, ret = -1;
3003 
3004     /* Sanity check device */
3005     if (!(vbasedev->flags & VFIO_DEVICE_FLAGS_PCI)) {
3006         error_report("vfio: Um, this isn't a PCI device");
3007         goto error;
3008     }
3009 
3010     if (vbasedev->num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) {
3011         error_report("vfio: unexpected number of io regions %u",
3012                      vbasedev->num_regions);
3013         goto error;
3014     }
3015 
3016     if (vbasedev->num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) {
3017         error_report("vfio: unexpected number of irqs %u", vbasedev->num_irqs);
3018         goto error;
3019     }
3020 
3021     for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
3022         reg_info.index = i;
3023 
3024         ret = ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
3025         if (ret) {
3026             error_report("vfio: Error getting region %d info: %m", i);
3027             goto error;
3028         }
3029 
3030         trace_vfio_populate_device_region(vbasedev->name, i,
3031                                           (unsigned long)reg_info.size,
3032                                           (unsigned long)reg_info.offset,
3033                                           (unsigned long)reg_info.flags);
3034 
3035         vdev->bars[i].region.vbasedev = vbasedev;
3036         vdev->bars[i].region.flags = reg_info.flags;
3037         vdev->bars[i].region.size = reg_info.size;
3038         vdev->bars[i].region.fd_offset = reg_info.offset;
3039         vdev->bars[i].region.nr = i;
3040         QLIST_INIT(&vdev->bars[i].quirks);
3041     }
3042 
3043     reg_info.index = VFIO_PCI_CONFIG_REGION_INDEX;
3044 
3045     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
3046     if (ret) {
3047         error_report("vfio: Error getting config info: %m");
3048         goto error;
3049     }
3050 
3051     trace_vfio_populate_device_config(vdev->vbasedev.name,
3052                                       (unsigned long)reg_info.size,
3053                                       (unsigned long)reg_info.offset,
3054                                       (unsigned long)reg_info.flags);
3055 
3056     vdev->config_size = reg_info.size;
3057     if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) {
3058         vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS;
3059     }
3060     vdev->config_offset = reg_info.offset;
3061 
3062     if ((vdev->features & VFIO_FEATURE_ENABLE_VGA) &&
3063         vbasedev->num_regions > VFIO_PCI_VGA_REGION_INDEX) {
3064         struct vfio_region_info vga_info = {
3065             .argsz = sizeof(vga_info),
3066             .index = VFIO_PCI_VGA_REGION_INDEX,
3067          };
3068 
3069         ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &vga_info);
3070         if (ret) {
3071             error_report(
3072                 "vfio: Device does not support requested feature x-vga");
3073             goto error;
3074         }
3075 
3076         if (!(vga_info.flags & VFIO_REGION_INFO_FLAG_READ) ||
3077             !(vga_info.flags & VFIO_REGION_INFO_FLAG_WRITE) ||
3078             vga_info.size < 0xbffff + 1) {
3079             error_report("vfio: Unexpected VGA info, flags 0x%lx, size 0x%lx",
3080                          (unsigned long)vga_info.flags,
3081                          (unsigned long)vga_info.size);
3082             goto error;
3083         }
3084 
3085         vdev->vga.fd_offset = vga_info.offset;
3086         vdev->vga.fd = vdev->vbasedev.fd;
3087 
3088         vdev->vga.region[QEMU_PCI_VGA_MEM].offset = QEMU_PCI_VGA_MEM_BASE;
3089         vdev->vga.region[QEMU_PCI_VGA_MEM].nr = QEMU_PCI_VGA_MEM;
3090         QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_MEM].quirks);
3091 
3092         vdev->vga.region[QEMU_PCI_VGA_IO_LO].offset = QEMU_PCI_VGA_IO_LO_BASE;
3093         vdev->vga.region[QEMU_PCI_VGA_IO_LO].nr = QEMU_PCI_VGA_IO_LO;
3094         QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_IO_LO].quirks);
3095 
3096         vdev->vga.region[QEMU_PCI_VGA_IO_HI].offset = QEMU_PCI_VGA_IO_HI_BASE;
3097         vdev->vga.region[QEMU_PCI_VGA_IO_HI].nr = QEMU_PCI_VGA_IO_HI;
3098         QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].quirks);
3099 
3100         vdev->has_vga = true;
3101     }
3102 
3103     irq_info.index = VFIO_PCI_ERR_IRQ_INDEX;
3104 
3105     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);
3106     if (ret) {
3107         /* This can fail for an old kernel or legacy PCI dev */
3108         trace_vfio_populate_device_get_irq_info_failure();
3109         ret = 0;
3110     } else if (irq_info.count == 1) {
3111         vdev->pci_aer = true;
3112     } else {
3113         error_report("vfio: %s "
3114                      "Could not enable error recovery for the device",
3115                      vbasedev->name);
3116     }
3117 
3118 error:
3119     return ret;
3120 }
3121 
3122 static void vfio_put_device(VFIOPCIDevice *vdev)
3123 {
3124     g_free(vdev->vbasedev.name);
3125     if (vdev->msix) {
3126         object_unparent(OBJECT(&vdev->msix->mmap_mem));
3127         g_free(vdev->msix);
3128         vdev->msix = NULL;
3129     }
3130     vfio_put_base_device(&vdev->vbasedev);
3131 }
3132 
3133 static void vfio_err_notifier_handler(void *opaque)
3134 {
3135     VFIOPCIDevice *vdev = opaque;
3136 
3137     if (!event_notifier_test_and_clear(&vdev->err_notifier)) {
3138         return;
3139     }
3140 
3141     /*
3142      * TBD. Retrieve the error details and decide what action
3143      * needs to be taken. One of the actions could be to pass
3144      * the error to the guest and have the guest driver recover
3145      * from the error. This requires that PCIe capabilities be
3146      * exposed to the guest. For now, we just terminate the
3147      * guest to contain the error.
3148      */
3149 
3150     error_report("%s(%04x:%02x:%02x.%x) Unrecoverable error detected.  "
3151                  "Please collect any data possible and then kill the guest",
3152                  __func__, vdev->host.domain, vdev->host.bus,
3153                  vdev->host.slot, vdev->host.function);
3154 
3155     vm_stop(RUN_STATE_INTERNAL_ERROR);
3156 }
3157 
3158 /*
3159  * Registers error notifier for devices supporting error recovery.
3160  * If we encounter a failure in this function, we report an error
3161  * and continue after disabling error recovery support for the
3162  * device.
3163  */
3164 static void vfio_register_err_notifier(VFIOPCIDevice *vdev)
3165 {
3166     int ret;
3167     int argsz;
3168     struct vfio_irq_set *irq_set;
3169     int32_t *pfd;
3170 
3171     if (!vdev->pci_aer) {
3172         return;
3173     }
3174 
3175     if (event_notifier_init(&vdev->err_notifier, 0)) {
3176         error_report("vfio: Unable to init event notifier for error detection");
3177         vdev->pci_aer = false;
3178         return;
3179     }
3180 
3181     argsz = sizeof(*irq_set) + sizeof(*pfd);
3182 
3183     irq_set = g_malloc0(argsz);
3184     irq_set->argsz = argsz;
3185     irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
3186                      VFIO_IRQ_SET_ACTION_TRIGGER;
3187     irq_set->index = VFIO_PCI_ERR_IRQ_INDEX;
3188     irq_set->start = 0;
3189     irq_set->count = 1;
3190     pfd = (int32_t *)&irq_set->data;
3191 
3192     *pfd = event_notifier_get_fd(&vdev->err_notifier);
3193     qemu_set_fd_handler(*pfd, vfio_err_notifier_handler, NULL, vdev);
3194 
3195     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
3196     if (ret) {
3197         error_report("vfio: Failed to set up error notification");
3198         qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
3199         event_notifier_cleanup(&vdev->err_notifier);
3200         vdev->pci_aer = false;
3201     }
3202     g_free(irq_set);
3203 }
3204 
3205 static void vfio_unregister_err_notifier(VFIOPCIDevice *vdev)
3206 {
3207     int argsz;
3208     struct vfio_irq_set *irq_set;
3209     int32_t *pfd;
3210     int ret;
3211 
3212     if (!vdev->pci_aer) {
3213         return;
3214     }
3215 
3216     argsz = sizeof(*irq_set) + sizeof(*pfd);
3217 
3218     irq_set = g_malloc0(argsz);
3219     irq_set->argsz = argsz;
3220     irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
3221                      VFIO_IRQ_SET_ACTION_TRIGGER;
3222     irq_set->index = VFIO_PCI_ERR_IRQ_INDEX;
3223     irq_set->start = 0;
3224     irq_set->count = 1;
3225     pfd = (int32_t *)&irq_set->data;
3226     *pfd = -1;
3227 
3228     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
3229     if (ret) {
3230         error_report("vfio: Failed to de-assign error fd: %m");
3231     }
3232     g_free(irq_set);
3233     qemu_set_fd_handler(event_notifier_get_fd(&vdev->err_notifier),
3234                         NULL, NULL, vdev);
3235     event_notifier_cleanup(&vdev->err_notifier);
3236 }
3237 
3238 static void vfio_req_notifier_handler(void *opaque)
3239 {
3240     VFIOPCIDevice *vdev = opaque;
3241 
3242     if (!event_notifier_test_and_clear(&vdev->req_notifier)) {
3243         return;
3244     }
3245 
3246     qdev_unplug(&vdev->pdev.qdev, NULL);
3247 }
3248 
3249 static void vfio_register_req_notifier(VFIOPCIDevice *vdev)
3250 {
3251     struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info),
3252                                       .index = VFIO_PCI_REQ_IRQ_INDEX };
3253     int argsz;
3254     struct vfio_irq_set *irq_set;
3255     int32_t *pfd;
3256 
3257     if (!(vdev->features & VFIO_FEATURE_ENABLE_REQ)) {
3258         return;
3259     }
3260 
3261     if (ioctl(vdev->vbasedev.fd,
3262               VFIO_DEVICE_GET_IRQ_INFO, &irq_info) < 0 || irq_info.count < 1) {
3263         return;
3264     }
3265 
3266     if (event_notifier_init(&vdev->req_notifier, 0)) {
3267         error_report("vfio: Unable to init event notifier for device request");
3268         return;
3269     }
3270 
3271     argsz = sizeof(*irq_set) + sizeof(*pfd);
3272 
3273     irq_set = g_malloc0(argsz);
3274     irq_set->argsz = argsz;
3275     irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
3276                      VFIO_IRQ_SET_ACTION_TRIGGER;
3277     irq_set->index = VFIO_PCI_REQ_IRQ_INDEX;
3278     irq_set->start = 0;
3279     irq_set->count = 1;
3280     pfd = (int32_t *)&irq_set->data;
3281 
3282     *pfd = event_notifier_get_fd(&vdev->req_notifier);
3283     qemu_set_fd_handler(*pfd, vfio_req_notifier_handler, NULL, vdev);
3284 
3285     if (ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set)) {
3286         error_report("vfio: Failed to set up device request notification");
3287         qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
3288         event_notifier_cleanup(&vdev->req_notifier);
3289     } else {
3290         vdev->req_enabled = true;
3291     }
3292 
3293     g_free(irq_set);
3294 }
3295 
3296 static void vfio_unregister_req_notifier(VFIOPCIDevice *vdev)
3297 {
3298     int argsz;
3299     struct vfio_irq_set *irq_set;
3300     int32_t *pfd;
3301 
3302     if (!vdev->req_enabled) {
3303         return;
3304     }
3305 
3306     argsz = sizeof(*irq_set) + sizeof(*pfd);
3307 
3308     irq_set = g_malloc0(argsz);
3309     irq_set->argsz = argsz;
3310     irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
3311                      VFIO_IRQ_SET_ACTION_TRIGGER;
3312     irq_set->index = VFIO_PCI_REQ_IRQ_INDEX;
3313     irq_set->start = 0;
3314     irq_set->count = 1;
3315     pfd = (int32_t *)&irq_set->data;
3316     *pfd = -1;
3317 
3318     if (ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set)) {
3319         error_report("vfio: Failed to de-assign device request fd: %m");
3320     }
3321     g_free(irq_set);
3322     qemu_set_fd_handler(event_notifier_get_fd(&vdev->req_notifier),
3323                         NULL, NULL, vdev);
3324     event_notifier_cleanup(&vdev->req_notifier);
3325 
3326     vdev->req_enabled = false;
3327 }
3328 
3329 /*
3330  * AMD Radeon PCI config reset, based on Linux:
3331  *   drivers/gpu/drm/radeon/ci_smc.c:ci_is_smc_running()
3332  *   drivers/gpu/drm/radeon/radeon_device.c:radeon_pci_config_reset
3333  *   drivers/gpu/drm/radeon/ci_smc.c:ci_reset_smc()
3334  *   drivers/gpu/drm/radeon/ci_smc.c:ci_stop_smc_clock()
3335  * IDs: include/drm/drm_pciids.h
3336  * Registers: http://cgit.freedesktop.org/~agd5f/linux/commit/?id=4e2aa447f6f0
3337  *
3338  * Bonaire and Hawaii GPUs do not respond to a bus reset.  This is a bug in the
3339  * hardware that should be fixed on future ASICs.  The symptom of this is that
3340  * once the accerlated driver loads, Windows guests will bsod on subsequent
3341  * attmpts to load the driver, such as after VM reset or shutdown/restart.  To
3342  * work around this, we do an AMD specific PCI config reset, followed by an SMC
3343  * reset.  The PCI config reset only works if SMC firmware is running, so we
3344  * have a dependency on the state of the device as to whether this reset will
3345  * be effective.  There are still cases where we won't be able to kick the
3346  * device into working, but this greatly improves the usability overall.  The
3347  * config reset magic is relatively common on AMD GPUs, but the setup and SMC
3348  * poking is largely ASIC specific.
3349  */
3350 static bool vfio_radeon_smc_is_running(VFIOPCIDevice *vdev)
3351 {
3352     uint32_t clk, pc_c;
3353 
3354     /*
3355      * Registers 200h and 204h are index and data registers for acessing
3356      * indirect configuration registers within the device.
3357      */
3358     vfio_region_write(&vdev->bars[5].region, 0x200, 0x80000004, 4);
3359     clk = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
3360     vfio_region_write(&vdev->bars[5].region, 0x200, 0x80000370, 4);
3361     pc_c = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
3362 
3363     return (!(clk & 1) && (0x20100 <= pc_c));
3364 }
3365 
3366 /*
3367  * The scope of a config reset is controlled by a mode bit in the misc register
3368  * and a fuse, exposed as a bit in another register.  The fuse is the default
3369  * (0 = GFX, 1 = whole GPU), the misc bit is a toggle, with the forumula
3370  * scope = !(misc ^ fuse), where the resulting scope is defined the same as
3371  * the fuse.  A truth table therefore tells us that if misc == fuse, we need
3372  * to flip the value of the bit in the misc register.
3373  */
3374 static void vfio_radeon_set_gfx_only_reset(VFIOPCIDevice *vdev)
3375 {
3376     uint32_t misc, fuse;
3377     bool a, b;
3378 
3379     vfio_region_write(&vdev->bars[5].region, 0x200, 0xc00c0000, 4);
3380     fuse = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
3381     b = fuse & 64;
3382 
3383     vfio_region_write(&vdev->bars[5].region, 0x200, 0xc0000010, 4);
3384     misc = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
3385     a = misc & 2;
3386 
3387     if (a == b) {
3388         vfio_region_write(&vdev->bars[5].region, 0x204, misc ^ 2, 4);
3389         vfio_region_read(&vdev->bars[5].region, 0x204, 4); /* flush */
3390     }
3391 }
3392 
3393 static int vfio_radeon_reset(VFIOPCIDevice *vdev)
3394 {
3395     PCIDevice *pdev = &vdev->pdev;
3396     int i, ret = 0;
3397     uint32_t data;
3398 
3399     /* Defer to a kernel implemented reset */
3400     if (vdev->vbasedev.reset_works) {
3401         return -ENODEV;
3402     }
3403 
3404     /* Enable only memory BAR access */
3405     vfio_pci_write_config(pdev, PCI_COMMAND, PCI_COMMAND_MEMORY, 2);
3406 
3407     /* Reset only works if SMC firmware is loaded and running */
3408     if (!vfio_radeon_smc_is_running(vdev)) {
3409         ret = -EINVAL;
3410         goto out;
3411     }
3412 
3413     /* Make sure only the GFX function is reset */
3414     vfio_radeon_set_gfx_only_reset(vdev);
3415 
3416     /* AMD PCI config reset */
3417     vfio_pci_write_config(pdev, 0x7c, 0x39d5e86b, 4);
3418     usleep(100);
3419 
3420     /* Read back the memory size to make sure we're out of reset */
3421     for (i = 0; i < 100000; i++) {
3422         if (vfio_region_read(&vdev->bars[5].region, 0x5428, 4) != 0xffffffff) {
3423             break;
3424         }
3425         usleep(1);
3426     }
3427 
3428     /* Reset SMC */
3429     vfio_region_write(&vdev->bars[5].region, 0x200, 0x80000000, 4);
3430     data = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
3431     data |= 1;
3432     vfio_region_write(&vdev->bars[5].region, 0x204, data, 4);
3433 
3434     /* Disable SMC clock */
3435     vfio_region_write(&vdev->bars[5].region, 0x200, 0x80000004, 4);
3436     data = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
3437     data |= 1;
3438     vfio_region_write(&vdev->bars[5].region, 0x204, data, 4);
3439 
3440 out:
3441     /* Restore PCI command register */
3442     vfio_pci_write_config(pdev, PCI_COMMAND, 0, 2);
3443 
3444     return ret;
3445 }
3446 
3447 static void vfio_setup_resetfn(VFIOPCIDevice *vdev)
3448 {
3449     PCIDevice *pdev = &vdev->pdev;
3450     uint16_t vendor, device;
3451 
3452     vendor = pci_get_word(pdev->config + PCI_VENDOR_ID);
3453     device = pci_get_word(pdev->config + PCI_DEVICE_ID);
3454 
3455     switch (vendor) {
3456     case 0x1002:
3457         switch (device) {
3458         /* Bonaire */
3459         case 0x6649: /* Bonaire [FirePro W5100] */
3460         case 0x6650:
3461         case 0x6651:
3462         case 0x6658: /* Bonaire XTX [Radeon R7 260X] */
3463         case 0x665c: /* Bonaire XT [Radeon HD 7790/8770 / R9 260 OEM] */
3464         case 0x665d: /* Bonaire [Radeon R7 200 Series] */
3465         /* Hawaii */
3466         case 0x67A0: /* Hawaii XT GL [FirePro W9100] */
3467         case 0x67A1: /* Hawaii PRO GL [FirePro W8100] */
3468         case 0x67A2:
3469         case 0x67A8:
3470         case 0x67A9:
3471         case 0x67AA:
3472         case 0x67B0: /* Hawaii XT [Radeon R9 290X] */
3473         case 0x67B1: /* Hawaii PRO [Radeon R9 290] */
3474         case 0x67B8:
3475         case 0x67B9:
3476         case 0x67BA:
3477         case 0x67BE:
3478             vdev->resetfn = vfio_radeon_reset;
3479             break;
3480         }
3481         break;
3482     }
3483 }
3484 
3485 static int vfio_initfn(PCIDevice *pdev)
3486 {
3487     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
3488     VFIODevice *vbasedev_iter;
3489     VFIOGroup *group;
3490     char path[PATH_MAX], iommu_group_path[PATH_MAX], *group_name;
3491     ssize_t len;
3492     struct stat st;
3493     int groupid;
3494     int ret;
3495 
3496     /* Check that the host device exists */
3497     snprintf(path, sizeof(path),
3498              "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/",
3499              vdev->host.domain, vdev->host.bus, vdev->host.slot,
3500              vdev->host.function);
3501     if (stat(path, &st) < 0) {
3502         error_report("vfio: error: no such host device: %s", path);
3503         return -errno;
3504     }
3505 
3506     vdev->vbasedev.ops = &vfio_pci_ops;
3507 
3508     vdev->vbasedev.type = VFIO_DEVICE_TYPE_PCI;
3509     vdev->vbasedev.name = g_strdup_printf("%04x:%02x:%02x.%01x",
3510                                           vdev->host.domain, vdev->host.bus,
3511                                           vdev->host.slot, vdev->host.function);
3512 
3513     strncat(path, "iommu_group", sizeof(path) - strlen(path) - 1);
3514 
3515     len = readlink(path, iommu_group_path, sizeof(path));
3516     if (len <= 0 || len >= sizeof(path)) {
3517         error_report("vfio: error no iommu_group for device");
3518         return len < 0 ? -errno : -ENAMETOOLONG;
3519     }
3520 
3521     iommu_group_path[len] = 0;
3522     group_name = basename(iommu_group_path);
3523 
3524     if (sscanf(group_name, "%d", &groupid) != 1) {
3525         error_report("vfio: error reading %s: %m", path);
3526         return -errno;
3527     }
3528 
3529     trace_vfio_initfn(vdev->vbasedev.name, groupid);
3530 
3531     group = vfio_get_group(groupid, pci_device_iommu_address_space(pdev));
3532     if (!group) {
3533         error_report("vfio: failed to get group %d", groupid);
3534         return -ENOENT;
3535     }
3536 
3537     snprintf(path, sizeof(path), "%04x:%02x:%02x.%01x",
3538             vdev->host.domain, vdev->host.bus, vdev->host.slot,
3539             vdev->host.function);
3540 
3541     QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
3542         if (strcmp(vbasedev_iter->name, vdev->vbasedev.name) == 0) {
3543             error_report("vfio: error: device %s is already attached", path);
3544             vfio_put_group(group);
3545             return -EBUSY;
3546         }
3547     }
3548 
3549     ret = vfio_get_device(group, path, &vdev->vbasedev);
3550     if (ret) {
3551         error_report("vfio: failed to get device %s", path);
3552         vfio_put_group(group);
3553         return ret;
3554     }
3555 
3556     ret = vfio_populate_device(vdev);
3557     if (ret) {
3558         return ret;
3559     }
3560 
3561     /* Get a copy of config space */
3562     ret = pread(vdev->vbasedev.fd, vdev->pdev.config,
3563                 MIN(pci_config_size(&vdev->pdev), vdev->config_size),
3564                 vdev->config_offset);
3565     if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
3566         ret = ret < 0 ? -errno : -EFAULT;
3567         error_report("vfio: Failed to read device config space");
3568         return ret;
3569     }
3570 
3571     /* vfio emulates a lot for us, but some bits need extra love */
3572     vdev->emulated_config_bits = g_malloc0(vdev->config_size);
3573 
3574     /* QEMU can choose to expose the ROM or not */
3575     memset(vdev->emulated_config_bits + PCI_ROM_ADDRESS, 0xff, 4);
3576 
3577     /* QEMU can change multi-function devices to single function, or reverse */
3578     vdev->emulated_config_bits[PCI_HEADER_TYPE] =
3579                                               PCI_HEADER_TYPE_MULTI_FUNCTION;
3580 
3581     /* Restore or clear multifunction, this is always controlled by QEMU */
3582     if (vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
3583         vdev->pdev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
3584     } else {
3585         vdev->pdev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
3586     }
3587 
3588     /*
3589      * Clear host resource mapping info.  If we choose not to register a
3590      * BAR, such as might be the case with the option ROM, we can get
3591      * confusing, unwritable, residual addresses from the host here.
3592      */
3593     memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
3594     memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
3595 
3596     vfio_pci_size_rom(vdev);
3597 
3598     ret = vfio_early_setup_msix(vdev);
3599     if (ret) {
3600         return ret;
3601     }
3602 
3603     vfio_map_bars(vdev);
3604 
3605     ret = vfio_add_capabilities(vdev);
3606     if (ret) {
3607         goto out_teardown;
3608     }
3609 
3610     /* QEMU emulates all of MSI & MSIX */
3611     if (pdev->cap_present & QEMU_PCI_CAP_MSIX) {
3612         memset(vdev->emulated_config_bits + pdev->msix_cap, 0xff,
3613                MSIX_CAP_LENGTH);
3614     }
3615 
3616     if (pdev->cap_present & QEMU_PCI_CAP_MSI) {
3617         memset(vdev->emulated_config_bits + pdev->msi_cap, 0xff,
3618                vdev->msi_cap_size);
3619     }
3620 
3621     if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
3622         vdev->intx.mmap_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
3623                                                   vfio_intx_mmap_enable, vdev);
3624         pci_device_set_intx_routing_notifier(&vdev->pdev, vfio_update_irq);
3625         ret = vfio_enable_intx(vdev);
3626         if (ret) {
3627             goto out_teardown;
3628         }
3629     }
3630 
3631     vfio_register_err_notifier(vdev);
3632     vfio_register_req_notifier(vdev);
3633     vfio_setup_resetfn(vdev);
3634 
3635     return 0;
3636 
3637 out_teardown:
3638     pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3639     vfio_teardown_msi(vdev);
3640     vfio_unregister_bars(vdev);
3641     return ret;
3642 }
3643 
3644 static void vfio_instance_finalize(Object *obj)
3645 {
3646     PCIDevice *pci_dev = PCI_DEVICE(obj);
3647     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pci_dev);
3648     VFIOGroup *group = vdev->vbasedev.group;
3649 
3650     vfio_unmap_bars(vdev);
3651     g_free(vdev->emulated_config_bits);
3652     g_free(vdev->rom);
3653     vfio_put_device(vdev);
3654     vfio_put_group(group);
3655 }
3656 
3657 static void vfio_exitfn(PCIDevice *pdev)
3658 {
3659     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
3660 
3661     vfio_unregister_req_notifier(vdev);
3662     vfio_unregister_err_notifier(vdev);
3663     pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3664     vfio_disable_interrupts(vdev);
3665     if (vdev->intx.mmap_timer) {
3666         timer_free(vdev->intx.mmap_timer);
3667     }
3668     vfio_teardown_msi(vdev);
3669     vfio_unregister_bars(vdev);
3670 }
3671 
3672 static void vfio_pci_reset(DeviceState *dev)
3673 {
3674     PCIDevice *pdev = DO_UPCAST(PCIDevice, qdev, dev);
3675     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
3676 
3677     trace_vfio_pci_reset(vdev->vbasedev.name);
3678 
3679     vfio_pci_pre_reset(vdev);
3680 
3681     if (vdev->resetfn && !vdev->resetfn(vdev)) {
3682         goto post_reset;
3683     }
3684 
3685     if (vdev->vbasedev.reset_works &&
3686         (vdev->has_flr || !vdev->has_pm_reset) &&
3687         !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
3688         trace_vfio_pci_reset_flr(vdev->vbasedev.name);
3689         goto post_reset;
3690     }
3691 
3692     /* See if we can do our own bus reset */
3693     if (!vfio_pci_hot_reset_one(vdev)) {
3694         goto post_reset;
3695     }
3696 
3697     /* If nothing else works and the device supports PM reset, use it */
3698     if (vdev->vbasedev.reset_works && vdev->has_pm_reset &&
3699         !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
3700         trace_vfio_pci_reset_pm(vdev->vbasedev.name);
3701         goto post_reset;
3702     }
3703 
3704 post_reset:
3705     vfio_pci_post_reset(vdev);
3706 }
3707 
3708 static void vfio_instance_init(Object *obj)
3709 {
3710     PCIDevice *pci_dev = PCI_DEVICE(obj);
3711     VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, PCI_DEVICE(obj));
3712 
3713     device_add_bootindex_property(obj, &vdev->bootindex,
3714                                   "bootindex", NULL,
3715                                   &pci_dev->qdev, NULL);
3716 }
3717 
3718 static Property vfio_pci_dev_properties[] = {
3719     DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIOPCIDevice, host),
3720     DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIOPCIDevice,
3721                        intx.mmap_timeout, 1100),
3722     DEFINE_PROP_BIT("x-vga", VFIOPCIDevice, features,
3723                     VFIO_FEATURE_ENABLE_VGA_BIT, false),
3724     DEFINE_PROP_BIT("x-req", VFIOPCIDevice, features,
3725                     VFIO_FEATURE_ENABLE_REQ_BIT, true),
3726     DEFINE_PROP_INT32("bootindex", VFIOPCIDevice, bootindex, -1),
3727     DEFINE_PROP_BOOL("x-mmap", VFIOPCIDevice, vbasedev.allow_mmap, true),
3728     /*
3729      * TODO - support passed fds... is this necessary?
3730      * DEFINE_PROP_STRING("vfiofd", VFIOPCIDevice, vfiofd_name),
3731      * DEFINE_PROP_STRING("vfiogroupfd, VFIOPCIDevice, vfiogroupfd_name),
3732      */
3733     DEFINE_PROP_END_OF_LIST(),
3734 };
3735 
3736 static const VMStateDescription vfio_pci_vmstate = {
3737     .name = "vfio-pci",
3738     .unmigratable = 1,
3739 };
3740 
3741 static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
3742 {
3743     DeviceClass *dc = DEVICE_CLASS(klass);
3744     PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
3745 
3746     dc->reset = vfio_pci_reset;
3747     dc->props = vfio_pci_dev_properties;
3748     dc->vmsd = &vfio_pci_vmstate;
3749     dc->desc = "VFIO-based PCI device assignment";
3750     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
3751     pdc->init = vfio_initfn;
3752     pdc->exit = vfio_exitfn;
3753     pdc->config_read = vfio_pci_read_config;
3754     pdc->config_write = vfio_pci_write_config;
3755     pdc->is_express = 1; /* We might be */
3756 }
3757 
3758 static const TypeInfo vfio_pci_dev_info = {
3759     .name = "vfio-pci",
3760     .parent = TYPE_PCI_DEVICE,
3761     .instance_size = sizeof(VFIOPCIDevice),
3762     .class_init = vfio_pci_dev_class_init,
3763     .instance_init = vfio_instance_init,
3764     .instance_finalize = vfio_instance_finalize,
3765 };
3766 
3767 static void register_vfio_pci_dev_type(void)
3768 {
3769     type_register_static(&vfio_pci_dev_info);
3770 }
3771 
3772 type_init(register_vfio_pci_dev_type)
3773