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