]> git.proxmox.com Git - mirror_qemu.git/blame - hw/vfio/common.c
vfio: Enable sparse mmap capability
[mirror_qemu.git] / hw / vfio / common.c
CommitLineData
e2c7d025
EA
1/*
2 * generic functions used by VFIO devices
3 *
4 * Copyright Red Hat, Inc. 2012
5 *
6 * Authors:
7 * Alex Williamson <alex.williamson@redhat.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 *
12 * Based on qemu-kvm device-assignment:
13 * Adapted for KVM by Qumranet.
14 * Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
15 * Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
16 * Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
17 * Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
18 * Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
19 */
20
c6eacb1a 21#include "qemu/osdep.h"
e2c7d025
EA
22#include <sys/ioctl.h>
23#include <sys/mman.h>
24#include <linux/vfio.h>
25
26#include "hw/vfio/vfio-common.h"
27#include "hw/vfio/vfio.h"
28#include "exec/address-spaces.h"
29#include "exec/memory.h"
30#include "hw/hw.h"
31#include "qemu/error-report.h"
32#include "sysemu/kvm.h"
e81096b1
PB
33#ifdef CONFIG_KVM
34#include "linux/kvm.h"
35#endif
e2c7d025
EA
36#include "trace.h"
37
38struct vfio_group_head vfio_group_list =
39cb514f 39 QLIST_HEAD_INITIALIZER(vfio_group_list);
e2c7d025
EA
40struct vfio_as_head vfio_address_spaces =
41 QLIST_HEAD_INITIALIZER(vfio_address_spaces);
42
43#ifdef CONFIG_KVM
44/*
45 * We have a single VFIO pseudo device per KVM VM. Once created it lives
46 * for the life of the VM. Closing the file descriptor only drops our
47 * reference to it and the device's reference to kvm. Therefore once
48 * initialized, this file descriptor is only released on QEMU exit and
49 * we'll re-use it should another vfio device be attached before then.
50 */
51static int vfio_kvm_device_fd = -1;
52#endif
53
54/*
55 * Common VFIO interrupt disable
56 */
57void vfio_disable_irqindex(VFIODevice *vbasedev, int index)
58{
59 struct vfio_irq_set irq_set = {
60 .argsz = sizeof(irq_set),
61 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
62 .index = index,
63 .start = 0,
64 .count = 0,
65 };
66
67 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
68}
69
70void vfio_unmask_single_irqindex(VFIODevice *vbasedev, int index)
71{
72 struct vfio_irq_set irq_set = {
73 .argsz = sizeof(irq_set),
74 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
75 .index = index,
76 .start = 0,
77 .count = 1,
78 };
79
80 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
81}
82
83void vfio_mask_single_irqindex(VFIODevice *vbasedev, int index)
84{
85 struct vfio_irq_set irq_set = {
86 .argsz = sizeof(irq_set),
87 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK,
88 .index = index,
89 .start = 0,
90 .count = 1,
91 };
92
93 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
94}
95
96/*
97 * IO Port/MMIO - Beware of the endians, VFIO is always little endian
98 */
99void vfio_region_write(void *opaque, hwaddr addr,
100 uint64_t data, unsigned size)
101{
102 VFIORegion *region = opaque;
103 VFIODevice *vbasedev = region->vbasedev;
104 union {
105 uint8_t byte;
106 uint16_t word;
107 uint32_t dword;
108 uint64_t qword;
109 } buf;
110
111 switch (size) {
112 case 1:
113 buf.byte = data;
114 break;
115 case 2:
116 buf.word = cpu_to_le16(data);
117 break;
118 case 4:
119 buf.dword = cpu_to_le32(data);
120 break;
121 default:
122 hw_error("vfio: unsupported write size, %d bytes", size);
123 break;
124 }
125
126 if (pwrite(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
127 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", 0x%"PRIx64
128 ",%d) failed: %m",
129 __func__, vbasedev->name, region->nr,
130 addr, data, size);
131 }
132
133 trace_vfio_region_write(vbasedev->name, region->nr, addr, data, size);
134
135 /*
136 * A read or write to a BAR always signals an INTx EOI. This will
137 * do nothing if not pending (including not in INTx mode). We assume
138 * that a BAR access is in response to an interrupt and that BAR
139 * accesses will service the interrupt. Unfortunately, we don't know
140 * which access will service the interrupt, so we're potentially
141 * getting quite a few host interrupts per guest interrupt.
142 */
143 vbasedev->ops->vfio_eoi(vbasedev);
144}
145
146uint64_t vfio_region_read(void *opaque,
147 hwaddr addr, unsigned size)
148{
149 VFIORegion *region = opaque;
150 VFIODevice *vbasedev = region->vbasedev;
151 union {
152 uint8_t byte;
153 uint16_t word;
154 uint32_t dword;
155 uint64_t qword;
156 } buf;
157 uint64_t data = 0;
158
159 if (pread(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
160 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", %d) failed: %m",
161 __func__, vbasedev->name, region->nr,
162 addr, size);
163 return (uint64_t)-1;
164 }
165 switch (size) {
166 case 1:
167 data = buf.byte;
168 break;
169 case 2:
170 data = le16_to_cpu(buf.word);
171 break;
172 case 4:
173 data = le32_to_cpu(buf.dword);
174 break;
175 default:
176 hw_error("vfio: unsupported read size, %d bytes", size);
177 break;
178 }
179
180 trace_vfio_region_read(vbasedev->name, region->nr, addr, size, data);
181
182 /* Same as write above */
183 vbasedev->ops->vfio_eoi(vbasedev);
184
185 return data;
186}
187
188const MemoryRegionOps vfio_region_ops = {
189 .read = vfio_region_read,
190 .write = vfio_region_write,
191 .endianness = DEVICE_LITTLE_ENDIAN,
192};
193
194/*
195 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
196 */
197static int vfio_dma_unmap(VFIOContainer *container,
198 hwaddr iova, ram_addr_t size)
199{
200 struct vfio_iommu_type1_dma_unmap unmap = {
201 .argsz = sizeof(unmap),
202 .flags = 0,
203 .iova = iova,
204 .size = size,
205 };
206
207 if (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
78e5b17f 208 error_report("VFIO_UNMAP_DMA: %d", -errno);
e2c7d025
EA
209 return -errno;
210 }
211
212 return 0;
213}
214
215static int vfio_dma_map(VFIOContainer *container, hwaddr iova,
216 ram_addr_t size, void *vaddr, bool readonly)
217{
218 struct vfio_iommu_type1_dma_map map = {
219 .argsz = sizeof(map),
220 .flags = VFIO_DMA_MAP_FLAG_READ,
221 .vaddr = (__u64)(uintptr_t)vaddr,
222 .iova = iova,
223 .size = size,
224 };
225
226 if (!readonly) {
227 map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
228 }
229
230 /*
231 * Try the mapping, if it fails with EBUSY, unmap the region and try
232 * again. This shouldn't be necessary, but we sometimes see it in
b6af0975 233 * the VGA ROM space.
e2c7d025
EA
234 */
235 if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
236 (errno == EBUSY && vfio_dma_unmap(container, iova, size) == 0 &&
237 ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
238 return 0;
239 }
240
78e5b17f 241 error_report("VFIO_MAP_DMA: %d", -errno);
e2c7d025
EA
242 return -errno;
243}
244
245static bool vfio_listener_skipped_section(MemoryRegionSection *section)
246{
247 return (!memory_region_is_ram(section->mr) &&
248 !memory_region_is_iommu(section->mr)) ||
249 /*
250 * Sizing an enabled 64-bit BAR can cause spurious mappings to
251 * addresses in the upper part of the 64-bit address space. These
252 * are never accessed by the CPU and beyond the address width of
253 * some IOMMU hardware. TODO: VFIO should tell us the IOMMU width.
254 */
255 section->offset_within_address_space & (1ULL << 63);
256}
257
258static void vfio_iommu_map_notify(Notifier *n, void *data)
259{
260 VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
261 VFIOContainer *container = giommu->container;
262 IOMMUTLBEntry *iotlb = data;
263 MemoryRegion *mr;
264 hwaddr xlat;
265 hwaddr len = iotlb->addr_mask + 1;
266 void *vaddr;
267 int ret;
268
269 trace_vfio_iommu_map_notify(iotlb->iova,
270 iotlb->iova + iotlb->addr_mask);
271
272 /*
273 * The IOMMU TLB entry we have just covers translation through
274 * this IOMMU to its immediate target. We need to translate
275 * it the rest of the way through to memory.
276 */
41063e1e 277 rcu_read_lock();
e2c7d025
EA
278 mr = address_space_translate(&address_space_memory,
279 iotlb->translated_addr,
280 &xlat, &len, iotlb->perm & IOMMU_WO);
281 if (!memory_region_is_ram(mr)) {
78e5b17f 282 error_report("iommu map to non memory area %"HWADDR_PRIx"",
e2c7d025 283 xlat);
41063e1e 284 goto out;
e2c7d025
EA
285 }
286 /*
287 * Translation truncates length to the IOMMU page size,
288 * check that it did not truncate too much.
289 */
290 if (len & iotlb->addr_mask) {
78e5b17f 291 error_report("iommu has granularity incompatible with target AS");
41063e1e 292 goto out;
e2c7d025
EA
293 }
294
295 if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {
296 vaddr = memory_region_get_ram_ptr(mr) + xlat;
297 ret = vfio_dma_map(container, iotlb->iova,
298 iotlb->addr_mask + 1, vaddr,
299 !(iotlb->perm & IOMMU_WO) || mr->readonly);
300 if (ret) {
301 error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
302 "0x%"HWADDR_PRIx", %p) = %d (%m)",
303 container, iotlb->iova,
304 iotlb->addr_mask + 1, vaddr, ret);
305 }
306 } else {
307 ret = vfio_dma_unmap(container, iotlb->iova, iotlb->addr_mask + 1);
308 if (ret) {
309 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
310 "0x%"HWADDR_PRIx") = %d (%m)",
311 container, iotlb->iova,
312 iotlb->addr_mask + 1, ret);
313 }
314 }
41063e1e
PB
315out:
316 rcu_read_unlock();
e2c7d025
EA
317}
318
508ce5eb
DG
319static hwaddr vfio_container_granularity(VFIOContainer *container)
320{
321 return (hwaddr)1 << ctz64(container->iova_pgsizes);
322}
323
e2c7d025
EA
324static void vfio_listener_region_add(MemoryListener *listener,
325 MemoryRegionSection *section)
326{
ee0bf0e5 327 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
e2c7d025 328 hwaddr iova, end;
55efcc53 329 Int128 llend, llsize;
e2c7d025
EA
330 void *vaddr;
331 int ret;
332
333 if (vfio_listener_skipped_section(section)) {
334 trace_vfio_listener_region_add_skip(
335 section->offset_within_address_space,
336 section->offset_within_address_space +
337 int128_get64(int128_sub(section->size, int128_one())));
338 return;
339 }
340
341 if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
342 (section->offset_within_region & ~TARGET_PAGE_MASK))) {
343 error_report("%s received unaligned region", __func__);
344 return;
345 }
346
347 iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
348 llend = int128_make64(section->offset_within_address_space);
349 llend = int128_add(llend, section->size);
350 llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
351
352 if (int128_ge(int128_make64(iova), llend)) {
353 return;
354 }
55efcc53 355 end = int128_get64(int128_sub(llend, int128_one()));
3898aad3 356
55efcc53 357 if ((iova < container->min_iova) || (end > container->max_iova)) {
3898aad3
DG
358 error_report("vfio: IOMMU container %p can't map guest IOVA region"
359 " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx,
55efcc53 360 container, iova, end);
3898aad3
DG
361 ret = -EFAULT;
362 goto fail;
363 }
e2c7d025
EA
364
365 memory_region_ref(section->mr);
366
367 if (memory_region_is_iommu(section->mr)) {
368 VFIOGuestIOMMU *giommu;
369
55efcc53 370 trace_vfio_listener_region_add_iommu(iova, end);
e2c7d025
EA
371 /*
372 * FIXME: We should do some checking to see if the
373 * capabilities of the host VFIO IOMMU are adequate to model
374 * the guest IOMMU
375 *
376 * FIXME: For VFIO iommu types which have KVM acceleration to
377 * avoid bouncing all map/unmaps through qemu this way, this
378 * would be the right place to wire that up (tell the KVM
379 * device emulation the VFIO iommu handles to use).
380 */
e2c7d025
EA
381 giommu = g_malloc0(sizeof(*giommu));
382 giommu->iommu = section->mr;
383 giommu->container = container;
384 giommu->n.notify = vfio_iommu_map_notify;
385 QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
508ce5eb 386
e2c7d025 387 memory_region_register_iommu_notifier(giommu->iommu, &giommu->n);
508ce5eb
DG
388 memory_region_iommu_replay(giommu->iommu, &giommu->n,
389 vfio_container_granularity(container),
390 false);
e2c7d025
EA
391
392 return;
393 }
394
395 /* Here we assume that memory_region_is_ram(section->mr)==true */
396
e2c7d025
EA
397 vaddr = memory_region_get_ram_ptr(section->mr) +
398 section->offset_within_region +
399 (iova - section->offset_within_address_space);
400
55efcc53 401 trace_vfio_listener_region_add_ram(iova, end, vaddr);
e2c7d025 402
55efcc53
BD
403 llsize = int128_sub(llend, int128_make64(iova));
404
405 ret = vfio_dma_map(container, iova, int128_get64(llsize),
406 vaddr, section->readonly);
e2c7d025
EA
407 if (ret) {
408 error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
409 "0x%"HWADDR_PRIx", %p) = %d (%m)",
55efcc53 410 container, iova, int128_get64(llsize), vaddr, ret);
ac6dc389
DG
411 goto fail;
412 }
e2c7d025 413
ac6dc389
DG
414 return;
415
416fail:
417 /*
418 * On the initfn path, store the first error in the container so we
419 * can gracefully fail. Runtime, there's not much we can do other
420 * than throw a hardware error.
421 */
422 if (!container->initialized) {
423 if (!container->error) {
424 container->error = ret;
e2c7d025 425 }
ac6dc389
DG
426 } else {
427 hw_error("vfio: DMA mapping failed, unable to continue");
e2c7d025
EA
428 }
429}
430
431static void vfio_listener_region_del(MemoryListener *listener,
432 MemoryRegionSection *section)
433{
ee0bf0e5 434 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
e2c7d025
EA
435 hwaddr iova, end;
436 int ret;
437
438 if (vfio_listener_skipped_section(section)) {
439 trace_vfio_listener_region_del_skip(
440 section->offset_within_address_space,
441 section->offset_within_address_space +
442 int128_get64(int128_sub(section->size, int128_one())));
443 return;
444 }
445
446 if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
447 (section->offset_within_region & ~TARGET_PAGE_MASK))) {
448 error_report("%s received unaligned region", __func__);
449 return;
450 }
451
452 if (memory_region_is_iommu(section->mr)) {
453 VFIOGuestIOMMU *giommu;
454
455 QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
456 if (giommu->iommu == section->mr) {
457 memory_region_unregister_iommu_notifier(&giommu->n);
458 QLIST_REMOVE(giommu, giommu_next);
459 g_free(giommu);
460 break;
461 }
462 }
463
464 /*
465 * FIXME: We assume the one big unmap below is adequate to
466 * remove any individual page mappings in the IOMMU which
467 * might have been copied into VFIO. This works for a page table
468 * based IOMMU where a big unmap flattens a large range of IO-PTEs.
469 * That may not be true for all IOMMU types.
470 */
471 }
472
473 iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
474 end = (section->offset_within_address_space + int128_get64(section->size)) &
475 TARGET_PAGE_MASK;
476
477 if (iova >= end) {
478 return;
479 }
480
481 trace_vfio_listener_region_del(iova, end - 1);
482
483 ret = vfio_dma_unmap(container, iova, end - iova);
484 memory_region_unref(section->mr);
485 if (ret) {
486 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
487 "0x%"HWADDR_PRIx") = %d (%m)",
488 container, iova, end - iova, ret);
489 }
490}
491
51b833f4 492static const MemoryListener vfio_memory_listener = {
e2c7d025
EA
493 .region_add = vfio_listener_region_add,
494 .region_del = vfio_listener_region_del,
495};
496
51b833f4 497static void vfio_listener_release(VFIOContainer *container)
e2c7d025 498{
ee0bf0e5 499 memory_listener_unregister(&container->listener);
e2c7d025
EA
500}
501
b53b0f69
AW
502static struct vfio_info_cap_header *
503vfio_get_region_info_cap(struct vfio_region_info *info, uint16_t id)
504{
505 struct vfio_info_cap_header *hdr;
506 void *ptr = info;
507
508 if (!(info->flags & VFIO_REGION_INFO_FLAG_CAPS)) {
509 return NULL;
510 }
511
512 for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
513 if (hdr->id == id) {
514 return hdr;
515 }
516 }
517
518 return NULL;
519}
520
521static void vfio_setup_region_sparse_mmaps(VFIORegion *region,
522 struct vfio_region_info *info)
523{
524 struct vfio_info_cap_header *hdr;
525 struct vfio_region_info_cap_sparse_mmap *sparse;
526 int i;
527
528 hdr = vfio_get_region_info_cap(info, VFIO_REGION_INFO_CAP_SPARSE_MMAP);
529 if (!hdr) {
530 return;
531 }
532
533 sparse = container_of(hdr, struct vfio_region_info_cap_sparse_mmap, header);
534
535 trace_vfio_region_sparse_mmap_header(region->vbasedev->name,
536 region->nr, sparse->nr_areas);
537
538 region->nr_mmaps = sparse->nr_areas;
539 region->mmaps = g_new0(VFIOMmap, region->nr_mmaps);
540
541 for (i = 0; i < region->nr_mmaps; i++) {
542 region->mmaps[i].offset = sparse->areas[i].offset;
543 region->mmaps[i].size = sparse->areas[i].size;
544 trace_vfio_region_sparse_mmap_entry(i, region->mmaps[i].offset,
545 region->mmaps[i].offset +
546 region->mmaps[i].size);
547 }
548}
549
db0da029
AW
550int vfio_region_setup(Object *obj, VFIODevice *vbasedev, VFIORegion *region,
551 int index, const char *name)
e2c7d025 552{
db0da029
AW
553 struct vfio_region_info *info;
554 int ret;
555
556 ret = vfio_get_region_info(vbasedev, index, &info);
557 if (ret) {
558 return ret;
559 }
560
561 region->vbasedev = vbasedev;
562 region->flags = info->flags;
563 region->size = info->size;
564 region->fd_offset = info->offset;
565 region->nr = index;
566
567 if (region->size) {
568 region->mem = g_new0(MemoryRegion, 1);
569 memory_region_init_io(region->mem, obj, &vfio_region_ops,
570 region, name, region->size);
e2c7d025 571
db0da029
AW
572 if (!vbasedev->no_mmap &&
573 region->flags & VFIO_REGION_INFO_FLAG_MMAP &&
574 !(region->size & ~qemu_real_host_page_mask)) {
e2c7d025 575
b53b0f69 576 vfio_setup_region_sparse_mmaps(region, info);
db0da029 577
b53b0f69
AW
578 if (!region->nr_mmaps) {
579 region->nr_mmaps = 1;
580 region->mmaps = g_new0(VFIOMmap, region->nr_mmaps);
581 region->mmaps[0].offset = 0;
582 region->mmaps[0].size = region->size;
583 }
e2c7d025 584 }
db0da029
AW
585 }
586
587 g_free(info);
588
589 trace_vfio_region_setup(vbasedev->name, index, name,
590 region->flags, region->fd_offset, region->size);
591 return 0;
592}
e2c7d025 593
db0da029
AW
594int vfio_region_mmap(VFIORegion *region)
595{
596 int i, prot = 0;
597 char *name;
598
599 if (!region->mem) {
600 return 0;
601 }
602
603 prot |= region->flags & VFIO_REGION_INFO_FLAG_READ ? PROT_READ : 0;
604 prot |= region->flags & VFIO_REGION_INFO_FLAG_WRITE ? PROT_WRITE : 0;
605
606 for (i = 0; i < region->nr_mmaps; i++) {
607 region->mmaps[i].mmap = mmap(NULL, region->mmaps[i].size, prot,
608 MAP_SHARED, region->vbasedev->fd,
609 region->fd_offset +
610 region->mmaps[i].offset);
611 if (region->mmaps[i].mmap == MAP_FAILED) {
612 int ret = -errno;
613
614 trace_vfio_region_mmap_fault(memory_region_name(region->mem), i,
615 region->fd_offset +
616 region->mmaps[i].offset,
617 region->fd_offset +
618 region->mmaps[i].offset +
619 region->mmaps[i].size - 1, ret);
620
621 region->mmaps[i].mmap = NULL;
622
623 for (i--; i >= 0; i--) {
624 memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
625 munmap(region->mmaps[i].mmap, region->mmaps[i].size);
626 object_unparent(OBJECT(&region->mmaps[i].mem));
627 region->mmaps[i].mmap = NULL;
628 }
629
630 return ret;
e2c7d025
EA
631 }
632
db0da029
AW
633 name = g_strdup_printf("%s mmaps[%d]",
634 memory_region_name(region->mem), i);
635 memory_region_init_ram_ptr(&region->mmaps[i].mem,
636 memory_region_owner(region->mem),
637 name, region->mmaps[i].size,
638 region->mmaps[i].mmap);
639 g_free(name);
640 memory_region_set_skip_dump(&region->mmaps[i].mem);
641 memory_region_add_subregion(region->mem, region->mmaps[i].offset,
642 &region->mmaps[i].mem);
643
644 trace_vfio_region_mmap(memory_region_name(&region->mmaps[i].mem),
645 region->mmaps[i].offset,
646 region->mmaps[i].offset +
647 region->mmaps[i].size - 1);
648 }
649
650 return 0;
651}
652
653void vfio_region_exit(VFIORegion *region)
654{
655 int i;
656
657 if (!region->mem) {
658 return;
659 }
660
661 for (i = 0; i < region->nr_mmaps; i++) {
662 if (region->mmaps[i].mmap) {
663 memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
e2c7d025 664 }
db0da029 665 }
e2c7d025 666
db0da029
AW
667 trace_vfio_region_exit(region->vbasedev->name, region->nr);
668}
669
670void vfio_region_finalize(VFIORegion *region)
671{
672 int i;
673
674 if (!region->mem) {
675 return;
e2c7d025
EA
676 }
677
db0da029
AW
678 for (i = 0; i < region->nr_mmaps; i++) {
679 if (region->mmaps[i].mmap) {
680 munmap(region->mmaps[i].mmap, region->mmaps[i].size);
681 object_unparent(OBJECT(&region->mmaps[i].mem));
682 }
683 }
684
685 object_unparent(OBJECT(region->mem));
686
687 g_free(region->mem);
688 g_free(region->mmaps);
689
690 trace_vfio_region_finalize(region->vbasedev->name, region->nr);
691}
692
693void vfio_region_mmaps_set_enabled(VFIORegion *region, bool enabled)
694{
695 int i;
696
697 if (!region->mem) {
698 return;
699 }
700
701 for (i = 0; i < region->nr_mmaps; i++) {
702 if (region->mmaps[i].mmap) {
703 memory_region_set_enabled(&region->mmaps[i].mem, enabled);
704 }
705 }
e2c7d025 706
db0da029
AW
707 trace_vfio_region_mmaps_set_enabled(memory_region_name(region->mem),
708 enabled);
e2c7d025
EA
709}
710
711void vfio_reset_handler(void *opaque)
712{
713 VFIOGroup *group;
714 VFIODevice *vbasedev;
715
716 QLIST_FOREACH(group, &vfio_group_list, next) {
717 QLIST_FOREACH(vbasedev, &group->device_list, next) {
718 vbasedev->ops->vfio_compute_needs_reset(vbasedev);
719 }
720 }
721
722 QLIST_FOREACH(group, &vfio_group_list, next) {
723 QLIST_FOREACH(vbasedev, &group->device_list, next) {
724 if (vbasedev->needs_reset) {
725 vbasedev->ops->vfio_hot_reset_multi(vbasedev);
726 }
727 }
728 }
729}
730
731static void vfio_kvm_device_add_group(VFIOGroup *group)
732{
733#ifdef CONFIG_KVM
734 struct kvm_device_attr attr = {
735 .group = KVM_DEV_VFIO_GROUP,
736 .attr = KVM_DEV_VFIO_GROUP_ADD,
737 .addr = (uint64_t)(unsigned long)&group->fd,
738 };
739
740 if (!kvm_enabled()) {
741 return;
742 }
743
744 if (vfio_kvm_device_fd < 0) {
745 struct kvm_create_device cd = {
746 .type = KVM_DEV_TYPE_VFIO,
747 };
748
749 if (kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd)) {
78e5b17f 750 error_report("Failed to create KVM VFIO device: %m");
e2c7d025
EA
751 return;
752 }
753
754 vfio_kvm_device_fd = cd.fd;
755 }
756
757 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
758 error_report("Failed to add group %d to KVM VFIO device: %m",
759 group->groupid);
760 }
761#endif
762}
763
764static void vfio_kvm_device_del_group(VFIOGroup *group)
765{
766#ifdef CONFIG_KVM
767 struct kvm_device_attr attr = {
768 .group = KVM_DEV_VFIO_GROUP,
769 .attr = KVM_DEV_VFIO_GROUP_DEL,
770 .addr = (uint64_t)(unsigned long)&group->fd,
771 };
772
773 if (vfio_kvm_device_fd < 0) {
774 return;
775 }
776
777 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
778 error_report("Failed to remove group %d from KVM VFIO device: %m",
779 group->groupid);
780 }
781#endif
782}
783
784static VFIOAddressSpace *vfio_get_address_space(AddressSpace *as)
785{
786 VFIOAddressSpace *space;
787
788 QLIST_FOREACH(space, &vfio_address_spaces, list) {
789 if (space->as == as) {
790 return space;
791 }
792 }
793
794 /* No suitable VFIOAddressSpace, create a new one */
795 space = g_malloc0(sizeof(*space));
796 space->as = as;
797 QLIST_INIT(&space->containers);
798
799 QLIST_INSERT_HEAD(&vfio_address_spaces, space, list);
800
801 return space;
802}
803
804static void vfio_put_address_space(VFIOAddressSpace *space)
805{
806 if (QLIST_EMPTY(&space->containers)) {
807 QLIST_REMOVE(space, list);
808 g_free(space);
809 }
810}
811
812static int vfio_connect_container(VFIOGroup *group, AddressSpace *as)
813{
814 VFIOContainer *container;
815 int ret, fd;
816 VFIOAddressSpace *space;
817
818 space = vfio_get_address_space(as);
819
820 QLIST_FOREACH(container, &space->containers, next) {
821 if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
822 group->container = container;
823 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
824 return 0;
825 }
826 }
827
828 fd = qemu_open("/dev/vfio/vfio", O_RDWR);
829 if (fd < 0) {
830 error_report("vfio: failed to open /dev/vfio/vfio: %m");
831 ret = -errno;
832 goto put_space_exit;
833 }
834
835 ret = ioctl(fd, VFIO_GET_API_VERSION);
836 if (ret != VFIO_API_VERSION) {
837 error_report("vfio: supported vfio version: %d, "
838 "reported version: %d", VFIO_API_VERSION, ret);
839 ret = -EINVAL;
840 goto close_fd_exit;
841 }
842
843 container = g_malloc0(sizeof(*container));
844 container->space = space;
845 container->fd = fd;
2e6e697e
AW
846 if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU) ||
847 ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU)) {
848 bool v2 = !!ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU);
7a140a57 849 struct vfio_iommu_type1_info info;
2e6e697e 850
e2c7d025
EA
851 ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
852 if (ret) {
853 error_report("vfio: failed to set group container: %m");
854 ret = -errno;
855 goto free_container_exit;
856 }
857
2e6e697e
AW
858 ret = ioctl(fd, VFIO_SET_IOMMU,
859 v2 ? VFIO_TYPE1v2_IOMMU : VFIO_TYPE1_IOMMU);
e2c7d025
EA
860 if (ret) {
861 error_report("vfio: failed to set iommu for container: %m");
862 ret = -errno;
863 goto free_container_exit;
864 }
3898aad3
DG
865
866 /*
867 * FIXME: This assumes that a Type1 IOMMU can map any 64-bit
868 * IOVA whatsoever. That's not actually true, but the current
869 * kernel interface doesn't tell us what it can map, and the
870 * existing Type1 IOMMUs generally support any IOVA we're
871 * going to actually try in practice.
872 */
873 container->min_iova = 0;
874 container->max_iova = (hwaddr)-1;
7a140a57
DG
875
876 /* Assume just 4K IOVA page size */
877 container->iova_pgsizes = 0x1000;
878 info.argsz = sizeof(info);
879 ret = ioctl(fd, VFIO_IOMMU_GET_INFO, &info);
880 /* Ignore errors */
881 if ((ret == 0) && (info.flags & VFIO_IOMMU_INFO_PGSIZES)) {
882 container->iova_pgsizes = info.iova_pgsizes;
883 }
e2c7d025 884 } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_IOMMU)) {
3898aad3
DG
885 struct vfio_iommu_spapr_tce_info info;
886
e2c7d025
EA
887 ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
888 if (ret) {
889 error_report("vfio: failed to set group container: %m");
890 ret = -errno;
891 goto free_container_exit;
892 }
893 ret = ioctl(fd, VFIO_SET_IOMMU, VFIO_SPAPR_TCE_IOMMU);
894 if (ret) {
895 error_report("vfio: failed to set iommu for container: %m");
896 ret = -errno;
897 goto free_container_exit;
898 }
899
900 /*
901 * The host kernel code implementing VFIO_IOMMU_DISABLE is called
902 * when container fd is closed so we do not call it explicitly
903 * in this file.
904 */
905 ret = ioctl(fd, VFIO_IOMMU_ENABLE);
906 if (ret) {
907 error_report("vfio: failed to enable container: %m");
908 ret = -errno;
909 goto free_container_exit;
910 }
3898aad3
DG
911
912 /*
913 * This only considers the host IOMMU's 32-bit window. At
914 * some point we need to add support for the optional 64-bit
915 * window and dynamic windows
916 */
917 info.argsz = sizeof(info);
918 ret = ioctl(fd, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info);
919 if (ret) {
920 error_report("vfio: VFIO_IOMMU_SPAPR_TCE_GET_INFO failed: %m");
921 ret = -errno;
922 goto free_container_exit;
923 }
924 container->min_iova = info.dma32_window_start;
925 container->max_iova = container->min_iova + info.dma32_window_size - 1;
7a140a57
DG
926
927 /* Assume just 4K IOVA pages for now */
928 container->iova_pgsizes = 0x1000;
e2c7d025
EA
929 } else {
930 error_report("vfio: No available IOMMU models");
931 ret = -EINVAL;
932 goto free_container_exit;
933 }
934
ee0bf0e5
DG
935 container->listener = vfio_memory_listener;
936
937 memory_listener_register(&container->listener, container->space->as);
938
939 if (container->error) {
940 ret = container->error;
941 error_report("vfio: memory listener initialization failed for container");
942 goto listener_release_exit;
943 }
944
945 container->initialized = true;
946
e2c7d025
EA
947 QLIST_INIT(&container->group_list);
948 QLIST_INSERT_HEAD(&space->containers, container, next);
949
950 group->container = container;
951 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
952
953 return 0;
954listener_release_exit:
955 vfio_listener_release(container);
956
957free_container_exit:
958 g_free(container);
959
960close_fd_exit:
961 close(fd);
962
963put_space_exit:
964 vfio_put_address_space(space);
965
966 return ret;
967}
968
969static void vfio_disconnect_container(VFIOGroup *group)
970{
971 VFIOContainer *container = group->container;
972
973 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
974 error_report("vfio: error disconnecting group %d from container",
975 group->groupid);
976 }
977
978 QLIST_REMOVE(group, container_next);
979 group->container = NULL;
980
981 if (QLIST_EMPTY(&container->group_list)) {
982 VFIOAddressSpace *space = container->space;
f8d8a944 983 VFIOGuestIOMMU *giommu, *tmp;
e2c7d025 984
ee0bf0e5 985 vfio_listener_release(container);
e2c7d025 986 QLIST_REMOVE(container, next);
f8d8a944
AK
987
988 QLIST_FOREACH_SAFE(giommu, &container->giommu_list, giommu_next, tmp) {
989 memory_region_unregister_iommu_notifier(&giommu->n);
990 QLIST_REMOVE(giommu, giommu_next);
991 g_free(giommu);
992 }
993
e2c7d025
EA
994 trace_vfio_disconnect_container(container->fd);
995 close(container->fd);
996 g_free(container);
997
998 vfio_put_address_space(space);
999 }
1000}
1001
1002VFIOGroup *vfio_get_group(int groupid, AddressSpace *as)
1003{
1004 VFIOGroup *group;
1005 char path[32];
1006 struct vfio_group_status status = { .argsz = sizeof(status) };
1007
1008 QLIST_FOREACH(group, &vfio_group_list, next) {
1009 if (group->groupid == groupid) {
1010 /* Found it. Now is it already in the right context? */
1011 if (group->container->space->as == as) {
1012 return group;
1013 } else {
1014 error_report("vfio: group %d used in multiple address spaces",
1015 group->groupid);
1016 return NULL;
1017 }
1018 }
1019 }
1020
1021 group = g_malloc0(sizeof(*group));
1022
1023 snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
1024 group->fd = qemu_open(path, O_RDWR);
1025 if (group->fd < 0) {
1026 error_report("vfio: error opening %s: %m", path);
1027 goto free_group_exit;
1028 }
1029
1030 if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
1031 error_report("vfio: error getting group status: %m");
1032 goto close_fd_exit;
1033 }
1034
1035 if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
1036 error_report("vfio: error, group %d is not viable, please ensure "
1037 "all devices within the iommu_group are bound to their "
1038 "vfio bus driver.", groupid);
1039 goto close_fd_exit;
1040 }
1041
1042 group->groupid = groupid;
1043 QLIST_INIT(&group->device_list);
1044
1045 if (vfio_connect_container(group, as)) {
1046 error_report("vfio: failed to setup container for group %d", groupid);
1047 goto close_fd_exit;
1048 }
1049
1050 if (QLIST_EMPTY(&vfio_group_list)) {
1051 qemu_register_reset(vfio_reset_handler, NULL);
1052 }
1053
1054 QLIST_INSERT_HEAD(&vfio_group_list, group, next);
1055
1056 vfio_kvm_device_add_group(group);
1057
1058 return group;
1059
1060close_fd_exit:
1061 close(group->fd);
1062
1063free_group_exit:
1064 g_free(group);
1065
1066 return NULL;
1067}
1068
1069void vfio_put_group(VFIOGroup *group)
1070{
77a10d04 1071 if (!group || !QLIST_EMPTY(&group->device_list)) {
e2c7d025
EA
1072 return;
1073 }
1074
1075 vfio_kvm_device_del_group(group);
1076 vfio_disconnect_container(group);
1077 QLIST_REMOVE(group, next);
1078 trace_vfio_put_group(group->fd);
1079 close(group->fd);
1080 g_free(group);
1081
1082 if (QLIST_EMPTY(&vfio_group_list)) {
1083 qemu_unregister_reset(vfio_reset_handler, NULL);
1084 }
1085}
1086
1087int vfio_get_device(VFIOGroup *group, const char *name,
1088 VFIODevice *vbasedev)
1089{
1090 struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
217e9fdc 1091 int ret, fd;
e2c7d025 1092
217e9fdc
PB
1093 fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
1094 if (fd < 0) {
e2c7d025
EA
1095 error_report("vfio: error getting device %s from group %d: %m",
1096 name, group->groupid);
1097 error_printf("Verify all devices in group %d are bound to vfio-<bus> "
1098 "or pci-stub and not already in use\n", group->groupid);
217e9fdc 1099 return fd;
e2c7d025
EA
1100 }
1101
217e9fdc 1102 ret = ioctl(fd, VFIO_DEVICE_GET_INFO, &dev_info);
e2c7d025
EA
1103 if (ret) {
1104 error_report("vfio: error getting device info: %m");
217e9fdc
PB
1105 close(fd);
1106 return ret;
e2c7d025
EA
1107 }
1108
217e9fdc
PB
1109 vbasedev->fd = fd;
1110 vbasedev->group = group;
1111 QLIST_INSERT_HEAD(&group->device_list, vbasedev, next);
1112
e2c7d025
EA
1113 vbasedev->num_irqs = dev_info.num_irqs;
1114 vbasedev->num_regions = dev_info.num_regions;
1115 vbasedev->flags = dev_info.flags;
1116
1117 trace_vfio_get_device(name, dev_info.flags, dev_info.num_regions,
1118 dev_info.num_irqs);
1119
1120 vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
217e9fdc 1121 return 0;
e2c7d025
EA
1122}
1123
1124void vfio_put_base_device(VFIODevice *vbasedev)
1125{
77a10d04
PB
1126 if (!vbasedev->group) {
1127 return;
1128 }
e2c7d025
EA
1129 QLIST_REMOVE(vbasedev, next);
1130 vbasedev->group = NULL;
1131 trace_vfio_put_base_device(vbasedev->fd);
1132 close(vbasedev->fd);
1133}
1134
46900226
AW
1135int vfio_get_region_info(VFIODevice *vbasedev, int index,
1136 struct vfio_region_info **info)
1137{
1138 size_t argsz = sizeof(struct vfio_region_info);
1139
1140 *info = g_malloc0(argsz);
1141
1142 (*info)->index = index;
b53b0f69 1143retry:
46900226
AW
1144 (*info)->argsz = argsz;
1145
1146 if (ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, *info)) {
1147 g_free(*info);
1148 return -errno;
1149 }
1150
b53b0f69
AW
1151 if ((*info)->argsz > argsz) {
1152 argsz = (*info)->argsz;
1153 *info = g_realloc(*info, argsz);
1154
1155 goto retry;
1156 }
1157
46900226
AW
1158 return 0;
1159}
1160
3153119e
DG
1161/*
1162 * Interfaces for IBM EEH (Enhanced Error Handling)
1163 */
1164static bool vfio_eeh_container_ok(VFIOContainer *container)
1165{
1166 /*
1167 * As of 2016-03-04 (linux-4.5) the host kernel EEH/VFIO
1168 * implementation is broken if there are multiple groups in a
1169 * container. The hardware works in units of Partitionable
1170 * Endpoints (== IOMMU groups) and the EEH operations naively
1171 * iterate across all groups in the container, without any logic
1172 * to make sure the groups have their state synchronized. For
1173 * certain operations (ENABLE) that might be ok, until an error
1174 * occurs, but for others (GET_STATE) it's clearly broken.
1175 */
1176
1177 /*
1178 * XXX Once fixed kernels exist, test for them here
1179 */
1180
1181 if (QLIST_EMPTY(&container->group_list)) {
1182 return false;
1183 }
1184
1185 if (QLIST_NEXT(QLIST_FIRST(&container->group_list), container_next)) {
1186 return false;
1187 }
1188
1189 return true;
1190}
1191
1192static int vfio_eeh_container_op(VFIOContainer *container, uint32_t op)
1193{
1194 struct vfio_eeh_pe_op pe_op = {
1195 .argsz = sizeof(pe_op),
1196 .op = op,
1197 };
1198 int ret;
1199
1200 if (!vfio_eeh_container_ok(container)) {
1201 error_report("vfio/eeh: EEH_PE_OP 0x%x: "
1202 "kernel requires a container with exactly one group", op);
1203 return -EPERM;
1204 }
1205
1206 ret = ioctl(container->fd, VFIO_EEH_PE_OP, &pe_op);
1207 if (ret < 0) {
1208 error_report("vfio/eeh: EEH_PE_OP 0x%x failed: %m", op);
1209 return -errno;
1210 }
1211
1212 return 0;
1213}
1214
1215static VFIOContainer *vfio_eeh_as_container(AddressSpace *as)
1216{
1217 VFIOAddressSpace *space = vfio_get_address_space(as);
1218 VFIOContainer *container = NULL;
1219
1220 if (QLIST_EMPTY(&space->containers)) {
1221 /* No containers to act on */
1222 goto out;
1223 }
1224
1225 container = QLIST_FIRST(&space->containers);
1226
1227 if (QLIST_NEXT(container, next)) {
1228 /* We don't yet have logic to synchronize EEH state across
1229 * multiple containers */
1230 container = NULL;
1231 goto out;
1232 }
1233
1234out:
1235 vfio_put_address_space(space);
1236 return container;
1237}
1238
1239bool vfio_eeh_as_ok(AddressSpace *as)
1240{
1241 VFIOContainer *container = vfio_eeh_as_container(as);
1242
1243 return (container != NULL) && vfio_eeh_container_ok(container);
1244}
1245
1246int vfio_eeh_as_op(AddressSpace *as, uint32_t op)
1247{
1248 VFIOContainer *container = vfio_eeh_as_container(as);
1249
1250 if (!container) {
1251 return -ENODEV;
1252 }
1253 return vfio_eeh_container_op(container, op);
1254}