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