master
c 870 lines 26 KB
Raw
1 /*
2 * VFIO utility
3 *
4 * Copyright 2016 - 2018 Red Hat, Inc.
5 *
6 * Authors:
7 * Fam Zheng <famz@redhat.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
10 * See the COPYING file in the top-level directory.
11 */
12
13 #include "qemu/osdep.h"
14 #include <sys/ioctl.h>
15 #include <linux/vfio.h>
16 #include "qapi/error.h"
17 #include "system/ramlist.h"
18 #include "exec/cpu-common.h"
19 #include "system/memory.h"
20 #include "trace.h"
21 #include "qemu/error-report.h"
22 #include "standard-headers/linux/pci_regs.h"
23 #include "qemu/event_notifier.h"
24 #include "qemu/vfio-helpers.h"
25 #include "qemu/lockable.h"
26 #include "trace.h"
27
28 #define QEMU_VFIO_DEBUG 0
29
30 #define QEMU_VFIO_IOVA_MIN 0x10000ULL
31 /* XXX: Once VFIO exposes the iova bit width in the IOMMU capability interface,
32 * we can use a runtime limit; alternatively it's also possible to do platform
33 * specific detection by reading sysfs entries. Until then, 39 is a safe bet.
34 **/
35 #define QEMU_VFIO_IOVA_MAX (1ULL << 39)
36
37 typedef struct {
38 /* Page aligned addr. */
39 void *host;
40 size_t size;
41 uint64_t iova;
42 } IOVAMapping;
43
44 struct IOVARange {
45 uint64_t start;
46 uint64_t end;
47 };
48
49 struct QEMUVFIOState {
50 QemuMutex lock;
51
52 /* These fields are protected by BQL */
53 int container;
54 int group;
55 int device;
56 RAMBlockNotifier ram_notifier;
57 struct vfio_region_info config_region_info, bar_region_info[6];
58 struct IOVARange *usable_iova_ranges;
59 uint8_t nb_iova_ranges;
60
61 /* These fields are protected by @lock */
62 /* VFIO's IO virtual address space is managed by splitting into a few
63 * sections:
64 *
65 * --------------- <= 0
66 * |xxxxxxxxxxxxx|
67 * |-------------| <= QEMU_VFIO_IOVA_MIN
68 * | |
69 * | Fixed |
70 * | |
71 * |-------------| <= low_water_mark
72 * | |
73 * | Free |
74 * | |
75 * |-------------| <= high_water_mark
76 * | |
77 * | Temp |
78 * | |
79 * |-------------| <= QEMU_VFIO_IOVA_MAX
80 * |xxxxxxxxxxxxx|
81 * |xxxxxxxxxxxxx|
82 * ---------------
83 *
84 * - Addresses lower than QEMU_VFIO_IOVA_MIN are reserved as invalid;
85 *
86 * - Fixed mappings of HVAs are assigned "low" IOVAs in the range of
87 * [QEMU_VFIO_IOVA_MIN, low_water_mark). Once allocated they will not be
88 * reclaimed - low_water_mark never shrinks;
89 *
90 * - IOVAs in range [low_water_mark, high_water_mark) are free;
91 *
92 * - IOVAs in range [high_water_mark, QEMU_VFIO_IOVA_MAX) are volatile
93 * mappings. At each qemu_vfio_dma_reset_temporary() call, the whole area
94 * is recycled. The caller should make sure I/O's depending on these
95 * mappings are completed before calling.
96 **/
97 uint64_t low_water_mark;
98 uint64_t high_water_mark;
99 IOVAMapping *mappings;
100 int nr_mappings;
101 };
102
103 /**
104 * Find group file by PCI device address as specified @device, and return the
105 * path. The returned string is owned by caller and should be g_free'ed later.
106 */
107 static char *sysfs_find_group_file(const char *device, Error **errp)
108 {
109 g_autoptr(GError) gerr = NULL;
110 char *sysfs_link;
111 char *sysfs_group;
112 char *p;
113 char *path = NULL;
114
115 sysfs_link = g_strdup_printf("/sys/bus/pci/devices/%s/iommu_group", device);
116 sysfs_group = g_file_read_link(sysfs_link, &gerr);
117 if (gerr) {
118 error_setg(errp, "Failed to find iommu group sysfs path: %s",
119 gerr->message);
120 goto out;
121 }
122 p = strrchr(sysfs_group, '/');
123 if (!p) {
124 error_setg(errp, "Failed to find iommu group number");
125 goto out;
126 }
127
128 path = g_strdup_printf("/dev/vfio/%s", p + 1);
129 out:
130 g_free(sysfs_link);
131 g_free(sysfs_group);
132 return path;
133 }
134
135 static inline void assert_bar_index_valid(QEMUVFIOState *s, int index)
136 {
137 assert(index >= 0 && index < ARRAY_SIZE(s->bar_region_info));
138 }
139
140 static int qemu_vfio_pci_init_bar(QEMUVFIOState *s, int index, Error **errp)
141 {
142 g_autofree char *barname = NULL;
143 assert_bar_index_valid(s, index);
144 s->bar_region_info[index] = (struct vfio_region_info) {
145 .index = VFIO_PCI_BAR0_REGION_INDEX + index,
146 .argsz = sizeof(struct vfio_region_info),
147 };
148 if (ioctl(s->device, VFIO_DEVICE_GET_REGION_INFO, &s->bar_region_info[index])) {
149 error_setg_errno(errp, errno, "Failed to get BAR region info");
150 return -errno;
151 }
152 barname = g_strdup_printf("bar[%d]", index);
153 trace_qemu_vfio_region_info(barname, s->bar_region_info[index].offset,
154 s->bar_region_info[index].size,
155 s->bar_region_info[index].cap_offset);
156
157 return 0;
158 }
159
160 /**
161 * Map a PCI bar area.
162 */
163 void *qemu_vfio_pci_map_bar(QEMUVFIOState *s, int index,
164 uint64_t offset, uint64_t size, int prot,
165 Error **errp)
166 {
167 void *p;
168 assert(QEMU_IS_ALIGNED(offset, qemu_real_host_page_size()));
169 assert_bar_index_valid(s, index);
170 p = mmap(NULL, MIN(size, s->bar_region_info[index].size - offset),
171 prot, MAP_SHARED,
172 s->device, s->bar_region_info[index].offset + offset);
173 trace_qemu_vfio_pci_map_bar(index, s->bar_region_info[index].offset ,
174 size, offset, p);
175 if (p == MAP_FAILED) {
176 error_setg_errno(errp, errno, "Failed to map BAR region");
177 p = NULL;
178 }
179 return p;
180 }
181
182 /**
183 * Unmap a PCI bar area.
184 */
185 void qemu_vfio_pci_unmap_bar(QEMUVFIOState *s, int index, void *bar,
186 uint64_t offset, uint64_t size)
187 {
188 if (bar) {
189 munmap(bar, MIN(size, s->bar_region_info[index].size - offset));
190 }
191 }
192
193 /**
194 * Initialize device IRQ with @irq_type and register an event notifier.
195 */
196 int qemu_vfio_pci_init_irq(QEMUVFIOState *s, EventNotifier *e,
197 int irq_type, Error **errp)
198 {
199 int r;
200 struct vfio_irq_set *irq_set;
201 size_t irq_set_size;
202 struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };
203
204 irq_info.index = irq_type;
205 if (ioctl(s->device, VFIO_DEVICE_GET_IRQ_INFO, &irq_info)) {
206 error_setg_errno(errp, errno, "Failed to get device interrupt info");
207 return -errno;
208 }
209 if (!(irq_info.flags & VFIO_IRQ_INFO_EVENTFD)) {
210 error_setg(errp, "Device interrupt doesn't support eventfd");
211 return -EINVAL;
212 }
213
214 irq_set_size = sizeof(*irq_set) + sizeof(int);
215 irq_set = g_malloc0(irq_set_size);
216
217 /* Get to a known IRQ state */
218 *irq_set = (struct vfio_irq_set) {
219 .argsz = irq_set_size,
220 .flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER,
221 .index = irq_info.index,
222 .start = 0,
223 .count = 1,
224 };
225
226 *(int *)&irq_set->data = event_notifier_get_fd(e);
227 r = ioctl(s->device, VFIO_DEVICE_SET_IRQS, irq_set);
228 g_free(irq_set);
229 if (r) {
230 error_setg_errno(errp, errno, "Failed to setup device interrupt");
231 return -errno;
232 }
233 return 0;
234 }
235
236 static int qemu_vfio_pci_read_config(QEMUVFIOState *s, uint32_t *buf,
237 int size, int ofs)
238 {
239 int ret;
240 uint32_t val_le;
241
242 trace_qemu_vfio_pci_read_config(buf, ofs, size,
243 s->config_region_info.offset,
244 s->config_region_info.size);
245 assert(QEMU_IS_ALIGNED(s->config_region_info.offset + ofs, size));
246 ret = RETRY_ON_EINTR(
247 pread(s->device, &val_le, size, s->config_region_info.offset + ofs)
248 );
249
250 *buf = le32_to_cpu(val_le);
251 return ret == size ? 0 : -errno;
252 }
253
254 static int qemu_vfio_pci_write_config(QEMUVFIOState *s, uint32_t *buf, int size, int ofs)
255 {
256 int ret;
257 uint32_t val_le;
258
259 val_le = cpu_to_le32(*buf);
260 trace_qemu_vfio_pci_write_config(buf, ofs, size,
261 s->config_region_info.offset,
262 s->config_region_info.size);
263 assert(QEMU_IS_ALIGNED(s->config_region_info.offset + ofs, size));
264 ret = RETRY_ON_EINTR(
265 pwrite(s->device, &val_le, size, s->config_region_info.offset + ofs)
266 );
267 return ret == size ? 0 : -errno;
268 }
269
270 static void collect_usable_iova_ranges(QEMUVFIOState *s, void *buf)
271 {
272 struct vfio_iommu_type1_info *info = (struct vfio_iommu_type1_info *)buf;
273 struct vfio_info_cap_header *cap = (void *)buf + info->cap_offset;
274 struct vfio_iommu_type1_info_cap_iova_range *cap_iova_range;
275 int i;
276
277 while (cap->id != VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE) {
278 if (!cap->next) {
279 return;
280 }
281 cap = buf + cap->next;
282 }
283
284 cap_iova_range = (struct vfio_iommu_type1_info_cap_iova_range *)cap;
285
286 s->nb_iova_ranges = cap_iova_range->nr_iovas;
287 if (s->nb_iova_ranges > 1) {
288 s->usable_iova_ranges =
289 g_renew(struct IOVARange, s->usable_iova_ranges,
290 s->nb_iova_ranges);
291 }
292
293 for (i = 0; i < s->nb_iova_ranges; i++) {
294 s->usable_iova_ranges[i].start = cap_iova_range->iova_ranges[i].start;
295 s->usable_iova_ranges[i].end = cap_iova_range->iova_ranges[i].end;
296 }
297 }
298
299 static int qemu_vfio_init_pci(QEMUVFIOState *s, const char *device,
300 Error **errp)
301 {
302 int ret;
303 int i;
304 uint32_t pci_cmd;
305 struct vfio_group_status group_status = { .argsz = sizeof(group_status) };
306 struct vfio_iommu_type1_info *iommu_info = NULL;
307 size_t iommu_info_size = sizeof(*iommu_info);
308 struct vfio_device_info device_info = { .argsz = sizeof(device_info) };
309 char *group_file = NULL;
310
311 s->usable_iova_ranges = NULL;
312
313 /* Create a new container */
314 s->container = open("/dev/vfio/vfio", O_RDWR);
315
316 if (s->container == -1) {
317 error_setg_file_open(errp, errno, "/dev/vfio/vfio");
318 return -errno;
319 }
320 if (ioctl(s->container, VFIO_GET_API_VERSION) != VFIO_API_VERSION) {
321 error_setg(errp, "Invalid VFIO version");
322 ret = -EINVAL;
323 goto fail_container;
324 }
325
326 if (!ioctl(s->container, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU)) {
327 error_setg_errno(errp, errno, "VFIO IOMMU Type1 is not supported");
328 ret = -EINVAL;
329 goto fail_container;
330 }
331
332 /* Open the group */
333 group_file = sysfs_find_group_file(device, errp);
334 if (!group_file) {
335 ret = -EINVAL;
336 goto fail_container;
337 }
338
339 s->group = open(group_file, O_RDWR);
340 if (s->group == -1) {
341 error_setg_file_open(errp, errno, group_file);
342 g_free(group_file);
343 ret = -errno;
344 goto fail_container;
345 }
346 g_free(group_file);
347
348 /* Test the group is viable and available */
349 if (ioctl(s->group, VFIO_GROUP_GET_STATUS, &group_status)) {
350 error_setg_errno(errp, errno, "Failed to get VFIO group status");
351 ret = -errno;
352 goto fail;
353 }
354
355 if (!(group_status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
356 error_setg(errp, "VFIO group is not viable");
357 ret = -EINVAL;
358 goto fail;
359 }
360
361 /* Add the group to the container */
362 if (ioctl(s->group, VFIO_GROUP_SET_CONTAINER, &s->container)) {
363 error_setg_errno(errp, errno, "Failed to add group to VFIO container");
364 ret = -errno;
365 goto fail;
366 }
367
368 /* Enable the IOMMU model we want */
369 if (ioctl(s->container, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU)) {
370 error_setg_errno(errp, errno, "Failed to set VFIO IOMMU type");
371 ret = -errno;
372 goto fail;
373 }
374
375 iommu_info = g_malloc0(iommu_info_size);
376 iommu_info->argsz = iommu_info_size;
377
378 /* Get additional IOMMU info */
379 if (ioctl(s->container, VFIO_IOMMU_GET_INFO, iommu_info)) {
380 error_setg_errno(errp, errno, "Failed to get IOMMU info");
381 ret = -errno;
382 goto fail;
383 }
384
385 /*
386 * if the kernel does not report usable IOVA regions, choose
387 * the legacy [QEMU_VFIO_IOVA_MIN, QEMU_VFIO_IOVA_MAX -1] region
388 */
389 s->nb_iova_ranges = 1;
390 s->usable_iova_ranges = g_new0(struct IOVARange, 1);
391 s->usable_iova_ranges[0].start = QEMU_VFIO_IOVA_MIN;
392 s->usable_iova_ranges[0].end = QEMU_VFIO_IOVA_MAX - 1;
393
394 if (iommu_info->argsz > iommu_info_size) {
395 iommu_info_size = iommu_info->argsz;
396 iommu_info = g_realloc(iommu_info, iommu_info_size);
397 if (ioctl(s->container, VFIO_IOMMU_GET_INFO, iommu_info)) {
398 ret = -errno;
399 goto fail;
400 }
401 collect_usable_iova_ranges(s, iommu_info);
402 }
403
404 s->device = ioctl(s->group, VFIO_GROUP_GET_DEVICE_FD, device);
405
406 if (s->device < 0) {
407 error_setg_errno(errp, errno, "Failed to get device fd");
408 ret = -errno;
409 goto fail;
410 }
411
412 /* Test and setup the device */
413 if (ioctl(s->device, VFIO_DEVICE_GET_INFO, &device_info)) {
414 error_setg_errno(errp, errno, "Failed to get device info");
415 ret = -errno;
416 goto fail;
417 }
418
419 if (device_info.num_regions < VFIO_PCI_CONFIG_REGION_INDEX) {
420 error_setg(errp, "Invalid device regions");
421 ret = -EINVAL;
422 goto fail;
423 }
424
425 s->config_region_info = (struct vfio_region_info) {
426 .index = VFIO_PCI_CONFIG_REGION_INDEX,
427 .argsz = sizeof(struct vfio_region_info),
428 };
429 if (ioctl(s->device, VFIO_DEVICE_GET_REGION_INFO, &s->config_region_info)) {
430 error_setg_errno(errp, errno, "Failed to get config region info");
431 ret = -errno;
432 goto fail;
433 }
434 trace_qemu_vfio_region_info("config", s->config_region_info.offset,
435 s->config_region_info.size,
436 s->config_region_info.cap_offset);
437
438 for (i = 0; i < ARRAY_SIZE(s->bar_region_info); i++) {
439 ret = qemu_vfio_pci_init_bar(s, i, errp);
440 if (ret) {
441 goto fail;
442 }
443 }
444
445 /* Enable bus master */
446 ret = qemu_vfio_pci_read_config(s, &pci_cmd, sizeof(pci_cmd), PCI_COMMAND);
447 if (ret) {
448 goto fail;
449 }
450 pci_cmd |= PCI_COMMAND_MASTER;
451 ret = qemu_vfio_pci_write_config(s, &pci_cmd, sizeof(pci_cmd), PCI_COMMAND);
452 if (ret) {
453 goto fail;
454 }
455 g_free(iommu_info);
456 return 0;
457 fail:
458 g_free(s->usable_iova_ranges);
459 s->usable_iova_ranges = NULL;
460 s->nb_iova_ranges = 0;
461 g_free(iommu_info);
462 close(s->group);
463 fail_container:
464 close(s->container);
465 return ret;
466 }
467
468 static void qemu_vfio_ram_block_added(RAMBlockNotifier *n, void *host,
469 size_t size, size_t max_size)
470 {
471 QEMUVFIOState *s = container_of(n, QEMUVFIOState, ram_notifier);
472 Error *local_err = NULL;
473 int ret;
474
475 trace_qemu_vfio_ram_block_added(s, host, max_size);
476 ret = qemu_vfio_dma_map(s, host, max_size, false, NULL, &local_err);
477 if (ret) {
478 error_reportf_err(local_err,
479 "qemu_vfio_dma_map(%p, %zu) failed: ",
480 host, max_size);
481 }
482 }
483
484 static void qemu_vfio_ram_block_removed(RAMBlockNotifier *n, void *host,
485 size_t size, size_t max_size)
486 {
487 QEMUVFIOState *s = container_of(n, QEMUVFIOState, ram_notifier);
488 if (host) {
489 trace_qemu_vfio_ram_block_removed(s, host, max_size);
490 qemu_vfio_dma_unmap(s, host);
491 }
492 }
493
494 static void qemu_vfio_open_common(QEMUVFIOState *s)
495 {
496 qemu_mutex_init(&s->lock);
497 s->ram_notifier.ram_block_added = qemu_vfio_ram_block_added;
498 s->ram_notifier.ram_block_removed = qemu_vfio_ram_block_removed;
499 s->low_water_mark = QEMU_VFIO_IOVA_MIN;
500 s->high_water_mark = QEMU_VFIO_IOVA_MAX;
501 ram_block_notifier_add(&s->ram_notifier);
502 }
503
504 /**
505 * Open a PCI device, e.g. "0000:00:01.0".
506 */
507 QEMUVFIOState *qemu_vfio_open_pci(const char *device, Error **errp)
508 {
509 int r;
510 QEMUVFIOState *s = g_new0(QEMUVFIOState, 1);
511
512 /*
513 * VFIO may pin all memory inside mappings, resulting it in pinning
514 * all memory inside RAM blocks unconditionally.
515 */
516 r = ram_block_discard_disable(true);
517 if (r) {
518 error_setg_errno(errp, -r, "Cannot set discarding of RAM broken");
519 g_free(s);
520 return NULL;
521 }
522
523 r = qemu_vfio_init_pci(s, device, errp);
524 if (r) {
525 ram_block_discard_disable(false);
526 g_free(s);
527 return NULL;
528 }
529 qemu_vfio_open_common(s);
530 return s;
531 }
532
533 static void qemu_vfio_dump_mappings(QEMUVFIOState *s)
534 {
535 for (int i = 0; i < s->nr_mappings; ++i) {
536 trace_qemu_vfio_dump_mapping(s->mappings[i].host,
537 s->mappings[i].iova,
538 s->mappings[i].size);
539 }
540 }
541
542 /**
543 * Find the mapping entry that contains [host, host + size) and set @index to
544 * the position. If no entry contains it, @index is the position _after_ which
545 * to insert the new mapping. IOW, it is the index of the largest element that
546 * is smaller than @host, or -1 if no entry is.
547 */
548 static IOVAMapping *qemu_vfio_find_mapping(QEMUVFIOState *s, void *host,
549 int *index)
550 {
551 IOVAMapping *p = s->mappings;
552 IOVAMapping *q = p ? p + s->nr_mappings - 1 : NULL;
553 IOVAMapping *mid;
554 trace_qemu_vfio_find_mapping(s, host);
555 if (!p) {
556 *index = -1;
557 return NULL;
558 }
559 while (true) {
560 mid = p + (q - p) / 2;
561 if (mid == p) {
562 break;
563 }
564 if (mid->host > host) {
565 q = mid;
566 } else if (mid->host < host) {
567 p = mid;
568 } else {
569 break;
570 }
571 }
572 if (mid->host > host) {
573 mid--;
574 } else if (mid < &s->mappings[s->nr_mappings - 1]
575 && (mid + 1)->host <= host) {
576 mid++;
577 }
578 *index = mid - &s->mappings[0];
579 if (mid >= &s->mappings[0] &&
580 mid->host <= host && mid->host + mid->size > host) {
581 assert(mid < &s->mappings[s->nr_mappings]);
582 return mid;
583 }
584 /* At this point *index + 1 is the right position to insert the new
585 * mapping.*/
586 return NULL;
587 }
588
589 /**
590 * Allocate IOVA and create a new mapping record and insert it in @s.
591 */
592 static IOVAMapping *qemu_vfio_add_mapping(QEMUVFIOState *s,
593 void *host, size_t size,
594 int index, uint64_t iova)
595 {
596 int shift;
597 IOVAMapping m = {.host = host, .size = size, .iova = iova};
598 IOVAMapping *insert;
599
600 assert(QEMU_IS_ALIGNED(size, qemu_real_host_page_size()));
601 assert(QEMU_IS_ALIGNED(s->low_water_mark, qemu_real_host_page_size()));
602 assert(QEMU_IS_ALIGNED(s->high_water_mark, qemu_real_host_page_size()));
603 trace_qemu_vfio_new_mapping(s, host, size, index, iova);
604
605 assert(index >= 0);
606 s->nr_mappings++;
607 s->mappings = g_renew(IOVAMapping, s->mappings, s->nr_mappings);
608 insert = &s->mappings[index];
609 shift = s->nr_mappings - index - 1;
610 if (shift) {
611 memmove(insert + 1, insert, shift * sizeof(s->mappings[0]));
612 }
613 *insert = m;
614 return insert;
615 }
616
617 /* Do the DMA mapping with VFIO. */
618 static int qemu_vfio_do_mapping(QEMUVFIOState *s, void *host, size_t size,
619 uint64_t iova, Error **errp)
620 {
621 struct vfio_iommu_type1_dma_map dma_map = {
622 .argsz = sizeof(dma_map),
623 .flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE,
624 .iova = iova,
625 .vaddr = (uintptr_t)host,
626 .size = size,
627 };
628 trace_qemu_vfio_do_mapping(s, host, iova, size);
629
630 if (ioctl(s->container, VFIO_IOMMU_MAP_DMA, &dma_map)) {
631 error_setg_errno(errp, errno, "VFIO_MAP_DMA failed");
632 return -errno;
633 }
634 return 0;
635 }
636
637 /**
638 * Undo the DMA mapping from @s with VFIO, and remove from mapping list.
639 */
640 static void qemu_vfio_undo_mapping(QEMUVFIOState *s, IOVAMapping *mapping,
641 Error **errp)
642 {
643 int index;
644 struct vfio_iommu_type1_dma_unmap unmap = {
645 .argsz = sizeof(unmap),
646 .flags = 0,
647 .iova = mapping->iova,
648 .size = mapping->size,
649 };
650
651 index = mapping - s->mappings;
652 assert(mapping->size > 0);
653 assert(QEMU_IS_ALIGNED(mapping->size, qemu_real_host_page_size()));
654 assert(index >= 0 && index < s->nr_mappings);
655 if (ioctl(s->container, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
656 error_setg_errno(errp, errno, "VFIO_UNMAP_DMA failed");
657 }
658 memmove(mapping, &s->mappings[index + 1],
659 sizeof(s->mappings[0]) * (s->nr_mappings - index - 1));
660 s->nr_mappings--;
661 s->mappings = g_renew(IOVAMapping, s->mappings, s->nr_mappings);
662 }
663
664 /* Check if the mapping list is (ascending) ordered. */
665 static bool qemu_vfio_verify_mappings(QEMUVFIOState *s)
666 {
667 int i;
668 if (QEMU_VFIO_DEBUG) {
669 for (i = 0; i < s->nr_mappings - 1; ++i) {
670 if (!(s->mappings[i].host < s->mappings[i + 1].host)) {
671 error_report("item %d not sorted!", i);
672 qemu_vfio_dump_mappings(s);
673 return false;
674 }
675 if (!(s->mappings[i].host + s->mappings[i].size <=
676 s->mappings[i + 1].host)) {
677 error_report("item %d overlap with next!", i);
678 qemu_vfio_dump_mappings(s);
679 return false;
680 }
681 }
682 }
683 return true;
684 }
685
686 static bool qemu_vfio_find_fixed_iova(QEMUVFIOState *s, size_t size,
687 uint64_t *iova, Error **errp)
688 {
689 int i;
690
691 for (i = 0; i < s->nb_iova_ranges; i++) {
692 if (s->usable_iova_ranges[i].end < s->low_water_mark) {
693 continue;
694 }
695 s->low_water_mark =
696 MAX(s->low_water_mark, s->usable_iova_ranges[i].start);
697
698 if (s->usable_iova_ranges[i].end - s->low_water_mark + 1 >= size ||
699 s->usable_iova_ranges[i].end - s->low_water_mark + 1 == 0) {
700 *iova = s->low_water_mark;
701 s->low_water_mark += size;
702 return true;
703 }
704 }
705 error_setg(errp, "fixed iova range not found");
706
707 return false;
708 }
709
710 static bool qemu_vfio_find_temp_iova(QEMUVFIOState *s, size_t size,
711 uint64_t *iova, Error **errp)
712 {
713 int i;
714
715 for (i = s->nb_iova_ranges - 1; i >= 0; i--) {
716 if (s->usable_iova_ranges[i].start > s->high_water_mark) {
717 continue;
718 }
719 s->high_water_mark =
720 MIN(s->high_water_mark, s->usable_iova_ranges[i].end + 1);
721
722 if (s->high_water_mark - s->usable_iova_ranges[i].start + 1 >= size ||
723 s->high_water_mark - s->usable_iova_ranges[i].start + 1 == 0) {
724 *iova = s->high_water_mark - size;
725 s->high_water_mark = *iova;
726 return true;
727 }
728 }
729 error_setg(errp, "temporary iova range not found");
730
731 return false;
732 }
733
734 /**
735 * qemu_vfio_water_mark_reached:
736 *
737 * Returns %true if high watermark has been reached, %false otherwise.
738 */
739 static bool qemu_vfio_water_mark_reached(QEMUVFIOState *s, size_t size,
740 Error **errp)
741 {
742 if (s->high_water_mark - s->low_water_mark + 1 < size) {
743 error_setg(errp, "iova exhausted (water mark reached)");
744 return true;
745 }
746 return false;
747 }
748
749 /* Map [host, host + size) area into a contiguous IOVA address space, and store
750 * the result in @iova if not NULL. The caller need to make sure the area is
751 * aligned to page size, and mustn't overlap with existing mapping areas (split
752 * mapping status within this area is not allowed).
753 */
754 int qemu_vfio_dma_map(QEMUVFIOState *s, void *host, size_t size,
755 bool temporary, uint64_t *iova, Error **errp)
756 {
757 int index;
758 IOVAMapping *mapping;
759 uint64_t iova0;
760
761 assert(QEMU_PTR_IS_ALIGNED(host, qemu_real_host_page_size()));
762 assert(QEMU_IS_ALIGNED(size, qemu_real_host_page_size()));
763 trace_qemu_vfio_dma_map(s, host, size, temporary, iova);
764 QEMU_LOCK_GUARD(&s->lock);
765 mapping = qemu_vfio_find_mapping(s, host, &index);
766 if (mapping) {
767 iova0 = mapping->iova + ((uint8_t *)host - (uint8_t *)mapping->host);
768 } else {
769 int ret;
770
771 if (qemu_vfio_water_mark_reached(s, size, errp)) {
772 return -ENOMEM;
773 }
774 if (!temporary) {
775 if (!qemu_vfio_find_fixed_iova(s, size, &iova0, errp)) {
776 return -ENOMEM;
777 }
778
779 mapping = qemu_vfio_add_mapping(s, host, size, index + 1, iova0);
780 assert(qemu_vfio_verify_mappings(s));
781 ret = qemu_vfio_do_mapping(s, host, size, iova0, errp);
782 if (ret < 0) {
783 qemu_vfio_undo_mapping(s, mapping, NULL);
784 return ret;
785 }
786 qemu_vfio_dump_mappings(s);
787 } else {
788 if (!qemu_vfio_find_temp_iova(s, size, &iova0, errp)) {
789 return -ENOMEM;
790 }
791 ret = qemu_vfio_do_mapping(s, host, size, iova0, errp);
792 if (ret < 0) {
793 return ret;
794 }
795 }
796 }
797 trace_qemu_vfio_dma_mapped(s, host, iova0, size);
798 if (iova) {
799 *iova = iova0;
800 }
801 return 0;
802 }
803
804 /* Reset the high watermark and free all "temporary" mappings. */
805 int qemu_vfio_dma_reset_temporary(QEMUVFIOState *s)
806 {
807 struct vfio_iommu_type1_dma_unmap unmap = {
808 .argsz = sizeof(unmap),
809 .flags = 0,
810 .iova = s->high_water_mark,
811 .size = QEMU_VFIO_IOVA_MAX - s->high_water_mark,
812 };
813 trace_qemu_vfio_dma_reset_temporary(s);
814 QEMU_LOCK_GUARD(&s->lock);
815 if (ioctl(s->container, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
816 error_report("VFIO_UNMAP_DMA failed: %s", strerror(errno));
817 return -errno;
818 }
819 s->high_water_mark = QEMU_VFIO_IOVA_MAX;
820 return 0;
821 }
822
823 /* Unmapping the whole area that was previously mapped with
824 * qemu_vfio_dma_map(). */
825 void qemu_vfio_dma_unmap(QEMUVFIOState *s, void *host)
826 {
827 int index = 0;
828 IOVAMapping *m;
829
830 if (!host) {
831 return;
832 }
833
834 trace_qemu_vfio_dma_unmap(s, host);
835 QEMU_LOCK_GUARD(&s->lock);
836 m = qemu_vfio_find_mapping(s, host, &index);
837 if (!m) {
838 return;
839 }
840 qemu_vfio_undo_mapping(s, m, NULL);
841 }
842
843 static void qemu_vfio_reset(QEMUVFIOState *s)
844 {
845 ioctl(s->device, VFIO_DEVICE_RESET);
846 }
847
848 /* Close and free the VFIO resources. */
849 void qemu_vfio_close(QEMUVFIOState *s)
850 {
851 int i;
852
853 if (!s) {
854 return;
855 }
856
857 ram_block_notifier_remove(&s->ram_notifier);
858
859 for (i = 0; i < s->nr_mappings; ++i) {
860 qemu_vfio_undo_mapping(s, &s->mappings[i], NULL);
861 }
862
863 g_free(s->usable_iova_ranges);
864 s->nb_iova_ranges = 0;
865 qemu_vfio_reset(s);
866 close(s->device);
867 close(s->group);
868 close(s->container);
869 ram_block_discard_disable(false);
870 }