vfio.c 14.6 KB
Newer Older
1
2
3
/** Virtual Function IO wrapper around kernel API
 *
 * @author Steffen Vogel <stvogel@eonerc.rwth-aachen.de>
Steffen Vogel's avatar
Steffen Vogel committed
4
 * @copyright 2014-2019, Steffen Vogel
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 **********************************************************************************/

#define _DEFAULT_SOURCE

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/eventfd.h>

#include <villas/utils.h>
#include <villas/log.h>
#include <villas/config.h>
#include <villas/kernel/kernel.h>
#include <villas/kernel/vfio.h>
#include <villas/kernel/pci.h>

static const char *vfio_pci_region_names[] = {
25
26
27
28
29
30
31
32
33
	"PCI_BAR0",		/* VFIO_PCI_BAR0_REGION_INDEX */
	"PCI_BAR1",		/* VFIO_PCI_BAR1_REGION_INDEX */
	"PCI_BAR2",		/* VFIO_PCI_BAR2_REGION_INDEX */
	"PCI_BAR3",		/* VFIO_PCI_BAR3_REGION_INDEX */
	"PCI_BAR4",		/* VFIO_PCI_BAR4_REGION_INDEX */
	"PCI_BAR5",		/* VFIO_PCI_BAR5_REGION_INDEX */
	"PCI_ROM",		/* VFIO_PCI_ROM_REGION_INDEX */
	"PCI_CONFIG",		/* VFIO_PCI_CONFIG_REGION_INDEX */
	"PCI_VGA"		/* VFIO_PCI_INTX_IRQ_INDEX */
34
35
36
};

static const char *vfio_pci_irq_names[] = {
37
38
39
40
41
	"PCI_INTX",		/* VFIO_PCI_INTX_IRQ_INDEX */
	"PCI_MSI", 		/* VFIO_PCI_MSI_IRQ_INDEX */
	"PCI_MSIX",		/* VFIO_PCI_MSIX_IRQ_INDEX */
	"PCI_ERR", 		/* VFIO_PCI_ERR_IRQ_INDEX */
	"PCI_REQ"		/* VFIO_PCI_REQ_IRQ_INDEX */
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
};

/* Helpers */
int vfio_get_iommu_name(int index, char *buf, size_t len)
{
	FILE *f;
	char fn[256];

	snprintf(fn, sizeof(fn), "/sys/kernel/iommu_groups/%d/name", index);

	f = fopen(fn, "r");
	if (!f)
		return -1;

	int ret = fgets(buf, len, f) == buf ? 0 : -1;

	/* Remove trailing newline */
	char *c = strrchr(buf, '\n');
	if (c)
		*c = 0;

	fclose(f);

	return ret;
}

/* Destructors */
int vfio_destroy(struct vfio_container *v)
{
	int ret;

	/* Release memory and close fds */
Steffen Vogel's avatar
Steffen Vogel committed
74
	vlist_destroy(&v->groups, (dtor_cb_t) vfio_group_destroy, true);
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

	/* Close container */
	ret = close(v->fd);
	if (ret < 0)
		return -1;

	debug(5, "VFIO: closed container: fd=%d", v->fd);

	return 0;
}

int vfio_group_destroy(struct vfio_group *g)
{
	int ret;

Steffen Vogel's avatar
Steffen Vogel committed
90
	vlist_destroy(&g->devices, (dtor_cb_t) vfio_device_destroy, false);
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

	ret = ioctl(g->fd, VFIO_GROUP_UNSET_CONTAINER);
	if (ret)
		return ret;

	debug(5, "VFIO: released group from container: group=%u", g->index);

	ret = close(g->fd);
	if (ret)
		return ret;

	debug(5, "VFIO: closed group: group=%u, fd=%d", g->index, g->fd);

	return 0;
}

int vfio_device_destroy(struct vfio_device *d)
{
	int ret;

	for (int i = 0; i < d->info.num_regions; i++)
		vfio_unmap_region(d, i);

	ret = close(d->fd);
	if (ret)
		return ret;

	debug(5, "VFIO: closed device: name=%s, fd=%d", d->name, d->fd);

	free(d->mappings);
	free(d->name);

	return 0;
}

