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