]> git.proxmox.com Git - mirror_qemu.git/blame - hw/vfio/pci.c
vfio-pci: Allow mmap of MSIX BAR
[mirror_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 <alex.williamson@redhat.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 *
12 * Based on qemu-kvm device-assignment:
13 * Adapted for KVM by Qumranet.
14 * Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
15 * Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
16 * Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
17 * Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
18 * Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
19 */
20
c6eacb1a 21#include "qemu/osdep.h"
6dcfdbad 22#include <linux/vfio.h>
65501a74 23#include <sys/ioctl.h>
65501a74 24
83c9f4ca
PB
25#include "hw/pci/msi.h"
26#include "hw/pci/msix.h"
0282abf0 27#include "hw/pci/pci_bridge.h"
1de7afc9 28#include "qemu/error-report.h"
922a01a0 29#include "qemu/option.h"
1de7afc9 30#include "qemu/range.h"
6dcfdbad
AW
31#include "sysemu/kvm.h"
32#include "sysemu/sysemu.h"
78f33d2b 33#include "pci.h"
385f57cf 34#include "trace.h"
1108b2f8 35#include "qapi/error.h"
4b943029 36
65501a74
AW
37#define MSIX_CAP_LENGTH 12
38
9ee27d73 39static void vfio_disable_interrupts(VFIOPCIDevice *vdev);
9ee27d73 40static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled);
65501a74 41
ea486926
AW
42/*
43 * Disabling BAR mmaping can be slow, but toggling it around INTx can
44 * also be a huge overhead. We try to get the best of both worlds by
45 * waiting until an interrupt to disable mmaps (subsequent transitions
46 * to the same state are effectively no overhead). If the interrupt has
47 * been serviced and the time gap is long enough, we re-enable mmaps for
48 * performance. This works well for things like graphics cards, which
49 * may not use their interrupt at all and are penalized to an unusable
50 * level by read/write BAR traps. Other devices, like NICs, have more
51 * regular interrupts and see much better latency by staying in non-mmap
52 * mode. We therefore set the default mmap_timeout such that a ping
53 * is just enough to keep the mmap disabled. Users can experiment with
54 * other options with the x-intx-mmap-timeout-ms parameter (a value of
55 * zero disables the timer).
56 */
57static void vfio_intx_mmap_enable(void *opaque)
58{
9ee27d73 59 VFIOPCIDevice *vdev = opaque;
ea486926
AW
60
61 if (vdev->intx.pending) {
bc72ad67
AB
62 timer_mod(vdev->intx.mmap_timer,
63 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
ea486926
AW
64 return;
65 }
66
67 vfio_mmap_set_enabled(vdev, true);
68}
69
65501a74
AW
70static void vfio_intx_interrupt(void *opaque)
71{
9ee27d73 72 VFIOPCIDevice *vdev = opaque;
65501a74
AW
73
74 if (!event_notifier_test_and_clear(&vdev->intx.interrupt)) {
75 return;
76 }
77
df92ee44 78 trace_vfio_intx_interrupt(vdev->vbasedev.name, 'A' + vdev->intx.pin);
65501a74
AW
79
80 vdev->intx.pending = true;
68919cac 81 pci_irq_assert(&vdev->pdev);
ea486926
AW
82 vfio_mmap_set_enabled(vdev, false);
83 if (vdev->intx.mmap_timeout) {
bc72ad67
AB
84 timer_mod(vdev->intx.mmap_timer,
85 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
ea486926 86 }
65501a74
AW
87}
88
870cb6f1 89static void vfio_intx_eoi(VFIODevice *vbasedev)
65501a74 90{
a664477d
EA
91 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
92
65501a74
AW
93 if (!vdev->intx.pending) {
94 return;
95 }
96
870cb6f1 97 trace_vfio_intx_eoi(vbasedev->name);
65501a74
AW
98
99 vdev->intx.pending = false;
68919cac 100 pci_irq_deassert(&vdev->pdev);
a664477d 101 vfio_unmask_single_irqindex(vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
65501a74
AW
102}
103
7dfb3424 104static void vfio_intx_enable_kvm(VFIOPCIDevice *vdev, Error **errp)
e1d1e586
AW
105{
106#ifdef CONFIG_KVM
107 struct kvm_irqfd irqfd = {
108 .fd = event_notifier_get_fd(&vdev->intx.interrupt),
109 .gsi = vdev->intx.route.irq,
110 .flags = KVM_IRQFD_FLAG_RESAMPLE,
111 };
112 struct vfio_irq_set *irq_set;
113 int ret, argsz;
114 int32_t *pfd;
115
46746dba 116 if (vdev->no_kvm_intx || !kvm_irqfds_enabled() ||
e1d1e586 117 vdev->intx.route.mode != PCI_INTX_ENABLED ||
9fc0e2d8 118 !kvm_resamplefds_enabled()) {
e1d1e586
AW
119 return;
120 }
121
122 /* Get to a known interrupt state */
123 qemu_set_fd_handler(irqfd.fd, NULL, NULL, vdev);
5546a621 124 vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
e1d1e586 125 vdev->intx.pending = false;
68919cac 126 pci_irq_deassert(&vdev->pdev);
e1d1e586
AW
127
128 /* Get an eventfd for resample/unmask */
129 if (event_notifier_init(&vdev->intx.unmask, 0)) {
7dfb3424 130 error_setg(errp, "event_notifier_init failed eoi");
e1d1e586
AW
131 goto fail;
132 }
133
134 /* KVM triggers it, VFIO listens for it */
135 irqfd.resamplefd = event_notifier_get_fd(&vdev->intx.unmask);
136
137 if (kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd)) {
7dfb3424 138 error_setg_errno(errp, errno, "failed to setup resample irqfd");
e1d1e586
AW
139 goto fail_irqfd;
140 }
141
142 argsz = sizeof(*irq_set) + sizeof(*pfd);
143
144 irq_set = g_malloc0(argsz);
145 irq_set->argsz = argsz;
146 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_UNMASK;
147 irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
148 irq_set->start = 0;
149 irq_set->count = 1;
150 pfd = (int32_t *)&irq_set->data;
151
152 *pfd = irqfd.resamplefd;
153
5546a621 154 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
e1d1e586
AW
155 g_free(irq_set);
156 if (ret) {
7dfb3424 157 error_setg_errno(errp, -ret, "failed to setup INTx unmask fd");
e1d1e586
AW
158 goto fail_vfio;
159 }
160
161 /* Let'em rip */
5546a621 162 vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
e1d1e586
AW
163
164 vdev->intx.kvm_accel = true;
165
870cb6f1 166 trace_vfio_intx_enable_kvm(vdev->vbasedev.name);
e1d1e586
AW
167
168 return;
169
170fail_vfio:
171 irqfd.flags = KVM_IRQFD_FLAG_DEASSIGN;
172 kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd);
173fail_irqfd:
174 event_notifier_cleanup(&vdev->intx.unmask);
175fail:
176 qemu_set_fd_handler(irqfd.fd, vfio_intx_interrupt, NULL, vdev);
5546a621 177 vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
e1d1e586
AW
178#endif
179}
180
870cb6f1 181static void vfio_intx_disable_kvm(VFIOPCIDevice *vdev)
e1d1e586
AW
182{
183#ifdef CONFIG_KVM
184 struct kvm_irqfd irqfd = {
185 .fd = event_notifier_get_fd(&vdev->intx.interrupt),
186 .gsi = vdev->intx.route.irq,
187 .flags = KVM_IRQFD_FLAG_DEASSIGN,
188 };
189
190 if (!vdev->intx.kvm_accel) {
191 return;
192 }
193
194 /*
195 * Get to a known state, hardware masked, QEMU ready to accept new
196 * interrupts, QEMU IRQ de-asserted.
197 */
5546a621 198 vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
e1d1e586 199 vdev->intx.pending = false;
68919cac 200 pci_irq_deassert(&vdev->pdev);
e1d1e586
AW
201
202 /* Tell KVM to stop listening for an INTx irqfd */
203 if (kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd)) {
312fd5f2 204 error_report("vfio: Error: Failed to disable INTx irqfd: %m");
e1d1e586
AW
205 }
206
207 /* We only need to close the eventfd for VFIO to cleanup the kernel side */
208 event_notifier_cleanup(&vdev->intx.unmask);
209
210 /* QEMU starts listening for interrupt events. */
211 qemu_set_fd_handler(irqfd.fd, vfio_intx_interrupt, NULL, vdev);
212
213 vdev->intx.kvm_accel = false;
214
215 /* If we've missed an event, let it re-fire through QEMU */
5546a621 216 vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
e1d1e586 217
870cb6f1 218 trace_vfio_intx_disable_kvm(vdev->vbasedev.name);
e1d1e586
AW
219#endif
220}
221
870cb6f1 222static void vfio_intx_update(PCIDevice *pdev)
e1d1e586 223{
9ee27d73 224 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
e1d1e586 225 PCIINTxRoute route;
7dfb3424 226 Error *err = NULL;
e1d1e586
AW
227
228 if (vdev->interrupt != VFIO_INT_INTx) {
229 return;
230 }
231
232 route = pci_device_route_intx_to_irq(&vdev->pdev, vdev->intx.pin);
233
234 if (!pci_intx_route_changed(&vdev->intx.route, &route)) {
235 return; /* Nothing changed */
236 }
237
870cb6f1
AW
238 trace_vfio_intx_update(vdev->vbasedev.name,
239 vdev->intx.route.irq, route.irq);
e1d1e586 240
870cb6f1 241 vfio_intx_disable_kvm(vdev);
e1d1e586
AW
242
243 vdev->intx.route = route;
244
245 if (route.mode != PCI_INTX_ENABLED) {
246 return;
247 }
248
7dfb3424
EA
249 vfio_intx_enable_kvm(vdev, &err);
250 if (err) {
251 error_reportf_err(err, WARN_PREFIX, vdev->vbasedev.name);
252 }
e1d1e586
AW
253
254 /* Re-enable the interrupt in cased we missed an EOI */
870cb6f1 255 vfio_intx_eoi(&vdev->vbasedev);
e1d1e586
AW
256}
257
7dfb3424 258static int vfio_intx_enable(VFIOPCIDevice *vdev, Error **errp)
65501a74 259{
65501a74 260 uint8_t pin = vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1);
96d2c2c5 261 int ret, argsz, retval = 0;
1a403133
AW
262 struct vfio_irq_set *irq_set;
263 int32_t *pfd;
7dfb3424 264 Error *err = NULL;
65501a74 265
ea486926 266 if (!pin) {
65501a74
AW
267 return 0;
268 }
269
270 vfio_disable_interrupts(vdev);
271
272 vdev->intx.pin = pin - 1; /* Pin A (1) -> irq[0] */
68919cac 273 pci_config_set_interrupt_pin(vdev->pdev.config, pin);
e1d1e586
AW
274
275#ifdef CONFIG_KVM
276 /*
277 * Only conditional to avoid generating error messages on platforms
278 * where we won't actually use the result anyway.
279 */
9fc0e2d8 280 if (kvm_irqfds_enabled() && kvm_resamplefds_enabled()) {
e1d1e586
AW
281 vdev->intx.route = pci_device_route_intx_to_irq(&vdev->pdev,
282 vdev->intx.pin);
283 }
284#endif
285
65501a74
AW
286 ret = event_notifier_init(&vdev->intx.interrupt, 0);
287 if (ret) {
7dfb3424 288 error_setg_errno(errp, -ret, "event_notifier_init failed");
65501a74
AW
289 return ret;
290 }
291
1a403133
AW
292 argsz = sizeof(*irq_set) + sizeof(*pfd);
293
294 irq_set = g_malloc0(argsz);
295 irq_set->argsz = argsz;
296 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
297 irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
298 irq_set->start = 0;
299 irq_set->count = 1;
300 pfd = (int32_t *)&irq_set->data;
301
302 *pfd = event_notifier_get_fd(&vdev->intx.interrupt);
303 qemu_set_fd_handler(*pfd, vfio_intx_interrupt, NULL, vdev);
65501a74 304
5546a621 305 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
1a403133 306 if (ret) {
7dfb3424 307 error_setg_errno(errp, -ret, "failed to setup INTx fd");
1a403133 308 qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
ce59af2d 309 event_notifier_cleanup(&vdev->intx.interrupt);
96d2c2c5
PMD
310 retval = -errno;
311 goto cleanup;
65501a74
AW
312 }
313
7dfb3424
EA
314 vfio_intx_enable_kvm(vdev, &err);
315 if (err) {
316 error_reportf_err(err, WARN_PREFIX, vdev->vbasedev.name);
317 }
e1d1e586 318
65501a74
AW
319 vdev->interrupt = VFIO_INT_INTx;
320
870cb6f1 321 trace_vfio_intx_enable(vdev->vbasedev.name);
65501a74 322
96d2c2c5
PMD
323cleanup:
324 g_free(irq_set);
325
326 return retval;
65501a74
AW
327}
328
870cb6f1 329static void vfio_intx_disable(VFIOPCIDevice *vdev)
65501a74
AW
330{
331 int fd;
332
bc72ad67 333 timer_del(vdev->intx.mmap_timer);
870cb6f1 334 vfio_intx_disable_kvm(vdev);
5546a621 335 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
65501a74 336 vdev->intx.pending = false;
68919cac 337 pci_irq_deassert(&vdev->pdev);
65501a74
AW
338 vfio_mmap_set_enabled(vdev, true);
339
340 fd = event_notifier_get_fd(&vdev->intx.interrupt);
341 qemu_set_fd_handler(fd, NULL, NULL, vdev);
342 event_notifier_cleanup(&vdev->intx.interrupt);
343
344 vdev->interrupt = VFIO_INT_NONE;
345
870cb6f1 346 trace_vfio_intx_disable(vdev->vbasedev.name);
65501a74
AW
347}
348
349/*
350 * MSI/X
351 */
352static void vfio_msi_interrupt(void *opaque)
353{
354 VFIOMSIVector *vector = opaque;
9ee27d73 355 VFIOPCIDevice *vdev = vector->vdev;
0de70dc7
AW
356 MSIMessage (*get_msg)(PCIDevice *dev, unsigned vector);
357 void (*notify)(PCIDevice *dev, unsigned vector);
358 MSIMessage msg;
65501a74
AW
359 int nr = vector - vdev->msi_vectors;
360
361 if (!event_notifier_test_and_clear(&vector->interrupt)) {
362 return;
363 }
364
b3ebc10c 365 if (vdev->interrupt == VFIO_INT_MSIX) {
0de70dc7
AW
366 get_msg = msix_get_message;
367 notify = msix_notify;
95239e16
AW
368
369 /* A masked vector firing needs to use the PBA, enable it */
370 if (msix_is_masked(&vdev->pdev, nr)) {
371 set_bit(nr, vdev->msix->pending);
372 memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, true);
373 trace_vfio_msix_pba_enable(vdev->vbasedev.name);
374 }
9035f8c0 375 } else if (vdev->interrupt == VFIO_INT_MSI) {
0de70dc7
AW
376 get_msg = msi_get_message;
377 notify = msi_notify;
b3ebc10c
AW
378 } else {
379 abort();
380 }
381
0de70dc7 382 msg = get_msg(&vdev->pdev, nr);
bc5baffa 383 trace_vfio_msi_interrupt(vdev->vbasedev.name, nr, msg.address, msg.data);
0de70dc7 384 notify(&vdev->pdev, nr);
65501a74
AW
385}
386
9ee27d73 387static int vfio_enable_vectors(VFIOPCIDevice *vdev, bool msix)
65501a74
AW
388{
389 struct vfio_irq_set *irq_set;
390 int ret = 0, i, argsz;
391 int32_t *fds;
392
393 argsz = sizeof(*irq_set) + (vdev->nr_vectors * sizeof(*fds));
394
395 irq_set = g_malloc0(argsz);
396 irq_set->argsz = argsz;
397 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
398 irq_set->index = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX;
399 irq_set->start = 0;
400 irq_set->count = vdev->nr_vectors;
401 fds = (int32_t *)&irq_set->data;
402
403 for (i = 0; i < vdev->nr_vectors; i++) {
c048be5c
AW
404 int fd = -1;
405
406 /*
407 * MSI vs MSI-X - The guest has direct access to MSI mask and pending
408 * bits, therefore we always use the KVM signaling path when setup.
409 * MSI-X mask and pending bits are emulated, so we want to use the
410 * KVM signaling path only when configured and unmasked.
411 */
412 if (vdev->msi_vectors[i].use) {
413 if (vdev->msi_vectors[i].virq < 0 ||
414 (msix && msix_is_masked(&vdev->pdev, i))) {
415 fd = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt);
416 } else {
417 fd = event_notifier_get_fd(&vdev->msi_vectors[i].kvm_interrupt);
418 }
65501a74 419 }
c048be5c
AW
420
421 fds[i] = fd;
65501a74
AW
422 }
423
5546a621 424 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
65501a74
AW
425
426 g_free(irq_set);
427
65501a74
AW
428 return ret;
429}
430
46746dba 431static void vfio_add_kvm_msi_virq(VFIOPCIDevice *vdev, VFIOMSIVector *vector,
d1f6af6a 432 int vector_n, bool msix)
f4d45d47
AW
433{
434 int virq;
435
d1f6af6a 436 if ((msix && vdev->no_kvm_msix) || (!msix && vdev->no_kvm_msi)) {
f4d45d47
AW
437 return;
438 }
439
440 if (event_notifier_init(&vector->kvm_interrupt, 0)) {
441 return;
442 }
443
d1f6af6a 444 virq = kvm_irqchip_add_msi_route(kvm_state, vector_n, &vdev->pdev);
f4d45d47
AW
445 if (virq < 0) {
446 event_notifier_cleanup(&vector->kvm_interrupt);
447 return;
448 }
449
1c9b71a7 450 if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt,
f4d45d47
AW
451 NULL, virq) < 0) {
452 kvm_irqchip_release_virq(kvm_state, virq);
453 event_notifier_cleanup(&vector->kvm_interrupt);
454 return;
455 }
456
f4d45d47
AW
457 vector->virq = virq;
458}
459
460static void vfio_remove_kvm_msi_virq(VFIOMSIVector *vector)
461{
1c9b71a7
EA
462 kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt,
463 vector->virq);
f4d45d47
AW
464 kvm_irqchip_release_virq(kvm_state, vector->virq);
465 vector->virq = -1;
466 event_notifier_cleanup(&vector->kvm_interrupt);
467}
468
dc9f06ca
PF
469static void vfio_update_kvm_msi_virq(VFIOMSIVector *vector, MSIMessage msg,
470 PCIDevice *pdev)
f4d45d47 471{
dc9f06ca 472 kvm_irqchip_update_msi_route(kvm_state, vector->virq, msg, pdev);
3f1fea0f 473 kvm_irqchip_commit_routes(kvm_state);
f4d45d47
AW
474}
475
b0223e29
AW
476static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr,
477 MSIMessage *msg, IOHandler *handler)
65501a74 478{
9ee27d73 479 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
65501a74
AW
480 VFIOMSIVector *vector;
481 int ret;
482
df92ee44 483 trace_vfio_msix_vector_do_use(vdev->vbasedev.name, nr);
65501a74 484
65501a74 485 vector = &vdev->msi_vectors[nr];
65501a74 486
f4d45d47
AW
487 if (!vector->use) {
488 vector->vdev = vdev;
489 vector->virq = -1;
490 if (event_notifier_init(&vector->interrupt, 0)) {
491 error_report("vfio: Error: event_notifier_init failed");
492 }
493 vector->use = true;
494 msix_vector_use(pdev, nr);
65501a74
AW
495 }
496
f4d45d47
AW
497 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
498 handler, NULL, vector);
499
65501a74
AW
500 /*
501 * Attempt to enable route through KVM irqchip,
502 * default to userspace handling if unavailable.
503 */
f4d45d47
AW
504 if (vector->virq >= 0) {
505 if (!msg) {
506 vfio_remove_kvm_msi_virq(vector);
507 } else {
dc9f06ca 508 vfio_update_kvm_msi_virq(vector, *msg, pdev);
65501a74 509 }
f4d45d47 510 } else {
6d17a018
DG
511 if (msg) {
512 vfio_add_kvm_msi_virq(vdev, vector, nr, true);
513 }
65501a74
AW
514 }
515
516 /*
517 * We don't want to have the host allocate all possible MSI vectors
518 * for a device if they're not in use, so we shutdown and incrementally
519 * increase them as needed.
520 */
521 if (vdev->nr_vectors < nr + 1) {
5546a621 522 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
65501a74
AW
523 vdev->nr_vectors = nr + 1;
524 ret = vfio_enable_vectors(vdev, true);
525 if (ret) {
312fd5f2 526 error_report("vfio: failed to enable vectors, %d", ret);
65501a74 527 }
65501a74 528 } else {
1a403133
AW
529 int argsz;
530 struct vfio_irq_set *irq_set;
531 int32_t *pfd;
532
533 argsz = sizeof(*irq_set) + sizeof(*pfd);
534
535 irq_set = g_malloc0(argsz);
536 irq_set->argsz = argsz;
537 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
538 VFIO_IRQ_SET_ACTION_TRIGGER;
539 irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
540 irq_set->start = nr;
541 irq_set->count = 1;
542 pfd = (int32_t *)&irq_set->data;
543
f4d45d47
AW
544 if (vector->virq >= 0) {
545 *pfd = event_notifier_get_fd(&vector->kvm_interrupt);
546 } else {
547 *pfd = event_notifier_get_fd(&vector->interrupt);
548 }
1a403133 549
5546a621 550 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
1a403133 551 g_free(irq_set);
65501a74 552 if (ret) {
312fd5f2 553 error_report("vfio: failed to modify vector, %d", ret);
65501a74 554 }
65501a74
AW
555 }
556
95239e16
AW
557 /* Disable PBA emulation when nothing more is pending. */
558 clear_bit(nr, vdev->msix->pending);
559 if (find_first_bit(vdev->msix->pending,
560 vdev->nr_vectors) == vdev->nr_vectors) {
561 memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, false);
562 trace_vfio_msix_pba_disable(vdev->vbasedev.name);
563 }
564
65501a74
AW
565 return 0;
566}
567
b0223e29
AW
568static int vfio_msix_vector_use(PCIDevice *pdev,
569 unsigned int nr, MSIMessage msg)
570{
571 return vfio_msix_vector_do_use(pdev, nr, &msg, vfio_msi_interrupt);
572}
573
65501a74
AW
574static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr)
575{
9ee27d73 576 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
65501a74 577 VFIOMSIVector *vector = &vdev->msi_vectors[nr];
65501a74 578
df92ee44 579 trace_vfio_msix_vector_release(vdev->vbasedev.name, nr);
65501a74
AW
580
581 /*
f4d45d47
AW
582 * There are still old guests that mask and unmask vectors on every
583 * interrupt. If we're using QEMU bypass with a KVM irqfd, leave all of
584 * the KVM setup in place, simply switch VFIO to use the non-bypass
585 * eventfd. We'll then fire the interrupt through QEMU and the MSI-X
586 * core will mask the interrupt and set pending bits, allowing it to
587 * be re-asserted on unmask. Nothing to do if already using QEMU mode.
65501a74 588 */
f4d45d47
AW
589 if (vector->virq >= 0) {
590 int argsz;
591 struct vfio_irq_set *irq_set;
592 int32_t *pfd;
1a403133 593
f4d45d47 594 argsz = sizeof(*irq_set) + sizeof(*pfd);
1a403133 595
f4d45d47
AW
596 irq_set = g_malloc0(argsz);
597 irq_set->argsz = argsz;
598 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
599 VFIO_IRQ_SET_ACTION_TRIGGER;
600 irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
601 irq_set->start = nr;
602 irq_set->count = 1;
603 pfd = (int32_t *)&irq_set->data;
1a403133 604
f4d45d47 605 *pfd = event_notifier_get_fd(&vector->interrupt);
1a403133 606
5546a621 607 ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
65501a74 608
f4d45d47 609 g_free(irq_set);
65501a74 610 }
65501a74
AW
611}
612
0de70dc7 613static void vfio_msix_enable(VFIOPCIDevice *vdev)
fd704adc
AW
614{
615 vfio_disable_interrupts(vdev);
616
bdd81add 617 vdev->msi_vectors = g_new0(VFIOMSIVector, vdev->msix->entries);
fd704adc
AW
618
619 vdev->interrupt = VFIO_INT_MSIX;
620
b0223e29
AW
621 /*
622 * Some communication channels between VF & PF or PF & fw rely on the
623 * physical state of the device and expect that enabling MSI-X from the
624 * guest enables the same on the host. When our guest is Linux, the
625 * guest driver call to pci_enable_msix() sets the enabling bit in the
626 * MSI-X capability, but leaves the vector table masked. We therefore
627 * can't rely on a vector_use callback (from request_irq() in the guest)
628 * to switch the physical device into MSI-X mode because that may come a
629 * long time after pci_enable_msix(). This code enables vector 0 with
630 * triggering to userspace, then immediately release the vector, leaving
631 * the physical device with no vectors enabled, but MSI-X enabled, just
632 * like the guest view.
633 */
634 vfio_msix_vector_do_use(&vdev->pdev, 0, NULL, NULL);
635 vfio_msix_vector_release(&vdev->pdev, 0);
636
fd704adc 637 if (msix_set_vector_notifiers(&vdev->pdev, vfio_msix_vector_use,
bbef882c 638 vfio_msix_vector_release, NULL)) {
312fd5f2 639 error_report("vfio: msix_set_vector_notifiers failed");
fd704adc
AW
640 }
641
0de70dc7 642 trace_vfio_msix_enable(vdev->vbasedev.name);
fd704adc
AW
643}
644
0de70dc7 645static void vfio_msi_enable(VFIOPCIDevice *vdev)
65501a74
AW
646{
647 int ret, i;
648
649 vfio_disable_interrupts(vdev);
650
651 vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev);
652retry:
bdd81add 653 vdev->msi_vectors = g_new0(VFIOMSIVector, vdev->nr_vectors);
65501a74
AW
654
655 for (i = 0; i < vdev->nr_vectors; i++) {
65501a74
AW
656 VFIOMSIVector *vector = &vdev->msi_vectors[i];
657
658 vector->vdev = vdev;
f4d45d47 659 vector->virq = -1;
65501a74
AW
660 vector->use = true;
661
662 if (event_notifier_init(&vector->interrupt, 0)) {
312fd5f2 663 error_report("vfio: Error: event_notifier_init failed");
65501a74
AW
664 }
665
f4d45d47
AW
666 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
667 vfio_msi_interrupt, NULL, vector);
668
65501a74
AW
669 /*
670 * Attempt to enable route through KVM irqchip,
671 * default to userspace handling if unavailable.
672 */
d1f6af6a 673 vfio_add_kvm_msi_virq(vdev, vector, i, false);
65501a74
AW
674 }
675
f4d45d47
AW
676 /* Set interrupt type prior to possible interrupts */
677 vdev->interrupt = VFIO_INT_MSI;
678
65501a74
AW
679 ret = vfio_enable_vectors(vdev, false);
680 if (ret) {
681 if (ret < 0) {
312fd5f2 682 error_report("vfio: Error: Failed to setup MSI fds: %m");
65501a74
AW
683 } else if (ret != vdev->nr_vectors) {
684 error_report("vfio: Error: Failed to enable %d "
312fd5f2 685 "MSI vectors, retry with %d", vdev->nr_vectors, ret);
65501a74
AW
686 }
687
688 for (i = 0; i < vdev->nr_vectors; i++) {
689 VFIOMSIVector *vector = &vdev->msi_vectors[i];
690 if (vector->virq >= 0) {
f4d45d47 691 vfio_remove_kvm_msi_virq(vector);
65501a74 692 }
f4d45d47
AW
693 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
694 NULL, NULL, NULL);
65501a74
AW
695 event_notifier_cleanup(&vector->interrupt);
696 }
697
698 g_free(vdev->msi_vectors);
699
700 if (ret > 0 && ret != vdev->nr_vectors) {
701 vdev->nr_vectors = ret;
702 goto retry;
703 }
704 vdev->nr_vectors = 0;
705
f4d45d47
AW
706 /*
707 * Failing to setup MSI doesn't really fall within any specification.
708 * Let's try leaving interrupts disabled and hope the guest figures
709 * out to fall back to INTx for this device.
710 */
711 error_report("vfio: Error: Failed to enable MSI");
712 vdev->interrupt = VFIO_INT_NONE;
713
65501a74
AW
714 return;
715 }
716
0de70dc7 717 trace_vfio_msi_enable(vdev->vbasedev.name, vdev->nr_vectors);
65501a74
AW
718}
719
0de70dc7 720static void vfio_msi_disable_common(VFIOPCIDevice *vdev)
fd704adc 721{
7dfb3424 722 Error *err = NULL;
f4d45d47
AW
723 int i;
724
725 for (i = 0; i < vdev->nr_vectors; i++) {
726 VFIOMSIVector *vector = &vdev->msi_vectors[i];
727 if (vdev->msi_vectors[i].use) {
728 if (vector->virq >= 0) {
729 vfio_remove_kvm_msi_virq(vector);
730 }
731 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
732 NULL, NULL, NULL);
733 event_notifier_cleanup(&vector->interrupt);
734 }
735 }
736
fd704adc
AW
737 g_free(vdev->msi_vectors);
738 vdev->msi_vectors = NULL;
739 vdev->nr_vectors = 0;
740 vdev->interrupt = VFIO_INT_NONE;
741
7dfb3424
EA
742 vfio_intx_enable(vdev, &err);
743 if (err) {
744 error_reportf_err(err, ERR_PREFIX, vdev->vbasedev.name);
745 }
fd704adc
AW
746}
747
0de70dc7 748static void vfio_msix_disable(VFIOPCIDevice *vdev)
fd704adc 749{
3e40ba0f
AW
750 int i;
751
fd704adc
AW
752 msix_unset_vector_notifiers(&vdev->pdev);
753
3e40ba0f
AW
754 /*
755 * MSI-X will only release vectors if MSI-X is still enabled on the
756 * device, check through the rest and release it ourselves if necessary.
757 */
758 for (i = 0; i < vdev->nr_vectors; i++) {
759 if (vdev->msi_vectors[i].use) {
760 vfio_msix_vector_release(&vdev->pdev, i);
f4d45d47 761 msix_vector_unuse(&vdev->pdev, i);
3e40ba0f
AW
762 }
763 }
764
fd704adc 765 if (vdev->nr_vectors) {
5546a621 766 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
fd704adc
AW
767 }
768
0de70dc7 769 vfio_msi_disable_common(vdev);
fd704adc 770
95239e16
AW
771 memset(vdev->msix->pending, 0,
772 BITS_TO_LONGS(vdev->msix->entries) * sizeof(unsigned long));
773
0de70dc7 774 trace_vfio_msix_disable(vdev->vbasedev.name);
fd704adc
AW
775}
776
0de70dc7 777static void vfio_msi_disable(VFIOPCIDevice *vdev)
65501a74 778{
5546a621 779 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSI_IRQ_INDEX);
0de70dc7 780 vfio_msi_disable_common(vdev);
65501a74 781
0de70dc7 782 trace_vfio_msi_disable(vdev->vbasedev.name);
65501a74
AW
783}
784
9ee27d73 785static void vfio_update_msi(VFIOPCIDevice *vdev)
c7679d45
AW
786{
787 int i;
788
789 for (i = 0; i < vdev->nr_vectors; i++) {
790 VFIOMSIVector *vector = &vdev->msi_vectors[i];
791 MSIMessage msg;
792
793 if (!vector->use || vector->virq < 0) {
794 continue;
795 }
796
797 msg = msi_get_message(&vdev->pdev, i);
dc9f06ca 798 vfio_update_kvm_msi_virq(vector, msg, &vdev->pdev);
c7679d45
AW
799 }
800}
801
9ee27d73 802static void vfio_pci_load_rom(VFIOPCIDevice *vdev)
6f864e6e 803{
46900226 804 struct vfio_region_info *reg_info;
6f864e6e
AW
805 uint64_t size;
806 off_t off = 0;
7d489dcd 807 ssize_t bytes;
6f864e6e 808
46900226
AW
809 if (vfio_get_region_info(&vdev->vbasedev,
810 VFIO_PCI_ROM_REGION_INDEX, &reg_info)) {
6f864e6e
AW
811 error_report("vfio: Error getting ROM info: %m");
812 return;
813 }
814
46900226
AW
815 trace_vfio_pci_load_rom(vdev->vbasedev.name, (unsigned long)reg_info->size,
816 (unsigned long)reg_info->offset,
817 (unsigned long)reg_info->flags);
818
819 vdev->rom_size = size = reg_info->size;
820 vdev->rom_offset = reg_info->offset;
6f864e6e 821
46900226 822 g_free(reg_info);
6f864e6e
AW
823
824 if (!vdev->rom_size) {
e638073c 825 vdev->rom_read_failed = true;
d20b43df 826 error_report("vfio-pci: Cannot read device rom at "
df92ee44 827 "%s", vdev->vbasedev.name);
d20b43df
BD
828 error_printf("Device option ROM contents are probably invalid "
829 "(check dmesg).\nSkip option ROM probe with rombar=0, "
830 "or load from file with romfile=\n");
6f864e6e
AW
831 return;
832 }
833
834 vdev->rom = g_malloc(size);
835 memset(vdev->rom, 0xff, size);
836
837 while (size) {
5546a621
EA
838 bytes = pread(vdev->vbasedev.fd, vdev->rom + off,
839 size, vdev->rom_offset + off);
6f864e6e
AW
840 if (bytes == 0) {
841 break;
842 } else if (bytes > 0) {
843 off += bytes;
844 size -= bytes;
845 } else {
846 if (errno == EINTR || errno == EAGAIN) {
847 continue;
848 }
849 error_report("vfio: Error reading device ROM: %m");
850 break;
851 }
852 }
e2e5ee9c
AW
853
854 /*
855 * Test the ROM signature against our device, if the vendor is correct
856 * but the device ID doesn't match, store the correct device ID and
857 * recompute the checksum. Intel IGD devices need this and are known
858 * to have bogus checksums so we can't simply adjust the checksum.
859 */
860 if (pci_get_word(vdev->rom) == 0xaa55 &&
861 pci_get_word(vdev->rom + 0x18) + 8 < vdev->rom_size &&
862 !memcmp(vdev->rom + pci_get_word(vdev->rom + 0x18), "PCIR", 4)) {
863 uint16_t vid, did;
864
865 vid = pci_get_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 4);
866 did = pci_get_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 6);
867
868 if (vid == vdev->vendor_id && did != vdev->device_id) {
869 int i;
870 uint8_t csum, *data = vdev->rom;
871
872 pci_set_word(vdev->rom + pci_get_word(vdev->rom + 0x18) + 6,
873 vdev->device_id);
874 data[6] = 0;
875
876 for (csum = 0, i = 0; i < vdev->rom_size; i++) {
877 csum += data[i];
878 }
879
880 data[6] = -csum;
881 }
882 }
6f864e6e
AW
883}
884
885static uint64_t vfio_rom_read(void *opaque, hwaddr addr, unsigned size)
886{
9ee27d73 887 VFIOPCIDevice *vdev = opaque;
75bd0c72
ND
888 union {
889 uint8_t byte;
890 uint16_t word;
891 uint32_t dword;
892 uint64_t qword;
893 } val;
894 uint64_t data = 0;
6f864e6e
AW
895
896 /* Load the ROM lazily when the guest tries to read it */
db01eedb 897 if (unlikely(!vdev->rom && !vdev->rom_read_failed)) {
6f864e6e
AW
898 vfio_pci_load_rom(vdev);
899 }
900
6758008e 901 memcpy(&val, vdev->rom + addr,
6f864e6e
AW
902 (addr < vdev->rom_size) ? MIN(size, vdev->rom_size - addr) : 0);
903
75bd0c72
ND
904 switch (size) {
905 case 1:
906 data = val.byte;
907 break;
908 case 2:
909 data = le16_to_cpu(val.word);
910 break;
911 case 4:
912 data = le32_to_cpu(val.dword);
913 break;
914 default:
915 hw_error("vfio: unsupported read size, %d bytes\n", size);
916 break;
917 }
918
df92ee44 919 trace_vfio_rom_read(vdev->vbasedev.name, addr, size, data);
6f864e6e 920
75bd0c72 921 return data;
6f864e6e
AW
922}
923
64fa25a0
AW
924static void vfio_rom_write(void *opaque, hwaddr addr,
925 uint64_t data, unsigned size)
926{
927}
928
6f864e6e
AW
929static const MemoryRegionOps vfio_rom_ops = {
930 .read = vfio_rom_read,
64fa25a0 931 .write = vfio_rom_write,
6758008e 932 .endianness = DEVICE_LITTLE_ENDIAN,
6f864e6e
AW
933};
934
9ee27d73 935static void vfio_pci_size_rom(VFIOPCIDevice *vdev)
6f864e6e 936{
b1c50c5f 937 uint32_t orig, size = cpu_to_le32((uint32_t)PCI_ROM_ADDRESS_MASK);
6f864e6e 938 off_t offset = vdev->config_offset + PCI_ROM_ADDRESS;
4b943029 939 DeviceState *dev = DEVICE(vdev);
062ed5d8 940 char *name;
5546a621 941 int fd = vdev->vbasedev.fd;
6f864e6e
AW
942
943 if (vdev->pdev.romfile || !vdev->pdev.rom_bar) {
4b943029
BD
944 /* Since pci handles romfile, just print a message and return */
945 if (vfio_blacklist_opt_rom(vdev) && vdev->pdev.romfile) {
7df9381b
AW
946 error_printf("Warning : Device at %s is known to cause system instability issues during option rom execution. Proceeding anyway since user specified romfile\n",
947 vdev->vbasedev.name);
4b943029 948 }
6f864e6e
AW
949 return;
950 }
951
952 /*
953 * Use the same size ROM BAR as the physical device. The contents
954 * will get filled in later when the guest tries to read it.
955 */
5546a621
EA
956 if (pread(fd, &orig, 4, offset) != 4 ||
957 pwrite(fd, &size, 4, offset) != 4 ||
958 pread(fd, &size, 4, offset) != 4 ||
959 pwrite(fd, &orig, 4, offset) != 4) {
7df9381b 960 error_report("%s(%s) failed: %m", __func__, vdev->vbasedev.name);
6f864e6e
AW
961 return;
962 }
963
b1c50c5f 964 size = ~(le32_to_cpu(size) & PCI_ROM_ADDRESS_MASK) + 1;
6f864e6e
AW
965
966 if (!size) {
967 return;
968 }
969
4b943029
BD
970 if (vfio_blacklist_opt_rom(vdev)) {
971 if (dev->opts && qemu_opt_get(dev->opts, "rombar")) {
7df9381b
AW
972 error_printf("Warning : Device at %s is known to cause system instability issues during option rom execution. Proceeding anyway since user specified non zero value for rombar\n",
973 vdev->vbasedev.name);
4b943029 974 } else {
7df9381b
AW
975 error_printf("Warning : Rom loading for device at %s has been disabled due to system instability issues. Specify rombar=1 or romfile to force\n",
976 vdev->vbasedev.name);
4b943029
BD
977 return;
978 }
979 }
980
df92ee44 981 trace_vfio_pci_size_rom(vdev->vbasedev.name, size);
6f864e6e 982
062ed5d8 983 name = g_strdup_printf("vfio[%s].rom", vdev->vbasedev.name);
6f864e6e
AW
984
985 memory_region_init_io(&vdev->pdev.rom, OBJECT(vdev),
986 &vfio_rom_ops, vdev, name, size);
062ed5d8 987 g_free(name);
6f864e6e
AW
988
989 pci_register_bar(&vdev->pdev, PCI_ROM_SLOT,
990 PCI_BASE_ADDRESS_SPACE_MEMORY, &vdev->pdev.rom);
991
992 vdev->pdev.has_rom = true;
e638073c 993 vdev->rom_read_failed = false;
6f864e6e
AW
994}
995
c00d61d8 996void vfio_vga_write(void *opaque, hwaddr addr,
f15689c7
AW
997 uint64_t data, unsigned size)
998{
999 VFIOVGARegion *region = opaque;
1000 VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
1001 union {
1002 uint8_t byte;
1003 uint16_t word;
1004 uint32_t dword;
1005 uint64_t qword;
1006 } buf;
1007 off_t offset = vga->fd_offset + region->offset + addr;
1008
1009 switch (size) {
1010 case 1:
1011 buf.byte = data;
1012 break;
1013 case 2:
1014 buf.word = cpu_to_le16(data);
1015 break;
1016 case 4:
1017 buf.dword = cpu_to_le32(data);
1018 break;
1019 default:
4e505ddd 1020 hw_error("vfio: unsupported write size, %d bytes", size);
f15689c7
AW
1021 break;
1022 }
1023
1024 if (pwrite(vga->fd, &buf, size, offset) != size) {
1025 error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m",
1026 __func__, region->offset + addr, data, size);
1027 }
1028
385f57cf 1029 trace_vfio_vga_write(region->offset + addr, data, size);
f15689c7
AW
1030}
1031
c00d61d8 1032uint64_t vfio_vga_read(void *opaque, hwaddr addr, unsigned size)
f15689c7
AW
1033{
1034 VFIOVGARegion *region = opaque;
1035 VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
1036 union {
1037 uint8_t byte;
1038 uint16_t word;
1039 uint32_t dword;
1040 uint64_t qword;
1041 } buf;
1042 uint64_t data = 0;
1043 off_t offset = vga->fd_offset + region->offset + addr;
1044
1045 if (pread(vga->fd, &buf, size, offset) != size) {
1046 error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m",
1047 __func__, region->offset + addr, size);
1048 return (uint64_t)-1;
1049 }
1050
1051 switch (size) {
1052 case 1:
1053 data = buf.byte;
1054 break;
1055 case 2:
1056 data = le16_to_cpu(buf.word);
1057 break;
1058 case 4:
1059 data = le32_to_cpu(buf.dword);
1060 break;
1061 default:
4e505ddd 1062 hw_error("vfio: unsupported read size, %d bytes", size);
f15689c7
AW
1063 break;
1064 }
1065
385f57cf 1066 trace_vfio_vga_read(region->offset + addr, size, data);
f15689c7
AW
1067
1068 return data;
1069}
1070
1071static const MemoryRegionOps vfio_vga_ops = {
1072 .read = vfio_vga_read,
1073 .write = vfio_vga_write,
1074 .endianness = DEVICE_LITTLE_ENDIAN,
1075};
1076
95251725
YX
1077/*
1078 * Expand memory region of sub-page(size < PAGE_SIZE) MMIO BAR to page
1079 * size if the BAR is in an exclusive page in host so that we could map
1080 * this BAR to guest. But this sub-page BAR may not occupy an exclusive
1081 * page in guest. So we should set the priority of the expanded memory
1082 * region to zero in case of overlap with BARs which share the same page
1083 * with the sub-page BAR in guest. Besides, we should also recover the
1084 * size of this sub-page BAR when its base address is changed in guest
1085 * and not page aligned any more.
1086 */
1087static void vfio_sub_page_bar_update_mapping(PCIDevice *pdev, int bar)
1088{
1089 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
1090 VFIORegion *region = &vdev->bars[bar].region;
3a286732 1091 MemoryRegion *mmap_mr, *region_mr, *base_mr;
95251725
YX
1092 PCIIORegion *r;
1093 pcibus_t bar_addr;
1094 uint64_t size = region->size;
1095
1096 /* Make sure that the whole region is allowed to be mmapped */
1097 if (region->nr_mmaps != 1 || !region->mmaps[0].mmap ||
1098 region->mmaps[0].size != region->size) {
1099 return;
1100 }
1101
1102 r = &pdev->io_regions[bar];
1103 bar_addr = r->addr;
3a286732
AW
1104 base_mr = vdev->bars[bar].mr;
1105 region_mr = region->mem;
95251725
YX
1106 mmap_mr = &region->mmaps[0].mem;
1107
1108 /* If BAR is mapped and page aligned, update to fill PAGE_SIZE */
1109 if (bar_addr != PCI_BAR_UNMAPPED &&
1110 !(bar_addr & ~qemu_real_host_page_mask)) {
1111 size = qemu_real_host_page_size;
1112 }
1113
1114 memory_region_transaction_begin();
1115
3a286732
AW
1116 if (vdev->bars[bar].size < size) {
1117 memory_region_set_size(base_mr, size);
1118 }
1119 memory_region_set_size(region_mr, size);
95251725 1120 memory_region_set_size(mmap_mr, size);
3a286732
AW
1121 if (size != vdev->bars[bar].size && memory_region_is_mapped(base_mr)) {
1122 memory_region_del_subregion(r->address_space, base_mr);
95251725 1123 memory_region_add_subregion_overlap(r->address_space,
3a286732 1124 bar_addr, base_mr, 0);
95251725
YX
1125 }
1126
1127 memory_region_transaction_commit();
1128}
1129
65501a74
AW
1130/*
1131 * PCI config space
1132 */
c00d61d8 1133uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len)
65501a74 1134{
9ee27d73 1135 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
4b5d5e87 1136 uint32_t emu_bits = 0, emu_val = 0, phys_val = 0, val;
65501a74 1137
4b5d5e87
AW
1138 memcpy(&emu_bits, vdev->emulated_config_bits + addr, len);
1139 emu_bits = le32_to_cpu(emu_bits);
65501a74 1140
4b5d5e87
AW
1141 if (emu_bits) {
1142 emu_val = pci_default_read_config(pdev, addr, len);
1143 }
1144
1145 if (~emu_bits & (0xffffffffU >> (32 - len * 8))) {
1146 ssize_t ret;
1147
5546a621
EA
1148 ret = pread(vdev->vbasedev.fd, &phys_val, len,
1149 vdev->config_offset + addr);
4b5d5e87 1150 if (ret != len) {
7df9381b
AW
1151 error_report("%s(%s, 0x%x, 0x%x) failed: %m",
1152 __func__, vdev->vbasedev.name, addr, len);
65501a74
AW
1153 return -errno;
1154 }
4b5d5e87 1155 phys_val = le32_to_cpu(phys_val);
65501a74
AW
1156 }
1157
4b5d5e87 1158 val = (emu_val & emu_bits) | (phys_val & ~emu_bits);
65501a74 1159
df92ee44 1160 trace_vfio_pci_read_config(vdev->vbasedev.name, addr, len, val);
65501a74
AW
1161
1162 return val;
1163}
1164
c00d61d8
AW
1165void vfio_pci_write_config(PCIDevice *pdev,
1166 uint32_t addr, uint32_t val, int len)
65501a74 1167{
9ee27d73 1168 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
65501a74
AW
1169 uint32_t val_le = cpu_to_le32(val);
1170
df92ee44 1171 trace_vfio_pci_write_config(vdev->vbasedev.name, addr, val, len);
65501a74
AW
1172
1173 /* Write everything to VFIO, let it filter out what we can't write */
5546a621
EA
1174 if (pwrite(vdev->vbasedev.fd, &val_le, len, vdev->config_offset + addr)
1175 != len) {
7df9381b
AW
1176 error_report("%s(%s, 0x%x, 0x%x, 0x%x) failed: %m",
1177 __func__, vdev->vbasedev.name, addr, val, len);
65501a74
AW
1178 }
1179
65501a74
AW
1180 /* MSI/MSI-X Enabling/Disabling */
1181 if (pdev->cap_present & QEMU_PCI_CAP_MSI &&
1182 ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {
1183 int is_enabled, was_enabled = msi_enabled(pdev);
1184
1185 pci_default_write_config(pdev, addr, val, len);
1186
1187 is_enabled = msi_enabled(pdev);
1188
c7679d45
AW
1189 if (!was_enabled) {
1190 if (is_enabled) {
0de70dc7 1191 vfio_msi_enable(vdev);
c7679d45
AW
1192 }
1193 } else {
1194 if (!is_enabled) {
0de70dc7 1195 vfio_msi_disable(vdev);
c7679d45
AW
1196 } else {
1197 vfio_update_msi(vdev);
1198 }
65501a74 1199 }
4b5d5e87 1200 } else if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
65501a74
AW
1201 ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {
1202 int is_enabled, was_enabled = msix_enabled(pdev);
1203
1204 pci_default_write_config(pdev, addr, val, len);
1205
1206 is_enabled = msix_enabled(pdev);
1207
1208 if (!was_enabled && is_enabled) {
0de70dc7 1209 vfio_msix_enable(vdev);
65501a74 1210 } else if (was_enabled && !is_enabled) {
0de70dc7 1211 vfio_msix_disable(vdev);
65501a74 1212 }
95251725
YX
1213 } else if (ranges_overlap(addr, len, PCI_BASE_ADDRESS_0, 24) ||
1214 range_covers_byte(addr, len, PCI_COMMAND)) {
1215 pcibus_t old_addr[PCI_NUM_REGIONS - 1];
1216 int bar;
1217
1218 for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
1219 old_addr[bar] = pdev->io_regions[bar].addr;
1220 }
1221
1222 pci_default_write_config(pdev, addr, val, len);
1223
1224 for (bar = 0; bar < PCI_ROM_SLOT; bar++) {
1225 if (old_addr[bar] != pdev->io_regions[bar].addr &&
3a286732
AW
1226 vdev->bars[bar].region.size > 0 &&
1227 vdev->bars[bar].region.size < qemu_real_host_page_size) {
95251725
YX
1228 vfio_sub_page_bar_update_mapping(pdev, bar);
1229 }
1230 }
4b5d5e87
AW
1231 } else {
1232 /* Write everything to QEMU to keep emulated bits correct */
1233 pci_default_write_config(pdev, addr, val, len);
65501a74
AW
1234 }
1235}
1236
65501a74
AW
1237/*
1238 * Interrupt setup
1239 */
9ee27d73 1240static void vfio_disable_interrupts(VFIOPCIDevice *vdev)
65501a74 1241{
b3e27c3a
AW
1242 /*
1243 * More complicated than it looks. Disabling MSI/X transitions the
1244 * device to INTx mode (if supported). Therefore we need to first
1245 * disable MSI/X and then cleanup by disabling INTx.
1246 */
1247 if (vdev->interrupt == VFIO_INT_MSIX) {
0de70dc7 1248 vfio_msix_disable(vdev);
b3e27c3a 1249 } else if (vdev->interrupt == VFIO_INT_MSI) {
0de70dc7 1250 vfio_msi_disable(vdev);
b3e27c3a
AW
1251 }
1252
1253 if (vdev->interrupt == VFIO_INT_INTx) {
870cb6f1 1254 vfio_intx_disable(vdev);
65501a74
AW
1255 }
1256}
1257
7ef165b9 1258static int vfio_msi_setup(VFIOPCIDevice *vdev, int pos, Error **errp)
65501a74
AW
1259{
1260 uint16_t ctrl;
1261 bool msi_64bit, msi_maskbit;
1262 int ret, entries;
1108b2f8 1263 Error *err = NULL;
65501a74 1264
5546a621 1265 if (pread(vdev->vbasedev.fd, &ctrl, sizeof(ctrl),
65501a74 1266 vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
7ef165b9 1267 error_setg_errno(errp, errno, "failed reading MSI PCI_CAP_FLAGS");
65501a74
AW
1268 return -errno;
1269 }
1270 ctrl = le16_to_cpu(ctrl);
1271
1272 msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT);
1273 msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT);
1274 entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1);
1275
0de70dc7 1276 trace_vfio_msi_setup(vdev->vbasedev.name, pos);
65501a74 1277
1108b2f8 1278 ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit, &err);
65501a74 1279 if (ret < 0) {
e43b9a5a
AW
1280 if (ret == -ENOTSUP) {
1281 return 0;
1282 }
7ef165b9
EA
1283 error_prepend(&err, "msi_init failed: ");
1284 error_propagate(errp, err);
65501a74
AW
1285 return ret;
1286 }
1287 vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0);
1288
1289 return 0;
1290}
1291
db0da029
AW
1292static void vfio_pci_fixup_msix_region(VFIOPCIDevice *vdev)
1293{
1294 off_t start, end;
1295 VFIORegion *region = &vdev->bars[vdev->msix->table_bar].region;
1296
ae0215b2
AK
1297 /*
1298 * If the host driver allows mapping of a MSIX data, we are going to
1299 * do map the entire BAR and emulate MSIX table on top of that.
1300 */
1301 if (vfio_has_region_cap(&vdev->vbasedev, region->nr,
1302 VFIO_REGION_INFO_CAP_MSIX_MAPPABLE)) {
1303 return;
1304 }
1305
db0da029
AW
1306 /*
1307 * We expect to find a single mmap covering the whole BAR, anything else
1308 * means it's either unsupported or already setup.
1309 */
1310 if (region->nr_mmaps != 1 || region->mmaps[0].offset ||
1311 region->size != region->mmaps[0].size) {
1312 return;
1313 }
1314
1315 /* MSI-X table start and end aligned to host page size */
1316 start = vdev->msix->table_offset & qemu_real_host_page_mask;
1317 end = REAL_HOST_PAGE_ALIGN((uint64_t)vdev->msix->table_offset +
1318 (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE));
1319
1320 /*
1321 * Does the MSI-X table cover the beginning of the BAR? The whole BAR?
1322 * NB - Host page size is necessarily a power of two and so is the PCI
1323 * BAR (not counting EA yet), therefore if we have host page aligned
1324 * @start and @end, then any remainder of the BAR before or after those
1325 * must be at least host page sized and therefore mmap'able.
1326 */
1327 if (!start) {
1328 if (end >= region->size) {
1329 region->nr_mmaps = 0;
1330 g_free(region->mmaps);
1331 region->mmaps = NULL;
1332 trace_vfio_msix_fixup(vdev->vbasedev.name,
1333 vdev->msix->table_bar, 0, 0);
1334 } else {
1335 region->mmaps[0].offset = end;
1336 region->mmaps[0].size = region->size - end;
1337 trace_vfio_msix_fixup(vdev->vbasedev.name,
1338 vdev->msix->table_bar, region->mmaps[0].offset,
1339 region->mmaps[0].offset + region->mmaps[0].size);
1340 }
1341
1342 /* Maybe it's aligned at the end of the BAR */
1343 } else if (end >= region->size) {
1344 region->mmaps[0].size = start;
1345 trace_vfio_msix_fixup(vdev->vbasedev.name,
1346 vdev->msix->table_bar, region->mmaps[0].offset,
1347 region->mmaps[0].offset + region->mmaps[0].size);
1348
1349 /* Otherwise it must split the BAR */
1350 } else {
1351 region->nr_mmaps = 2;
1352 region->mmaps = g_renew(VFIOMmap, region->mmaps, 2);
1353
1354 memcpy(&region->mmaps[1], &region->mmaps[0], sizeof(VFIOMmap));
1355
1356 region->mmaps[0].size = start;
1357 trace_vfio_msix_fixup(vdev->vbasedev.name,
1358 vdev->msix->table_bar, region->mmaps[0].offset,
1359 region->mmaps[0].offset + region->mmaps[0].size);
1360
1361 region->mmaps[1].offset = end;
1362 region->mmaps[1].size = region->size - end;
1363 trace_vfio_msix_fixup(vdev->vbasedev.name,
1364 vdev->msix->table_bar, region->mmaps[1].offset,
1365 region->mmaps[1].offset + region->mmaps[1].size);
1366 }
1367}
1368
89d5202e
AW
1369static void vfio_pci_relocate_msix(VFIOPCIDevice *vdev, Error **errp)
1370{
1371 int target_bar = -1;
1372 size_t msix_sz;
1373
1374 if (!vdev->msix || vdev->msix_relo == OFF_AUTOPCIBAR_OFF) {
1375 return;
1376 }
1377
1378 /* The actual minimum size of MSI-X structures */
1379 msix_sz = (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE) +
1380 (QEMU_ALIGN_UP(vdev->msix->entries, 64) / 8);
1381 /* Round up to host pages, we don't want to share a page */
1382 msix_sz = REAL_HOST_PAGE_ALIGN(msix_sz);
1383 /* PCI BARs must be a power of 2 */
1384 msix_sz = pow2ceil(msix_sz);
1385
1386 if (vdev->msix_relo == OFF_AUTOPCIBAR_AUTO) {
1387 /*
1388 * TODO: Lookup table for known devices.
1389 *
1390 * Logically we might use an algorithm here to select the BAR adding
1391 * the least additional MMIO space, but we cannot programatically
1392 * predict the driver dependency on BAR ordering or sizing, therefore
1393 * 'auto' becomes a lookup for combinations reported to work.
1394 */
1395 if (target_bar < 0) {
1396 error_setg(errp, "No automatic MSI-X relocation available for "
1397 "device %04x:%04x", vdev->vendor_id, vdev->device_id);
1398 return;
1399 }
1400 } else {
1401 target_bar = (int)(vdev->msix_relo - OFF_AUTOPCIBAR_BAR0);
1402 }
1403
1404 /* I/O port BARs cannot host MSI-X structures */
1405 if (vdev->bars[target_bar].ioport) {
1406 error_setg(errp, "Invalid MSI-X relocation BAR %d, "
1407 "I/O port BAR", target_bar);
1408 return;
1409 }
1410
1411 /* Cannot use a BAR in the "shadow" of a 64-bit BAR */
1412 if (!vdev->bars[target_bar].size &&
1413 target_bar > 0 && vdev->bars[target_bar - 1].mem64) {
1414 error_setg(errp, "Invalid MSI-X relocation BAR %d, "
1415 "consumed by 64-bit BAR %d", target_bar, target_bar - 1);
1416 return;
1417 }
1418
1419 /* 2GB max size for 32-bit BARs, cannot double if already > 1G */
1420 if (vdev->bars[target_bar].size > (1 * 1024 * 1024 * 1024) &&
1421 !vdev->bars[target_bar].mem64) {
1422 error_setg(errp, "Invalid MSI-X relocation BAR %d, "
1423 "no space to extend 32-bit BAR", target_bar);
1424 return;
1425 }
1426
1427 /*
1428 * If adding a new BAR, test if we can make it 64bit. We make it
1429 * prefetchable since QEMU MSI-X emulation has no read side effects
1430 * and doing so makes mapping more flexible.
1431 */
1432 if (!vdev->bars[target_bar].size) {
1433 if (target_bar < (PCI_ROM_SLOT - 1) &&
1434 !vdev->bars[target_bar + 1].size) {
1435 vdev->bars[target_bar].mem64 = true;
1436 vdev->bars[target_bar].type = PCI_BASE_ADDRESS_MEM_TYPE_64;
1437 }
1438 vdev->bars[target_bar].type |= PCI_BASE_ADDRESS_MEM_PREFETCH;
1439 vdev->bars[target_bar].size = msix_sz;
1440 vdev->msix->table_offset = 0;
1441 } else {
1442 vdev->bars[target_bar].size = MAX(vdev->bars[target_bar].size * 2,
1443 msix_sz * 2);
1444 /*
1445 * Due to above size calc, MSI-X always starts halfway into the BAR,
1446 * which will always be a separate host page.
1447 */
1448 vdev->msix->table_offset = vdev->bars[target_bar].size / 2;
1449 }
1450
1451 vdev->msix->table_bar = target_bar;
1452 vdev->msix->pba_bar = target_bar;
1453 /* Requires 8-byte alignment, but PCI_MSIX_ENTRY_SIZE guarantees that */
1454 vdev->msix->pba_offset = vdev->msix->table_offset +
1455 (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE);
1456
1457 trace_vfio_msix_relo(vdev->vbasedev.name,
1458 vdev->msix->table_bar, vdev->msix->table_offset);
1459}
1460
65501a74
AW
1461/*
1462 * We don't have any control over how pci_add_capability() inserts
1463 * capabilities into the chain. In order to setup MSI-X we need a
1464 * MemoryRegion for the BAR. In order to setup the BAR and not
1465 * attempt to mmap the MSI-X table area, which VFIO won't allow, we
1466 * need to first look for where the MSI-X table lives. So we
1467 * unfortunately split MSI-X setup across two functions.
1468 */
ec3bcf42 1469static void vfio_msix_early_setup(VFIOPCIDevice *vdev, Error **errp)
65501a74
AW
1470{
1471 uint8_t pos;
1472 uint16_t ctrl;
1473 uint32_t table, pba;
5546a621 1474 int fd = vdev->vbasedev.fd;
b5bd049f 1475 VFIOMSIXInfo *msix;
65501a74
AW
1476
1477 pos = pci_find_capability(&vdev->pdev, PCI_CAP_ID_MSIX);
1478 if (!pos) {
ec3bcf42 1479 return;
65501a74
AW
1480 }
1481
5546a621 1482 if (pread(fd, &ctrl, sizeof(ctrl),
b58b17f7 1483 vdev->config_offset + pos + PCI_MSIX_FLAGS) != sizeof(ctrl)) {
008d0e2d 1484 error_setg_errno(errp, errno, "failed to read PCI MSIX FLAGS");
ec3bcf42 1485 return;
65501a74
AW
1486 }
1487
5546a621 1488 if (pread(fd, &table, sizeof(table),
65501a74 1489 vdev->config_offset + pos + PCI_MSIX_TABLE) != sizeof(table)) {
008d0e2d 1490 error_setg_errno(errp, errno, "failed to read PCI MSIX TABLE");
ec3bcf42 1491 return;
65501a74
AW
1492 }
1493
5546a621 1494 if (pread(fd, &pba, sizeof(pba),
65501a74 1495 vdev->config_offset + pos + PCI_MSIX_PBA) != sizeof(pba)) {
008d0e2d 1496 error_setg_errno(errp, errno, "failed to read PCI MSIX PBA");
ec3bcf42 1497 return;
65501a74
AW
1498 }
1499
1500 ctrl = le16_to_cpu(ctrl);
1501 table = le32_to_cpu(table);
1502 pba = le32_to_cpu(pba);
1503
b5bd049f
AW
1504 msix = g_malloc0(sizeof(*msix));
1505 msix->table_bar = table & PCI_MSIX_FLAGS_BIRMASK;
1506 msix->table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
1507 msix->pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK;
1508 msix->pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
1509 msix->entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
65501a74 1510
43302969
GL
1511 /*
1512 * Test the size of the pba_offset variable and catch if it extends outside
1513 * of the specified BAR. If it is the case, we need to apply a hardware
1514 * specific quirk if the device is known or we have a broken configuration.
1515 */
b5bd049f 1516 if (msix->pba_offset >= vdev->bars[msix->pba_bar].region.size) {
43302969
GL
1517 /*
1518 * Chelsio T5 Virtual Function devices are encoded as 0x58xx for T5
1519 * adapters. The T5 hardware returns an incorrect value of 0x8000 for
1520 * the VF PBA offset while the BAR itself is only 8k. The correct value
1521 * is 0x1000, so we hard code that here.
1522 */
ff635e37
AW
1523 if (vdev->vendor_id == PCI_VENDOR_ID_CHELSIO &&
1524 (vdev->device_id & 0xff00) == 0x5800) {
b5bd049f 1525 msix->pba_offset = 0x1000;
43302969 1526 } else {
008d0e2d
EA
1527 error_setg(errp, "hardware reports invalid configuration, "
1528 "MSIX PBA outside of specified BAR");
b5bd049f 1529 g_free(msix);
ec3bcf42 1530 return;
43302969
GL
1531 }
1532 }
1533
0de70dc7 1534 trace_vfio_msix_early_setup(vdev->vbasedev.name, pos, msix->table_bar,
b5bd049f
AW
1535 msix->table_offset, msix->entries);
1536 vdev->msix = msix;
65501a74 1537
db0da029 1538 vfio_pci_fixup_msix_region(vdev);
89d5202e
AW
1539
1540 vfio_pci_relocate_msix(vdev, errp);
65501a74
AW
1541}
1542
7ef165b9 1543static int vfio_msix_setup(VFIOPCIDevice *vdev, int pos, Error **errp)
65501a74
AW
1544{
1545 int ret;
ee640c62 1546 Error *err = NULL;
65501a74 1547
95239e16
AW
1548 vdev->msix->pending = g_malloc0(BITS_TO_LONGS(vdev->msix->entries) *
1549 sizeof(unsigned long));
65501a74 1550 ret = msix_init(&vdev->pdev, vdev->msix->entries,
3a286732 1551 vdev->bars[vdev->msix->table_bar].mr,
65501a74 1552 vdev->msix->table_bar, vdev->msix->table_offset,
3a286732 1553 vdev->bars[vdev->msix->pba_bar].mr,
ee640c62
C
1554 vdev->msix->pba_bar, vdev->msix->pba_offset, pos,
1555 &err);
65501a74 1556 if (ret < 0) {
e43b9a5a 1557 if (ret == -ENOTSUP) {
ee640c62 1558 error_report_err(err);
e43b9a5a
AW
1559 return 0;
1560 }
ee640c62
C
1561
1562 error_propagate(errp, err);
65501a74
AW
1563 return ret;
1564 }
1565
95239e16
AW
1566 /*
1567 * The PCI spec suggests that devices provide additional alignment for
1568 * MSI-X structures and avoid overlapping non-MSI-X related registers.
1569 * For an assigned device, this hopefully means that emulation of MSI-X
1570 * structures does not affect the performance of the device. If devices
1571 * fail to provide that alignment, a significant performance penalty may
1572 * result, for instance Mellanox MT27500 VFs:
1573 * http://www.spinics.net/lists/kvm/msg125881.html
1574 *
1575 * The PBA is simply not that important for such a serious regression and
1576 * most drivers do not appear to look at it. The solution for this is to
1577 * disable the PBA MemoryRegion unless it's being used. We disable it
1578 * here and only enable it if a masked vector fires through QEMU. As the
1579 * vector-use notifier is called, which occurs on unmask, we test whether
1580 * PBA emulation is needed and again disable if not.
1581 */
1582 memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, false);
1583
65501a74
AW
1584 return 0;
1585}
1586
9ee27d73 1587static void vfio_teardown_msi(VFIOPCIDevice *vdev)
65501a74
AW
1588{
1589 msi_uninit(&vdev->pdev);
1590
1591 if (vdev->msix) {
a664477d 1592 msix_uninit(&vdev->pdev,
3a286732
AW
1593 vdev->bars[vdev->msix->table_bar].mr,
1594 vdev->bars[vdev->msix->pba_bar].mr);
95239e16 1595 g_free(vdev->msix->pending);
65501a74
AW
1596 }
1597}
1598
1599/*
1600 * Resource setup
1601 */
9ee27d73 1602static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled)
65501a74
AW
1603{
1604 int i;
1605
1606 for (i = 0; i < PCI_ROM_SLOT; i++) {
db0da029 1607 vfio_region_mmaps_set_enabled(&vdev->bars[i].region, enabled);
65501a74
AW
1608 }
1609}
1610
3a286732 1611static void vfio_bar_prepare(VFIOPCIDevice *vdev, int nr)
65501a74
AW
1612{
1613 VFIOBAR *bar = &vdev->bars[nr];
1614
65501a74 1615 uint32_t pci_bar;
65501a74
AW
1616 int ret;
1617
1618 /* Skip both unimplemented BARs and the upper half of 64bit BARS. */
2d82f8a3 1619 if (!bar->region.size) {
65501a74
AW
1620 return;
1621 }
1622
65501a74 1623 /* Determine what type of BAR this is for registration */
5546a621 1624 ret = pread(vdev->vbasedev.fd, &pci_bar, sizeof(pci_bar),
65501a74
AW
1625 vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));
1626 if (ret != sizeof(pci_bar)) {
312fd5f2 1627 error_report("vfio: Failed to read BAR %d (%m)", nr);
65501a74
AW
1628 return;
1629 }
1630
1631 pci_bar = le32_to_cpu(pci_bar);
39360f0b
AW
1632 bar->ioport = (pci_bar & PCI_BASE_ADDRESS_SPACE_IO);
1633 bar->mem64 = bar->ioport ? 0 : (pci_bar & PCI_BASE_ADDRESS_MEM_TYPE_64);
3a286732
AW
1634 bar->type = pci_bar & (bar->ioport ? ~PCI_BASE_ADDRESS_IO_MASK :
1635 ~PCI_BASE_ADDRESS_MEM_MASK);
1636 bar->size = bar->region.size;
1637}
1638
1639static void vfio_bars_prepare(VFIOPCIDevice *vdev)
1640{
1641 int i;
1642
1643 for (i = 0; i < PCI_ROM_SLOT; i++) {
1644 vfio_bar_prepare(vdev, i);
1645 }
1646}
1647
1648static void vfio_bar_register(VFIOPCIDevice *vdev, int nr)
1649{
1650 VFIOBAR *bar = &vdev->bars[nr];
1651 char *name;
65501a74 1652
3a286732
AW
1653 if (!bar->size) {
1654 return;
65501a74 1655 }
7076eabc 1656
3a286732
AW
1657 bar->mr = g_new0(MemoryRegion, 1);
1658 name = g_strdup_printf("%s base BAR %d", vdev->vbasedev.name, nr);
1659 memory_region_init_io(bar->mr, OBJECT(vdev), NULL, NULL, name, bar->size);
1660 g_free(name);
1661
1662 if (bar->region.size) {
1663 memory_region_add_subregion(bar->mr, 0, bar->region.mem);
1664
1665 if (vfio_region_mmap(&bar->region)) {
1666 error_report("Failed to mmap %s BAR %d. Performance may be slow",
1667 vdev->vbasedev.name, nr);
1668 }
1669 }
1670
1671 pci_register_bar(&vdev->pdev, nr, bar->type, bar->mr);
65501a74
AW
1672}
1673
3a286732 1674static void vfio_bars_register(VFIOPCIDevice *vdev)
65501a74
AW
1675{
1676 int i;
1677
1678 for (i = 0; i < PCI_ROM_SLOT; i++) {
3a286732 1679 vfio_bar_register(vdev, i);
65501a74
AW
1680 }
1681}
1682
2d82f8a3 1683static void vfio_bars_exit(VFIOPCIDevice *vdev)
65501a74
AW
1684{
1685 int i;
1686
1687 for (i = 0; i < PCI_ROM_SLOT; i++) {
3a286732
AW
1688 VFIOBAR *bar = &vdev->bars[i];
1689
2d82f8a3 1690 vfio_bar_quirk_exit(vdev, i);
3a286732
AW
1691 vfio_region_exit(&bar->region);
1692 if (bar->region.size) {
1693 memory_region_del_subregion(bar->mr, bar->region.mem);
1694 }
65501a74 1695 }
f15689c7 1696
2d82f8a3 1697 if (vdev->vga) {
f15689c7 1698 pci_unregister_vga(&vdev->pdev);
2d82f8a3 1699 vfio_vga_quirk_exit(vdev);
f15689c7 1700 }
65501a74
AW
1701}
1702
2d82f8a3 1703static void vfio_bars_finalize(VFIOPCIDevice *vdev)
ba5e6bfa
PB
1704{
1705 int i;
1706
1707 for (i = 0; i < PCI_ROM_SLOT; i++) {
3a286732
AW
1708 VFIOBAR *bar = &vdev->bars[i];
1709
2d82f8a3 1710 vfio_bar_quirk_finalize(vdev, i);
3a286732
AW
1711 vfio_region_finalize(&bar->region);
1712 if (bar->size) {
1713 object_unparent(OBJECT(bar->mr));
1714 g_free(bar->mr);
1715 }
ba5e6bfa
PB
1716 }
1717
2d82f8a3
AW
1718 if (vdev->vga) {
1719 vfio_vga_quirk_finalize(vdev);
1720 for (i = 0; i < ARRAY_SIZE(vdev->vga->region); i++) {
1721 object_unparent(OBJECT(&vdev->vga->region[i].mem));
1722 }
1723 g_free(vdev->vga);
ba5e6bfa
PB
1724 }
1725}
1726
65501a74
AW
1727/*
1728 * General setup
1729 */
1730static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos)
1731{
88caf177
CF
1732 uint8_t tmp;
1733 uint16_t next = PCI_CONFIG_SPACE_SIZE;
65501a74
AW
1734
1735 for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp;
3fc1c182 1736 tmp = pdev->config[tmp + PCI_CAP_LIST_NEXT]) {
65501a74
AW
1737 if (tmp > pos && tmp < next) {
1738 next = tmp;
1739 }
1740 }
1741
1742 return next - pos;
1743}
1744
325ae8d5
CF
1745
1746static uint16_t vfio_ext_cap_max_size(const uint8_t *config, uint16_t pos)
1747{
1748 uint16_t tmp, next = PCIE_CONFIG_SPACE_SIZE;
1749
1750 for (tmp = PCI_CONFIG_SPACE_SIZE; tmp;
1751 tmp = PCI_EXT_CAP_NEXT(pci_get_long(config + tmp))) {
1752 if (tmp > pos && tmp < next) {
1753 next = tmp;
1754 }
1755 }
1756
1757 return next - pos;
1758}
1759
96adc5c7
AW
1760static void vfio_set_word_bits(uint8_t *buf, uint16_t val, uint16_t mask)
1761{
1762 pci_set_word(buf, (pci_get_word(buf) & ~mask) | val);
1763}
1764
9ee27d73 1765static void vfio_add_emulated_word(VFIOPCIDevice *vdev, int pos,
96adc5c7
AW
1766 uint16_t val, uint16_t mask)
1767{
1768 vfio_set_word_bits(vdev->pdev.config + pos, val, mask);
1769 vfio_set_word_bits(vdev->pdev.wmask + pos, ~mask, mask);
1770 vfio_set_word_bits(vdev->emulated_config_bits + pos, mask, mask);
1771}
1772
1773static void vfio_set_long_bits(uint8_t *buf, uint32_t val, uint32_t mask)
1774{
1775 pci_set_long(buf, (pci_get_long(buf) & ~mask) | val);
1776}
1777
9ee27d73 1778static void vfio_add_emulated_long(VFIOPCIDevice *vdev, int pos,
96adc5c7
AW
1779 uint32_t val, uint32_t mask)
1780{
1781 vfio_set_long_bits(vdev->pdev.config + pos, val, mask);
1782 vfio_set_long_bits(vdev->pdev.wmask + pos, ~mask, mask);
1783 vfio_set_long_bits(vdev->emulated_config_bits + pos, mask, mask);
1784}
1785
7ef165b9
EA
1786static int vfio_setup_pcie_cap(VFIOPCIDevice *vdev, int pos, uint8_t size,
1787 Error **errp)
96adc5c7
AW
1788{
1789 uint16_t flags;
1790 uint8_t type;
1791
1792 flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS);
1793 type = (flags & PCI_EXP_FLAGS_TYPE) >> 4;
1794
1795 if (type != PCI_EXP_TYPE_ENDPOINT &&
1796 type != PCI_EXP_TYPE_LEG_END &&
1797 type != PCI_EXP_TYPE_RC_END) {
1798
7ef165b9
EA
1799 error_setg(errp, "assignment of PCIe type 0x%x "
1800 "devices is not currently supported", type);
96adc5c7
AW
1801 return -EINVAL;
1802 }
1803
fd56e061
DG
1804 if (!pci_bus_is_express(pci_get_bus(&vdev->pdev))) {
1805 PCIBus *bus = pci_get_bus(&vdev->pdev);
0282abf0
AW
1806 PCIDevice *bridge;
1807
96adc5c7 1808 /*
0282abf0
AW
1809 * Traditionally PCI device assignment exposes the PCIe capability
1810 * as-is on non-express buses. The reason being that some drivers
1811 * simply assume that it's there, for example tg3. However when
1812 * we're running on a native PCIe machine type, like Q35, we need
1813 * to hide the PCIe capability. The reason for this is twofold;
1814 * first Windows guests get a Code 10 error when the PCIe capability
1815 * is exposed in this configuration. Therefore express devices won't
1816 * work at all unless they're attached to express buses in the VM.
1817 * Second, a native PCIe machine introduces the possibility of fine
1818 * granularity IOMMUs supporting both translation and isolation.
1819 * Guest code to discover the IOMMU visibility of a device, such as
1820 * IOMMU grouping code on Linux, is very aware of device types and
1821 * valid transitions between bus types. An express device on a non-
1822 * express bus is not a valid combination on bare metal systems.
1823 *
1824 * Drivers that require a PCIe capability to make the device
1825 * functional are simply going to need to have their devices placed
1826 * on a PCIe bus in the VM.
96adc5c7 1827 */
0282abf0
AW
1828 while (!pci_bus_is_root(bus)) {
1829 bridge = pci_bridge_get_device(bus);
fd56e061 1830 bus = pci_get_bus(bridge);
0282abf0
AW
1831 }
1832
1833 if (pci_bus_is_express(bus)) {
1834 return 0;
1835 }
1836
fd56e061 1837 } else if (pci_bus_is_root(pci_get_bus(&vdev->pdev))) {
96adc5c7
AW
1838 /*
1839 * On a Root Complex bus Endpoints become Root Complex Integrated
1840 * Endpoints, which changes the type and clears the LNK & LNK2 fields.
1841 */
1842 if (type == PCI_EXP_TYPE_ENDPOINT) {
1843 vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
1844 PCI_EXP_TYPE_RC_END << 4,
1845 PCI_EXP_FLAGS_TYPE);
1846
1847 /* Link Capabilities, Status, and Control goes away */
1848 if (size > PCI_EXP_LNKCTL) {
1849 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0);
1850 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
1851 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0);
1852
1853#ifndef PCI_EXP_LNKCAP2
1854#define PCI_EXP_LNKCAP2 44
1855#endif
1856#ifndef PCI_EXP_LNKSTA2
1857#define PCI_EXP_LNKSTA2 50
1858#endif
1859 /* Link 2 Capabilities, Status, and Control goes away */
1860 if (size > PCI_EXP_LNKCAP2) {
1861 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0);
1862 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0);
1863 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0);
1864 }
1865 }
1866
1867 } else if (type == PCI_EXP_TYPE_LEG_END) {
1868 /*
1869 * Legacy endpoints don't belong on the root complex. Windows
1870 * seems to be happier with devices if we skip the capability.
1871 */
1872 return 0;
1873 }
1874
1875 } else {
1876 /*
1877 * Convert Root Complex Integrated Endpoints to regular endpoints.
1878 * These devices don't support LNK/LNK2 capabilities, so make them up.
1879 */
1880 if (type == PCI_EXP_TYPE_RC_END) {
1881 vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
1882 PCI_EXP_TYPE_ENDPOINT << 4,
1883 PCI_EXP_FLAGS_TYPE);
1884 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP,
1885 PCI_EXP_LNK_MLW_1 | PCI_EXP_LNK_LS_25, ~0);
1886 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
1887 }
1888
1889 /* Mark the Link Status bits as emulated to allow virtual negotiation */
1890 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA,
1891 pci_get_word(vdev->pdev.config + pos +
1892 PCI_EXP_LNKSTA),
1893 PCI_EXP_LNKCAP_MLW | PCI_EXP_LNKCAP_SLS);
1894 }
1895
47985727
AW
1896 /*
1897 * Intel 82599 SR-IOV VFs report an invalid PCIe capability version 0
1898 * (Niantic errate #35) causing Windows to error with a Code 10 for the
1899 * device on Q35. Fixup any such devices to report version 1. If we
1900 * were to remove the capability entirely the guest would lose extended
1901 * config space.
1902 */
1903 if ((flags & PCI_EXP_FLAGS_VERS) == 0) {
1904 vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
1905 1, PCI_EXP_FLAGS_VERS);
1906 }
1907
9a7c2a59
MZ
1908 pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size,
1909 errp);
1910 if (pos < 0) {
1911 return pos;
96adc5c7
AW
1912 }
1913
9a7c2a59
MZ
1914 vdev->pdev.exp.exp_cap = pos;
1915
96adc5c7
AW
1916 return pos;
1917}
1918
9ee27d73 1919static void vfio_check_pcie_flr(VFIOPCIDevice *vdev, uint8_t pos)
befe5176
AW
1920{
1921 uint32_t cap = pci_get_long(vdev->pdev.config + pos + PCI_EXP_DEVCAP);
1922
1923 if (cap & PCI_EXP_DEVCAP_FLR) {
df92ee44 1924 trace_vfio_check_pcie_flr(vdev->vbasedev.name);
befe5176
AW
1925 vdev->has_flr = true;
1926 }
1927}
1928
9ee27d73 1929static void vfio_check_pm_reset(VFIOPCIDevice *vdev, uint8_t pos)
befe5176
AW
1930{
1931 uint16_t csr = pci_get_word(vdev->pdev.config + pos + PCI_PM_CTRL);
1932
1933 if (!(csr & PCI_PM_CTRL_NO_SOFT_RESET)) {
df92ee44 1934 trace_vfio_check_pm_reset(vdev->vbasedev.name);
befe5176
AW
1935 vdev->has_pm_reset = true;
1936 }
1937}
1938
9ee27d73 1939static void vfio_check_af_flr(VFIOPCIDevice *vdev, uint8_t pos)
befe5176
AW
1940{
1941 uint8_t cap = pci_get_byte(vdev->pdev.config + pos + PCI_AF_CAP);
1942
1943 if ((cap & PCI_AF_CAP_TP) && (cap & PCI_AF_CAP_FLR)) {
df92ee44 1944 trace_vfio_check_af_flr(vdev->vbasedev.name);
befe5176
AW
1945 vdev->has_flr = true;
1946 }
1947}
1948
7ef165b9 1949static int vfio_add_std_cap(VFIOPCIDevice *vdev, uint8_t pos, Error **errp)
65501a74
AW
1950{
1951 PCIDevice *pdev = &vdev->pdev;
1952 uint8_t cap_id, next, size;
1953 int ret;
1954
1955 cap_id = pdev->config[pos];
3fc1c182 1956 next = pdev->config[pos + PCI_CAP_LIST_NEXT];
65501a74
AW
1957
1958 /*
1959 * If it becomes important to configure capabilities to their actual
1960 * size, use this as the default when it's something we don't recognize.
1961 * Since QEMU doesn't actually handle many of the config accesses,
1962 * exact size doesn't seem worthwhile.
1963 */
1964 size = vfio_std_cap_max_size(pdev, pos);
1965
1966 /*
1967 * pci_add_capability always inserts the new capability at the head
1968 * of the chain. Therefore to end up with a chain that matches the
1969 * physical device, we insert from the end by making this recursive.
3fc1c182 1970 * This is also why we pre-calculate size above as cached config space
65501a74
AW
1971 * will be changed as we unwind the stack.
1972 */
1973 if (next) {
7ef165b9 1974 ret = vfio_add_std_cap(vdev, next, errp);
65501a74 1975 if (ret) {
5b31c822 1976 return ret;
65501a74
AW
1977 }
1978 } else {
96adc5c7
AW
1979 /* Begin the rebuild, use QEMU emulated list bits */
1980 pdev->config[PCI_CAPABILITY_LIST] = 0;
1981 vdev->emulated_config_bits[PCI_CAPABILITY_LIST] = 0xff;
1982 vdev->emulated_config_bits[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
e3f79f3b
AW
1983
1984 ret = vfio_add_virt_caps(vdev, errp);
1985 if (ret) {
1986 return ret;
1987 }
65501a74
AW
1988 }
1989
e3f79f3b
AW
1990 /* Scale down size, esp in case virt caps were added above */
1991 size = MIN(size, vfio_std_cap_max_size(pdev, pos));
1992
96adc5c7 1993 /* Use emulated next pointer to allow dropping caps */
3fc1c182 1994 pci_set_byte(vdev->emulated_config_bits + pos + PCI_CAP_LIST_NEXT, 0xff);
96adc5c7 1995
65501a74
AW
1996 switch (cap_id) {
1997 case PCI_CAP_ID_MSI:
7ef165b9 1998 ret = vfio_msi_setup(vdev, pos, errp);
65501a74 1999 break;
96adc5c7 2000 case PCI_CAP_ID_EXP:
befe5176 2001 vfio_check_pcie_flr(vdev, pos);
7ef165b9 2002 ret = vfio_setup_pcie_cap(vdev, pos, size, errp);
96adc5c7 2003 break;
65501a74 2004 case PCI_CAP_ID_MSIX:
7ef165b9 2005 ret = vfio_msix_setup(vdev, pos, errp);
65501a74 2006 break;
ba661818 2007 case PCI_CAP_ID_PM:
befe5176 2008 vfio_check_pm_reset(vdev, pos);
ba661818 2009 vdev->pm_cap = pos;
27841278 2010 ret = pci_add_capability(pdev, cap_id, pos, size, errp);
befe5176
AW
2011 break;
2012 case PCI_CAP_ID_AF:
2013 vfio_check_af_flr(vdev, pos);
27841278 2014 ret = pci_add_capability(pdev, cap_id, pos, size, errp);
befe5176 2015 break;
65501a74 2016 default:
27841278 2017 ret = pci_add_capability(pdev, cap_id, pos, size, errp);
65501a74
AW
2018 break;
2019 }
5b31c822 2020
65501a74 2021 if (ret < 0) {
7ef165b9
EA
2022 error_prepend(errp,
2023 "failed to add PCI capability 0x%x[0x%x]@0x%x: ",
2024 cap_id, size, pos);
65501a74
AW
2025 return ret;
2026 }
2027
2028 return 0;
2029}
2030
7ef165b9 2031static void vfio_add_ext_cap(VFIOPCIDevice *vdev)
325ae8d5
CF
2032{
2033 PCIDevice *pdev = &vdev->pdev;
2034 uint32_t header;
2035 uint16_t cap_id, next, size;
2036 uint8_t cap_ver;
2037 uint8_t *config;
2038
e37dac06 2039 /* Only add extended caps if we have them and the guest can see them */
fd56e061 2040 if (!pci_is_express(pdev) || !pci_bus_is_express(pci_get_bus(pdev)) ||
e37dac06 2041 !pci_get_long(pdev->config + PCI_CONFIG_SPACE_SIZE)) {
7ef165b9 2042 return;
e37dac06
AW
2043 }
2044
325ae8d5
CF
2045 /*
2046 * pcie_add_capability always inserts the new capability at the tail
2047 * of the chain. Therefore to end up with a chain that matches the
2048 * physical device, we cache the config space to avoid overwriting
2049 * the original config space when we parse the extended capabilities.
2050 */
2051 config = g_memdup(pdev->config, vdev->config_size);
2052
e37dac06
AW
2053 /*
2054 * Extended capabilities are chained with each pointing to the next, so we
2055 * can drop anything other than the head of the chain simply by modifying
d0d1cd70
AW
2056 * the previous next pointer. Seed the head of the chain here such that
2057 * we can simply skip any capabilities we want to drop below, regardless
2058 * of their position in the chain. If this stub capability still exists
2059 * after we add the capabilities we want to expose, update the capability
2060 * ID to zero. Note that we cannot seed with the capability header being
2061 * zero as this conflicts with definition of an absent capability chain
2062 * and prevents capabilities beyond the head of the list from being added.
2063 * By replacing the dummy capability ID with zero after walking the device
2064 * chain, we also transparently mark extended capabilities as absent if
2065 * no capabilities were added. Note that the PCIe spec defines an absence
2066 * of extended capabilities to be determined by a value of zero for the
2067 * capability ID, version, AND next pointer. A non-zero next pointer
2068 * should be sufficient to indicate additional capabilities are present,
2069 * which will occur if we call pcie_add_capability() below. The entire
2070 * first dword is emulated to support this.
2071 *
2072 * NB. The kernel side does similar masking, so be prepared that our
2073 * view of the device may also contain a capability ID zero in the head
2074 * of the chain. Skip it for the same reason that we cannot seed the
2075 * chain with a zero capability.
e37dac06
AW
2076 */
2077 pci_set_long(pdev->config + PCI_CONFIG_SPACE_SIZE,
2078 PCI_EXT_CAP(0xFFFF, 0, 0));
2079 pci_set_long(pdev->wmask + PCI_CONFIG_SPACE_SIZE, 0);
2080 pci_set_long(vdev->emulated_config_bits + PCI_CONFIG_SPACE_SIZE, ~0);
2081
325ae8d5
CF
2082 for (next = PCI_CONFIG_SPACE_SIZE; next;
2083 next = PCI_EXT_CAP_NEXT(pci_get_long(config + next))) {
2084 header = pci_get_long(config + next);
2085 cap_id = PCI_EXT_CAP_ID(header);
2086 cap_ver = PCI_EXT_CAP_VER(header);
2087
2088 /*
2089 * If it becomes important to configure extended capabilities to their
2090 * actual size, use this as the default when it's something we don't
2091 * recognize. Since QEMU doesn't actually handle many of the config
2092 * accesses, exact size doesn't seem worthwhile.
2093 */
2094 size = vfio_ext_cap_max_size(config, next);
2095
325ae8d5
CF
2096 /* Use emulated next pointer to allow dropping extended caps */
2097 pci_long_test_and_set_mask(vdev->emulated_config_bits + next,
2098 PCI_EXT_CAP_NEXT_MASK);
e37dac06
AW
2099
2100 switch (cap_id) {
d0d1cd70 2101 case 0: /* kernel masked capability */
e37dac06 2102 case PCI_EXT_CAP_ID_SRIOV: /* Read-only VF BARs confuse OVMF */
383a7af7 2103 case PCI_EXT_CAP_ID_ARI: /* XXX Needs next function virtualization */
e37dac06
AW
2104 trace_vfio_add_ext_cap_dropped(vdev->vbasedev.name, cap_id, next);
2105 break;
2106 default:
2107 pcie_add_capability(pdev, cap_id, cap_ver, next, size);
2108 }
2109
2110 }
2111
2112 /* Cleanup chain head ID if necessary */
2113 if (pci_get_word(pdev->config + PCI_CONFIG_SPACE_SIZE) == 0xFFFF) {
2114 pci_set_word(pdev->config + PCI_CONFIG_SPACE_SIZE, 0);
325ae8d5
CF
2115 }
2116
2117 g_free(config);
7ef165b9 2118 return;
325ae8d5
CF
2119}
2120
7ef165b9 2121static int vfio_add_capabilities(VFIOPCIDevice *vdev, Error **errp)
65501a74
AW
2122{
2123 PCIDevice *pdev = &vdev->pdev;
325ae8d5 2124 int ret;
65501a74
AW
2125
2126 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
2127 !pdev->config[PCI_CAPABILITY_LIST]) {
2128 return 0; /* Nothing to add */
2129 }
2130
7ef165b9 2131 ret = vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST], errp);
325ae8d5
CF
2132 if (ret) {
2133 return ret;
2134 }
2135
7ef165b9
EA
2136 vfio_add_ext_cap(vdev);
2137 return 0;
65501a74
AW
2138}
2139
9ee27d73 2140static void vfio_pci_pre_reset(VFIOPCIDevice *vdev)
f16f39c3
AW
2141{
2142 PCIDevice *pdev = &vdev->pdev;
2143 uint16_t cmd;
2144
2145 vfio_disable_interrupts(vdev);
2146
2147 /* Make sure the device is in D0 */
2148 if (vdev->pm_cap) {
2149 uint16_t pmcsr;
2150 uint8_t state;
2151
2152 pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2153 state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2154 if (state) {
2155 pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
2156 vfio_pci_write_config(pdev, vdev->pm_cap + PCI_PM_CTRL, pmcsr, 2);
2157 /* vfio handles the necessary delay here */
2158 pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2159 state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2160 if (state) {
4e505ddd 2161 error_report("vfio: Unable to power on device, stuck in D%d",
f16f39c3
AW
2162 state);
2163 }
2164 }
2165 }
2166
2167 /*
2168 * Stop any ongoing DMA by disconecting I/O, MMIO, and bus master.
2169 * Also put INTx Disable in known state.
2170 */
2171 cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2);
2172 cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
2173 PCI_COMMAND_INTX_DISABLE);
2174 vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2);
2175}
2176
9ee27d73 2177static void vfio_pci_post_reset(VFIOPCIDevice *vdev)
f16f39c3 2178{
7dfb3424 2179 Error *err = NULL;
a52a4c47 2180 int nr;
7dfb3424
EA
2181
2182 vfio_intx_enable(vdev, &err);
2183 if (err) {
2184 error_reportf_err(err, ERR_PREFIX, vdev->vbasedev.name);
2185 }
a52a4c47
IY
2186
2187 for (nr = 0; nr < PCI_NUM_REGIONS - 1; ++nr) {
2188 off_t addr = vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr);
2189 uint32_t val = 0;
2190 uint32_t len = sizeof(val);
2191
2192 if (pwrite(vdev->vbasedev.fd, &val, len, addr) != len) {
2193 error_report("%s(%s) reset bar %d failed: %m", __func__,
2194 vdev->vbasedev.name, nr);
2195 }
2196 }
f16f39c3
AW
2197}
2198
7df9381b 2199static bool vfio_pci_host_match(PCIHostDeviceAddress *addr, const char *name)
f16f39c3 2200{
7df9381b
AW
2201 char tmp[13];
2202
2203 sprintf(tmp, "%04x:%02x:%02x.%1x", addr->domain,
2204 addr->bus, addr->slot, addr->function);
2205
2206 return (strcmp(tmp, name) == 0);
f16f39c3
AW
2207}
2208
9ee27d73 2209static int vfio_pci_hot_reset(VFIOPCIDevice *vdev, bool single)
f16f39c3
AW
2210{
2211 VFIOGroup *group;
2212 struct vfio_pci_hot_reset_info *info;
2213 struct vfio_pci_dependent_device *devices;
2214 struct vfio_pci_hot_reset *reset;
2215 int32_t *fds;
2216 int ret, i, count;
2217 bool multi = false;
2218
df92ee44 2219 trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
f16f39c3 2220
893bfc3c
C
2221 if (!single) {
2222 vfio_pci_pre_reset(vdev);
2223 }
b47d8efa 2224 vdev->vbasedev.needs_reset = false;
f16f39c3
AW
2225
2226 info = g_malloc0(sizeof(*info));
2227 info->argsz = sizeof(*info);
2228
5546a621 2229 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
f16f39c3
AW
2230 if (ret && errno != ENOSPC) {
2231 ret = -errno;
2232 if (!vdev->has_pm_reset) {
7df9381b
AW
2233 error_report("vfio: Cannot reset device %s, "
2234 "no available reset mechanism.", vdev->vbasedev.name);
f16f39c3
AW
2235 }
2236 goto out_single;
2237 }
2238
2239 count = info->count;
2240 info = g_realloc(info, sizeof(*info) + (count * sizeof(*devices)));
2241 info->argsz = sizeof(*info) + (count * sizeof(*devices));
2242 devices = &info->devices[0];
2243
5546a621 2244 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
f16f39c3
AW
2245 if (ret) {
2246 ret = -errno;
2247 error_report("vfio: hot reset info failed: %m");
2248 goto out_single;
2249 }
2250
df92ee44 2251 trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
f16f39c3
AW
2252
2253 /* Verify that we have all the groups required */
2254 for (i = 0; i < info->count; i++) {
2255 PCIHostDeviceAddress host;
9ee27d73 2256 VFIOPCIDevice *tmp;
b47d8efa 2257 VFIODevice *vbasedev_iter;
f16f39c3
AW
2258
2259 host.domain = devices[i].segment;
2260 host.bus = devices[i].bus;
2261 host.slot = PCI_SLOT(devices[i].devfn);
2262 host.function = PCI_FUNC(devices[i].devfn);
2263
385f57cf 2264 trace_vfio_pci_hot_reset_dep_devices(host.domain,
f16f39c3
AW
2265 host.bus, host.slot, host.function, devices[i].group_id);
2266
7df9381b 2267 if (vfio_pci_host_match(&host, vdev->vbasedev.name)) {
f16f39c3
AW
2268 continue;
2269 }
2270
62356b72 2271 QLIST_FOREACH(group, &vfio_group_list, next) {
f16f39c3
AW
2272 if (group->groupid == devices[i].group_id) {
2273 break;
2274 }
2275 }
2276
2277 if (!group) {
2278 if (!vdev->has_pm_reset) {
df92ee44 2279 error_report("vfio: Cannot reset device %s, "
f16f39c3 2280 "depends on group %d which is not owned.",
df92ee44 2281 vdev->vbasedev.name, devices[i].group_id);
f16f39c3
AW
2282 }
2283 ret = -EPERM;
2284 goto out;
2285 }
2286
2287 /* Prep dependent devices for reset and clear our marker. */
b47d8efa 2288 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
7da624e2
AW
2289 if (!vbasedev_iter->dev->realized ||
2290 vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
b47d8efa
EA
2291 continue;
2292 }
2293 tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
7df9381b 2294 if (vfio_pci_host_match(&host, tmp->vbasedev.name)) {
f16f39c3 2295 if (single) {
f16f39c3
AW
2296 ret = -EINVAL;
2297 goto out_single;
2298 }
2299 vfio_pci_pre_reset(tmp);
b47d8efa 2300 tmp->vbasedev.needs_reset = false;
f16f39c3
AW
2301 multi = true;
2302 break;
2303 }
2304 }
2305 }
2306
2307 if (!single && !multi) {
f16f39c3
AW
2308 ret = -EINVAL;
2309 goto out_single;
2310 }
2311
2312 /* Determine how many group fds need to be passed */
2313 count = 0;
62356b72 2314 QLIST_FOREACH(group, &vfio_group_list, next) {
f16f39c3
AW
2315 for (i = 0; i < info->count; i++) {
2316 if (group->groupid == devices[i].group_id) {
2317 count++;
2318 break;
2319 }
2320 }
2321 }
2322
2323 reset = g_malloc0(sizeof(*reset) + (count * sizeof(*fds)));
2324 reset->argsz = sizeof(*reset) + (count * sizeof(*fds));
2325 fds = &reset->group_fds[0];
2326
2327 /* Fill in group fds */
62356b72 2328 QLIST_FOREACH(group, &vfio_group_list, next) {
f16f39c3
AW
2329 for (i = 0; i < info->count; i++) {
2330 if (group->groupid == devices[i].group_id) {
2331 fds[reset->count++] = group->fd;
2332 break;
2333 }
2334 }
2335 }
2336
2337 /* Bus reset! */
5546a621 2338 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
f16f39c3
AW
2339 g_free(reset);
2340
df92ee44 2341 trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
385f57cf 2342 ret ? "%m" : "Success");
f16f39c3
AW
2343
2344out:
2345 /* Re-enable INTx on affected devices */
2346 for (i = 0; i < info->count; i++) {
2347 PCIHostDeviceAddress host;
9ee27d73 2348 VFIOPCIDevice *tmp;
b47d8efa 2349 VFIODevice *vbasedev_iter;
f16f39c3
AW
2350
2351 host.domain = devices[i].segment;
2352 host.bus = devices[i].bus;
2353 host.slot = PCI_SLOT(devices[i].devfn);
2354 host.function = PCI_FUNC(devices[i].devfn);
2355
7df9381b 2356 if (vfio_pci_host_match(&host, vdev->vbasedev.name)) {
f16f39c3
AW
2357 continue;
2358 }
2359
62356b72 2360 QLIST_FOREACH(group, &vfio_group_list, next) {
f16f39c3
AW
2361 if (group->groupid == devices[i].group_id) {
2362 break;
2363 }
2364 }
2365
2366 if (!group) {
2367 break;
2368 }
2369
b47d8efa 2370 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
7da624e2
AW
2371 if (!vbasedev_iter->dev->realized ||
2372 vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
b47d8efa
EA
2373 continue;
2374 }
2375 tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
7df9381b 2376 if (vfio_pci_host_match(&host, tmp->vbasedev.name)) {
f16f39c3
AW
2377 vfio_pci_post_reset(tmp);
2378 break;
2379 }
2380 }
2381 }
2382out_single:
893bfc3c
C
2383 if (!single) {
2384 vfio_pci_post_reset(vdev);
2385 }
f16f39c3
AW
2386 g_free(info);
2387
2388 return ret;
2389}
2390
2391/*
2392 * We want to differentiate hot reset of mulitple in-use devices vs hot reset
2393 * of a single in-use device. VFIO_DEVICE_RESET will already handle the case
2394 * of doing hot resets when there is only a single device per bus. The in-use
2395 * here refers to how many VFIODevices are affected. A hot reset that affects
2396 * multiple devices, but only a single in-use device, means that we can call
2397 * it from our bus ->reset() callback since the extent is effectively a single
2398 * device. This allows us to make use of it in the hotplug path. When there
2399 * are multiple in-use devices, we can only trigger the hot reset during a
2400 * system reset and thus from our reset handler. We separate _one vs _multi
2401 * here so that we don't overlap and do a double reset on the system reset
2402 * path where both our reset handler and ->reset() callback are used. Calling
2403 * _one() will only do a hot reset for the one in-use devices case, calling
2404 * _multi() will do nothing if a _one() would have been sufficient.
2405 */
9ee27d73 2406static int vfio_pci_hot_reset_one(VFIOPCIDevice *vdev)
f16f39c3
AW
2407{
2408 return vfio_pci_hot_reset(vdev, true);
2409}
2410
b47d8efa 2411static int vfio_pci_hot_reset_multi(VFIODevice *vbasedev)
f16f39c3 2412{
b47d8efa 2413 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
f16f39c3
AW
2414 return vfio_pci_hot_reset(vdev, false);
2415}
2416
b47d8efa
EA
2417static void vfio_pci_compute_needs_reset(VFIODevice *vbasedev)
2418{
2419 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
2420 if (!vbasedev->reset_works || (!vdev->has_flr && vdev->has_pm_reset)) {
2421 vbasedev->needs_reset = true;
2422 }
2423}
2424
2425static VFIODeviceOps vfio_pci_ops = {
2426 .vfio_compute_needs_reset = vfio_pci_compute_needs_reset,
2427 .vfio_hot_reset_multi = vfio_pci_hot_reset_multi,
870cb6f1 2428 .vfio_eoi = vfio_intx_eoi,
b47d8efa
EA
2429};
2430
cde4279b 2431int vfio_populate_vga(VFIOPCIDevice *vdev, Error **errp)
e593c021
AW
2432{
2433 VFIODevice *vbasedev = &vdev->vbasedev;
2434 struct vfio_region_info *reg_info;
2435 int ret;
2436
4225f2b6
AW
2437 ret = vfio_get_region_info(vbasedev, VFIO_PCI_VGA_REGION_INDEX, &reg_info);
2438 if (ret) {
cde4279b
EA
2439 error_setg_errno(errp, -ret,
2440 "failed getting region info for VGA region index %d",
2441 VFIO_PCI_VGA_REGION_INDEX);
4225f2b6
AW
2442 return ret;
2443 }
e593c021 2444
4225f2b6
AW
2445 if (!(reg_info->flags & VFIO_REGION_INFO_FLAG_READ) ||
2446 !(reg_info->flags & VFIO_REGION_INFO_FLAG_WRITE) ||
2447 reg_info->size < 0xbffff + 1) {
cde4279b
EA
2448 error_setg(errp, "unexpected VGA info, flags 0x%lx, size 0x%lx",
2449 (unsigned long)reg_info->flags,
2450 (unsigned long)reg_info->size);
4225f2b6
AW
2451 g_free(reg_info);
2452 return -EINVAL;
2453 }
e593c021 2454
4225f2b6 2455 vdev->vga = g_new0(VFIOVGA, 1);
e593c021 2456
4225f2b6
AW
2457 vdev->vga->fd_offset = reg_info->offset;
2458 vdev->vga->fd = vdev->vbasedev.fd;
e593c021 2459
4225f2b6 2460 g_free(reg_info);
e593c021 2461
4225f2b6
AW
2462 vdev->vga->region[QEMU_PCI_VGA_MEM].offset = QEMU_PCI_VGA_MEM_BASE;
2463 vdev->vga->region[QEMU_PCI_VGA_MEM].nr = QEMU_PCI_VGA_MEM;
2464 QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_MEM].quirks);
e593c021 2465
182bca45
AW
2466 memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_MEM].mem,
2467 OBJECT(vdev), &vfio_vga_ops,
2468 &vdev->vga->region[QEMU_PCI_VGA_MEM],
2469 "vfio-vga-mmio@0xa0000",
2470 QEMU_PCI_VGA_MEM_SIZE);
2471
4225f2b6
AW
2472 vdev->vga->region[QEMU_PCI_VGA_IO_LO].offset = QEMU_PCI_VGA_IO_LO_BASE;
2473 vdev->vga->region[QEMU_PCI_VGA_IO_LO].nr = QEMU_PCI_VGA_IO_LO;
2474 QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].quirks);
e593c021 2475
182bca45
AW
2476 memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem,
2477 OBJECT(vdev), &vfio_vga_ops,
2478 &vdev->vga->region[QEMU_PCI_VGA_IO_LO],
2479 "vfio-vga-io@0x3b0",
2480 QEMU_PCI_VGA_IO_LO_SIZE);
2481
4225f2b6
AW
2482 vdev->vga->region[QEMU_PCI_VGA_IO_HI].offset = QEMU_PCI_VGA_IO_HI_BASE;
2483 vdev->vga->region[QEMU_PCI_VGA_IO_HI].nr = QEMU_PCI_VGA_IO_HI;
2484 QLIST_INIT(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].quirks);
e593c021 2485
182bca45
AW
2486 memory_region_init_io(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem,
2487 OBJECT(vdev), &vfio_vga_ops,
2488 &vdev->vga->region[QEMU_PCI_VGA_IO_HI],
2489 "vfio-vga-io@0x3c0",
2490 QEMU_PCI_VGA_IO_HI_SIZE);
2491
2492 pci_register_vga(&vdev->pdev, &vdev->vga->region[QEMU_PCI_VGA_MEM].mem,
2493 &vdev->vga->region[QEMU_PCI_VGA_IO_LO].mem,
2494 &vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem);
2495
e593c021
AW
2496 return 0;
2497}
2498
e04cff9d 2499static void vfio_populate_device(VFIOPCIDevice *vdev, Error **errp)
65501a74 2500{
217e9fdc 2501 VFIODevice *vbasedev = &vdev->vbasedev;
46900226 2502 struct vfio_region_info *reg_info;
7b4b0e9e 2503 struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };
d13dd2d7 2504 int i, ret = -1;
65501a74
AW
2505
2506 /* Sanity check device */
d13dd2d7 2507 if (!(vbasedev->flags & VFIO_DEVICE_FLAGS_PCI)) {
2312d907 2508 error_setg(errp, "this isn't a PCI device");
e04cff9d 2509 return;
65501a74
AW
2510 }
2511
d13dd2d7 2512 if (vbasedev->num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) {
2312d907
EA
2513 error_setg(errp, "unexpected number of io regions %u",
2514 vbasedev->num_regions);
e04cff9d 2515 return;
65501a74
AW
2516 }
2517
d13dd2d7 2518 if (vbasedev->num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) {
2312d907 2519 error_setg(errp, "unexpected number of irqs %u", vbasedev->num_irqs);
e04cff9d 2520 return;
65501a74
AW
2521 }
2522
2523 for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
db0da029
AW
2524 char *name = g_strdup_printf("%s BAR %d", vbasedev->name, i);
2525
2526 ret = vfio_region_setup(OBJECT(vdev), vbasedev,
2527 &vdev->bars[i].region, i, name);
2528 g_free(name);
2529
65501a74 2530 if (ret) {
2312d907 2531 error_setg_errno(errp, -ret, "failed to get region %d info", i);
e04cff9d 2532 return;
65501a74
AW
2533 }
2534
7076eabc 2535 QLIST_INIT(&vdev->bars[i].quirks);
46900226 2536 }
65501a74 2537
46900226
AW
2538 ret = vfio_get_region_info(vbasedev,
2539 VFIO_PCI_CONFIG_REGION_INDEX, &reg_info);
65501a74 2540 if (ret) {
2312d907 2541 error_setg_errno(errp, -ret, "failed to get config info");
e04cff9d 2542 return;
65501a74
AW
2543 }
2544
d13dd2d7 2545 trace_vfio_populate_device_config(vdev->vbasedev.name,
46900226
AW
2546 (unsigned long)reg_info->size,
2547 (unsigned long)reg_info->offset,
2548 (unsigned long)reg_info->flags);
65501a74 2549
46900226 2550 vdev->config_size = reg_info->size;
6a659bbf
AW
2551 if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) {
2552 vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS;
2553 }
46900226
AW
2554 vdev->config_offset = reg_info->offset;
2555
2556 g_free(reg_info);
65501a74 2557
e593c021 2558 if (vdev->features & VFIO_FEATURE_ENABLE_VGA) {
2312d907 2559 ret = vfio_populate_vga(vdev, errp);
f15689c7 2560 if (ret) {
2312d907 2561 error_append_hint(errp, "device does not support "
cde4279b 2562 "requested feature x-vga\n");
e04cff9d 2563 return;
f15689c7 2564 }
f15689c7 2565 }
47cbe50c 2566
7b4b0e9e
VMP
2567 irq_info.index = VFIO_PCI_ERR_IRQ_INDEX;
2568
5546a621 2569 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);
7b4b0e9e
VMP
2570 if (ret) {
2571 /* This can fail for an old kernel or legacy PCI dev */
d13dd2d7 2572 trace_vfio_populate_device_get_irq_info_failure();
7b4b0e9e
VMP
2573 } else if (irq_info.count == 1) {
2574 vdev->pci_aer = true;
2575 } else {
2312d907 2576 error_report(WARN_PREFIX
8fbf47c3 2577 "Could not enable error recovery for the device",
df92ee44 2578 vbasedev->name);
7b4b0e9e 2579 }
d13dd2d7
EA
2580}
2581
9ee27d73 2582static void vfio_put_device(VFIOPCIDevice *vdev)
65501a74 2583{
462037c9 2584 g_free(vdev->vbasedev.name);
db0da029
AW
2585 g_free(vdev->msix);
2586
d13dd2d7 2587 vfio_put_base_device(&vdev->vbasedev);
65501a74
AW
2588}
2589
7b4b0e9e
VMP
2590static void vfio_err_notifier_handler(void *opaque)
2591{
9ee27d73 2592 VFIOPCIDevice *vdev = opaque;
7b4b0e9e
VMP
2593
2594 if (!event_notifier_test_and_clear(&vdev->err_notifier)) {
2595 return;
2596 }
2597
2598 /*
2599 * TBD. Retrieve the error details and decide what action
2600 * needs to be taken. One of the actions could be to pass
2601 * the error to the guest and have the guest driver recover
2602 * from the error. This requires that PCIe capabilities be
2603 * exposed to the guest. For now, we just terminate the
2604 * guest to contain the error.
2605 */
2606
7df9381b 2607 error_report("%s(%s) Unrecoverable error detected. Please collect any data possible and then kill the guest", __func__, vdev->vbasedev.name);
7b4b0e9e 2608
ba29776f 2609 vm_stop(RUN_STATE_INTERNAL_ERROR);
7b4b0e9e
VMP
2610}
2611
2612/*
2613 * Registers error notifier for devices supporting error recovery.
2614 * If we encounter a failure in this function, we report an error
2615 * and continue after disabling error recovery support for the
2616 * device.
2617 */
9ee27d73 2618static void vfio_register_err_notifier(VFIOPCIDevice *vdev)
7b4b0e9e
VMP
2619{
2620 int ret;
2621 int argsz;
2622 struct vfio_irq_set *irq_set;
2623 int32_t *pfd;
2624
2625 if (!vdev->pci_aer) {
2626 return;
2627 }
2628
2629 if (event_notifier_init(&vdev->err_notifier, 0)) {
8fbf47c3 2630 error_report("vfio: Unable to init event notifier for error detection");
7b4b0e9e
VMP
2631 vdev->pci_aer = false;
2632 return;
2633 }
2634
2635 argsz = sizeof(*irq_set) + sizeof(*pfd);
2636
2637 irq_set = g_malloc0(argsz);
2638 irq_set->argsz = argsz;
2639 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
2640 VFIO_IRQ_SET_ACTION_TRIGGER;
2641 irq_set->index = VFIO_PCI_ERR_IRQ_INDEX;
2642 irq_set->start = 0;
2643 irq_set->count = 1;
2644 pfd = (int32_t *)&irq_set->data;
2645
2646 *pfd = event_notifier_get_fd(&vdev->err_notifier);
2647 qemu_set_fd_handler(*pfd, vfio_err_notifier_handler, NULL, vdev);
2648
5546a621 2649 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
7b4b0e9e 2650 if (ret) {
8fbf47c3 2651 error_report("vfio: Failed to set up error notification");
7b4b0e9e
VMP
2652 qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
2653 event_notifier_cleanup(&vdev->err_notifier);
2654 vdev->pci_aer = false;
2655 }
2656 g_free(irq_set);
2657}
2658
9ee27d73 2659static void vfio_unregister_err_notifier(VFIOPCIDevice *vdev)
7b4b0e9e
VMP
2660{
2661 int argsz;
2662 struct vfio_irq_set *irq_set;
2663 int32_t *pfd;
2664 int ret;
2665
2666 if (!vdev->pci_aer) {
2667 return;
2668 }
2669
2670 argsz = sizeof(*irq_set) + sizeof(*pfd);
2671
2672 irq_set = g_malloc0(argsz);
2673 irq_set->argsz = argsz;
2674 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
2675 VFIO_IRQ_SET_ACTION_TRIGGER;
2676 irq_set->index = VFIO_PCI_ERR_IRQ_INDEX;
2677 irq_set->start = 0;
2678 irq_set->count = 1;
2679 pfd = (int32_t *)&irq_set->data;
2680 *pfd = -1;
2681
5546a621 2682 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
7b4b0e9e 2683 if (ret) {
8fbf47c3 2684 error_report("vfio: Failed to de-assign error fd: %m");
7b4b0e9e
VMP
2685 }
2686 g_free(irq_set);
2687 qemu_set_fd_handler(event_notifier_get_fd(&vdev->err_notifier),
2688 NULL, NULL, vdev);
2689 event_notifier_cleanup(&vdev->err_notifier);
2690}
2691
47cbe50c
AW
2692static void vfio_req_notifier_handler(void *opaque)
2693{
2694 VFIOPCIDevice *vdev = opaque;
35c7cb4c 2695 Error *err = NULL;
47cbe50c
AW
2696
2697 if (!event_notifier_test_and_clear(&vdev->req_notifier)) {
2698 return;
2699 }
2700
35c7cb4c
AW
2701 qdev_unplug(&vdev->pdev.qdev, &err);
2702 if (err) {
2703 error_reportf_err(err, WARN_PREFIX, vdev->vbasedev.name);
2704 }
47cbe50c
AW
2705}
2706
2707static void vfio_register_req_notifier(VFIOPCIDevice *vdev)
2708{
2709 struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info),
2710 .index = VFIO_PCI_REQ_IRQ_INDEX };
2711 int argsz;
2712 struct vfio_irq_set *irq_set;
2713 int32_t *pfd;
2714
2715 if (!(vdev->features & VFIO_FEATURE_ENABLE_REQ)) {
2716 return;
2717 }
2718
2719 if (ioctl(vdev->vbasedev.fd,
2720 VFIO_DEVICE_GET_IRQ_INFO, &irq_info) < 0 || irq_info.count < 1) {
2721 return;
2722 }
2723
2724 if (event_notifier_init(&vdev->req_notifier, 0)) {
2725 error_report("vfio: Unable to init event notifier for device request");
2726 return;
2727 }
2728
2729 argsz = sizeof(*irq_set) + sizeof(*pfd);
2730
2731 irq_set = g_malloc0(argsz);
2732 irq_set->argsz = argsz;
2733 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
2734 VFIO_IRQ_SET_ACTION_TRIGGER;
2735 irq_set->index = VFIO_PCI_REQ_IRQ_INDEX;
2736 irq_set->start = 0;
2737 irq_set->count = 1;
2738 pfd = (int32_t *)&irq_set->data;
2739
2740 *pfd = event_notifier_get_fd(&vdev->req_notifier);
2741 qemu_set_fd_handler(*pfd, vfio_req_notifier_handler, NULL, vdev);
2742
2743 if (ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set)) {
2744 error_report("vfio: Failed to set up device request notification");
2745 qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
2746 event_notifier_cleanup(&vdev->req_notifier);
2747 } else {
2748 vdev->req_enabled = true;
2749 }
2750
2751 g_free(irq_set);
2752}
2753
2754static void vfio_unregister_req_notifier(VFIOPCIDevice *vdev)
2755{
2756 int argsz;
2757 struct vfio_irq_set *irq_set;
2758 int32_t *pfd;
2759
2760 if (!vdev->req_enabled) {
2761 return;
2762 }
2763
2764 argsz = sizeof(*irq_set) + sizeof(*pfd);
2765
2766 irq_set = g_malloc0(argsz);
2767 irq_set->argsz = argsz;
2768 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
2769 VFIO_IRQ_SET_ACTION_TRIGGER;
2770 irq_set->index = VFIO_PCI_REQ_IRQ_INDEX;
2771 irq_set->start = 0;
2772 irq_set->count = 1;
2773 pfd = (int32_t *)&irq_set->data;
2774 *pfd = -1;
2775
2776 if (ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set)) {
2777 error_report("vfio: Failed to de-assign device request fd: %m");
2778 }
2779 g_free(irq_set);
2780 qemu_set_fd_handler(event_notifier_get_fd(&vdev->req_notifier),
2781 NULL, NULL, vdev);
2782 event_notifier_cleanup(&vdev->req_notifier);
2783
2784 vdev->req_enabled = false;
2785}
2786
1a22aca1 2787static void vfio_realize(PCIDevice *pdev, Error **errp)
65501a74 2788{
b47d8efa
EA
2789 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
2790 VFIODevice *vbasedev_iter;
65501a74 2791 VFIOGroup *group;
7df9381b 2792 char *tmp, group_path[PATH_MAX], *group_name;
ec3bcf42 2793 Error *err = NULL;
65501a74
AW
2794 ssize_t len;
2795 struct stat st;
2796 int groupid;
581406e0 2797 int i, ret;
65501a74 2798
7df9381b 2799 if (!vdev->vbasedev.sysfsdev) {
4a946268
EA
2800 if (!(~vdev->host.domain || ~vdev->host.bus ||
2801 ~vdev->host.slot || ~vdev->host.function)) {
2802 error_setg(errp, "No provided host device");
6e4e6f0d
DJS
2803 error_append_hint(errp, "Use -device vfio-pci,host=DDDD:BB:DD.F "
2804 "or -device vfio-pci,sysfsdev=PATH_TO_DEVICE\n");
4a946268
EA
2805 return;
2806 }
7df9381b
AW
2807 vdev->vbasedev.sysfsdev =
2808 g_strdup_printf("/sys/bus/pci/devices/%04x:%02x:%02x.%01x",
2809 vdev->host.domain, vdev->host.bus,
2810 vdev->host.slot, vdev->host.function);
2811 }
2812
2813 if (stat(vdev->vbasedev.sysfsdev, &st) < 0) {
1a22aca1
EA
2814 error_setg_errno(errp, errno, "no such host device");
2815 error_prepend(errp, ERR_PREFIX, vdev->vbasedev.sysfsdev);
2816 return;
65501a74
AW
2817 }
2818
3e015d81 2819 vdev->vbasedev.name = g_path_get_basename(vdev->vbasedev.sysfsdev);
b47d8efa 2820 vdev->vbasedev.ops = &vfio_pci_ops;
462037c9 2821 vdev->vbasedev.type = VFIO_DEVICE_TYPE_PCI;
7da624e2 2822 vdev->vbasedev.dev = &vdev->pdev.qdev;
462037c9 2823
7df9381b
AW
2824 tmp = g_strdup_printf("%s/iommu_group", vdev->vbasedev.sysfsdev);
2825 len = readlink(tmp, group_path, sizeof(group_path));
2826 g_free(tmp);
65501a74 2827
7df9381b 2828 if (len <= 0 || len >= sizeof(group_path)) {
1a22aca1
EA
2829 error_setg_errno(errp, len < 0 ? errno : ENAMETOOLONG,
2830 "no iommu_group found");
426ec904 2831 goto error;
65501a74
AW
2832 }
2833
7df9381b 2834 group_path[len] = 0;
65501a74 2835
7df9381b 2836 group_name = basename(group_path);
65501a74 2837 if (sscanf(group_name, "%d", &groupid) != 1) {
1a22aca1 2838 error_setg_errno(errp, errno, "failed to read %s", group_path);
426ec904 2839 goto error;
65501a74
AW
2840 }
2841
1a22aca1 2842 trace_vfio_realize(vdev->vbasedev.name, groupid);
65501a74 2843
1a22aca1 2844 group = vfio_get_group(groupid, pci_device_iommu_address_space(pdev), errp);
65501a74 2845 if (!group) {
426ec904 2846 goto error;
65501a74
AW
2847 }
2848
b47d8efa
EA
2849 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2850 if (strcmp(vbasedev_iter->name, vdev->vbasedev.name) == 0) {
1a22aca1 2851 error_setg(errp, "device is already attached");
65501a74 2852 vfio_put_group(group);
426ec904 2853 goto error;
65501a74
AW
2854 }
2855 }
2856
1a22aca1 2857 ret = vfio_get_device(group, vdev->vbasedev.name, &vdev->vbasedev, errp);
65501a74 2858 if (ret) {
65501a74 2859 vfio_put_group(group);
426ec904 2860 goto error;
65501a74
AW
2861 }
2862
e04cff9d
EA
2863 vfio_populate_device(vdev, &err);
2864 if (err) {
2865 error_propagate(errp, err);
2312d907 2866 goto error;
217e9fdc
PB
2867 }
2868
65501a74 2869 /* Get a copy of config space */
5546a621 2870 ret = pread(vdev->vbasedev.fd, vdev->pdev.config,
65501a74
AW
2871 MIN(pci_config_size(&vdev->pdev), vdev->config_size),
2872 vdev->config_offset);
2873 if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
2874 ret = ret < 0 ? -errno : -EFAULT;
1a22aca1 2875 error_setg_errno(errp, -ret, "failed to read device config space");
426ec904 2876 goto error;
65501a74
AW
2877 }
2878
4b5d5e87
AW
2879 /* vfio emulates a lot for us, but some bits need extra love */
2880 vdev->emulated_config_bits = g_malloc0(vdev->config_size);
2881
2882 /* QEMU can choose to expose the ROM or not */
2883 memset(vdev->emulated_config_bits + PCI_ROM_ADDRESS, 0xff, 4);
04f336b0
AW
2884 /* QEMU can also add or extend BARs */
2885 memset(vdev->emulated_config_bits + PCI_BASE_ADDRESS_0, 0xff, 6 * 4);
4b5d5e87 2886
89dcccc5
AW
2887 /*
2888 * The PCI spec reserves vendor ID 0xffff as an invalid value. The
2889 * device ID is managed by the vendor and need only be a 16-bit value.
2890 * Allow any 16-bit value for subsystem so they can be hidden or changed.
2891 */
2892 if (vdev->vendor_id != PCI_ANY_ID) {
2893 if (vdev->vendor_id >= 0xffff) {
1a22aca1 2894 error_setg(errp, "invalid PCI vendor ID provided");
426ec904 2895 goto error;
89dcccc5
AW
2896 }
2897 vfio_add_emulated_word(vdev, PCI_VENDOR_ID, vdev->vendor_id, ~0);
2898 trace_vfio_pci_emulated_vendor_id(vdev->vbasedev.name, vdev->vendor_id);
2899 } else {
2900 vdev->vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2901 }
2902
2903 if (vdev->device_id != PCI_ANY_ID) {
2904 if (vdev->device_id > 0xffff) {
1a22aca1 2905 error_setg(errp, "invalid PCI device ID provided");
426ec904 2906 goto error;
89dcccc5
AW
2907 }
2908 vfio_add_emulated_word(vdev, PCI_DEVICE_ID, vdev->device_id, ~0);
2909 trace_vfio_pci_emulated_device_id(vdev->vbasedev.name, vdev->device_id);
2910 } else {
2911 vdev->device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2912 }
2913
2914 if (vdev->sub_vendor_id != PCI_ANY_ID) {
2915 if (vdev->sub_vendor_id > 0xffff) {
1a22aca1 2916 error_setg(errp, "invalid PCI subsystem vendor ID provided");
426ec904 2917 goto error;
89dcccc5
AW
2918 }
2919 vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_VENDOR_ID,
2920 vdev->sub_vendor_id, ~0);
2921 trace_vfio_pci_emulated_sub_vendor_id(vdev->vbasedev.name,
2922 vdev->sub_vendor_id);
2923 }
2924
2925 if (vdev->sub_device_id != PCI_ANY_ID) {
2926 if (vdev->sub_device_id > 0xffff) {
1a22aca1 2927 error_setg(errp, "invalid PCI subsystem device ID provided");
426ec904 2928 goto error;
89dcccc5
AW
2929 }
2930 vfio_add_emulated_word(vdev, PCI_SUBSYSTEM_ID, vdev->sub_device_id, ~0);
2931 trace_vfio_pci_emulated_sub_device_id(vdev->vbasedev.name,
2932 vdev->sub_device_id);
2933 }
ff635e37 2934
4b5d5e87
AW
2935 /* QEMU can change multi-function devices to single function, or reverse */
2936 vdev->emulated_config_bits[PCI_HEADER_TYPE] =
2937 PCI_HEADER_TYPE_MULTI_FUNCTION;
2938
187d6232
AW
2939 /* Restore or clear multifunction, this is always controlled by QEMU */
2940 if (vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
2941 vdev->pdev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
2942 } else {
2943 vdev->pdev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
2944 }
2945
65501a74
AW
2946 /*
2947 * Clear host resource mapping info. If we choose not to register a
2948 * BAR, such as might be the case with the option ROM, we can get
2949 * confusing, unwritable, residual addresses from the host here.
2950 */
2951 memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
2952 memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
2953
6f864e6e 2954 vfio_pci_size_rom(vdev);
65501a74 2955
89d5202e
AW
2956 vfio_bars_prepare(vdev);
2957
ec3bcf42
EA
2958 vfio_msix_early_setup(vdev, &err);
2959 if (err) {
2960 error_propagate(errp, err);
008d0e2d 2961 goto error;
65501a74
AW
2962 }
2963
3a286732 2964 vfio_bars_register(vdev);
65501a74 2965
1a22aca1 2966 ret = vfio_add_capabilities(vdev, errp);
65501a74
AW
2967 if (ret) {
2968 goto out_teardown;
2969 }
2970
182bca45
AW
2971 if (vdev->vga) {
2972 vfio_vga_quirk_setup(vdev);
2973 }
2974
581406e0
AW
2975 for (i = 0; i < PCI_ROM_SLOT; i++) {
2976 vfio_bar_quirk_setup(vdev, i);
2977 }
2978
6ced0bba
AW
2979 if (!vdev->igd_opregion &&
2980 vdev->features & VFIO_FEATURE_ENABLE_IGD_OPREGION) {
2981 struct vfio_region_info *opregion;
2982
2983 if (vdev->pdev.qdev.hotplugged) {
1a22aca1 2984 error_setg(errp,
426ec904
EA
2985 "cannot support IGD OpRegion feature on hotplugged "
2986 "device");
6ced0bba
AW
2987 goto out_teardown;
2988 }
2989
2990 ret = vfio_get_dev_region_info(&vdev->vbasedev,
2991 VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL,
2992 VFIO_REGION_SUBTYPE_INTEL_IGD_OPREGION, &opregion);
2993 if (ret) {
1a22aca1 2994 error_setg_errno(errp, -ret,
426ec904 2995 "does not support requested IGD OpRegion feature");
6ced0bba
AW
2996 goto out_teardown;
2997 }
2998
1a22aca1 2999 ret = vfio_pci_igd_opregion_init(vdev, opregion, errp);
6ced0bba
AW
3000 g_free(opregion);
3001 if (ret) {
6ced0bba
AW
3002 goto out_teardown;
3003 }
3004 }
3005
4b5d5e87
AW
3006 /* QEMU emulates all of MSI & MSIX */
3007 if (pdev->cap_present & QEMU_PCI_CAP_MSIX) {
3008 memset(vdev->emulated_config_bits + pdev->msix_cap, 0xff,
3009 MSIX_CAP_LENGTH);
3010 }
3011
3012 if (pdev->cap_present & QEMU_PCI_CAP_MSI) {
3013 memset(vdev->emulated_config_bits + pdev->msi_cap, 0xff,
3014 vdev->msi_cap_size);
3015 }
3016
65501a74 3017 if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
bc72ad67 3018 vdev->intx.mmap_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
ea486926 3019 vfio_intx_mmap_enable, vdev);
870cb6f1 3020 pci_device_set_intx_routing_notifier(&vdev->pdev, vfio_intx_update);
1a22aca1 3021 ret = vfio_intx_enable(vdev, errp);
65501a74
AW
3022 if (ret) {
3023 goto out_teardown;
3024 }
3025 }
3026
a9994687
GH
3027 if (vdev->display != ON_OFF_AUTO_OFF) {
3028 ret = vfio_display_probe(vdev, errp);
3029 if (ret) {
3030 goto out_teardown;
3031 }
3032 }
3033
7b4b0e9e 3034 vfio_register_err_notifier(vdev);
47cbe50c 3035 vfio_register_req_notifier(vdev);
c9c50009 3036 vfio_setup_resetfn_quirk(vdev);
c29029dd 3037
1a22aca1 3038 return;
65501a74
AW
3039
3040out_teardown:
3041 pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3042 vfio_teardown_msi(vdev);
2d82f8a3 3043 vfio_bars_exit(vdev);
426ec904 3044error:
1a22aca1 3045 error_prepend(errp, ERR_PREFIX, vdev->vbasedev.name);
77a10d04
PB
3046}
3047
3048static void vfio_instance_finalize(Object *obj)
3049{
3050 PCIDevice *pci_dev = PCI_DEVICE(obj);
3051 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pci_dev);
3052 VFIOGroup *group = vdev->vbasedev.group;
3053
a9994687 3054 vfio_display_finalize(vdev);
2d82f8a3 3055 vfio_bars_finalize(vdev);
4b5d5e87 3056 g_free(vdev->emulated_config_bits);
77a10d04 3057 g_free(vdev->rom);
c4c45e94
AW
3058 /*
3059 * XXX Leaking igd_opregion is not an oversight, we can't remove the
3060 * fw_cfg entry therefore leaking this allocation seems like the safest
3061 * option.
3062 *
3063 * g_free(vdev->igd_opregion);
3064 */
65501a74
AW
3065 vfio_put_device(vdev);
3066 vfio_put_group(group);
65501a74
AW
3067}
3068
3069static void vfio_exitfn(PCIDevice *pdev)
3070{
9ee27d73 3071 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
65501a74 3072
47cbe50c 3073 vfio_unregister_req_notifier(vdev);
7b4b0e9e 3074 vfio_unregister_err_notifier(vdev);
65501a74
AW
3075 pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3076 vfio_disable_interrupts(vdev);
ea486926 3077 if (vdev->intx.mmap_timer) {
bc72ad67 3078 timer_free(vdev->intx.mmap_timer);
ea486926 3079 }
65501a74 3080 vfio_teardown_msi(vdev);
2d82f8a3 3081 vfio_bars_exit(vdev);
65501a74
AW
3082}
3083
3084static void vfio_pci_reset(DeviceState *dev)
3085{
3086 PCIDevice *pdev = DO_UPCAST(PCIDevice, qdev, dev);
9ee27d73 3087 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
65501a74 3088
df92ee44 3089 trace_vfio_pci_reset(vdev->vbasedev.name);
5834a83f 3090
f16f39c3 3091 vfio_pci_pre_reset(vdev);
ba661818 3092
5655f931
AW
3093 if (vdev->resetfn && !vdev->resetfn(vdev)) {
3094 goto post_reset;
3095 }
3096
b47d8efa
EA
3097 if (vdev->vbasedev.reset_works &&
3098 (vdev->has_flr || !vdev->has_pm_reset) &&
5546a621 3099 !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
df92ee44 3100 trace_vfio_pci_reset_flr(vdev->vbasedev.name);
f16f39c3 3101 goto post_reset;
ba661818
AW
3102 }
3103
f16f39c3
AW
3104 /* See if we can do our own bus reset */
3105 if (!vfio_pci_hot_reset_one(vdev)) {
3106 goto post_reset;
3107 }
5834a83f 3108
f16f39c3 3109 /* If nothing else works and the device supports PM reset, use it */
b47d8efa 3110 if (vdev->vbasedev.reset_works && vdev->has_pm_reset &&
5546a621 3111 !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
df92ee44 3112 trace_vfio_pci_reset_pm(vdev->vbasedev.name);
f16f39c3 3113 goto post_reset;
65501a74 3114 }
5834a83f 3115
f16f39c3
AW
3116post_reset:
3117 vfio_pci_post_reset(vdev);
65501a74
AW
3118}
3119
abc5b3bf
GA
3120static void vfio_instance_init(Object *obj)
3121{
3122 PCIDevice *pci_dev = PCI_DEVICE(obj);
9ee27d73 3123 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, PCI_DEVICE(obj));
abc5b3bf
GA
3124
3125 device_add_bootindex_property(obj, &vdev->bootindex,
3126 "bootindex", NULL,
3127 &pci_dev->qdev, NULL);
4a946268
EA
3128 vdev->host.domain = ~0U;
3129 vdev->host.bus = ~0U;
3130 vdev->host.slot = ~0U;
3131 vdev->host.function = ~0U;
dfbee78d
AW
3132
3133 vdev->nv_gpudirect_clique = 0xFF;
d61a363d
YB
3134
3135 /* QEMU_PCI_CAP_EXPRESS initialization does not depend on QEMU command
3136 * line, therefore, no need to wait to realize like other devices */
3137 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
abc5b3bf
GA
3138}
3139
65501a74 3140static Property vfio_pci_dev_properties[] = {
9ee27d73 3141 DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIOPCIDevice, host),
7df9381b 3142 DEFINE_PROP_STRING("sysfsdev", VFIOPCIDevice, vbasedev.sysfsdev),
a9994687
GH
3143 DEFINE_PROP_ON_OFF_AUTO("display", VFIOPCIDevice,
3144 display, ON_OFF_AUTO_AUTO),
9ee27d73 3145 DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIOPCIDevice,
ea486926 3146 intx.mmap_timeout, 1100),
9ee27d73 3147 DEFINE_PROP_BIT("x-vga", VFIOPCIDevice, features,
f15689c7 3148 VFIO_FEATURE_ENABLE_VGA_BIT, false),
47cbe50c
AW
3149 DEFINE_PROP_BIT("x-req", VFIOPCIDevice, features,
3150 VFIO_FEATURE_ENABLE_REQ_BIT, true),
6ced0bba
AW
3151 DEFINE_PROP_BIT("x-igd-opregion", VFIOPCIDevice, features,
3152 VFIO_FEATURE_ENABLE_IGD_OPREGION_BIT, false),
5e15d79b 3153 DEFINE_PROP_BOOL("x-no-mmap", VFIOPCIDevice, vbasedev.no_mmap, false),
46746dba
AW
3154 DEFINE_PROP_BOOL("x-no-kvm-intx", VFIOPCIDevice, no_kvm_intx, false),
3155 DEFINE_PROP_BOOL("x-no-kvm-msi", VFIOPCIDevice, no_kvm_msi, false),
3156 DEFINE_PROP_BOOL("x-no-kvm-msix", VFIOPCIDevice, no_kvm_msix, false),
db32d0f4
AW
3157 DEFINE_PROP_BOOL("x-no-geforce-quirks", VFIOPCIDevice,
3158 no_geforce_quirks, false),
89dcccc5
AW
3159 DEFINE_PROP_UINT32("x-pci-vendor-id", VFIOPCIDevice, vendor_id, PCI_ANY_ID),
3160 DEFINE_PROP_UINT32("x-pci-device-id", VFIOPCIDevice, device_id, PCI_ANY_ID),
3161 DEFINE_PROP_UINT32("x-pci-sub-vendor-id", VFIOPCIDevice,
3162 sub_vendor_id, PCI_ANY_ID),
3163 DEFINE_PROP_UINT32("x-pci-sub-device-id", VFIOPCIDevice,
3164 sub_device_id, PCI_ANY_ID),
c4c45e94 3165 DEFINE_PROP_UINT32("x-igd-gms", VFIOPCIDevice, igd_gms, 0),
dfbee78d
AW
3166 DEFINE_PROP_UNSIGNED_NODEFAULT("x-nv-gpudirect-clique", VFIOPCIDevice,
3167 nv_gpudirect_clique,
3168 qdev_prop_nv_gpudirect_clique, uint8_t),
89d5202e
AW
3169 DEFINE_PROP_OFF_AUTO_PCIBAR("x-msix-relocation", VFIOPCIDevice, msix_relo,
3170 OFF_AUTOPCIBAR_OFF),
65501a74
AW
3171 /*
3172 * TODO - support passed fds... is this necessary?
9ee27d73
EA
3173 * DEFINE_PROP_STRING("vfiofd", VFIOPCIDevice, vfiofd_name),
3174 * DEFINE_PROP_STRING("vfiogroupfd, VFIOPCIDevice, vfiogroupfd_name),
65501a74
AW
3175 */
3176 DEFINE_PROP_END_OF_LIST(),
3177};
3178
d9f0e638
AW
3179static const VMStateDescription vfio_pci_vmstate = {
3180 .name = "vfio-pci",
3181 .unmigratable = 1,
3182};
65501a74
AW
3183
3184static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
3185{
3186 DeviceClass *dc = DEVICE_CLASS(klass);
3187 PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
3188
3189 dc->reset = vfio_pci_reset;
3190 dc->props = vfio_pci_dev_properties;
d9f0e638
AW
3191 dc->vmsd = &vfio_pci_vmstate;
3192 dc->desc = "VFIO-based PCI device assignment";
125ee0ed 3193 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
1a22aca1 3194 pdc->realize = vfio_realize;
65501a74
AW
3195 pdc->exit = vfio_exitfn;
3196 pdc->config_read = vfio_pci_read_config;
3197 pdc->config_write = vfio_pci_write_config;
3198}
3199
3200static const TypeInfo vfio_pci_dev_info = {
3201 .name = "vfio-pci",
3202 .parent = TYPE_PCI_DEVICE,
9ee27d73 3203 .instance_size = sizeof(VFIOPCIDevice),
65501a74 3204 .class_init = vfio_pci_dev_class_init,
abc5b3bf 3205 .instance_init = vfio_instance_init,
77a10d04 3206 .instance_finalize = vfio_instance_finalize,
a5fa336f
EH
3207 .interfaces = (InterfaceInfo[]) {
3208 { INTERFACE_PCIE_DEVICE },
3209 { INTERFACE_CONVENTIONAL_PCI_DEVICE },
3210 { }
3211 },
65501a74
AW
3212};
3213
3214static void register_vfio_pci_dev_type(void)
3215{
3216 type_register_static(&vfio_pci_dev_info);
3217}
3218
3219type_init(register_vfio_pci_dev_type)