]> git.proxmox.com Git - mirror_qemu.git/blame - hw/vfio/common.c
vfio/migration: Implement VFIO migration protocol v2
[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"
b6dd6504 32#include "exec/ram_addr.h"
e2c7d025
EA
33#include "hw/hw.h"
34#include "qemu/error-report.h"
db725815 35#include "qemu/main-loop.h"
f4ec5e26 36#include "qemu/range.h"
e2c7d025 37#include "sysemu/kvm.h"
71e8a915 38#include "sysemu/reset.h"
0fd7616e 39#include "sysemu/runstate.h"
e2c7d025 40#include "trace.h"
01905f58 41#include "qapi/error.h"
b6dd6504 42#include "migration/migration.h"
8b942af3 43#include "migration/misc.h"
29d81b71 44#include "migration/blocker.h"
851d6d1a 45#include "sysemu/tpm.h"
e2c7d025 46
f481ee2d 47VFIOGroupList vfio_group_list =
39cb514f 48 QLIST_HEAD_INITIALIZER(vfio_group_list);
10ca76b4 49static QLIST_HEAD(, VFIOAddressSpace) vfio_address_spaces =
e2c7d025
EA
50 QLIST_HEAD_INITIALIZER(vfio_address_spaces);
51
52#ifdef CONFIG_KVM
53/*
54 * We have a single VFIO pseudo device per KVM VM. Once created it lives
55 * for the life of the VM. Closing the file descriptor only drops our
56 * reference to it and the device's reference to kvm. Therefore once
57 * initialized, this file descriptor is only released on QEMU exit and
58 * we'll re-use it should another vfio device be attached before then.
59 */
60static int vfio_kvm_device_fd = -1;
61#endif
62
63/*
64 * Common VFIO interrupt disable
65 */
66void vfio_disable_irqindex(VFIODevice *vbasedev, int index)
67{
68 struct vfio_irq_set irq_set = {
69 .argsz = sizeof(irq_set),
70 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
71 .index = index,
72 .start = 0,
73 .count = 0,
74 };
75
76 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
77}
78
79void vfio_unmask_single_irqindex(VFIODevice *vbasedev, int index)
80{
81 struct vfio_irq_set irq_set = {
82 .argsz = sizeof(irq_set),
83 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
84 .index = index,
85 .start = 0,
86 .count = 1,
87 };
88
89 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
90}
91
92void vfio_mask_single_irqindex(VFIODevice *vbasedev, int index)
93{
94 struct vfio_irq_set irq_set = {
95 .argsz = sizeof(irq_set),
96 .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK,
97 .index = index,
98 .start = 0,
99 .count = 1,
100 };
101
102 ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
103}
104
201a7331
EA
105static inline const char *action_to_str(int action)
106{
107 switch (action) {
108 case VFIO_IRQ_SET_ACTION_MASK:
109 return "MASK";
110 case VFIO_IRQ_SET_ACTION_UNMASK:
111 return "UNMASK";
112 case VFIO_IRQ_SET_ACTION_TRIGGER:
113 return "TRIGGER";
114 default:
115 return "UNKNOWN ACTION";
116 }
117}
118
119static const char *index_to_str(VFIODevice *vbasedev, int index)
120{
121 if (vbasedev->type != VFIO_DEVICE_TYPE_PCI) {
122 return NULL;
123 }
124
125 switch (index) {
126 case VFIO_PCI_INTX_IRQ_INDEX:
127 return "INTX";
128 case VFIO_PCI_MSI_IRQ_INDEX:
129 return "MSI";
130 case VFIO_PCI_MSIX_IRQ_INDEX:
131 return "MSIX";
132 case VFIO_PCI_ERR_IRQ_INDEX:
133 return "ERR";
134 case VFIO_PCI_REQ_IRQ_INDEX:
135 return "REQ";
136 default:
137 return NULL;
138 }
139}
140
53d1b5fc
DH
141static int vfio_ram_block_discard_disable(VFIOContainer *container, bool state)
142{
143 switch (container->iommu_type) {
144 case VFIO_TYPE1v2_IOMMU:
145 case VFIO_TYPE1_IOMMU:
146 /*
147 * We support coordinated discarding of RAM via the RamDiscardManager.
148 */
149 return ram_block_uncoordinated_discard_disable(state);
150 default:
151 /*
152 * VFIO_SPAPR_TCE_IOMMU most probably works just fine with
153 * RamDiscardManager, however, it is completely untested.
154 *
155 * VFIO_SPAPR_TCE_v2_IOMMU with "DMA memory preregistering" does
156 * completely the opposite of managing mapping/pinning dynamically as
157 * required by RamDiscardManager. We would have to special-case sections
158 * with a RamDiscardManager.
159 */
160 return ram_block_discard_disable(state);
161 }
162}
163
201a7331
EA
164int vfio_set_irq_signaling(VFIODevice *vbasedev, int index, int subindex,
165 int action, int fd, Error **errp)
166{
167 struct vfio_irq_set *irq_set;
168 int argsz, ret = 0;
169 const char *name;
170 int32_t *pfd;
171
172 argsz = sizeof(*irq_set) + sizeof(*pfd);
173
174 irq_set = g_malloc0(argsz);
175 irq_set->argsz = argsz;
176 irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | action;
177 irq_set->index = index;
178 irq_set->start = subindex;
179 irq_set->count = 1;
180 pfd = (int32_t *)&irq_set->data;
181 *pfd = fd;
182
183 if (ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, irq_set)) {
184 ret = -errno;
185 }
186 g_free(irq_set);
187
188 if (!ret) {
189 return 0;
190 }
191
192 error_setg_errno(errp, -ret, "VFIO_DEVICE_SET_IRQS failure");
193
194 name = index_to_str(vbasedev, index);
195 if (name) {
196 error_prepend(errp, "%s-%d: ", name, subindex);
197 } else {
198 error_prepend(errp, "index %d-%d: ", index, subindex);
199 }
200 error_prepend(errp,
201 "Failed to %s %s eventfd signaling for interrupt ",
202 fd < 0 ? "tear down" : "set up", action_to_str(action));
203 return ret;
204}
205
e2c7d025
EA
206/*
207 * IO Port/MMIO - Beware of the endians, VFIO is always little endian
208 */
209void vfio_region_write(void *opaque, hwaddr addr,
210 uint64_t data, unsigned size)
211{
212 VFIORegion *region = opaque;
213 VFIODevice *vbasedev = region->vbasedev;
214 union {
215 uint8_t byte;
216 uint16_t word;
217 uint32_t dword;
218 uint64_t qword;
219 } buf;
220
221 switch (size) {
222 case 1:
223 buf.byte = data;
224 break;
225 case 2:
226 buf.word = cpu_to_le16(data);
227 break;
228 case 4:
229 buf.dword = cpu_to_le32(data);
230 break;
38d49e8c
JRZ
231 case 8:
232 buf.qword = cpu_to_le64(data);
233 break;
e2c7d025 234 default:
c624b6b3 235 hw_error("vfio: unsupported write size, %u bytes", size);
e2c7d025
EA
236 break;
237 }
238
239 if (pwrite(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
240 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", 0x%"PRIx64
241 ",%d) failed: %m",
242 __func__, vbasedev->name, region->nr,
243 addr, data, size);
244 }
245
246 trace_vfio_region_write(vbasedev->name, region->nr, addr, data, size);
247
248 /*
249 * A read or write to a BAR always signals an INTx EOI. This will
250 * do nothing if not pending (including not in INTx mode). We assume
251 * that a BAR access is in response to an interrupt and that BAR
252 * accesses will service the interrupt. Unfortunately, we don't know
253 * which access will service the interrupt, so we're potentially
254 * getting quite a few host interrupts per guest interrupt.
255 */
256 vbasedev->ops->vfio_eoi(vbasedev);
257}
258
259uint64_t vfio_region_read(void *opaque,
260 hwaddr addr, unsigned size)
261{
262 VFIORegion *region = opaque;
263 VFIODevice *vbasedev = region->vbasedev;
264 union {
265 uint8_t byte;
266 uint16_t word;
267 uint32_t dword;
268 uint64_t qword;
269 } buf;
270 uint64_t data = 0;
271
272 if (pread(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
273 error_report("%s(%s:region%d+0x%"HWADDR_PRIx", %d) failed: %m",
274 __func__, vbasedev->name, region->nr,
275 addr, size);
276 return (uint64_t)-1;
277 }
278 switch (size) {
279 case 1:
280 data = buf.byte;
281 break;
282 case 2:
283 data = le16_to_cpu(buf.word);
284 break;
285 case 4:
286 data = le32_to_cpu(buf.dword);
287 break;
38d49e8c
JRZ
288 case 8:
289 data = le64_to_cpu(buf.qword);
290 break;
e2c7d025 291 default:
c624b6b3 292 hw_error("vfio: unsupported read size, %u bytes", size);
e2c7d025
EA
293 break;
294 }
295
296 trace_vfio_region_read(vbasedev->name, region->nr, addr, size, data);
297
298 /* Same as write above */
299 vbasedev->ops->vfio_eoi(vbasedev);
300
301 return data;
302}
303
304const MemoryRegionOps vfio_region_ops = {
305 .read = vfio_region_read,
306 .write = vfio_region_write,
307 .endianness = DEVICE_LITTLE_ENDIAN,
15126cba
JRZ
308 .valid = {
309 .min_access_size = 1,
310 .max_access_size = 8,
311 },
38d49e8c
JRZ
312 .impl = {
313 .min_access_size = 1,
314 .max_access_size = 8,
315 },
e2c7d025
EA
316};
317
b6dd6504
KW
318/*
319 * Device state interfaces
320 */
321
3710586c
KW
322bool vfio_mig_active(void)
323{
324 VFIOGroup *group;
325 VFIODevice *vbasedev;
326
327 if (QLIST_EMPTY(&vfio_group_list)) {
328 return false;
329 }
330
331 QLIST_FOREACH(group, &vfio_group_list, next) {
332 QLIST_FOREACH(vbasedev, &group->device_list, next) {
333 if (vbasedev->migration_blocker) {
334 return false;
335 }
336 }
337 }
338 return true;
339}
340
29d81b71
AH
341static Error *multiple_devices_migration_blocker;
342
343static unsigned int vfio_migratable_device_num(void)
344{
345 VFIOGroup *group;
346 VFIODevice *vbasedev;
347 unsigned int device_num = 0;
348
349 QLIST_FOREACH(group, &vfio_group_list, next) {
350 QLIST_FOREACH(vbasedev, &group->device_list, next) {
351 if (vbasedev->migration) {
352 device_num++;
353 }
354 }
355 }
356
357 return device_num;
358}
359
360int vfio_block_multiple_devices_migration(Error **errp)
361{
362 int ret;
363
364 if (multiple_devices_migration_blocker ||
365 vfio_migratable_device_num() <= 1) {
366 return 0;
367 }
368
369 error_setg(&multiple_devices_migration_blocker,
370 "Migration is currently not supported with multiple "
371 "VFIO devices");
372 ret = migrate_add_blocker(multiple_devices_migration_blocker, errp);
373 if (ret < 0) {
374 error_free(multiple_devices_migration_blocker);
375 multiple_devices_migration_blocker = NULL;
376 }
377
378 return ret;
379}
380
381void vfio_unblock_multiple_devices_migration(void)
382{
383 if (!multiple_devices_migration_blocker ||
384 vfio_migratable_device_num() > 1) {
385 return;
386 }
387
388 migrate_del_blocker(multiple_devices_migration_blocker);
389 error_free(multiple_devices_migration_blocker);
390 multiple_devices_migration_blocker = NULL;
391}
392
758b96b6 393static bool vfio_devices_all_dirty_tracking(VFIOContainer *container)
b6dd6504
KW
394{
395 VFIOGroup *group;
396 VFIODevice *vbasedev;
397 MigrationState *ms = migrate_get_current();
398
399 if (!migration_is_setup_or_active(ms->state)) {
400 return false;
401 }
402
403 QLIST_FOREACH(group, &container->group_list, container_next) {
404 QLIST_FOREACH(vbasedev, &group->device_list, next) {
405 VFIOMigration *migration = vbasedev->migration;
406
407 if (!migration) {
408 return false;
409 }
410
31bcbbb5
AH
411 if (!migration->v2 &&
412 (vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF) &&
6eeb2909 413 (migration->device_state_v1 & VFIO_DEVICE_STATE_V1_RUNNING)) {
b6dd6504
KW
414 return false;
415 }
31bcbbb5
AH
416
417 if (migration->v2 &&
418 vbasedev->pre_copy_dirty_page_tracking == ON_OFF_AUTO_OFF &&
419 migration->device_state == VFIO_DEVICE_STATE_RUNNING) {
420 return false;
421 }
b6dd6504
KW
422 }
423 }
424 return true;
425}
426
8b942af3
AH
427/*
428 * Check if all VFIO devices are running and migration is active, which is
429 * essentially equivalent to the migration being in pre-copy phase.
430 */
431static bool vfio_devices_all_running_and_mig_active(VFIOContainer *container)
9e7b0442
KW
432{
433 VFIOGroup *group;
434 VFIODevice *vbasedev;
9e7b0442 435
8b942af3 436 if (!migration_is_active(migrate_get_current())) {
9e7b0442
KW
437 return false;
438 }
439
440 QLIST_FOREACH(group, &container->group_list, container_next) {
441 QLIST_FOREACH(vbasedev, &group->device_list, next) {
442 VFIOMigration *migration = vbasedev->migration;
443
444 if (!migration) {
445 return false;
446 }
447
31bcbbb5
AH
448 if (!migration->v2 &&
449 migration->device_state_v1 & VFIO_DEVICE_STATE_V1_RUNNING) {
450 continue;
451 }
452
453 if (migration->v2 &&
454 migration->device_state == VFIO_DEVICE_STATE_RUNNING) {
9e7b0442
KW
455 continue;
456 } else {
457 return false;
458 }
459 }
460 }
461 return true;
462}
463
464static int vfio_dma_unmap_bitmap(VFIOContainer *container,
465 hwaddr iova, ram_addr_t size,
466 IOMMUTLBEntry *iotlb)
467{
468 struct vfio_iommu_type1_dma_unmap *unmap;
469 struct vfio_bitmap *bitmap;
8e3b0cbb 470 uint64_t pages = REAL_HOST_PAGE_ALIGN(size) / qemu_real_host_page_size();
9e7b0442
KW
471 int ret;
472
473 unmap = g_malloc0(sizeof(*unmap) + sizeof(*bitmap));
474
475 unmap->argsz = sizeof(*unmap) + sizeof(*bitmap);
476 unmap->iova = iova;
477 unmap->size = size;
478 unmap->flags |= VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP;
479 bitmap = (struct vfio_bitmap *)&unmap->data;
480
481 /*
1eb7f642
KJ
482 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
483 * qemu_real_host_page_size to mark those dirty. Hence set bitmap_pgsize
484 * to qemu_real_host_page_size.
9e7b0442
KW
485 */
486
8e3b0cbb 487 bitmap->pgsize = qemu_real_host_page_size();
9e7b0442
KW
488 bitmap->size = ROUND_UP(pages, sizeof(__u64) * BITS_PER_BYTE) /
489 BITS_PER_BYTE;
490
491 if (bitmap->size > container->max_dirty_bitmap_size) {
492 error_report("UNMAP: Size of bitmap too big 0x%"PRIx64,
493 (uint64_t)bitmap->size);
494 ret = -E2BIG;
495 goto unmap_exit;
496 }
497
498 bitmap->data = g_try_malloc0(bitmap->size);
499 if (!bitmap->data) {
500 ret = -ENOMEM;
501 goto unmap_exit;
502 }
503
504 ret = ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, unmap);
505 if (!ret) {
506 cpu_physical_memory_set_dirty_lebitmap((unsigned long *)bitmap->data,
507 iotlb->translated_addr, pages);
508 } else {
509 error_report("VFIO_UNMAP_DMA with DIRTY_BITMAP : %m");
510 }
511
512 g_free(bitmap->data);
513unmap_exit:
514 g_free(unmap);
515 return ret;
516}
517
e2c7d025
EA
518/*
519 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
520 */
521static int vfio_dma_unmap(VFIOContainer *container,
9e7b0442
KW
522 hwaddr iova, ram_addr_t size,
523 IOMMUTLBEntry *iotlb)
e2c7d025
EA
524{
525 struct vfio_iommu_type1_dma_unmap unmap = {
526 .argsz = sizeof(unmap),
527 .flags = 0,
528 .iova = iova,
529 .size = size,
530 };
531
9e7b0442 532 if (iotlb && container->dirty_pages_supported &&
8b942af3 533 vfio_devices_all_running_and_mig_active(container)) {
9e7b0442
KW
534 return vfio_dma_unmap_bitmap(container, iova, size, iotlb);
535 }
536
567d7d3e
AW
537 while (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
538 /*
539 * The type1 backend has an off-by-one bug in the kernel (71a7d3d78e3c
540 * v4.15) where an overflow in its wrap-around check prevents us from
541 * unmapping the last page of the address space. Test for the error
542 * condition and re-try the unmap excluding the last page. The
543 * expectation is that we've never mapped the last page anyway and this
544 * unmap request comes via vIOMMU support which also makes it unlikely
545 * that this page is used. This bug was introduced well after type1 v2
546 * support was introduced, so we shouldn't need to test for v1. A fix
547 * is queued for kernel v5.0 so this workaround can be removed once
548 * affected kernels are sufficiently deprecated.
549 */
550 if (errno == EINVAL && unmap.size && !(unmap.iova + unmap.size) &&
551 container->iommu_type == VFIO_TYPE1v2_IOMMU) {
552 trace_vfio_dma_unmap_overflow_workaround();
553 unmap.size -= 1ULL << ctz64(container->pgsizes);
554 continue;
555 }
b09d51c9 556 error_report("VFIO_UNMAP_DMA failed: %s", strerror(errno));
e2c7d025
EA
557 return -errno;
558 }
559
8b942af3 560 if (iotlb && vfio_devices_all_running_and_mig_active(container)) {
b051a3f6
AH
561 cpu_physical_memory_set_dirty_range(iotlb->translated_addr, size,
562 tcg_enabled() ? DIRTY_CLIENTS_ALL :
563 DIRTY_CLIENTS_NOCODE);
564 }
565
e2c7d025
EA
566 return 0;
567}
568
569static int vfio_dma_map(VFIOContainer *container, hwaddr iova,
570 ram_addr_t size, void *vaddr, bool readonly)
571{
572 struct vfio_iommu_type1_dma_map map = {
573 .argsz = sizeof(map),
574 .flags = VFIO_DMA_MAP_FLAG_READ,
575 .vaddr = (__u64)(uintptr_t)vaddr,
576 .iova = iova,
577 .size = size,
578 };
579
580 if (!readonly) {
581 map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
582 }
583
584 /*
585 * Try the mapping, if it fails with EBUSY, unmap the region and try
586 * again. This shouldn't be necessary, but we sometimes see it in
b6af0975 587 * the VGA ROM space.
e2c7d025
EA
588 */
589 if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
9e7b0442 590 (errno == EBUSY && vfio_dma_unmap(container, iova, size, NULL) == 0 &&
e2c7d025
EA
591 ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
592 return 0;
593 }
594
b09d51c9 595 error_report("VFIO_MAP_DMA failed: %s", strerror(errno));
e2c7d025
EA
596 return -errno;
597}
598
f4ec5e26
AK
599static void vfio_host_win_add(VFIOContainer *container,
600 hwaddr min_iova, hwaddr max_iova,
601 uint64_t iova_pgsizes)
602{
603 VFIOHostDMAWindow *hostwin;
604
605 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
606 if (ranges_overlap(hostwin->min_iova,
607 hostwin->max_iova - hostwin->min_iova + 1,
608 min_iova,
609 max_iova - min_iova + 1)) {
610 hw_error("%s: Overlapped IOMMU are not enabled", __func__);
611 }
612 }
613
614 hostwin = g_malloc0(sizeof(*hostwin));
615
616 hostwin->min_iova = min_iova;
617 hostwin->max_iova = max_iova;
618 hostwin->iova_pgsizes = iova_pgsizes;
619 QLIST_INSERT_HEAD(&container->hostwin_list, hostwin, hostwin_next);
620}
621
2e4109de
AK
622static int vfio_host_win_del(VFIOContainer *container, hwaddr min_iova,
623 hwaddr max_iova)
624{
625 VFIOHostDMAWindow *hostwin;
626
627 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
628 if (hostwin->min_iova == min_iova && hostwin->max_iova == max_iova) {
629 QLIST_REMOVE(hostwin, hostwin_next);
f3bc3a73 630 g_free(hostwin);
2e4109de
AK
631 return 0;
632 }
633 }
634
635 return -1;
636}
637
e2c7d025
EA
638static bool vfio_listener_skipped_section(MemoryRegionSection *section)
639{
640 return (!memory_region_is_ram(section->mr) &&
641 !memory_region_is_iommu(section->mr)) ||
56918a12 642 memory_region_is_protected(section->mr) ||
e2c7d025
EA
643 /*
644 * Sizing an enabled 64-bit BAR can cause spurious mappings to
645 * addresses in the upper part of the 64-bit address space. These
646 * are never accessed by the CPU and beyond the address width of
647 * some IOMMU hardware. TODO: VFIO should tell us the IOMMU width.
648 */
649 section->offset_within_address_space & (1ULL << 63);
650}
651
4a4b88fb 652/* Called with rcu_read_lock held. */
9a04fe09
KW
653static bool vfio_get_xlat_addr(IOMMUTLBEntry *iotlb, void **vaddr,
654 ram_addr_t *ram_addr, bool *read_only)
e2c7d025 655{
baa44bce 656 bool ret, mr_has_discard_manager;
0fd7616e 657
baa44bce
CL
658 ret = memory_get_xlat_addr(iotlb, vaddr, ram_addr, read_only,
659 &mr_has_discard_manager);
660 if (ret && mr_has_discard_manager) {
0fd7616e
DH
661 /*
662 * Malicious VMs might trigger discarding of IOMMU-mapped memory. The
663 * pages will remain pinned inside vfio until unmapped, resulting in a
664 * higher memory consumption than expected. If memory would get
665 * populated again later, there would be an inconsistency between pages
666 * pinned by vfio and pages seen by QEMU. This is the case until
667 * unmapped from the IOMMU (e.g., during device reset).
668 *
669 * With malicious guests, we really only care about pinning more memory
670 * than expected. RLIMIT_MEMLOCK set for the user/process can never be
671 * exceeded and can be used to mitigate this problem.
672 */
673 warn_report_once("Using vfio with vIOMMUs and coordinated discarding of"
674 " RAM (e.g., virtio-mem) works, however, malicious"
675 " guests can trigger pinning of more memory than"
676 " intended via an IOMMU. It's possible to mitigate "
677 " by setting/adjusting RLIMIT_MEMLOCK.");
e2c7d025 678 }
baa44bce 679 return ret;
4a4b88fb
PX
680}
681
682static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
683{
684 VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
685 VFIOContainer *container = giommu->container;
686 hwaddr iova = iotlb->iova + giommu->iommu_offset;
4a4b88fb
PX
687 void *vaddr;
688 int ret;
689
690 trace_vfio_iommu_map_notify(iotlb->perm == IOMMU_NONE ? "UNMAP" : "MAP",
691 iova, iova + iotlb->addr_mask);
692
693 if (iotlb->target_as != &address_space_memory) {
694 error_report("Wrong target AS \"%s\", only system memory is allowed",
695 iotlb->target_as->name ? iotlb->target_as->name : "none");
696 return;
697 }
698
699 rcu_read_lock();
700
e2c7d025 701 if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {
9a04fe09
KW
702 bool read_only;
703
704 if (!vfio_get_xlat_addr(iotlb, &vaddr, NULL, &read_only)) {
dfbd90e5
PX
705 goto out;
706 }
4a4b88fb
PX
707 /*
708 * vaddr is only valid until rcu_read_unlock(). But after
709 * vfio_dma_map has set up the mapping the pages will be
710 * pinned by the kernel. This makes sure that the RAM backend
711 * of vaddr will always be there, even if the memory object is
712 * destroyed and its backing memory munmap-ed.
713 */
d78c19b5 714 ret = vfio_dma_map(container, iova,
e2c7d025 715 iotlb->addr_mask + 1, vaddr,
4a4b88fb 716 read_only);
e2c7d025
EA
717 if (ret) {
718 error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
719 "0x%"HWADDR_PRIx", %p) = %d (%m)",
d78c19b5 720 container, iova,
e2c7d025
EA
721 iotlb->addr_mask + 1, vaddr, ret);
722 }
723 } else {
9e7b0442 724 ret = vfio_dma_unmap(container, iova, iotlb->addr_mask + 1, iotlb);
e2c7d025
EA
725 if (ret) {
726 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
727 "0x%"HWADDR_PRIx") = %d (%m)",
d78c19b5 728 container, iova,
e2c7d025
EA
729 iotlb->addr_mask + 1, ret);
730 }
731 }
41063e1e
PB
732out:
733 rcu_read_unlock();
e2c7d025
EA
734}
735
5e3b981c
DH
736static void vfio_ram_discard_notify_discard(RamDiscardListener *rdl,
737 MemoryRegionSection *section)
738{
739 VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
740 listener);
741 const hwaddr size = int128_get64(section->size);
742 const hwaddr iova = section->offset_within_address_space;
743 int ret;
744
745 /* Unmap with a single call. */
746 ret = vfio_dma_unmap(vrdl->container, iova, size , NULL);
747 if (ret) {
748 error_report("%s: vfio_dma_unmap() failed: %s", __func__,
749 strerror(-ret));
750 }
751}
752
753static int vfio_ram_discard_notify_populate(RamDiscardListener *rdl,
754 MemoryRegionSection *section)
755{
756 VFIORamDiscardListener *vrdl = container_of(rdl, VFIORamDiscardListener,
757 listener);
758 const hwaddr end = section->offset_within_region +
759 int128_get64(section->size);
760 hwaddr start, next, iova;
761 void *vaddr;
762 int ret;
763
764 /*
765 * Map in (aligned within memory region) minimum granularity, so we can
766 * unmap in minimum granularity later.
767 */
768 for (start = section->offset_within_region; start < end; start = next) {
769 next = ROUND_UP(start + 1, vrdl->granularity);
770 next = MIN(next, end);
771
772 iova = start - section->offset_within_region +
773 section->offset_within_address_space;
774 vaddr = memory_region_get_ram_ptr(section->mr) + start;
775
776 ret = vfio_dma_map(vrdl->container, iova, next - start,
777 vaddr, section->readonly);
778 if (ret) {
779 /* Rollback */
780 vfio_ram_discard_notify_discard(rdl, section);
781 return ret;
782 }
783 }
784 return 0;
785}
786
787static void vfio_register_ram_discard_listener(VFIOContainer *container,
788 MemoryRegionSection *section)
789{
790 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
791 VFIORamDiscardListener *vrdl;
792
793 /* Ignore some corner cases not relevant in practice. */
794 g_assert(QEMU_IS_ALIGNED(section->offset_within_region, TARGET_PAGE_SIZE));
795 g_assert(QEMU_IS_ALIGNED(section->offset_within_address_space,
796 TARGET_PAGE_SIZE));
797 g_assert(QEMU_IS_ALIGNED(int128_get64(section->size), TARGET_PAGE_SIZE));
798
799 vrdl = g_new0(VFIORamDiscardListener, 1);
800 vrdl->container = container;
801 vrdl->mr = section->mr;
802 vrdl->offset_within_address_space = section->offset_within_address_space;
803 vrdl->size = int128_get64(section->size);
804 vrdl->granularity = ram_discard_manager_get_min_granularity(rdm,
805 section->mr);
806
807 g_assert(vrdl->granularity && is_power_of_2(vrdl->granularity));
a5dba9bc
DH
808 g_assert(container->pgsizes &&
809 vrdl->granularity >= 1ULL << ctz64(container->pgsizes));
5e3b981c
DH
810
811 ram_discard_listener_init(&vrdl->listener,
812 vfio_ram_discard_notify_populate,
813 vfio_ram_discard_notify_discard, true);
814 ram_discard_manager_register_listener(rdm, &vrdl->listener, section);
815 QLIST_INSERT_HEAD(&container->vrdl_list, vrdl, next);
a74317f6
DH
816
817 /*
818 * Sanity-check if we have a theoretically problematic setup where we could
819 * exceed the maximum number of possible DMA mappings over time. We assume
820 * that each mapped section in the same address space as a RamDiscardManager
821 * section consumes exactly one DMA mapping, with the exception of
822 * RamDiscardManager sections; i.e., we don't expect to have gIOMMU sections
823 * in the same address space as RamDiscardManager sections.
824 *
825 * We assume that each section in the address space consumes one memslot.
826 * We take the number of KVM memory slots as a best guess for the maximum
827 * number of sections in the address space we could have over time,
828 * also consuming DMA mappings.
829 */
830 if (container->dma_max_mappings) {
831 unsigned int vrdl_count = 0, vrdl_mappings = 0, max_memslots = 512;
832
833#ifdef CONFIG_KVM
834 if (kvm_enabled()) {
835 max_memslots = kvm_get_max_memslots();
836 }
837#endif
838
839 QLIST_FOREACH(vrdl, &container->vrdl_list, next) {
840 hwaddr start, end;
841
842 start = QEMU_ALIGN_DOWN(vrdl->offset_within_address_space,
843 vrdl->granularity);
844 end = ROUND_UP(vrdl->offset_within_address_space + vrdl->size,
845 vrdl->granularity);
846 vrdl_mappings += (end - start) / vrdl->granularity;
847 vrdl_count++;
848 }
849
850 if (vrdl_mappings + max_memslots - vrdl_count >
851 container->dma_max_mappings) {
852 warn_report("%s: possibly running out of DMA mappings. E.g., try"
853 " increasing the 'block-size' of virtio-mem devies."
854 " Maximum possible DMA mappings: %d, Maximum possible"
855 " memslots: %d", __func__, container->dma_max_mappings,
856 max_memslots);
857 }
858 }
5e3b981c
DH
859}
860
861static void vfio_unregister_ram_discard_listener(VFIOContainer *container,
862 MemoryRegionSection *section)
863{
864 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
865 VFIORamDiscardListener *vrdl = NULL;
866
867 QLIST_FOREACH(vrdl, &container->vrdl_list, next) {
868 if (vrdl->mr == section->mr &&
869 vrdl->offset_within_address_space ==
870 section->offset_within_address_space) {
871 break;
872 }
873 }
874
875 if (!vrdl) {
876 hw_error("vfio: Trying to unregister missing RAM discard listener");
877 }
878
879 ram_discard_manager_unregister_listener(rdm, &vrdl->listener);
880 QLIST_REMOVE(vrdl, next);
881 g_free(vrdl);
882}
883
851d6d1a
EA
884static bool vfio_known_safe_misalignment(MemoryRegionSection *section)
885{
886 MemoryRegion *mr = section->mr;
887
888 if (!TPM_IS_CRB(mr->owner)) {
889 return false;
890 }
891
892 /* this is a known safe misaligned region, just trace for debug purpose */
893 trace_vfio_known_safe_misalignment(memory_region_name(mr),
894 section->offset_within_address_space,
895 section->offset_within_region,
896 qemu_real_host_page_size());
897 return true;
898}
899
e2c7d025
EA
900static void vfio_listener_region_add(MemoryListener *listener,
901 MemoryRegionSection *section)
902{
ee0bf0e5 903 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
e2c7d025 904 hwaddr iova, end;
55efcc53 905 Int128 llend, llsize;
e2c7d025
EA
906 void *vaddr;
907 int ret;
f4ec5e26
AK
908 VFIOHostDMAWindow *hostwin;
909 bool hostwin_found;
d7d87836 910 Error *err = NULL;
e2c7d025
EA
911
912 if (vfio_listener_skipped_section(section)) {
913 trace_vfio_listener_region_add_skip(
914 section->offset_within_address_space,
915 section->offset_within_address_space +
916 int128_get64(int128_sub(section->size, int128_one())));
917 return;
918 }
919
1eb7f642 920 if (unlikely((section->offset_within_address_space &
8e3b0cbb
MAL
921 ~qemu_real_host_page_mask()) !=
922 (section->offset_within_region & ~qemu_real_host_page_mask()))) {
851d6d1a
EA
923 if (!vfio_known_safe_misalignment(section)) {
924 error_report("%s received unaligned region %s iova=0x%"PRIx64
925 " offset_within_region=0x%"PRIx64
926 " qemu_real_host_page_size=0x%"PRIxPTR,
927 __func__, memory_region_name(section->mr),
928 section->offset_within_address_space,
929 section->offset_within_region,
930 qemu_real_host_page_size());
931 }
e2c7d025
EA
932 return;
933 }
934
1eb7f642 935 iova = REAL_HOST_PAGE_ALIGN(section->offset_within_address_space);
e2c7d025
EA
936 llend = int128_make64(section->offset_within_address_space);
937 llend = int128_add(llend, section->size);
8e3b0cbb 938 llend = int128_and(llend, int128_exts64(qemu_real_host_page_mask()));
e2c7d025
EA
939
940 if (int128_ge(int128_make64(iova), llend)) {
e4b34708
KJ
941 if (memory_region_is_ram_device(section->mr)) {
942 trace_vfio_listener_region_add_no_dma_map(
943 memory_region_name(section->mr),
944 section->offset_within_address_space,
945 int128_getlo(section->size),
8e3b0cbb 946 qemu_real_host_page_size());
e4b34708 947 }
e2c7d025
EA
948 return;
949 }
55efcc53 950 end = int128_get64(int128_sub(llend, int128_one()));
3898aad3 951
2e4109de 952 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
2e4109de
AK
953 hwaddr pgsize = 0;
954
955 /* For now intersections are not allowed, we may relax this later */
956 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
957 if (ranges_overlap(hostwin->min_iova,
958 hostwin->max_iova - hostwin->min_iova + 1,
959 section->offset_within_address_space,
960 int128_get64(section->size))) {
d7d87836
EA
961 error_setg(&err,
962 "region [0x%"PRIx64",0x%"PRIx64"] overlaps with existing"
963 "host DMA window [0x%"PRIx64",0x%"PRIx64"]",
964 section->offset_within_address_space,
965 section->offset_within_address_space +
966 int128_get64(section->size) - 1,
967 hostwin->min_iova, hostwin->max_iova);
2e4109de
AK
968 goto fail;
969 }
970 }
971
972 ret = vfio_spapr_create_window(container, section, &pgsize);
973 if (ret) {
d7d87836 974 error_setg_errno(&err, -ret, "Failed to create SPAPR window");
2e4109de
AK
975 goto fail;
976 }
977
978 vfio_host_win_add(container, section->offset_within_address_space,
979 section->offset_within_address_space +
980 int128_get64(section->size) - 1, pgsize);
07bc681a
AK
981#ifdef CONFIG_KVM
982 if (kvm_enabled()) {
983 VFIOGroup *group;
984 IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
985 struct kvm_vfio_spapr_tce param;
986 struct kvm_device_attr attr = {
987 .group = KVM_DEV_VFIO_GROUP,
988 .attr = KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE,
989 .addr = (uint64_t)(unsigned long)&param,
990 };
991
992 if (!memory_region_iommu_get_attr(iommu_mr, IOMMU_ATTR_SPAPR_TCE_FD,
993 &param.tablefd)) {
994 QLIST_FOREACH(group, &container->group_list, container_next) {
995 param.groupfd = group->fd;
996 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
997 error_report("vfio: failed to setup fd %d "
998 "for a group with fd %d: %s",
999 param.tablefd, param.groupfd,
1000 strerror(errno));
1001 return;
1002 }
1003 trace_vfio_spapr_group_attach(param.groupfd, param.tablefd);
1004 }
1005 }
1006 }
1007#endif
2e4109de
AK
1008 }
1009
f4ec5e26
AK
1010 hostwin_found = false;
1011 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
1012 if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
1013 hostwin_found = true;
1014 break;
1015 }
1016 }
1017
1018 if (!hostwin_found) {
d7d87836
EA
1019 error_setg(&err, "Container %p can't map guest IOVA region"
1020 " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx, container, iova, end);
3898aad3
DG
1021 goto fail;
1022 }
e2c7d025
EA
1023
1024 memory_region_ref(section->mr);
1025
1026 if (memory_region_is_iommu(section->mr)) {
1027 VFIOGuestIOMMU *giommu;
3df9d748 1028 IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
cb1efcf4 1029 int iommu_idx;
e2c7d025 1030
55efcc53 1031 trace_vfio_listener_region_add_iommu(iova, end);
e2c7d025 1032 /*
e2c7d025
EA
1033 * FIXME: For VFIO iommu types which have KVM acceleration to
1034 * avoid bouncing all map/unmaps through qemu this way, this
1035 * would be the right place to wire that up (tell the KVM
1036 * device emulation the VFIO iommu handles to use).
1037 */
e2c7d025 1038 giommu = g_malloc0(sizeof(*giommu));
44ee6aaa 1039 giommu->iommu_mr = iommu_mr;
d78c19b5
AK
1040 giommu->iommu_offset = section->offset_within_address_space -
1041 section->offset_within_region;
e2c7d025 1042 giommu->container = container;
698feb5e
PX
1043 llend = int128_add(int128_make64(section->offset_within_region),
1044 section->size);
1045 llend = int128_sub(llend, int128_one());
cb1efcf4
PM
1046 iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
1047 MEMTXATTRS_UNSPECIFIED);
698feb5e 1048 iommu_notifier_init(&giommu->n, vfio_iommu_map_notify,
8dca037b 1049 IOMMU_NOTIFIER_IOTLB_EVENTS,
698feb5e 1050 section->offset_within_region,
cb1efcf4
PM
1051 int128_get64(llend),
1052 iommu_idx);
508ce5eb 1053
44ee6aaa 1054 ret = memory_region_iommu_set_page_size_mask(giommu->iommu_mr,
b9177498
BB
1055 container->pgsizes,
1056 &err);
1057 if (ret) {
1058 g_free(giommu);
1059 goto fail;
1060 }
1061
549d4005
EA
1062 ret = memory_region_register_iommu_notifier(section->mr, &giommu->n,
1063 &err);
1064 if (ret) {
1065 g_free(giommu);
1066 goto fail;
1067 }
1068 QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
44ee6aaa 1069 memory_region_iommu_replay(giommu->iommu_mr, &giommu->n);
e2c7d025
EA
1070
1071 return;
1072 }
1073
1074 /* Here we assume that memory_region_is_ram(section->mr)==true */
1075
5e3b981c
DH
1076 /*
1077 * For RAM memory regions with a RamDiscardManager, we only want to map the
1078 * actually populated parts - and update the mapping whenever we're notified
1079 * about changes.
1080 */
1081 if (memory_region_has_ram_discard_manager(section->mr)) {
1082 vfio_register_ram_discard_listener(container, section);
1083 return;
1084 }
1085
e2c7d025
EA
1086 vaddr = memory_region_get_ram_ptr(section->mr) +
1087 section->offset_within_region +
1088 (iova - section->offset_within_address_space);
1089
55efcc53 1090 trace_vfio_listener_region_add_ram(iova, end, vaddr);
e2c7d025 1091
55efcc53
BD
1092 llsize = int128_sub(llend, int128_make64(iova));
1093
567b5b30
AK
1094 if (memory_region_is_ram_device(section->mr)) {
1095 hwaddr pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
1096
1097 if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) {
5c086005
EA
1098 trace_vfio_listener_region_add_no_dma_map(
1099 memory_region_name(section->mr),
1100 section->offset_within_address_space,
1101 int128_getlo(section->size),
1102 pgmask + 1);
567b5b30
AK
1103 return;
1104 }
1105 }
1106
55efcc53
BD
1107 ret = vfio_dma_map(container, iova, int128_get64(llsize),
1108 vaddr, section->readonly);
e2c7d025 1109 if (ret) {
d7d87836
EA
1110 error_setg(&err, "vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
1111 "0x%"HWADDR_PRIx", %p) = %d (%m)",
1112 container, iova, int128_get64(llsize), vaddr, ret);
567b5b30
AK
1113 if (memory_region_is_ram_device(section->mr)) {
1114 /* Allow unexpected mappings not to be fatal for RAM devices */
d7d87836 1115 error_report_err(err);
567b5b30
AK
1116 return;
1117 }
ac6dc389
DG
1118 goto fail;
1119 }
e2c7d025 1120
ac6dc389
DG
1121 return;
1122
1123fail:
567b5b30
AK
1124 if (memory_region_is_ram_device(section->mr)) {
1125 error_report("failed to vfio_dma_map. pci p2p may not work");
1126 return;
1127 }
ac6dc389
DG
1128 /*
1129 * On the initfn path, store the first error in the container so we
1130 * can gracefully fail. Runtime, there's not much we can do other
1131 * than throw a hardware error.
1132 */
1133 if (!container->initialized) {
1134 if (!container->error) {
d7d87836
EA
1135 error_propagate_prepend(&container->error, err,
1136 "Region %s: ",
1137 memory_region_name(section->mr));
1138 } else {
1139 error_free(err);
e2c7d025 1140 }
ac6dc389 1141 } else {
d7d87836 1142 error_report_err(err);
ac6dc389 1143 hw_error("vfio: DMA mapping failed, unable to continue");
e2c7d025
EA
1144 }
1145}
1146
1147static void vfio_listener_region_del(MemoryListener *listener,
1148 MemoryRegionSection *section)
1149{
ee0bf0e5 1150 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
e2c7d025 1151 hwaddr iova, end;
7a057b4f 1152 Int128 llend, llsize;
e2c7d025 1153 int ret;
567b5b30 1154 bool try_unmap = true;
e2c7d025
EA
1155
1156 if (vfio_listener_skipped_section(section)) {
1157 trace_vfio_listener_region_del_skip(
1158 section->offset_within_address_space,
1159 section->offset_within_address_space +
1160 int128_get64(int128_sub(section->size, int128_one())));
1161 return;
1162 }
1163
1eb7f642 1164 if (unlikely((section->offset_within_address_space &
8e3b0cbb
MAL
1165 ~qemu_real_host_page_mask()) !=
1166 (section->offset_within_region & ~qemu_real_host_page_mask()))) {
ec6600be
EA
1167 if (!vfio_known_safe_misalignment(section)) {
1168 error_report("%s received unaligned region %s iova=0x%"PRIx64
1169 " offset_within_region=0x%"PRIx64
1170 " qemu_real_host_page_size=0x%"PRIxPTR,
1171 __func__, memory_region_name(section->mr),
1172 section->offset_within_address_space,
1173 section->offset_within_region,
1174 qemu_real_host_page_size());
1175 }
e2c7d025
EA
1176 return;
1177 }
1178
1179 if (memory_region_is_iommu(section->mr)) {
1180 VFIOGuestIOMMU *giommu;
1181
1182 QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
44ee6aaa 1183 if (MEMORY_REGION(giommu->iommu_mr) == section->mr &&
698feb5e 1184 giommu->n.start == section->offset_within_region) {
3df9d748 1185 memory_region_unregister_iommu_notifier(section->mr,
d22d8956 1186 &giommu->n);
e2c7d025
EA
1187 QLIST_REMOVE(giommu, giommu_next);
1188 g_free(giommu);
1189 break;
1190 }
1191 }
1192
1193 /*
1194 * FIXME: We assume the one big unmap below is adequate to
1195 * remove any individual page mappings in the IOMMU which
1196 * might have been copied into VFIO. This works for a page table
1197 * based IOMMU where a big unmap flattens a large range of IO-PTEs.
1198 * That may not be true for all IOMMU types.
1199 */
1200 }
1201
1eb7f642 1202 iova = REAL_HOST_PAGE_ALIGN(section->offset_within_address_space);
7a057b4f
AK
1203 llend = int128_make64(section->offset_within_address_space);
1204 llend = int128_add(llend, section->size);
8e3b0cbb 1205 llend = int128_and(llend, int128_exts64(qemu_real_host_page_mask()));
e2c7d025 1206
7a057b4f 1207 if (int128_ge(int128_make64(iova), llend)) {
e2c7d025
EA
1208 return;
1209 }
7a057b4f
AK
1210 end = int128_get64(int128_sub(llend, int128_one()));
1211
1212 llsize = int128_sub(llend, int128_make64(iova));
e2c7d025 1213
7a057b4f 1214 trace_vfio_listener_region_del(iova, end);
e2c7d025 1215
567b5b30
AK
1216 if (memory_region_is_ram_device(section->mr)) {
1217 hwaddr pgmask;
1218 VFIOHostDMAWindow *hostwin;
1219 bool hostwin_found = false;
1220
1221 QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
1222 if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
1223 hostwin_found = true;
1224 break;
1225 }
1226 }
1227 assert(hostwin_found); /* or region_add() would have failed */
1228
1229 pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
1230 try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask));
5e3b981c
DH
1231 } else if (memory_region_has_ram_discard_manager(section->mr)) {
1232 vfio_unregister_ram_discard_listener(container, section);
1233 /* Unregistering will trigger an unmap. */
1234 try_unmap = false;
e2c7d025 1235 }
2e4109de 1236
567b5b30 1237 if (try_unmap) {
1b296c3d
JPB
1238 if (int128_eq(llsize, int128_2_64())) {
1239 /* The unmap ioctl doesn't accept a full 64-bit span. */
1240 llsize = int128_rshift(llsize, 1);
1241 ret = vfio_dma_unmap(container, iova, int128_get64(llsize), NULL);
1242 if (ret) {
1243 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
1244 "0x%"HWADDR_PRIx") = %d (%m)",
1245 container, iova, int128_get64(llsize), ret);
1246 }
1247 iova += int128_get64(llsize);
1248 }
9e7b0442 1249 ret = vfio_dma_unmap(container, iova, int128_get64(llsize), NULL);
567b5b30
AK
1250 if (ret) {
1251 error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
1252 "0x%"HWADDR_PRIx") = %d (%m)",
1253 container, iova, int128_get64(llsize), ret);
1254 }
1255 }
1256
1257 memory_region_unref(section->mr);
1258
2e4109de
AK
1259 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
1260 vfio_spapr_remove_window(container,
1261 section->offset_within_address_space);
1262 if (vfio_host_win_del(container,
1263 section->offset_within_address_space,
1264 section->offset_within_address_space +
1265 int128_get64(section->size) - 1) < 0) {
1266 hw_error("%s: Cannot delete missing window at %"HWADDR_PRIx,
1267 __func__, section->offset_within_address_space);
1268 }
1269 }
e2c7d025
EA
1270}
1271
758b96b6
KZ
1272static void vfio_set_dirty_page_tracking(VFIOContainer *container, bool start)
1273{
1274 int ret;
1275 struct vfio_iommu_type1_dirty_bitmap dirty = {
1276 .argsz = sizeof(dirty),
1277 };
1278
b051a3f6
AH
1279 if (!container->dirty_pages_supported) {
1280 return;
1281 }
1282
758b96b6
KZ
1283 if (start) {
1284 dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_START;
1285 } else {
1286 dirty.flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP;
1287 }
1288
1289 ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, &dirty);
1290 if (ret) {
1291 error_report("Failed to set dirty tracking flag 0x%x errno: %d",
1292 dirty.flags, errno);
1293 }
1294}
1295
1296static void vfio_listener_log_global_start(MemoryListener *listener)
1297{
1298 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1299
1300 vfio_set_dirty_page_tracking(container, true);
1301}
1302
1303static void vfio_listener_log_global_stop(MemoryListener *listener)
1304{
1305 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1306
1307 vfio_set_dirty_page_tracking(container, false);
1308}
1309
b6dd6504
KW
1310static int vfio_get_dirty_bitmap(VFIOContainer *container, uint64_t iova,
1311 uint64_t size, ram_addr_t ram_addr)
1312{
1313 struct vfio_iommu_type1_dirty_bitmap *dbitmap;
1314 struct vfio_iommu_type1_dirty_bitmap_get *range;
1315 uint64_t pages;
1316 int ret;
1317
b051a3f6
AH
1318 if (!container->dirty_pages_supported) {
1319 cpu_physical_memory_set_dirty_range(ram_addr, size,
1320 tcg_enabled() ? DIRTY_CLIENTS_ALL :
1321 DIRTY_CLIENTS_NOCODE);
1322 return 0;
1323 }
1324
b6dd6504
KW
1325 dbitmap = g_malloc0(sizeof(*dbitmap) + sizeof(*range));
1326
1327 dbitmap->argsz = sizeof(*dbitmap) + sizeof(*range);
1328 dbitmap->flags = VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
1329 range = (struct vfio_iommu_type1_dirty_bitmap_get *)&dbitmap->data;
1330 range->iova = iova;
1331 range->size = size;
1332
1333 /*
1eb7f642
KJ
1334 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
1335 * qemu_real_host_page_size to mark those dirty. Hence set bitmap's pgsize
1336 * to qemu_real_host_page_size.
b6dd6504 1337 */
8e3b0cbb 1338 range->bitmap.pgsize = qemu_real_host_page_size();
b6dd6504 1339
8e3b0cbb 1340 pages = REAL_HOST_PAGE_ALIGN(range->size) / qemu_real_host_page_size();
b6dd6504
KW
1341 range->bitmap.size = ROUND_UP(pages, sizeof(__u64) * BITS_PER_BYTE) /
1342 BITS_PER_BYTE;
1343 range->bitmap.data = g_try_malloc0(range->bitmap.size);
1344 if (!range->bitmap.data) {
1345 ret = -ENOMEM;
1346 goto err_out;
1347 }
1348
1349 ret = ioctl(container->fd, VFIO_IOMMU_DIRTY_PAGES, dbitmap);
1350 if (ret) {
1351 error_report("Failed to get dirty bitmap for iova: 0x%"PRIx64
1352 " size: 0x%"PRIx64" err: %d", (uint64_t)range->iova,
1353 (uint64_t)range->size, errno);
1354 goto err_out;
1355 }
1356
1357 cpu_physical_memory_set_dirty_lebitmap((unsigned long *)range->bitmap.data,
1358 ram_addr, pages);
1359
1360 trace_vfio_get_dirty_bitmap(container->fd, range->iova, range->size,
1361 range->bitmap.size, ram_addr);
1362err_out:
1363 g_free(range->bitmap.data);
1364 g_free(dbitmap);
1365
1366 return ret;
1367}
1368
9a04fe09
KW
1369typedef struct {
1370 IOMMUNotifier n;
1371 VFIOGuestIOMMU *giommu;
1372} vfio_giommu_dirty_notifier;
1373
1374static void vfio_iommu_map_dirty_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
1375{
1376 vfio_giommu_dirty_notifier *gdn = container_of(n,
1377 vfio_giommu_dirty_notifier, n);
1378 VFIOGuestIOMMU *giommu = gdn->giommu;
1379 VFIOContainer *container = giommu->container;
1380 hwaddr iova = iotlb->iova + giommu->iommu_offset;
1381 ram_addr_t translated_addr;
1382
1383 trace_vfio_iommu_map_dirty_notify(iova, iova + iotlb->addr_mask);
1384
1385 if (iotlb->target_as != &address_space_memory) {
1386 error_report("Wrong target AS \"%s\", only system memory is allowed",
1387 iotlb->target_as->name ? iotlb->target_as->name : "none");
1388 return;
1389 }
1390
1391 rcu_read_lock();
1392 if (vfio_get_xlat_addr(iotlb, NULL, &translated_addr, NULL)) {
1393 int ret;
1394
1395 ret = vfio_get_dirty_bitmap(container, iova, iotlb->addr_mask + 1,
1396 translated_addr);
1397 if (ret) {
1398 error_report("vfio_iommu_map_dirty_notify(%p, 0x%"HWADDR_PRIx", "
1399 "0x%"HWADDR_PRIx") = %d (%m)",
1400 container, iova,
1401 iotlb->addr_mask + 1, ret);
1402 }
1403 }
1404 rcu_read_unlock();
1405}
1406
5e3b981c
DH
1407static int vfio_ram_discard_get_dirty_bitmap(MemoryRegionSection *section,
1408 void *opaque)
1409{
1410 const hwaddr size = int128_get64(section->size);
1411 const hwaddr iova = section->offset_within_address_space;
1412 const ram_addr_t ram_addr = memory_region_get_ram_addr(section->mr) +
1413 section->offset_within_region;
1414 VFIORamDiscardListener *vrdl = opaque;
1415
1416 /*
1417 * Sync the whole mapped region (spanning multiple individual mappings)
1418 * in one go.
1419 */
1420 return vfio_get_dirty_bitmap(vrdl->container, iova, size, ram_addr);
1421}
1422
1423static int vfio_sync_ram_discard_listener_dirty_bitmap(VFIOContainer *container,
1424 MemoryRegionSection *section)
1425{
1426 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(section->mr);
1427 VFIORamDiscardListener *vrdl = NULL;
1428
1429 QLIST_FOREACH(vrdl, &container->vrdl_list, next) {
1430 if (vrdl->mr == section->mr &&
1431 vrdl->offset_within_address_space ==
1432 section->offset_within_address_space) {
1433 break;
1434 }
1435 }
1436
1437 if (!vrdl) {
1438 hw_error("vfio: Trying to sync missing RAM discard listener");
1439 }
1440
1441 /*
1442 * We only want/can synchronize the bitmap for actually mapped parts -
1443 * which correspond to populated parts. Replay all populated parts.
1444 */
1445 return ram_discard_manager_replay_populated(rdm, section,
1446 vfio_ram_discard_get_dirty_bitmap,
1447 &vrdl);
1448}
1449
b6dd6504
KW
1450static int vfio_sync_dirty_bitmap(VFIOContainer *container,
1451 MemoryRegionSection *section)
1452{
1453 ram_addr_t ram_addr;
1454
9a04fe09
KW
1455 if (memory_region_is_iommu(section->mr)) {
1456 VFIOGuestIOMMU *giommu;
1457
1458 QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
44ee6aaa 1459 if (MEMORY_REGION(giommu->iommu_mr) == section->mr &&
9a04fe09
KW
1460 giommu->n.start == section->offset_within_region) {
1461 Int128 llend;
1462 vfio_giommu_dirty_notifier gdn = { .giommu = giommu };
44ee6aaa 1463 int idx = memory_region_iommu_attrs_to_index(giommu->iommu_mr,
9a04fe09
KW
1464 MEMTXATTRS_UNSPECIFIED);
1465
1466 llend = int128_add(int128_make64(section->offset_within_region),
1467 section->size);
1468 llend = int128_sub(llend, int128_one());
1469
1470 iommu_notifier_init(&gdn.n,
1471 vfio_iommu_map_dirty_notify,
1472 IOMMU_NOTIFIER_MAP,
1473 section->offset_within_region,
1474 int128_get64(llend),
1475 idx);
44ee6aaa 1476 memory_region_iommu_replay(giommu->iommu_mr, &gdn.n);
9a04fe09
KW
1477 break;
1478 }
1479 }
1480 return 0;
5e3b981c
DH
1481 } else if (memory_region_has_ram_discard_manager(section->mr)) {
1482 return vfio_sync_ram_discard_listener_dirty_bitmap(container, section);
9a04fe09
KW
1483 }
1484
b6dd6504
KW
1485 ram_addr = memory_region_get_ram_addr(section->mr) +
1486 section->offset_within_region;
1487
1488 return vfio_get_dirty_bitmap(container,
1eb7f642
KJ
1489 REAL_HOST_PAGE_ALIGN(section->offset_within_address_space),
1490 int128_get64(section->size), ram_addr);
b6dd6504
KW
1491}
1492
4292d501 1493static void vfio_listener_log_sync(MemoryListener *listener,
b6dd6504
KW
1494 MemoryRegionSection *section)
1495{
1496 VFIOContainer *container = container_of(listener, VFIOContainer, listener);
1497
b051a3f6 1498 if (vfio_listener_skipped_section(section)) {
b6dd6504
KW
1499 return;
1500 }
1501
758b96b6 1502 if (vfio_devices_all_dirty_tracking(container)) {
b6dd6504
KW
1503 vfio_sync_dirty_bitmap(container, section);
1504 }
1505}
1506
51b833f4 1507static const MemoryListener vfio_memory_listener = {
142518bd 1508 .name = "vfio",
e2c7d025
EA
1509 .region_add = vfio_listener_region_add,
1510 .region_del = vfio_listener_region_del,
758b96b6
KZ
1511 .log_global_start = vfio_listener_log_global_start,
1512 .log_global_stop = vfio_listener_log_global_stop,
4292d501 1513 .log_sync = vfio_listener_log_sync,
e2c7d025
EA
1514};
1515
51b833f4 1516static void vfio_listener_release(VFIOContainer *container)
e2c7d025 1517{
ee0bf0e5 1518 memory_listener_unregister(&container->listener);
318f67ce
AK
1519 if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
1520 memory_listener_unregister(&container->prereg_listener);
1521 }
e2c7d025
EA
1522}
1523
3ab7a0b4
MR
1524static struct vfio_info_cap_header *
1525vfio_get_cap(void *ptr, uint32_t cap_offset, uint16_t id)
b53b0f69
AW
1526{
1527 struct vfio_info_cap_header *hdr;
b53b0f69 1528
3ab7a0b4 1529 for (hdr = ptr + cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
b53b0f69
AW
1530 if (hdr->id == id) {
1531 return hdr;
1532 }
1533 }
1534
1535 return NULL;
1536}
1537
3ab7a0b4
MR
1538struct vfio_info_cap_header *
1539vfio_get_region_info_cap(struct vfio_region_info *info, uint16_t id)
1540{
1541 if (!(info->flags & VFIO_REGION_INFO_FLAG_CAPS)) {
1542 return NULL;
1543 }
1544
1545 return vfio_get_cap((void *)info, info->cap_offset, id);
1546}
1547
7486a628
MR
1548static struct vfio_info_cap_header *
1549vfio_get_iommu_type1_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
1550{
1551 if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
1552 return NULL;
1553 }
1554
1555 return vfio_get_cap((void *)info, info->cap_offset, id);
1556}
1557
92fe289a
MR
1558struct vfio_info_cap_header *
1559vfio_get_device_info_cap(struct vfio_device_info *info, uint16_t id)
1560{
1561 if (!(info->flags & VFIO_DEVICE_FLAGS_CAPS)) {
1562 return NULL;
1563 }
1564
1565 return vfio_get_cap((void *)info, info->cap_offset, id);
1566}
1567
7486a628
MR
1568bool vfio_get_info_dma_avail(struct vfio_iommu_type1_info *info,
1569 unsigned int *avail)
1570{
1571 struct vfio_info_cap_header *hdr;
1572 struct vfio_iommu_type1_info_dma_avail *cap;
1573
1574 /* If the capability cannot be found, assume no DMA limiting */
1575 hdr = vfio_get_iommu_type1_info_cap(info,
1576 VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL);
1577 if (hdr == NULL) {
1578 return false;
1579 }
1580
1581 if (avail != NULL) {
1582 cap = (void *) hdr;
1583 *avail = cap->avail;
1584 }
1585
1586 return true;
1587}
1588
24acf72b
AW
1589static int vfio_setup_region_sparse_mmaps(VFIORegion *region,
1590 struct vfio_region_info *info)
b53b0f69
AW
1591{
1592 struct vfio_info_cap_header *hdr;
1593 struct vfio_region_info_cap_sparse_mmap *sparse;
24acf72b 1594 int i, j;
b53b0f69
AW
1595
1596 hdr = vfio_get_region_info_cap(info, VFIO_REGION_INFO_CAP_SPARSE_MMAP);
1597 if (!hdr) {
24acf72b 1598 return -ENODEV;
b53b0f69
AW
1599 }
1600
1601 sparse = container_of(hdr, struct vfio_region_info_cap_sparse_mmap, header);
1602
1603 trace_vfio_region_sparse_mmap_header(region->vbasedev->name,
1604 region->nr, sparse->nr_areas);
1605
24acf72b
AW
1606 region->mmaps = g_new0(VFIOMmap, sparse->nr_areas);
1607
1608 for (i = 0, j = 0; i < sparse->nr_areas; i++) {
24acf72b 1609 if (sparse->areas[i].size) {
99510d27
XC
1610 trace_vfio_region_sparse_mmap_entry(i, sparse->areas[i].offset,
1611 sparse->areas[i].offset +
1612 sparse->areas[i].size - 1);
24acf72b
AW
1613 region->mmaps[j].offset = sparse->areas[i].offset;
1614 region->mmaps[j].size = sparse->areas[i].size;
1615 j++;
1616 }
b53b0f69 1617 }
24acf72b
AW
1618
1619 region->nr_mmaps = j;
1620 region->mmaps = g_realloc(region->mmaps, j * sizeof(VFIOMmap));
1621
1622 return 0;
b53b0f69
AW
1623}
1624
db0da029
AW
1625int vfio_region_setup(Object *obj, VFIODevice *vbasedev, VFIORegion *region,
1626 int index, const char *name)
e2c7d025 1627{
db0da029
AW
1628 struct vfio_region_info *info;
1629 int ret;
1630
1631 ret = vfio_get_region_info(vbasedev, index, &info);
1632 if (ret) {
1633 return ret;
1634 }
1635
1636 region->vbasedev = vbasedev;
1637 region->flags = info->flags;
1638 region->size = info->size;
1639 region->fd_offset = info->offset;
1640 region->nr = index;
1641
1642 if (region->size) {
1643 region->mem = g_new0(MemoryRegion, 1);
1644 memory_region_init_io(region->mem, obj, &vfio_region_ops,
1645 region, name, region->size);
e2c7d025 1646
db0da029 1647 if (!vbasedev->no_mmap &&
95251725 1648 region->flags & VFIO_REGION_INFO_FLAG_MMAP) {
e2c7d025 1649
24acf72b 1650 ret = vfio_setup_region_sparse_mmaps(region, info);
db0da029 1651
24acf72b 1652 if (ret) {
b53b0f69
AW
1653 region->nr_mmaps = 1;
1654 region->mmaps = g_new0(VFIOMmap, region->nr_mmaps);
1655 region->mmaps[0].offset = 0;
1656 region->mmaps[0].size = region->size;
1657 }
e2c7d025 1658 }
db0da029
AW
1659 }
1660
1661 g_free(info);
1662
1663 trace_vfio_region_setup(vbasedev->name, index, name,
1664 region->flags, region->fd_offset, region->size);
1665 return 0;
1666}
e2c7d025 1667
0f7a903b
KW
1668static void vfio_subregion_unmap(VFIORegion *region, int index)
1669{
1670 trace_vfio_region_unmap(memory_region_name(&region->mmaps[index].mem),
1671 region->mmaps[index].offset,
1672 region->mmaps[index].offset +
1673 region->mmaps[index].size - 1);
1674 memory_region_del_subregion(region->mem, &region->mmaps[index].mem);
1675 munmap(region->mmaps[index].mmap, region->mmaps[index].size);
1676 object_unparent(OBJECT(&region->mmaps[index].mem));
1677 region->mmaps[index].mmap = NULL;
1678}
1679
db0da029
AW
1680int vfio_region_mmap(VFIORegion *region)
1681{
1682 int i, prot = 0;
1683 char *name;
1684
1685 if (!region->mem) {
1686 return 0;
1687 }
1688
1689 prot |= region->flags & VFIO_REGION_INFO_FLAG_READ ? PROT_READ : 0;
1690 prot |= region->flags & VFIO_REGION_INFO_FLAG_WRITE ? PROT_WRITE : 0;
1691
1692 for (i = 0; i < region->nr_mmaps; i++) {
1693 region->mmaps[i].mmap = mmap(NULL, region->mmaps[i].size, prot,
1694 MAP_SHARED, region->vbasedev->fd,
1695 region->fd_offset +
1696 region->mmaps[i].offset);
1697 if (region->mmaps[i].mmap == MAP_FAILED) {
1698 int ret = -errno;
1699
1700 trace_vfio_region_mmap_fault(memory_region_name(region->mem), i,
1701 region->fd_offset +
1702 region->mmaps[i].offset,
1703 region->fd_offset +
1704 region->mmaps[i].offset +
1705 region->mmaps[i].size - 1, ret);
1706
1707 region->mmaps[i].mmap = NULL;
1708
1709 for (i--; i >= 0; i--) {
0f7a903b 1710 vfio_subregion_unmap(region, i);
db0da029
AW
1711 }
1712
1713 return ret;
e2c7d025
EA
1714 }
1715
db0da029
AW
1716 name = g_strdup_printf("%s mmaps[%d]",
1717 memory_region_name(region->mem), i);
21e00fa5
AW
1718 memory_region_init_ram_device_ptr(&region->mmaps[i].mem,
1719 memory_region_owner(region->mem),
1720 name, region->mmaps[i].size,
1721 region->mmaps[i].mmap);
db0da029 1722 g_free(name);
db0da029
AW
1723 memory_region_add_subregion(region->mem, region->mmaps[i].offset,
1724 &region->mmaps[i].mem);
1725
1726 trace_vfio_region_mmap(memory_region_name(&region->mmaps[i].mem),
1727 region->mmaps[i].offset,
1728 region->mmaps[i].offset +
1729 region->mmaps[i].size - 1);
1730 }
1731
1732 return 0;
1733}
1734
0f7a903b
KW
1735void vfio_region_unmap(VFIORegion *region)
1736{
1737 int i;
1738
1739 if (!region->mem) {
1740 return;
1741 }
1742
1743 for (i = 0; i < region->nr_mmaps; i++) {
1744 if (region->mmaps[i].mmap) {
1745 vfio_subregion_unmap(region, i);
1746 }
1747 }
1748}
1749
db0da029
AW
1750void vfio_region_exit(VFIORegion *region)
1751{
1752 int i;
1753
1754 if (!region->mem) {
1755 return;
1756 }
1757
1758 for (i = 0; i < region->nr_mmaps; i++) {
1759 if (region->mmaps[i].mmap) {
1760 memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
e2c7d025 1761 }
db0da029 1762 }
e2c7d025 1763
db0da029
AW
1764 trace_vfio_region_exit(region->vbasedev->name, region->nr);
1765}
1766
1767void vfio_region_finalize(VFIORegion *region)
1768{
1769 int i;
1770
1771 if (!region->mem) {
1772 return;
e2c7d025
EA
1773 }
1774
db0da029
AW
1775 for (i = 0; i < region->nr_mmaps; i++) {
1776 if (region->mmaps[i].mmap) {
1777 munmap(region->mmaps[i].mmap, region->mmaps[i].size);
1778 object_unparent(OBJECT(&region->mmaps[i].mem));
1779 }
1780 }
1781
1782 object_unparent(OBJECT(region->mem));
1783
1784 g_free(region->mem);
1785 g_free(region->mmaps);
1786
1787 trace_vfio_region_finalize(region->vbasedev->name, region->nr);
92f86bff
GH
1788
1789 region->mem = NULL;
1790 region->mmaps = NULL;
1791 region->nr_mmaps = 0;
1792 region->size = 0;
1793 region->flags = 0;
1794 region->nr = 0;
db0da029
AW
1795}
1796
1797void vfio_region_mmaps_set_enabled(VFIORegion *region, bool enabled)
1798{
1799 int i;
1800
1801 if (!region->mem) {
1802 return;
1803 }
1804
1805 for (i = 0; i < region->nr_mmaps; i++) {
1806 if (region->mmaps[i].mmap) {
1807 memory_region_set_enabled(&region->mmaps[i].mem, enabled);
1808 }
1809 }
e2c7d025 1810
db0da029
AW
1811 trace_vfio_region_mmaps_set_enabled(memory_region_name(region->mem),
1812 enabled);
e2c7d025
EA
1813}
1814
1815void vfio_reset_handler(void *opaque)
1816{
1817 VFIOGroup *group;
1818 VFIODevice *vbasedev;
1819
1820 QLIST_FOREACH(group, &vfio_group_list, next) {
1821 QLIST_FOREACH(vbasedev, &group->device_list, next) {
7da624e2
AW
1822 if (vbasedev->dev->realized) {
1823 vbasedev->ops->vfio_compute_needs_reset(vbasedev);
1824 }
e2c7d025
EA
1825 }
1826 }
1827
1828 QLIST_FOREACH(group, &vfio_group_list, next) {
1829 QLIST_FOREACH(vbasedev, &group->device_list, next) {
7da624e2 1830 if (vbasedev->dev->realized && vbasedev->needs_reset) {
e2c7d025
EA
1831 vbasedev->ops->vfio_hot_reset_multi(vbasedev);
1832 }
1833 }
1834 }
1835}
1836
1837static void vfio_kvm_device_add_group(VFIOGroup *group)
1838{
1839#ifdef CONFIG_KVM
1840 struct kvm_device_attr attr = {
1841 .group = KVM_DEV_VFIO_GROUP,
1842 .attr = KVM_DEV_VFIO_GROUP_ADD,
1843 .addr = (uint64_t)(unsigned long)&group->fd,
1844 };
1845
1846 if (!kvm_enabled()) {
1847 return;
1848 }
1849
1850 if (vfio_kvm_device_fd < 0) {
1851 struct kvm_create_device cd = {
1852 .type = KVM_DEV_TYPE_VFIO,
1853 };
1854
1855 if (kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd)) {
78e5b17f 1856 error_report("Failed to create KVM VFIO device: %m");
e2c7d025
EA
1857 return;
1858 }
1859
1860 vfio_kvm_device_fd = cd.fd;
1861 }
1862
1863 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1864 error_report("Failed to add group %d to KVM VFIO device: %m",
1865 group->groupid);
1866 }
1867#endif
1868}
1869
1870static void vfio_kvm_device_del_group(VFIOGroup *group)
1871{
1872#ifdef CONFIG_KVM
1873 struct kvm_device_attr attr = {
1874 .group = KVM_DEV_VFIO_GROUP,
1875 .attr = KVM_DEV_VFIO_GROUP_DEL,
1876 .addr = (uint64_t)(unsigned long)&group->fd,
1877 };
1878
1879 if (vfio_kvm_device_fd < 0) {
1880 return;
1881 }
1882
1883 if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
1884 error_report("Failed to remove group %d from KVM VFIO device: %m",
1885 group->groupid);
1886 }
1887#endif
1888}
1889
1890static VFIOAddressSpace *vfio_get_address_space(AddressSpace *as)
1891{
1892 VFIOAddressSpace *space;
1893
1894 QLIST_FOREACH(space, &vfio_address_spaces, list) {
1895 if (space->as == as) {
1896 return space;
1897 }
1898 }
1899
1900 /* No suitable VFIOAddressSpace, create a new one */
1901 space = g_malloc0(sizeof(*space));
1902 space->as = as;
1903 QLIST_INIT(&space->containers);
1904
1905 QLIST_INSERT_HEAD(&vfio_address_spaces, space, list);
1906
1907 return space;
1908}
1909
1910static void vfio_put_address_space(VFIOAddressSpace *space)
1911{
1912 if (QLIST_EMPTY(&space->containers)) {
1913 QLIST_REMOVE(space, list);
1914 g_free(space);
1915 }
1916}
1917
2b6326c0
EA
1918/*
1919 * vfio_get_iommu_type - selects the richest iommu_type (v2 first)
1920 */
1921static int vfio_get_iommu_type(VFIOContainer *container,
1922 Error **errp)
1923{
1924 int iommu_types[] = { VFIO_TYPE1v2_IOMMU, VFIO_TYPE1_IOMMU,
1925 VFIO_SPAPR_TCE_v2_IOMMU, VFIO_SPAPR_TCE_IOMMU };
1926 int i;
1927
1928 for (i = 0; i < ARRAY_SIZE(iommu_types); i++) {
1929 if (ioctl(container->fd, VFIO_CHECK_EXTENSION, iommu_types[i])) {
1930 return iommu_types[i];
1931 }
1932 }
1933 error_setg(errp, "No available IOMMU models");
1934 return -EINVAL;
1935}
1936
1937static int vfio_init_container(VFIOContainer *container, int group_fd,
1938 Error **errp)
1939{
1940 int iommu_type, ret;
1941
1942 iommu_type = vfio_get_iommu_type(container, errp);
1943 if (iommu_type < 0) {
1944 return iommu_type;
1945 }
1946
1947 ret = ioctl(group_fd, VFIO_GROUP_SET_CONTAINER, &container->fd);
1948 if (ret) {
1949 error_setg_errno(errp, errno, "Failed to set group container");
1950 return -errno;
1951 }
1952
1953 while (ioctl(container->fd, VFIO_SET_IOMMU, iommu_type)) {
1954 if (iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
1955 /*
1956 * On sPAPR, despite the IOMMU subdriver always advertises v1 and
1957 * v2, the running platform may not support v2 and there is no
1958 * way to guess it until an IOMMU group gets added to the container.
1959 * So in case it fails with v2, try v1 as a fallback.
1960 */
1961 iommu_type = VFIO_SPAPR_TCE_IOMMU;
1962 continue;
1963 }
1964 error_setg_errno(errp, errno, "Failed to set iommu for container");
1965 return -errno;
1966 }
1967
1968 container->iommu_type = iommu_type;
1969 return 0;
1970}
1971
87ea529c
KW
1972static int vfio_get_iommu_info(VFIOContainer *container,
1973 struct vfio_iommu_type1_info **info)
1974{
1975
1976 size_t argsz = sizeof(struct vfio_iommu_type1_info);
1977
1978 *info = g_new0(struct vfio_iommu_type1_info, 1);
1979again:
1980 (*info)->argsz = argsz;
1981
1982 if (ioctl(container->fd, VFIO_IOMMU_GET_INFO, *info)) {
1983 g_free(*info);
1984 *info = NULL;
1985 return -errno;
1986 }
1987
1988 if (((*info)->argsz > argsz)) {
1989 argsz = (*info)->argsz;
1990 *info = g_realloc(*info, argsz);
1991 goto again;
1992 }
1993
1994 return 0;
1995}
1996
1997static struct vfio_info_cap_header *
1998vfio_get_iommu_info_cap(struct vfio_iommu_type1_info *info, uint16_t id)
1999{
2000 struct vfio_info_cap_header *hdr;
2001 void *ptr = info;
2002
2003 if (!(info->flags & VFIO_IOMMU_INFO_CAPS)) {
2004 return NULL;
2005 }
2006
2007 for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
2008 if (hdr->id == id) {
2009 return hdr;
2010 }
2011 }
2012
2013 return NULL;
2014}
2015
2016static void vfio_get_iommu_info_migration(VFIOContainer *container,
2017 struct vfio_iommu_type1_info *info)
2018{
2019 struct vfio_info_cap_header *hdr;
2020 struct vfio_iommu_type1_info_cap_migration *cap_mig;
2021
2022 hdr = vfio_get_iommu_info_cap(info, VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION);
2023 if (!hdr) {
2024 return;
2025 }
2026
2027 cap_mig = container_of(hdr, struct vfio_iommu_type1_info_cap_migration,
2028 header);
2029
2030 /*
1eb7f642
KJ
2031 * cpu_physical_memory_set_dirty_lebitmap() supports pages in bitmap of
2032 * qemu_real_host_page_size to mark those dirty.
87ea529c 2033 */
8e3b0cbb 2034 if (cap_mig->pgsize_bitmap & qemu_real_host_page_size()) {
87ea529c
KW
2035 container->dirty_pages_supported = true;
2036 container->max_dirty_bitmap_size = cap_mig->max_dirty_bitmap_size;
2037 container->dirty_pgsizes = cap_mig->pgsize_bitmap;
2038 }
2039}
2040
01905f58
EA
2041static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
2042 Error **errp)
e2c7d025
EA
2043{
2044 VFIOContainer *container;
2045 int ret, fd;
2046 VFIOAddressSpace *space;
2047
2048 space = vfio_get_address_space(as);
2049
c65ee433 2050 /*
aff92b82 2051 * VFIO is currently incompatible with discarding of RAM insofar as the
c65ee433
AW
2052 * madvise to purge (zap) the page from QEMU's address space does not
2053 * interact with the memory API and therefore leaves stale virtual to
2054 * physical mappings in the IOMMU if the page was previously pinned. We
aff92b82 2055 * therefore set discarding broken for each group added to a container,
c65ee433
AW
2056 * whether the container is used individually or shared. This provides
2057 * us with options to allow devices within a group to opt-in and allow
aff92b82 2058 * discarding, so long as it is done consistently for a group (for instance
c65ee433
AW
2059 * if the device is an mdev device where it is known that the host vendor
2060 * driver will never pin pages outside of the working set of the guest
aff92b82 2061 * driver, which would thus not be discarding candidates).
c65ee433
AW
2062 *
2063 * The first opportunity to induce pinning occurs here where we attempt to
2064 * attach the group to existing containers within the AddressSpace. If any
aff92b82
DH
2065 * pages are already zapped from the virtual address space, such as from
2066 * previous discards, new pinning will cause valid mappings to be
c65ee433
AW
2067 * re-established. Likewise, when the overall MemoryListener for a new
2068 * container is registered, a replay of mappings within the AddressSpace
2069 * will occur, re-establishing any previously zapped pages as well.
2070 *
aff92b82
DH
2071 * Especially virtio-balloon is currently only prevented from discarding
2072 * new memory, it will not yet set ram_block_discard_set_required() and
2073 * therefore, neither stops us here or deals with the sudden memory
2074 * consumption of inflated memory.
53d1b5fc
DH
2075 *
2076 * We do support discarding of memory coordinated via the RamDiscardManager
2077 * with some IOMMU types. vfio_ram_block_discard_disable() handles the
2078 * details once we know which type of IOMMU we are using.
c65ee433 2079 */
c65ee433 2080
e2c7d025
EA
2081 QLIST_FOREACH(container, &space->containers, next) {
2082 if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
53d1b5fc
DH
2083 ret = vfio_ram_block_discard_disable(container, true);
2084 if (ret) {
2085 error_setg_errno(errp, -ret,
2086 "Cannot set discarding of RAM broken");
2087 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER,
2088 &container->fd)) {
2089 error_report("vfio: error disconnecting group %d from"
2090 " container", group->groupid);
2091 }
2092 return ret;
2093 }
e2c7d025
EA
2094 group->container = container;
2095 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
2016986a 2096 vfio_kvm_device_add_group(group);
e2c7d025
EA
2097 return 0;
2098 }
2099 }
2100
448058aa 2101 fd = qemu_open_old("/dev/vfio/vfio", O_RDWR);
e2c7d025 2102 if (fd < 0) {
01905f58 2103 error_setg_errno(errp, errno, "failed to open /dev/vfio/vfio");
e2c7d025
EA
2104 ret = -errno;
2105 goto put_space_exit;
2106 }
2107
2108 ret = ioctl(fd, VFIO_GET_API_VERSION);
2109 if (ret != VFIO_API_VERSION) {
01905f58
EA
2110 error_setg(errp, "supported vfio version: %d, "
2111 "reported version: %d", VFIO_API_VERSION, ret);
e2c7d025
EA
2112 ret = -EINVAL;
2113 goto close_fd_exit;
2114 }
2115
2116 container = g_malloc0(sizeof(*container));
2117 container->space = space;
2118 container->fd = fd;
d7d87836 2119 container->error = NULL;
87ea529c 2120 container->dirty_pages_supported = false;
3eed155c 2121 container->dma_max_mappings = 0;
f7f9c7b2
LY
2122 QLIST_INIT(&container->giommu_list);
2123 QLIST_INIT(&container->hostwin_list);
5e3b981c 2124 QLIST_INIT(&container->vrdl_list);
2e6e697e 2125
2b6326c0
EA
2126 ret = vfio_init_container(container, group->fd, errp);
2127 if (ret) {
2128 goto free_container_exit;
2129 }
e2c7d025 2130
53d1b5fc
DH
2131 ret = vfio_ram_block_discard_disable(container, true);
2132 if (ret) {
2133 error_setg_errno(errp, -ret, "Cannot set discarding of RAM broken");
2134 goto free_container_exit;
2135 }
2136
2b6326c0
EA
2137 switch (container->iommu_type) {
2138 case VFIO_TYPE1v2_IOMMU:
2139 case VFIO_TYPE1_IOMMU:
2140 {
87ea529c 2141 struct vfio_iommu_type1_info *info;
3898aad3 2142
87ea529c 2143 ret = vfio_get_iommu_info(container, &info);
85b6d2b5
AW
2144 if (ret) {
2145 error_setg_errno(errp, -ret, "Failed to get VFIO IOMMU info");
2146 goto enable_discards_exit;
2147 }
87ea529c 2148
85b6d2b5
AW
2149 if (info->flags & VFIO_IOMMU_INFO_PGSIZES) {
2150 container->pgsizes = info->iova_pgsizes;
2151 } else {
2152 container->pgsizes = qemu_real_host_page_size();
87ea529c 2153 }
85b6d2b5
AW
2154
2155 if (!vfio_get_info_dma_avail(info, &container->dma_max_mappings)) {
2156 container->dma_max_mappings = 65535;
7a140a57 2157 }
85b6d2b5 2158 vfio_get_iommu_info_migration(container, info);
87ea529c 2159 g_free(info);
85b6d2b5
AW
2160
2161 /*
2162 * FIXME: We should parse VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE
2163 * information to get the actual window extent rather than assume
2164 * a 64-bit IOVA address space.
2165 */
2166 vfio_host_win_add(container, 0, (hwaddr)-1, container->pgsizes);
2167
2b6326c0
EA
2168 break;
2169 }
2170 case VFIO_SPAPR_TCE_v2_IOMMU:
2171 case VFIO_SPAPR_TCE_IOMMU:
2172 {
3898aad3 2173 struct vfio_iommu_spapr_tce_info info;
2b6326c0 2174 bool v2 = container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU;
e2c7d025
EA
2175
2176 /*
2177 * The host kernel code implementing VFIO_IOMMU_DISABLE is called
2178 * when container fd is closed so we do not call it explicitly
2179 * in this file.
2180 */
318f67ce
AK
2181 if (!v2) {
2182 ret = ioctl(fd, VFIO_IOMMU_ENABLE);
2183 if (ret) {
01905f58 2184 error_setg_errno(errp, errno, "failed to enable container");
318f67ce 2185 ret = -errno;
53d1b5fc 2186 goto enable_discards_exit;
318f67ce
AK
2187 }
2188 } else {
2189 container->prereg_listener = vfio_prereg_listener;
2190
2191 memory_listener_register(&container->prereg_listener,
2192 &address_space_memory);
2193 if (container->error) {
2194 memory_listener_unregister(&container->prereg_listener);
d7d87836
EA
2195 ret = -1;
2196 error_propagate_prepend(errp, container->error,
2197 "RAM memory listener initialization failed: ");
53d1b5fc 2198 goto enable_discards_exit;
318f67ce 2199 }
e2c7d025 2200 }
3898aad3 2201
3898aad3
DG
2202 info.argsz = sizeof(info);
2203 ret = ioctl(fd, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info);
2204 if (ret) {
01905f58
EA
2205 error_setg_errno(errp, errno,
2206 "VFIO_IOMMU_SPAPR_TCE_GET_INFO failed");
3898aad3 2207 ret = -errno;
318f67ce
AK
2208 if (v2) {
2209 memory_listener_unregister(&container->prereg_listener);
2210 }
53d1b5fc 2211 goto enable_discards_exit;
3898aad3 2212 }
7a140a57 2213
2e4109de 2214 if (v2) {
c26bc185 2215 container->pgsizes = info.ddw.pgsizes;
2e4109de
AK
2216 /*
2217 * There is a default window in just created container.
2218 * To make region_add/del simpler, we better remove this
2219 * window now and let those iommu_listener callbacks
2220 * create/remove them when needed.
2221 */
2222 ret = vfio_spapr_remove_window(container, info.dma32_window_start);
2223 if (ret) {
01905f58
EA
2224 error_setg_errno(errp, -ret,
2225 "failed to remove existing window");
53d1b5fc 2226 goto enable_discards_exit;
2e4109de
AK
2227 }
2228 } else {
2229 /* The default table uses 4K pages */
c26bc185 2230 container->pgsizes = 0x1000;
2e4109de
AK
2231 vfio_host_win_add(container, info.dma32_window_start,
2232 info.dma32_window_start +
2233 info.dma32_window_size - 1,
2234 0x1000);
2235 }
2b6326c0 2236 }
e2c7d025
EA
2237 }
2238
8c37faa4
AK
2239 vfio_kvm_device_add_group(group);
2240
2241 QLIST_INIT(&container->group_list);
2242 QLIST_INSERT_HEAD(&space->containers, container, next);
2243
2244 group->container = container;
2245 QLIST_INSERT_HEAD(&container->group_list, group, container_next);
2246
ee0bf0e5
DG
2247 container->listener = vfio_memory_listener;
2248
2249 memory_listener_register(&container->listener, container->space->as);
2250
2251 if (container->error) {
d7d87836
EA
2252 ret = -1;
2253 error_propagate_prepend(errp, container->error,
2254 "memory listener initialization failed: ");
ee0bf0e5
DG
2255 goto listener_release_exit;
2256 }
2257
2258 container->initialized = true;
2259
e2c7d025
EA
2260 return 0;
2261listener_release_exit:
8c37faa4
AK
2262 QLIST_REMOVE(group, container_next);
2263 QLIST_REMOVE(container, next);
2264 vfio_kvm_device_del_group(group);
e2c7d025
EA
2265 vfio_listener_release(container);
2266
53d1b5fc
DH
2267enable_discards_exit:
2268 vfio_ram_block_discard_disable(container, false);
2269
e2c7d025
EA
2270free_container_exit:
2271 g_free(container);
2272
2273close_fd_exit:
2274 close(fd);
2275
2276put_space_exit:
2277 vfio_put_address_space(space);
2278
2279 return ret;
2280}
2281
2282static void vfio_disconnect_container(VFIOGroup *group)
2283{
2284 VFIOContainer *container = group->container;
2285
36968626
PX
2286 QLIST_REMOVE(group, container_next);
2287 group->container = NULL;
2288
2289 /*
2290 * Explicitly release the listener first before unset container,
2291 * since unset may destroy the backend container if it's the last
2292 * group.
2293 */
2294 if (QLIST_EMPTY(&container->group_list)) {
2295 vfio_listener_release(container);
2296 }
2297
e2c7d025
EA
2298 if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
2299 error_report("vfio: error disconnecting group %d from container",
2300 group->groupid);
2301 }
2302
e2c7d025
EA
2303 if (QLIST_EMPTY(&container->group_list)) {
2304 VFIOAddressSpace *space = container->space;
f8d8a944 2305 VFIOGuestIOMMU *giommu, *tmp;
f3bc3a73 2306 VFIOHostDMAWindow *hostwin, *next;
e2c7d025 2307
e2c7d025 2308 QLIST_REMOVE(container, next);
f8d8a944
AK
2309
2310 QLIST_FOREACH_SAFE(giommu, &container->giommu_list, giommu_next, tmp) {
3df9d748 2311 memory_region_unregister_iommu_notifier(
44ee6aaa 2312 MEMORY_REGION(giommu->iommu_mr), &giommu->n);
f8d8a944
AK
2313 QLIST_REMOVE(giommu, giommu_next);
2314 g_free(giommu);
2315 }
2316
f3bc3a73
PL
2317 QLIST_FOREACH_SAFE(hostwin, &container->hostwin_list, hostwin_next,
2318 next) {
2319 QLIST_REMOVE(hostwin, hostwin_next);
2320 g_free(hostwin);
2321 }
2322
e2c7d025
EA
2323 trace_vfio_disconnect_container(container->fd);
2324 close(container->fd);
2325 g_free(container);
2326
2327 vfio_put_address_space(space);
2328 }
2329}
2330
1b808d5b 2331VFIOGroup *vfio_get_group(int groupid, AddressSpace *as, Error **errp)
e2c7d025
EA
2332{
2333 VFIOGroup *group;
2334 char path[32];
2335 struct vfio_group_status status = { .argsz = sizeof(status) };
2336
2337 QLIST_FOREACH(group, &vfio_group_list, next) {
2338 if (group->groupid == groupid) {
2339 /* Found it. Now is it already in the right context? */
2340 if (group->container->space->as == as) {
2341 return group;
2342 } else {
1b808d5b
EA
2343 error_setg(errp, "group %d used in multiple address spaces",
2344 group->groupid);
e2c7d025
EA
2345 return NULL;
2346 }
2347 }
2348 }
2349
2350 group = g_malloc0(sizeof(*group));
2351
2352 snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
448058aa 2353 group->fd = qemu_open_old(path, O_RDWR);
e2c7d025 2354 if (group->fd < 0) {
1b808d5b 2355 error_setg_errno(errp, errno, "failed to open %s", path);
e2c7d025
EA
2356 goto free_group_exit;
2357 }
2358
2359 if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
1b808d5b 2360 error_setg_errno(errp, errno, "failed to get group %d status", groupid);
e2c7d025
EA
2361 goto close_fd_exit;
2362 }
2363
2364 if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
1b808d5b
EA
2365 error_setg(errp, "group %d is not viable", groupid);
2366 error_append_hint(errp,
2367 "Please ensure all devices within the iommu_group "
2368 "are bound to their vfio bus driver.\n");
e2c7d025
EA
2369 goto close_fd_exit;
2370 }
2371
2372 group->groupid = groupid;
2373 QLIST_INIT(&group->device_list);
2374
1b808d5b
EA
2375 if (vfio_connect_container(group, as, errp)) {
2376 error_prepend(errp, "failed to setup container for group %d: ",
2377 groupid);
e2c7d025
EA
2378 goto close_fd_exit;
2379 }
2380
2381 if (QLIST_EMPTY(&vfio_group_list)) {
2382 qemu_register_reset(vfio_reset_handler, NULL);
2383 }
2384
2385 QLIST_INSERT_HEAD(&vfio_group_list, group, next);
2386
e2c7d025
EA
2387 return group;
2388
2389close_fd_exit:
2390 close(group->fd);
2391
2392free_group_exit:
2393 g_free(group);
2394
2395 return NULL;
2396}
2397
2398void vfio_put_group(VFIOGroup *group)
2399{
77a10d04 2400 if (!group || !QLIST_EMPTY(&group->device_list)) {
e2c7d025
EA
2401 return;
2402 }
2403
aff92b82 2404 if (!group->ram_block_discard_allowed) {
53d1b5fc 2405 vfio_ram_block_discard_disable(group->container, false);
238e9172 2406 }
e2c7d025
EA
2407 vfio_kvm_device_del_group(group);
2408 vfio_disconnect_container(group);
2409 QLIST_REMOVE(group, next);
2410 trace_vfio_put_group(group->fd);
2411 close(group->fd);
2412 g_free(group);
2413
2414 if (QLIST_EMPTY(&vfio_group_list)) {
2415 qemu_unregister_reset(vfio_reset_handler, NULL);
2416 }
2417}
2418
2419int vfio_get_device(VFIOGroup *group, const char *name,
59f7d674 2420 VFIODevice *vbasedev, Error **errp)
e2c7d025
EA
2421{
2422 struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
217e9fdc 2423 int ret, fd;
e2c7d025 2424
217e9fdc
PB
2425 fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
2426 if (fd < 0) {
59f7d674
EA
2427 error_setg_errno(errp, errno, "error getting device from group %d",
2428 group->groupid);
2429 error_append_hint(errp,
2430 "Verify all devices in group %d are bound to vfio-<bus> "
2431 "or pci-stub and not already in use\n", group->groupid);
217e9fdc 2432 return fd;
e2c7d025
EA
2433 }
2434
217e9fdc 2435 ret = ioctl(fd, VFIO_DEVICE_GET_INFO, &dev_info);
e2c7d025 2436 if (ret) {
59f7d674 2437 error_setg_errno(errp, errno, "error getting device info");
217e9fdc
PB
2438 close(fd);
2439 return ret;
e2c7d025
EA
2440 }
2441
238e9172 2442 /*
aff92b82
DH
2443 * Set discarding of RAM as not broken for this group if the driver knows
2444 * the device operates compatibly with discarding. Setting must be
2445 * consistent per group, but since compatibility is really only possible
2446 * with mdev currently, we expect singleton groups.
238e9172 2447 */
aff92b82
DH
2448 if (vbasedev->ram_block_discard_allowed !=
2449 group->ram_block_discard_allowed) {
238e9172 2450 if (!QLIST_EMPTY(&group->device_list)) {
aff92b82
DH
2451 error_setg(errp, "Inconsistent setting of support for discarding "
2452 "RAM (e.g., balloon) within group");
8709b395 2453 close(fd);
238e9172
AW
2454 return -1;
2455 }
2456
aff92b82
DH
2457 if (!group->ram_block_discard_allowed) {
2458 group->ram_block_discard_allowed = true;
53d1b5fc 2459 vfio_ram_block_discard_disable(group->container, false);
238e9172
AW
2460 }
2461 }
2462
217e9fdc
PB
2463 vbasedev->fd = fd;
2464 vbasedev->group = group;
2465 QLIST_INSERT_HEAD(&group->device_list, vbasedev, next);
2466
e2c7d025
EA
2467 vbasedev->num_irqs = dev_info.num_irqs;
2468 vbasedev->num_regions = dev_info.num_regions;
2469 vbasedev->flags = dev_info.flags;
2470
2471 trace_vfio_get_device(name, dev_info.flags, dev_info.num_regions,
2472 dev_info.num_irqs);
2473
2474 vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
217e9fdc 2475 return 0;
e2c7d025
EA
2476}
2477
2478void vfio_put_base_device(VFIODevice *vbasedev)
2479{
77a10d04
PB
2480 if (!vbasedev->group) {
2481 return;
2482 }
e2c7d025
EA
2483 QLIST_REMOVE(vbasedev, next);
2484 vbasedev->group = NULL;
2485 trace_vfio_put_base_device(vbasedev->fd);
2486 close(vbasedev->fd);
2487}
2488
46900226
AW
2489int vfio_get_region_info(VFIODevice *vbasedev, int index,
2490 struct vfio_region_info **info)
2491{
2492 size_t argsz = sizeof(struct vfio_region_info);
2493
2494 *info = g_malloc0(argsz);
2495
2496 (*info)->index = index;
b53b0f69 2497retry:
46900226
AW
2498 (*info)->argsz = argsz;
2499
2500 if (ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, *info)) {
2501 g_free(*info);
e61a424f 2502 *info = NULL;
46900226
AW
2503 return -errno;
2504 }
2505
b53b0f69
AW
2506 if ((*info)->argsz > argsz) {
2507 argsz = (*info)->argsz;
2508 *info = g_realloc(*info, argsz);
2509
2510 goto retry;
2511 }
2512
46900226
AW
2513 return 0;
2514}
2515
e61a424f
AW
2516int vfio_get_dev_region_info(VFIODevice *vbasedev, uint32_t type,
2517 uint32_t subtype, struct vfio_region_info **info)
2518{
2519 int i;
2520
2521 for (i = 0; i < vbasedev->num_regions; i++) {
2522 struct vfio_info_cap_header *hdr;
2523 struct vfio_region_info_cap_type *cap_type;
2524
2525 if (vfio_get_region_info(vbasedev, i, info)) {
2526 continue;
2527 }
2528
2529 hdr = vfio_get_region_info_cap(*info, VFIO_REGION_INFO_CAP_TYPE);
2530 if (!hdr) {
2531 g_free(*info);
2532 continue;
2533 }
2534
2535 cap_type = container_of(hdr, struct vfio_region_info_cap_type, header);
2536
2537 trace_vfio_get_dev_region(vbasedev->name, i,
2538 cap_type->type, cap_type->subtype);
2539
2540 if (cap_type->type == type && cap_type->subtype == subtype) {
2541 return 0;
2542 }
2543
2544 g_free(*info);
2545 }
2546
2547 *info = NULL;
2548 return -ENODEV;
2549}
2550
ae0215b2
AK
2551bool vfio_has_region_cap(VFIODevice *vbasedev, int region, uint16_t cap_type)
2552{
2553 struct vfio_region_info *info = NULL;
2554 bool ret = false;
2555
2556 if (!vfio_get_region_info(vbasedev, region, &info)) {
2557 if (vfio_get_region_info_cap(info, cap_type)) {
2558 ret = true;
2559 }
2560 g_free(info);
2561 }
2562
2563 return ret;
2564}
2565
3153119e
DG
2566/*
2567 * Interfaces for IBM EEH (Enhanced Error Handling)
2568 */
2569static bool vfio_eeh_container_ok(VFIOContainer *container)
2570{
2571 /*
2572 * As of 2016-03-04 (linux-4.5) the host kernel EEH/VFIO
2573 * implementation is broken if there are multiple groups in a
2574 * container. The hardware works in units of Partitionable
2575 * Endpoints (== IOMMU groups) and the EEH operations naively
2576 * iterate across all groups in the container, without any logic
2577 * to make sure the groups have their state synchronized. For
2578 * certain operations (ENABLE) that might be ok, until an error
2579 * occurs, but for others (GET_STATE) it's clearly broken.
2580 */
2581
2582 /*
2583 * XXX Once fixed kernels exist, test for them here
2584 */
2585
2586 if (QLIST_EMPTY(&container->group_list)) {
2587 return false;
2588 }
2589
2590 if (QLIST_NEXT(QLIST_FIRST(&container->group_list), container_next)) {
2591 return false;
2592 }
2593
2594 return true;
2595}
2596
2597static int vfio_eeh_container_op(VFIOContainer *container, uint32_t op)
2598{
2599 struct vfio_eeh_pe_op pe_op = {
2600 .argsz = sizeof(pe_op),
2601 .op = op,
2602 };
2603 int ret;
2604
2605 if (!vfio_eeh_container_ok(container)) {
2606 error_report("vfio/eeh: EEH_PE_OP 0x%x: "
2607 "kernel requires a container with exactly one group", op);
2608 return -EPERM;
2609 }
2610
2611 ret = ioctl(container->fd, VFIO_EEH_PE_OP, &pe_op);
2612 if (ret < 0) {
2613 error_report("vfio/eeh: EEH_PE_OP 0x%x failed: %m", op);
2614 return -errno;
2615 }
2616
d917e88d 2617 return ret;
3153119e
DG
2618}
2619
2620static VFIOContainer *vfio_eeh_as_container(AddressSpace *as)
2621{
2622 VFIOAddressSpace *space = vfio_get_address_space(as);
2623 VFIOContainer *container = NULL;
2624
2625 if (QLIST_EMPTY(&space->containers)) {
2626 /* No containers to act on */
2627 goto out;
2628 }
2629
2630 container = QLIST_FIRST(&space->containers);
2631
2632 if (QLIST_NEXT(container, next)) {
2633 /* We don't yet have logic to synchronize EEH state across
2634 * multiple containers */
2635 container = NULL;
2636 goto out;
2637 }
2638
2639out:
2640 vfio_put_address_space(space);
2641 return container;
2642}
2643
2644bool vfio_eeh_as_ok(AddressSpace *as)
2645{
2646 VFIOContainer *container = vfio_eeh_as_container(as);
2647
2648 return (container != NULL) && vfio_eeh_container_ok(container);
2649}
2650
2651int vfio_eeh_as_op(AddressSpace *as, uint32_t op)
2652{
2653 VFIOContainer *container = vfio_eeh_as_container(as);
2654
2655 if (!container) {
2656 return -ENODEV;
2657 }
2658 return vfio_eeh_container_op(container, op);
2659}