/* Constructors */
int vfio_init(struct vfio_container *v)
{
	int ret;

	/* Initialize datastructures */
	memset(v, 0, sizeof(*v));

Steffen Vogel's avatar
Steffen Vogel committed
134
	vlist_init(&v->groups);
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170

	/* Load VFIO kernel module */
	if (kernel_module_load("vfio"))
		error("Failed to load kernel module: %s", "vfio");

	/* Open VFIO API */
	v->fd = open(VFIO_DEV("vfio"), O_RDWR);
	if (v->fd < 0)
		error("Failed to open VFIO container");

	/* Check VFIO API version */
	v->version = ioctl(v->fd, VFIO_GET_API_VERSION);
	if (v->version < 0 || v->version != VFIO_API_VERSION)
		error("Failed to get VFIO version");

	/* Check available VFIO extensions (IOMMU types) */
	v->extensions = 0;
	for (int i = 1; i < VFIO_DMA_CC_IOMMU; i++) {
		ret = ioctl(v->fd, VFIO_CHECK_EXTENSION, i);
		if (ret < 0)
			error("Failed to get VFIO extensions");
		else if (ret > 0)
			v->extensions |= (1 << i);
	}

	return 0;
}

int vfio_group_attach(struct vfio_group *g, struct vfio_container *c, int index)
{
	int ret;
	char buf[128];

	g->index = index;
	g->container = c;

Steffen Vogel's avatar
Steffen Vogel committed
171
	vlist_init(&g->devices);
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198

	/* Open group fd */
	snprintf(buf, sizeof(buf), VFIO_DEV("%u"), g->index);
	g->fd = open(buf, O_RDWR);
	if (g->fd < 0)
		serror("Failed to open VFIO group: %u", g->index);

	/* Claim group ownership */
	ret = ioctl(g->fd, VFIO_GROUP_SET_CONTAINER, &c->fd);
	if (ret < 0)
		serror("Failed to attach VFIO group to container");

	/* Set IOMMU type */
	ret = ioctl(c->fd, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU);
	if (ret < 0)
		serror("Failed to set IOMMU type of container");

	/* Check group viability and features */
	g->status.argsz = sizeof(g->status);

	ret = ioctl(g->fd, VFIO_GROUP_GET_STATUS, &g->status);
	if (ret < 0)
		serror("Failed to get VFIO group status");

	if (!(g->status.flags & VFIO_GROUP_FLAGS_VIABLE))
		error("VFIO group is not available: bind all devices to the VFIO driver!");

Steffen Vogel's avatar
Steffen Vogel committed
199
	vlist_push(&c->groups, g);
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

	return 0;
}

int vfio_pci_attach(struct vfio_device *d, struct vfio_container *c, struct pci_device *pdev)
{
	char name[32];
	int ret;

	/* Load PCI bus driver for VFIO */
	if (kernel_module_load("vfio_pci"))
		error("Failed to load kernel driver: %s", "vfio_pci");

	/* Bind PCI card to vfio-pci driver*/
	ret = pci_attach_driver(pdev, "vfio-pci");
	if (ret)
		error("Failed to attach device to driver");

	/* Get IOMMU group of device */
	int index = pci_get_iommu_group(pdev);
	if (index < 0)
		error("Failed to get IOMMU group of device");

	/* VFIO device name consists of PCI BDF */
	snprintf(name, sizeof(name), "%04x:%02x:%02x.%x", pdev->slot.domain, pdev->slot.bus, pdev->slot.device, pdev->slot.function);

	ret = vfio_device_attach(d, c, name, index);
	if (ret < 0)
		return ret;

	/* Check if this is really a vfio-pci device */
	if (!(d->info.flags & VFIO_DEVICE_FLAGS_PCI)) {
		vfio_device_destroy(d);
		return -1;
	}

	d->pci_device = pdev;

	return 0;
}

