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