pci bridge dev: change msi property type
[qemu/ar7.git] / hw / vfio / common.c
blob7be638e0e37eca5218720c6efdf56ef2e78a5c0b
1 /*
2 * generic functions used by VFIO devices
4 * Copyright Red Hat, Inc. 2012
6 * Authors:
7 * Alex Williamson <alex.williamson@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
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)
21 #include "qemu/osdep.h"
22 #include <sys/ioctl.h>
23 #include <linux/vfio.h>
25 #include "hw/vfio/vfio-common.h"
26 #include "hw/vfio/vfio.h"
27 #include "exec/address-spaces.h"
28 #include "exec/memory.h"
29 #include "hw/hw.h"
30 #include "qemu/error-report.h"
31 #include "sysemu/kvm.h"
32 #ifdef CONFIG_KVM
33 #include "linux/kvm.h"
34 #endif
35 #include "trace.h"
37 struct vfio_group_head vfio_group_list =
38 QLIST_HEAD_INITIALIZER(vfio_group_list);
39 struct vfio_as_head vfio_address_spaces =
40 QLIST_HEAD_INITIALIZER(vfio_address_spaces);
42 #ifdef CONFIG_KVM
44 * We have a single VFIO pseudo device per KVM VM. Once created it lives
45 * for the life of the VM. Closing the file descriptor only drops our
46 * reference to it and the device's reference to kvm. Therefore once
47 * initialized, this file descriptor is only released on QEMU exit and
48 * we'll re-use it should another vfio device be attached before then.
50 static int vfio_kvm_device_fd = -1;
51 #endif
54 * Common VFIO interrupt disable
56 void vfio_disable_irqindex(VFIODevice *vbasedev, int index)
58 struct vfio_irq_set irq_set = {
59 .argsz = sizeof(irq_set),
60 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
61 .index = index,
62 .start = 0,
63 .count = 0,
66 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
69 void vfio_unmask_single_irqindex(VFIODevice *vbasedev, int index)
71 struct vfio_irq_set irq_set = {
72 .argsz = sizeof(irq_set),
73 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
74 .index = index,
75 .start = 0,
76 .count = 1,
79 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
82 void vfio_mask_single_irqindex(VFIODevice *vbasedev, int index)
84 struct vfio_irq_set irq_set = {
85 .argsz = sizeof(irq_set),
86 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK,
87 .index = index,
88 .start = 0,
89 .count = 1,
92 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
96 * IO Port/MMIO - Beware of the endians, VFIO is always little endian
98 void vfio_region_write(void *opaque, hwaddr addr,
99 uint64_t data, unsigned size)
101 VFIORegion *region = opaque;
102 VFIODevice *vbasedev = region->vbasedev;
103 union {
104 uint8_t byte;
105 uint16_t word;
106 uint32_t dword;
107 uint64_t qword;
108 } buf;
110 switch (size) {
111 case 1:
112 buf.byte = data;
113 break;
114 case 2:
115 buf.word = cpu_to_le16(data);
116 break;
117 case 4:
118 buf.dword = cpu_to_le32(data);
119 break;
120 default:
121 hw_error("vfio: unsupported write size, %d bytes", size);
122 break;
125 if (pwrite(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
126 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", 0x%"PRIx64
127 ",%d) failed: %m",
128 __func__, vbasedev->name, region->nr,
129 addr, data, size);
132 trace_vfio_region_write(vbasedev->name, region->nr, addr, data, size);
135 * A read or write to a BAR always signals an INTx EOI. This will
136 * do nothing if not pending (including not in INTx mode). We assume
137 * that a BAR access is in response to an interrupt and that BAR
138 * accesses will service the interrupt. Unfortunately, we don't know
139 * which access will service the interrupt, so we're potentially
140 * getting quite a few host interrupts per guest interrupt.
142 vbasedev->ops->vfio_eoi(vbasedev);
145 uint64_t vfio_region_read(void *opaque,
146 hwaddr addr, unsigned size)
148 VFIORegion *region = opaque;
149 VFIODevice *vbasedev = region->vbasedev;
150 union {
151 uint8_t byte;
152 uint16_t word;
153 uint32_t dword;
154 uint64_t qword;
155 } buf;
156 uint64_t data = 0;
158 if (pread(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
159 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", %d) failed: %m",
160 __func__, vbasedev->name, region->nr,
161 addr, size);
162 return (uint64_t)-1;
164 switch (size) {
165 case 1:
166 data = buf.byte;
167 break;
168 case 2:
169 data = le16_to_cpu(buf.word);
170 break;
171 case 4:
172 data = le32_to_cpu(buf.dword);
173 break;
174 default:
175 hw_error("vfio: unsupported read size, %d bytes", size);
176 break;
179 trace_vfio_region_read(vbasedev->name, region->nr, addr, size, data);
181 /* Same as write above */
182 vbasedev->ops->vfio_eoi(vbasedev);
184 return data;
187 const MemoryRegionOps vfio_region_ops = {
188 .read = vfio_region_read,
189 .write = vfio_region_write,
190 .endianness = DEVICE_LITTLE_ENDIAN,
194 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
196 static int vfio_dma_unmap(VFIOContainer *container,
197 hwaddr iova, ram_addr_t size)
199 struct vfio_iommu_type1_dma_unmap unmap = {
200 .argsz = sizeof(unmap),
201 .flags = 0,
202 .iova = iova,
203 .size = size,
206 if (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
207 error_report("VFIO_UNMAP_DMA: %d", -errno);
208 return -errno;
211 return 0;
214 static int vfio_dma_map(VFIOContainer *container, hwaddr iova,
215 ram_addr_t size, void *vaddr, bool readonly)
217 struct vfio_iommu_type1_dma_map map = {
218 .argsz = sizeof(map),
219 .flags = VFIO_DMA_MAP_FLAG_READ,
220 .vaddr = (__u64)(uintptr_t)vaddr,
221 .iova = iova,
222 .size = size,
225 if (!readonly) {
226 map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
230 * Try the mapping, if it fails with EBUSY, unmap the region and try
231 * again. This shouldn't be necessary, but we sometimes see it in
232 * the VGA ROM space.
234 if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
235 (errno == EBUSY && vfio_dma_unmap(container, iova, size) == 0 &&
236 ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
237 return 0;
240 error_report("VFIO_MAP_DMA: %d", -errno);
241 return -errno;
244 static bool vfio_listener_skipped_section(MemoryRegionSection *section)
246 return (!memory_region_is_ram(section->mr) &&
247 !memory_region_is_iommu(section->mr)) ||
249 * Sizing an enabled 64-bit BAR can cause spurious mappings to
250 * addresses in the upper part of the 64-bit address space. These
251 * are never accessed by the CPU and beyond the address width of
252 * some IOMMU hardware. TODO: VFIO should tell us the IOMMU width.
254 section->offset_within_address_space & (1ULL << 63);
257 static void vfio_iommu_map_notify(Notifier *n, void *data)
259 VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
260 VFIOContainer *container = giommu->container;
261 IOMMUTLBEntry *iotlb = data;
262 hwaddr iova = iotlb->iova + giommu->iommu_offset;
263 MemoryRegion *mr;
264 hwaddr xlat;
265 hwaddr len = iotlb->addr_mask + 1;
266 void *vaddr;
267 int ret;
269 trace_vfio_iommu_map_notify(iova, iova + iotlb->addr_mask);
271 if (iotlb->target_as != &address_space_memory) {
272 error_report("Wrong target AS \"%s\", only system memory is allowed",
273 iotlb->target_as->name ? iotlb->target_as->name : "none");
274 return;
278 * The IOMMU TLB entry we have just covers translation through
279 * this IOMMU to its immediate target. We need to translate
280 * it the rest of the way through to memory.
282 rcu_read_lock();
283 mr = address_space_translate(&address_space_memory,
284 iotlb->translated_addr,
285 &xlat, &len, iotlb->perm & IOMMU_WO);
286 if (!memory_region_is_ram(mr)) {
287 error_report("iommu map to non memory area %"HWADDR_PRIx"",
288 xlat);
289 goto out;
292 * Translation truncates length to the IOMMU page size,
293 * check that it did not truncate too much.
295 if (len & iotlb->addr_mask) {
296 error_report("iommu has granularity incompatible with target AS");
297 goto out;
300 if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {
301 vaddr = memory_region_get_ram_ptr(mr) + xlat;
302 ret = vfio_dma_map(container, iova,
303 iotlb->addr_mask + 1, vaddr,
304 !(iotlb->perm & IOMMU_WO) || mr->readonly);
305 if (ret) {
306 error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
307 "0x%"HWADDR_PRIx", %p) = %d (%m)",
308 container, iova,
309 iotlb->addr_mask + 1, vaddr, ret);
311 } else {
312 ret = vfio_dma_unmap(container, iova, iotlb->addr_mask + 1);
313 if (ret) {
314 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
315 "0x%"HWADDR_PRIx") = %d (%m)",
316 container, iova,
317 iotlb->addr_mask + 1, ret);
320 out:
321 rcu_read_unlock();
324 static void vfio_listener_region_add(MemoryListener *listener,
325 MemoryRegionSection *section)
327 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
328 hwaddr iova, end;
329 Int128 llend, llsize;
330 void *vaddr;
331 int ret;
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;
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;
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));
352 if (int128_ge(int128_make64(iova), llend)) {
353 return;
355 end = int128_get64(int128_sub(llend, int128_one()));
357 if ((iova < container->min_iova) || (end > container->max_iova)) {
358 error_report("vfio: IOMMU container %p can't map guest IOVA region"
359 " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx,
360 container, iova, end);
361 ret = -EFAULT;
362 goto fail;
365 memory_region_ref(section->mr);
367 if (memory_region_is_iommu(section->mr)) {
368 VFIOGuestIOMMU *giommu;
370 trace_vfio_listener_region_add_iommu(iova, end);
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
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).
381 giommu = g_malloc0(sizeof(*giommu));
382 giommu->iommu = section->mr;
383 giommu->iommu_offset = section->offset_within_address_space -
384 section->offset_within_region;
385 giommu->container = container;
386 giommu->n.notify = vfio_iommu_map_notify;
387 QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
389 memory_region_register_iommu_notifier(giommu->iommu, &giommu->n);
390 memory_region_iommu_replay(giommu->iommu, &giommu->n, false);
392 return;
395 /* Here we assume that memory_region_is_ram(section->mr)==true */
397 vaddr = memory_region_get_ram_ptr(section->mr) +
398 section->offset_within_region +
399 (iova - section->offset_within_address_space);
401 trace_vfio_listener_region_add_ram(iova, end, vaddr);
403 llsize = int128_sub(llend, int128_make64(iova));
405 ret = vfio_dma_map(container, iova, int128_get64(llsize),
406 vaddr, section->readonly);
407 if (ret) {
408 error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
409 "0x%"HWADDR_PRIx", %p) = %d (%m)",
410 container, iova, int128_get64(llsize), vaddr, ret);
411 goto fail;
414 return;
416 fail:
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.
422 if (!container->initialized) {
423 if (!container->error) {
424 container->error = ret;
426 } else {
427 hw_error("vfio: DMA mapping failed, unable to continue");
431 static void vfio_listener_region_del(MemoryListener *listener,
432 MemoryRegionSection *section)
434 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
435 hwaddr iova, end;
436 Int128 llend, llsize;
437 int ret;
439 if (vfio_listener_skipped_section(section)) {
440 trace_vfio_listener_region_del_skip(
441 section->offset_within_address_space,
442 section->offset_within_address_space +
443 int128_get64(int128_sub(section->size, int128_one())));
444 return;
447 if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
448 (section->offset_within_region & ~TARGET_PAGE_MASK))) {
449 error_report("%s received unaligned region", __func__);
450 return;
453 if (memory_region_is_iommu(section->mr)) {
454 VFIOGuestIOMMU *giommu;
456 QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
457 if (giommu->iommu == section->mr) {
458 memory_region_unregister_iommu_notifier(giommu->iommu,
459 &giommu->n);
460 QLIST_REMOVE(giommu, giommu_next);
461 g_free(giommu);
462 break;
467 * FIXME: We assume the one big unmap below is adequate to
468 * remove any individual page mappings in the IOMMU which
469 * might have been copied into VFIO. This works for a page table
470 * based IOMMU where a big unmap flattens a large range of IO-PTEs.
471 * That may not be true for all IOMMU types.
475 iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
476 llend = int128_make64(section->offset_within_address_space);
477 llend = int128_add(llend, section->size);
478 llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
480 if (int128_ge(int128_make64(iova), llend)) {
481 return;
483 end = int128_get64(int128_sub(llend, int128_one()));
485 llsize = int128_sub(llend, int128_make64(iova));
487 trace_vfio_listener_region_del(iova, end);
489 ret = vfio_dma_unmap(container, iova, int128_get64(llsize));
490 memory_region_unref(section->mr);
491 if (ret) {
492 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
493 "0x%"HWADDR_PRIx") = %d (%m)",
494 container, iova, int128_get64(llsize), ret);
498 static const MemoryListener vfio_memory_listener = {
499 .region_add = vfio_listener_region_add,
500 .region_del = vfio_listener_region_del,
503 static void vfio_listener_release(VFIOContainer *container)
505 memory_listener_unregister(&container->listener);
508 static struct vfio_info_cap_header *
509 vfio_get_region_info_cap(struct vfio_region_info *info, uint16_t id)
511 struct vfio_info_cap_header *hdr;
512 void *ptr = info;
514 if (!(info->flags & VFIO_REGION_INFO_FLAG_CAPS)) {
515 return NULL;
518 for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
519 if (hdr->id == id) {
520 return hdr;
524 return NULL;
527 static void vfio_setup_region_sparse_mmaps(VFIORegion *region,
528 struct vfio_region_info *info)
530 struct vfio_info_cap_header *hdr;
531 struct vfio_region_info_cap_sparse_mmap *sparse;
532 int i;
534 hdr = vfio_get_region_info_cap(info, VFIO_REGION_INFO_CAP_SPARSE_MMAP);
535 if (!hdr) {
536 return;
539 sparse = container_of(hdr, struct vfio_region_info_cap_sparse_mmap, header);
541 trace_vfio_region_sparse_mmap_header(region->vbasedev->name,
542 region->nr, sparse->nr_areas);
544 region->nr_mmaps = sparse->nr_areas;
545 region->mmaps = g_new0(VFIOMmap, region->nr_mmaps);
547 for (i = 0; i < region->nr_mmaps; i++) {
548 region->mmaps[i].offset = sparse->areas[i].offset;
549 region->mmaps[i].size = sparse->areas[i].size;
550 trace_vfio_region_sparse_mmap_entry(i, region->mmaps[i].offset,
551 region->mmaps[i].offset +
552 region->mmaps[i].size);
556 int vfio_region_setup(Object *obj, VFIODevice *vbasedev, VFIORegion *region,
557 int index, const char *name)
559 struct vfio_region_info *info;
560 int ret;
562 ret = vfio_get_region_info(vbasedev, index, &info);
563 if (ret) {
564 return ret;
567 region->vbasedev = vbasedev;
568 region->flags = info->flags;
569 region->size = info->size;
570 region->fd_offset = info->offset;
571 region->nr = index;
573 if (region->size) {
574 region->mem = g_new0(MemoryRegion, 1);
575 memory_region_init_io(region->mem, obj, &vfio_region_ops,
576 region, name, region->size);
578 if (!vbasedev->no_mmap &&
579 region->flags & VFIO_REGION_INFO_FLAG_MMAP &&
580 !(region->size & ~qemu_real_host_page_mask)) {
582 vfio_setup_region_sparse_mmaps(region, info);
584 if (!region->nr_mmaps) {
585 region->nr_mmaps = 1;
586 region->mmaps = g_new0(VFIOMmap, region->nr_mmaps);
587 region->mmaps[0].offset = 0;
588 region->mmaps[0].size = region->size;
593 g_free(info);
595 trace_vfio_region_setup(vbasedev->name, index, name,
596 region->flags, region->fd_offset, region->size);
597 return 0;
600 int vfio_region_mmap(VFIORegion *region)
602 int i, prot = 0;
603 char *name;
605 if (!region->mem) {
606 return 0;
609 prot |= region->flags & VFIO_REGION_INFO_FLAG_READ ? PROT_READ : 0;
610 prot |= region->flags & VFIO_REGION_INFO_FLAG_WRITE ? PROT_WRITE : 0;
612 for (i = 0; i < region->nr_mmaps; i++) {
613 region->mmaps[i].mmap = mmap(NULL, region->mmaps[i].size, prot,
614 MAP_SHARED, region->vbasedev->fd,
615 region->fd_offset +
616 region->mmaps[i].offset);
617 if (region->mmaps[i].mmap == MAP_FAILED) {
618 int ret = -errno;
620 trace_vfio_region_mmap_fault(memory_region_name(region->mem), i,
621 region->fd_offset +
622 region->mmaps[i].offset,
623 region->fd_offset +
624 region->mmaps[i].offset +
625 region->mmaps[i].size - 1, ret);
627 region->mmaps[i].mmap = NULL;
629 for (i--; i >= 0; i--) {
630 memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
631 munmap(region->mmaps[i].mmap, region->mmaps[i].size);
632 object_unparent(OBJECT(&region->mmaps[i].mem));
633 region->mmaps[i].mmap = NULL;
636 return ret;
639 name = g_strdup_printf("%s mmaps[%d]",
640 memory_region_name(region->mem), i);
641 memory_region_init_ram_ptr(&region->mmaps[i].mem,
642 memory_region_owner(region->mem),
643 name, region->mmaps[i].size,
644 region->mmaps[i].mmap);
645 g_free(name);
646 memory_region_set_skip_dump(&region->mmaps[i].mem);
647 memory_region_add_subregion(region->mem, region->mmaps[i].offset,
648 &region->mmaps[i].mem);
650 trace_vfio_region_mmap(memory_region_name(&region->mmaps[i].mem),
651 region->mmaps[i].offset,
652 region->mmaps[i].offset +
653 region->mmaps[i].size - 1);
656 return 0;
659 void vfio_region_exit(VFIORegion *region)
661 int i;
663 if (!region->mem) {
664 return;
667 for (i = 0; i < region->nr_mmaps; i++) {
668 if (region->mmaps[i].mmap) {
669 memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
673 trace_vfio_region_exit(region->vbasedev->name, region->nr);
676 void vfio_region_finalize(VFIORegion *region)
678 int i;
680 if (!region->mem) {
681 return;
684 for (i = 0; i < region->nr_mmaps; i++) {
685 if (region->mmaps[i].mmap) {
686 munmap(region->mmaps[i].mmap, region->mmaps[i].size);
687 object_unparent(OBJECT(&region->mmaps[i].mem));
691 object_unparent(OBJECT(region->mem));
693 g_free(region->mem);
694 g_free(region->mmaps);
696 trace_vfio_region_finalize(region->vbasedev->name, region->nr);
699 void vfio_region_mmaps_set_enabled(VFIORegion *region, bool enabled)
701 int i;
703 if (!region->mem) {
704 return;
707 for (i = 0; i < region->nr_mmaps; i++) {
708 if (region->mmaps[i].mmap) {
709 memory_region_set_enabled(&region->mmaps[i].mem, enabled);
713 trace_vfio_region_mmaps_set_enabled(memory_region_name(region->mem),
714 enabled);
717 void vfio_reset_handler(void *opaque)
719 VFIOGroup *group;
720 VFIODevice *vbasedev;
722 QLIST_FOREACH(group, &vfio_group_list, next) {
723 QLIST_FOREACH(vbasedev, &group->device_list, next) {
724 vbasedev->ops->vfio_compute_needs_reset(vbasedev);
728 QLIST_FOREACH(group, &vfio_group_list, next) {
729 QLIST_FOREACH(vbasedev, &group->device_list, next) {
730 if (vbasedev->needs_reset) {
731 vbasedev->ops->vfio_hot_reset_multi(vbasedev);
737 static void vfio_kvm_device_add_group(VFIOGroup *group)
739 #ifdef CONFIG_KVM
740 struct kvm_device_attr attr = {
741 .group = KVM_DEV_VFIO_GROUP,
742 .attr = KVM_DEV_VFIO_GROUP_ADD,
743 .addr = (uint64_t)(unsigned long)&group->fd,
746 if (!kvm_enabled()) {
747 return;
750 if (vfio_kvm_device_fd < 0) {
751 struct kvm_create_device cd = {
752 .type = KVM_DEV_TYPE_VFIO,
755 if (kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd)) {
756 error_report("Failed to create KVM VFIO device: %m");
757 return;
760 vfio_kvm_device_fd = cd.fd;
763 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
764 error_report("Failed to add group %d to KVM VFIO device: %m",
765 group->groupid);
767 #endif
770 static void vfio_kvm_device_del_group(VFIOGroup *group)
772 #ifdef CONFIG_KVM
773 struct kvm_device_attr attr = {
774 .group = KVM_DEV_VFIO_GROUP,
775 .attr = KVM_DEV_VFIO_GROUP_DEL,
776 .addr = (uint64_t)(unsigned long)&group->fd,
779 if (vfio_kvm_device_fd < 0) {
780 return;
783 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
784 error_report("Failed to remove group %d from KVM VFIO device: %m",
785 group->groupid);
787 #endif
790 static VFIOAddressSpace *vfio_get_address_space(AddressSpace *as)
792 VFIOAddressSpace *space;
794 QLIST_FOREACH(space, &vfio_address_spaces, list) {
795 if (space->as == as) {
796 return space;
800 /* No suitable VFIOAddressSpace, create a new one */
801 space = g_malloc0(sizeof(*space));
802 space->as = as;
803 QLIST_INIT(&space->containers);
805 QLIST_INSERT_HEAD(&vfio_address_spaces, space, list);
807 return space;
810 static void vfio_put_address_space(VFIOAddressSpace *space)
812 if (QLIST_EMPTY(&space->containers)) {
813 QLIST_REMOVE(space, list);
814 g_free(space);
818 static int vfio_connect_container(VFIOGroup *group, AddressSpace *as)
820 VFIOContainer *container;
821 int ret, fd;
822 VFIOAddressSpace *space;
824 space = vfio_get_address_space(as);
826 QLIST_FOREACH(container, &space->containers, next) {
827 if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
828 group->container = container;
829 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
830 return 0;
834 fd = qemu_open("/dev/vfio/vfio", O_RDWR);
835 if (fd < 0) {
836 error_report("vfio: failed to open /dev/vfio/vfio: %m");
837 ret = -errno;
838 goto put_space_exit;
841 ret = ioctl(fd, VFIO_GET_API_VERSION);
842 if (ret != VFIO_API_VERSION) {
843 error_report("vfio: supported vfio version: %d, "
844 "reported version: %d", VFIO_API_VERSION, ret);
845 ret = -EINVAL;
846 goto close_fd_exit;
849 container = g_malloc0(sizeof(*container));
850 container->space = space;
851 container->fd = fd;
852 if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU) ||
853 ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU)) {
854 bool v2 = !!ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU);
855 struct vfio_iommu_type1_info info;
857 ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
858 if (ret) {
859 error_report("vfio: failed to set group container: %m");
860 ret = -errno;
861 goto free_container_exit;
864 ret = ioctl(fd, VFIO_SET_IOMMU,
865 v2 ? VFIO_TYPE1v2_IOMMU : VFIO_TYPE1_IOMMU);
866 if (ret) {
867 error_report("vfio: failed to set iommu for container: %m");
868 ret = -errno;
869 goto free_container_exit;
873 * FIXME: This assumes that a Type1 IOMMU can map any 64-bit
874 * IOVA whatsoever. That's not actually true, but the current
875 * kernel interface doesn't tell us what it can map, and the
876 * existing Type1 IOMMUs generally support any IOVA we're
877 * going to actually try in practice.
879 container->min_iova = 0;
880 container->max_iova = (hwaddr)-1;
882 /* Assume just 4K IOVA page size */
883 container->iova_pgsizes = 0x1000;
884 info.argsz = sizeof(info);
885 ret = ioctl(fd, VFIO_IOMMU_GET_INFO, &info);
886 /* Ignore errors */
887 if ((ret == 0) && (info.flags & VFIO_IOMMU_INFO_PGSIZES)) {
888 container->iova_pgsizes = info.iova_pgsizes;
890 } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_IOMMU)) {
891 struct vfio_iommu_spapr_tce_info info;
893 ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
894 if (ret) {
895 error_report("vfio: failed to set group container: %m");
896 ret = -errno;
897 goto free_container_exit;
899 ret = ioctl(fd, VFIO_SET_IOMMU, VFIO_SPAPR_TCE_IOMMU);
900 if (ret) {
901 error_report("vfio: failed to set iommu for container: %m");
902 ret = -errno;
903 goto free_container_exit;
907 * The host kernel code implementing VFIO_IOMMU_DISABLE is called
908 * when container fd is closed so we do not call it explicitly
909 * in this file.
911 ret = ioctl(fd, VFIO_IOMMU_ENABLE);
912 if (ret) {
913 error_report("vfio: failed to enable container: %m");
914 ret = -errno;
915 goto free_container_exit;
919 * This only considers the host IOMMU's 32-bit window. At
920 * some point we need to add support for the optional 64-bit
921 * window and dynamic windows
923 info.argsz = sizeof(info);
924 ret = ioctl(fd, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info);
925 if (ret) {
926 error_report("vfio: VFIO_IOMMU_SPAPR_TCE_GET_INFO failed: %m");
927 ret = -errno;
928 goto free_container_exit;
930 container->min_iova = info.dma32_window_start;
931 container->max_iova = container->min_iova + info.dma32_window_size - 1;
933 /* Assume just 4K IOVA pages for now */
934 container->iova_pgsizes = 0x1000;
935 } else {
936 error_report("vfio: No available IOMMU models");
937 ret = -EINVAL;
938 goto free_container_exit;
941 container->listener = vfio_memory_listener;
943 memory_listener_register(&container->listener, container->space->as);
945 if (container->error) {
946 ret = container->error;
947 error_report("vfio: memory listener initialization failed for container");
948 goto listener_release_exit;
951 container->initialized = true;
953 QLIST_INIT(&container->group_list);
954 QLIST_INSERT_HEAD(&space->containers, container, next);
956 group->container = container;
957 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
959 return 0;
960 listener_release_exit:
961 vfio_listener_release(container);
963 free_container_exit:
964 g_free(container);
966 close_fd_exit:
967 close(fd);
969 put_space_exit:
970 vfio_put_address_space(space);
972 return ret;
975 static void vfio_disconnect_container(VFIOGroup *group)
977 VFIOContainer *container = group->container;
979 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
980 error_report("vfio: error disconnecting group %d from container",
981 group->groupid);
984 QLIST_REMOVE(group, container_next);
985 group->container = NULL;
987 if (QLIST_EMPTY(&container->group_list)) {
988 VFIOAddressSpace *space = container->space;
989 VFIOGuestIOMMU *giommu, *tmp;
991 vfio_listener_release(container);
992 QLIST_REMOVE(container, next);
994 QLIST_FOREACH_SAFE(giommu, &container->giommu_list, giommu_next, tmp) {
995 memory_region_unregister_iommu_notifier(giommu->iommu, &giommu->n);
996 QLIST_REMOVE(giommu, giommu_next);
997 g_free(giommu);
1000 trace_vfio_disconnect_container(container->fd);
1001 close(container->fd);
1002 g_free(container);
1004 vfio_put_address_space(space);
1008 VFIOGroup *vfio_get_group(int groupid, AddressSpace *as)
1010 VFIOGroup *group;
1011 char path[32];
1012 struct vfio_group_status status = { .argsz = sizeof(status) };
1014 QLIST_FOREACH(group, &vfio_group_list, next) {
1015 if (group->groupid == groupid) {
1016 /* Found it. Now is it already in the right context? */
1017 if (group->container->space->as == as) {
1018 return group;
1019 } else {
1020 error_report("vfio: group %d used in multiple address spaces",
1021 group->groupid);
1022 return NULL;
1027 group = g_malloc0(sizeof(*group));
1029 snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
1030 group->fd = qemu_open(path, O_RDWR);
1031 if (group->fd < 0) {
1032 error_report("vfio: error opening %s: %m", path);
1033 goto free_group_exit;
1036 if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
1037 error_report("vfio: error getting group status: %m");
1038 goto close_fd_exit;
1041 if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
1042 error_report("vfio: error, group %d is not viable, please ensure "
1043 "all devices within the iommu_group are bound to their "
1044 "vfio bus driver.", groupid);
1045 goto close_fd_exit;
1048 group->groupid = groupid;
1049 QLIST_INIT(&group->device_list);
1051 if (vfio_connect_container(group, as)) {
1052 error_report("vfio: failed to setup container for group %d", groupid);
1053 goto close_fd_exit;
1056 if (QLIST_EMPTY(&vfio_group_list)) {
1057 qemu_register_reset(vfio_reset_handler, NULL);
1060 QLIST_INSERT_HEAD(&vfio_group_list, group, next);
1062 vfio_kvm_device_add_group(group);
1064 return group;
1066 close_fd_exit:
1067 close(group->fd);
1069 free_group_exit:
1070 g_free(group);
1072 return NULL;
1075 void vfio_put_group(VFIOGroup *group)
1077 if (!group || !QLIST_EMPTY(&group->device_list)) {
1078 return;
1081 vfio_kvm_device_del_group(group);
1082 vfio_disconnect_container(group);
1083 QLIST_REMOVE(group, next);
1084 trace_vfio_put_group(group->fd);
1085 close(group->fd);
1086 g_free(group);
1088 if (QLIST_EMPTY(&vfio_group_list)) {
1089 qemu_unregister_reset(vfio_reset_handler, NULL);
1093 int vfio_get_device(VFIOGroup *group, const char *name,
1094 VFIODevice *vbasedev)
1096 struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
1097 int ret, fd;
1099 fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
1100 if (fd < 0) {
1101 error_report("vfio: error getting device %s from group %d: %m",
1102 name, group->groupid);
1103 error_printf("Verify all devices in group %d are bound to vfio-<bus> "
1104 "or pci-stub and not already in use\n", group->groupid);
1105 return fd;
1108 ret = ioctl(fd, VFIO_DEVICE_GET_INFO, &dev_info);
1109 if (ret) {
1110 error_report("vfio: error getting device info: %m");
1111 close(fd);
1112 return ret;
1115 vbasedev->fd = fd;
1116 vbasedev->group = group;
1117 QLIST_INSERT_HEAD(&group->device_list, vbasedev, next);
1119 vbasedev->num_irqs = dev_info.num_irqs;
1120 vbasedev->num_regions = dev_info.num_regions;
1121 vbasedev->flags = dev_info.flags;
1123 trace_vfio_get_device(name, dev_info.flags, dev_info.num_regions,
1124 dev_info.num_irqs);
1126 vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
1127 return 0;
1130 void vfio_put_base_device(VFIODevice *vbasedev)
1132 if (!vbasedev->group) {
1133 return;
1135 QLIST_REMOVE(vbasedev, next);
1136 vbasedev->group = NULL;
1137 trace_vfio_put_base_device(vbasedev->fd);
1138 close(vbasedev->fd);
1141 int vfio_get_region_info(VFIODevice *vbasedev, int index,
1142 struct vfio_region_info **info)
1144 size_t argsz = sizeof(struct vfio_region_info);
1146 *info = g_malloc0(argsz);
1148 (*info)->index = index;
1149 retry:
1150 (*info)->argsz = argsz;
1152 if (ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, *info)) {
1153 g_free(*info);
1154 *info = NULL;
1155 return -errno;
1158 if ((*info)->argsz > argsz) {
1159 argsz = (*info)->argsz;
1160 *info = g_realloc(*info, argsz);
1162 goto retry;
1165 return 0;
1168 int vfio_get_dev_region_info(VFIODevice *vbasedev, uint32_t type,
1169 uint32_t subtype, struct vfio_region_info **info)
1171 int i;
1173 for (i = 0; i < vbasedev->num_regions; i++) {
1174 struct vfio_info_cap_header *hdr;
1175 struct vfio_region_info_cap_type *cap_type;
1177 if (vfio_get_region_info(vbasedev, i, info)) {
1178 continue;
1181 hdr = vfio_get_region_info_cap(*info, VFIO_REGION_INFO_CAP_TYPE);
1182 if (!hdr) {
1183 g_free(*info);
1184 continue;
1187 cap_type = container_of(hdr, struct vfio_region_info_cap_type, header);
1189 trace_vfio_get_dev_region(vbasedev->name, i,
1190 cap_type->type, cap_type->subtype);
1192 if (cap_type->type == type && cap_type->subtype == subtype) {
1193 return 0;
1196 g_free(*info);
1199 *info = NULL;
1200 return -ENODEV;
1204 * Interfaces for IBM EEH (Enhanced Error Handling)
1206 static bool vfio_eeh_container_ok(VFIOContainer *container)
1209 * As of 2016-03-04 (linux-4.5) the host kernel EEH/VFIO
1210 * implementation is broken if there are multiple groups in a
1211 * container. The hardware works in units of Partitionable
1212 * Endpoints (== IOMMU groups) and the EEH operations naively
1213 * iterate across all groups in the container, without any logic
1214 * to make sure the groups have their state synchronized. For
1215 * certain operations (ENABLE) that might be ok, until an error
1216 * occurs, but for others (GET_STATE) it's clearly broken.
1220 * XXX Once fixed kernels exist, test for them here
1223 if (QLIST_EMPTY(&container->group_list)) {
1224 return false;
1227 if (QLIST_NEXT(QLIST_FIRST(&container->group_list), container_next)) {
1228 return false;
1231 return true;
1234 static int vfio_eeh_container_op(VFIOContainer *container, uint32_t op)
1236 struct vfio_eeh_pe_op pe_op = {
1237 .argsz = sizeof(pe_op),
1238 .op = op,
1240 int ret;
1242 if (!vfio_eeh_container_ok(container)) {
1243 error_report("vfio/eeh: EEH_PE_OP 0x%x: "
1244 "kernel requires a container with exactly one group", op);
1245 return -EPERM;
1248 ret = ioctl(container->fd, VFIO_EEH_PE_OP, &pe_op);
1249 if (ret < 0) {
1250 error_report("vfio/eeh: EEH_PE_OP 0x%x failed: %m", op);
1251 return -errno;
1254 return ret;
1257 static VFIOContainer *vfio_eeh_as_container(AddressSpace *as)
1259 VFIOAddressSpace *space = vfio_get_address_space(as);
1260 VFIOContainer *container = NULL;
1262 if (QLIST_EMPTY(&space->containers)) {
1263 /* No containers to act on */
1264 goto out;
1267 container = QLIST_FIRST(&space->containers);
1269 if (QLIST_NEXT(container, next)) {
1270 /* We don't yet have logic to synchronize EEH state across
1271 * multiple containers */
1272 container = NULL;
1273 goto out;
1276 out:
1277 vfio_put_address_space(space);
1278 return container;
1281 bool vfio_eeh_as_ok(AddressSpace *as)
1283 VFIOContainer *container = vfio_eeh_as_container(as);
1285 return (container != NULL) && vfio_eeh_container_ok(container);
1288 int vfio_eeh_as_op(AddressSpace *as, uint32_t op)
1290 VFIOContainer *container = vfio_eeh_as_container(as);
1292 if (!container) {
1293 return -ENODEV;
1295 return vfio_eeh_container_op(container, op);