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