int vfio_device_attach(struct vfio_device *d, struct vfio_container *c, const char *name, int index)
{
	int ret;
	struct vfio_group *g = NULL;

	/* Check if group already exists */
Steffen Vogel's avatar
Steffen Vogel committed
247
248
	for (size_t i = 0; i < vlist_length(&c->groups); i++) {
		struct vfio_group *h = (struct vfio_group *) vlist_at(&c->groups, i);
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307

		if (h->index == index)
			g = h;
	}

	if (!g) {
		g = alloc(sizeof(struct vfio_group));

		/* Aquire group ownership */
		ret = vfio_group_attach(g, c, index);
		if (ret)
			error("Failed to attach to IOMMU group: %u", index);

		info("Attached new group %u to VFIO container", g->index);
	}

	d->group = g;
	d->name = strdup(name);

	/* Open device fd */
	d->fd = ioctl(g->fd, VFIO_GROUP_GET_DEVICE_FD, d->name);
	if (d->fd < 0)
		serror("Failed to open VFIO device: %s", d->name);

	/* Get device info */
	d->info.argsz = sizeof(d->info);

	ret = ioctl(d->fd, VFIO_DEVICE_GET_INFO, &d->info);
	if (ret < 0)
		serror("Failed to get VFIO device info for: %s", d->name);

	d->irqs     = alloc(d->info.num_irqs    * sizeof(struct vfio_irq_info));
	d->regions  = alloc(d->info.num_regions * sizeof(struct vfio_region_info));
	d->mappings = alloc(d->info.num_regions * sizeof(void *));

	/* Get device regions */
	for (int i = 0; i < d->info.num_regions && i < 8; i++) {
		struct vfio_region_info *region = &d->regions[i];

		region->argsz = sizeof(*region);
		region->index = i;

		ret = ioctl(d->fd, VFIO_DEVICE_GET_REGION_INFO, region);
		if (ret < 0)
			serror("Failed to get regions of VFIO device: %s", d->name);
	}

	/* Get device irqs */
	for (int i = 0; i < d->info.num_irqs; i++) {
		struct vfio_irq_info *irq = &d->irqs[i];

		irq->argsz = sizeof(*irq);
		irq->index = i;

		ret = ioctl(d->fd, VFIO_DEVICE_GET_IRQ_INFO, irq);
		if (ret < 0)
			serror("Failed to get IRQs of VFIO device: %s", d->name);
	}

Steffen Vogel's avatar
Steffen Vogel committed
308
	vlist_push(&d->group->devices, d);
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355

	return 0;
}

int vfio_pci_reset(struct vfio_device *d)
{
	int ret;

	/* Check if this is really a vfio-pci device */
	if (!(d->info.flags & VFIO_DEVICE_FLAGS_PCI))
		return -1;

	size_t reset_infolen = sizeof(struct vfio_pci_hot_reset_info) + sizeof(struct vfio_pci_dependent_device) * 64;
	size_t resetlen = sizeof(struct vfio_pci_hot_reset) + sizeof(int32_t) * 1;

	struct vfio_pci_hot_reset_info *reset_info = (struct vfio_pci_hot_reset_info *) alloc(reset_infolen);
	struct vfio_pci_hot_reset *reset = (struct vfio_pci_hot_reset *) alloc(resetlen);

	reset_info->argsz = reset_infolen;
	reset->argsz = resetlen;

	ret = ioctl(d->fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, reset_info);
	if (ret)
		return ret;

	debug(5, "VFIO: dependent devices for hot-reset:");
	for (int i = 0; i < reset_info->count; i++) {
		struct vfio_pci_dependent_device *dd = &reset_info->devices[i];
		debug(5, "%04x:%02x:%02x.%01x: iommu_group=%u", dd->segment, dd->bus, PCI_SLOT(dd->devfn), PCI_FUNC(dd->devfn), dd->group_id);

		if (dd->group_id != d->group->index)
			return -3;
	}

	reset->count = 1;
	reset->group_fds[0] = d->group->fd;

	ret = ioctl(d->fd, VFIO_DEVICE_PCI_HOT_RESET, reset);

	free(reset_info);

	return ret;
}

