]> git.proxmox.com Git - mirror_qemu.git/blame - hw/vfio/pci.c
vfio/pci: Cache vendor and device ID
[mirror_qemu.git] / hw / vfio / pci.c
CommitLineData
65501a74
AW
1/*
2 * vfio based device assignment support
3 *
4 * Copyright Red Hat, Inc. 2012
5 *
6 * Authors:
7 * Alex Williamson <alex.williamson@redhat.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 *
12 * Based on qemu-kvm device-assignment:
13 * Adapted for KVM by Qumranet.
14 * Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
15 * Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
16 * Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
17 * Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
18 * Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
19 */
20
6dcfdbad 21#include <linux/vfio.h>
65501a74
AW
22#include <sys/ioctl.h>
23#include <sys/mman.h>
24#include <sys/stat.h>
25#include <sys/types.h>
6dcfdbad 26#include <unistd.h>
65501a74
AW
27
28#include "config.h"
83c9f4ca
PB
29#include "hw/pci/msi.h"
30#include "hw/pci/msix.h"
1de7afc9 31#include "qemu/error-report.h"
1de7afc9 32#include "qemu/range.h"
6dcfdbad
AW
33#include "sysemu/kvm.h"
34#include "sysemu/sysemu.h"
78f33d2b 35#include "pci.h"
385f57cf 36#include "trace.h"
4b943029 37
65501a74
AW
38#define MSIX_CAP_LENGTH 12
39
9ee27d73 40static void vfio_disable_interrupts(VFIOPCIDevice *vdev);
9ee27d73 41static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled);
65501a74 42
ea486926
AW
43/*
44 * Disabling BAR mmaping can be slow, but toggling it around INTx can
45 * also be a huge overhead. We try to get the best of both worlds by
46 * waiting until an interrupt to disable mmaps (subsequent transitions
47 * to the same state are effectively no overhead). If the interrupt has
48 * been serviced and the time gap is long enough, we re-enable mmaps for
49 * performance. This works well for things like graphics cards, which
50 * may not use their interrupt at all and are penalized to an unusable
51 * level by read/write BAR traps. Other devices, like NICs, have more
52 * regular interrupts and see much better latency by staying in non-mmap
53 * mode. We therefore set the default mmap_timeout such that a ping
54 * is just enough to keep the mmap disabled. Users can experiment with
55 * other options with the x-intx-mmap-timeout-ms parameter (a value of
56 * zero disables the timer).
57 */
58static void vfio_intx_mmap_enable(void *opaque)
59{
9ee27d73 60 VFIOPCIDevice *vdev = opaque;
ea486926
AW
61
62 if (vdev->intx.pending) {
bc72ad67
AB
63 timer_mod(vdev->intx.mmap_timer,
64 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
ea486926
AW
65 return;
66 }
67
68 vfio_mmap_set_enabled(vdev, true);
69}
70
65501a74
AW
71static void vfio_intx_interrupt(void *opaque)
72{
9ee27d73 73 VFIOPCIDevice *vdev = opaque;
65501a74
AW
74
75 if (!event_notifier_test_and_clear(&vdev->intx.interrupt)) {
76 return;
77 }
78
df92ee44 79 trace_vfio_intx_interrupt(vdev->vbasedev.name, 'A' + vdev->intx.pin);
65501a74
AW
80
81 vdev->intx.pending = true;
68919cac 82 pci_irq_assert(&vdev->pdev);
ea486926
AW
83 vfio_mmap_set_enabled(vdev, false);
84 if (vdev->intx.mmap_timeout) {
bc72ad67
AB
85 timer_mod(vdev->intx.mmap_timer,
86 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
ea486926 87 }
65501a74
AW
88}
89
870cb6f1 90static void vfio_intx_eoi(VFIODevice *vbasedev)
65501a74 91{
a664477d
EA
92 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
93
65501a74
AW
94 if (!vdev->intx.pending) {
95 return;
96 }
97
870cb6f1 98 trace_vfio_intx_eoi(vbasedev->name);
65501a74
AW
99
100 vdev->intx.pending = false;
68919cac 101 pci_irq_deassert(&vdev->pdev);
a664477d 102 vfio_unmask_single_irqindex(vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
65501a74
AW
103}
104
870cb6f1 105static void vfio_intx_enable_kvm(VFIOPCIDevice *vdev)
e1d1e586
AW
106{
107#ifdef CONFIG_KVM
108 struct kvm_irqfd irqfd = {
109 .fd = event_notifier_get_fd(&vdev->intx.interrupt),
110 .gsi = vdev->intx.route.irq,
111 .flags = KVM_IRQFD_FLAG_RESAMPLE,
112 };
113 struct vfio_irq_set *irq_set;
114 int ret, argsz;
115 int32_t *pfd;
116
46746dba 117 if (vdev->no_kvm_intx || !kvm_irqfds_enabled() ||
e1d1e586 118 vdev->intx.route.mode != PCI_INTX_ENABLED ||
9fc0e2d8 119 !kvm_resamplefds_enabled()) {
e1d1e586
AW
120 return;
121 }
122
123 /* Get to a known interrupt state */
124 qemu_set_fd_handler(irqfd.fd, NULL, NULL, vdev);
5546a621 125 vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
e1d1e586 126 vdev->intx.pending = false;
68919cac 127 pci_irq_deassert(&vdev->pdev);
e1d1e586
AW
128
129 /* Get an eventfd for resample/unmask */
130 if (event_notifier_init(&vdev->intx.unmask, 0)) {
312fd5f2 131 error_report("vfio: Error: event_notifier_init failed eoi");
e1d1e586
AW
132 goto fail;
133 }
134
135 /* KVM triggers it, VFIO listens for it */
136 irqfd.resamplefd = event_notifier_get_fd(&vdev->intx.unmask);
137
138 if (kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd)) {
312fd5f2 139 error_report("vfio: Error: Failed to setup resample irqfd: %m");
e1d1e586
AW
140 goto fail_irqfd;
141 }
142
143 argsz = sizeof(*irq_set) + sizeof(*pfd);
144
145 irq_set = g_malloc0(argsz);
146 irq_set->argsz = argsz;
147 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_UNMASK;
148 irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
149 irq_set->start = 0;
150 irq_set->count = 1;
151 pfd = (int32_t *)&irq_set->data;
152
153 *pfd = irqfd.resamplefd;
154
5546a621 155 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
e1d1e586
AW
156 g_free(irq_set);
157 if (ret) {
312fd5f2 158 error_report("vfio: Error: Failed to setup INTx unmask fd: %m");
e1d1e586
AW
159 goto fail_vfio;
160 }
161
162 /* Let'em rip */
5546a621 163 vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
e1d1e586
AW
164
165 vdev->intx.kvm_accel = true;
166
870cb6f1 167 trace_vfio_intx_enable_kvm(vdev->vbasedev.name);
e1d1e586
AW
168
169 return;
170
171fail_vfio:
172 irqfd.flags = KVM_IRQFD_FLAG_DEASSIGN;
173 kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd);
174fail_irqfd:
175 event_notifier_cleanup(&vdev->intx.unmask);
176fail:
177 qemu_set_fd_handler(irqfd.fd, vfio_intx_interrupt, NULL, vdev);
5546a621 178 vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
e1d1e586
AW
179#endif
180}
181
870cb6f1 182static void vfio_intx_disable_kvm(VFIOPCIDevice *vdev)
e1d1e586
AW
183{
184#ifdef CONFIG_KVM
185 struct kvm_irqfd irqfd = {
186 .fd = event_notifier_get_fd(&vdev->intx.interrupt),
187 .gsi = vdev->intx.route.irq,
188 .flags = KVM_IRQFD_FLAG_DEASSIGN,
189 };
190
191 if (!vdev->intx.kvm_accel) {
192 return;
193 }
194
195 /*
196 * Get to a known state, hardware masked, QEMU ready to accept new
197 * interrupts, QEMU IRQ de-asserted.
198 */
5546a621 199 vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
e1d1e586 200 vdev->intx.pending = false;
68919cac 201 pci_irq_deassert(&vdev->pdev);
e1d1e586
AW
202
203 /* Tell KVM to stop listening for an INTx irqfd */
204 if (kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd)) {
312fd5f2 205 error_report("vfio: Error: Failed to disable INTx irqfd: %m");
e1d1e586
AW
206 }
207
208 /* We only need to close the eventfd for VFIO to cleanup the kernel side */
209 event_notifier_cleanup(&vdev->intx.unmask);
210
211 /* QEMU starts listening for interrupt events. */
212 qemu_set_fd_handler(irqfd.fd, vfio_intx_interrupt, NULL, vdev);
213
214 vdev->intx.kvm_accel = false;
215
216 /* If we've missed an event, let it re-fire through QEMU */
5546a621 217 vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
e1d1e586 218
870cb6f1 219 trace_vfio_intx_disable_kvm(vdev->vbasedev.name);
e1d1e586
AW
220#endif
221}
222
870cb6f1 223static void vfio_intx_update(PCIDevice *pdev)
e1d1e586 224{
9ee27d73 225 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
e1d1e586
AW
226 PCIINTxRoute route;
227
228 if (vdev->interrupt != VFIO_INT_INTx) {
229 return;
230 }
231
232 route = pci_device_route_intx_to_irq(&vdev->pdev, vdev->intx.pin);
233
234 if (!pci_intx_route_changed(&vdev->intx.route, &route)) {
235 return; /* Nothing changed */
236 }
237
870cb6f1
AW
238 trace_vfio_intx_update(vdev->vbasedev.name,
239 vdev->intx.route.irq, route.irq);
e1d1e586 240
870cb6f1 241 vfio_intx_disable_kvm(vdev);
e1d1e586
AW
242
243 vdev->intx.route = route;
244
245 if (route.mode != PCI_INTX_ENABLED) {
246 return;
247 }
248
870cb6f1 249 vfio_intx_enable_kvm(vdev);
e1d1e586
AW
250
251 /* Re-enable the interrupt in cased we missed an EOI */
870cb6f1 252 vfio_intx_eoi(&vdev->vbasedev);
e1d1e586
AW
253}
254
870cb6f1 255static int vfio_intx_enable(VFIOPCIDevice *vdev)
65501a74 256{
65501a74 257 uint8_t pin = vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1);
1a403133
AW
258 int ret, argsz;
259 struct vfio_irq_set *irq_set;
260 int32_t *pfd;
65501a74 261
ea486926 262 if (!pin) {
65501a74
AW
263 return 0;
264 }
265
266 vfio_disable_interrupts(vdev);
267
268 vdev->intx.pin = pin - 1; /* Pin A (1) -> irq[0] */
68919cac 269 pci_config_set_interrupt_pin(vdev->pdev.config, pin);
e1d1e586
AW
270
271#ifdef CONFIG_KVM
272 /*
273 * Only conditional to avoid generating error messages on platforms
274 * where we won't actually use the result anyway.
275 */
9fc0e2d8 276 if (kvm_irqfds_enabled() && kvm_resamplefds_enabled()) {
e1d1e586
AW
277 vdev->intx.route = pci_device_route_intx_to_irq(&vdev->pdev,
278 vdev->intx.pin);
279 }
280#endif
281
65501a74
AW
282 ret = event_notifier_init(&vdev->intx.interrupt, 0);
283 if (ret) {
312fd5f2 284 error_report("vfio: Error: event_notifier_init failed");
65501a74
AW
285 return ret;
286 }
287
1a403133
AW
288 argsz = sizeof(*irq_set) + sizeof(*pfd);
289
290 irq_set = g_malloc0(argsz);
291 irq_set->argsz = argsz;
292 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
293 irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
294 irq_set->start = 0;
295 irq_set->count = 1;
296 pfd = (int32_t *)&irq_set->data;
297
298 *pfd = event_notifier_get_fd(&vdev->intx.interrupt);
299 qemu_set_fd_handler(*pfd, vfio_intx_interrupt, NULL, vdev);
65501a74 300
5546a621 301 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
1a403133
AW
302 g_free(irq_set);
303 if (ret) {
312fd5f2 304 error_report("vfio: Error: Failed to setup INTx fd: %m");
1a403133 305 qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
ce59af2d 306 event_notifier_cleanup(&vdev->intx.interrupt);
65501a74
AW
307 return -errno;
308 }
309
870cb6f1 310 vfio_intx_enable_kvm(vdev);
e1d1e586 311
65501a74
AW
312 vdev->interrupt = VFIO_INT_INTx;
313
870cb6f1 314 trace_vfio_intx_enable(vdev->vbasedev.name);
65501a74
AW
315
316 return 0;
317}
318
870cb6f1 319static void vfio_intx_disable(VFIOPCIDevice *vdev)
65501a74
AW
320{
321 int fd;
322
bc72ad67 323 timer_del(vdev->intx.mmap_timer);
870cb6f1 324 vfio_intx_disable_kvm(vdev);
5546a621 325 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);
65501a74 326 vdev->intx.pending = false;
68919cac 327 pci_irq_deassert(&vdev->pdev);
65501a74
AW
328 vfio_mmap_set_enabled(vdev, true);
329
330 fd = event_notifier_get_fd(&vdev->intx.interrupt);
331 qemu_set_fd_handler(fd, NULL, NULL, vdev);
332 event_notifier_cleanup(&vdev->intx.interrupt);
333
334 vdev->interrupt = VFIO_INT_NONE;
335
870cb6f1 336 trace_vfio_intx_disable(vdev->vbasedev.name);
65501a74
AW
337}
338
339/*
340 * MSI/X
341 */
342static void vfio_msi_interrupt(void *opaque)
343{
344 VFIOMSIVector *vector = opaque;
9ee27d73 345 VFIOPCIDevice *vdev = vector->vdev;
0de70dc7
AW
346 MSIMessage (*get_msg)(PCIDevice *dev, unsigned vector);
347 void (*notify)(PCIDevice *dev, unsigned vector);
348 MSIMessage msg;
65501a74
AW
349 int nr = vector - vdev->msi_vectors;
350
351 if (!event_notifier_test_and_clear(&vector->interrupt)) {
352 return;
353 }
354
b3ebc10c 355 if (vdev->interrupt == VFIO_INT_MSIX) {
0de70dc7
AW
356 get_msg = msix_get_message;
357 notify = msix_notify;
9035f8c0 358 } else if (vdev->interrupt == VFIO_INT_MSI) {
0de70dc7
AW
359 get_msg = msi_get_message;
360 notify = msi_notify;
b3ebc10c
AW
361 } else {
362 abort();
363 }
364
0de70dc7 365 msg = get_msg(&vdev->pdev, nr);
bc5baffa 366 trace_vfio_msi_interrupt(vdev->vbasedev.name, nr, msg.address, msg.data);
0de70dc7 367 notify(&vdev->pdev, nr);
65501a74
AW
368}
369
9ee27d73 370static int vfio_enable_vectors(VFIOPCIDevice *vdev, bool msix)
65501a74
AW
371{
372 struct vfio_irq_set *irq_set;
373 int ret = 0, i, argsz;
374 int32_t *fds;
375
376 argsz = sizeof(*irq_set) + (vdev->nr_vectors * sizeof(*fds));
377
378 irq_set = g_malloc0(argsz);
379 irq_set->argsz = argsz;
380 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
381 irq_set->index = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX;
382 irq_set->start = 0;
383 irq_set->count = vdev->nr_vectors;
384 fds = (int32_t *)&irq_set->data;
385
386 for (i = 0; i < vdev->nr_vectors; i++) {
c048be5c
AW
387 int fd = -1;
388
389 /*
390 * MSI vs MSI-X - The guest has direct access to MSI mask and pending
391 * bits, therefore we always use the KVM signaling path when setup.
392 * MSI-X mask and pending bits are emulated, so we want to use the
393 * KVM signaling path only when configured and unmasked.
394 */
395 if (vdev->msi_vectors[i].use) {
396 if (vdev->msi_vectors[i].virq < 0 ||
397 (msix && msix_is_masked(&vdev->pdev, i))) {
398 fd = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt);
399 } else {
400 fd = event_notifier_get_fd(&vdev->msi_vectors[i].kvm_interrupt);
401 }
65501a74 402 }
c048be5c
AW
403
404 fds[i] = fd;
65501a74
AW
405 }
406
5546a621 407 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
65501a74
AW
408
409 g_free(irq_set);
410
65501a74
AW
411 return ret;
412}
413
46746dba
AW
414static void vfio_add_kvm_msi_virq(VFIOPCIDevice *vdev, VFIOMSIVector *vector,
415 MSIMessage *msg, bool msix)
f4d45d47
AW
416{
417 int virq;
418
46746dba 419 if ((msix && vdev->no_kvm_msix) || (!msix && vdev->no_kvm_msi) || !msg) {
f4d45d47
AW
420 return;
421 }
422
423 if (event_notifier_init(&vector->kvm_interrupt, 0)) {
424 return;
425 }
426
427 virq = kvm_irqchip_add_msi_route(kvm_state, *msg);
428 if (virq < 0) {
429 event_notifier_cleanup(&vector->kvm_interrupt);
430 return;
431 }
432
1c9b71a7 433 if (kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt,
f4d45d47
AW
434 NULL, virq) < 0) {
435 kvm_irqchip_release_virq(kvm_state, virq);
436 event_notifier_cleanup(&vector->kvm_interrupt);
437 return;
438 }
439
f4d45d47
AW
440 vector->virq = virq;
441}
442
443static void vfio_remove_kvm_msi_virq(VFIOMSIVector *vector)
444{
1c9b71a7
EA
445 kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, &vector->kvm_interrupt,
446 vector->virq);
f4d45d47
AW
447 kvm_irqchip_release_virq(kvm_state, vector->virq);
448 vector->virq = -1;
449 event_notifier_cleanup(&vector->kvm_interrupt);
450}
451
452static void vfio_update_kvm_msi_virq(VFIOMSIVector *vector, MSIMessage msg)
453{
454 kvm_irqchip_update_msi_route(kvm_state, vector->virq, msg);
f4d45d47
AW
455}
456
b0223e29
AW
457static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr,
458 MSIMessage *msg, IOHandler *handler)
65501a74 459{
9ee27d73 460 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
65501a74
AW
461 VFIOMSIVector *vector;
462 int ret;
463
df92ee44 464 trace_vfio_msix_vector_do_use(vdev->vbasedev.name, nr);
65501a74 465
65501a74 466 vector = &vdev->msi_vectors[nr];
65501a74 467
f4d45d47
AW
468 if (!vector->use) {
469 vector->vdev = vdev;
470 vector->virq = -1;
471 if (event_notifier_init(&vector->interrupt, 0)) {
472 error_report("vfio: Error: event_notifier_init failed");
473 }
474 vector->use = true;
475 msix_vector_use(pdev, nr);
65501a74
AW
476 }
477
f4d45d47
AW
478 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
479 handler, NULL, vector);
480
65501a74
AW
481 /*
482 * Attempt to enable route through KVM irqchip,
483 * default to userspace handling if unavailable.
484 */
f4d45d47
AW
485 if (vector->virq >= 0) {
486 if (!msg) {
487 vfio_remove_kvm_msi_virq(vector);
488 } else {
489 vfio_update_kvm_msi_virq(vector, *msg);
65501a74 490 }
f4d45d47 491 } else {
46746dba 492 vfio_add_kvm_msi_virq(vdev, vector, msg, true);
65501a74
AW
493 }
494
495 /*
496 * We don't want to have the host allocate all possible MSI vectors
497 * for a device if they're not in use, so we shutdown and incrementally
498 * increase them as needed.
499 */
500 if (vdev->nr_vectors < nr + 1) {
5546a621 501 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
65501a74
AW
502 vdev->nr_vectors = nr + 1;
503 ret = vfio_enable_vectors(vdev, true);
504 if (ret) {
312fd5f2 505 error_report("vfio: failed to enable vectors, %d", ret);
65501a74 506 }
65501a74 507 } else {
1a403133
AW
508 int argsz;
509 struct vfio_irq_set *irq_set;
510 int32_t *pfd;
511
512 argsz = sizeof(*irq_set) + sizeof(*pfd);
513
514 irq_set = g_malloc0(argsz);
515 irq_set->argsz = argsz;
516 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
517 VFIO_IRQ_SET_ACTION_TRIGGER;
518 irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
519 irq_set->start = nr;
520 irq_set->count = 1;
521 pfd = (int32_t *)&irq_set->data;
522
f4d45d47
AW
523 if (vector->virq >= 0) {
524 *pfd = event_notifier_get_fd(&vector->kvm_interrupt);
525 } else {
526 *pfd = event_notifier_get_fd(&vector->interrupt);
527 }
1a403133 528
5546a621 529 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
1a403133 530 g_free(irq_set);
65501a74 531 if (ret) {
312fd5f2 532 error_report("vfio: failed to modify vector, %d", ret);
65501a74 533 }
65501a74
AW
534 }
535
536 return 0;
537}
538
b0223e29
AW
539static int vfio_msix_vector_use(PCIDevice *pdev,
540 unsigned int nr, MSIMessage msg)
541{
542 return vfio_msix_vector_do_use(pdev, nr, &msg, vfio_msi_interrupt);
543}
544
65501a74
AW
545static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr)
546{
9ee27d73 547 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
65501a74 548 VFIOMSIVector *vector = &vdev->msi_vectors[nr];
65501a74 549
df92ee44 550 trace_vfio_msix_vector_release(vdev->vbasedev.name, nr);
65501a74
AW
551
552 /*
f4d45d47
AW
553 * There are still old guests that mask and unmask vectors on every
554 * interrupt. If we're using QEMU bypass with a KVM irqfd, leave all of
555 * the KVM setup in place, simply switch VFIO to use the non-bypass
556 * eventfd. We'll then fire the interrupt through QEMU and the MSI-X
557 * core will mask the interrupt and set pending bits, allowing it to
558 * be re-asserted on unmask. Nothing to do if already using QEMU mode.
65501a74 559 */
f4d45d47
AW
560 if (vector->virq >= 0) {
561 int argsz;
562 struct vfio_irq_set *irq_set;
563 int32_t *pfd;
1a403133 564
f4d45d47 565 argsz = sizeof(*irq_set) + sizeof(*pfd);
1a403133 566
f4d45d47
AW
567 irq_set = g_malloc0(argsz);
568 irq_set->argsz = argsz;
569 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
570 VFIO_IRQ_SET_ACTION_TRIGGER;
571 irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
572 irq_set->start = nr;
573 irq_set->count = 1;
574 pfd = (int32_t *)&irq_set->data;
1a403133 575
f4d45d47 576 *pfd = event_notifier_get_fd(&vector->interrupt);
1a403133 577
5546a621 578 ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
65501a74 579
f4d45d47 580 g_free(irq_set);
65501a74 581 }
65501a74
AW
582}
583
0de70dc7 584static void vfio_msix_enable(VFIOPCIDevice *vdev)
fd704adc
AW
585{
586 vfio_disable_interrupts(vdev);
587
588 vdev->msi_vectors = g_malloc0(vdev->msix->entries * sizeof(VFIOMSIVector));
589
590 vdev->interrupt = VFIO_INT_MSIX;
591
b0223e29
AW
592 /*
593 * Some communication channels between VF & PF or PF & fw rely on the
594 * physical state of the device and expect that enabling MSI-X from the
595 * guest enables the same on the host. When our guest is Linux, the
596 * guest driver call to pci_enable_msix() sets the enabling bit in the
597 * MSI-X capability, but leaves the vector table masked. We therefore
598 * can't rely on a vector_use callback (from request_irq() in the guest)
599 * to switch the physical device into MSI-X mode because that may come a
600 * long time after pci_enable_msix(). This code enables vector 0 with
601 * triggering to userspace, then immediately release the vector, leaving
602 * the physical device with no vectors enabled, but MSI-X enabled, just
603 * like the guest view.
604 */
605 vfio_msix_vector_do_use(&vdev->pdev, 0, NULL, NULL);
606 vfio_msix_vector_release(&vdev->pdev, 0);
607
fd704adc 608 if (msix_set_vector_notifiers(&vdev->pdev, vfio_msix_vector_use,
bbef882c 609 vfio_msix_vector_release, NULL)) {
312fd5f2 610 error_report("vfio: msix_set_vector_notifiers failed");
fd704adc
AW
611 }
612
0de70dc7 613 trace_vfio_msix_enable(vdev->vbasedev.name);
fd704adc
AW
614}
615
0de70dc7 616static void vfio_msi_enable(VFIOPCIDevice *vdev)
65501a74
AW
617{
618 int ret, i;
619
620 vfio_disable_interrupts(vdev);
621
622 vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev);
623retry:
624 vdev->msi_vectors = g_malloc0(vdev->nr_vectors * sizeof(VFIOMSIVector));
625
626 for (i = 0; i < vdev->nr_vectors; i++) {
65501a74 627 VFIOMSIVector *vector = &vdev->msi_vectors[i];
9b3af4c0 628 MSIMessage msg = msi_get_message(&vdev->pdev, i);
65501a74
AW
629
630 vector->vdev = vdev;
f4d45d47 631 vector->virq = -1;
65501a74
AW
632 vector->use = true;
633
634 if (event_notifier_init(&vector->interrupt, 0)) {
312fd5f2 635 error_report("vfio: Error: event_notifier_init failed");
65501a74
AW
636 }
637
f4d45d47
AW
638 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
639 vfio_msi_interrupt, NULL, vector);
640
65501a74
AW
641 /*
642 * Attempt to enable route through KVM irqchip,
643 * default to userspace handling if unavailable.
644 */
46746dba 645 vfio_add_kvm_msi_virq(vdev, vector, &msg, false);
65501a74
AW
646 }
647
f4d45d47
AW
648 /* Set interrupt type prior to possible interrupts */
649 vdev->interrupt = VFIO_INT_MSI;
650
65501a74
AW
651 ret = vfio_enable_vectors(vdev, false);
652 if (ret) {
653 if (ret < 0) {
312fd5f2 654 error_report("vfio: Error: Failed to setup MSI fds: %m");
65501a74
AW
655 } else if (ret != vdev->nr_vectors) {
656 error_report("vfio: Error: Failed to enable %d "
312fd5f2 657 "MSI vectors, retry with %d", vdev->nr_vectors, ret);
65501a74
AW
658 }
659
660 for (i = 0; i < vdev->nr_vectors; i++) {
661 VFIOMSIVector *vector = &vdev->msi_vectors[i];
662 if (vector->virq >= 0) {
f4d45d47 663 vfio_remove_kvm_msi_virq(vector);
65501a74 664 }
f4d45d47
AW
665 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
666 NULL, NULL, NULL);
65501a74
AW
667 event_notifier_cleanup(&vector->interrupt);
668 }
669
670 g_free(vdev->msi_vectors);
671
672 if (ret > 0 && ret != vdev->nr_vectors) {
673 vdev->nr_vectors = ret;
674 goto retry;
675 }
676 vdev->nr_vectors = 0;
677
f4d45d47
AW
678 /*
679 * Failing to setup MSI doesn't really fall within any specification.
680 * Let's try leaving interrupts disabled and hope the guest figures
681 * out to fall back to INTx for this device.
682 */
683 error_report("vfio: Error: Failed to enable MSI");
684 vdev->interrupt = VFIO_INT_NONE;
685
65501a74
AW
686 return;
687 }
688
0de70dc7 689 trace_vfio_msi_enable(vdev->vbasedev.name, vdev->nr_vectors);
65501a74
AW
690}
691
0de70dc7 692static void vfio_msi_disable_common(VFIOPCIDevice *vdev)
fd704adc 693{
f4d45d47
AW
694 int i;
695
696 for (i = 0; i < vdev->nr_vectors; i++) {
697 VFIOMSIVector *vector = &vdev->msi_vectors[i];
698 if (vdev->msi_vectors[i].use) {
699 if (vector->virq >= 0) {
700 vfio_remove_kvm_msi_virq(vector);
701 }
702 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
703 NULL, NULL, NULL);
704 event_notifier_cleanup(&vector->interrupt);
705 }
706 }
707
fd704adc
AW
708 g_free(vdev->msi_vectors);
709 vdev->msi_vectors = NULL;
710 vdev->nr_vectors = 0;
711 vdev->interrupt = VFIO_INT_NONE;
712
870cb6f1 713 vfio_intx_enable(vdev);
fd704adc
AW
714}
715
0de70dc7 716static void vfio_msix_disable(VFIOPCIDevice *vdev)
fd704adc 717{
3e40ba0f
AW
718 int i;
719
fd704adc
AW
720 msix_unset_vector_notifiers(&vdev->pdev);
721
3e40ba0f
AW
722 /*
723 * MSI-X will only release vectors if MSI-X is still enabled on the
724 * device, check through the rest and release it ourselves if necessary.
725 */
726 for (i = 0; i < vdev->nr_vectors; i++) {
727 if (vdev->msi_vectors[i].use) {
728 vfio_msix_vector_release(&vdev->pdev, i);
f4d45d47 729 msix_vector_unuse(&vdev->pdev, i);
3e40ba0f
AW
730 }
731 }
732
fd704adc 733 if (vdev->nr_vectors) {
5546a621 734 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);
fd704adc
AW
735 }
736
0de70dc7 737 vfio_msi_disable_common(vdev);
fd704adc 738
0de70dc7 739 trace_vfio_msix_disable(vdev->vbasedev.name);
fd704adc
AW
740}
741
0de70dc7 742static void vfio_msi_disable(VFIOPCIDevice *vdev)
65501a74 743{
5546a621 744 vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSI_IRQ_INDEX);
0de70dc7 745 vfio_msi_disable_common(vdev);
65501a74 746
0de70dc7 747 trace_vfio_msi_disable(vdev->vbasedev.name);
65501a74
AW
748}
749
9ee27d73 750static void vfio_update_msi(VFIOPCIDevice *vdev)
c7679d45
AW
751{
752 int i;
753
754 for (i = 0; i < vdev->nr_vectors; i++) {
755 VFIOMSIVector *vector = &vdev->msi_vectors[i];
756 MSIMessage msg;
757
758 if (!vector->use || vector->virq < 0) {
759 continue;
760 }
761
762 msg = msi_get_message(&vdev->pdev, i);
f4d45d47 763 vfio_update_kvm_msi_virq(vector, msg);
c7679d45
AW
764 }
765}
766
9ee27d73 767static void vfio_pci_load_rom(VFIOPCIDevice *vdev)
6f864e6e
AW
768{
769 struct vfio_region_info reg_info = {
770 .argsz = sizeof(reg_info),
771 .index = VFIO_PCI_ROM_REGION_INDEX
772 };
773 uint64_t size;
774 off_t off = 0;
7d489dcd 775 ssize_t bytes;
6f864e6e 776
5546a621 777 if (ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info)) {
6f864e6e
AW
778 error_report("vfio: Error getting ROM info: %m");
779 return;
780 }
781
df92ee44 782 trace_vfio_pci_load_rom(vdev->vbasedev.name, (unsigned long)reg_info.size,
385f57cf
EA
783 (unsigned long)reg_info.offset,
784 (unsigned long)reg_info.flags);
6f864e6e
AW
785
786 vdev->rom_size = size = reg_info.size;
787 vdev->rom_offset = reg_info.offset;
788
789 if (!vdev->rom_size) {
e638073c 790 vdev->rom_read_failed = true;
d20b43df 791 error_report("vfio-pci: Cannot read device rom at "
df92ee44 792 "%s", vdev->vbasedev.name);
d20b43df
BD
793 error_printf("Device option ROM contents are probably invalid "
794 "(check dmesg).\nSkip option ROM probe with rombar=0, "
795 "or load from file with romfile=\n");
6f864e6e
AW
796 return;
797 }
798
799 vdev->rom = g_malloc(size);
800 memset(vdev->rom, 0xff, size);
801
802 while (size) {
5546a621
EA
803 bytes = pread(vdev->vbasedev.fd, vdev->rom + off,
804 size, vdev->rom_offset + off);
6f864e6e
AW
805 if (bytes == 0) {
806 break;
807 } else if (bytes > 0) {
808 off += bytes;
809 size -= bytes;
810 } else {
811 if (errno == EINTR || errno == EAGAIN) {
812 continue;
813 }
814 error_report("vfio: Error reading device ROM: %m");
815 break;
816 }
817 }
818}
819
820static uint64_t vfio_rom_read(void *opaque, hwaddr addr, unsigned size)
821{
9ee27d73 822 VFIOPCIDevice *vdev = opaque;
75bd0c72
ND
823 union {
824 uint8_t byte;
825 uint16_t word;
826 uint32_t dword;
827 uint64_t qword;
828 } val;
829 uint64_t data = 0;
6f864e6e
AW
830
831 /* Load the ROM lazily when the guest tries to read it */
db01eedb 832 if (unlikely(!vdev->rom && !vdev->rom_read_failed)) {
6f864e6e
AW
833 vfio_pci_load_rom(vdev);
834 }
835
6758008e 836 memcpy(&val, vdev->rom + addr,
6f864e6e
AW
837 (addr < vdev->rom_size) ? MIN(size, vdev->rom_size - addr) : 0);
838
75bd0c72
ND
839 switch (size) {
840 case 1:
841 data = val.byte;
842 break;
843 case 2:
844 data = le16_to_cpu(val.word);
845 break;
846 case 4:
847 data = le32_to_cpu(val.dword);
848 break;
849 default:
850 hw_error("vfio: unsupported read size, %d bytes\n", size);
851 break;
852 }
853
df92ee44 854 trace_vfio_rom_read(vdev->vbasedev.name, addr, size, data);
6f864e6e 855
75bd0c72 856 return data;
6f864e6e
AW
857}
858
64fa25a0
AW
859static void vfio_rom_write(void *opaque, hwaddr addr,
860 uint64_t data, unsigned size)
861{
862}
863
6f864e6e
AW
864static const MemoryRegionOps vfio_rom_ops = {
865 .read = vfio_rom_read,
64fa25a0 866 .write = vfio_rom_write,
6758008e 867 .endianness = DEVICE_LITTLE_ENDIAN,
6f864e6e
AW
868};
869
9ee27d73 870static void vfio_pci_size_rom(VFIOPCIDevice *vdev)
6f864e6e 871{
b1c50c5f 872 uint32_t orig, size = cpu_to_le32((uint32_t)PCI_ROM_ADDRESS_MASK);
6f864e6e 873 off_t offset = vdev->config_offset + PCI_ROM_ADDRESS;
4b943029 874 DeviceState *dev = DEVICE(vdev);
6f864e6e 875 char name[32];
5546a621 876 int fd = vdev->vbasedev.fd;
6f864e6e
AW
877
878 if (vdev->pdev.romfile || !vdev->pdev.rom_bar) {
4b943029
BD
879 /* Since pci handles romfile, just print a message and return */
880 if (vfio_blacklist_opt_rom(vdev) && vdev->pdev.romfile) {
881 error_printf("Warning : Device at %04x:%02x:%02x.%x "
882 "is known to cause system instability issues during "
883 "option rom execution. "
884 "Proceeding anyway since user specified romfile\n",
885 vdev->host.domain, vdev->host.bus, vdev->host.slot,
886 vdev->host.function);
887 }
6f864e6e
AW
888 return;
889 }
890
891 /*
892 * Use the same size ROM BAR as the physical device. The contents
893 * will get filled in later when the guest tries to read it.
894 */
5546a621
EA
895 if (pread(fd, &orig, 4, offset) != 4 ||
896 pwrite(fd, &size, 4, offset) != 4 ||
897 pread(fd, &size, 4, offset) != 4 ||
898 pwrite(fd, &orig, 4, offset) != 4) {
6f864e6e
AW
899 error_report("%s(%04x:%02x:%02x.%x) failed: %m",
900 __func__, vdev->host.domain, vdev->host.bus,
901 vdev->host.slot, vdev->host.function);
902 return;
903 }
904
b1c50c5f 905 size = ~(le32_to_cpu(size) & PCI_ROM_ADDRESS_MASK) + 1;
6f864e6e
AW
906
907 if (!size) {
908 return;
909 }
910
4b943029
BD
911 if (vfio_blacklist_opt_rom(vdev)) {
912 if (dev->opts && qemu_opt_get(dev->opts, "rombar")) {
913 error_printf("Warning : Device at %04x:%02x:%02x.%x "
914 "is known to cause system instability issues during "
915 "option rom execution. "
916 "Proceeding anyway since user specified non zero value for "
917 "rombar\n",
918 vdev->host.domain, vdev->host.bus, vdev->host.slot,
919 vdev->host.function);
920 } else {
921 error_printf("Warning : Rom loading for device at "
922 "%04x:%02x:%02x.%x has been disabled due to "
923 "system instability issues. "
924 "Specify rombar=1 or romfile to force\n",
925 vdev->host.domain, vdev->host.bus, vdev->host.slot,
926 vdev->host.function);
927 return;
928 }
929 }
930
df92ee44 931 trace_vfio_pci_size_rom(vdev->vbasedev.name, size);
6f864e6e
AW
932
933 snprintf(name, sizeof(name), "vfio[%04x:%02x:%02x.%x].rom",
934 vdev->host.domain, vdev->host.bus, vdev->host.slot,
935 vdev->host.function);
936
937 memory_region_init_io(&vdev->pdev.rom, OBJECT(vdev),
938 &vfio_rom_ops, vdev, name, size);
939
940 pci_register_bar(&vdev->pdev, PCI_ROM_SLOT,
941 PCI_BASE_ADDRESS_SPACE_MEMORY, &vdev->pdev.rom);
942
943 vdev->pdev.has_rom = true;
e638073c 944 vdev->rom_read_failed = false;
6f864e6e
AW
945}
946
c00d61d8 947void vfio_vga_write(void *opaque, hwaddr addr,
f15689c7
AW
948 uint64_t data, unsigned size)
949{
950 VFIOVGARegion *region = opaque;
951 VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
952 union {
953 uint8_t byte;
954 uint16_t word;
955 uint32_t dword;
956 uint64_t qword;
957 } buf;
958 off_t offset = vga->fd_offset + region->offset + addr;
959
960 switch (size) {
961 case 1:
962 buf.byte = data;
963 break;
964 case 2:
965 buf.word = cpu_to_le16(data);
966 break;
967 case 4:
968 buf.dword = cpu_to_le32(data);
969 break;
970 default:
4e505ddd 971 hw_error("vfio: unsupported write size, %d bytes", size);
f15689c7
AW
972 break;
973 }
974
975 if (pwrite(vga->fd, &buf, size, offset) != size) {
976 error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m",
977 __func__, region->offset + addr, data, size);
978 }
979
385f57cf 980 trace_vfio_vga_write(region->offset + addr, data, size);
f15689c7
AW
981}
982
c00d61d8 983uint64_t vfio_vga_read(void *opaque, hwaddr addr, unsigned size)
f15689c7
AW
984{
985 VFIOVGARegion *region = opaque;
986 VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
987 union {
988 uint8_t byte;
989 uint16_t word;
990 uint32_t dword;
991 uint64_t qword;
992 } buf;
993 uint64_t data = 0;
994 off_t offset = vga->fd_offset + region->offset + addr;
995
996 if (pread(vga->fd, &buf, size, offset) != size) {
997 error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m",
998 __func__, region->offset + addr, size);
999 return (uint64_t)-1;
1000 }
1001
1002 switch (size) {
1003 case 1:
1004 data = buf.byte;
1005 break;
1006 case 2:
1007 data = le16_to_cpu(buf.word);
1008 break;
1009 case 4:
1010 data = le32_to_cpu(buf.dword);
1011 break;
1012 default:
4e505ddd 1013 hw_error("vfio: unsupported read size, %d bytes", size);
f15689c7
AW
1014 break;
1015 }
1016
385f57cf 1017 trace_vfio_vga_read(region->offset + addr, size, data);
f15689c7
AW
1018
1019 return data;
1020}
1021
1022static const MemoryRegionOps vfio_vga_ops = {
1023 .read = vfio_vga_read,
1024 .write = vfio_vga_write,
1025 .endianness = DEVICE_LITTLE_ENDIAN,
1026};
1027
65501a74
AW
1028/*
1029 * PCI config space
1030 */
c00d61d8 1031uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len)
65501a74 1032{
9ee27d73 1033 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
4b5d5e87 1034 uint32_t emu_bits = 0, emu_val = 0, phys_val = 0, val;
65501a74 1035
4b5d5e87
AW
1036 memcpy(&emu_bits, vdev->emulated_config_bits + addr, len);
1037 emu_bits = le32_to_cpu(emu_bits);
65501a74 1038
4b5d5e87
AW
1039 if (emu_bits) {
1040 emu_val = pci_default_read_config(pdev, addr, len);
1041 }
1042
1043 if (~emu_bits & (0xffffffffU >> (32 - len * 8))) {
1044 ssize_t ret;
1045
5546a621
EA
1046 ret = pread(vdev->vbasedev.fd, &phys_val, len,
1047 vdev->config_offset + addr);
4b5d5e87 1048 if (ret != len) {
312fd5f2 1049 error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x) failed: %m",
65501a74
AW
1050 __func__, vdev->host.domain, vdev->host.bus,
1051 vdev->host.slot, vdev->host.function, addr, len);
1052 return -errno;
1053 }
4b5d5e87 1054 phys_val = le32_to_cpu(phys_val);
65501a74
AW
1055 }
1056
4b5d5e87 1057 val = (emu_val & emu_bits) | (phys_val & ~emu_bits);
65501a74 1058
df92ee44 1059 trace_vfio_pci_read_config(vdev->vbasedev.name, addr, len, val);
65501a74
AW
1060
1061 return val;
1062}
1063
c00d61d8
AW
1064void vfio_pci_write_config(PCIDevice *pdev,
1065 uint32_t addr, uint32_t val, int len)
65501a74 1066{
9ee27d73 1067 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
65501a74
AW
1068 uint32_t val_le = cpu_to_le32(val);
1069
df92ee44 1070 trace_vfio_pci_write_config(vdev->vbasedev.name, addr, val, len);
65501a74
AW
1071
1072 /* Write everything to VFIO, let it filter out what we can't write */
5546a621
EA
1073 if (pwrite(vdev->vbasedev.fd, &val_le, len, vdev->config_offset + addr)
1074 != len) {
312fd5f2 1075 error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x, 0x%x) failed: %m",
65501a74
AW
1076 __func__, vdev->host.domain, vdev->host.bus,
1077 vdev->host.slot, vdev->host.function, addr, val, len);
1078 }
1079
65501a74
AW
1080 /* MSI/MSI-X Enabling/Disabling */
1081 if (pdev->cap_present & QEMU_PCI_CAP_MSI &&
1082 ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {
1083 int is_enabled, was_enabled = msi_enabled(pdev);
1084
1085 pci_default_write_config(pdev, addr, val, len);
1086
1087 is_enabled = msi_enabled(pdev);
1088
c7679d45
AW
1089 if (!was_enabled) {
1090 if (is_enabled) {
0de70dc7 1091 vfio_msi_enable(vdev);
c7679d45
AW
1092 }
1093 } else {
1094 if (!is_enabled) {
0de70dc7 1095 vfio_msi_disable(vdev);
c7679d45
AW
1096 } else {
1097 vfio_update_msi(vdev);
1098 }
65501a74 1099 }
4b5d5e87 1100 } else if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
65501a74
AW
1101 ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {
1102 int is_enabled, was_enabled = msix_enabled(pdev);
1103
1104 pci_default_write_config(pdev, addr, val, len);
1105
1106 is_enabled = msix_enabled(pdev);
1107
1108 if (!was_enabled && is_enabled) {
0de70dc7 1109 vfio_msix_enable(vdev);
65501a74 1110 } else if (was_enabled && !is_enabled) {
0de70dc7 1111 vfio_msix_disable(vdev);
65501a74 1112 }
4b5d5e87
AW
1113 } else {
1114 /* Write everything to QEMU to keep emulated bits correct */
1115 pci_default_write_config(pdev, addr, val, len);
65501a74
AW
1116 }
1117}
1118
65501a74
AW
1119/*
1120 * Interrupt setup
1121 */
9ee27d73 1122static void vfio_disable_interrupts(VFIOPCIDevice *vdev)
65501a74 1123{
b3e27c3a
AW
1124 /*
1125 * More complicated than it looks. Disabling MSI/X transitions the
1126 * device to INTx mode (if supported). Therefore we need to first
1127 * disable MSI/X and then cleanup by disabling INTx.
1128 */
1129 if (vdev->interrupt == VFIO_INT_MSIX) {
0de70dc7 1130 vfio_msix_disable(vdev);
b3e27c3a 1131 } else if (vdev->interrupt == VFIO_INT_MSI) {
0de70dc7 1132 vfio_msi_disable(vdev);
b3e27c3a
AW
1133 }
1134
1135 if (vdev->interrupt == VFIO_INT_INTx) {
870cb6f1 1136 vfio_intx_disable(vdev);
65501a74
AW
1137 }
1138}
1139
0de70dc7 1140static int vfio_msi_setup(VFIOPCIDevice *vdev, int pos)
65501a74
AW
1141{
1142 uint16_t ctrl;
1143 bool msi_64bit, msi_maskbit;
1144 int ret, entries;
1145
5546a621 1146 if (pread(vdev->vbasedev.fd, &ctrl, sizeof(ctrl),
65501a74
AW
1147 vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
1148 return -errno;
1149 }
1150 ctrl = le16_to_cpu(ctrl);
1151
1152 msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT);
1153 msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT);
1154 entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1);
1155
0de70dc7 1156 trace_vfio_msi_setup(vdev->vbasedev.name, pos);
65501a74
AW
1157
1158 ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit);
1159 if (ret < 0) {
e43b9a5a
AW
1160 if (ret == -ENOTSUP) {
1161 return 0;
1162 }
312fd5f2 1163 error_report("vfio: msi_init failed");
65501a74
AW
1164 return ret;
1165 }
1166 vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0);
1167
1168 return 0;
1169}
1170
1171/*
1172 * We don't have any control over how pci_add_capability() inserts
1173 * capabilities into the chain. In order to setup MSI-X we need a
1174 * MemoryRegion for the BAR. In order to setup the BAR and not
1175 * attempt to mmap the MSI-X table area, which VFIO won't allow, we
1176 * need to first look for where the MSI-X table lives. So we
1177 * unfortunately split MSI-X setup across two functions.
1178 */
0de70dc7 1179static int vfio_msix_early_setup(VFIOPCIDevice *vdev)
65501a74
AW
1180{
1181 uint8_t pos;
1182 uint16_t ctrl;
1183 uint32_t table, pba;
5546a621 1184 int fd = vdev->vbasedev.fd;
b5bd049f 1185 VFIOMSIXInfo *msix;
65501a74
AW
1186
1187 pos = pci_find_capability(&vdev->pdev, PCI_CAP_ID_MSIX);
1188 if (!pos) {
1189 return 0;
1190 }
1191
5546a621 1192 if (pread(fd, &ctrl, sizeof(ctrl),
65501a74
AW
1193 vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
1194 return -errno;
1195 }
1196
5546a621 1197 if (pread(fd, &table, sizeof(table),
65501a74
AW
1198 vdev->config_offset + pos + PCI_MSIX_TABLE) != sizeof(table)) {
1199 return -errno;
1200 }
1201
5546a621 1202 if (pread(fd, &pba, sizeof(pba),
65501a74
AW
1203 vdev->config_offset + pos + PCI_MSIX_PBA) != sizeof(pba)) {
1204 return -errno;
1205 }
1206
1207 ctrl = le16_to_cpu(ctrl);
1208 table = le32_to_cpu(table);
1209 pba = le32_to_cpu(pba);
1210
b5bd049f
AW
1211 msix = g_malloc0(sizeof(*msix));
1212 msix->table_bar = table & PCI_MSIX_FLAGS_BIRMASK;
1213 msix->table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
1214 msix->pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK;
1215 msix->pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
1216 msix->entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
65501a74 1217
43302969
GL
1218 /*
1219 * Test the size of the pba_offset variable and catch if it extends outside
1220 * of the specified BAR. If it is the case, we need to apply a hardware
1221 * specific quirk if the device is known or we have a broken configuration.
1222 */
b5bd049f 1223 if (msix->pba_offset >= vdev->bars[msix->pba_bar].region.size) {
43302969
GL
1224 /*
1225 * Chelsio T5 Virtual Function devices are encoded as 0x58xx for T5
1226 * adapters. The T5 hardware returns an incorrect value of 0x8000 for
1227 * the VF PBA offset while the BAR itself is only 8k. The correct value
1228 * is 0x1000, so we hard code that here.
1229 */
ff635e37
AW
1230 if (vdev->vendor_id == PCI_VENDOR_ID_CHELSIO &&
1231 (vdev->device_id & 0xff00) == 0x5800) {
b5bd049f 1232 msix->pba_offset = 0x1000;
43302969
GL
1233 } else {
1234 error_report("vfio: Hardware reports invalid configuration, "
1235 "MSIX PBA outside of specified BAR");
b5bd049f 1236 g_free(msix);
43302969
GL
1237 return -EINVAL;
1238 }
1239 }
1240
0de70dc7 1241 trace_vfio_msix_early_setup(vdev->vbasedev.name, pos, msix->table_bar,
b5bd049f
AW
1242 msix->table_offset, msix->entries);
1243 vdev->msix = msix;
65501a74
AW
1244
1245 return 0;
1246}
1247
0de70dc7 1248static int vfio_msix_setup(VFIOPCIDevice *vdev, int pos)
65501a74
AW
1249{
1250 int ret;
1251
65501a74 1252 ret = msix_init(&vdev->pdev, vdev->msix->entries,
a664477d 1253 &vdev->bars[vdev->msix->table_bar].region.mem,
65501a74 1254 vdev->msix->table_bar, vdev->msix->table_offset,
a664477d 1255 &vdev->bars[vdev->msix->pba_bar].region.mem,
65501a74
AW
1256 vdev->msix->pba_bar, vdev->msix->pba_offset, pos);
1257 if (ret < 0) {
e43b9a5a
AW
1258 if (ret == -ENOTSUP) {
1259 return 0;
1260 }
312fd5f2 1261 error_report("vfio: msix_init failed");
65501a74
AW
1262 return ret;
1263 }
1264
65501a74
AW
1265 return 0;
1266}
1267
9ee27d73 1268static void vfio_teardown_msi(VFIOPCIDevice *vdev)
65501a74
AW
1269{
1270 msi_uninit(&vdev->pdev);
1271
1272 if (vdev->msix) {
a664477d
EA
1273 msix_uninit(&vdev->pdev,
1274 &vdev->bars[vdev->msix->table_bar].region.mem,
1275 &vdev->bars[vdev->msix->pba_bar].region.mem);
65501a74
AW
1276 }
1277}
1278
1279/*
1280 * Resource setup
1281 */
9ee27d73 1282static void vfio_mmap_set_enabled(VFIOPCIDevice *vdev, bool enabled)
65501a74
AW
1283{
1284 int i;
1285
1286 for (i = 0; i < PCI_ROM_SLOT; i++) {
1287 VFIOBAR *bar = &vdev->bars[i];
1288
a664477d 1289 if (!bar->region.size) {
65501a74
AW
1290 continue;
1291 }
1292
a664477d 1293 memory_region_set_enabled(&bar->region.mmap_mem, enabled);
65501a74
AW
1294 if (vdev->msix && vdev->msix->table_bar == i) {
1295 memory_region_set_enabled(&vdev->msix->mmap_mem, enabled);
1296 }
1297 }
1298}
1299
ba5e6bfa 1300static void vfio_unregister_bar(VFIOPCIDevice *vdev, int nr)
65501a74
AW
1301{
1302 VFIOBAR *bar = &vdev->bars[nr];
1303
a664477d 1304 if (!bar->region.size) {
65501a74
AW
1305 return;
1306 }
1307
7076eabc
AW
1308 vfio_bar_quirk_teardown(vdev, nr);
1309
a664477d 1310 memory_region_del_subregion(&bar->region.mem, &bar->region.mmap_mem);
65501a74
AW
1311
1312 if (vdev->msix && vdev->msix->table_bar == nr) {
a664477d 1313 memory_region_del_subregion(&bar->region.mem, &vdev->msix->mmap_mem);
ba5e6bfa
PB
1314 }
1315}
1316
1317static void vfio_unmap_bar(VFIOPCIDevice *vdev, int nr)
1318{
1319 VFIOBAR *bar = &vdev->bars[nr];
1320
1321 if (!bar->region.size) {
1322 return;
1323 }
1324
1325 vfio_bar_quirk_free(vdev, nr);
1326
1327 munmap(bar->region.mmap, memory_region_size(&bar->region.mmap_mem));
1328
1329 if (vdev->msix && vdev->msix->table_bar == nr) {
65501a74
AW
1330 munmap(vdev->msix->mmap, memory_region_size(&vdev->msix->mmap_mem));
1331 }
65501a74
AW
1332}
1333
9ee27d73 1334static void vfio_map_bar(VFIOPCIDevice *vdev, int nr)
65501a74
AW
1335{
1336 VFIOBAR *bar = &vdev->bars[nr];
29c6e6df 1337 uint64_t size = bar->region.size;
65501a74
AW
1338 char name[64];
1339 uint32_t pci_bar;
1340 uint8_t type;
1341 int ret;
1342
1343 /* Skip both unimplemented BARs and the upper half of 64bit BARS. */
1344 if (!size) {
1345 return;
1346 }
1347
1348 snprintf(name, sizeof(name), "VFIO %04x:%02x:%02x.%x BAR %d",
1349 vdev->host.domain, vdev->host.bus, vdev->host.slot,
1350 vdev->host.function, nr);
1351
1352 /* Determine what type of BAR this is for registration */
5546a621 1353 ret = pread(vdev->vbasedev.fd, &pci_bar, sizeof(pci_bar),
65501a74
AW
1354 vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));
1355 if (ret != sizeof(pci_bar)) {
312fd5f2 1356 error_report("vfio: Failed to read BAR %d (%m)", nr);
65501a74
AW
1357 return;
1358 }
1359
1360 pci_bar = le32_to_cpu(pci_bar);
39360f0b
AW
1361 bar->ioport = (pci_bar & PCI_BASE_ADDRESS_SPACE_IO);
1362 bar->mem64 = bar->ioport ? 0 : (pci_bar & PCI_BASE_ADDRESS_MEM_TYPE_64);
1363 type = pci_bar & (bar->ioport ? ~PCI_BASE_ADDRESS_IO_MASK :
1364 ~PCI_BASE_ADDRESS_MEM_MASK);
65501a74
AW
1365
1366 /* A "slow" read/write mapping underlies all BARs */
a664477d 1367 memory_region_init_io(&bar->region.mem, OBJECT(vdev), &vfio_region_ops,
39360f0b 1368 bar, name, size);
a664477d 1369 pci_register_bar(&vdev->pdev, nr, type, &bar->region.mem);
65501a74
AW
1370
1371 /*
1372 * We can't mmap areas overlapping the MSIX vector table, so we
1373 * potentially insert a direct-mapped subregion before and after it.
1374 */
1375 if (vdev->msix && vdev->msix->table_bar == nr) {
f7ceed19 1376 size = vdev->msix->table_offset & qemu_real_host_page_mask;
65501a74
AW
1377 }
1378
1379 strncat(name, " mmap", sizeof(name) - strlen(name) - 1);
a664477d
EA
1380 if (vfio_mmap_region(OBJECT(vdev), &bar->region, &bar->region.mem,
1381 &bar->region.mmap_mem, &bar->region.mmap,
1382 size, 0, name)) {
312fd5f2 1383 error_report("%s unsupported. Performance may be slow", name);
65501a74
AW
1384 }
1385
1386 if (vdev->msix && vdev->msix->table_bar == nr) {
29c6e6df 1387 uint64_t start;
65501a74 1388
f7ceed19
PC
1389 start = REAL_HOST_PAGE_ALIGN((uint64_t)vdev->msix->table_offset +
1390 (vdev->msix->entries *
1391 PCI_MSIX_ENTRY_SIZE));
65501a74 1392
a664477d 1393 size = start < bar->region.size ? bar->region.size - start : 0;
65501a74
AW
1394 strncat(name, " msix-hi", sizeof(name) - strlen(name) - 1);
1395 /* VFIOMSIXInfo contains another MemoryRegion for this mapping */
a664477d
EA
1396 if (vfio_mmap_region(OBJECT(vdev), &bar->region, &bar->region.mem,
1397 &vdev->msix->mmap_mem,
65501a74 1398 &vdev->msix->mmap, size, start, name)) {
312fd5f2 1399 error_report("%s unsupported. Performance may be slow", name);
65501a74
AW
1400 }
1401 }
7076eabc
AW
1402
1403 vfio_bar_quirk_setup(vdev, nr);
65501a74
AW
1404}
1405
9ee27d73 1406static void vfio_map_bars(VFIOPCIDevice *vdev)
65501a74
AW
1407{
1408 int i;
1409
1410 for (i = 0; i < PCI_ROM_SLOT; i++) {
1411 vfio_map_bar(vdev, i);
1412 }
f15689c7
AW
1413
1414 if (vdev->has_vga) {
3c161542
PB
1415 memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_MEM].mem,
1416 OBJECT(vdev), &vfio_vga_ops,
f15689c7
AW
1417 &vdev->vga.region[QEMU_PCI_VGA_MEM],
1418 "vfio-vga-mmio@0xa0000",
1419 QEMU_PCI_VGA_MEM_SIZE);
3c161542
PB
1420 memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_IO_LO].mem,
1421 OBJECT(vdev), &vfio_vga_ops,
f15689c7
AW
1422 &vdev->vga.region[QEMU_PCI_VGA_IO_LO],
1423 "vfio-vga-io@0x3b0",
1424 QEMU_PCI_VGA_IO_LO_SIZE);
3c161542
PB
1425 memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem,
1426 OBJECT(vdev), &vfio_vga_ops,
f15689c7
AW
1427 &vdev->vga.region[QEMU_PCI_VGA_IO_HI],
1428 "vfio-vga-io@0x3c0",
1429 QEMU_PCI_VGA_IO_HI_SIZE);
1430
1431 pci_register_vga(&vdev->pdev, &vdev->vga.region[QEMU_PCI_VGA_MEM].mem,
1432 &vdev->vga.region[QEMU_PCI_VGA_IO_LO].mem,
1433 &vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem);
7076eabc 1434 vfio_vga_quirk_setup(vdev);
f15689c7 1435 }
65501a74
AW
1436}
1437
ba5e6bfa 1438static void vfio_unregister_bars(VFIOPCIDevice *vdev)
65501a74
AW
1439{
1440 int i;
1441
1442 for (i = 0; i < PCI_ROM_SLOT; i++) {
ba5e6bfa 1443 vfio_unregister_bar(vdev, i);
65501a74 1444 }
f15689c7
AW
1445
1446 if (vdev->has_vga) {
7076eabc 1447 vfio_vga_quirk_teardown(vdev);
f15689c7 1448 pci_unregister_vga(&vdev->pdev);
f15689c7 1449 }
65501a74
AW
1450}
1451
ba5e6bfa
PB
1452static void vfio_unmap_bars(VFIOPCIDevice *vdev)
1453{
1454 int i;
1455
1456 for (i = 0; i < PCI_ROM_SLOT; i++) {
1457 vfio_unmap_bar(vdev, i);
1458 }
1459
1460 if (vdev->has_vga) {
1461 vfio_vga_quirk_free(vdev);
1462 }
1463}
1464
65501a74
AW
1465/*
1466 * General setup
1467 */
1468static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos)
1469{
1470 uint8_t tmp, next = 0xff;
1471
1472 for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp;
1473 tmp = pdev->config[tmp + 1]) {
1474 if (tmp > pos && tmp < next) {
1475 next = tmp;
1476 }
1477 }
1478
1479 return next - pos;
1480}
1481
96adc5c7
AW
1482static void vfio_set_word_bits(uint8_t *buf, uint16_t val, uint16_t mask)
1483{
1484 pci_set_word(buf, (pci_get_word(buf) & ~mask) | val);
1485}
1486
9ee27d73 1487static void vfio_add_emulated_word(VFIOPCIDevice *vdev, int pos,
96adc5c7
AW
1488 uint16_t val, uint16_t mask)
1489{
1490 vfio_set_word_bits(vdev->pdev.config + pos, val, mask);
1491 vfio_set_word_bits(vdev->pdev.wmask + pos, ~mask, mask);
1492 vfio_set_word_bits(vdev->emulated_config_bits + pos, mask, mask);
1493}
1494
1495static void vfio_set_long_bits(uint8_t *buf, uint32_t val, uint32_t mask)
1496{
1497 pci_set_long(buf, (pci_get_long(buf) & ~mask) | val);
1498}
1499
9ee27d73 1500static void vfio_add_emulated_long(VFIOPCIDevice *vdev, int pos,
96adc5c7
AW
1501 uint32_t val, uint32_t mask)
1502{
1503 vfio_set_long_bits(vdev->pdev.config + pos, val, mask);
1504 vfio_set_long_bits(vdev->pdev.wmask + pos, ~mask, mask);
1505 vfio_set_long_bits(vdev->emulated_config_bits + pos, mask, mask);
1506}
1507
9ee27d73 1508static int vfio_setup_pcie_cap(VFIOPCIDevice *vdev, int pos, uint8_t size)
96adc5c7
AW
1509{
1510 uint16_t flags;
1511 uint8_t type;
1512
1513 flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS);
1514 type = (flags & PCI_EXP_FLAGS_TYPE) >> 4;
1515
1516 if (type != PCI_EXP_TYPE_ENDPOINT &&
1517 type != PCI_EXP_TYPE_LEG_END &&
1518 type != PCI_EXP_TYPE_RC_END) {
1519
1520 error_report("vfio: Assignment of PCIe type 0x%x "
1521 "devices is not currently supported", type);
1522 return -EINVAL;
1523 }
1524
1525 if (!pci_bus_is_express(vdev->pdev.bus)) {
1526 /*
1527 * Use express capability as-is on PCI bus. It doesn't make much
1528 * sense to even expose, but some drivers (ex. tg3) depend on it
1529 * and guests don't seem to be particular about it. We'll need
1530 * to revist this or force express devices to express buses if we
1531 * ever expose an IOMMU to the guest.
1532 */
1533 } else if (pci_bus_is_root(vdev->pdev.bus)) {
1534 /*
1535 * On a Root Complex bus Endpoints become Root Complex Integrated
1536 * Endpoints, which changes the type and clears the LNK & LNK2 fields.
1537 */
1538 if (type == PCI_EXP_TYPE_ENDPOINT) {
1539 vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
1540 PCI_EXP_TYPE_RC_END << 4,
1541 PCI_EXP_FLAGS_TYPE);
1542
1543 /* Link Capabilities, Status, and Control goes away */
1544 if (size > PCI_EXP_LNKCTL) {
1545 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0);
1546 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
1547 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0);
1548
1549#ifndef PCI_EXP_LNKCAP2
1550#define PCI_EXP_LNKCAP2 44
1551#endif
1552#ifndef PCI_EXP_LNKSTA2
1553#define PCI_EXP_LNKSTA2 50
1554#endif
1555 /* Link 2 Capabilities, Status, and Control goes away */
1556 if (size > PCI_EXP_LNKCAP2) {
1557 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0);
1558 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0);
1559 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0);
1560 }
1561 }
1562
1563 } else if (type == PCI_EXP_TYPE_LEG_END) {
1564 /*
1565 * Legacy endpoints don't belong on the root complex. Windows
1566 * seems to be happier with devices if we skip the capability.
1567 */
1568 return 0;
1569 }
1570
1571 } else {
1572 /*
1573 * Convert Root Complex Integrated Endpoints to regular endpoints.
1574 * These devices don't support LNK/LNK2 capabilities, so make them up.
1575 */
1576 if (type == PCI_EXP_TYPE_RC_END) {
1577 vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
1578 PCI_EXP_TYPE_ENDPOINT << 4,
1579 PCI_EXP_FLAGS_TYPE);
1580 vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP,
1581 PCI_EXP_LNK_MLW_1 | PCI_EXP_LNK_LS_25, ~0);
1582 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
1583 }
1584
1585 /* Mark the Link Status bits as emulated to allow virtual negotiation */
1586 vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA,
1587 pci_get_word(vdev->pdev.config + pos +
1588 PCI_EXP_LNKSTA),
1589 PCI_EXP_LNKCAP_MLW | PCI_EXP_LNKCAP_SLS);
1590 }
1591
1592 pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size);
1593 if (pos >= 0) {
1594 vdev->pdev.exp.exp_cap = pos;
1595 }
1596
1597 return pos;
1598}
1599
9ee27d73 1600static void vfio_check_pcie_flr(VFIOPCIDevice *vdev, uint8_t pos)
befe5176
AW
1601{
1602 uint32_t cap = pci_get_long(vdev->pdev.config + pos + PCI_EXP_DEVCAP);
1603
1604 if (cap & PCI_EXP_DEVCAP_FLR) {
df92ee44 1605 trace_vfio_check_pcie_flr(vdev->vbasedev.name);
befe5176
AW
1606 vdev->has_flr = true;
1607 }
1608}
1609
9ee27d73 1610static void vfio_check_pm_reset(VFIOPCIDevice *vdev, uint8_t pos)
befe5176
AW
1611{
1612 uint16_t csr = pci_get_word(vdev->pdev.config + pos + PCI_PM_CTRL);
1613
1614 if (!(csr & PCI_PM_CTRL_NO_SOFT_RESET)) {
df92ee44 1615 trace_vfio_check_pm_reset(vdev->vbasedev.name);
befe5176
AW
1616 vdev->has_pm_reset = true;
1617 }
1618}
1619
9ee27d73 1620static void vfio_check_af_flr(VFIOPCIDevice *vdev, uint8_t pos)
befe5176
AW
1621{
1622 uint8_t cap = pci_get_byte(vdev->pdev.config + pos + PCI_AF_CAP);
1623
1624 if ((cap & PCI_AF_CAP_TP) && (cap & PCI_AF_CAP_FLR)) {
df92ee44 1625 trace_vfio_check_af_flr(vdev->vbasedev.name);
befe5176
AW
1626 vdev->has_flr = true;
1627 }
1628}
1629
9ee27d73 1630static int vfio_add_std_cap(VFIOPCIDevice *vdev, uint8_t pos)
65501a74
AW
1631{
1632 PCIDevice *pdev = &vdev->pdev;
1633 uint8_t cap_id, next, size;
1634 int ret;
1635
1636 cap_id = pdev->config[pos];
1637 next = pdev->config[pos + 1];
1638
1639 /*
1640 * If it becomes important to configure capabilities to their actual
1641 * size, use this as the default when it's something we don't recognize.
1642 * Since QEMU doesn't actually handle many of the config accesses,
1643 * exact size doesn't seem worthwhile.
1644 */
1645 size = vfio_std_cap_max_size(pdev, pos);
1646
1647 /*
1648 * pci_add_capability always inserts the new capability at the head
1649 * of the chain. Therefore to end up with a chain that matches the
1650 * physical device, we insert from the end by making this recursive.
1651 * This is also why we pre-caclulate size above as cached config space
1652 * will be changed as we unwind the stack.
1653 */
1654 if (next) {
1655 ret = vfio_add_std_cap(vdev, next);
1656 if (ret) {
1657 return ret;
1658 }
1659 } else {
96adc5c7
AW
1660 /* Begin the rebuild, use QEMU emulated list bits */
1661 pdev->config[PCI_CAPABILITY_LIST] = 0;
1662 vdev->emulated_config_bits[PCI_CAPABILITY_LIST] = 0xff;
1663 vdev->emulated_config_bits[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
65501a74
AW
1664 }
1665
96adc5c7
AW
1666 /* Use emulated next pointer to allow dropping caps */
1667 pci_set_byte(vdev->emulated_config_bits + pos + 1, 0xff);
1668
65501a74
AW
1669 switch (cap_id) {
1670 case PCI_CAP_ID_MSI:
0de70dc7 1671 ret = vfio_msi_setup(vdev, pos);
65501a74 1672 break;
96adc5c7 1673 case PCI_CAP_ID_EXP:
befe5176 1674 vfio_check_pcie_flr(vdev, pos);
96adc5c7
AW
1675 ret = vfio_setup_pcie_cap(vdev, pos, size);
1676 break;
65501a74 1677 case PCI_CAP_ID_MSIX:
0de70dc7 1678 ret = vfio_msix_setup(vdev, pos);
65501a74 1679 break;
ba661818 1680 case PCI_CAP_ID_PM:
befe5176 1681 vfio_check_pm_reset(vdev, pos);
ba661818 1682 vdev->pm_cap = pos;
befe5176
AW
1683 ret = pci_add_capability(pdev, cap_id, pos, size);
1684 break;
1685 case PCI_CAP_ID_AF:
1686 vfio_check_af_flr(vdev, pos);
1687 ret = pci_add_capability(pdev, cap_id, pos, size);
1688 break;
65501a74
AW
1689 default:
1690 ret = pci_add_capability(pdev, cap_id, pos, size);
1691 break;
1692 }
1693
1694 if (ret < 0) {
1695 error_report("vfio: %04x:%02x:%02x.%x Error adding PCI capability "
312fd5f2 1696 "0x%x[0x%x]@0x%x: %d", vdev->host.domain,
65501a74
AW
1697 vdev->host.bus, vdev->host.slot, vdev->host.function,
1698 cap_id, size, pos, ret);
1699 return ret;
1700 }
1701
1702 return 0;
1703}
1704
9ee27d73 1705static int vfio_add_capabilities(VFIOPCIDevice *vdev)
65501a74
AW
1706{
1707 PCIDevice *pdev = &vdev->pdev;
1708
1709 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
1710 !pdev->config[PCI_CAPABILITY_LIST]) {
1711 return 0; /* Nothing to add */
1712 }
1713
1714 return vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST]);
1715}
1716
9ee27d73 1717static void vfio_pci_pre_reset(VFIOPCIDevice *vdev)
f16f39c3
AW
1718{
1719 PCIDevice *pdev = &vdev->pdev;
1720 uint16_t cmd;
1721
1722 vfio_disable_interrupts(vdev);
1723
1724 /* Make sure the device is in D0 */
1725 if (vdev->pm_cap) {
1726 uint16_t pmcsr;
1727 uint8_t state;
1728
1729 pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
1730 state = pmcsr & PCI_PM_CTRL_STATE_MASK;
1731 if (state) {
1732 pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
1733 vfio_pci_write_config(pdev, vdev->pm_cap + PCI_PM_CTRL, pmcsr, 2);
1734 /* vfio handles the necessary delay here */
1735 pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
1736 state = pmcsr & PCI_PM_CTRL_STATE_MASK;
1737 if (state) {
4e505ddd 1738 error_report("vfio: Unable to power on device, stuck in D%d",
f16f39c3
AW
1739 state);
1740 }
1741 }
1742 }
1743
1744 /*
1745 * Stop any ongoing DMA by disconecting I/O, MMIO, and bus master.
1746 * Also put INTx Disable in known state.
1747 */
1748 cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2);
1749 cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
1750 PCI_COMMAND_INTX_DISABLE);
1751 vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2);
1752}
1753
9ee27d73 1754static void vfio_pci_post_reset(VFIOPCIDevice *vdev)
f16f39c3 1755{
870cb6f1 1756 vfio_intx_enable(vdev);
f16f39c3
AW
1757}
1758
1759static bool vfio_pci_host_match(PCIHostDeviceAddress *host1,
1760 PCIHostDeviceAddress *host2)
1761{
1762 return (host1->domain == host2->domain && host1->bus == host2->bus &&
1763 host1->slot == host2->slot && host1->function == host2->function);
1764}
1765
9ee27d73 1766static int vfio_pci_hot_reset(VFIOPCIDevice *vdev, bool single)
f16f39c3
AW
1767{
1768 VFIOGroup *group;
1769 struct vfio_pci_hot_reset_info *info;
1770 struct vfio_pci_dependent_device *devices;
1771 struct vfio_pci_hot_reset *reset;
1772 int32_t *fds;
1773 int ret, i, count;
1774 bool multi = false;
1775
df92ee44 1776 trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
f16f39c3
AW
1777
1778 vfio_pci_pre_reset(vdev);
b47d8efa 1779 vdev->vbasedev.needs_reset = false;
f16f39c3
AW
1780
1781 info = g_malloc0(sizeof(*info));
1782 info->argsz = sizeof(*info);
1783
5546a621 1784 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
f16f39c3
AW
1785 if (ret && errno != ENOSPC) {
1786 ret = -errno;
1787 if (!vdev->has_pm_reset) {
1788 error_report("vfio: Cannot reset device %04x:%02x:%02x.%x, "
1789 "no available reset mechanism.", vdev->host.domain,
1790 vdev->host.bus, vdev->host.slot, vdev->host.function);
1791 }
1792 goto out_single;
1793 }
1794
1795 count = info->count;
1796 info = g_realloc(info, sizeof(*info) + (count * sizeof(*devices)));
1797 info->argsz = sizeof(*info) + (count * sizeof(*devices));
1798 devices = &info->devices[0];
1799
5546a621 1800 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
f16f39c3
AW
1801 if (ret) {
1802 ret = -errno;
1803 error_report("vfio: hot reset info failed: %m");
1804 goto out_single;
1805 }
1806
df92ee44 1807 trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
f16f39c3
AW
1808
1809 /* Verify that we have all the groups required */
1810 for (i = 0; i < info->count; i++) {
1811 PCIHostDeviceAddress host;
9ee27d73 1812 VFIOPCIDevice *tmp;
b47d8efa 1813 VFIODevice *vbasedev_iter;
f16f39c3
AW
1814
1815 host.domain = devices[i].segment;
1816 host.bus = devices[i].bus;
1817 host.slot = PCI_SLOT(devices[i].devfn);
1818 host.function = PCI_FUNC(devices[i].devfn);
1819
385f57cf 1820 trace_vfio_pci_hot_reset_dep_devices(host.domain,
f16f39c3
AW
1821 host.bus, host.slot, host.function, devices[i].group_id);
1822
1823 if (vfio_pci_host_match(&host, &vdev->host)) {
1824 continue;
1825 }
1826
62356b72 1827 QLIST_FOREACH(group, &vfio_group_list, next) {
f16f39c3
AW
1828 if (group->groupid == devices[i].group_id) {
1829 break;
1830 }
1831 }
1832
1833 if (!group) {
1834 if (!vdev->has_pm_reset) {
df92ee44 1835 error_report("vfio: Cannot reset device %s, "
f16f39c3 1836 "depends on group %d which is not owned.",
df92ee44 1837 vdev->vbasedev.name, devices[i].group_id);
f16f39c3
AW
1838 }
1839 ret = -EPERM;
1840 goto out;
1841 }
1842
1843 /* Prep dependent devices for reset and clear our marker. */
b47d8efa
EA
1844 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
1845 if (vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
1846 continue;
1847 }
1848 tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
f16f39c3
AW
1849 if (vfio_pci_host_match(&host, &tmp->host)) {
1850 if (single) {
f16f39c3
AW
1851 ret = -EINVAL;
1852 goto out_single;
1853 }
1854 vfio_pci_pre_reset(tmp);
b47d8efa 1855 tmp->vbasedev.needs_reset = false;
f16f39c3
AW
1856 multi = true;
1857 break;
1858 }
1859 }
1860 }
1861
1862 if (!single && !multi) {
f16f39c3
AW
1863 ret = -EINVAL;
1864 goto out_single;
1865 }
1866
1867 /* Determine how many group fds need to be passed */
1868 count = 0;
62356b72 1869 QLIST_FOREACH(group, &vfio_group_list, next) {
f16f39c3
AW
1870 for (i = 0; i < info->count; i++) {
1871 if (group->groupid == devices[i].group_id) {
1872 count++;
1873 break;
1874 }
1875 }
1876 }
1877
1878 reset = g_malloc0(sizeof(*reset) + (count * sizeof(*fds)));
1879 reset->argsz = sizeof(*reset) + (count * sizeof(*fds));
1880 fds = &reset->group_fds[0];
1881
1882 /* Fill in group fds */
62356b72 1883 QLIST_FOREACH(group, &vfio_group_list, next) {
f16f39c3
AW
1884 for (i = 0; i < info->count; i++) {
1885 if (group->groupid == devices[i].group_id) {
1886 fds[reset->count++] = group->fd;
1887 break;
1888 }
1889 }
1890 }
1891
1892 /* Bus reset! */
5546a621 1893 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
f16f39c3
AW
1894 g_free(reset);
1895
df92ee44 1896 trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
385f57cf 1897 ret ? "%m" : "Success");
f16f39c3
AW
1898
1899out:
1900 /* Re-enable INTx on affected devices */
1901 for (i = 0; i < info->count; i++) {
1902 PCIHostDeviceAddress host;
9ee27d73 1903 VFIOPCIDevice *tmp;
b47d8efa 1904 VFIODevice *vbasedev_iter;
f16f39c3
AW
1905
1906 host.domain = devices[i].segment;
1907 host.bus = devices[i].bus;
1908 host.slot = PCI_SLOT(devices[i].devfn);
1909 host.function = PCI_FUNC(devices[i].devfn);
1910
1911 if (vfio_pci_host_match(&host, &vdev->host)) {
1912 continue;
1913 }
1914
62356b72 1915 QLIST_FOREACH(group, &vfio_group_list, next) {
f16f39c3
AW
1916 if (group->groupid == devices[i].group_id) {
1917 break;
1918 }
1919 }
1920
1921 if (!group) {
1922 break;
1923 }
1924
b47d8efa
EA
1925 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
1926 if (vbasedev_iter->type != VFIO_DEVICE_TYPE_PCI) {
1927 continue;
1928 }
1929 tmp = container_of(vbasedev_iter, VFIOPCIDevice, vbasedev);
f16f39c3
AW
1930 if (vfio_pci_host_match(&host, &tmp->host)) {
1931 vfio_pci_post_reset(tmp);
1932 break;
1933 }
1934 }
1935 }
1936out_single:
1937 vfio_pci_post_reset(vdev);
1938 g_free(info);
1939
1940 return ret;
1941}
1942
1943/*
1944 * We want to differentiate hot reset of mulitple in-use devices vs hot reset
1945 * of a single in-use device. VFIO_DEVICE_RESET will already handle the case
1946 * of doing hot resets when there is only a single device per bus. The in-use
1947 * here refers to how many VFIODevices are affected. A hot reset that affects
1948 * multiple devices, but only a single in-use device, means that we can call
1949 * it from our bus ->reset() callback since the extent is effectively a single
1950 * device. This allows us to make use of it in the hotplug path. When there
1951 * are multiple in-use devices, we can only trigger the hot reset during a
1952 * system reset and thus from our reset handler. We separate _one vs _multi
1953 * here so that we don't overlap and do a double reset on the system reset
1954 * path where both our reset handler and ->reset() callback are used. Calling
1955 * _one() will only do a hot reset for the one in-use devices case, calling
1956 * _multi() will do nothing if a _one() would have been sufficient.
1957 */
9ee27d73 1958static int vfio_pci_hot_reset_one(VFIOPCIDevice *vdev)
f16f39c3
AW
1959{
1960 return vfio_pci_hot_reset(vdev, true);
1961}
1962
b47d8efa 1963static int vfio_pci_hot_reset_multi(VFIODevice *vbasedev)
f16f39c3 1964{
b47d8efa 1965 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
f16f39c3
AW
1966 return vfio_pci_hot_reset(vdev, false);
1967}
1968
b47d8efa
EA
1969static void vfio_pci_compute_needs_reset(VFIODevice *vbasedev)
1970{
1971 VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
1972 if (!vbasedev->reset_works || (!vdev->has_flr && vdev->has_pm_reset)) {
1973 vbasedev->needs_reset = true;
1974 }
1975}
1976
1977static VFIODeviceOps vfio_pci_ops = {
1978 .vfio_compute_needs_reset = vfio_pci_compute_needs_reset,
1979 .vfio_hot_reset_multi = vfio_pci_hot_reset_multi,
870cb6f1 1980 .vfio_eoi = vfio_intx_eoi,
b47d8efa
EA
1981};
1982
217e9fdc 1983static int vfio_populate_device(VFIOPCIDevice *vdev)
65501a74 1984{
217e9fdc 1985 VFIODevice *vbasedev = &vdev->vbasedev;
65501a74 1986 struct vfio_region_info reg_info = { .argsz = sizeof(reg_info) };
7b4b0e9e 1987 struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };
d13dd2d7 1988 int i, ret = -1;
65501a74
AW
1989
1990 /* Sanity check device */
d13dd2d7 1991 if (!(vbasedev->flags & VFIO_DEVICE_FLAGS_PCI)) {
312fd5f2 1992 error_report("vfio: Um, this isn't a PCI device");
65501a74
AW
1993 goto error;
1994 }
1995
d13dd2d7 1996 if (vbasedev->num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) {
312fd5f2 1997 error_report("vfio: unexpected number of io regions %u",
d13dd2d7 1998 vbasedev->num_regions);
65501a74
AW
1999 goto error;
2000 }
2001
d13dd2d7
EA
2002 if (vbasedev->num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) {
2003 error_report("vfio: unexpected number of irqs %u", vbasedev->num_irqs);
65501a74
AW
2004 goto error;
2005 }
2006
2007 for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
2008 reg_info.index = i;
2009
d13dd2d7 2010 ret = ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
65501a74 2011 if (ret) {
312fd5f2 2012 error_report("vfio: Error getting region %d info: %m", i);
65501a74
AW
2013 goto error;
2014 }
2015
d13dd2d7
EA
2016 trace_vfio_populate_device_region(vbasedev->name, i,
2017 (unsigned long)reg_info.size,
2018 (unsigned long)reg_info.offset,
2019 (unsigned long)reg_info.flags);
65501a74 2020
d13dd2d7 2021 vdev->bars[i].region.vbasedev = vbasedev;
a664477d
EA
2022 vdev->bars[i].region.flags = reg_info.flags;
2023 vdev->bars[i].region.size = reg_info.size;
2024 vdev->bars[i].region.fd_offset = reg_info.offset;
2025 vdev->bars[i].region.nr = i;
7076eabc 2026 QLIST_INIT(&vdev->bars[i].quirks);
65501a74
AW
2027 }
2028
65501a74
AW
2029 reg_info.index = VFIO_PCI_CONFIG_REGION_INDEX;
2030
5546a621 2031 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
65501a74 2032 if (ret) {
312fd5f2 2033 error_report("vfio: Error getting config info: %m");
65501a74
AW
2034 goto error;
2035 }
2036
d13dd2d7
EA
2037 trace_vfio_populate_device_config(vdev->vbasedev.name,
2038 (unsigned long)reg_info.size,
2039 (unsigned long)reg_info.offset,
2040 (unsigned long)reg_info.flags);
65501a74
AW
2041
2042 vdev->config_size = reg_info.size;
6a659bbf
AW
2043 if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) {
2044 vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS;
2045 }
65501a74
AW
2046 vdev->config_offset = reg_info.offset;
2047
f15689c7 2048 if ((vdev->features & VFIO_FEATURE_ENABLE_VGA) &&
d13dd2d7 2049 vbasedev->num_regions > VFIO_PCI_VGA_REGION_INDEX) {
f15689c7
AW
2050 struct vfio_region_info vga_info = {
2051 .argsz = sizeof(vga_info),
2052 .index = VFIO_PCI_VGA_REGION_INDEX,
2053 };
2054
5546a621 2055 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &vga_info);
f15689c7
AW
2056 if (ret) {
2057 error_report(
2058 "vfio: Device does not support requested feature x-vga");
2059 goto error;
2060 }
2061
2062 if (!(vga_info.flags & VFIO_REGION_INFO_FLAG_READ) ||
2063 !(vga_info.flags & VFIO_REGION_INFO_FLAG_WRITE) ||
2064 vga_info.size < 0xbffff + 1) {
2065 error_report("vfio: Unexpected VGA info, flags 0x%lx, size 0x%lx",
2066 (unsigned long)vga_info.flags,
2067 (unsigned long)vga_info.size);
2068 goto error;
2069 }
2070
2071 vdev->vga.fd_offset = vga_info.offset;
5546a621 2072 vdev->vga.fd = vdev->vbasedev.fd;
f15689c7
AW
2073
2074 vdev->vga.region[QEMU_PCI_VGA_MEM].offset = QEMU_PCI_VGA_MEM_BASE;
2075 vdev->vga.region[QEMU_PCI_VGA_MEM].nr = QEMU_PCI_VGA_MEM;
7076eabc 2076 QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_MEM].quirks);
f15689c7
AW
2077
2078 vdev->vga.region[QEMU_PCI_VGA_IO_LO].offset = QEMU_PCI_VGA_IO_LO_BASE;
2079 vdev->vga.region[QEMU_PCI_VGA_IO_LO].nr = QEMU_PCI_VGA_IO_LO;
7076eabc 2080 QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_IO_LO].quirks);
f15689c7
AW
2081
2082 vdev->vga.region[QEMU_PCI_VGA_IO_HI].offset = QEMU_PCI_VGA_IO_HI_BASE;
2083 vdev->vga.region[QEMU_PCI_VGA_IO_HI].nr = QEMU_PCI_VGA_IO_HI;
7076eabc 2084 QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].quirks);
f15689c7
AW
2085
2086 vdev->has_vga = true;
2087 }
47cbe50c 2088
7b4b0e9e
VMP
2089 irq_info.index = VFIO_PCI_ERR_IRQ_INDEX;
2090
5546a621 2091 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);
7b4b0e9e
VMP
2092 if (ret) {
2093 /* This can fail for an old kernel or legacy PCI dev */
d13dd2d7 2094 trace_vfio_populate_device_get_irq_info_failure();
7b4b0e9e
VMP
2095 ret = 0;
2096 } else if (irq_info.count == 1) {
2097 vdev->pci_aer = true;
2098 } else {
df92ee44 2099 error_report("vfio: %s "
8fbf47c3 2100 "Could not enable error recovery for the device",
df92ee44 2101 vbasedev->name);
7b4b0e9e 2102 }
f15689c7 2103
d13dd2d7
EA
2104error:
2105 return ret;
2106}
2107
9ee27d73 2108static void vfio_put_device(VFIOPCIDevice *vdev)
65501a74 2109{
462037c9 2110 g_free(vdev->vbasedev.name);
65501a74 2111 if (vdev->msix) {
3a4dbe6a 2112 object_unparent(OBJECT(&vdev->msix->mmap_mem));
65501a74
AW
2113 g_free(vdev->msix);
2114 vdev->msix = NULL;
2115 }
d13dd2d7 2116 vfio_put_base_device(&vdev->vbasedev);
65501a74
AW
2117}
2118
7b4b0e9e
VMP
2119static void vfio_err_notifier_handler(void *opaque)
2120{
9ee27d73 2121 VFIOPCIDevice *vdev = opaque;
7b4b0e9e
VMP
2122
2123 if (!event_notifier_test_and_clear(&vdev->err_notifier)) {
2124 return;
2125 }
2126
2127 /*
2128 * TBD. Retrieve the error details and decide what action
2129 * needs to be taken. One of the actions could be to pass
2130 * the error to the guest and have the guest driver recover
2131 * from the error. This requires that PCIe capabilities be
2132 * exposed to the guest. For now, we just terminate the
2133 * guest to contain the error.
2134 */
2135
8fbf47c3
AW
2136 error_report("%s(%04x:%02x:%02x.%x) Unrecoverable error detected. "
2137 "Please collect any data possible and then kill the guest",
2138 __func__, vdev->host.domain, vdev->host.bus,
2139 vdev->host.slot, vdev->host.function);
7b4b0e9e 2140
ba29776f 2141 vm_stop(RUN_STATE_INTERNAL_ERROR);
7b4b0e9e
VMP
2142}
2143
2144/*
2145 * Registers error notifier for devices supporting error recovery.
2146 * If we encounter a failure in this function, we report an error
2147 * and continue after disabling error recovery support for the
2148 * device.
2149 */
9ee27d73 2150static void vfio_register_err_notifier(VFIOPCIDevice *vdev)
7b4b0e9e
VMP
2151{
2152 int ret;
2153 int argsz;
2154 struct vfio_irq_set *irq_set;
2155 int32_t *pfd;
2156
2157 if (!vdev->pci_aer) {
2158 return;
2159 }
2160
2161 if (event_notifier_init(&vdev->err_notifier, 0)) {
8fbf47c3 2162 error_report("vfio: Unable to init event notifier for error detection");
7b4b0e9e
VMP
2163 vdev->pci_aer = false;
2164 return;
2165 }
2166
2167 argsz = sizeof(*irq_set) + sizeof(*pfd);
2168
2169 irq_set = g_malloc0(argsz);
2170 irq_set->argsz = argsz;
2171 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
2172 VFIO_IRQ_SET_ACTION_TRIGGER;
2173 irq_set->index = VFIO_PCI_ERR_IRQ_INDEX;
2174 irq_set->start = 0;
2175 irq_set->count = 1;
2176 pfd = (int32_t *)&irq_set->data;
2177
2178 *pfd = event_notifier_get_fd(&vdev->err_notifier);
2179 qemu_set_fd_handler(*pfd, vfio_err_notifier_handler, NULL, vdev);
2180
5546a621 2181 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
7b4b0e9e 2182 if (ret) {
8fbf47c3 2183 error_report("vfio: Failed to set up error notification");
7b4b0e9e
VMP
2184 qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
2185 event_notifier_cleanup(&vdev->err_notifier);
2186 vdev->pci_aer = false;
2187 }
2188 g_free(irq_set);
2189}
2190
9ee27d73 2191static void vfio_unregister_err_notifier(VFIOPCIDevice *vdev)
7b4b0e9e
VMP
2192{
2193 int argsz;
2194 struct vfio_irq_set *irq_set;
2195 int32_t *pfd;
2196 int ret;
2197
2198 if (!vdev->pci_aer) {
2199 return;
2200 }
2201
2202 argsz = sizeof(*irq_set) + sizeof(*pfd);
2203
2204 irq_set = g_malloc0(argsz);
2205 irq_set->argsz = argsz;
2206 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
2207 VFIO_IRQ_SET_ACTION_TRIGGER;
2208 irq_set->index = VFIO_PCI_ERR_IRQ_INDEX;
2209 irq_set->start = 0;
2210 irq_set->count = 1;
2211 pfd = (int32_t *)&irq_set->data;
2212 *pfd = -1;
2213
5546a621 2214 ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);
7b4b0e9e 2215 if (ret) {
8fbf47c3 2216 error_report("vfio: Failed to de-assign error fd: %m");
7b4b0e9e
VMP
2217 }
2218 g_free(irq_set);
2219 qemu_set_fd_handler(event_notifier_get_fd(&vdev->err_notifier),
2220 NULL, NULL, vdev);
2221 event_notifier_cleanup(&vdev->err_notifier);
2222}
2223
47cbe50c
AW
2224static void vfio_req_notifier_handler(void *opaque)
2225{
2226 VFIOPCIDevice *vdev = opaque;
2227
2228 if (!event_notifier_test_and_clear(&vdev->req_notifier)) {
2229 return;
2230 }
2231
2232 qdev_unplug(&vdev->pdev.qdev, NULL);
2233}
2234
2235static void vfio_register_req_notifier(VFIOPCIDevice *vdev)
2236{
2237 struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info),
2238 .index = VFIO_PCI_REQ_IRQ_INDEX };
2239 int argsz;
2240 struct vfio_irq_set *irq_set;
2241 int32_t *pfd;
2242
2243 if (!(vdev->features & VFIO_FEATURE_ENABLE_REQ)) {
2244 return;
2245 }
2246
2247 if (ioctl(vdev->vbasedev.fd,
2248 VFIO_DEVICE_GET_IRQ_INFO, &irq_info) < 0 || irq_info.count < 1) {
2249 return;
2250 }
2251
2252 if (event_notifier_init(&vdev->req_notifier, 0)) {
2253 error_report("vfio: Unable to init event notifier for device request");
2254 return;
2255 }
2256
2257 argsz = sizeof(*irq_set) + sizeof(*pfd);
2258
2259 irq_set = g_malloc0(argsz);
2260 irq_set->argsz = argsz;
2261 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
2262 VFIO_IRQ_SET_ACTION_TRIGGER;
2263 irq_set->index = VFIO_PCI_REQ_IRQ_INDEX;
2264 irq_set->start = 0;
2265 irq_set->count = 1;
2266 pfd = (int32_t *)&irq_set->data;
2267
2268 *pfd = event_notifier_get_fd(&vdev->req_notifier);
2269 qemu_set_fd_handler(*pfd, vfio_req_notifier_handler, NULL, vdev);
2270
2271 if (ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set)) {
2272 error_report("vfio: Failed to set up device request notification");
2273 qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
2274 event_notifier_cleanup(&vdev->req_notifier);
2275 } else {
2276 vdev->req_enabled = true;
2277 }
2278
2279 g_free(irq_set);
2280}
2281
2282static void vfio_unregister_req_notifier(VFIOPCIDevice *vdev)
2283{
2284 int argsz;
2285 struct vfio_irq_set *irq_set;
2286 int32_t *pfd;
2287
2288 if (!vdev->req_enabled) {
2289 return;
2290 }
2291
2292 argsz = sizeof(*irq_set) + sizeof(*pfd);
2293
2294 irq_set = g_malloc0(argsz);
2295 irq_set->argsz = argsz;
2296 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
2297 VFIO_IRQ_SET_ACTION_TRIGGER;
2298 irq_set->index = VFIO_PCI_REQ_IRQ_INDEX;
2299 irq_set->start = 0;
2300 irq_set->count = 1;
2301 pfd = (int32_t *)&irq_set->data;
2302 *pfd = -1;
2303
2304 if (ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set)) {
2305 error_report("vfio: Failed to de-assign device request fd: %m");
2306 }
2307 g_free(irq_set);
2308 qemu_set_fd_handler(event_notifier_get_fd(&vdev->req_notifier),
2309 NULL, NULL, vdev);
2310 event_notifier_cleanup(&vdev->req_notifier);
2311
2312 vdev->req_enabled = false;
2313}
2314
65501a74
AW
2315static int vfio_initfn(PCIDevice *pdev)
2316{
b47d8efa
EA
2317 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
2318 VFIODevice *vbasedev_iter;
65501a74
AW
2319 VFIOGroup *group;
2320 char path[PATH_MAX], iommu_group_path[PATH_MAX], *group_name;
2321 ssize_t len;
2322 struct stat st;
2323 int groupid;
2324 int ret;
2325
2326 /* Check that the host device exists */
2327 snprintf(path, sizeof(path),
2328 "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/",
2329 vdev->host.domain, vdev->host.bus, vdev->host.slot,
2330 vdev->host.function);
2331 if (stat(path, &st) < 0) {
312fd5f2 2332 error_report("vfio: error: no such host device: %s", path);
65501a74
AW
2333 return -errno;
2334 }
2335
b47d8efa
EA
2336 vdev->vbasedev.ops = &vfio_pci_ops;
2337
462037c9
EA
2338 vdev->vbasedev.type = VFIO_DEVICE_TYPE_PCI;
2339 vdev->vbasedev.name = g_strdup_printf("%04x:%02x:%02x.%01x",
2340 vdev->host.domain, vdev->host.bus,
2341 vdev->host.slot, vdev->host.function);
2342
65501a74
AW
2343 strncat(path, "iommu_group", sizeof(path) - strlen(path) - 1);
2344
13665a2d
MA
2345 len = readlink(path, iommu_group_path, sizeof(path));
2346 if (len <= 0 || len >= sizeof(path)) {
312fd5f2 2347 error_report("vfio: error no iommu_group for device");
c6d231e2 2348 return len < 0 ? -errno : -ENAMETOOLONG;
65501a74
AW
2349 }
2350
2351 iommu_group_path[len] = 0;
2352 group_name = basename(iommu_group_path);
2353
2354 if (sscanf(group_name, "%d", &groupid) != 1) {
312fd5f2 2355 error_report("vfio: error reading %s: %m", path);
65501a74
AW
2356 return -errno;
2357 }
2358
df92ee44 2359 trace_vfio_initfn(vdev->vbasedev.name, groupid);
65501a74 2360
0688448b 2361 group = vfio_get_group(groupid, pci_device_iommu_address_space(pdev));
65501a74 2362 if (!group) {
312fd5f2 2363 error_report("vfio: failed to get group %d", groupid);
65501a74
AW
2364 return -ENOENT;
2365 }
2366
2367 snprintf(path, sizeof(path), "%04x:%02x:%02x.%01x",
2368 vdev->host.domain, vdev->host.bus, vdev->host.slot,
2369 vdev->host.function);
2370
b47d8efa
EA
2371 QLIST_FOREACH(vbasedev_iter, &group->device_list, next) {
2372 if (strcmp(vbasedev_iter->name, vdev->vbasedev.name) == 0) {
312fd5f2 2373 error_report("vfio: error: device %s is already attached", path);
65501a74
AW
2374 vfio_put_group(group);
2375 return -EBUSY;
2376 }
2377 }
2378
d13dd2d7 2379 ret = vfio_get_device(group, path, &vdev->vbasedev);
65501a74 2380 if (ret) {
312fd5f2 2381 error_report("vfio: failed to get device %s", path);
65501a74
AW
2382 vfio_put_group(group);
2383 return ret;
2384 }
2385
217e9fdc
PB
2386 ret = vfio_populate_device(vdev);
2387 if (ret) {
77a10d04 2388 return ret;
217e9fdc
PB
2389 }
2390
65501a74 2391 /* Get a copy of config space */
5546a621 2392 ret = pread(vdev->vbasedev.fd, vdev->pdev.config,
65501a74
AW
2393 MIN(pci_config_size(&vdev->pdev), vdev->config_size),
2394 vdev->config_offset);
2395 if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
2396 ret = ret < 0 ? -errno : -EFAULT;
312fd5f2 2397 error_report("vfio: Failed to read device config space");
77a10d04 2398 return ret;
65501a74
AW
2399 }
2400
4b5d5e87
AW
2401 /* vfio emulates a lot for us, but some bits need extra love */
2402 vdev->emulated_config_bits = g_malloc0(vdev->config_size);
2403
2404 /* QEMU can choose to expose the ROM or not */
2405 memset(vdev->emulated_config_bits + PCI_ROM_ADDRESS, 0xff, 4);
2406
ff635e37
AW
2407 vdev->vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2408 vdev->device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2409
4b5d5e87
AW
2410 /* QEMU can change multi-function devices to single function, or reverse */
2411 vdev->emulated_config_bits[PCI_HEADER_TYPE] =
2412 PCI_HEADER_TYPE_MULTI_FUNCTION;
2413
187d6232
AW
2414 /* Restore or clear multifunction, this is always controlled by QEMU */
2415 if (vdev->pdev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
2416 vdev->pdev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
2417 } else {
2418 vdev->pdev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
2419 }
2420
65501a74
AW
2421 /*
2422 * Clear host resource mapping info. If we choose not to register a
2423 * BAR, such as might be the case with the option ROM, we can get
2424 * confusing, unwritable, residual addresses from the host here.
2425 */
2426 memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
2427 memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
2428
6f864e6e 2429 vfio_pci_size_rom(vdev);
65501a74 2430
0de70dc7 2431 ret = vfio_msix_early_setup(vdev);
65501a74 2432 if (ret) {
77a10d04 2433 return ret;
65501a74
AW
2434 }
2435
2436 vfio_map_bars(vdev);
2437
2438 ret = vfio_add_capabilities(vdev);
2439 if (ret) {
2440 goto out_teardown;
2441 }
2442
4b5d5e87
AW
2443 /* QEMU emulates all of MSI & MSIX */
2444 if (pdev->cap_present & QEMU_PCI_CAP_MSIX) {
2445 memset(vdev->emulated_config_bits + pdev->msix_cap, 0xff,
2446 MSIX_CAP_LENGTH);
2447 }
2448
2449 if (pdev->cap_present & QEMU_PCI_CAP_MSI) {
2450 memset(vdev->emulated_config_bits + pdev->msi_cap, 0xff,
2451 vdev->msi_cap_size);
2452 }
2453
65501a74 2454 if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
bc72ad67 2455 vdev->intx.mmap_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
ea486926 2456 vfio_intx_mmap_enable, vdev);
870cb6f1
AW
2457 pci_device_set_intx_routing_notifier(&vdev->pdev, vfio_intx_update);
2458 ret = vfio_intx_enable(vdev);
65501a74
AW
2459 if (ret) {
2460 goto out_teardown;
2461 }
2462 }
2463
7b4b0e9e 2464 vfio_register_err_notifier(vdev);
47cbe50c 2465 vfio_register_req_notifier(vdev);
c9c50009 2466 vfio_setup_resetfn_quirk(vdev);
c29029dd 2467
65501a74
AW
2468 return 0;
2469
2470out_teardown:
2471 pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
2472 vfio_teardown_msi(vdev);
ba5e6bfa 2473 vfio_unregister_bars(vdev);
77a10d04
PB
2474 return ret;
2475}
2476
2477static void vfio_instance_finalize(Object *obj)
2478{
2479 PCIDevice *pci_dev = PCI_DEVICE(obj);
2480 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pci_dev);
2481 VFIOGroup *group = vdev->vbasedev.group;
2482
ba5e6bfa 2483 vfio_unmap_bars(vdev);
4b5d5e87 2484 g_free(vdev->emulated_config_bits);
77a10d04 2485 g_free(vdev->rom);
65501a74
AW
2486 vfio_put_device(vdev);
2487 vfio_put_group(group);
65501a74
AW
2488}
2489
2490static void vfio_exitfn(PCIDevice *pdev)
2491{
9ee27d73 2492 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
65501a74 2493
47cbe50c 2494 vfio_unregister_req_notifier(vdev);
7b4b0e9e 2495 vfio_unregister_err_notifier(vdev);
65501a74
AW
2496 pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
2497 vfio_disable_interrupts(vdev);
ea486926 2498 if (vdev->intx.mmap_timer) {
bc72ad67 2499 timer_free(vdev->intx.mmap_timer);
ea486926 2500 }
65501a74 2501 vfio_teardown_msi(vdev);
ba5e6bfa 2502 vfio_unregister_bars(vdev);
65501a74
AW
2503}
2504
2505static void vfio_pci_reset(DeviceState *dev)
2506{
2507 PCIDevice *pdev = DO_UPCAST(PCIDevice, qdev, dev);
9ee27d73 2508 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);
65501a74 2509
df92ee44 2510 trace_vfio_pci_reset(vdev->vbasedev.name);
5834a83f 2511
f16f39c3 2512 vfio_pci_pre_reset(vdev);
ba661818 2513
5655f931
AW
2514 if (vdev->resetfn && !vdev->resetfn(vdev)) {
2515 goto post_reset;
2516 }
2517
b47d8efa
EA
2518 if (vdev->vbasedev.reset_works &&
2519 (vdev->has_flr || !vdev->has_pm_reset) &&
5546a621 2520 !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
df92ee44 2521 trace_vfio_pci_reset_flr(vdev->vbasedev.name);
f16f39c3 2522 goto post_reset;
ba661818
AW
2523 }
2524
f16f39c3
AW
2525 /* See if we can do our own bus reset */
2526 if (!vfio_pci_hot_reset_one(vdev)) {
2527 goto post_reset;
2528 }
5834a83f 2529
f16f39c3 2530 /* If nothing else works and the device supports PM reset, use it */
b47d8efa 2531 if (vdev->vbasedev.reset_works && vdev->has_pm_reset &&
5546a621 2532 !ioctl(vdev->vbasedev.fd, VFIO_DEVICE_RESET)) {
df92ee44 2533 trace_vfio_pci_reset_pm(vdev->vbasedev.name);
f16f39c3 2534 goto post_reset;
65501a74 2535 }
5834a83f 2536
f16f39c3
AW
2537post_reset:
2538 vfio_pci_post_reset(vdev);
65501a74
AW
2539}
2540
abc5b3bf
GA
2541static void vfio_instance_init(Object *obj)
2542{
2543 PCIDevice *pci_dev = PCI_DEVICE(obj);
9ee27d73 2544 VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, PCI_DEVICE(obj));
abc5b3bf
GA
2545
2546 device_add_bootindex_property(obj, &vdev->bootindex,
2547 "bootindex", NULL,
2548 &pci_dev->qdev, NULL);
2549}
2550
65501a74 2551static Property vfio_pci_dev_properties[] = {
9ee27d73
EA
2552 DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIOPCIDevice, host),
2553 DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIOPCIDevice,
ea486926 2554 intx.mmap_timeout, 1100),
9ee27d73 2555 DEFINE_PROP_BIT("x-vga", VFIOPCIDevice, features,
f15689c7 2556 VFIO_FEATURE_ENABLE_VGA_BIT, false),
47cbe50c
AW
2557 DEFINE_PROP_BIT("x-req", VFIOPCIDevice, features,
2558 VFIO_FEATURE_ENABLE_REQ_BIT, true),
5e15d79b 2559 DEFINE_PROP_BOOL("x-no-mmap", VFIOPCIDevice, vbasedev.no_mmap, false),
46746dba
AW
2560 DEFINE_PROP_BOOL("x-no-kvm-intx", VFIOPCIDevice, no_kvm_intx, false),
2561 DEFINE_PROP_BOOL("x-no-kvm-msi", VFIOPCIDevice, no_kvm_msi, false),
2562 DEFINE_PROP_BOOL("x-no-kvm-msix", VFIOPCIDevice, no_kvm_msix, false),
65501a74
AW
2563 /*
2564 * TODO - support passed fds... is this necessary?
9ee27d73
EA
2565 * DEFINE_PROP_STRING("vfiofd", VFIOPCIDevice, vfiofd_name),
2566 * DEFINE_PROP_STRING("vfiogroupfd, VFIOPCIDevice, vfiogroupfd_name),
65501a74
AW
2567 */
2568 DEFINE_PROP_END_OF_LIST(),
2569};
2570
d9f0e638
AW
2571static const VMStateDescription vfio_pci_vmstate = {
2572 .name = "vfio-pci",
2573 .unmigratable = 1,
2574};
65501a74
AW
2575
2576static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
2577{
2578 DeviceClass *dc = DEVICE_CLASS(klass);
2579 PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
2580
2581 dc->reset = vfio_pci_reset;
2582 dc->props = vfio_pci_dev_properties;
d9f0e638
AW
2583 dc->vmsd = &vfio_pci_vmstate;
2584 dc->desc = "VFIO-based PCI device assignment";
125ee0ed 2585 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
65501a74
AW
2586 pdc->init = vfio_initfn;
2587 pdc->exit = vfio_exitfn;
2588 pdc->config_read = vfio_pci_read_config;
2589 pdc->config_write = vfio_pci_write_config;
6a659bbf 2590 pdc->is_express = 1; /* We might be */
65501a74
AW
2591}
2592
2593static const TypeInfo vfio_pci_dev_info = {
2594 .name = "vfio-pci",
2595 .parent = TYPE_PCI_DEVICE,
9ee27d73 2596 .instance_size = sizeof(VFIOPCIDevice),
65501a74 2597 .class_init = vfio_pci_dev_class_init,
abc5b3bf 2598 .instance_init = vfio_instance_init,
77a10d04 2599 .instance_finalize = vfio_instance_finalize,
65501a74
AW
2600};
2601
2602static void register_vfio_pci_dev_type(void)
2603{
2604 type_register_static(&vfio_pci_dev_info);
2605}
2606
2607type_init(register_vfio_pci_dev_type)