xref: /spdk/lib/env_dpdk/memory.c (revision cc6920a4763d4b9a43aa40583c8397d8f14fa100)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright (c) Intel Corporation.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include "spdk/stdinc.h"
35 
36 #include "env_internal.h"
37 
38 #include <rte_config.h>
39 #include <rte_memory.h>
40 #include <rte_eal_memconfig.h>
41 
42 #include "spdk_internal/assert.h"
43 
44 #include "spdk/assert.h"
45 #include "spdk/likely.h"
46 #include "spdk/queue.h"
47 #include "spdk/util.h"
48 #include "spdk/memory.h"
49 #include "spdk/env_dpdk.h"
50 #include "spdk/log.h"
51 
52 #ifndef __linux__
53 #define VFIO_ENABLED 0
54 #else
55 #include <linux/version.h>
56 #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 6, 0)
57 #define VFIO_ENABLED 1
58 #include <linux/vfio.h>
59 #include <rte_vfio.h>
60 
61 struct spdk_vfio_dma_map {
62 	struct vfio_iommu_type1_dma_map map;
63 	TAILQ_ENTRY(spdk_vfio_dma_map) tailq;
64 };
65 
66 struct vfio_cfg {
67 	int fd;
68 	bool enabled;
69 	bool noiommu_enabled;
70 	unsigned device_ref;
71 	TAILQ_HEAD(, spdk_vfio_dma_map) maps;
72 	pthread_mutex_t mutex;
73 };
74 
75 static struct vfio_cfg g_vfio = {
76 	.fd = -1,
77 	.enabled = false,
78 	.noiommu_enabled = false,
79 	.device_ref = 0,
80 	.maps = TAILQ_HEAD_INITIALIZER(g_vfio.maps),
81 	.mutex = PTHREAD_MUTEX_INITIALIZER
82 };
83 
84 #else
85 #define VFIO_ENABLED 0
86 #endif
87 #endif
88 
89 #if DEBUG
90 #define DEBUG_PRINT(...) SPDK_ERRLOG(__VA_ARGS__)
91 #else
92 #define DEBUG_PRINT(...)
93 #endif
94 
95 #define FN_2MB_TO_4KB(fn)	(fn << (SHIFT_2MB - SHIFT_4KB))
96 #define FN_4KB_TO_2MB(fn)	(fn >> (SHIFT_2MB - SHIFT_4KB))
97 
98 #define MAP_256TB_IDX(vfn_2mb)	((vfn_2mb) >> (SHIFT_1GB - SHIFT_2MB))
99 #define MAP_1GB_IDX(vfn_2mb)	((vfn_2mb) & ((1ULL << (SHIFT_1GB - SHIFT_2MB)) - 1))
100 
101 /* Page is registered */
102 #define REG_MAP_REGISTERED	(1ULL << 62)
103 
104 /* A notification region barrier. The 2MB translation entry that's marked
105  * with this flag must be unregistered separately. This allows contiguous
106  * regions to be unregistered in the same chunks they were registered.
107  */
108 #define REG_MAP_NOTIFY_START	(1ULL << 63)
109 
110 /* Translation of a single 2MB page. */
111 struct map_2mb {
112 	uint64_t translation_2mb;
113 };
114 
115 /* Second-level map table indexed by bits [21..29] of the virtual address.
116  * Each entry contains the address translation or error for entries that haven't
117  * been retrieved yet.
118  */
119 struct map_1gb {
120 	struct map_2mb map[1ULL << (SHIFT_1GB - SHIFT_2MB)];
121 };
122 
123 /* Top-level map table indexed by bits [30..47] of the virtual address.
124  * Each entry points to a second-level map table or NULL.
125  */
126 struct map_256tb {
127 	struct map_1gb *map[1ULL << (SHIFT_256TB - SHIFT_1GB)];
128 };
129 
130 /* Page-granularity memory address translation */
131 struct spdk_mem_map {
132 	struct map_256tb map_256tb;
133 	pthread_mutex_t mutex;
134 	uint64_t default_translation;
135 	struct spdk_mem_map_ops ops;
136 	void *cb_ctx;
137 	TAILQ_ENTRY(spdk_mem_map) tailq;
138 };
139 
140 /* Registrations map. The 64 bit translations are bit fields with the
141  * following layout (starting with the low bits):
142  *    0 - 61 : reserved
143  *   62 - 63 : flags
144  */
145 static struct spdk_mem_map *g_mem_reg_map;
146 static TAILQ_HEAD(spdk_mem_map_head, spdk_mem_map) g_spdk_mem_maps =
147 	TAILQ_HEAD_INITIALIZER(g_spdk_mem_maps);
148 static pthread_mutex_t g_spdk_mem_map_mutex = PTHREAD_MUTEX_INITIALIZER;
149 
150 static bool g_legacy_mem;
151 
152 /*
153  * Walk the currently registered memory via the main memory registration map
154  * and call the new map's notify callback for each virtually contiguous region.
155  */
156 static int
157 mem_map_notify_walk(struct spdk_mem_map *map, enum spdk_mem_map_notify_action action)
158 {
159 	size_t idx_256tb;
160 	uint64_t idx_1gb;
161 	uint64_t contig_start = UINT64_MAX;
162 	uint64_t contig_end = UINT64_MAX;
163 	struct map_1gb *map_1gb;
164 	int rc;
165 
166 	if (!g_mem_reg_map) {
167 		return -EINVAL;
168 	}
169 
170 	/* Hold the memory registration map mutex so no new registrations can be added while we are looping. */
171 	pthread_mutex_lock(&g_mem_reg_map->mutex);
172 
173 	for (idx_256tb = 0;
174 	     idx_256tb < sizeof(g_mem_reg_map->map_256tb.map) / sizeof(g_mem_reg_map->map_256tb.map[0]);
175 	     idx_256tb++) {
176 		map_1gb = g_mem_reg_map->map_256tb.map[idx_256tb];
177 
178 		if (!map_1gb) {
179 			if (contig_start != UINT64_MAX) {
180 				/* End of of a virtually contiguous range */
181 				rc = map->ops.notify_cb(map->cb_ctx, map, action,
182 							(void *)contig_start,
183 							contig_end - contig_start + VALUE_2MB);
184 				/* Don't bother handling unregister failures. It can't be any worse */
185 				if (rc != 0 && action == SPDK_MEM_MAP_NOTIFY_REGISTER) {
186 					goto err_unregister;
187 				}
188 			}
189 			contig_start = UINT64_MAX;
190 			continue;
191 		}
192 
193 		for (idx_1gb = 0; idx_1gb < sizeof(map_1gb->map) / sizeof(map_1gb->map[0]); idx_1gb++) {
194 			if ((map_1gb->map[idx_1gb].translation_2mb & REG_MAP_REGISTERED) &&
195 			    (contig_start == UINT64_MAX ||
196 			     (map_1gb->map[idx_1gb].translation_2mb & REG_MAP_NOTIFY_START) == 0)) {
197 				/* Rebuild the virtual address from the indexes */
198 				uint64_t vaddr = (idx_256tb << SHIFT_1GB) | (idx_1gb << SHIFT_2MB);
199 
200 				if (contig_start == UINT64_MAX) {
201 					contig_start = vaddr;
202 				}
203 
204 				contig_end = vaddr;
205 			} else {
206 				if (contig_start != UINT64_MAX) {
207 					/* End of of a virtually contiguous range */
208 					rc = map->ops.notify_cb(map->cb_ctx, map, action,
209 								(void *)contig_start,
210 								contig_end - contig_start + VALUE_2MB);
211 					/* Don't bother handling unregister failures. It can't be any worse */
212 					if (rc != 0 && action == SPDK_MEM_MAP_NOTIFY_REGISTER) {
213 						goto err_unregister;
214 					}
215 
216 					/* This page might be a part of a neighbour region, so process
217 					 * it again. The idx_1gb will be incremented immediately.
218 					 */
219 					idx_1gb--;
220 				}
221 				contig_start = UINT64_MAX;
222 			}
223 		}
224 	}
225 
226 	pthread_mutex_unlock(&g_mem_reg_map->mutex);
227 	return 0;
228 
229 err_unregister:
230 	/* Unwind to the first empty translation so we don't unregister
231 	 * a region that just failed to register.
232 	 */
233 	idx_256tb = MAP_256TB_IDX((contig_start >> SHIFT_2MB) - 1);
234 	idx_1gb = MAP_1GB_IDX((contig_start >> SHIFT_2MB) - 1);
235 	contig_start = UINT64_MAX;
236 	contig_end = UINT64_MAX;
237 
238 	/* Unregister any memory we managed to register before the failure */
239 	for (; idx_256tb < SIZE_MAX; idx_256tb--) {
240 		map_1gb = g_mem_reg_map->map_256tb.map[idx_256tb];
241 
242 		if (!map_1gb) {
243 			if (contig_end != UINT64_MAX) {
244 				/* End of of a virtually contiguous range */
245 				map->ops.notify_cb(map->cb_ctx, map,
246 						   SPDK_MEM_MAP_NOTIFY_UNREGISTER,
247 						   (void *)contig_start,
248 						   contig_end - contig_start + VALUE_2MB);
249 			}
250 			contig_end = UINT64_MAX;
251 			continue;
252 		}
253 
254 		for (; idx_1gb < UINT64_MAX; idx_1gb--) {
255 			if ((map_1gb->map[idx_1gb].translation_2mb & REG_MAP_REGISTERED) &&
256 			    (contig_end == UINT64_MAX || (map_1gb->map[idx_1gb].translation_2mb & REG_MAP_NOTIFY_START) == 0)) {
257 				/* Rebuild the virtual address from the indexes */
258 				uint64_t vaddr = (idx_256tb << SHIFT_1GB) | (idx_1gb << SHIFT_2MB);
259 
260 				if (contig_end == UINT64_MAX) {
261 					contig_end = vaddr;
262 				}
263 				contig_start = vaddr;
264 			} else {
265 				if (contig_end != UINT64_MAX) {
266 					/* End of of a virtually contiguous range */
267 					map->ops.notify_cb(map->cb_ctx, map,
268 							   SPDK_MEM_MAP_NOTIFY_UNREGISTER,
269 							   (void *)contig_start,
270 							   contig_end - contig_start + VALUE_2MB);
271 					idx_1gb++;
272 				}
273 				contig_end = UINT64_MAX;
274 			}
275 		}
276 		idx_1gb = sizeof(map_1gb->map) / sizeof(map_1gb->map[0]) - 1;
277 	}
278 
279 	pthread_mutex_unlock(&g_mem_reg_map->mutex);
280 	return rc;
281 }
282 
283 struct spdk_mem_map *
284 spdk_mem_map_alloc(uint64_t default_translation, const struct spdk_mem_map_ops *ops, void *cb_ctx)
285 {
286 	struct spdk_mem_map *map;
287 	int rc;
288 
289 	map = calloc(1, sizeof(*map));
290 	if (map == NULL) {
291 		return NULL;
292 	}
293 
294 	if (pthread_mutex_init(&map->mutex, NULL)) {
295 		free(map);
296 		return NULL;
297 	}
298 
299 	map->default_translation = default_translation;
300 	map->cb_ctx = cb_ctx;
301 	if (ops) {
302 		map->ops = *ops;
303 	}
304 
305 	if (ops && ops->notify_cb) {
306 		pthread_mutex_lock(&g_spdk_mem_map_mutex);
307 		rc = mem_map_notify_walk(map, SPDK_MEM_MAP_NOTIFY_REGISTER);
308 		if (rc != 0) {
309 			pthread_mutex_unlock(&g_spdk_mem_map_mutex);
310 			DEBUG_PRINT("Initial mem_map notify failed\n");
311 			pthread_mutex_destroy(&map->mutex);
312 			free(map);
313 			return NULL;
314 		}
315 		TAILQ_INSERT_TAIL(&g_spdk_mem_maps, map, tailq);
316 		pthread_mutex_unlock(&g_spdk_mem_map_mutex);
317 	}
318 
319 	return map;
320 }
321 
322 void
323 spdk_mem_map_free(struct spdk_mem_map **pmap)
324 {
325 	struct spdk_mem_map *map;
326 	size_t i;
327 
328 	if (!pmap) {
329 		return;
330 	}
331 
332 	map = *pmap;
333 
334 	if (!map) {
335 		return;
336 	}
337 
338 	if (map->ops.notify_cb) {
339 		pthread_mutex_lock(&g_spdk_mem_map_mutex);
340 		mem_map_notify_walk(map, SPDK_MEM_MAP_NOTIFY_UNREGISTER);
341 		TAILQ_REMOVE(&g_spdk_mem_maps, map, tailq);
342 		pthread_mutex_unlock(&g_spdk_mem_map_mutex);
343 	}
344 
345 	for (i = 0; i < sizeof(map->map_256tb.map) / sizeof(map->map_256tb.map[0]); i++) {
346 		free(map->map_256tb.map[i]);
347 	}
348 
349 	pthread_mutex_destroy(&map->mutex);
350 
351 	free(map);
352 	*pmap = NULL;
353 }
354 
355 int
356 spdk_mem_register(void *vaddr, size_t len)
357 {
358 	struct spdk_mem_map *map;
359 	int rc;
360 	void *seg_vaddr;
361 	size_t seg_len;
362 	uint64_t reg;
363 
364 	if ((uintptr_t)vaddr & ~MASK_256TB) {
365 		DEBUG_PRINT("invalid usermode virtual address %p\n", vaddr);
366 		return -EINVAL;
367 	}
368 
369 	if (((uintptr_t)vaddr & MASK_2MB) || (len & MASK_2MB)) {
370 		DEBUG_PRINT("invalid %s parameters, vaddr=%p len=%ju\n",
371 			    __func__, vaddr, len);
372 		return -EINVAL;
373 	}
374 
375 	if (len == 0) {
376 		return 0;
377 	}
378 
379 	pthread_mutex_lock(&g_spdk_mem_map_mutex);
380 
381 	seg_vaddr = vaddr;
382 	seg_len = len;
383 	while (seg_len > 0) {
384 		reg = spdk_mem_map_translate(g_mem_reg_map, (uint64_t)seg_vaddr, NULL);
385 		if (reg & REG_MAP_REGISTERED) {
386 			pthread_mutex_unlock(&g_spdk_mem_map_mutex);
387 			return -EBUSY;
388 		}
389 		seg_vaddr += VALUE_2MB;
390 		seg_len -= VALUE_2MB;
391 	}
392 
393 	seg_vaddr = vaddr;
394 	seg_len = 0;
395 	while (len > 0) {
396 		spdk_mem_map_set_translation(g_mem_reg_map, (uint64_t)vaddr, VALUE_2MB,
397 					     seg_len == 0 ? REG_MAP_REGISTERED | REG_MAP_NOTIFY_START : REG_MAP_REGISTERED);
398 		seg_len += VALUE_2MB;
399 		vaddr += VALUE_2MB;
400 		len -= VALUE_2MB;
401 	}
402 
403 	TAILQ_FOREACH(map, &g_spdk_mem_maps, tailq) {
404 		rc = map->ops.notify_cb(map->cb_ctx, map, SPDK_MEM_MAP_NOTIFY_REGISTER, seg_vaddr, seg_len);
405 		if (rc != 0) {
406 			pthread_mutex_unlock(&g_spdk_mem_map_mutex);
407 			return rc;
408 		}
409 	}
410 
411 	pthread_mutex_unlock(&g_spdk_mem_map_mutex);
412 	return 0;
413 }
414 
415 int
416 spdk_mem_unregister(void *vaddr, size_t len)
417 {
418 	struct spdk_mem_map *map;
419 	int rc;
420 	void *seg_vaddr;
421 	size_t seg_len;
422 	uint64_t reg, newreg;
423 
424 	if ((uintptr_t)vaddr & ~MASK_256TB) {
425 		DEBUG_PRINT("invalid usermode virtual address %p\n", vaddr);
426 		return -EINVAL;
427 	}
428 
429 	if (((uintptr_t)vaddr & MASK_2MB) || (len & MASK_2MB)) {
430 		DEBUG_PRINT("invalid %s parameters, vaddr=%p len=%ju\n",
431 			    __func__, vaddr, len);
432 		return -EINVAL;
433 	}
434 
435 	pthread_mutex_lock(&g_spdk_mem_map_mutex);
436 
437 	/* The first page must be a start of a region. Also check if it's
438 	 * registered to make sure we don't return -ERANGE for non-registered
439 	 * regions.
440 	 */
441 	reg = spdk_mem_map_translate(g_mem_reg_map, (uint64_t)vaddr, NULL);
442 	if ((reg & REG_MAP_REGISTERED) && (reg & REG_MAP_NOTIFY_START) == 0) {
443 		pthread_mutex_unlock(&g_spdk_mem_map_mutex);
444 		return -ERANGE;
445 	}
446 
447 	seg_vaddr = vaddr;
448 	seg_len = len;
449 	while (seg_len > 0) {
450 		reg = spdk_mem_map_translate(g_mem_reg_map, (uint64_t)seg_vaddr, NULL);
451 		if ((reg & REG_MAP_REGISTERED) == 0) {
452 			pthread_mutex_unlock(&g_spdk_mem_map_mutex);
453 			return -EINVAL;
454 		}
455 		seg_vaddr += VALUE_2MB;
456 		seg_len -= VALUE_2MB;
457 	}
458 
459 	newreg = spdk_mem_map_translate(g_mem_reg_map, (uint64_t)seg_vaddr, NULL);
460 	/* If the next page is registered, it must be a start of a region as well,
461 	 * otherwise we'd be unregistering only a part of a region.
462 	 */
463 	if ((newreg & REG_MAP_NOTIFY_START) == 0 && (newreg & REG_MAP_REGISTERED)) {
464 		pthread_mutex_unlock(&g_spdk_mem_map_mutex);
465 		return -ERANGE;
466 	}
467 	seg_vaddr = vaddr;
468 	seg_len = 0;
469 
470 	while (len > 0) {
471 		reg = spdk_mem_map_translate(g_mem_reg_map, (uint64_t)vaddr, NULL);
472 		spdk_mem_map_set_translation(g_mem_reg_map, (uint64_t)vaddr, VALUE_2MB, 0);
473 
474 		if (seg_len > 0 && (reg & REG_MAP_NOTIFY_START)) {
475 			TAILQ_FOREACH_REVERSE(map, &g_spdk_mem_maps, spdk_mem_map_head, tailq) {
476 				rc = map->ops.notify_cb(map->cb_ctx, map, SPDK_MEM_MAP_NOTIFY_UNREGISTER, seg_vaddr, seg_len);
477 				if (rc != 0) {
478 					pthread_mutex_unlock(&g_spdk_mem_map_mutex);
479 					return rc;
480 				}
481 			}
482 
483 			seg_vaddr = vaddr;
484 			seg_len = VALUE_2MB;
485 		} else {
486 			seg_len += VALUE_2MB;
487 		}
488 
489 		vaddr += VALUE_2MB;
490 		len -= VALUE_2MB;
491 	}
492 
493 	if (seg_len > 0) {
494 		TAILQ_FOREACH_REVERSE(map, &g_spdk_mem_maps, spdk_mem_map_head, tailq) {
495 			rc = map->ops.notify_cb(map->cb_ctx, map, SPDK_MEM_MAP_NOTIFY_UNREGISTER, seg_vaddr, seg_len);
496 			if (rc != 0) {
497 				pthread_mutex_unlock(&g_spdk_mem_map_mutex);
498 				return rc;
499 			}
500 		}
501 	}
502 
503 	pthread_mutex_unlock(&g_spdk_mem_map_mutex);
504 	return 0;
505 }
506 
507 int
508 spdk_mem_reserve(void *vaddr, size_t len)
509 {
510 	struct spdk_mem_map *map;
511 	void *seg_vaddr;
512 	size_t seg_len;
513 	uint64_t reg;
514 
515 	if ((uintptr_t)vaddr & ~MASK_256TB) {
516 		DEBUG_PRINT("invalid usermode virtual address %p\n", vaddr);
517 		return -EINVAL;
518 	}
519 
520 	if (((uintptr_t)vaddr & MASK_2MB) || (len & MASK_2MB)) {
521 		DEBUG_PRINT("invalid %s parameters, vaddr=%p len=%ju\n",
522 			    __func__, vaddr, len);
523 		return -EINVAL;
524 	}
525 
526 	if (len == 0) {
527 		return 0;
528 	}
529 
530 	pthread_mutex_lock(&g_spdk_mem_map_mutex);
531 
532 	/* Check if any part of this range is already registered */
533 	seg_vaddr = vaddr;
534 	seg_len = len;
535 	while (seg_len > 0) {
536 		reg = spdk_mem_map_translate(g_mem_reg_map, (uint64_t)seg_vaddr, NULL);
537 		if (reg & REG_MAP_REGISTERED) {
538 			pthread_mutex_unlock(&g_spdk_mem_map_mutex);
539 			return -EBUSY;
540 		}
541 		seg_vaddr += VALUE_2MB;
542 		seg_len -= VALUE_2MB;
543 	}
544 
545 	/* Simply set the translation to the memory map's default. This allocates the space in the
546 	 * map but does not provide a valid translation. */
547 	spdk_mem_map_set_translation(g_mem_reg_map, (uint64_t)vaddr, len,
548 				     g_mem_reg_map->default_translation);
549 
550 	TAILQ_FOREACH(map, &g_spdk_mem_maps, tailq) {
551 		spdk_mem_map_set_translation(map, (uint64_t)vaddr, len, map->default_translation);
552 	}
553 
554 	pthread_mutex_unlock(&g_spdk_mem_map_mutex);
555 	return 0;
556 }
557 
558 static struct map_1gb *
559 mem_map_get_map_1gb(struct spdk_mem_map *map, uint64_t vfn_2mb)
560 {
561 	struct map_1gb *map_1gb;
562 	uint64_t idx_256tb = MAP_256TB_IDX(vfn_2mb);
563 	size_t i;
564 
565 	if (spdk_unlikely(idx_256tb >= SPDK_COUNTOF(map->map_256tb.map))) {
566 		return NULL;
567 	}
568 
569 	map_1gb = map->map_256tb.map[idx_256tb];
570 
571 	if (!map_1gb) {
572 		pthread_mutex_lock(&map->mutex);
573 
574 		/* Recheck to make sure nobody else got the mutex first. */
575 		map_1gb = map->map_256tb.map[idx_256tb];
576 		if (!map_1gb) {
577 			map_1gb = malloc(sizeof(struct map_1gb));
578 			if (map_1gb) {
579 				/* initialize all entries to default translation */
580 				for (i = 0; i < SPDK_COUNTOF(map_1gb->map); i++) {
581 					map_1gb->map[i].translation_2mb = map->default_translation;
582 				}
583 				map->map_256tb.map[idx_256tb] = map_1gb;
584 			}
585 		}
586 
587 		pthread_mutex_unlock(&map->mutex);
588 
589 		if (!map_1gb) {
590 			DEBUG_PRINT("allocation failed\n");
591 			return NULL;
592 		}
593 	}
594 
595 	return map_1gb;
596 }
597 
598 int
599 spdk_mem_map_set_translation(struct spdk_mem_map *map, uint64_t vaddr, uint64_t size,
600 			     uint64_t translation)
601 {
602 	uint64_t vfn_2mb;
603 	struct map_1gb *map_1gb;
604 	uint64_t idx_1gb;
605 	struct map_2mb *map_2mb;
606 
607 	if ((uintptr_t)vaddr & ~MASK_256TB) {
608 		DEBUG_PRINT("invalid usermode virtual address %" PRIu64 "\n", vaddr);
609 		return -EINVAL;
610 	}
611 
612 	/* For now, only 2 MB-aligned registrations are supported */
613 	if (((uintptr_t)vaddr & MASK_2MB) || (size & MASK_2MB)) {
614 		DEBUG_PRINT("invalid %s parameters, vaddr=%" PRIu64 " len=%" PRIu64 "\n",
615 			    __func__, vaddr, size);
616 		return -EINVAL;
617 	}
618 
619 	vfn_2mb = vaddr >> SHIFT_2MB;
620 
621 	while (size) {
622 		map_1gb = mem_map_get_map_1gb(map, vfn_2mb);
623 		if (!map_1gb) {
624 			DEBUG_PRINT("could not get %p map\n", (void *)vaddr);
625 			return -ENOMEM;
626 		}
627 
628 		idx_1gb = MAP_1GB_IDX(vfn_2mb);
629 		map_2mb = &map_1gb->map[idx_1gb];
630 		map_2mb->translation_2mb = translation;
631 
632 		size -= VALUE_2MB;
633 		vfn_2mb++;
634 	}
635 
636 	return 0;
637 }
638 
639 int
640 spdk_mem_map_clear_translation(struct spdk_mem_map *map, uint64_t vaddr, uint64_t size)
641 {
642 	return spdk_mem_map_set_translation(map, vaddr, size, map->default_translation);
643 }
644 
645 inline uint64_t
646 spdk_mem_map_translate(const struct spdk_mem_map *map, uint64_t vaddr, uint64_t *size)
647 {
648 	const struct map_1gb *map_1gb;
649 	const struct map_2mb *map_2mb;
650 	uint64_t idx_256tb;
651 	uint64_t idx_1gb;
652 	uint64_t vfn_2mb;
653 	uint64_t cur_size;
654 	uint64_t prev_translation;
655 	uint64_t orig_translation;
656 
657 	if (spdk_unlikely(vaddr & ~MASK_256TB)) {
658 		DEBUG_PRINT("invalid usermode virtual address %p\n", (void *)vaddr);
659 		return map->default_translation;
660 	}
661 
662 	vfn_2mb = vaddr >> SHIFT_2MB;
663 	idx_256tb = MAP_256TB_IDX(vfn_2mb);
664 	idx_1gb = MAP_1GB_IDX(vfn_2mb);
665 
666 	map_1gb = map->map_256tb.map[idx_256tb];
667 	if (spdk_unlikely(!map_1gb)) {
668 		return map->default_translation;
669 	}
670 
671 	cur_size = VALUE_2MB - _2MB_OFFSET(vaddr);
672 	map_2mb = &map_1gb->map[idx_1gb];
673 	if (size == NULL || map->ops.are_contiguous == NULL ||
674 	    map_2mb->translation_2mb == map->default_translation) {
675 		if (size != NULL) {
676 			*size = spdk_min(*size, cur_size);
677 		}
678 		return map_2mb->translation_2mb;
679 	}
680 
681 	orig_translation = map_2mb->translation_2mb;
682 	prev_translation = orig_translation;
683 	while (cur_size < *size) {
684 		vfn_2mb++;
685 		idx_256tb = MAP_256TB_IDX(vfn_2mb);
686 		idx_1gb = MAP_1GB_IDX(vfn_2mb);
687 
688 		map_1gb = map->map_256tb.map[idx_256tb];
689 		if (spdk_unlikely(!map_1gb)) {
690 			break;
691 		}
692 
693 		map_2mb = &map_1gb->map[idx_1gb];
694 		if (!map->ops.are_contiguous(prev_translation, map_2mb->translation_2mb)) {
695 			break;
696 		}
697 
698 		cur_size += VALUE_2MB;
699 		prev_translation = map_2mb->translation_2mb;
700 	}
701 
702 	*size = spdk_min(*size, cur_size);
703 	return orig_translation;
704 }
705 
706 static void
707 memory_hotplug_cb(enum rte_mem_event event_type,
708 		  const void *addr, size_t len, void *arg)
709 {
710 	if (event_type == RTE_MEM_EVENT_ALLOC) {
711 		spdk_mem_register((void *)addr, len);
712 
713 		if (!spdk_env_dpdk_external_init()) {
714 			return;
715 		}
716 
717 		/* When the user initialized DPDK separately, we can't
718 		 * be sure that --match-allocations RTE flag was specified.
719 		 * Without this flag, DPDK can free memory in different units
720 		 * than it was allocated. It doesn't work with things like RDMA MRs.
721 		 *
722 		 * For such cases, we mark segments so they aren't freed.
723 		 */
724 		while (len > 0) {
725 			struct rte_memseg *seg;
726 
727 			seg = rte_mem_virt2memseg(addr, NULL);
728 			assert(seg != NULL);
729 			seg->flags |= RTE_MEMSEG_FLAG_DO_NOT_FREE;
730 			addr = (void *)((uintptr_t)addr + seg->hugepage_sz);
731 			len -= seg->hugepage_sz;
732 		}
733 	} else if (event_type == RTE_MEM_EVENT_FREE) {
734 		spdk_mem_unregister((void *)addr, len);
735 	}
736 }
737 
738 static int
739 memory_iter_cb(const struct rte_memseg_list *msl,
740 	       const struct rte_memseg *ms, size_t len, void *arg)
741 {
742 	return spdk_mem_register(ms->addr, len);
743 }
744 
745 int
746 mem_map_init(bool legacy_mem)
747 {
748 	g_legacy_mem = legacy_mem;
749 
750 	g_mem_reg_map = spdk_mem_map_alloc(0, NULL, NULL);
751 	if (g_mem_reg_map == NULL) {
752 		DEBUG_PRINT("memory registration map allocation failed\n");
753 		return -ENOMEM;
754 	}
755 
756 	/*
757 	 * Walk all DPDK memory segments and register them
758 	 * with the main memory map
759 	 */
760 	rte_mem_event_callback_register("spdk", memory_hotplug_cb, NULL);
761 	rte_memseg_contig_walk(memory_iter_cb, NULL);
762 	return 0;
763 }
764 
765 bool
766 spdk_iommu_is_enabled(void)
767 {
768 #if VFIO_ENABLED
769 	return g_vfio.enabled && !g_vfio.noiommu_enabled;
770 #else
771 	return false;
772 #endif
773 }
774 
775 struct spdk_vtophys_pci_device {
776 	struct rte_pci_device *pci_device;
777 	TAILQ_ENTRY(spdk_vtophys_pci_device) tailq;
778 };
779 
780 static pthread_mutex_t g_vtophys_pci_devices_mutex = PTHREAD_MUTEX_INITIALIZER;
781 static TAILQ_HEAD(, spdk_vtophys_pci_device) g_vtophys_pci_devices =
782 	TAILQ_HEAD_INITIALIZER(g_vtophys_pci_devices);
783 
784 static struct spdk_mem_map *g_vtophys_map;
785 static struct spdk_mem_map *g_phys_ref_map;
786 
787 #if VFIO_ENABLED
788 static int
789 vtophys_iommu_map_dma(uint64_t vaddr, uint64_t iova, uint64_t size)
790 {
791 	struct spdk_vfio_dma_map *dma_map;
792 	uint64_t refcount;
793 	int ret;
794 
795 	refcount = spdk_mem_map_translate(g_phys_ref_map, iova, NULL);
796 	assert(refcount < UINT64_MAX);
797 	if (refcount > 0) {
798 		spdk_mem_map_set_translation(g_phys_ref_map, iova, size, refcount + 1);
799 		return 0;
800 	}
801 
802 	dma_map = calloc(1, sizeof(*dma_map));
803 	if (dma_map == NULL) {
804 		return -ENOMEM;
805 	}
806 
807 	dma_map->map.argsz = sizeof(dma_map->map);
808 	dma_map->map.flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE;
809 	dma_map->map.vaddr = vaddr;
810 	dma_map->map.iova = iova;
811 	dma_map->map.size = size;
812 
813 	pthread_mutex_lock(&g_vfio.mutex);
814 	if (g_vfio.device_ref == 0) {
815 		/* VFIO requires at least one device (IOMMU group) to be added to
816 		 * a VFIO container before it is possible to perform any IOMMU
817 		 * operations on that container. This memory will be mapped once
818 		 * the first device (IOMMU group) is hotplugged.
819 		 *
820 		 * Since the vfio container is managed internally by DPDK, it is
821 		 * also possible that some device is already in that container, but
822 		 * it's not managed by SPDK -  e.g. an NIC attached internally
823 		 * inside DPDK. We could map the memory straight away in such
824 		 * scenario, but there's no need to do it. DPDK devices clearly
825 		 * don't need our mappings and hence we defer the mapping
826 		 * unconditionally until the first SPDK-managed device is
827 		 * hotplugged.
828 		 */
829 		goto out_insert;
830 	}
831 
832 	ret = ioctl(g_vfio.fd, VFIO_IOMMU_MAP_DMA, &dma_map->map);
833 	if (ret) {
834 		/* There are cases the vfio container doesn't have IOMMU group, it's safe for this case */
835 		SPDK_NOTICELOG("Cannot set up DMA mapping, error %d, ignored\n", errno);
836 	}
837 
838 out_insert:
839 	TAILQ_INSERT_TAIL(&g_vfio.maps, dma_map, tailq);
840 	pthread_mutex_unlock(&g_vfio.mutex);
841 	spdk_mem_map_set_translation(g_phys_ref_map, iova, size, refcount + 1);
842 	return 0;
843 }
844 
845 static int
846 vtophys_iommu_unmap_dma(uint64_t iova, uint64_t size)
847 {
848 	struct spdk_vfio_dma_map *dma_map;
849 	uint64_t refcount;
850 	int ret;
851 	struct vfio_iommu_type1_dma_unmap unmap = {};
852 
853 	pthread_mutex_lock(&g_vfio.mutex);
854 	TAILQ_FOREACH(dma_map, &g_vfio.maps, tailq) {
855 		if (dma_map->map.iova == iova) {
856 			break;
857 		}
858 	}
859 
860 	if (dma_map == NULL) {
861 		DEBUG_PRINT("Cannot clear DMA mapping for IOVA %"PRIx64" - it's not mapped\n", iova);
862 		pthread_mutex_unlock(&g_vfio.mutex);
863 		return -ENXIO;
864 	}
865 
866 	refcount = spdk_mem_map_translate(g_phys_ref_map, iova, NULL);
867 	assert(refcount < UINT64_MAX);
868 	if (refcount > 0) {
869 		spdk_mem_map_set_translation(g_phys_ref_map, iova, size, refcount - 1);
870 	}
871 
872 	/* We still have outstanding references, don't clear it. */
873 	if (refcount > 1) {
874 		pthread_mutex_unlock(&g_vfio.mutex);
875 		return 0;
876 	}
877 
878 	/** don't support partial or multiple-page unmap for now */
879 	assert(dma_map->map.size == size);
880 
881 	if (g_vfio.device_ref == 0) {
882 		/* Memory is not mapped anymore, just remove it's references */
883 		goto out_remove;
884 	}
885 
886 	unmap.argsz = sizeof(unmap);
887 	unmap.flags = 0;
888 	unmap.iova = dma_map->map.iova;
889 	unmap.size = dma_map->map.size;
890 	ret = ioctl(g_vfio.fd, VFIO_IOMMU_UNMAP_DMA, &unmap);
891 	if (ret) {
892 		SPDK_NOTICELOG("Cannot clear DMA mapping, error %d, ignored\n", errno);
893 	}
894 
895 out_remove:
896 	TAILQ_REMOVE(&g_vfio.maps, dma_map, tailq);
897 	pthread_mutex_unlock(&g_vfio.mutex);
898 	free(dma_map);
899 	return 0;
900 }
901 #endif
902 
903 static uint64_t
904 vtophys_get_paddr_memseg(uint64_t vaddr)
905 {
906 	uintptr_t paddr;
907 	struct rte_memseg *seg;
908 
909 	seg = rte_mem_virt2memseg((void *)(uintptr_t)vaddr, NULL);
910 	if (seg != NULL) {
911 		paddr = seg->iova;
912 		if (paddr == RTE_BAD_IOVA) {
913 			return SPDK_VTOPHYS_ERROR;
914 		}
915 		paddr += (vaddr - (uintptr_t)seg->addr);
916 		return paddr;
917 	}
918 
919 	return SPDK_VTOPHYS_ERROR;
920 }
921 
922 /* Try to get the paddr from /proc/self/pagemap */
923 static uint64_t
924 vtophys_get_paddr_pagemap(uint64_t vaddr)
925 {
926 	uintptr_t paddr;
927 
928 	/* Silence static analyzers */
929 	assert(vaddr != 0);
930 	paddr = rte_mem_virt2iova((void *)vaddr);
931 	if (paddr == RTE_BAD_IOVA) {
932 		/*
933 		 * The vaddr may be valid but doesn't have a backing page
934 		 * assigned yet.  Touch the page to ensure a backing page
935 		 * gets assigned, then try to translate again.
936 		 */
937 		rte_atomic64_read((rte_atomic64_t *)vaddr);
938 		paddr = rte_mem_virt2iova((void *)vaddr);
939 	}
940 	if (paddr == RTE_BAD_IOVA) {
941 		/* Unable to get to the physical address. */
942 		return SPDK_VTOPHYS_ERROR;
943 	}
944 
945 	return paddr;
946 }
947 
948 /* Try to get the paddr from pci devices */
949 static uint64_t
950 vtophys_get_paddr_pci(uint64_t vaddr)
951 {
952 	struct spdk_vtophys_pci_device *vtophys_dev;
953 	uintptr_t paddr;
954 	struct rte_pci_device	*dev;
955 	struct rte_mem_resource *res;
956 	unsigned r;
957 
958 	pthread_mutex_lock(&g_vtophys_pci_devices_mutex);
959 	TAILQ_FOREACH(vtophys_dev, &g_vtophys_pci_devices, tailq) {
960 		dev = vtophys_dev->pci_device;
961 
962 		for (r = 0; r < PCI_MAX_RESOURCE; r++) {
963 			res = &dev->mem_resource[r];
964 			if (res->phys_addr && vaddr >= (uint64_t)res->addr &&
965 			    vaddr < (uint64_t)res->addr + res->len) {
966 				paddr = res->phys_addr + (vaddr - (uint64_t)res->addr);
967 				DEBUG_PRINT("%s: %p -> %p\n", __func__, (void *)vaddr,
968 					    (void *)paddr);
969 				pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
970 				return paddr;
971 			}
972 		}
973 	}
974 	pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
975 
976 	return  SPDK_VTOPHYS_ERROR;
977 }
978 
979 static int
980 vtophys_notify(void *cb_ctx, struct spdk_mem_map *map,
981 	       enum spdk_mem_map_notify_action action,
982 	       void *vaddr, size_t len)
983 {
984 	int rc = 0, pci_phys = 0;
985 	uint64_t paddr;
986 
987 	if ((uintptr_t)vaddr & ~MASK_256TB) {
988 		DEBUG_PRINT("invalid usermode virtual address %p\n", vaddr);
989 		return -EINVAL;
990 	}
991 
992 	if (((uintptr_t)vaddr & MASK_2MB) || (len & MASK_2MB)) {
993 		DEBUG_PRINT("invalid parameters, vaddr=%p len=%ju\n",
994 			    vaddr, len);
995 		return -EINVAL;
996 	}
997 
998 	/* Get the physical address from the DPDK memsegs */
999 	paddr = vtophys_get_paddr_memseg((uint64_t)vaddr);
1000 
1001 	switch (action) {
1002 	case SPDK_MEM_MAP_NOTIFY_REGISTER:
1003 		if (paddr == SPDK_VTOPHYS_ERROR) {
1004 			/* This is not an address that DPDK is managing. */
1005 #if VFIO_ENABLED
1006 			enum rte_iova_mode iova_mode;
1007 
1008 			iova_mode = rte_eal_iova_mode();
1009 
1010 			if (spdk_iommu_is_enabled() && iova_mode == RTE_IOVA_VA) {
1011 				/* We'll use the virtual address as the iova to match DPDK. */
1012 				paddr = (uint64_t)vaddr;
1013 				rc = vtophys_iommu_map_dma((uint64_t)vaddr, paddr, len);
1014 				if (rc) {
1015 					return -EFAULT;
1016 				}
1017 				while (len > 0) {
1018 					rc = spdk_mem_map_set_translation(map, (uint64_t)vaddr, VALUE_2MB, paddr);
1019 					if (rc != 0) {
1020 						return rc;
1021 					}
1022 					vaddr += VALUE_2MB;
1023 					paddr += VALUE_2MB;
1024 					len -= VALUE_2MB;
1025 				}
1026 			} else
1027 #endif
1028 			{
1029 				/* Get the physical address from /proc/self/pagemap. */
1030 				paddr = vtophys_get_paddr_pagemap((uint64_t)vaddr);
1031 				if (paddr == SPDK_VTOPHYS_ERROR) {
1032 					/* Get the physical address from PCI devices */
1033 					paddr = vtophys_get_paddr_pci((uint64_t)vaddr);
1034 					if (paddr == SPDK_VTOPHYS_ERROR) {
1035 						DEBUG_PRINT("could not get phys addr for %p\n", vaddr);
1036 						return -EFAULT;
1037 					}
1038 					/* The beginning of this address range points to a PCI resource,
1039 					 * so the rest must point to a PCI resource as well.
1040 					 */
1041 					pci_phys = 1;
1042 				}
1043 
1044 				/* Get paddr for each 2MB chunk in this address range */
1045 				while (len > 0) {
1046 					/* Get the physical address from /proc/self/pagemap. */
1047 					if (pci_phys) {
1048 						paddr = vtophys_get_paddr_pci((uint64_t)vaddr);
1049 					} else {
1050 						paddr = vtophys_get_paddr_pagemap((uint64_t)vaddr);
1051 					}
1052 
1053 					if (paddr == SPDK_VTOPHYS_ERROR) {
1054 						DEBUG_PRINT("could not get phys addr for %p\n", vaddr);
1055 						return -EFAULT;
1056 					}
1057 
1058 					/* Since PCI paddr can break the 2MiB physical alignment skip this check for that. */
1059 					if (!pci_phys && (paddr & MASK_2MB)) {
1060 						DEBUG_PRINT("invalid paddr 0x%" PRIx64 " - must be 2MB aligned\n", paddr);
1061 						return -EINVAL;
1062 					}
1063 #if VFIO_ENABLED
1064 					/* If the IOMMU is on, but DPDK is using iova-mode=pa, we want to register this memory
1065 					 * with the IOMMU using the physical address to match. */
1066 					if (spdk_iommu_is_enabled()) {
1067 						rc = vtophys_iommu_map_dma((uint64_t)vaddr, paddr, VALUE_2MB);
1068 						if (rc) {
1069 							DEBUG_PRINT("Unable to assign vaddr %p to paddr 0x%" PRIx64 "\n", vaddr, paddr);
1070 							return -EFAULT;
1071 						}
1072 					}
1073 #endif
1074 
1075 					rc = spdk_mem_map_set_translation(map, (uint64_t)vaddr, VALUE_2MB, paddr);
1076 					if (rc != 0) {
1077 						return rc;
1078 					}
1079 
1080 					vaddr += VALUE_2MB;
1081 					len -= VALUE_2MB;
1082 				}
1083 			}
1084 		} else {
1085 			/* This is an address managed by DPDK. Just setup the translations. */
1086 			while (len > 0) {
1087 				paddr = vtophys_get_paddr_memseg((uint64_t)vaddr);
1088 				if (paddr == SPDK_VTOPHYS_ERROR) {
1089 					DEBUG_PRINT("could not get phys addr for %p\n", vaddr);
1090 					return -EFAULT;
1091 				}
1092 
1093 				rc = spdk_mem_map_set_translation(map, (uint64_t)vaddr, VALUE_2MB, paddr);
1094 				if (rc != 0) {
1095 					return rc;
1096 				}
1097 
1098 				vaddr += VALUE_2MB;
1099 				len -= VALUE_2MB;
1100 			}
1101 		}
1102 
1103 		break;
1104 	case SPDK_MEM_MAP_NOTIFY_UNREGISTER:
1105 #if VFIO_ENABLED
1106 		if (paddr == SPDK_VTOPHYS_ERROR) {
1107 			/*
1108 			 * This is not an address that DPDK is managing. If vfio is enabled,
1109 			 * we need to unmap the range from the IOMMU
1110 			 */
1111 			if (spdk_iommu_is_enabled()) {
1112 				uint64_t buffer_len = len;
1113 				uint8_t *va = vaddr;
1114 				enum rte_iova_mode iova_mode;
1115 
1116 				iova_mode = rte_eal_iova_mode();
1117 				/*
1118 				 * In virtual address mode, the region is contiguous and can be done in
1119 				 * one unmap.
1120 				 */
1121 				if (iova_mode == RTE_IOVA_VA) {
1122 					paddr = spdk_mem_map_translate(map, (uint64_t)va, &buffer_len);
1123 					if (buffer_len != len || paddr != (uintptr_t)va) {
1124 						DEBUG_PRINT("Unmapping %p with length %lu failed because "
1125 							    "translation had address 0x%" PRIx64 " and length %lu\n",
1126 							    va, len, paddr, buffer_len);
1127 						return -EINVAL;
1128 					}
1129 					rc = vtophys_iommu_unmap_dma(paddr, len);
1130 					if (rc) {
1131 						DEBUG_PRINT("Failed to iommu unmap paddr 0x%" PRIx64 "\n", paddr);
1132 						return -EFAULT;
1133 					}
1134 				} else if (iova_mode == RTE_IOVA_PA) {
1135 					/* Get paddr for each 2MB chunk in this address range */
1136 					while (buffer_len > 0) {
1137 						paddr = spdk_mem_map_translate(map, (uint64_t)va, NULL);
1138 
1139 						if (paddr == SPDK_VTOPHYS_ERROR || buffer_len < VALUE_2MB) {
1140 							DEBUG_PRINT("could not get phys addr for %p\n", va);
1141 							return -EFAULT;
1142 						}
1143 
1144 						rc = vtophys_iommu_unmap_dma(paddr, VALUE_2MB);
1145 						if (rc) {
1146 							DEBUG_PRINT("Failed to iommu unmap paddr 0x%" PRIx64 "\n", paddr);
1147 							return -EFAULT;
1148 						}
1149 
1150 						va += VALUE_2MB;
1151 						buffer_len -= VALUE_2MB;
1152 					}
1153 				}
1154 			}
1155 		}
1156 #endif
1157 		while (len > 0) {
1158 			rc = spdk_mem_map_clear_translation(map, (uint64_t)vaddr, VALUE_2MB);
1159 			if (rc != 0) {
1160 				return rc;
1161 			}
1162 
1163 			vaddr += VALUE_2MB;
1164 			len -= VALUE_2MB;
1165 		}
1166 
1167 		break;
1168 	default:
1169 		SPDK_UNREACHABLE();
1170 	}
1171 
1172 	return rc;
1173 }
1174 
1175 static int
1176 vtophys_check_contiguous_entries(uint64_t paddr1, uint64_t paddr2)
1177 {
1178 	/* This function is always called with paddrs for two subsequent
1179 	 * 2MB chunks in virtual address space, so those chunks will be only
1180 	 * physically contiguous if the physical addresses are 2MB apart
1181 	 * from each other as well.
1182 	 */
1183 	return (paddr2 - paddr1 == VALUE_2MB);
1184 }
1185 
1186 #if VFIO_ENABLED
1187 
1188 static bool
1189 vfio_enabled(void)
1190 {
1191 	return rte_vfio_is_enabled("vfio_pci");
1192 }
1193 
1194 /* Check if IOMMU is enabled on the system */
1195 static bool
1196 has_iommu_groups(void)
1197 {
1198 	int count = 0;
1199 	DIR *dir = opendir("/sys/kernel/iommu_groups");
1200 
1201 	if (dir == NULL) {
1202 		return false;
1203 	}
1204 
1205 	while (count < 3 && readdir(dir) != NULL) {
1206 		count++;
1207 	}
1208 
1209 	closedir(dir);
1210 	/* there will always be ./ and ../ entries */
1211 	return count > 2;
1212 }
1213 
1214 static bool
1215 vfio_noiommu_enabled(void)
1216 {
1217 	return rte_vfio_noiommu_is_enabled();
1218 }
1219 
1220 static void
1221 vtophys_iommu_init(void)
1222 {
1223 	char proc_fd_path[PATH_MAX + 1];
1224 	char link_path[PATH_MAX + 1];
1225 	const char vfio_path[] = "/dev/vfio/vfio";
1226 	DIR *dir;
1227 	struct dirent *d;
1228 
1229 	if (!vfio_enabled()) {
1230 		return;
1231 	}
1232 
1233 	if (vfio_noiommu_enabled()) {
1234 		g_vfio.noiommu_enabled = true;
1235 	} else if (!has_iommu_groups()) {
1236 		return;
1237 	}
1238 
1239 	dir = opendir("/proc/self/fd");
1240 	if (!dir) {
1241 		DEBUG_PRINT("Failed to open /proc/self/fd (%d)\n", errno);
1242 		return;
1243 	}
1244 
1245 	while ((d = readdir(dir)) != NULL) {
1246 		if (d->d_type != DT_LNK) {
1247 			continue;
1248 		}
1249 
1250 		snprintf(proc_fd_path, sizeof(proc_fd_path), "/proc/self/fd/%s", d->d_name);
1251 		if (readlink(proc_fd_path, link_path, sizeof(link_path)) != (sizeof(vfio_path) - 1)) {
1252 			continue;
1253 		}
1254 
1255 		if (memcmp(link_path, vfio_path, sizeof(vfio_path) - 1) == 0) {
1256 			sscanf(d->d_name, "%d", &g_vfio.fd);
1257 			break;
1258 		}
1259 	}
1260 
1261 	closedir(dir);
1262 
1263 	if (g_vfio.fd < 0) {
1264 		DEBUG_PRINT("Failed to discover DPDK VFIO container fd.\n");
1265 		return;
1266 	}
1267 
1268 	g_vfio.enabled = true;
1269 
1270 	return;
1271 }
1272 
1273 #endif
1274 
1275 void
1276 vtophys_pci_device_added(struct rte_pci_device *pci_device)
1277 {
1278 	struct spdk_vtophys_pci_device *vtophys_dev;
1279 
1280 	pthread_mutex_lock(&g_vtophys_pci_devices_mutex);
1281 
1282 	vtophys_dev = calloc(1, sizeof(*vtophys_dev));
1283 	if (vtophys_dev) {
1284 		vtophys_dev->pci_device = pci_device;
1285 		TAILQ_INSERT_TAIL(&g_vtophys_pci_devices, vtophys_dev, tailq);
1286 	} else {
1287 		DEBUG_PRINT("Memory allocation error\n");
1288 	}
1289 	pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
1290 
1291 #if VFIO_ENABLED
1292 	struct spdk_vfio_dma_map *dma_map;
1293 	int ret;
1294 
1295 	if (!g_vfio.enabled) {
1296 		return;
1297 	}
1298 
1299 	pthread_mutex_lock(&g_vfio.mutex);
1300 	g_vfio.device_ref++;
1301 	if (g_vfio.device_ref > 1) {
1302 		pthread_mutex_unlock(&g_vfio.mutex);
1303 		return;
1304 	}
1305 
1306 	/* This is the first SPDK device using DPDK vfio. This means that the first
1307 	 * IOMMU group might have been just been added to the DPDK vfio container.
1308 	 * From this point it is certain that the memory can be mapped now.
1309 	 */
1310 	TAILQ_FOREACH(dma_map, &g_vfio.maps, tailq) {
1311 		ret = ioctl(g_vfio.fd, VFIO_IOMMU_MAP_DMA, &dma_map->map);
1312 		if (ret) {
1313 			DEBUG_PRINT("Cannot update DMA mapping, error %d\n", errno);
1314 			break;
1315 		}
1316 	}
1317 	pthread_mutex_unlock(&g_vfio.mutex);
1318 #endif
1319 }
1320 
1321 void
1322 vtophys_pci_device_removed(struct rte_pci_device *pci_device)
1323 {
1324 	struct spdk_vtophys_pci_device *vtophys_dev;
1325 
1326 	pthread_mutex_lock(&g_vtophys_pci_devices_mutex);
1327 	TAILQ_FOREACH(vtophys_dev, &g_vtophys_pci_devices, tailq) {
1328 		if (vtophys_dev->pci_device == pci_device) {
1329 			TAILQ_REMOVE(&g_vtophys_pci_devices, vtophys_dev, tailq);
1330 			free(vtophys_dev);
1331 			break;
1332 		}
1333 	}
1334 	pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
1335 
1336 #if VFIO_ENABLED
1337 	struct spdk_vfio_dma_map *dma_map;
1338 	int ret;
1339 
1340 	if (!g_vfio.enabled) {
1341 		return;
1342 	}
1343 
1344 	pthread_mutex_lock(&g_vfio.mutex);
1345 	assert(g_vfio.device_ref > 0);
1346 	g_vfio.device_ref--;
1347 	if (g_vfio.device_ref > 0) {
1348 		pthread_mutex_unlock(&g_vfio.mutex);
1349 		return;
1350 	}
1351 
1352 	/* This is the last SPDK device using DPDK vfio. If DPDK doesn't have
1353 	 * any additional devices using it's vfio container, all the mappings
1354 	 * will be automatically removed by the Linux vfio driver. We unmap
1355 	 * the memory manually to be able to easily re-map it later regardless
1356 	 * of other, external factors.
1357 	 */
1358 	TAILQ_FOREACH(dma_map, &g_vfio.maps, tailq) {
1359 		struct vfio_iommu_type1_dma_unmap unmap = {};
1360 		unmap.argsz = sizeof(unmap);
1361 		unmap.flags = 0;
1362 		unmap.iova = dma_map->map.iova;
1363 		unmap.size = dma_map->map.size;
1364 		ret = ioctl(g_vfio.fd, VFIO_IOMMU_UNMAP_DMA, &unmap);
1365 		if (ret) {
1366 			DEBUG_PRINT("Cannot unmap DMA memory, error %d\n", errno);
1367 			break;
1368 		}
1369 	}
1370 	pthread_mutex_unlock(&g_vfio.mutex);
1371 #endif
1372 }
1373 
1374 int
1375 vtophys_init(void)
1376 {
1377 	const struct spdk_mem_map_ops vtophys_map_ops = {
1378 		.notify_cb = vtophys_notify,
1379 		.are_contiguous = vtophys_check_contiguous_entries,
1380 	};
1381 
1382 	const struct spdk_mem_map_ops phys_ref_map_ops = {
1383 		.notify_cb = NULL,
1384 		.are_contiguous = NULL,
1385 	};
1386 
1387 #if VFIO_ENABLED
1388 	vtophys_iommu_init();
1389 #endif
1390 
1391 	g_phys_ref_map = spdk_mem_map_alloc(0, &phys_ref_map_ops, NULL);
1392 	if (g_phys_ref_map == NULL) {
1393 		DEBUG_PRINT("phys_ref map allocation failed.\n");
1394 		return -ENOMEM;
1395 	}
1396 
1397 	g_vtophys_map = spdk_mem_map_alloc(SPDK_VTOPHYS_ERROR, &vtophys_map_ops, NULL);
1398 	if (g_vtophys_map == NULL) {
1399 		DEBUG_PRINT("vtophys map allocation failed\n");
1400 		spdk_mem_map_free(&g_phys_ref_map);
1401 		return -ENOMEM;
1402 	}
1403 	return 0;
1404 }
1405 
1406 uint64_t
1407 spdk_vtophys(const void *buf, uint64_t *size)
1408 {
1409 	uint64_t vaddr, paddr_2mb;
1410 
1411 	vaddr = (uint64_t)buf;
1412 	paddr_2mb = spdk_mem_map_translate(g_vtophys_map, vaddr, size);
1413 
1414 	/*
1415 	 * SPDK_VTOPHYS_ERROR has all bits set, so if the lookup returned SPDK_VTOPHYS_ERROR,
1416 	 * we will still bitwise-or it with the buf offset below, but the result will still be
1417 	 * SPDK_VTOPHYS_ERROR. However now that we do + rather than | (due to PCI vtophys being
1418 	 * unaligned) we must now check the return value before addition.
1419 	 */
1420 	SPDK_STATIC_ASSERT(SPDK_VTOPHYS_ERROR == UINT64_C(-1), "SPDK_VTOPHYS_ERROR should be all 1s");
1421 	if (paddr_2mb == SPDK_VTOPHYS_ERROR) {
1422 		return SPDK_VTOPHYS_ERROR;
1423 	} else {
1424 		return paddr_2mb + (vaddr & MASK_2MB);
1425 	}
1426 }
1427 
1428 int
1429 spdk_mem_get_fd_and_offset(void *vaddr, uint64_t *offset)
1430 {
1431 	struct rte_memseg *seg;
1432 	int ret, fd;
1433 
1434 	seg = rte_mem_virt2memseg(vaddr, NULL);
1435 	if (!seg) {
1436 		SPDK_ERRLOG("memory %p doesn't exist\n", vaddr);
1437 		return -ENOENT;
1438 	}
1439 
1440 	fd = rte_memseg_get_fd_thread_unsafe(seg);
1441 	if (fd < 0) {
1442 		return fd;
1443 	}
1444 
1445 	ret = rte_memseg_get_fd_offset_thread_unsafe(seg, offset);
1446 	if (ret < 0) {
1447 		return ret;
1448 	}
1449 
1450 	return fd;
1451 }
1452