]> git.proxmox.com Git - mirror_qemu.git/blame - hw/vfio/common.c
Merge remote-tracking branch 'remotes/thibault/tags/samuel-thibault' into staging
[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 22#include <sys/ioctl.h>
a9c94277
MA
23#ifdef CONFIG_KVM
24#include <linux/kvm.h>
25#endif
e2c7d025
EA
26#include <linux/vfio.h>
27
28#include "hw/vfio/vfio-common.h"
29#include "hw/vfio/vfio.h"
30#include "exec/address-spaces.h"
31#include "exec/memory.h"
32#include "hw/hw.h"
33#include "qemu/error-report.h"
db725815 34#include "qemu/main-loop.h"
f4ec5e26 35#include "qemu/range.h"
c65ee433 36#include "sysemu/balloon.h"
e2c7d025 37#include "sysemu/kvm.h"
71e8a915 38#include "sysemu/reset.h"
e2c7d025 39#include "trace.h"
01905f58 40#include "qapi/error.h"
e2c7d025 41
f481ee2d 42VFIOGroupList vfio_group_list =
39cb514f 43 QLIST_HEAD_INITIALIZER(vfio_group_list);
10ca76b4 44static QLIST_HEAD(, VFIOAddressSpace) vfio_address_spaces =
e2c7d025
EA
45 QLIST_HEAD_INITIALIZER(vfio_address_spaces);
46
47#ifdef CONFIG_KVM
48/*
49 * We have a single VFIO pseudo device per KVM VM. Once created it lives
50 * for the life of the VM. Closing the file descriptor only drops our
51 * reference to it and the device's reference to kvm. Therefore once
52 * initialized, this file descriptor is only released on QEMU exit and
53 * we'll re-use it should another vfio device be attached before then.
54 */
55static int vfio_kvm_device_fd = -1;
56#endif
57
58/*
59 * Common VFIO interrupt disable
60 */
61void vfio_disable_irqindex(VFIODevice *vbasedev, int index)
62{
63 struct vfio_irq_set irq_set = {
64 .argsz = sizeof(irq_set),
65 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
66 .index = index,
67 .start = 0,
68 .count = 0,
69 };
70
71 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
72}
73
74void vfio_unmask_single_irqindex(VFIODevice *vbasedev, int index)
75{
76 struct vfio_irq_set irq_set = {
77 .argsz = sizeof(irq_set),
78 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
79 .index = index,
80 .start = 0,
81 .count = 1,
82 };
83
84 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
85}
86
87void vfio_mask_single_irqindex(VFIODevice *vbasedev, int index)
88{
89 struct vfio_irq_set irq_set = {
90 .argsz = sizeof(irq_set),
91 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK,
92 .index = index,
93 .start = 0,
94 .count = 1,
95 };
96
97 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
98}
99
201a7331
EA
100static inline const char *action_to_str(int action)
101{
102 switch (action) {
103 case VFIO_IRQ_SET_ACTION_MASK:
104 return "MASK";
105 case VFIO_IRQ_SET_ACTION_UNMASK:
106 return "UNMASK";
107 case VFIO_IRQ_SET_ACTION_TRIGGER:
108 return "TRIGGER";
109 default:
110 return "UNKNOWN ACTION";
111 }
112}
113
114static const char *index_to_str(VFIODevice *vbasedev, int index)
115{
116 if (vbasedev->type != VFIO_DEVICE_TYPE_PCI) {
117 return NULL;
118 }
119
120 switch (index) {
121 case VFIO_PCI_INTX_IRQ_INDEX:
122 return "INTX";
123 case VFIO_PCI_MSI_IRQ_INDEX:
124 return "MSI";
125 case VFIO_PCI_MSIX_IRQ_INDEX:
126 return "MSIX";
127 case VFIO_PCI_ERR_IRQ_INDEX:
128 return "ERR";
129 case VFIO_PCI_REQ_IRQ_INDEX:
130 return "REQ";
131 default:
132 return NULL;
133 }
134}
135
136int vfio_set_irq_signaling(VFIODevice *vbasedev, int index, int subindex,
137 int action, int fd, Error **errp)
138{
139 struct vfio_irq_set *irq_set;
140 int argsz, ret = 0;
141 const char *name;
142 int32_t *pfd;
143
144 argsz = sizeof(*irq_set) + sizeof(*pfd);
145
146 irq_set = g_malloc0(argsz);
147 irq_set->argsz = argsz;
148 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | action;
149 irq_set->index = index;
150 irq_set->start = subindex;
151 irq_set->count = 1;
152 pfd = (int32_t *)&irq_set->data;
153 *pfd = fd;
154
155 if (ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, irq_set)) {
156 ret = -errno;
157 }
158 g_free(irq_set);
159
160 if (!ret) {
161 return 0;
162 }
163
164 error_setg_errno(errp, -ret, "VFIO_DEVICE_SET_IRQS failure");
165
166 name = index_to_str(vbasedev, index);
167 if (name) {
168 error_prepend(errp, "%s-%d: ", name, subindex);
169 } else {
170 error_prepend(errp, "index %d-%d: ", index, subindex);
171 }
172 error_prepend(errp,
173 "Failed to %s %s eventfd signaling for interrupt ",
174 fd < 0 ? "tear down" : "set up", action_to_str(action));
175 return ret;
176}
177
e2c7d025
EA
178/*
179 * IO Port/MMIO - Beware of the endians, VFIO is always little endian
180 */
181void vfio_region_write(void *opaque, hwaddr addr,
182 uint64_t data, unsigned size)
183{
184 VFIORegion *region = opaque;
185 VFIODevice *vbasedev = region->vbasedev;
186 union {
187 uint8_t byte;
188 uint16_t word;
189 uint32_t dword;
190 uint64_t qword;
191 } buf;
192
193 switch (size) {
194 case 1:
195 buf.byte = data;
196 break;
197 case 2:
198 buf.word = cpu_to_le16(data);
199 break;
200 case 4:
201 buf.dword = cpu_to_le32(data);
202 break;
38d49e8c
JRZ
203 case 8:
204 buf.qword = cpu_to_le64(data);
205 break;
e2c7d025
EA
206 default:
207 hw_error("vfio: unsupported write size, %d bytes", size);
208 break;
209 }
210
211 if (pwrite(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
212 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", 0x%"PRIx64
213 ",%d) failed: %m",
214 __func__, vbasedev->name, region->nr,
215 addr, data, size);
216 }
217
218 trace_vfio_region_write(vbasedev->name, region->nr, addr, data, size);
219
220 /*
221 * A read or write to a BAR always signals an INTx EOI. This will
222 * do nothing if not pending (including not in INTx mode). We assume
223 * that a BAR access is in response to an interrupt and that BAR
224 * accesses will service the interrupt. Unfortunately, we don't know
225 * which access will service the interrupt, so we're potentially
226 * getting quite a few host interrupts per guest interrupt.
227 */
228 vbasedev->ops->vfio_eoi(vbasedev);
229}
230
231uint64_t vfio_region_read(void *opaque,
232 hwaddr addr, unsigned size)
233{
234 VFIORegion *region = opaque;
235 VFIODevice *vbasedev = region->vbasedev;
236 union {
237 uint8_t byte;
238 uint16_t word;
239 uint32_t dword;
240 uint64_t qword;
241 } buf;
242 uint64_t data = 0;
243
244 if (pread(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
245 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", %d) failed: %m",
246 __func__, vbasedev->name, region->nr,
247 addr, size);
248 return (uint64_t)-1;
249 }
250 switch (size) {
251 case 1:
252 data = buf.byte;
253 break;
254 case 2:
255 data = le16_to_cpu(buf.word);
256 break;
257 case 4:
258 data = le32_to_cpu(buf.dword);
259 break;
38d49e8c
JRZ
260 case 8:
261 data = le64_to_cpu(buf.qword);
262 break;
e2c7d025
EA
263 default:
264 hw_error("vfio: unsupported read size, %d bytes", size);
265 break;
266 }
267
268 trace_vfio_region_read(vbasedev->name, region->nr, addr, size, data);
269
270 /* Same as write above */
271 vbasedev->ops->vfio_eoi(vbasedev);
272
273 return data;
274}
275
276const MemoryRegionOps vfio_region_ops = {
277 .read = vfio_region_read,
278 .write = vfio_region_write,
279 .endianness = DEVICE_LITTLE_ENDIAN,
15126cba
JRZ
280 .valid = {
281 .min_access_size = 1,
282 .max_access_size = 8,
283 },
38d49e8c
JRZ
284 .impl = {
285 .min_access_size = 1,
286 .max_access_size = 8,
287 },
e2c7d025
EA
288};
289
290/*
291 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
292 */
293static int vfio_dma_unmap(VFIOContainer *container,
294 hwaddr iova, ram_addr_t size)
295{
296 struct vfio_iommu_type1_dma_unmap unmap = {
297 .argsz = sizeof(unmap),
298 .flags = 0,
299 .iova = iova,
300 .size = size,
301 };
302
567d7d3e
AW
303 while (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
304 /*
305 * The type1 backend has an off-by-one bug in the kernel (71a7d3d78e3c
306 * v4.15) where an overflow in its wrap-around check prevents us from
307 * unmapping the last page of the address space. Test for the error
308 * condition and re-try the unmap excluding the last page. The
309 * expectation is that we've never mapped the last page anyway and this
310 * unmap request comes via vIOMMU support which also makes it unlikely
311 * that this page is used. This bug was introduced well after type1 v2
312 * support was introduced, so we shouldn't need to test for v1. A fix
313 * is queued for kernel v5.0 so this workaround can be removed once
314 * affected kernels are sufficiently deprecated.
315 */
316 if (errno == EINVAL && unmap.size && !(unmap.iova + unmap.size) &&
317 container->iommu_type == VFIO_TYPE1v2_IOMMU) {
318 trace_vfio_dma_unmap_overflow_workaround();
319 unmap.size -= 1ULL << ctz64(container->pgsizes);
320 continue;
321 }
78e5b17f 322 error_report("VFIO_UNMAP_DMA: %d", -errno);
e2c7d025
EA
323 return -errno;
324 }
325
326 return 0;
327}
328
329static int vfio_dma_map(VFIOContainer *container, hwaddr iova,
330 ram_addr_t size, void *vaddr, bool readonly)
331{
332 struct vfio_iommu_type1_dma_map map = {
333 .argsz = sizeof(map),
334 .flags = VFIO_DMA_MAP_FLAG_READ,
335 .vaddr = (__u64)(uintptr_t)vaddr,
336 .iova = iova,
337 .size = size,
338 };
339
340 if (!readonly) {
341 map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
342 }
343
344 /*
345 * Try the mapping, if it fails with EBUSY, unmap the region and try
346 * again. This shouldn't be necessary, but we sometimes see it in
b6af0975 347 * the VGA ROM space.
e2c7d025
EA
348 */
349 if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
350 (errno == EBUSY && vfio_dma_unmap(container, iova, size) == 0 &&
351 ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
352 return 0;
353 }
354
78e5b17f 355 error_report("VFIO_MAP_DMA: %d", -errno);
e2c7d025
EA
356 return -errno;
357}
358
f4ec5e26
AK
359static void vfio_host_win_add(VFIOContainer *container,
360 hwaddr min_iova, hwaddr max_iova,
361 uint64_t iova_pgsizes)
362{
363 VFIOHostDMAWindow *hostwin;
364
365 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
366 if (ranges_overlap(hostwin->min_iova,
367 hostwin->max_iova - hostwin->min_iova + 1,
368 min_iova,
369 max_iova - min_iova + 1)) {
370 hw_error("%s: Overlapped IOMMU are not enabled", __func__);
371 }
372 }
373
374 hostwin = g_malloc0(sizeof(*hostwin));
375
376 hostwin->min_iova = min_iova;
377 hostwin->max_iova = max_iova;
378 hostwin->iova_pgsizes = iova_pgsizes;
379 QLIST_INSERT_HEAD(&container->hostwin_list, hostwin, hostwin_next);
380}
381
2e4109de
AK
382static int vfio_host_win_del(VFIOContainer *container, hwaddr min_iova,
383 hwaddr max_iova)
384{
385 VFIOHostDMAWindow *hostwin;
386
387 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
388 if (hostwin->min_iova == min_iova && hostwin->max_iova == max_iova) {
389 QLIST_REMOVE(hostwin, hostwin_next);
390 return 0;
391 }
392 }
393
394 return -1;
395}
396
e2c7d025
EA
397static bool vfio_listener_skipped_section(MemoryRegionSection *section)
398{
399 return (!memory_region_is_ram(section->mr) &&
400 !memory_region_is_iommu(section->mr)) ||
401 /*
402 * Sizing an enabled 64-bit BAR can cause spurious mappings to
403 * addresses in the upper part of the 64-bit address space. These
404 * are never accessed by the CPU and beyond the address width of
405 * some IOMMU hardware. TODO: VFIO should tell us the IOMMU width.
406 */
407 section->offset_within_address_space & (1ULL << 63);
408}
409
4a4b88fb
PX
410/* Called with rcu_read_lock held. */
411static bool vfio_get_vaddr(IOMMUTLBEntry *iotlb, void **vaddr,
412 bool *read_only)
e2c7d025 413{
e2c7d025
EA
414 MemoryRegion *mr;
415 hwaddr xlat;
416 hwaddr len = iotlb->addr_mask + 1;
4a4b88fb 417 bool writable = iotlb->perm & IOMMU_WO;
f1f93650 418
e2c7d025
EA
419 /*
420 * The IOMMU TLB entry we have just covers translation through
421 * this IOMMU to its immediate target. We need to translate
422 * it the rest of the way through to memory.
423 */
424 mr = address_space_translate(&address_space_memory,
425 iotlb->translated_addr,
bc6b1cec
PM
426 &xlat, &len, writable,
427 MEMTXATTRS_UNSPECIFIED);
e2c7d025 428 if (!memory_region_is_ram(mr)) {
78e5b17f 429 error_report("iommu map to non memory area %"HWADDR_PRIx"",
e2c7d025 430 xlat);
4a4b88fb 431 return false;
e2c7d025 432 }
4a4b88fb 433
e2c7d025
EA
434 /*
435 * Translation truncates length to the IOMMU page size,
436 * check that it did not truncate too much.
437 */
438 if (len & iotlb->addr_mask) {
78e5b17f 439 error_report("iommu has granularity incompatible with target AS");
4a4b88fb
PX
440 return false;
441 }
442
443 *vaddr = memory_region_get_ram_ptr(mr) + xlat;
444 *read_only = !writable || mr->readonly;
445
446 return true;
447}
448
449static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
450{
451 VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
452 VFIOContainer *container = giommu->container;
453 hwaddr iova = iotlb->iova + giommu->iommu_offset;
454 bool read_only;
455 void *vaddr;
456 int ret;
457
458 trace_vfio_iommu_map_notify(iotlb->perm == IOMMU_NONE ? "UNMAP" : "MAP",
459 iova, iova + iotlb->addr_mask);
460
461 if (iotlb->target_as != &address_space_memory) {
462 error_report("Wrong target AS \"%s\", only system memory is allowed",
463 iotlb->target_as->name ? iotlb->target_as->name : "none");
464 return;
465 }
466
467 rcu_read_lock();
468
e2c7d025 469 if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {
dfbd90e5
PX
470 if (!vfio_get_vaddr(iotlb, &vaddr, &read_only)) {
471 goto out;
472 }
4a4b88fb
PX
473 /*
474 * vaddr is only valid until rcu_read_unlock(). But after
475 * vfio_dma_map has set up the mapping the pages will be
476 * pinned by the kernel. This makes sure that the RAM backend
477 * of vaddr will always be there, even if the memory object is
478 * destroyed and its backing memory munmap-ed.
479 */
d78c19b5 480 ret = vfio_dma_map(container, iova,
e2c7d025 481 iotlb->addr_mask + 1, vaddr,
4a4b88fb 482 read_only);
e2c7d025
EA
483 if (ret) {
484 error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
485 "0x%"HWADDR_PRIx", %p) = %d (%m)",
d78c19b5 486 container, iova,
e2c7d025
EA
487 iotlb->addr_mask + 1, vaddr, ret);
488 }
489 } else {
d78c19b5 490 ret = vfio_dma_unmap(container, iova, iotlb->addr_mask + 1);
e2c7d025
EA
491 if (ret) {
492 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
493 "0x%"HWADDR_PRIx") = %d (%m)",
d78c19b5 494 container, iova,
e2c7d025
EA
495 iotlb->addr_mask + 1, ret);
496 }
497 }
41063e1e
PB
498out:
499 rcu_read_unlock();
e2c7d025
EA
500}
501
502static void vfio_listener_region_add(MemoryListener *listener,
503 MemoryRegionSection *section)
504{
ee0bf0e5 505 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
e2c7d025 506 hwaddr iova, end;
55efcc53 507 Int128 llend, llsize;
e2c7d025
EA
508 void *vaddr;
509 int ret;
f4ec5e26
AK
510 VFIOHostDMAWindow *hostwin;
511 bool hostwin_found;
d7d87836 512 Error *err = NULL;
e2c7d025
EA
513
514 if (vfio_listener_skipped_section(section)) {
515 trace_vfio_listener_region_add_skip(
516 section->offset_within_address_space,
517 section->offset_within_address_space +
518 int128_get64(int128_sub(section->size, int128_one())));
519 return;
520 }
521
522 if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
523 (section->offset_within_region & ~TARGET_PAGE_MASK))) {
524 error_report("%s received unaligned region", __func__);
525 return;
526 }
527
528 iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
529 llend = int128_make64(section->offset_within_address_space);
530 llend = int128_add(llend, section->size);
531 llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
532
533 if (int128_ge(int128_make64(iova), llend)) {
534 return;
535 }
55efcc53 536 end = int128_get64(int128_sub(llend, int128_one()));
3898aad3 537
2e4109de 538 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
2e4109de
AK
539 hwaddr pgsize = 0;
540
541 /* For now intersections are not allowed, we may relax this later */
542 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
543 if (ranges_overlap(hostwin->min_iova,
544 hostwin->max_iova - hostwin->min_iova + 1,
545 section->offset_within_address_space,
546 int128_get64(section->size))) {
d7d87836
EA
547 error_setg(&err,
548 "region [0x%"PRIx64",0x%"PRIx64"] overlaps with existing"
549 "host DMA window [0x%"PRIx64",0x%"PRIx64"]",
550 section->offset_within_address_space,
551 section->offset_within_address_space +
552 int128_get64(section->size) - 1,
553 hostwin->min_iova, hostwin->max_iova);
2e4109de
AK
554 goto fail;
555 }
556 }
557
558 ret = vfio_spapr_create_window(container, section, &pgsize);
559 if (ret) {
d7d87836 560 error_setg_errno(&err, -ret, "Failed to create SPAPR window");
2e4109de
AK
561 goto fail;
562 }
563
564 vfio_host_win_add(container, section->offset_within_address_space,
565 section->offset_within_address_space +
566 int128_get64(section->size) - 1, pgsize);
07bc681a
AK
567#ifdef CONFIG_KVM
568 if (kvm_enabled()) {
569 VFIOGroup *group;
570 IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
571 struct kvm_vfio_spapr_tce param;
572 struct kvm_device_attr attr = {
573 .group = KVM_DEV_VFIO_GROUP,
574 .attr = KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE,
575 .addr = (uint64_t)(unsigned long)&param,
576 };
577
578 if (!memory_region_iommu_get_attr(iommu_mr, IOMMU_ATTR_SPAPR_TCE_FD,
579 &param.tablefd)) {
580 QLIST_FOREACH(group, &container->group_list, container_next) {
581 param.groupfd = group->fd;
582 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
583 error_report("vfio: failed to setup fd %d "
584 "for a group with fd %d: %s",
585 param.tablefd, param.groupfd,
586 strerror(errno));
587 return;
588 }
589 trace_vfio_spapr_group_attach(param.groupfd, param.tablefd);
590 }
591 }
592 }
593#endif
2e4109de
AK
594 }
595
f4ec5e26
AK
596 hostwin_found = false;
597 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
598 if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
599 hostwin_found = true;
600 break;
601 }
602 }
603
604 if (!hostwin_found) {
d7d87836
EA
605 error_setg(&err, "Container %p can't map guest IOVA region"
606 " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx, container, iova, end);
3898aad3
DG
607 goto fail;
608 }
e2c7d025
EA
609
610 memory_region_ref(section->mr);
611
612 if (memory_region_is_iommu(section->mr)) {
613 VFIOGuestIOMMU *giommu;
3df9d748 614 IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
cb1efcf4 615 int iommu_idx;
e2c7d025 616
55efcc53 617 trace_vfio_listener_region_add_iommu(iova, end);
e2c7d025 618 /*
e2c7d025
EA
619 * FIXME: For VFIO iommu types which have KVM acceleration to
620 * avoid bouncing all map/unmaps through qemu this way, this
621 * would be the right place to wire that up (tell the KVM
622 * device emulation the VFIO iommu handles to use).
623 */
e2c7d025 624 giommu = g_malloc0(sizeof(*giommu));
3df9d748 625 giommu->iommu = iommu_mr;
d78c19b5
AK
626 giommu->iommu_offset = section->offset_within_address_space -
627 section->offset_within_region;
e2c7d025 628 giommu->container = container;
698feb5e
PX
629 llend = int128_add(int128_make64(section->offset_within_region),
630 section->size);
631 llend = int128_sub(llend, int128_one());
cb1efcf4
PM
632 iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
633 MEMTXATTRS_UNSPECIFIED);
698feb5e
PX
634 iommu_notifier_init(&giommu->n, vfio_iommu_map_notify,
635 IOMMU_NOTIFIER_ALL,
636 section->offset_within_region,
cb1efcf4
PM
637 int128_get64(llend),
638 iommu_idx);
508ce5eb 639
549d4005
EA
640 ret = memory_region_register_iommu_notifier(section->mr, &giommu->n,
641 &err);
642 if (ret) {
643 g_free(giommu);
644 goto fail;
645 }
646 QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
ad523590 647 memory_region_iommu_replay(giommu->iommu, &giommu->n);
e2c7d025
EA
648
649 return;
650 }
651
652 /* Here we assume that memory_region_is_ram(section->mr)==true */
653
e2c7d025
EA
654 vaddr = memory_region_get_ram_ptr(section->mr) +
655 section->offset_within_region +
656 (iova - section->offset_within_address_space);
657
55efcc53 658 trace_vfio_listener_region_add_ram(iova, end, vaddr);
e2c7d025 659
55efcc53
BD
660 llsize = int128_sub(llend, int128_make64(iova));
661
567b5b30
AK
662 if (memory_region_is_ram_device(section->mr)) {
663 hwaddr pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
664
665 if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) {
5c086005
EA
666 trace_vfio_listener_region_add_no_dma_map(
667 memory_region_name(section->mr),
668 section->offset_within_address_space,
669 int128_getlo(section->size),
670 pgmask + 1);
567b5b30
AK
671 return;
672 }
673 }
674
55efcc53
BD
675 ret = vfio_dma_map(container, iova, int128_get64(llsize),
676 vaddr, section->readonly);
e2c7d025 677 if (ret) {
d7d87836
EA
678 error_setg(&err, "vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
679 "0x%"HWADDR_PRIx", %p) = %d (%m)",
680 container, iova, int128_get64(llsize), vaddr, ret);
567b5b30
AK
681 if (memory_region_is_ram_device(section->mr)) {
682 /* Allow unexpected mappings not to be fatal for RAM devices */
d7d87836 683 error_report_err(err);
567b5b30
AK
684 return;
685 }
ac6dc389
DG
686 goto fail;
687 }
e2c7d025 688
ac6dc389
DG
689 return;
690
691fail:
567b5b30
AK
692 if (memory_region_is_ram_device(section->mr)) {
693 error_report("failed to vfio_dma_map. pci p2p may not work");
694 return;
695 }
ac6dc389
DG
696 /*
697 * On the initfn path, store the first error in the container so we
698 * can gracefully fail. Runtime, there's not much we can do other
699 * than throw a hardware error.
700 */
701 if (!container->initialized) {
702 if (!container->error) {
d7d87836
EA
703 error_propagate_prepend(&container->error, err,
704 "Region %s: ",
705 memory_region_name(section->mr));
706 } else {
707 error_free(err);
e2c7d025 708 }
ac6dc389 709 } else {
d7d87836 710 error_report_err(err);
ac6dc389 711 hw_error("vfio: DMA mapping failed, unable to continue");
e2c7d025
EA
712 }
713}
714
715static void vfio_listener_region_del(MemoryListener *listener,
716 MemoryRegionSection *section)
717{
ee0bf0e5 718 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
e2c7d025 719 hwaddr iova, end;
7a057b4f 720 Int128 llend, llsize;
e2c7d025 721 int ret;
567b5b30 722 bool try_unmap = true;
e2c7d025
EA
723
724 if (vfio_listener_skipped_section(section)) {
725 trace_vfio_listener_region_del_skip(
726 section->offset_within_address_space,
727 section->offset_within_address_space +
728 int128_get64(int128_sub(section->size, int128_one())));
729 return;
730 }
731
732 if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
733 (section->offset_within_region & ~TARGET_PAGE_MASK))) {
734 error_report("%s received unaligned region", __func__);
735 return;
736 }
737
738 if (memory_region_is_iommu(section->mr)) {
739 VFIOGuestIOMMU *giommu;
740
741 QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
3df9d748 742 if (MEMORY_REGION(giommu->iommu) == section->mr &&
698feb5e 743 giommu->n.start == section->offset_within_region) {
3df9d748 744 memory_region_unregister_iommu_notifier(section->mr,
d22d8956 745 &giommu->n);
e2c7d025
EA
746 QLIST_REMOVE(giommu, giommu_next);
747 g_free(giommu);
748 break;
749 }
750 }
751
752 /*
753 * FIXME: We assume the one big unmap below is adequate to
754 * remove any individual page mappings in the IOMMU which
755 * might have been copied into VFIO. This works for a page table
756 * based IOMMU where a big unmap flattens a large range of IO-PTEs.
757 * That may not be true for all IOMMU types.
758 */
759 }
760
761 iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
7a057b4f
AK
762 llend = int128_make64(section->offset_within_address_space);
763 llend = int128_add(llend, section->size);
764 llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
e2c7d025 765
7a057b4f 766 if (int128_ge(int128_make64(iova), llend)) {
e2c7d025
EA
767 return;
768 }
7a057b4f
AK
769 end = int128_get64(int128_sub(llend, int128_one()));
770
771 llsize = int128_sub(llend, int128_make64(iova));
e2c7d025 772
7a057b4f 773 trace_vfio_listener_region_del(iova, end);
e2c7d025 774
567b5b30
AK
775 if (memory_region_is_ram_device(section->mr)) {
776 hwaddr pgmask;
777 VFIOHostDMAWindow *hostwin;
778 bool hostwin_found = false;
779
780 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
781 if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
782 hostwin_found = true;
783 break;
784 }
785 }
786 assert(hostwin_found); /* or region_add() would have failed */
787
788 pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
789 try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask));
e2c7d025 790 }
2e4109de 791
567b5b30
AK
792 if (try_unmap) {
793 ret = vfio_dma_unmap(container, iova, int128_get64(llsize));
794 if (ret) {
795 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
796 "0x%"HWADDR_PRIx") = %d (%m)",
797 container, iova, int128_get64(llsize), ret);
798 }
799 }
800
801 memory_region_unref(section->mr);
802
2e4109de
AK
803 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
804 vfio_spapr_remove_window(container,
805 section->offset_within_address_space);
806 if (vfio_host_win_del(container,
807 section->offset_within_address_space,
808 section->offset_within_address_space +
809 int128_get64(section->size) - 1) < 0) {
810 hw_error("%s: Cannot delete missing window at %"HWADDR_PRIx,
811 __func__, section->offset_within_address_space);
812 }
813 }
e2c7d025
EA
814}
815
51b833f4 816static const MemoryListener vfio_memory_listener = {
e2c7d025
EA
817 .region_add = vfio_listener_region_add,
818 .region_del = vfio_listener_region_del,
819};
820
51b833f4 821static void vfio_listener_release(VFIOContainer *container)
e2c7d025 822{
ee0bf0e5 823 memory_listener_unregister(&container->listener);
318f67ce
AK
824 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
825 memory_listener_unregister(&container->prereg_listener);
826 }
e2c7d025
EA
827}
828
013002f0 829struct vfio_info_cap_header *
b53b0f69
AW
830vfio_get_region_info_cap(struct vfio_region_info *info, uint16_t id)
831{
832 struct vfio_info_cap_header *hdr;
833 void *ptr = info;
834
835 if (!(info->flags & VFIO_REGION_INFO_FLAG_CAPS)) {
836 return NULL;
837 }
838
839 for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
840 if (hdr->id == id) {
841 return hdr;
842 }
843 }
844
845 return NULL;
846}
847
24acf72b
AW
848static int vfio_setup_region_sparse_mmaps(VFIORegion *region,
849 struct vfio_region_info *info)
b53b0f69
AW
850{
851 struct vfio_info_cap_header *hdr;
852 struct vfio_region_info_cap_sparse_mmap *sparse;
24acf72b 853 int i, j;
b53b0f69
AW
854
855 hdr = vfio_get_region_info_cap(info, VFIO_REGION_INFO_CAP_SPARSE_MMAP);
856 if (!hdr) {
24acf72b 857 return -ENODEV;
b53b0f69
AW
858 }
859
860 sparse = container_of(hdr, struct vfio_region_info_cap_sparse_mmap, header);
861
862 trace_vfio_region_sparse_mmap_header(region->vbasedev->name,
863 region->nr, sparse->nr_areas);
864
24acf72b
AW
865 region->mmaps = g_new0(VFIOMmap, sparse->nr_areas);
866
867 for (i = 0, j = 0; i < sparse->nr_areas; i++) {
868 trace_vfio_region_sparse_mmap_entry(i, sparse->areas[i].offset,
869 sparse->areas[i].offset +
870 sparse->areas[i].size);
b53b0f69 871
24acf72b
AW
872 if (sparse->areas[i].size) {
873 region->mmaps[j].offset = sparse->areas[i].offset;
874 region->mmaps[j].size = sparse->areas[i].size;
875 j++;
876 }
b53b0f69 877 }
24acf72b
AW
878
879 region->nr_mmaps = j;
880 region->mmaps = g_realloc(region->mmaps, j * sizeof(VFIOMmap));
881
882 return 0;
b53b0f69
AW
883}
884
db0da029
AW
885int vfio_region_setup(Object *obj, VFIODevice *vbasedev, VFIORegion *region,
886 int index, const char *name)
e2c7d025 887{
db0da029
AW
888 struct vfio_region_info *info;
889 int ret;
890
891 ret = vfio_get_region_info(vbasedev, index, &info);
892 if (ret) {
893 return ret;
894 }
895
896 region->vbasedev = vbasedev;
897 region->flags = info->flags;
898 region->size = info->size;
899 region->fd_offset = info->offset;
900 region->nr = index;
901
902 if (region->size) {
903 region->mem = g_new0(MemoryRegion, 1);
904 memory_region_init_io(region->mem, obj, &vfio_region_ops,
905 region, name, region->size);
e2c7d025 906
db0da029 907 if (!vbasedev->no_mmap &&
95251725 908 region->flags & VFIO_REGION_INFO_FLAG_MMAP) {
e2c7d025 909
24acf72b 910 ret = vfio_setup_region_sparse_mmaps(region, info);
db0da029 911
24acf72b 912 if (ret) {
b53b0f69
AW
913 region->nr_mmaps = 1;
914 region->mmaps = g_new0(VFIOMmap, region->nr_mmaps);
915 region->mmaps[0].offset = 0;
916 region->mmaps[0].size = region->size;
917 }
e2c7d025 918 }
db0da029
AW
919 }
920
921 g_free(info);
922
923 trace_vfio_region_setup(vbasedev->name, index, name,
924 region->flags, region->fd_offset, region->size);
925 return 0;
926}
e2c7d025 927
db0da029
AW
928int vfio_region_mmap(VFIORegion *region)
929{
930 int i, prot = 0;
931 char *name;
932
933 if (!region->mem) {
934 return 0;
935 }
936
937 prot |= region->flags & VFIO_REGION_INFO_FLAG_READ ? PROT_READ : 0;
938 prot |= region->flags & VFIO_REGION_INFO_FLAG_WRITE ? PROT_WRITE : 0;
939
940 for (i = 0; i < region->nr_mmaps; i++) {
941 region->mmaps[i].mmap = mmap(NULL, region->mmaps[i].size, prot,
942 MAP_SHARED, region->vbasedev->fd,
943 region->fd_offset +
944 region->mmaps[i].offset);
945 if (region->mmaps[i].mmap == MAP_FAILED) {
946 int ret = -errno;
947
948 trace_vfio_region_mmap_fault(memory_region_name(region->mem), i,
949 region->fd_offset +
950 region->mmaps[i].offset,
951 region->fd_offset +
952 region->mmaps[i].offset +
953 region->mmaps[i].size - 1, ret);
954
955 region->mmaps[i].mmap = NULL;
956
957 for (i--; i >= 0; i--) {
958 memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
959 munmap(region->mmaps[i].mmap, region->mmaps[i].size);
960 object_unparent(OBJECT(&region->mmaps[i].mem));
961 region->mmaps[i].mmap = NULL;
962 }
963
964 return ret;
e2c7d025
EA
965 }
966
db0da029
AW
967 name = g_strdup_printf("%s mmaps[%d]",
968 memory_region_name(region->mem), i);
21e00fa5
AW
969 memory_region_init_ram_device_ptr(&region->mmaps[i].mem,
970 memory_region_owner(region->mem),
971 name, region->mmaps[i].size,
972 region->mmaps[i].mmap);
db0da029 973 g_free(name);
db0da029
AW
974 memory_region_add_subregion(region->mem, region->mmaps[i].offset,
975 &region->mmaps[i].mem);
976
977 trace_vfio_region_mmap(memory_region_name(&region->mmaps[i].mem),
978 region->mmaps[i].offset,
979 region->mmaps[i].offset +
980 region->mmaps[i].size - 1);
981 }
982
983 return 0;
984}
985
986void vfio_region_exit(VFIORegion *region)
987{
988 int i;
989
990 if (!region->mem) {
991 return;
992 }
993
994 for (i = 0; i < region->nr_mmaps; i++) {
995 if (region->mmaps[i].mmap) {
996 memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
e2c7d025 997 }
db0da029 998 }
e2c7d025 999
db0da029
AW
1000 trace_vfio_region_exit(region->vbasedev->name, region->nr);
1001}
1002
1003void vfio_region_finalize(VFIORegion *region)
1004{
1005 int i;
1006
1007 if (!region->mem) {
1008 return;
e2c7d025
EA
1009 }
1010
db0da029
AW
1011 for (i = 0; i < region->nr_mmaps; i++) {
1012 if (region->mmaps[i].mmap) {
1013 munmap(region->mmaps[i].mmap, region->mmaps[i].size);
1014 object_unparent(OBJECT(&region->mmaps[i].mem));
1015 }
1016 }
1017
1018 object_unparent(OBJECT(region->mem));
1019
1020 g_free(region->mem);
1021 g_free(region->mmaps);
1022
1023 trace_vfio_region_finalize(region->vbasedev->name, region->nr);
92f86bff
GH
1024
1025 region->mem = NULL;
1026 region->mmaps = NULL;
1027 region->nr_mmaps = 0;
1028 region->size = 0;
1029 region->flags = 0;
1030 region->nr = 0;
db0da029
AW
1031}
1032
1033void vfio_region_mmaps_set_enabled(VFIORegion *region, bool enabled)
1034{
1035 int i;
1036
1037 if (!region->mem) {
1038 return;
1039 }
1040
1041 for (i = 0; i < region->nr_mmaps; i++) {
1042 if (region->mmaps[i].mmap) {
1043 memory_region_set_enabled(&region->mmaps[i].mem, enabled);
1044 }
1045 }
e2c7d025 1046
db0da029
AW
1047 trace_vfio_region_mmaps_set_enabled(memory_region_name(region->mem),
1048 enabled);
e2c7d025
EA
1049}
1050
1051void vfio_reset_handler(void *opaque)
1052{
1053 VFIOGroup *group;
1054 VFIODevice *vbasedev;
1055
1056 QLIST_FOREACH(group, &vfio_group_list, next) {
1057 QLIST_FOREACH(vbasedev, &group->device_list, next) {
7da624e2
AW
1058 if (vbasedev->dev->realized) {
1059 vbasedev->ops->vfio_compute_needs_reset(vbasedev);
1060 }
e2c7d025
EA
1061 }
1062 }
1063
1064 QLIST_FOREACH(group, &vfio_group_list, next) {
1065 QLIST_FOREACH(vbasedev, &group->device_list, next) {
7da624e2 1066 if (vbasedev->dev->realized && vbasedev->needs_reset) {
e2c7d025
EA
1067 vbasedev->ops->vfio_hot_reset_multi(vbasedev);
1068 }
1069 }
1070 }
1071}
1072
1073static void vfio_kvm_device_add_group(VFIOGroup *group)
1074{
1075#ifdef CONFIG_KVM
1076 struct kvm_device_attr attr = {
1077 .group = KVM_DEV_VFIO_GROUP,
1078 .attr = KVM_DEV_VFIO_GROUP_ADD,
1079 .addr = (uint64_t)(unsigned long)&group->fd,
1080 };
1081
1082 if (!kvm_enabled()) {
1083 return;
1084 }
1085
1086 if (vfio_kvm_device_fd < 0) {
1087 struct kvm_create_device cd = {
1088 .type = KVM_DEV_TYPE_VFIO,
1089 };
1090
1091 if (kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd)) {
78e5b17f 1092 error_report("Failed to create KVM VFIO device: %m");
e2c7d025
EA
1093 return;
1094 }
1095
1096 vfio_kvm_device_fd = cd.fd;
1097 }
1098
1099 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1100 error_report("Failed to add group %d to KVM VFIO device: %m",
1101 group->groupid);
1102 }
1103#endif
1104}
1105
1106static void vfio_kvm_device_del_group(VFIOGroup *group)
1107{
1108#ifdef CONFIG_KVM
1109 struct kvm_device_attr attr = {
1110 .group = KVM_DEV_VFIO_GROUP,
1111 .attr = KVM_DEV_VFIO_GROUP_DEL,
1112 .addr = (uint64_t)(unsigned long)&group->fd,
1113 };
1114
1115 if (vfio_kvm_device_fd < 0) {
1116 return;
1117 }
1118
1119 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1120 error_report("Failed to remove group %d from KVM VFIO device: %m",
1121 group->groupid);
1122 }
1123#endif
1124}
1125
1126static VFIOAddressSpace *vfio_get_address_space(AddressSpace *as)
1127{
1128 VFIOAddressSpace *space;
1129
1130 QLIST_FOREACH(space, &vfio_address_spaces, list) {
1131 if (space->as == as) {
1132 return space;
1133 }
1134 }
1135
1136 /* No suitable VFIOAddressSpace, create a new one */
1137 space = g_malloc0(sizeof(*space));
1138 space->as = as;
1139 QLIST_INIT(&space->containers);
1140
1141 QLIST_INSERT_HEAD(&vfio_address_spaces, space, list);
1142
1143 return space;
1144}
1145
1146static void vfio_put_address_space(VFIOAddressSpace *space)
1147{
1148 if (QLIST_EMPTY(&space->containers)) {
1149 QLIST_REMOVE(space, list);
1150 g_free(space);
1151 }
1152}
1153
2b6326c0
EA
1154/*
1155 * vfio_get_iommu_type - selects the richest iommu_type (v2 first)
1156 */
1157static int vfio_get_iommu_type(VFIOContainer *container,
1158 Error **errp)
1159{
1160 int iommu_types[] = { VFIO_TYPE1v2_IOMMU, VFIO_TYPE1_IOMMU,
1161 VFIO_SPAPR_TCE_v2_IOMMU, VFIO_SPAPR_TCE_IOMMU };
1162 int i;
1163
1164 for (i = 0; i < ARRAY_SIZE(iommu_types); i++) {
1165 if (ioctl(container->fd, VFIO_CHECK_EXTENSION, iommu_types[i])) {
1166 return iommu_types[i];
1167 }
1168 }
1169 error_setg(errp, "No available IOMMU models");
1170 return -EINVAL;
1171}
1172
1173static int vfio_init_container(VFIOContainer *container, int group_fd,
1174 Error **errp)
1175{
1176 int iommu_type, ret;
1177
1178 iommu_type = vfio_get_iommu_type(container, errp);
1179 if (iommu_type < 0) {
1180 return iommu_type;
1181 }
1182
1183 ret = ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container->fd);
1184 if (ret) {
1185 error_setg_errno(errp, errno, "Failed to set group container");
1186 return -errno;
1187 }
1188
1189 while (ioctl(container->fd, VFIO_SET_IOMMU, iommu_type)) {
1190 if (iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
1191 /*
1192 * On sPAPR, despite the IOMMU subdriver always advertises v1 and
1193 * v2, the running platform may not support v2 and there is no
1194 * way to guess it until an IOMMU group gets added to the container.
1195 * So in case it fails with v2, try v1 as a fallback.
1196 */
1197 iommu_type = VFIO_SPAPR_TCE_IOMMU;
1198 continue;
1199 }
1200 error_setg_errno(errp, errno, "Failed to set iommu for container");
1201 return -errno;
1202 }
1203
1204 container->iommu_type = iommu_type;
1205 return 0;
1206}
1207
01905f58
EA
1208static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
1209 Error **errp)
e2c7d025
EA
1210{
1211 VFIOContainer *container;
1212 int ret, fd;
1213 VFIOAddressSpace *space;
1214
1215 space = vfio_get_address_space(as);
1216
c65ee433
AW
1217 /*
1218 * VFIO is currently incompatible with memory ballooning insofar as the
1219 * madvise to purge (zap) the page from QEMU's address space does not
1220 * interact with the memory API and therefore leaves stale virtual to
1221 * physical mappings in the IOMMU if the page was previously pinned. We
1222 * therefore add a balloon inhibit for each group added to a container,
1223 * whether the container is used individually or shared. This provides
1224 * us with options to allow devices within a group to opt-in and allow
1225 * ballooning, so long as it is done consistently for a group (for instance
1226 * if the device is an mdev device where it is known that the host vendor
1227 * driver will never pin pages outside of the working set of the guest
1228 * driver, which would thus not be ballooning candidates).
1229 *
1230 * The first opportunity to induce pinning occurs here where we attempt to
1231 * attach the group to existing containers within the AddressSpace. If any
1232 * pages are already zapped from the virtual address space, such as from a
1233 * previous ballooning opt-in, new pinning will cause valid mappings to be
1234 * re-established. Likewise, when the overall MemoryListener for a new
1235 * container is registered, a replay of mappings within the AddressSpace
1236 * will occur, re-establishing any previously zapped pages as well.
1237 *
1238 * NB. Balloon inhibiting does not currently block operation of the
1239 * balloon driver or revoke previously pinned pages, it only prevents
1240 * calling madvise to modify the virtual mapping of ballooned pages.
1241 */
1242 qemu_balloon_inhibit(true);
1243
e2c7d025
EA
1244 QLIST_FOREACH(container, &space->containers, next) {
1245 if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
1246 group->container = container;
1247 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
2016986a 1248 vfio_kvm_device_add_group(group);
e2c7d025
EA
1249 return 0;
1250 }
1251 }
1252
1253 fd = qemu_open("/dev/vfio/vfio", O_RDWR);
1254 if (fd < 0) {
01905f58 1255 error_setg_errno(errp, errno, "failed to open /dev/vfio/vfio");
e2c7d025
EA
1256 ret = -errno;
1257 goto put_space_exit;
1258 }
1259
1260 ret = ioctl(fd, VFIO_GET_API_VERSION);
1261 if (ret != VFIO_API_VERSION) {
01905f58
EA
1262 error_setg(errp, "supported vfio version: %d, "
1263 "reported version: %d", VFIO_API_VERSION, ret);
e2c7d025
EA
1264 ret = -EINVAL;
1265 goto close_fd_exit;
1266 }
1267
1268 container = g_malloc0(sizeof(*container));
1269 container->space = space;
1270 container->fd = fd;
d7d87836 1271 container->error = NULL;
f7f9c7b2
LY
1272 QLIST_INIT(&container->giommu_list);
1273 QLIST_INIT(&container->hostwin_list);
2e6e697e 1274
2b6326c0
EA
1275 ret = vfio_init_container(container, group->fd, errp);
1276 if (ret) {
1277 goto free_container_exit;
1278 }
e2c7d025 1279
2b6326c0
EA
1280 switch (container->iommu_type) {
1281 case VFIO_TYPE1v2_IOMMU:
1282 case VFIO_TYPE1_IOMMU:
1283 {
1284 struct vfio_iommu_type1_info info;
3898aad3
DG
1285
1286 /*
1287 * FIXME: This assumes that a Type1 IOMMU can map any 64-bit
1288 * IOVA whatsoever. That's not actually true, but the current
1289 * kernel interface doesn't tell us what it can map, and the
1290 * existing Type1 IOMMUs generally support any IOVA we're
1291 * going to actually try in practice.
1292 */
7a140a57
DG
1293 info.argsz = sizeof(info);
1294 ret = ioctl(fd, VFIO_IOMMU_GET_INFO, &info);
1295 /* Ignore errors */
f4ec5e26
AK
1296 if (ret || !(info.flags & VFIO_IOMMU_INFO_PGSIZES)) {
1297 /* Assume 4k IOVA page size */
1298 info.iova_pgsizes = 4096;
7a140a57 1299 }
f4ec5e26 1300 vfio_host_win_add(container, 0, (hwaddr)-1, info.iova_pgsizes);
c26bc185 1301 container->pgsizes = info.iova_pgsizes;
2b6326c0
EA
1302 break;
1303 }
1304 case VFIO_SPAPR_TCE_v2_IOMMU:
1305 case VFIO_SPAPR_TCE_IOMMU:
1306 {
3898aad3 1307 struct vfio_iommu_spapr_tce_info info;
2b6326c0 1308 bool v2 = container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU;
e2c7d025
EA
1309
1310 /*
1311 * The host kernel code implementing VFIO_IOMMU_DISABLE is called
1312 * when container fd is closed so we do not call it explicitly
1313 * in this file.
1314 */
318f67ce
AK
1315 if (!v2) {
1316 ret = ioctl(fd, VFIO_IOMMU_ENABLE);
1317 if (ret) {
01905f58 1318 error_setg_errno(errp, errno, "failed to enable container");
318f67ce
AK
1319 ret = -errno;
1320 goto free_container_exit;
1321 }
1322 } else {
1323 container->prereg_listener = vfio_prereg_listener;
1324
1325 memory_listener_register(&container->prereg_listener,
1326 &address_space_memory);
1327 if (container->error) {
1328 memory_listener_unregister(&container->prereg_listener);
d7d87836
EA
1329 ret = -1;
1330 error_propagate_prepend(errp, container->error,
1331 "RAM memory listener initialization failed: ");
318f67ce
AK
1332 goto free_container_exit;
1333 }
e2c7d025 1334 }
3898aad3 1335
3898aad3
DG
1336 info.argsz = sizeof(info);
1337 ret = ioctl(fd, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info);
1338 if (ret) {
01905f58
EA
1339 error_setg_errno(errp, errno,
1340 "VFIO_IOMMU_SPAPR_TCE_GET_INFO failed");
3898aad3 1341 ret = -errno;
318f67ce
AK
1342 if (v2) {
1343 memory_listener_unregister(&container->prereg_listener);
1344 }
3898aad3
DG
1345 goto free_container_exit;
1346 }
7a140a57 1347
2e4109de 1348 if (v2) {
c26bc185 1349 container->pgsizes = info.ddw.pgsizes;
2e4109de
AK
1350 /*
1351 * There is a default window in just created container.
1352 * To make region_add/del simpler, we better remove this
1353 * window now and let those iommu_listener callbacks
1354 * create/remove them when needed.
1355 */
1356 ret = vfio_spapr_remove_window(container, info.dma32_window_start);
1357 if (ret) {
01905f58
EA
1358 error_setg_errno(errp, -ret,
1359 "failed to remove existing window");
2e4109de
AK
1360 goto free_container_exit;
1361 }
1362 } else {
1363 /* The default table uses 4K pages */
c26bc185 1364 container->pgsizes = 0x1000;
2e4109de
AK
1365 vfio_host_win_add(container, info.dma32_window_start,
1366 info.dma32_window_start +
1367 info.dma32_window_size - 1,
1368 0x1000);
1369 }
2b6326c0 1370 }
e2c7d025
EA
1371 }
1372
8c37faa4
AK
1373 vfio_kvm_device_add_group(group);
1374
1375 QLIST_INIT(&container->group_list);
1376 QLIST_INSERT_HEAD(&space->containers, container, next);
1377
1378 group->container = container;
1379 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
1380
ee0bf0e5
DG
1381 container->listener = vfio_memory_listener;
1382
1383 memory_listener_register(&container->listener, container->space->as);
1384
1385 if (container->error) {
d7d87836
EA
1386 ret = -1;
1387 error_propagate_prepend(errp, container->error,
1388 "memory listener initialization failed: ");
ee0bf0e5
DG
1389 goto listener_release_exit;
1390 }
1391
1392 container->initialized = true;
1393
e2c7d025
EA
1394 return 0;
1395listener_release_exit:
8c37faa4
AK
1396 QLIST_REMOVE(group, container_next);
1397 QLIST_REMOVE(container, next);
1398 vfio_kvm_device_del_group(group);
e2c7d025
EA
1399 vfio_listener_release(container);
1400
1401free_container_exit:
1402 g_free(container);
1403
1404close_fd_exit:
1405 close(fd);
1406
1407put_space_exit:
c65ee433 1408 qemu_balloon_inhibit(false);
e2c7d025
EA
1409 vfio_put_address_space(space);
1410
1411 return ret;
1412}
1413
1414static void vfio_disconnect_container(VFIOGroup *group)
1415{
1416 VFIOContainer *container = group->container;
1417
36968626
PX
1418 QLIST_REMOVE(group, container_next);
1419 group->container = NULL;
1420
1421 /*
1422 * Explicitly release the listener first before unset container,
1423 * since unset may destroy the backend container if it's the last
1424 * group.
1425 */
1426 if (QLIST_EMPTY(&container->group_list)) {
1427 vfio_listener_release(container);
1428 }
1429
e2c7d025
EA
1430 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
1431 error_report("vfio: error disconnecting group %d from container",
1432 group->groupid);
1433 }
1434
e2c7d025
EA
1435 if (QLIST_EMPTY(&container->group_list)) {
1436 VFIOAddressSpace *space = container->space;
f8d8a944 1437 VFIOGuestIOMMU *giommu, *tmp;
e2c7d025 1438
e2c7d025 1439 QLIST_REMOVE(container, next);
f8d8a944
AK
1440
1441 QLIST_FOREACH_SAFE(giommu, &container->giommu_list, giommu_next, tmp) {
3df9d748
AK
1442 memory_region_unregister_iommu_notifier(
1443 MEMORY_REGION(giommu->iommu), &giommu->n);
f8d8a944
AK
1444 QLIST_REMOVE(giommu, giommu_next);
1445 g_free(giommu);
1446 }
1447
e2c7d025
EA
1448 trace_vfio_disconnect_container(container->fd);
1449 close(container->fd);
1450 g_free(container);
1451
1452 vfio_put_address_space(space);
1453 }
1454}
1455
1b808d5b 1456VFIOGroup *vfio_get_group(int groupid, AddressSpace *as, Error **errp)
e2c7d025
EA
1457{
1458 VFIOGroup *group;
1459 char path[32];
1460 struct vfio_group_status status = { .argsz = sizeof(status) };
1461
1462 QLIST_FOREACH(group, &vfio_group_list, next) {
1463 if (group->groupid == groupid) {
1464 /* Found it. Now is it already in the right context? */
1465 if (group->container->space->as == as) {
1466 return group;
1467 } else {
1b808d5b
EA
1468 error_setg(errp, "group %d used in multiple address spaces",
1469 group->groupid);
e2c7d025
EA
1470 return NULL;
1471 }
1472 }
1473 }
1474
1475 group = g_malloc0(sizeof(*group));
1476
1477 snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
1478 group->fd = qemu_open(path, O_RDWR);
1479 if (group->fd < 0) {
1b808d5b 1480 error_setg_errno(errp, errno, "failed to open %s", path);
e2c7d025
EA
1481 goto free_group_exit;
1482 }
1483
1484 if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
1b808d5b 1485 error_setg_errno(errp, errno, "failed to get group %d status", groupid);
e2c7d025
EA
1486 goto close_fd_exit;
1487 }
1488
1489 if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
1b808d5b
EA
1490 error_setg(errp, "group %d is not viable", groupid);
1491 error_append_hint(errp,
1492 "Please ensure all devices within the iommu_group "
1493 "are bound to their vfio bus driver.\n");
e2c7d025
EA
1494 goto close_fd_exit;
1495 }
1496
1497 group->groupid = groupid;
1498 QLIST_INIT(&group->device_list);
1499
1b808d5b
EA
1500 if (vfio_connect_container(group, as, errp)) {
1501 error_prepend(errp, "failed to setup container for group %d: ",
1502 groupid);
e2c7d025
EA
1503 goto close_fd_exit;
1504 }
1505
1506 if (QLIST_EMPTY(&vfio_group_list)) {
1507 qemu_register_reset(vfio_reset_handler, NULL);
1508 }
1509
1510 QLIST_INSERT_HEAD(&vfio_group_list, group, next);
1511
e2c7d025
EA
1512 return group;
1513
1514close_fd_exit:
1515 close(group->fd);
1516
1517free_group_exit:
1518 g_free(group);
1519
1520 return NULL;
1521}
1522
1523void vfio_put_group(VFIOGroup *group)
1524{
77a10d04 1525 if (!group || !QLIST_EMPTY(&group->device_list)) {
e2c7d025
EA
1526 return;
1527 }
1528
238e9172
AW
1529 if (!group->balloon_allowed) {
1530 qemu_balloon_inhibit(false);
1531 }
e2c7d025
EA
1532 vfio_kvm_device_del_group(group);
1533 vfio_disconnect_container(group);
1534 QLIST_REMOVE(group, next);
1535 trace_vfio_put_group(group->fd);
1536 close(group->fd);
1537 g_free(group);
1538
1539 if (QLIST_EMPTY(&vfio_group_list)) {
1540 qemu_unregister_reset(vfio_reset_handler, NULL);
1541 }
1542}
1543
1544int vfio_get_device(VFIOGroup *group, const char *name,
59f7d674 1545 VFIODevice *vbasedev, Error **errp)
e2c7d025
EA
1546{
1547 struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
217e9fdc 1548 int ret, fd;
e2c7d025 1549
217e9fdc
PB
1550 fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
1551 if (fd < 0) {
59f7d674
EA
1552 error_setg_errno(errp, errno, "error getting device from group %d",
1553 group->groupid);
1554 error_append_hint(errp,
1555 "Verify all devices in group %d are bound to vfio-<bus> "
1556 "or pci-stub and not already in use\n", group->groupid);
217e9fdc 1557 return fd;
e2c7d025
EA
1558 }
1559
217e9fdc 1560 ret = ioctl(fd, VFIO_DEVICE_GET_INFO, &dev_info);
e2c7d025 1561 if (ret) {
59f7d674 1562 error_setg_errno(errp, errno, "error getting device info");
217e9fdc
PB
1563 close(fd);
1564 return ret;
e2c7d025
EA
1565 }
1566
238e9172
AW
1567 /*
1568 * Clear the balloon inhibitor for this group if the driver knows the
1569 * device operates compatibly with ballooning. Setting must be consistent
1570 * per group, but since compatibility is really only possible with mdev
1571 * currently, we expect singleton groups.
1572 */
1573 if (vbasedev->balloon_allowed != group->balloon_allowed) {
1574 if (!QLIST_EMPTY(&group->device_list)) {
1575 error_setg(errp,
1576 "Inconsistent device balloon setting within group");
8709b395 1577 close(fd);
238e9172
AW
1578 return -1;
1579 }
1580
1581 if (!group->balloon_allowed) {
1582 group->balloon_allowed = true;
1583 qemu_balloon_inhibit(false);
1584 }
1585 }
1586
217e9fdc
PB
1587 vbasedev->fd = fd;
1588 vbasedev->group = group;
1589 QLIST_INSERT_HEAD(&group->device_list, vbasedev, next);
1590
e2c7d025
EA
1591 vbasedev->num_irqs = dev_info.num_irqs;
1592 vbasedev->num_regions = dev_info.num_regions;
1593 vbasedev->flags = dev_info.flags;
1594
1595 trace_vfio_get_device(name, dev_info.flags, dev_info.num_regions,
1596 dev_info.num_irqs);
1597
1598 vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
217e9fdc 1599 return 0;
e2c7d025
EA
1600}
1601
1602void vfio_put_base_device(VFIODevice *vbasedev)
1603{
77a10d04
PB
1604 if (!vbasedev->group) {
1605 return;
1606 }
e2c7d025
EA
1607 QLIST_REMOVE(vbasedev, next);
1608 vbasedev->group = NULL;
1609 trace_vfio_put_base_device(vbasedev->fd);
1610 close(vbasedev->fd);
1611}
1612
46900226
AW
1613int vfio_get_region_info(VFIODevice *vbasedev, int index,
1614 struct vfio_region_info **info)
1615{
1616 size_t argsz = sizeof(struct vfio_region_info);
1617
1618 *info = g_malloc0(argsz);
1619
1620 (*info)->index = index;
b53b0f69 1621retry:
46900226
AW
1622 (*info)->argsz = argsz;
1623
1624 if (ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, *info)) {
1625 g_free(*info);
e61a424f 1626 *info = NULL;
46900226
AW
1627 return -errno;
1628 }
1629
b53b0f69
AW
1630 if ((*info)->argsz > argsz) {
1631 argsz = (*info)->argsz;
1632 *info = g_realloc(*info, argsz);
1633
1634 goto retry;
1635 }
1636
46900226
AW
1637 return 0;
1638}
1639
e61a424f
AW
1640int vfio_get_dev_region_info(VFIODevice *vbasedev, uint32_t type,
1641 uint32_t subtype, struct vfio_region_info **info)
1642{
1643 int i;
1644
1645 for (i = 0; i < vbasedev->num_regions; i++) {
1646 struct vfio_info_cap_header *hdr;
1647 struct vfio_region_info_cap_type *cap_type;
1648
1649 if (vfio_get_region_info(vbasedev, i, info)) {
1650 continue;
1651 }
1652
1653 hdr = vfio_get_region_info_cap(*info, VFIO_REGION_INFO_CAP_TYPE);
1654 if (!hdr) {
1655 g_free(*info);
1656 continue;
1657 }
1658
1659 cap_type = container_of(hdr, struct vfio_region_info_cap_type, header);
1660
1661 trace_vfio_get_dev_region(vbasedev->name, i,
1662 cap_type->type, cap_type->subtype);
1663
1664 if (cap_type->type == type && cap_type->subtype == subtype) {
1665 return 0;
1666 }
1667
1668 g_free(*info);
1669 }
1670
1671 *info = NULL;
1672 return -ENODEV;
1673}
1674
ae0215b2
AK
1675bool vfio_has_region_cap(VFIODevice *vbasedev, int region, uint16_t cap_type)
1676{
1677 struct vfio_region_info *info = NULL;
1678 bool ret = false;
1679
1680 if (!vfio_get_region_info(vbasedev, region, &info)) {
1681 if (vfio_get_region_info_cap(info, cap_type)) {
1682 ret = true;
1683 }
1684 g_free(info);
1685 }
1686
1687 return ret;
1688}
1689
3153119e
DG
1690/*
1691 * Interfaces for IBM EEH (Enhanced Error Handling)
1692 */
1693static bool vfio_eeh_container_ok(VFIOContainer *container)
1694{
1695 /*
1696 * As of 2016-03-04 (linux-4.5) the host kernel EEH/VFIO
1697 * implementation is broken if there are multiple groups in a
1698 * container. The hardware works in units of Partitionable
1699 * Endpoints (== IOMMU groups) and the EEH operations naively
1700 * iterate across all groups in the container, without any logic
1701 * to make sure the groups have their state synchronized. For
1702 * certain operations (ENABLE) that might be ok, until an error
1703 * occurs, but for others (GET_STATE) it's clearly broken.
1704 */
1705
1706 /*
1707 * XXX Once fixed kernels exist, test for them here
1708 */
1709
1710 if (QLIST_EMPTY(&container->group_list)) {
1711 return false;
1712 }
1713
1714 if (QLIST_NEXT(QLIST_FIRST(&container->group_list), container_next)) {
1715 return false;
1716 }
1717
1718 return true;
1719}
1720
1721static int vfio_eeh_container_op(VFIOContainer *container, uint32_t op)
1722{
1723 struct vfio_eeh_pe_op pe_op = {
1724 .argsz = sizeof(pe_op),
1725 .op = op,
1726 };
1727 int ret;
1728
1729 if (!vfio_eeh_container_ok(container)) {
1730 error_report("vfio/eeh: EEH_PE_OP 0x%x: "
1731 "kernel requires a container with exactly one group", op);
1732 return -EPERM;
1733 }
1734
1735 ret = ioctl(container->fd, VFIO_EEH_PE_OP, &pe_op);
1736 if (ret < 0) {
1737 error_report("vfio/eeh: EEH_PE_OP 0x%x failed: %m", op);
1738 return -errno;
1739 }
1740
d917e88d 1741 return ret;
3153119e
DG
1742}
1743
1744static VFIOContainer *vfio_eeh_as_container(AddressSpace *as)
1745{
1746 VFIOAddressSpace *space = vfio_get_address_space(as);
1747 VFIOContainer *container = NULL;
1748
1749 if (QLIST_EMPTY(&space->containers)) {
1750 /* No containers to act on */
1751 goto out;
1752 }
1753
1754 container = QLIST_FIRST(&space->containers);
1755
1756 if (QLIST_NEXT(container, next)) {
1757 /* We don't yet have logic to synchronize EEH state across
1758 * multiple containers */
1759 container = NULL;
1760 goto out;
1761 }
1762
1763out:
1764 vfio_put_address_space(space);
1765 return container;
1766}
1767
1768bool vfio_eeh_as_ok(AddressSpace *as)
1769{
1770 VFIOContainer *container = vfio_eeh_as_container(as);
1771
1772 return (container != NULL) && vfio_eeh_container_ok(container);
1773}
1774
1775int vfio_eeh_as_op(AddressSpace *as, uint32_t op)
1776{
1777 VFIOContainer *container = vfio_eeh_as_container(as);
1778
1779 if (!container) {
1780 return -ENODEV;
1781 }
1782 return vfio_eeh_container_op(container, op);
1783}