int vfio_pci_msi_find(struct vfio_device *d, int nos[32])
{
	int ret, idx, irq;
356
	char *end, *col, *last, *lasts, line[1024], name[13];
357
358
359
360
361
362
363
364
365
366
367
	FILE *f;

	f = fopen("/proc/interrupts", "r");
	if (!f)
		return -1;

	for (int i = 0; i < 32; i++)
		nos[i] = -1;

	/* For each line in /proc/interruipts */
	while (fgets(line, sizeof(line), f)) {
368
		col = strtok_r(line, " ", &lasts);
369
370
371
372
373
374
375
376
377

		/* IRQ number is in first column */
		irq = strtol(col, &end, 10);
		if (col == end)
			continue;

		/* Find last column of line */
		do {
			last = col;
378
		} while ((col = strtok_r(NULL, " ", &lasts)));
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498


		ret = sscanf(last, "vfio-msi[%u](%12[0-9:])", &idx, name);
		if (ret == 2) {
			if (strstr(d->name, name) == d->name)
				nos[idx] = irq;
		}
	}

	fclose(f);

	return 0;
}

int vfio_pci_msi_deinit(struct vfio_device *d, int efds[32])
{
	int ret, irq_setlen, irq_count = d->irqs[VFIO_PCI_MSI_IRQ_INDEX].count;
	struct vfio_irq_set *irq_set;

	/* Check if this is really a vfio-pci device */
	if (!(d->info.flags & VFIO_DEVICE_FLAGS_PCI))
		return -1;

	irq_setlen = sizeof(struct vfio_irq_set) + sizeof(int) * irq_count;
	irq_set = alloc(irq_setlen);

	irq_set->argsz = irq_setlen;
	irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
	irq_set->index = VFIO_PCI_MSI_IRQ_INDEX;
	irq_set->count = irq_count;
	irq_set->start = 0;

	for (int i = 0; i < irq_count; i++) {
		close(efds[i]);
		efds[i] = -1;
	}

	memcpy(irq_set->data, efds, sizeof(int) * irq_count);

	ret = ioctl(d->fd, VFIO_DEVICE_SET_IRQS, irq_set);
	if (ret)
		return -4;

	free(irq_set);

	return irq_count;
}

int vfio_pci_msi_init(struct vfio_device *d, int efds[32])
{
	int ret, irq_setlen, irq_count = d->irqs[VFIO_PCI_MSI_IRQ_INDEX].count;
	struct vfio_irq_set *irq_set;

	/* Check if this is really a vfio-pci device */
	if (!(d->info.flags & VFIO_DEVICE_FLAGS_PCI))
		return -1;

	irq_setlen = sizeof(struct vfio_irq_set) + sizeof(int) * irq_count;
	irq_set = alloc(irq_setlen);

	irq_set->argsz = irq_setlen;
	irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
	irq_set->index = VFIO_PCI_MSI_IRQ_INDEX;
	irq_set->start = 0;
	irq_set->count = irq_count;

	/* Now set the new eventfds */
	for (int i = 0; i < irq_count; i++) {
		efds[i] = eventfd(0, 0);
		if (efds[i] < 0)
			return -3;
	}
	memcpy(irq_set->data, efds, sizeof(int) * irq_count);

	ret = ioctl(d->fd, VFIO_DEVICE_SET_IRQS, irq_set);
	if (ret)
		return -4;

	free(irq_set);

	return irq_count;
}

int vfio_pci_enable(struct vfio_device *d)
{
	int ret;
	uint32_t reg;
	off_t offset = ((off_t) VFIO_PCI_CONFIG_REGION_INDEX << 40) + PCI_COMMAND;

	/* Check if this is really a vfio-pci device */
	if (!(d->info.flags & VFIO_DEVICE_FLAGS_PCI))
		return -1;

	ret = pread(d->fd, &reg, sizeof(reg), offset);
	if (ret != sizeof(reg))
		return -1;

	/* Enable memory access and PCI bus mastering which is required for DMA */
	reg |= PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER;

	ret = pwrite(d->fd, &reg, sizeof(reg), offset);
	if (ret != sizeof(reg))
		return -1;

	return 0;
}

int vfio_device_reset(struct vfio_device *d)
{
	if (d->info.flags & VFIO_DEVICE_FLAGS_RESET)
		return ioctl(d->fd, VFIO_DEVICE_RESET);
	else
		return -1; /* not supported by this device */
}

