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