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