void vfio_dump(struct vfio_container *v)
{
	info("VFIO Version: %u", v->version);
	info("VFIO Extensions: %#x", v->extensions);

Steffen Vogel's avatar
Steffen Vogel committed
499
500
	for (size_t i = 0; i < vlist_length(&v->groups); i++) {
		struct vfio_group *g = (struct vfio_group *) vlist_at(&v->groups, i);
501
502
503
504
505
506
507

		info("VFIO Group %u, viable=%u, container=%d", g->index,
			(g->status.flags & VFIO_GROUP_FLAGS_VIABLE) > 0,
			(g->status.flags & VFIO_GROUP_FLAGS_CONTAINER_SET) > 0
		);


Steffen Vogel's avatar
Steffen Vogel committed
508
509
		for (size_t i = 0; i < vlist_length(&g->devices); i++) {
			struct vfio_device *d = (struct vfio_device *) vlist_at(&g->devices, i);
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622

			info("Device %s: regions=%u, irqs=%u, flags=%#x", d->name,
				d->info.num_regions,
				d->info.num_irqs,
				d->info.flags
			);

			for (int i = 0; i < d->info.num_regions && i < 8; i++) {
				struct vfio_region_info *region = &d->regions[i];

				if (region->size > 0)
					info("Region %u %s: size=%#llx, offset=%#llx, flags=%u",
						region->index, (d->info.flags & VFIO_DEVICE_FLAGS_PCI) ? vfio_pci_region_names[i] : "",
						region->size,
						region->offset,
						region->flags
					);
			}

			for (int i = 0; i < d->info.num_irqs; i++) {
				struct vfio_irq_info *irq = &d->irqs[i];

				if (irq->count > 0)
					info("IRQ %u %s: count=%u, flags=%u",
						irq->index, (d->info.flags & VFIO_DEVICE_FLAGS_PCI ) ? vfio_pci_irq_names[i] : "",
						irq->count,
						irq->flags
				);
			}
		}
	}
}

void * vfio_map_region(struct vfio_device *d, int idx)
{
	struct vfio_region_info *r = &d->regions[idx];

	if (!(r->flags & VFIO_REGION_INFO_FLAG_MMAP))
		return MAP_FAILED;

	d->mappings[idx] = mmap(NULL, r->size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_32BIT, d->fd, r->offset);

	return d->mappings[idx];
}

int vfio_unmap_region(struct vfio_device *d, int idx)
{
	int ret;
	struct vfio_region_info *r = &d->regions[idx];

	if (!d->mappings[idx])
		return -1; /* was not mapped */

	debug(3, "VFIO: unmap region %u from device", idx);

	ret = munmap(d->mappings[idx], r->size);
	if (ret)
		return -2;

	d->mappings[idx] = NULL;

	return 0;
}

int vfio_map_dma(struct vfio_container *c, uint64_t virt, uint64_t phys, size_t len)
{
	int ret;

	if (len & 0xFFF) {
		len += 0x1000;
		len &= ~0xFFF;
	}

	/* Super stupid allocator */
	if (phys == -1) {
		phys = c->iova_next;
		c->iova_next += len;
	}

	struct vfio_iommu_type1_dma_map dma_map = {
		.argsz = sizeof(struct vfio_iommu_type1_dma_map),
		.vaddr = virt,
		.iova  = phys,
		.size  = len,
		.flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE
	};

	ret = ioctl(c->fd, VFIO_IOMMU_MAP_DMA, &dma_map);
	if (ret)
		serror("Failed to create DMA mapping");

	info("DMA map size=%#llx, iova=%#llx, vaddr=%#llx", dma_map.size, dma_map.iova, dma_map.vaddr);

	return 0;
}

int vfio_unmap_dma(struct vfio_container *c, uint64_t virt, uint64_t phys, size_t len)
{
	int ret;

	struct vfio_iommu_type1_dma_unmap dma_unmap = {
		.argsz = sizeof(struct vfio_iommu_type1_dma_unmap),
		.flags = 0,
		.iova  = phys,
		.size  = len,
	};

	ret = ioctl(c->fd, VFIO_IOMMU_UNMAP_DMA, &dma_unmap);
	if (ret)
		serror("Failed to unmap DMA mapping");

	return 0;
}