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