]> git.proxmox.com Git - mirror_qemu.git/blame - hw/vfio_pci.c
vfio-pci: Update slow path INTx algorithm
[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
21#include <dirent.h>
22#include <unistd.h>
23#include <sys/ioctl.h>
24#include <sys/mman.h>
25#include <sys/stat.h>
26#include <sys/types.h>
27#include <linux/vfio.h>
28
29#include "config.h"
30#include "event_notifier.h"
31#include "exec-memory.h"
32#include "kvm.h"
33#include "memory.h"
34#include "msi.h"
35#include "msix.h"
36#include "qemu-error.h"
37#include "range.h"
38#include "vfio_pci_int.h"
39
40/* #define DEBUG_VFIO */
41#ifdef DEBUG_VFIO
42#define DPRINTF(fmt, ...) \
43 do { fprintf(stderr, "vfio: " fmt, ## __VA_ARGS__); } while (0)
44#else
45#define DPRINTF(fmt, ...) \
46 do { } while (0)
47#endif
48
49#define MSIX_CAP_LENGTH 12
50
51static QLIST_HEAD(, VFIOContainer)
52 container_list = QLIST_HEAD_INITIALIZER(container_list);
53
54static QLIST_HEAD(, VFIOGroup)
55 group_list = QLIST_HEAD_INITIALIZER(group_list);
56
57static void vfio_disable_interrupts(VFIODevice *vdev);
58static uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len);
59static void vfio_mmap_set_enabled(VFIODevice *vdev, bool enabled);
60
61/*
62 * Common VFIO interrupt disable
63 */
64static void vfio_disable_irqindex(VFIODevice *vdev, int index)
65{
66 struct vfio_irq_set irq_set = {
67 .argsz = sizeof(irq_set),
68 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
69 .index = index,
70 .start = 0,
71 .count = 0,
72 };
73
74 ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
75
76 vdev->interrupt = VFIO_INT_NONE;
77}
78
79/*
80 * INTx
81 */
82static void vfio_unmask_intx(VFIODevice *vdev)
83{
84 struct vfio_irq_set irq_set = {
85 .argsz = sizeof(irq_set),
86 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
87 .index = VFIO_PCI_INTX_IRQ_INDEX,
88 .start = 0,
89 .count = 1,
90 };
91
92 ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
93}
94
ea486926
AW
95/*
96 * Disabling BAR mmaping can be slow, but toggling it around INTx can
97 * also be a huge overhead. We try to get the best of both worlds by
98 * waiting until an interrupt to disable mmaps (subsequent transitions
99 * to the same state are effectively no overhead). If the interrupt has
100 * been serviced and the time gap is long enough, we re-enable mmaps for
101 * performance. This works well for things like graphics cards, which
102 * may not use their interrupt at all and are penalized to an unusable
103 * level by read/write BAR traps. Other devices, like NICs, have more
104 * regular interrupts and see much better latency by staying in non-mmap
105 * mode. We therefore set the default mmap_timeout such that a ping
106 * is just enough to keep the mmap disabled. Users can experiment with
107 * other options with the x-intx-mmap-timeout-ms parameter (a value of
108 * zero disables the timer).
109 */
110static void vfio_intx_mmap_enable(void *opaque)
111{
112 VFIODevice *vdev = opaque;
113
114 if (vdev->intx.pending) {
115 qemu_mod_timer(vdev->intx.mmap_timer,
116 qemu_get_clock_ms(vm_clock) + vdev->intx.mmap_timeout);
117 return;
118 }
119
120 vfio_mmap_set_enabled(vdev, true);
121}
122
65501a74
AW
123static void vfio_intx_interrupt(void *opaque)
124{
125 VFIODevice *vdev = opaque;
126
127 if (!event_notifier_test_and_clear(&vdev->intx.interrupt)) {
128 return;
129 }
130
131 DPRINTF("%s(%04x:%02x:%02x.%x) Pin %c\n", __func__, vdev->host.domain,
132 vdev->host.bus, vdev->host.slot, vdev->host.function,
133 'A' + vdev->intx.pin);
134
135 vdev->intx.pending = true;
136 qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 1);
ea486926
AW
137 vfio_mmap_set_enabled(vdev, false);
138 if (vdev->intx.mmap_timeout) {
139 qemu_mod_timer(vdev->intx.mmap_timer,
140 qemu_get_clock_ms(vm_clock) + vdev->intx.mmap_timeout);
141 }
65501a74
AW
142}
143
144static void vfio_eoi(VFIODevice *vdev)
145{
146 if (!vdev->intx.pending) {
147 return;
148 }
149
150 DPRINTF("%s(%04x:%02x:%02x.%x) EOI\n", __func__, vdev->host.domain,
151 vdev->host.bus, vdev->host.slot, vdev->host.function);
152
153 vdev->intx.pending = false;
154 qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 0);
155 vfio_unmask_intx(vdev);
156}
157
158typedef struct QEMU_PACKED VFIOIRQSetFD {
159 struct vfio_irq_set irq_set;
160 int32_t fd;
161} VFIOIRQSetFD;
162
163static int vfio_enable_intx(VFIODevice *vdev)
164{
165 VFIOIRQSetFD irq_set_fd = {
166 .irq_set = {
167 .argsz = sizeof(irq_set_fd),
168 .flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER,
169 .index = VFIO_PCI_INTX_IRQ_INDEX,
170 .start = 0,
171 .count = 1,
172 },
173 };
174 uint8_t pin = vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1);
175 int ret;
176
ea486926 177 if (!pin) {
65501a74
AW
178 return 0;
179 }
180
181 vfio_disable_interrupts(vdev);
182
183 vdev->intx.pin = pin - 1; /* Pin A (1) -> irq[0] */
184 ret = event_notifier_init(&vdev->intx.interrupt, 0);
185 if (ret) {
186 error_report("vfio: Error: event_notifier_init failed\n");
187 return ret;
188 }
189
190 irq_set_fd.fd = event_notifier_get_fd(&vdev->intx.interrupt);
191 qemu_set_fd_handler(irq_set_fd.fd, vfio_intx_interrupt, NULL, vdev);
192
193 if (ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set_fd)) {
194 error_report("vfio: Error: Failed to setup INTx fd: %m\n");
195 return -errno;
196 }
197
65501a74
AW
198 vdev->interrupt = VFIO_INT_INTx;
199
200 DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
201 vdev->host.bus, vdev->host.slot, vdev->host.function);
202
203 return 0;
204}
205
206static void vfio_disable_intx(VFIODevice *vdev)
207{
208 int fd;
209
ea486926 210 qemu_del_timer(vdev->intx.mmap_timer);
65501a74
AW
211 vfio_disable_irqindex(vdev, VFIO_PCI_INTX_IRQ_INDEX);
212 vdev->intx.pending = false;
213 qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 0);
214 vfio_mmap_set_enabled(vdev, true);
215
216 fd = event_notifier_get_fd(&vdev->intx.interrupt);
217 qemu_set_fd_handler(fd, NULL, NULL, vdev);
218 event_notifier_cleanup(&vdev->intx.interrupt);
219
220 vdev->interrupt = VFIO_INT_NONE;
221
222 DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
223 vdev->host.bus, vdev->host.slot, vdev->host.function);
224}
225
226/*
227 * MSI/X
228 */
229static void vfio_msi_interrupt(void *opaque)
230{
231 VFIOMSIVector *vector = opaque;
232 VFIODevice *vdev = vector->vdev;
233 int nr = vector - vdev->msi_vectors;
234
235 if (!event_notifier_test_and_clear(&vector->interrupt)) {
236 return;
237 }
238
239 DPRINTF("%s(%04x:%02x:%02x.%x) vector %d\n", __func__,
240 vdev->host.domain, vdev->host.bus, vdev->host.slot,
241 vdev->host.function, nr);
242
243 if (vdev->interrupt == VFIO_INT_MSIX) {
244 msix_notify(&vdev->pdev, nr);
245 } else if (vdev->interrupt == VFIO_INT_MSI) {
246 msi_notify(&vdev->pdev, nr);
247 } else {
248 error_report("vfio: MSI interrupt receieved, but not enabled?\n");
249 }
250}
251
252static int vfio_enable_vectors(VFIODevice *vdev, bool msix)
253{
254 struct vfio_irq_set *irq_set;
255 int ret = 0, i, argsz;
256 int32_t *fds;
257
258 argsz = sizeof(*irq_set) + (vdev->nr_vectors * sizeof(*fds));
259
260 irq_set = g_malloc0(argsz);
261 irq_set->argsz = argsz;
262 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
263 irq_set->index = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX;
264 irq_set->start = 0;
265 irq_set->count = vdev->nr_vectors;
266 fds = (int32_t *)&irq_set->data;
267
268 for (i = 0; i < vdev->nr_vectors; i++) {
269 if (!vdev->msi_vectors[i].use) {
270 fds[i] = -1;
271 continue;
272 }
273
274 fds[i] = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt);
275 }
276
277 ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
278
279 g_free(irq_set);
280
281 if (!ret) {
282 vdev->interrupt = msix ? VFIO_INT_MSIX : VFIO_INT_MSI;
283 }
284
285 return ret;
286}
287
288static int vfio_msix_vector_use(PCIDevice *pdev,
289 unsigned int nr, MSIMessage msg)
290{
291 VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
292 VFIOMSIVector *vector;
293 int ret;
294
295 DPRINTF("%s(%04x:%02x:%02x.%x) vector %d used\n", __func__,
296 vdev->host.domain, vdev->host.bus, vdev->host.slot,
297 vdev->host.function, nr);
298
299 if (vdev->interrupt != VFIO_INT_MSIX) {
300 vfio_disable_interrupts(vdev);
301 }
302
303 if (!vdev->msi_vectors) {
304 vdev->msi_vectors = g_malloc0(vdev->msix->entries *
305 sizeof(VFIOMSIVector));
306 }
307
308 vector = &vdev->msi_vectors[nr];
309 vector->vdev = vdev;
310 vector->use = true;
311
312 msix_vector_use(pdev, nr);
313
314 if (event_notifier_init(&vector->interrupt, 0)) {
315 error_report("vfio: Error: event_notifier_init failed\n");
316 }
317
318 /*
319 * Attempt to enable route through KVM irqchip,
320 * default to userspace handling if unavailable.
321 */
322 vector->virq = kvm_irqchip_add_msi_route(kvm_state, msg);
323 if (vector->virq < 0 ||
324 kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->interrupt,
325 vector->virq) < 0) {
326 if (vector->virq >= 0) {
327 kvm_irqchip_release_virq(kvm_state, vector->virq);
328 vector->virq = -1;
329 }
330 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
331 vfio_msi_interrupt, NULL, vector);
332 }
333
334 /*
335 * We don't want to have the host allocate all possible MSI vectors
336 * for a device if they're not in use, so we shutdown and incrementally
337 * increase them as needed.
338 */
339 if (vdev->nr_vectors < nr + 1) {
340 int i;
341
342 vfio_disable_irqindex(vdev, VFIO_PCI_MSIX_IRQ_INDEX);
343 vdev->nr_vectors = nr + 1;
344 ret = vfio_enable_vectors(vdev, true);
345 if (ret) {
346 error_report("vfio: failed to enable vectors, %d\n", ret);
347 }
348
349 /* We don't know if we've missed interrupts in the interim... */
350 for (i = 0; i < vdev->msix->entries; i++) {
351 if (vdev->msi_vectors[i].use) {
352 msix_notify(&vdev->pdev, i);
353 }
354 }
355 } else {
356 VFIOIRQSetFD irq_set_fd = {
357 .irq_set = {
358 .argsz = sizeof(irq_set_fd),
359 .flags = VFIO_IRQ_SET_DATA_EVENTFD |
360 VFIO_IRQ_SET_ACTION_TRIGGER,
361 .index = VFIO_PCI_MSIX_IRQ_INDEX,
362 .start = nr,
363 .count = 1,
364 },
365 .fd = event_notifier_get_fd(&vector->interrupt),
366 };
367 ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set_fd);
368 if (ret) {
369 error_report("vfio: failed to modify vector, %d\n", ret);
370 }
371
372 /*
373 * If we were connected to the hardware PBA we could skip this,
374 * until then, a spurious interrupt is better than starvation.
375 */
376 msix_notify(&vdev->pdev, nr);
377 }
378
379 return 0;
380}
381
382static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr)
383{
384 VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
385 VFIOMSIVector *vector = &vdev->msi_vectors[nr];
386 VFIOIRQSetFD irq_set_fd = {
387 .irq_set = {
388 .argsz = sizeof(irq_set_fd),
389 .flags = VFIO_IRQ_SET_DATA_EVENTFD |
390 VFIO_IRQ_SET_ACTION_TRIGGER,
391 .index = VFIO_PCI_MSIX_IRQ_INDEX,
392 .start = nr,
393 .count = 1,
394 },
395 .fd = -1,
396 };
397
398 DPRINTF("%s(%04x:%02x:%02x.%x) vector %d released\n", __func__,
399 vdev->host.domain, vdev->host.bus, vdev->host.slot,
400 vdev->host.function, nr);
401
402 /*
403 * XXX What's the right thing to do here? This turns off the interrupt
404 * completely, but do we really just want to switch the interrupt to
405 * bouncing through userspace and let msix.c drop it? Not sure.
406 */
407 msix_vector_unuse(pdev, nr);
408 ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set_fd);
409
410 if (vector->virq < 0) {
411 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
412 NULL, NULL, NULL);
413 } else {
414 kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->interrupt,
415 vector->virq);
416 kvm_irqchip_release_virq(kvm_state, vector->virq);
417 vector->virq = -1;
418 }
419
420 event_notifier_cleanup(&vector->interrupt);
421 vector->use = false;
422}
423
424/* TODO This should move to msi.c */
425static MSIMessage msi_get_msg(PCIDevice *pdev, unsigned int vector)
426{
427 uint16_t flags = pci_get_word(pdev->config + pdev->msi_cap + PCI_MSI_FLAGS);
428 bool msi64bit = flags & PCI_MSI_FLAGS_64BIT;
429 MSIMessage msg;
430
431 if (msi64bit) {
432 msg.address = pci_get_quad(pdev->config +
433 pdev->msi_cap + PCI_MSI_ADDRESS_LO);
434 } else {
435 msg.address = pci_get_long(pdev->config +
436 pdev->msi_cap + PCI_MSI_ADDRESS_LO);
437 }
438
439 msg.data = pci_get_word(pdev->config + pdev->msi_cap +
440 (msi64bit ? PCI_MSI_DATA_64 : PCI_MSI_DATA_32));
441 msg.data += vector;
442
443 return msg;
444}
445
446/* So should this */
447static void msi_set_qsize(PCIDevice *pdev, uint8_t size)
448{
449 uint8_t *config = pdev->config + pdev->msi_cap;
450 uint16_t flags;
451
452 flags = pci_get_word(config + PCI_MSI_FLAGS);
453 flags = le16_to_cpu(flags);
454 flags &= ~PCI_MSI_FLAGS_QSIZE;
455 flags |= (size & 0x7) << 4;
456 flags = cpu_to_le16(flags);
457 pci_set_word(config + PCI_MSI_FLAGS, flags);
458}
459
460static void vfio_enable_msi(VFIODevice *vdev)
461{
462 int ret, i;
463
464 vfio_disable_interrupts(vdev);
465
466 vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev);
467retry:
468 vdev->msi_vectors = g_malloc0(vdev->nr_vectors * sizeof(VFIOMSIVector));
469
470 for (i = 0; i < vdev->nr_vectors; i++) {
471 MSIMessage msg;
472 VFIOMSIVector *vector = &vdev->msi_vectors[i];
473
474 vector->vdev = vdev;
475 vector->use = true;
476
477 if (event_notifier_init(&vector->interrupt, 0)) {
478 error_report("vfio: Error: event_notifier_init failed\n");
479 }
480
481 msg = msi_get_msg(&vdev->pdev, i);
482
483 /*
484 * Attempt to enable route through KVM irqchip,
485 * default to userspace handling if unavailable.
486 */
487 vector->virq = kvm_irqchip_add_msi_route(kvm_state, msg);
488 if (vector->virq < 0 ||
489 kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->interrupt,
490 vector->virq) < 0) {
491 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
492 vfio_msi_interrupt, NULL, vector);
493 }
494 }
495
496 ret = vfio_enable_vectors(vdev, false);
497 if (ret) {
498 if (ret < 0) {
499 error_report("vfio: Error: Failed to setup MSI fds: %m\n");
500 } else if (ret != vdev->nr_vectors) {
501 error_report("vfio: Error: Failed to enable %d "
502 "MSI vectors, retry with %d\n", vdev->nr_vectors, ret);
503 }
504
505 for (i = 0; i < vdev->nr_vectors; i++) {
506 VFIOMSIVector *vector = &vdev->msi_vectors[i];
507 if (vector->virq >= 0) {
508 kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->interrupt,
509 vector->virq);
510 kvm_irqchip_release_virq(kvm_state, vector->virq);
511 vector->virq = -1;
512 } else {
513 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
514 NULL, NULL, NULL);
515 }
516 event_notifier_cleanup(&vector->interrupt);
517 }
518
519 g_free(vdev->msi_vectors);
520
521 if (ret > 0 && ret != vdev->nr_vectors) {
522 vdev->nr_vectors = ret;
523 goto retry;
524 }
525 vdev->nr_vectors = 0;
526
527 return;
528 }
529
530 msi_set_qsize(&vdev->pdev, vdev->nr_vectors);
531
532 DPRINTF("%s(%04x:%02x:%02x.%x) Enabled %d MSI vectors\n", __func__,
533 vdev->host.domain, vdev->host.bus, vdev->host.slot,
534 vdev->host.function, vdev->nr_vectors);
535}
536
537static void vfio_disable_msi_x(VFIODevice *vdev, bool msix)
538{
539 int i;
540
541 vfio_disable_irqindex(vdev, msix ? VFIO_PCI_MSIX_IRQ_INDEX :
542 VFIO_PCI_MSI_IRQ_INDEX);
543
544 for (i = 0; i < vdev->nr_vectors; i++) {
545 VFIOMSIVector *vector = &vdev->msi_vectors[i];
546
547 if (!vector->use) {
548 continue;
549 }
550
551 if (vector->virq >= 0) {
552 kvm_irqchip_remove_irqfd_notifier(kvm_state,
553 &vector->interrupt, vector->virq);
554 kvm_irqchip_release_virq(kvm_state, vector->virq);
555 vector->virq = -1;
556 } else {
557 qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
558 NULL, NULL, NULL);
559 }
560
561 if (msix) {
562 msix_vector_unuse(&vdev->pdev, i);
563 }
564
565 event_notifier_cleanup(&vector->interrupt);
566 }
567
568 g_free(vdev->msi_vectors);
569 vdev->msi_vectors = NULL;
570 vdev->nr_vectors = 0;
571
572 if (!msix) {
573 msi_set_qsize(&vdev->pdev, 0); /* Actually still means 1 vector */
574 }
575
576 DPRINTF("%s(%04x:%02x:%02x.%x, msi%s)\n", __func__,
577 vdev->host.domain, vdev->host.bus, vdev->host.slot,
578 vdev->host.function, msix ? "x" : "");
579
580 vfio_enable_intx(vdev);
581}
582
583/*
584 * IO Port/MMIO - Beware of the endians, VFIO is always little endian
585 */
586static void vfio_bar_write(void *opaque, target_phys_addr_t addr,
587 uint64_t data, unsigned size)
588{
589 VFIOBAR *bar = opaque;
590 union {
591 uint8_t byte;
592 uint16_t word;
593 uint32_t dword;
594 uint64_t qword;
595 } buf;
596
597 switch (size) {
598 case 1:
599 buf.byte = data;
600 break;
601 case 2:
602 buf.word = cpu_to_le16(data);
603 break;
604 case 4:
605 buf.dword = cpu_to_le32(data);
606 break;
607 default:
608 hw_error("vfio: unsupported write size, %d bytes\n", size);
609 break;
610 }
611
612 if (pwrite(bar->fd, &buf, size, bar->fd_offset + addr) != size) {
613 error_report("%s(,0x%"TARGET_PRIxPHYS", 0x%"PRIx64", %d) failed: %m\n",
614 __func__, addr, data, size);
615 }
616
617 DPRINTF("%s(BAR%d+0x%"TARGET_PRIxPHYS", 0x%"PRIx64", %d)\n",
618 __func__, bar->nr, addr, data, size);
619
620 /*
621 * A read or write to a BAR always signals an INTx EOI. This will
622 * do nothing if not pending (including not in INTx mode). We assume
623 * that a BAR access is in response to an interrupt and that BAR
624 * accesses will service the interrupt. Unfortunately, we don't know
625 * which access will service the interrupt, so we're potentially
626 * getting quite a few host interrupts per guest interrupt.
627 */
628 vfio_eoi(DO_UPCAST(VFIODevice, bars[bar->nr], bar));
629}
630
631static uint64_t vfio_bar_read(void *opaque,
632 target_phys_addr_t addr, unsigned size)
633{
634 VFIOBAR *bar = opaque;
635 union {
636 uint8_t byte;
637 uint16_t word;
638 uint32_t dword;
639 uint64_t qword;
640 } buf;
641 uint64_t data = 0;
642
643 if (pread(bar->fd, &buf, size, bar->fd_offset + addr) != size) {
644 error_report("%s(,0x%"TARGET_PRIxPHYS", %d) failed: %m\n",
645 __func__, addr, size);
646 return (uint64_t)-1;
647 }
648
649 switch (size) {
650 case 1:
651 data = buf.byte;
652 break;
653 case 2:
654 data = le16_to_cpu(buf.word);
655 break;
656 case 4:
657 data = le32_to_cpu(buf.dword);
658 break;
659 default:
660 hw_error("vfio: unsupported read size, %d bytes\n", size);
661 break;
662 }
663
664 DPRINTF("%s(BAR%d+0x%"TARGET_PRIxPHYS", %d) = 0x%"PRIx64"\n",
665 __func__, bar->nr, addr, size, data);
666
667 /* Same as write above */
668 vfio_eoi(DO_UPCAST(VFIODevice, bars[bar->nr], bar));
669
670 return data;
671}
672
673static const MemoryRegionOps vfio_bar_ops = {
674 .read = vfio_bar_read,
675 .write = vfio_bar_write,
676 .endianness = DEVICE_LITTLE_ENDIAN,
677};
678
679/*
680 * PCI config space
681 */
682static uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len)
683{
684 VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
685 uint32_t val = 0;
686
687 /*
688 * We only need QEMU PCI config support for the ROM BAR, the MSI and MSIX
689 * capabilities, and the multifunction bit below. We let VFIO handle
690 * virtualizing everything else. Performance is not a concern here.
691 */
692 if (ranges_overlap(addr, len, PCI_ROM_ADDRESS, 4) ||
693 (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
694 ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) ||
695 (pdev->cap_present & QEMU_PCI_CAP_MSI &&
696 ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size))) {
697
698 val = pci_default_read_config(pdev, addr, len);
699 } else {
700 if (pread(vdev->fd, &val, len, vdev->config_offset + addr) != len) {
701 error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x) failed: %m\n",
702 __func__, vdev->host.domain, vdev->host.bus,
703 vdev->host.slot, vdev->host.function, addr, len);
704 return -errno;
705 }
706 val = le32_to_cpu(val);
707 }
708
709 /* Multifunction bit is virualized in QEMU */
710 if (unlikely(ranges_overlap(addr, len, PCI_HEADER_TYPE, 1))) {
711 uint32_t mask = PCI_HEADER_TYPE_MULTI_FUNCTION;
712
713 if (len == 4) {
714 mask <<= 16;
715 }
716
717 if (pdev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
718 val |= mask;
719 } else {
720 val &= ~mask;
721 }
722 }
723
724 DPRINTF("%s(%04x:%02x:%02x.%x, @0x%x, len=0x%x) %x\n", __func__,
725 vdev->host.domain, vdev->host.bus, vdev->host.slot,
726 vdev->host.function, addr, len, val);
727
728 return val;
729}
730
731static void vfio_pci_write_config(PCIDevice *pdev, uint32_t addr,
732 uint32_t val, int len)
733{
734 VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
735 uint32_t val_le = cpu_to_le32(val);
736
737 DPRINTF("%s(%04x:%02x:%02x.%x, @0x%x, 0x%x, len=0x%x)\n", __func__,
738 vdev->host.domain, vdev->host.bus, vdev->host.slot,
739 vdev->host.function, addr, val, len);
740
741 /* Write everything to VFIO, let it filter out what we can't write */
742 if (pwrite(vdev->fd, &val_le, len, vdev->config_offset + addr) != len) {
743 error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x, 0x%x) failed: %m\n",
744 __func__, vdev->host.domain, vdev->host.bus,
745 vdev->host.slot, vdev->host.function, addr, val, len);
746 }
747
748 /* Write standard header bits to emulation */
749 if (addr < PCI_CONFIG_HEADER_SIZE) {
750 pci_default_write_config(pdev, addr, val, len);
751 return;
752 }
753
754 /* MSI/MSI-X Enabling/Disabling */
755 if (pdev->cap_present & QEMU_PCI_CAP_MSI &&
756 ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {
757 int is_enabled, was_enabled = msi_enabled(pdev);
758
759 pci_default_write_config(pdev, addr, val, len);
760
761 is_enabled = msi_enabled(pdev);
762
763 if (!was_enabled && is_enabled) {
764 vfio_enable_msi(vdev);
765 } else if (was_enabled && !is_enabled) {
766 vfio_disable_msi_x(vdev, false);
767 }
768 }
769
770 if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
771 ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {
772 int is_enabled, was_enabled = msix_enabled(pdev);
773
774 pci_default_write_config(pdev, addr, val, len);
775
776 is_enabled = msix_enabled(pdev);
777
778 if (!was_enabled && is_enabled) {
779 /* vfio_msix_vector_use handles this automatically */
780 } else if (was_enabled && !is_enabled) {
781 vfio_disable_msi_x(vdev, true);
782 }
783 }
784}
785
786/*
787 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
788 */
789static int vfio_dma_map(VFIOContainer *container, target_phys_addr_t iova,
790 ram_addr_t size, void *vaddr, bool readonly)
791{
792 struct vfio_iommu_type1_dma_map map = {
793 .argsz = sizeof(map),
794 .flags = VFIO_DMA_MAP_FLAG_READ,
0f41dc18 795 .vaddr = (__u64)(intptr_t)vaddr,
65501a74
AW
796 .iova = iova,
797 .size = size,
798 };
799
800 if (!readonly) {
801 map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
802 }
803
804 if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map)) {
805 DPRINTF("VFIO_MAP_DMA: %d\n", -errno);
806 return -errno;
807 }
808
809 return 0;
810}
811
812static int vfio_dma_unmap(VFIOContainer *container,
813 target_phys_addr_t iova, ram_addr_t size)
814{
815 struct vfio_iommu_type1_dma_unmap unmap = {
816 .argsz = sizeof(unmap),
817 .flags = 0,
818 .iova = iova,
819 .size = size,
820 };
821
822 if (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
823 DPRINTF("VFIO_UNMAP_DMA: %d\n", -errno);
824 return -errno;
825 }
826
827 return 0;
828}
829
830static void vfio_listener_dummy1(MemoryListener *listener)
831{
832 /* We don't do batching (begin/commit) or care about logging */
833}
834
835static void vfio_listener_dummy2(MemoryListener *listener,
836 MemoryRegionSection *section)
837{
838 /* We don't do logging or care about nops */
839}
840
841static void vfio_listener_dummy3(MemoryListener *listener,
842 MemoryRegionSection *section,
843 bool match_data, uint64_t data,
844 EventNotifier *e)
845{
846 /* We don't care about eventfds */
847}
848
849static bool vfio_listener_skipped_section(MemoryRegionSection *section)
850{
851 return !memory_region_is_ram(section->mr);
852}
853
854static void vfio_listener_region_add(MemoryListener *listener,
855 MemoryRegionSection *section)
856{
857 VFIOContainer *container = container_of(listener, VFIOContainer,
858 iommu_data.listener);
859 target_phys_addr_t iova, end;
860 void *vaddr;
861 int ret;
862
863 if (vfio_listener_skipped_section(section)) {
864 DPRINTF("vfio: SKIPPING region_add %"TARGET_PRIxPHYS" - %"PRIx64"\n",
865 section->offset_within_address_space,
866 section->offset_within_address_space + section->size - 1);
867 return;
868 }
869
870 if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
871 (section->offset_within_region & ~TARGET_PAGE_MASK))) {
872 error_report("%s received unaligned region\n", __func__);
873 return;
874 }
875
876 iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
877 end = (section->offset_within_address_space + section->size) &
878 TARGET_PAGE_MASK;
879
880 if (iova >= end) {
881 return;
882 }
883
884 vaddr = memory_region_get_ram_ptr(section->mr) +
885 section->offset_within_region +
886 (iova - section->offset_within_address_space);
887
888 DPRINTF("vfio: region_add %"TARGET_PRIxPHYS" - %"TARGET_PRIxPHYS" [%p]\n",
889 iova, end - 1, vaddr);
890
891 ret = vfio_dma_map(container, iova, end - iova, vaddr, section->readonly);
892 if (ret) {
893 error_report("vfio_dma_map(%p, 0x%"TARGET_PRIxPHYS", "
894 "0x%"TARGET_PRIxPHYS", %p) = %d (%m)\n",
895 container, iova, end - iova, vaddr, ret);
896 }
897}
898
899static void vfio_listener_region_del(MemoryListener *listener,
900 MemoryRegionSection *section)
901{
902 VFIOContainer *container = container_of(listener, VFIOContainer,
903 iommu_data.listener);
904 target_phys_addr_t iova, end;
905 int ret;
906
907 if (vfio_listener_skipped_section(section)) {
908 DPRINTF("vfio: SKIPPING region_del %"TARGET_PRIxPHYS" - %"PRIx64"\n",
909 section->offset_within_address_space,
910 section->offset_within_address_space + section->size - 1);
911 return;
912 }
913
914 if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
915 (section->offset_within_region & ~TARGET_PAGE_MASK))) {
916 error_report("%s received unaligned region\n", __func__);
917 return;
918 }
919
920 iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
921 end = (section->offset_within_address_space + section->size) &
922 TARGET_PAGE_MASK;
923
924 if (iova >= end) {
925 return;
926 }
927
928 DPRINTF("vfio: region_del %"TARGET_PRIxPHYS" - %"TARGET_PRIxPHYS"\n",
929 iova, end - 1);
930
931 ret = vfio_dma_unmap(container, iova, end - iova);
932 if (ret) {
933 error_report("vfio_dma_unmap(%p, 0x%"TARGET_PRIxPHYS", "
934 "0x%"TARGET_PRIxPHYS") = %d (%m)\n",
935 container, iova, end - iova, ret);
936 }
937}
938
939static MemoryListener vfio_memory_listener = {
940 .begin = vfio_listener_dummy1,
941 .commit = vfio_listener_dummy1,
942 .region_add = vfio_listener_region_add,
943 .region_del = vfio_listener_region_del,
944 .region_nop = vfio_listener_dummy2,
945 .log_start = vfio_listener_dummy2,
946 .log_stop = vfio_listener_dummy2,
947 .log_sync = vfio_listener_dummy2,
948 .log_global_start = vfio_listener_dummy1,
949 .log_global_stop = vfio_listener_dummy1,
950 .eventfd_add = vfio_listener_dummy3,
951 .eventfd_del = vfio_listener_dummy3,
952};
953
954static void vfio_listener_release(VFIOContainer *container)
955{
956 memory_listener_unregister(&container->iommu_data.listener);
957}
958
959/*
960 * Interrupt setup
961 */
962static void vfio_disable_interrupts(VFIODevice *vdev)
963{
964 switch (vdev->interrupt) {
965 case VFIO_INT_INTx:
966 vfio_disable_intx(vdev);
967 break;
968 case VFIO_INT_MSI:
969 vfio_disable_msi_x(vdev, false);
970 break;
971 case VFIO_INT_MSIX:
972 vfio_disable_msi_x(vdev, true);
973 break;
974 }
975}
976
977static int vfio_setup_msi(VFIODevice *vdev, int pos)
978{
979 uint16_t ctrl;
980 bool msi_64bit, msi_maskbit;
981 int ret, entries;
982
983 /*
984 * TODO: don't peek into msi_supported, let msi_init fail and
985 * check for ENOTSUP
986 */
987 if (!msi_supported) {
988 return 0;
989 }
990
991 if (pread(vdev->fd, &ctrl, sizeof(ctrl),
992 vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
993 return -errno;
994 }
995 ctrl = le16_to_cpu(ctrl);
996
997 msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT);
998 msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT);
999 entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1);
1000
1001 DPRINTF("%04x:%02x:%02x.%x PCI MSI CAP @0x%x\n", vdev->host.domain,
1002 vdev->host.bus, vdev->host.slot, vdev->host.function, pos);
1003
1004 ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit);
1005 if (ret < 0) {
1006 error_report("vfio: msi_init failed\n");
1007 return ret;
1008 }
1009 vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0);
1010
1011 return 0;
1012}
1013
1014/*
1015 * We don't have any control over how pci_add_capability() inserts
1016 * capabilities into the chain. In order to setup MSI-X we need a
1017 * MemoryRegion for the BAR. In order to setup the BAR and not
1018 * attempt to mmap the MSI-X table area, which VFIO won't allow, we
1019 * need to first look for where the MSI-X table lives. So we
1020 * unfortunately split MSI-X setup across two functions.
1021 */
1022static int vfio_early_setup_msix(VFIODevice *vdev)
1023{
1024 uint8_t pos;
1025 uint16_t ctrl;
1026 uint32_t table, pba;
1027
1028 pos = pci_find_capability(&vdev->pdev, PCI_CAP_ID_MSIX);
1029 if (!pos) {
1030 return 0;
1031 }
1032
1033 if (pread(vdev->fd, &ctrl, sizeof(ctrl),
1034 vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
1035 return -errno;
1036 }
1037
1038 if (pread(vdev->fd, &table, sizeof(table),
1039 vdev->config_offset + pos + PCI_MSIX_TABLE) != sizeof(table)) {
1040 return -errno;
1041 }
1042
1043 if (pread(vdev->fd, &pba, sizeof(pba),
1044 vdev->config_offset + pos + PCI_MSIX_PBA) != sizeof(pba)) {
1045 return -errno;
1046 }
1047
1048 ctrl = le16_to_cpu(ctrl);
1049 table = le32_to_cpu(table);
1050 pba = le32_to_cpu(pba);
1051
1052 vdev->msix = g_malloc0(sizeof(*(vdev->msix)));
1053 vdev->msix->table_bar = table & PCI_MSIX_FLAGS_BIRMASK;
1054 vdev->msix->table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
1055 vdev->msix->pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK;
1056 vdev->msix->pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
1057 vdev->msix->entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
1058
1059 DPRINTF("%04x:%02x:%02x.%x "
1060 "PCI MSI-X CAP @0x%x, BAR %d, offset 0x%x, entries %d\n",
1061 vdev->host.domain, vdev->host.bus, vdev->host.slot,
1062 vdev->host.function, pos, vdev->msix->table_bar,
1063 vdev->msix->table_offset, vdev->msix->entries);
1064
1065 return 0;
1066}
1067
1068static int vfio_setup_msix(VFIODevice *vdev, int pos)
1069{
1070 int ret;
1071
1072 /*
1073 * TODO: don't peek into msi_supported, let msix_init fail and
1074 * check for ENOTSUP
1075 */
1076 if (!msi_supported) {
1077 return 0;
1078 }
1079
1080 ret = msix_init(&vdev->pdev, vdev->msix->entries,
1081 &vdev->bars[vdev->msix->table_bar].mem,
1082 vdev->msix->table_bar, vdev->msix->table_offset,
1083 &vdev->bars[vdev->msix->pba_bar].mem,
1084 vdev->msix->pba_bar, vdev->msix->pba_offset, pos);
1085 if (ret < 0) {
1086 error_report("vfio: msix_init failed\n");
1087 return ret;
1088 }
1089
1090 ret = msix_set_vector_notifiers(&vdev->pdev, vfio_msix_vector_use,
1091 vfio_msix_vector_release);
1092 if (ret) {
1093 error_report("vfio: msix_set_vector_notifiers failed %d\n", ret);
1094 msix_uninit(&vdev->pdev, &vdev->bars[vdev->msix->table_bar].mem,
1095 &vdev->bars[vdev->msix->pba_bar].mem);
1096 return ret;
1097 }
1098
1099 return 0;
1100}
1101
1102static void vfio_teardown_msi(VFIODevice *vdev)
1103{
1104 msi_uninit(&vdev->pdev);
1105
1106 if (vdev->msix) {
1107 /* FIXME: Why can't unset just silently do nothing?? */
1108 if (vdev->pdev.msix_vector_use_notifier &&
1109 vdev->pdev.msix_vector_release_notifier) {
1110 msix_unset_vector_notifiers(&vdev->pdev);
1111 }
1112
1113 msix_uninit(&vdev->pdev, &vdev->bars[vdev->msix->table_bar].mem,
1114 &vdev->bars[vdev->msix->pba_bar].mem);
1115 }
1116}
1117
1118/*
1119 * Resource setup
1120 */
1121static void vfio_mmap_set_enabled(VFIODevice *vdev, bool enabled)
1122{
1123 int i;
1124
1125 for (i = 0; i < PCI_ROM_SLOT; i++) {
1126 VFIOBAR *bar = &vdev->bars[i];
1127
1128 if (!bar->size) {
1129 continue;
1130 }
1131
1132 memory_region_set_enabled(&bar->mmap_mem, enabled);
1133 if (vdev->msix && vdev->msix->table_bar == i) {
1134 memory_region_set_enabled(&vdev->msix->mmap_mem, enabled);
1135 }
1136 }
1137}
1138
1139static void vfio_unmap_bar(VFIODevice *vdev, int nr)
1140{
1141 VFIOBAR *bar = &vdev->bars[nr];
1142
1143 if (!bar->size) {
1144 return;
1145 }
1146
1147 memory_region_del_subregion(&bar->mem, &bar->mmap_mem);
1148 munmap(bar->mmap, memory_region_size(&bar->mmap_mem));
1149
1150 if (vdev->msix && vdev->msix->table_bar == nr) {
1151 memory_region_del_subregion(&bar->mem, &vdev->msix->mmap_mem);
1152 munmap(vdev->msix->mmap, memory_region_size(&vdev->msix->mmap_mem));
1153 }
1154
1155 memory_region_destroy(&bar->mem);
1156}
1157
1158static int vfio_mmap_bar(VFIOBAR *bar, MemoryRegion *mem, MemoryRegion *submem,
1159 void **map, size_t size, off_t offset,
1160 const char *name)
1161{
1162 int ret = 0;
1163
1164 if (size && bar->flags & VFIO_REGION_INFO_FLAG_MMAP) {
1165 int prot = 0;
1166
1167 if (bar->flags & VFIO_REGION_INFO_FLAG_READ) {
1168 prot |= PROT_READ;
1169 }
1170
1171 if (bar->flags & VFIO_REGION_INFO_FLAG_WRITE) {
1172 prot |= PROT_WRITE;
1173 }
1174
1175 *map = mmap(NULL, size, prot, MAP_SHARED,
1176 bar->fd, bar->fd_offset + offset);
1177 if (*map == MAP_FAILED) {
1178 *map = NULL;
1179 ret = -errno;
1180 goto empty_region;
1181 }
1182
1183 memory_region_init_ram_ptr(submem, name, size, *map);
1184 } else {
1185empty_region:
1186 /* Create a zero sized sub-region to make cleanup easy. */
1187 memory_region_init(submem, name, 0);
1188 }
1189
1190 memory_region_add_subregion(mem, offset, submem);
1191
1192 return ret;
1193}
1194
1195static void vfio_map_bar(VFIODevice *vdev, int nr)
1196{
1197 VFIOBAR *bar = &vdev->bars[nr];
1198 unsigned size = bar->size;
1199 char name[64];
1200 uint32_t pci_bar;
1201 uint8_t type;
1202 int ret;
1203
1204 /* Skip both unimplemented BARs and the upper half of 64bit BARS. */
1205 if (!size) {
1206 return;
1207 }
1208
1209 snprintf(name, sizeof(name), "VFIO %04x:%02x:%02x.%x BAR %d",
1210 vdev->host.domain, vdev->host.bus, vdev->host.slot,
1211 vdev->host.function, nr);
1212
1213 /* Determine what type of BAR this is for registration */
1214 ret = pread(vdev->fd, &pci_bar, sizeof(pci_bar),
1215 vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));
1216 if (ret != sizeof(pci_bar)) {
1217 error_report("vfio: Failed to read BAR %d (%m)\n", nr);
1218 return;
1219 }
1220
1221 pci_bar = le32_to_cpu(pci_bar);
1222 type = pci_bar & (pci_bar & PCI_BASE_ADDRESS_SPACE_IO ?
1223 ~PCI_BASE_ADDRESS_IO_MASK : ~PCI_BASE_ADDRESS_MEM_MASK);
1224
1225 /* A "slow" read/write mapping underlies all BARs */
1226 memory_region_init_io(&bar->mem, &vfio_bar_ops, bar, name, size);
1227 pci_register_bar(&vdev->pdev, nr, type, &bar->mem);
1228
1229 /*
1230 * We can't mmap areas overlapping the MSIX vector table, so we
1231 * potentially insert a direct-mapped subregion before and after it.
1232 */
1233 if (vdev->msix && vdev->msix->table_bar == nr) {
1234 size = vdev->msix->table_offset & TARGET_PAGE_MASK;
1235 }
1236
1237 strncat(name, " mmap", sizeof(name) - strlen(name) - 1);
1238 if (vfio_mmap_bar(bar, &bar->mem,
1239 &bar->mmap_mem, &bar->mmap, size, 0, name)) {
1240 error_report("%s unsupported. Performance may be slow\n", name);
1241 }
1242
1243 if (vdev->msix && vdev->msix->table_bar == nr) {
1244 unsigned start;
1245
1246 start = TARGET_PAGE_ALIGN(vdev->msix->table_offset +
1247 (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE));
1248
1249 size = start < bar->size ? bar->size - start : 0;
1250 strncat(name, " msix-hi", sizeof(name) - strlen(name) - 1);
1251 /* VFIOMSIXInfo contains another MemoryRegion for this mapping */
1252 if (vfio_mmap_bar(bar, &bar->mem, &vdev->msix->mmap_mem,
1253 &vdev->msix->mmap, size, start, name)) {
1254 error_report("%s unsupported. Performance may be slow\n", name);
1255 }
1256 }
1257}
1258
1259static void vfio_map_bars(VFIODevice *vdev)
1260{
1261 int i;
1262
1263 for (i = 0; i < PCI_ROM_SLOT; i++) {
1264 vfio_map_bar(vdev, i);
1265 }
1266}
1267
1268static void vfio_unmap_bars(VFIODevice *vdev)
1269{
1270 int i;
1271
1272 for (i = 0; i < PCI_ROM_SLOT; i++) {
1273 vfio_unmap_bar(vdev, i);
1274 }
1275}
1276
1277/*
1278 * General setup
1279 */
1280static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos)
1281{
1282 uint8_t tmp, next = 0xff;
1283
1284 for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp;
1285 tmp = pdev->config[tmp + 1]) {
1286 if (tmp > pos && tmp < next) {
1287 next = tmp;
1288 }
1289 }
1290
1291 return next - pos;
1292}
1293
1294static int vfio_add_std_cap(VFIODevice *vdev, uint8_t pos)
1295{
1296 PCIDevice *pdev = &vdev->pdev;
1297 uint8_t cap_id, next, size;
1298 int ret;
1299
1300 cap_id = pdev->config[pos];
1301 next = pdev->config[pos + 1];
1302
1303 /*
1304 * If it becomes important to configure capabilities to their actual
1305 * size, use this as the default when it's something we don't recognize.
1306 * Since QEMU doesn't actually handle many of the config accesses,
1307 * exact size doesn't seem worthwhile.
1308 */
1309 size = vfio_std_cap_max_size(pdev, pos);
1310
1311 /*
1312 * pci_add_capability always inserts the new capability at the head
1313 * of the chain. Therefore to end up with a chain that matches the
1314 * physical device, we insert from the end by making this recursive.
1315 * This is also why we pre-caclulate size above as cached config space
1316 * will be changed as we unwind the stack.
1317 */
1318 if (next) {
1319 ret = vfio_add_std_cap(vdev, next);
1320 if (ret) {
1321 return ret;
1322 }
1323 } else {
1324 pdev->config[PCI_CAPABILITY_LIST] = 0; /* Begin the rebuild */
1325 }
1326
1327 switch (cap_id) {
1328 case PCI_CAP_ID_MSI:
1329 ret = vfio_setup_msi(vdev, pos);
1330 break;
1331 case PCI_CAP_ID_MSIX:
1332 ret = vfio_setup_msix(vdev, pos);
1333 break;
1334 default:
1335 ret = pci_add_capability(pdev, cap_id, pos, size);
1336 break;
1337 }
1338
1339 if (ret < 0) {
1340 error_report("vfio: %04x:%02x:%02x.%x Error adding PCI capability "
1341 "0x%x[0x%x]@0x%x: %d\n", vdev->host.domain,
1342 vdev->host.bus, vdev->host.slot, vdev->host.function,
1343 cap_id, size, pos, ret);
1344 return ret;
1345 }
1346
1347 return 0;
1348}
1349
1350static int vfio_add_capabilities(VFIODevice *vdev)
1351{
1352 PCIDevice *pdev = &vdev->pdev;
1353
1354 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
1355 !pdev->config[PCI_CAPABILITY_LIST]) {
1356 return 0; /* Nothing to add */
1357 }
1358
1359 return vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST]);
1360}
1361
1362static int vfio_load_rom(VFIODevice *vdev)
1363{
1364 uint64_t size = vdev->rom_size;
1365 char name[32];
1366 off_t off = 0, voff = vdev->rom_offset;
1367 ssize_t bytes;
1368 void *ptr;
1369
1370 /* If loading ROM from file, pci handles it */
1371 if (vdev->pdev.romfile || !vdev->pdev.rom_bar || !size) {
1372 return 0;
1373 }
1374
1375 DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
1376 vdev->host.bus, vdev->host.slot, vdev->host.function);
1377
1378 snprintf(name, sizeof(name), "vfio[%04x:%02x:%02x.%x].rom",
1379 vdev->host.domain, vdev->host.bus, vdev->host.slot,
1380 vdev->host.function);
1381 memory_region_init_ram(&vdev->pdev.rom, name, size);
1382 ptr = memory_region_get_ram_ptr(&vdev->pdev.rom);
1383 memset(ptr, 0xff, size);
1384
1385 while (size) {
1386 bytes = pread(vdev->fd, ptr + off, size, voff + off);
1387 if (bytes == 0) {
1388 break; /* expect that we could get back less than the ROM BAR */
1389 } else if (bytes > 0) {
1390 off += bytes;
1391 size -= bytes;
1392 } else {
1393 if (errno == EINTR || errno == EAGAIN) {
1394 continue;
1395 }
1396 error_report("vfio: Error reading device ROM: %m\n");
1397 memory_region_destroy(&vdev->pdev.rom);
1398 return -errno;
1399 }
1400 }
1401
1402 pci_register_bar(&vdev->pdev, PCI_ROM_SLOT, 0, &vdev->pdev.rom);
1403 vdev->pdev.has_rom = true;
1404 return 0;
1405}
1406
1407static int vfio_connect_container(VFIOGroup *group)
1408{
1409 VFIOContainer *container;
1410 int ret, fd;
1411
1412 if (group->container) {
1413 return 0;
1414 }
1415
1416 QLIST_FOREACH(container, &container_list, next) {
1417 if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
1418 group->container = container;
1419 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
1420 return 0;
1421 }
1422 }
1423
1424 fd = qemu_open("/dev/vfio/vfio", O_RDWR);
1425 if (fd < 0) {
1426 error_report("vfio: failed to open /dev/vfio/vfio: %m\n");
1427 return -errno;
1428 }
1429
1430 ret = ioctl(fd, VFIO_GET_API_VERSION);
1431 if (ret != VFIO_API_VERSION) {
1432 error_report("vfio: supported vfio version: %d, "
1433 "reported version: %d\n", VFIO_API_VERSION, ret);
1434 close(fd);
1435 return -EINVAL;
1436 }
1437
1438 container = g_malloc0(sizeof(*container));
1439 container->fd = fd;
1440
1441 if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU)) {
1442 ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
1443 if (ret) {
1444 error_report("vfio: failed to set group container: %m\n");
1445 g_free(container);
1446 close(fd);
1447 return -errno;
1448 }
1449
1450 ret = ioctl(fd, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU);
1451 if (ret) {
1452 error_report("vfio: failed to set iommu for container: %m\n");
1453 g_free(container);
1454 close(fd);
1455 return -errno;
1456 }
1457
1458 container->iommu_data.listener = vfio_memory_listener;
1459 container->iommu_data.release = vfio_listener_release;
1460
1461 memory_listener_register(&container->iommu_data.listener,
1462 get_system_memory());
1463 } else {
1464 error_report("vfio: No available IOMMU models\n");
1465 g_free(container);
1466 close(fd);
1467 return -EINVAL;
1468 }
1469
1470 QLIST_INIT(&container->group_list);
1471 QLIST_INSERT_HEAD(&container_list, container, next);
1472
1473 group->container = container;
1474 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
1475
1476 return 0;
1477}
1478
1479static void vfio_disconnect_container(VFIOGroup *group)
1480{
1481 VFIOContainer *container = group->container;
1482
1483 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
1484 error_report("vfio: error disconnecting group %d from container\n",
1485 group->groupid);
1486 }
1487
1488 QLIST_REMOVE(group, container_next);
1489 group->container = NULL;
1490
1491 if (QLIST_EMPTY(&container->group_list)) {
1492 if (container->iommu_data.release) {
1493 container->iommu_data.release(container);
1494 }
1495 QLIST_REMOVE(container, next);
1496 DPRINTF("vfio_disconnect_container: close container->fd\n");
1497 close(container->fd);
1498 g_free(container);
1499 }
1500}
1501
1502static VFIOGroup *vfio_get_group(int groupid)
1503{
1504 VFIOGroup *group;
1505 char path[32];
1506 struct vfio_group_status status = { .argsz = sizeof(status) };
1507
1508 QLIST_FOREACH(group, &group_list, next) {
1509 if (group->groupid == groupid) {
1510 return group;
1511 }
1512 }
1513
1514 group = g_malloc0(sizeof(*group));
1515
1516 snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
1517 group->fd = qemu_open(path, O_RDWR);
1518 if (group->fd < 0) {
1519 error_report("vfio: error opening %s: %m\n", path);
1520 g_free(group);
1521 return NULL;
1522 }
1523
1524 if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
1525 error_report("vfio: error getting group status: %m\n");
1526 close(group->fd);
1527 g_free(group);
1528 return NULL;
1529 }
1530
1531 if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
1532 error_report("vfio: error, group %d is not viable, please ensure "
1533 "all devices within the iommu_group are bound to their "
1534 "vfio bus driver.\n", groupid);
1535 close(group->fd);
1536 g_free(group);
1537 return NULL;
1538 }
1539
1540 group->groupid = groupid;
1541 QLIST_INIT(&group->device_list);
1542
1543 if (vfio_connect_container(group)) {
1544 error_report("vfio: failed to setup container for group %d\n", groupid);
1545 close(group->fd);
1546 g_free(group);
1547 return NULL;
1548 }
1549
1550 QLIST_INSERT_HEAD(&group_list, group, next);
1551
1552 return group;
1553}
1554
1555static void vfio_put_group(VFIOGroup *group)
1556{
1557 if (!QLIST_EMPTY(&group->device_list)) {
1558 return;
1559 }
1560
1561 vfio_disconnect_container(group);
1562 QLIST_REMOVE(group, next);
1563 DPRINTF("vfio_put_group: close group->fd\n");
1564 close(group->fd);
1565 g_free(group);
1566}
1567
1568static int vfio_get_device(VFIOGroup *group, const char *name, VFIODevice *vdev)
1569{
1570 struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
1571 struct vfio_region_info reg_info = { .argsz = sizeof(reg_info) };
1572 int ret, i;
1573
1574 ret = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
1575 if (ret < 0) {
1576 error_report("vfio: error getting device %s from group %d: %m\n",
1577 name, group->groupid);
1578 error_report("Verify all devices in group %d are bound to vfio-pci "
1579 "or pci-stub and not already in use\n", group->groupid);
1580 return ret;
1581 }
1582
1583 vdev->fd = ret;
1584 vdev->group = group;
1585 QLIST_INSERT_HEAD(&group->device_list, vdev, next);
1586
1587 /* Sanity check device */
1588 ret = ioctl(vdev->fd, VFIO_DEVICE_GET_INFO, &dev_info);
1589 if (ret) {
1590 error_report("vfio: error getting device info: %m\n");
1591 goto error;
1592 }
1593
1594 DPRINTF("Device %s flags: %u, regions: %u, irgs: %u\n", name,
1595 dev_info.flags, dev_info.num_regions, dev_info.num_irqs);
1596
1597 if (!(dev_info.flags & VFIO_DEVICE_FLAGS_PCI)) {
1598 error_report("vfio: Um, this isn't a PCI device\n");
1599 goto error;
1600 }
1601
1602 vdev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
1603 if (!vdev->reset_works) {
1604 error_report("Warning, device %s does not support reset\n", name);
1605 }
1606
1607 if (dev_info.num_regions != VFIO_PCI_NUM_REGIONS) {
1608 error_report("vfio: unexpected number of io regions %u\n",
1609 dev_info.num_regions);
1610 goto error;
1611 }
1612
1613 if (dev_info.num_irqs != VFIO_PCI_NUM_IRQS) {
1614 error_report("vfio: unexpected number of irqs %u\n", dev_info.num_irqs);
1615 goto error;
1616 }
1617
1618 for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
1619 reg_info.index = i;
1620
1621 ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
1622 if (ret) {
1623 error_report("vfio: Error getting region %d info: %m\n", i);
1624 goto error;
1625 }
1626
1627 DPRINTF("Device %s region %d:\n", name, i);
1628 DPRINTF(" size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
1629 (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
1630 (unsigned long)reg_info.flags);
1631
1632 vdev->bars[i].flags = reg_info.flags;
1633 vdev->bars[i].size = reg_info.size;
1634 vdev->bars[i].fd_offset = reg_info.offset;
1635 vdev->bars[i].fd = vdev->fd;
1636 vdev->bars[i].nr = i;
1637 }
1638
1639 reg_info.index = VFIO_PCI_ROM_REGION_INDEX;
1640
1641 ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
1642 if (ret) {
1643 error_report("vfio: Error getting ROM info: %m\n");
1644 goto error;
1645 }
1646
1647 DPRINTF("Device %s ROM:\n", name);
1648 DPRINTF(" size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
1649 (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
1650 (unsigned long)reg_info.flags);
1651
1652 vdev->rom_size = reg_info.size;
1653 vdev->rom_offset = reg_info.offset;
1654
1655 reg_info.index = VFIO_PCI_CONFIG_REGION_INDEX;
1656
1657 ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
1658 if (ret) {
1659 error_report("vfio: Error getting config info: %m\n");
1660 goto error;
1661 }
1662
1663 DPRINTF("Device %s config:\n", name);
1664 DPRINTF(" size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
1665 (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
1666 (unsigned long)reg_info.flags);
1667
1668 vdev->config_size = reg_info.size;
1669 vdev->config_offset = reg_info.offset;
1670
1671error:
1672 if (ret) {
1673 QLIST_REMOVE(vdev, next);
1674 vdev->group = NULL;
1675 close(vdev->fd);
1676 }
1677 return ret;
1678}
1679
1680static void vfio_put_device(VFIODevice *vdev)
1681{
1682 QLIST_REMOVE(vdev, next);
1683 vdev->group = NULL;
1684 DPRINTF("vfio_put_device: close vdev->fd\n");
1685 close(vdev->fd);
1686 if (vdev->msix) {
1687 g_free(vdev->msix);
1688 vdev->msix = NULL;
1689 }
1690}
1691
1692static int vfio_initfn(PCIDevice *pdev)
1693{
1694 VFIODevice *pvdev, *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
1695 VFIOGroup *group;
1696 char path[PATH_MAX], iommu_group_path[PATH_MAX], *group_name;
1697 ssize_t len;
1698 struct stat st;
1699 int groupid;
1700 int ret;
1701
1702 /* Check that the host device exists */
1703 snprintf(path, sizeof(path),
1704 "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/",
1705 vdev->host.domain, vdev->host.bus, vdev->host.slot,
1706 vdev->host.function);
1707 if (stat(path, &st) < 0) {
1708 error_report("vfio: error: no such host device: %s\n", path);
1709 return -errno;
1710 }
1711
1712 strncat(path, "iommu_group", sizeof(path) - strlen(path) - 1);
1713
1714 len = readlink(path, iommu_group_path, PATH_MAX);
1715 if (len <= 0) {
1716 error_report("vfio: error no iommu_group for device\n");
1717 return -errno;
1718 }
1719
1720 iommu_group_path[len] = 0;
1721 group_name = basename(iommu_group_path);
1722
1723 if (sscanf(group_name, "%d", &groupid) != 1) {
1724 error_report("vfio: error reading %s: %m\n", path);
1725 return -errno;
1726 }
1727
1728 DPRINTF("%s(%04x:%02x:%02x.%x) group %d\n", __func__, vdev->host.domain,
1729 vdev->host.bus, vdev->host.slot, vdev->host.function, groupid);
1730
1731 group = vfio_get_group(groupid);
1732 if (!group) {
1733 error_report("vfio: failed to get group %d\n", groupid);
1734 return -ENOENT;
1735 }
1736
1737 snprintf(path, sizeof(path), "%04x:%02x:%02x.%01x",
1738 vdev->host.domain, vdev->host.bus, vdev->host.slot,
1739 vdev->host.function);
1740
1741 QLIST_FOREACH(pvdev, &group->device_list, next) {
1742 if (pvdev->host.domain == vdev->host.domain &&
1743 pvdev->host.bus == vdev->host.bus &&
1744 pvdev->host.slot == vdev->host.slot &&
1745 pvdev->host.function == vdev->host.function) {
1746
1747 error_report("vfio: error: device %s is already attached\n", path);
1748 vfio_put_group(group);
1749 return -EBUSY;
1750 }
1751 }
1752
1753 ret = vfio_get_device(group, path, vdev);
1754 if (ret) {
1755 error_report("vfio: failed to get device %s\n", path);
1756 vfio_put_group(group);
1757 return ret;
1758 }
1759
1760 /* Get a copy of config space */
1761 ret = pread(vdev->fd, vdev->pdev.config,
1762 MIN(pci_config_size(&vdev->pdev), vdev->config_size),
1763 vdev->config_offset);
1764 if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
1765 ret = ret < 0 ? -errno : -EFAULT;
1766 error_report("vfio: Failed to read device config space\n");
1767 goto out_put;
1768 }
1769
1770 /*
1771 * Clear host resource mapping info. If we choose not to register a
1772 * BAR, such as might be the case with the option ROM, we can get
1773 * confusing, unwritable, residual addresses from the host here.
1774 */
1775 memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
1776 memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
1777
1778 vfio_load_rom(vdev);
1779
1780 ret = vfio_early_setup_msix(vdev);
1781 if (ret) {
1782 goto out_put;
1783 }
1784
1785 vfio_map_bars(vdev);
1786
1787 ret = vfio_add_capabilities(vdev);
1788 if (ret) {
1789 goto out_teardown;
1790 }
1791
1792 if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
ea486926
AW
1793 vdev->intx.mmap_timer = qemu_new_timer_ms(vm_clock,
1794 vfio_intx_mmap_enable, vdev);
65501a74
AW
1795 ret = vfio_enable_intx(vdev);
1796 if (ret) {
1797 goto out_teardown;
1798 }
1799 }
1800
1801 return 0;
1802
1803out_teardown:
1804 pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
1805 vfio_teardown_msi(vdev);
1806 vfio_unmap_bars(vdev);
1807out_put:
1808 vfio_put_device(vdev);
1809 vfio_put_group(group);
1810 return ret;
1811}
1812
1813static void vfio_exitfn(PCIDevice *pdev)
1814{
1815 VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
1816 VFIOGroup *group = vdev->group;
1817
1818 pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
1819 vfio_disable_interrupts(vdev);
ea486926
AW
1820 if (vdev->intx.mmap_timer) {
1821 qemu_free_timer(vdev->intx.mmap_timer);
1822 }
65501a74
AW
1823 vfio_teardown_msi(vdev);
1824 vfio_unmap_bars(vdev);
1825 vfio_put_device(vdev);
1826 vfio_put_group(group);
1827}
1828
1829static void vfio_pci_reset(DeviceState *dev)
1830{
1831 PCIDevice *pdev = DO_UPCAST(PCIDevice, qdev, dev);
1832 VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
1833
1834 if (!vdev->reset_works) {
1835 return;
1836 }
1837
1838 if (ioctl(vdev->fd, VFIO_DEVICE_RESET)) {
1839 error_report("vfio: Error unable to reset physical device "
1840 "(%04x:%02x:%02x.%x): %m\n", vdev->host.domain,
1841 vdev->host.bus, vdev->host.slot, vdev->host.function);
1842 }
1843}
1844
1845static Property vfio_pci_dev_properties[] = {
1846 DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIODevice, host),
ea486926
AW
1847 DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIODevice,
1848 intx.mmap_timeout, 1100),
65501a74
AW
1849 /*
1850 * TODO - support passed fds... is this necessary?
1851 * DEFINE_PROP_STRING("vfiofd", VFIODevice, vfiofd_name),
1852 * DEFINE_PROP_STRING("vfiogroupfd, VFIODevice, vfiogroupfd_name),
1853 */
1854 DEFINE_PROP_END_OF_LIST(),
1855};
1856
1857
1858static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
1859{
1860 DeviceClass *dc = DEVICE_CLASS(klass);
1861 PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
1862
1863 dc->reset = vfio_pci_reset;
1864 dc->props = vfio_pci_dev_properties;
1865 pdc->init = vfio_initfn;
1866 pdc->exit = vfio_exitfn;
1867 pdc->config_read = vfio_pci_read_config;
1868 pdc->config_write = vfio_pci_write_config;
1869}
1870
1871static const TypeInfo vfio_pci_dev_info = {
1872 .name = "vfio-pci",
1873 .parent = TYPE_PCI_DEVICE,
1874 .instance_size = sizeof(VFIODevice),
1875 .class_init = vfio_pci_dev_class_init,
1876};
1877
1878static void register_vfio_pci_dev_type(void)
1879{
1880 type_register_static(&vfio_pci_dev_info);
1881}
1882
1883type_init(register_vfio_pci_dev_type)