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