xref: /spdk/lib/env_dpdk/memory.c (revision ceea3088870a3919d6bdfe61d7adba11b9733fb7)
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 #if RTE_VERSION >= RTE_VERSION_NUM(19, 11, 0, 0)
927 		paddr = seg->iova;
928 #else
929 		paddr = seg->phys_addr;
930 #endif
931 		if (paddr == RTE_BAD_IOVA) {
932 			return SPDK_VTOPHYS_ERROR;
933 		}
934 		paddr += (vaddr - (uintptr_t)seg->addr);
935 		return paddr;
936 	}
937 
938 	return SPDK_VTOPHYS_ERROR;
939 }
940 
941 /* Try to get the paddr from /proc/self/pagemap */
942 static uint64_t
943 vtophys_get_paddr_pagemap(uint64_t vaddr)
944 {
945 	uintptr_t paddr;
946 
947 	/* Silence static analyzers */
948 	assert(vaddr != 0);
949 	paddr = rte_mem_virt2iova((void *)vaddr);
950 	if (paddr == RTE_BAD_IOVA) {
951 		/*
952 		 * The vaddr may be valid but doesn't have a backing page
953 		 * assigned yet.  Touch the page to ensure a backing page
954 		 * gets assigned, then try to translate again.
955 		 */
956 		rte_atomic64_read((rte_atomic64_t *)vaddr);
957 		paddr = rte_mem_virt2iova((void *)vaddr);
958 	}
959 	if (paddr == RTE_BAD_IOVA) {
960 		/* Unable to get to the physical address. */
961 		return SPDK_VTOPHYS_ERROR;
962 	}
963 
964 	return paddr;
965 }
966 
967 /* Try to get the paddr from pci devices */
968 static uint64_t
969 vtophys_get_paddr_pci(uint64_t vaddr)
970 {
971 	struct spdk_vtophys_pci_device *vtophys_dev;
972 	uintptr_t paddr;
973 	struct rte_pci_device	*dev;
974 	struct rte_mem_resource *res;
975 	unsigned r;
976 
977 	pthread_mutex_lock(&g_vtophys_pci_devices_mutex);
978 	TAILQ_FOREACH(vtophys_dev, &g_vtophys_pci_devices, tailq) {
979 		dev = vtophys_dev->pci_device;
980 
981 		for (r = 0; r < PCI_MAX_RESOURCE; r++) {
982 			res = &dev->mem_resource[r];
983 			if (res->phys_addr && vaddr >= (uint64_t)res->addr &&
984 			    vaddr < (uint64_t)res->addr + res->len) {
985 				paddr = res->phys_addr + (vaddr - (uint64_t)res->addr);
986 				DEBUG_PRINT("%s: %p -> %p\n", __func__, (void *)vaddr,
987 					    (void *)paddr);
988 				pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
989 				return paddr;
990 			}
991 		}
992 	}
993 	pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
994 
995 	return  SPDK_VTOPHYS_ERROR;
996 }
997 
998 static int
999 vtophys_notify(void *cb_ctx, struct spdk_mem_map *map,
1000 	       enum spdk_mem_map_notify_action action,
1001 	       void *vaddr, size_t len)
1002 {
1003 	int rc = 0, pci_phys = 0;
1004 	uint64_t paddr;
1005 
1006 	if ((uintptr_t)vaddr & ~MASK_256TB) {
1007 		DEBUG_PRINT("invalid usermode virtual address %p\n", vaddr);
1008 		return -EINVAL;
1009 	}
1010 
1011 	if (((uintptr_t)vaddr & MASK_2MB) || (len & MASK_2MB)) {
1012 		DEBUG_PRINT("invalid parameters, vaddr=%p len=%ju\n",
1013 			    vaddr, len);
1014 		return -EINVAL;
1015 	}
1016 
1017 	/* Get the physical address from the DPDK memsegs */
1018 	paddr = vtophys_get_paddr_memseg((uint64_t)vaddr);
1019 
1020 	switch (action) {
1021 	case SPDK_MEM_MAP_NOTIFY_REGISTER:
1022 		if (paddr == SPDK_VTOPHYS_ERROR) {
1023 			/* This is not an address that DPDK is managing. */
1024 #if VFIO_ENABLED
1025 			enum rte_iova_mode iova_mode;
1026 
1027 #if RTE_VERSION >= RTE_VERSION_NUM(19, 11, 0, 0)
1028 			iova_mode = rte_eal_iova_mode();
1029 #else
1030 			iova_mode = rte_eal_get_configuration()->iova_mode;
1031 #endif
1032 
1033 			if (spdk_iommu_is_enabled() && iova_mode == RTE_IOVA_VA) {
1034 				/* We'll use the virtual address as the iova to match DPDK. */
1035 				paddr = (uint64_t)vaddr;
1036 				rc = vtophys_iommu_map_dma((uint64_t)vaddr, paddr, len);
1037 				if (rc) {
1038 					return -EFAULT;
1039 				}
1040 				while (len > 0) {
1041 					rc = spdk_mem_map_set_translation(map, (uint64_t)vaddr, VALUE_2MB, paddr);
1042 					if (rc != 0) {
1043 						return rc;
1044 					}
1045 					vaddr += VALUE_2MB;
1046 					paddr += VALUE_2MB;
1047 					len -= VALUE_2MB;
1048 				}
1049 			} else
1050 #endif
1051 			{
1052 				/* Get the physical address from /proc/self/pagemap. */
1053 				paddr = vtophys_get_paddr_pagemap((uint64_t)vaddr);
1054 				if (paddr == SPDK_VTOPHYS_ERROR) {
1055 					/* Get the physical address from PCI devices */
1056 					paddr = vtophys_get_paddr_pci((uint64_t)vaddr);
1057 					if (paddr == SPDK_VTOPHYS_ERROR) {
1058 						DEBUG_PRINT("could not get phys addr for %p\n", vaddr);
1059 						return -EFAULT;
1060 					}
1061 					/* The beginning of this address range points to a PCI resource,
1062 					 * so the rest must point to a PCI resource as well.
1063 					 */
1064 					pci_phys = 1;
1065 				}
1066 
1067 				/* Get paddr for each 2MB chunk in this address range */
1068 				while (len > 0) {
1069 					/* Get the physical address from /proc/self/pagemap. */
1070 					if (pci_phys) {
1071 						paddr = vtophys_get_paddr_pci((uint64_t)vaddr);
1072 					} else {
1073 						paddr = vtophys_get_paddr_pagemap((uint64_t)vaddr);
1074 					}
1075 
1076 					if (paddr == SPDK_VTOPHYS_ERROR) {
1077 						DEBUG_PRINT("could not get phys addr for %p\n", vaddr);
1078 						return -EFAULT;
1079 					}
1080 
1081 					/* Since PCI paddr can break the 2MiB physical alignment skip this check for that. */
1082 					if (!pci_phys && (paddr & MASK_2MB)) {
1083 						DEBUG_PRINT("invalid paddr 0x%" PRIx64 " - must be 2MB aligned\n", paddr);
1084 						return -EINVAL;
1085 					}
1086 #if VFIO_ENABLED
1087 					/* If the IOMMU is on, but DPDK is using iova-mode=pa, we want to register this memory
1088 					 * with the IOMMU using the physical address to match. */
1089 					if (spdk_iommu_is_enabled()) {
1090 						rc = vtophys_iommu_map_dma((uint64_t)vaddr, paddr, VALUE_2MB);
1091 						if (rc) {
1092 							DEBUG_PRINT("Unable to assign vaddr %p to paddr 0x%" PRIx64 "\n", vaddr, paddr);
1093 							return -EFAULT;
1094 						}
1095 					}
1096 #endif
1097 
1098 					rc = spdk_mem_map_set_translation(map, (uint64_t)vaddr, VALUE_2MB, paddr);
1099 					if (rc != 0) {
1100 						return rc;
1101 					}
1102 
1103 					vaddr += VALUE_2MB;
1104 					len -= VALUE_2MB;
1105 				}
1106 			}
1107 		} else {
1108 			/* This is an address managed by DPDK. Just setup the translations. */
1109 			while (len > 0) {
1110 				paddr = vtophys_get_paddr_memseg((uint64_t)vaddr);
1111 				if (paddr == SPDK_VTOPHYS_ERROR) {
1112 					DEBUG_PRINT("could not get phys addr for %p\n", vaddr);
1113 					return -EFAULT;
1114 				}
1115 
1116 				rc = spdk_mem_map_set_translation(map, (uint64_t)vaddr, VALUE_2MB, paddr);
1117 				if (rc != 0) {
1118 					return rc;
1119 				}
1120 
1121 				vaddr += VALUE_2MB;
1122 				len -= VALUE_2MB;
1123 			}
1124 		}
1125 
1126 		break;
1127 	case SPDK_MEM_MAP_NOTIFY_UNREGISTER:
1128 #if VFIO_ENABLED
1129 		if (paddr == SPDK_VTOPHYS_ERROR) {
1130 			/*
1131 			 * This is not an address that DPDK is managing. If vfio is enabled,
1132 			 * we need to unmap the range from the IOMMU
1133 			 */
1134 			if (spdk_iommu_is_enabled()) {
1135 				uint64_t buffer_len = len;
1136 				uint8_t *va = vaddr;
1137 				enum rte_iova_mode iova_mode;
1138 
1139 #if RTE_VERSION >= RTE_VERSION_NUM(19, 11, 0, 0)
1140 				iova_mode = rte_eal_iova_mode();
1141 #else
1142 				iova_mode = rte_eal_get_configuration()->iova_mode;
1143 #endif
1144 				/*
1145 				 * In virtual address mode, the region is contiguous and can be done in
1146 				 * one unmap.
1147 				 */
1148 				if (iova_mode == RTE_IOVA_VA) {
1149 					paddr = spdk_mem_map_translate(map, (uint64_t)va, &buffer_len);
1150 					if (buffer_len != len || paddr != (uintptr_t)va) {
1151 						DEBUG_PRINT("Unmapping %p with length %lu failed because "
1152 							    "translation had address 0x%" PRIx64 " and length %lu\n",
1153 							    va, len, paddr, buffer_len);
1154 						return -EINVAL;
1155 					}
1156 					rc = vtophys_iommu_unmap_dma(paddr, len);
1157 					if (rc) {
1158 						DEBUG_PRINT("Failed to iommu unmap paddr 0x%" PRIx64 "\n", paddr);
1159 						return -EFAULT;
1160 					}
1161 				} else if (iova_mode == RTE_IOVA_PA) {
1162 					/* Get paddr for each 2MB chunk in this address range */
1163 					while (buffer_len > 0) {
1164 						paddr = spdk_mem_map_translate(map, (uint64_t)va, NULL);
1165 
1166 						if (paddr == SPDK_VTOPHYS_ERROR || buffer_len < VALUE_2MB) {
1167 							DEBUG_PRINT("could not get phys addr for %p\n", va);
1168 							return -EFAULT;
1169 						}
1170 
1171 						rc = vtophys_iommu_unmap_dma(paddr, VALUE_2MB);
1172 						if (rc) {
1173 							DEBUG_PRINT("Failed to iommu unmap paddr 0x%" PRIx64 "\n", paddr);
1174 							return -EFAULT;
1175 						}
1176 
1177 						va += VALUE_2MB;
1178 						buffer_len -= VALUE_2MB;
1179 					}
1180 				}
1181 			}
1182 		}
1183 #endif
1184 		while (len > 0) {
1185 			rc = spdk_mem_map_clear_translation(map, (uint64_t)vaddr, VALUE_2MB);
1186 			if (rc != 0) {
1187 				return rc;
1188 			}
1189 
1190 			vaddr += VALUE_2MB;
1191 			len -= VALUE_2MB;
1192 		}
1193 
1194 		break;
1195 	default:
1196 		SPDK_UNREACHABLE();
1197 	}
1198 
1199 	return rc;
1200 }
1201 
1202 static int
1203 vtophys_check_contiguous_entries(uint64_t paddr1, uint64_t paddr2)
1204 {
1205 	/* This function is always called with paddrs for two subsequent
1206 	 * 2MB chunks in virtual address space, so those chunks will be only
1207 	 * physically contiguous if the physical addresses are 2MB apart
1208 	 * from each other as well.
1209 	 */
1210 	return (paddr2 - paddr1 == VALUE_2MB);
1211 }
1212 
1213 #if VFIO_ENABLED
1214 
1215 static bool
1216 vfio_enabled(void)
1217 {
1218 	return rte_vfio_is_enabled("vfio_pci");
1219 }
1220 
1221 /* Check if IOMMU is enabled on the system */
1222 static bool
1223 has_iommu_groups(void)
1224 {
1225 	struct dirent *d;
1226 	int count = 0;
1227 	DIR *dir = opendir("/sys/kernel/iommu_groups");
1228 
1229 	if (dir == NULL) {
1230 		return false;
1231 	}
1232 
1233 	while (count < 3 && (d = readdir(dir)) != NULL) {
1234 		count++;
1235 	}
1236 
1237 	closedir(dir);
1238 	/* there will always be ./ and ../ entries */
1239 	return count > 2;
1240 }
1241 
1242 static bool
1243 vfio_noiommu_enabled(void)
1244 {
1245 	return rte_vfio_noiommu_is_enabled();
1246 }
1247 
1248 static void
1249 vtophys_iommu_init(void)
1250 {
1251 	char proc_fd_path[PATH_MAX + 1];
1252 	char link_path[PATH_MAX + 1];
1253 	const char vfio_path[] = "/dev/vfio/vfio";
1254 	DIR *dir;
1255 	struct dirent *d;
1256 
1257 	if (!vfio_enabled()) {
1258 		return;
1259 	}
1260 
1261 	if (vfio_noiommu_enabled()) {
1262 		g_vfio.noiommu_enabled = true;
1263 	} else if (!has_iommu_groups()) {
1264 		return;
1265 	}
1266 
1267 	dir = opendir("/proc/self/fd");
1268 	if (!dir) {
1269 		DEBUG_PRINT("Failed to open /proc/self/fd (%d)\n", errno);
1270 		return;
1271 	}
1272 
1273 	while ((d = readdir(dir)) != NULL) {
1274 		if (d->d_type != DT_LNK) {
1275 			continue;
1276 		}
1277 
1278 		snprintf(proc_fd_path, sizeof(proc_fd_path), "/proc/self/fd/%s", d->d_name);
1279 		if (readlink(proc_fd_path, link_path, sizeof(link_path)) != (sizeof(vfio_path) - 1)) {
1280 			continue;
1281 		}
1282 
1283 		if (memcmp(link_path, vfio_path, sizeof(vfio_path) - 1) == 0) {
1284 			sscanf(d->d_name, "%d", &g_vfio.fd);
1285 			break;
1286 		}
1287 	}
1288 
1289 	closedir(dir);
1290 
1291 	if (g_vfio.fd < 0) {
1292 		DEBUG_PRINT("Failed to discover DPDK VFIO container fd.\n");
1293 		return;
1294 	}
1295 
1296 	g_vfio.enabled = true;
1297 
1298 	return;
1299 }
1300 #endif
1301 
1302 void
1303 vtophys_pci_device_added(struct rte_pci_device *pci_device)
1304 {
1305 	struct spdk_vtophys_pci_device *vtophys_dev;
1306 
1307 	pthread_mutex_lock(&g_vtophys_pci_devices_mutex);
1308 
1309 	vtophys_dev = calloc(1, sizeof(*vtophys_dev));
1310 	if (vtophys_dev) {
1311 		vtophys_dev->pci_device = pci_device;
1312 		TAILQ_INSERT_TAIL(&g_vtophys_pci_devices, vtophys_dev, tailq);
1313 	} else {
1314 		DEBUG_PRINT("Memory allocation error\n");
1315 	}
1316 	pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
1317 
1318 #if VFIO_ENABLED
1319 	struct spdk_vfio_dma_map *dma_map;
1320 	int ret;
1321 
1322 	if (!g_vfio.enabled) {
1323 		return;
1324 	}
1325 
1326 	pthread_mutex_lock(&g_vfio.mutex);
1327 	g_vfio.device_ref++;
1328 	if (g_vfio.device_ref > 1) {
1329 		pthread_mutex_unlock(&g_vfio.mutex);
1330 		return;
1331 	}
1332 
1333 	/* This is the first SPDK device using DPDK vfio. This means that the first
1334 	 * IOMMU group might have been just been added to the DPDK vfio container.
1335 	 * From this point it is certain that the memory can be mapped now.
1336 	 */
1337 	TAILQ_FOREACH(dma_map, &g_vfio.maps, tailq) {
1338 		ret = ioctl(g_vfio.fd, VFIO_IOMMU_MAP_DMA, &dma_map->map);
1339 		if (ret) {
1340 			DEBUG_PRINT("Cannot update DMA mapping, error %d\n", errno);
1341 			break;
1342 		}
1343 	}
1344 	pthread_mutex_unlock(&g_vfio.mutex);
1345 #endif
1346 }
1347 
1348 void
1349 vtophys_pci_device_removed(struct rte_pci_device *pci_device)
1350 {
1351 	struct spdk_vtophys_pci_device *vtophys_dev;
1352 
1353 	pthread_mutex_lock(&g_vtophys_pci_devices_mutex);
1354 	TAILQ_FOREACH(vtophys_dev, &g_vtophys_pci_devices, tailq) {
1355 		if (vtophys_dev->pci_device == pci_device) {
1356 			TAILQ_REMOVE(&g_vtophys_pci_devices, vtophys_dev, tailq);
1357 			free(vtophys_dev);
1358 			break;
1359 		}
1360 	}
1361 	pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
1362 
1363 #if VFIO_ENABLED
1364 	struct spdk_vfio_dma_map *dma_map;
1365 	int ret;
1366 
1367 	if (!g_vfio.enabled) {
1368 		return;
1369 	}
1370 
1371 	pthread_mutex_lock(&g_vfio.mutex);
1372 	assert(g_vfio.device_ref > 0);
1373 	g_vfio.device_ref--;
1374 	if (g_vfio.device_ref > 0) {
1375 		pthread_mutex_unlock(&g_vfio.mutex);
1376 		return;
1377 	}
1378 
1379 	/* This is the last SPDK device using DPDK vfio. If DPDK doesn't have
1380 	 * any additional devices using it's vfio container, all the mappings
1381 	 * will be automatically removed by the Linux vfio driver. We unmap
1382 	 * the memory manually to be able to easily re-map it later regardless
1383 	 * of other, external factors.
1384 	 */
1385 	TAILQ_FOREACH(dma_map, &g_vfio.maps, tailq) {
1386 		ret = ioctl(g_vfio.fd, VFIO_IOMMU_UNMAP_DMA, &dma_map->unmap);
1387 		if (ret) {
1388 			DEBUG_PRINT("Cannot unmap DMA memory, error %d\n", errno);
1389 			break;
1390 		}
1391 	}
1392 	pthread_mutex_unlock(&g_vfio.mutex);
1393 #endif
1394 }
1395 
1396 int
1397 vtophys_init(void)
1398 {
1399 	const struct spdk_mem_map_ops vtophys_map_ops = {
1400 		.notify_cb = vtophys_notify,
1401 		.are_contiguous = vtophys_check_contiguous_entries,
1402 	};
1403 
1404 	const struct spdk_mem_map_ops phys_ref_map_ops = {
1405 		.notify_cb = NULL,
1406 		.are_contiguous = NULL,
1407 	};
1408 
1409 #if VFIO_ENABLED
1410 	vtophys_iommu_init();
1411 #endif
1412 
1413 	g_phys_ref_map = spdk_mem_map_alloc(0, &phys_ref_map_ops, NULL);
1414 	if (g_phys_ref_map == NULL) {
1415 		DEBUG_PRINT("phys_ref map allocation failed.\n");
1416 		return -ENOMEM;
1417 	}
1418 
1419 	g_vtophys_map = spdk_mem_map_alloc(SPDK_VTOPHYS_ERROR, &vtophys_map_ops, NULL);
1420 	if (g_vtophys_map == NULL) {
1421 		DEBUG_PRINT("vtophys map allocation failed\n");
1422 		return -ENOMEM;
1423 	}
1424 	return 0;
1425 }
1426 
1427 uint64_t
1428 spdk_vtophys(const void *buf, uint64_t *size)
1429 {
1430 	uint64_t vaddr, paddr_2mb;
1431 
1432 	vaddr = (uint64_t)buf;
1433 	paddr_2mb = spdk_mem_map_translate(g_vtophys_map, vaddr, size);
1434 
1435 	/*
1436 	 * SPDK_VTOPHYS_ERROR has all bits set, so if the lookup returned SPDK_VTOPHYS_ERROR,
1437 	 * we will still bitwise-or it with the buf offset below, but the result will still be
1438 	 * SPDK_VTOPHYS_ERROR. However now that we do + rather than | (due to PCI vtophys being
1439 	 * unaligned) we must now check the return value before addition.
1440 	 */
1441 	SPDK_STATIC_ASSERT(SPDK_VTOPHYS_ERROR == UINT64_C(-1), "SPDK_VTOPHYS_ERROR should be all 1s");
1442 	if (paddr_2mb == SPDK_VTOPHYS_ERROR) {
1443 		return SPDK_VTOPHYS_ERROR;
1444 	} else {
1445 		return paddr_2mb + (vaddr & MASK_2MB);
1446 	}
1447 }
1448