xref: /spdk/lib/env_dpdk/memory.c (revision 6a9e923da298dda69cbdaf73eed6fb0e85ec2ad2)
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 
51 #ifdef __FreeBSD__
52 #define VFIO_ENABLED 0
53 #else
54 #include <linux/version.h>
55 #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 6, 0)
56 #define VFIO_ENABLED 1
57 #include <linux/vfio.h>
58 #include <rte_vfio.h>
59 
60 struct spdk_vfio_dma_map {
61 	struct vfio_iommu_type1_dma_map map;
62 	struct vfio_iommu_type1_dma_unmap unmap;
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(...) fprintf(stderr, __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 %lu\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=%lu len=%ju\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 RTE_VERSION >= RTE_VERSION_NUM(19, 02, 0, 0)
714 		if (!spdk_env_dpdk_external_init()) {
715 			return;
716 		}
717 #endif
718 
719 		/* Prior to DPDK 19.02, we have to worry about DPDK
720 		 * freeing memory in different units than it was allocated.
721 		 * That doesn't work with things like RDMA MRs.  So for
722 		 * those versions of DPDK, mark each segment so that DPDK
723 		 * won't later free it.  That ensures we don't have to deal
724 		 * with that scenario.
725 		 *
726 		 * DPDK 19.02 added the --match-allocations RTE flag to
727 		 * avoid this condition.
728 		 *
729 		 * Note: if the user initialized DPDK separately, we can't
730 		 * be sure that --match-allocations was specified, so need
731 		 * to still mark the segments so they aren't freed.
732 		 */
733 		while (len > 0) {
734 			struct rte_memseg *seg;
735 
736 			seg = rte_mem_virt2memseg(addr, NULL);
737 			assert(seg != NULL);
738 			seg->flags |= RTE_MEMSEG_FLAG_DO_NOT_FREE;
739 			addr = (void *)((uintptr_t)addr + seg->hugepage_sz);
740 			len -= seg->hugepage_sz;
741 		}
742 	} else if (event_type == RTE_MEM_EVENT_FREE) {
743 		spdk_mem_unregister((void *)addr, len);
744 	}
745 }
746 
747 static int
748 memory_iter_cb(const struct rte_memseg_list *msl,
749 	       const struct rte_memseg *ms, size_t len, void *arg)
750 {
751 	return spdk_mem_register(ms->addr, len);
752 }
753 
754 int
755 mem_map_init(bool legacy_mem)
756 {
757 	g_legacy_mem = legacy_mem;
758 
759 	g_mem_reg_map = spdk_mem_map_alloc(0, NULL, NULL);
760 	if (g_mem_reg_map == NULL) {
761 		DEBUG_PRINT("memory registration map allocation failed\n");
762 		return -ENOMEM;
763 	}
764 
765 	/*
766 	 * Walk all DPDK memory segments and register them
767 	 * with the master memory map
768 	 */
769 	rte_mem_event_callback_register("spdk", memory_hotplug_cb, NULL);
770 	rte_memseg_contig_walk(memory_iter_cb, NULL);
771 	return 0;
772 }
773 
774 bool
775 spdk_iommu_is_enabled(void)
776 {
777 #if VFIO_ENABLED
778 	return g_vfio.enabled && !g_vfio.noiommu_enabled;
779 #else
780 	return false;
781 #endif
782 }
783 
784 struct spdk_vtophys_pci_device {
785 	struct rte_pci_device *pci_device;
786 	TAILQ_ENTRY(spdk_vtophys_pci_device) tailq;
787 };
788 
789 static pthread_mutex_t g_vtophys_pci_devices_mutex = PTHREAD_MUTEX_INITIALIZER;
790 static TAILQ_HEAD(, spdk_vtophys_pci_device) g_vtophys_pci_devices =
791 	TAILQ_HEAD_INITIALIZER(g_vtophys_pci_devices);
792 
793 static struct spdk_mem_map *g_vtophys_map;
794 static struct spdk_mem_map *g_phys_ref_map;
795 
796 #if VFIO_ENABLED
797 static int
798 vtophys_iommu_map_dma(uint64_t vaddr, uint64_t iova, uint64_t size)
799 {
800 	struct spdk_vfio_dma_map *dma_map;
801 	uint64_t refcount;
802 	int ret;
803 
804 	refcount = spdk_mem_map_translate(g_phys_ref_map, iova, NULL);
805 	assert(refcount < UINT64_MAX);
806 	if (refcount > 0) {
807 		spdk_mem_map_set_translation(g_phys_ref_map, iova, size, refcount + 1);
808 		return 0;
809 	}
810 
811 	dma_map = calloc(1, sizeof(*dma_map));
812 	if (dma_map == NULL) {
813 		return -ENOMEM;
814 	}
815 
816 	dma_map->map.argsz = sizeof(dma_map->map);
817 	dma_map->map.flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE;
818 	dma_map->map.vaddr = vaddr;
819 	dma_map->map.iova = iova;
820 	dma_map->map.size = size;
821 
822 	dma_map->unmap.argsz = sizeof(dma_map->unmap);
823 	dma_map->unmap.flags = 0;
824 	dma_map->unmap.iova = iova;
825 	dma_map->unmap.size = size;
826 
827 	pthread_mutex_lock(&g_vfio.mutex);
828 	if (g_vfio.device_ref == 0) {
829 		/* VFIO requires at least one device (IOMMU group) to be added to
830 		 * a VFIO container before it is possible to perform any IOMMU
831 		 * operations on that container. This memory will be mapped once
832 		 * the first device (IOMMU group) is hotplugged.
833 		 *
834 		 * Since the vfio container is managed internally by DPDK, it is
835 		 * also possible that some device is already in that container, but
836 		 * it's not managed by SPDK -  e.g. an NIC attached internally
837 		 * inside DPDK. We could map the memory straight away in such
838 		 * scenario, but there's no need to do it. DPDK devices clearly
839 		 * don't need our mappings and hence we defer the mapping
840 		 * unconditionally until the first SPDK-managed device is
841 		 * hotplugged.
842 		 */
843 		goto out_insert;
844 	}
845 
846 	ret = ioctl(g_vfio.fd, VFIO_IOMMU_MAP_DMA, &dma_map->map);
847 	if (ret) {
848 		DEBUG_PRINT("Cannot set up DMA mapping, error %d\n", errno);
849 		pthread_mutex_unlock(&g_vfio.mutex);
850 		free(dma_map);
851 		return ret;
852 	}
853 
854 out_insert:
855 	TAILQ_INSERT_TAIL(&g_vfio.maps, dma_map, tailq);
856 	pthread_mutex_unlock(&g_vfio.mutex);
857 	spdk_mem_map_set_translation(g_phys_ref_map, iova, size, refcount + 1);
858 	return 0;
859 }
860 
861 static int
862 vtophys_iommu_unmap_dma(uint64_t iova, uint64_t size)
863 {
864 	struct spdk_vfio_dma_map *dma_map;
865 	uint64_t refcount;
866 	int ret;
867 
868 	pthread_mutex_lock(&g_vfio.mutex);
869 	TAILQ_FOREACH(dma_map, &g_vfio.maps, tailq) {
870 		if (dma_map->map.iova == iova) {
871 			break;
872 		}
873 	}
874 
875 	if (dma_map == NULL) {
876 		DEBUG_PRINT("Cannot clear DMA mapping for IOVA %"PRIx64" - it's not mapped\n", iova);
877 		pthread_mutex_unlock(&g_vfio.mutex);
878 		return -ENXIO;
879 	}
880 
881 	refcount = spdk_mem_map_translate(g_phys_ref_map, iova, NULL);
882 	assert(refcount < UINT64_MAX);
883 	if (refcount > 0) {
884 		spdk_mem_map_set_translation(g_phys_ref_map, iova, size, refcount - 1);
885 	}
886 
887 	/* We still have outstanding references, don't clear it. */
888 	if (refcount > 1) {
889 		pthread_mutex_unlock(&g_vfio.mutex);
890 		return 0;
891 	}
892 
893 	/** don't support partial or multiple-page unmap for now */
894 	assert(dma_map->map.size == size);
895 
896 	if (g_vfio.device_ref == 0) {
897 		/* Memory is not mapped anymore, just remove it's references */
898 		goto out_remove;
899 	}
900 
901 
902 	ret = ioctl(g_vfio.fd, VFIO_IOMMU_UNMAP_DMA, &dma_map->unmap);
903 	if (ret) {
904 		DEBUG_PRINT("Cannot clear DMA mapping, error %d\n", errno);
905 		pthread_mutex_unlock(&g_vfio.mutex);
906 		return ret;
907 	}
908 
909 out_remove:
910 	TAILQ_REMOVE(&g_vfio.maps, dma_map, tailq);
911 	pthread_mutex_unlock(&g_vfio.mutex);
912 	free(dma_map);
913 	return 0;
914 }
915 #endif
916 
917 static uint64_t
918 vtophys_get_paddr_memseg(uint64_t vaddr)
919 {
920 	uintptr_t paddr;
921 	struct rte_memseg *seg;
922 
923 	seg = rte_mem_virt2memseg((void *)(uintptr_t)vaddr, NULL);
924 	if (seg != NULL) {
925 		paddr = seg->phys_addr;
926 		if (paddr == RTE_BAD_IOVA) {
927 			return SPDK_VTOPHYS_ERROR;
928 		}
929 		paddr += (vaddr - (uintptr_t)seg->addr);
930 		return paddr;
931 	}
932 
933 	return SPDK_VTOPHYS_ERROR;
934 }
935 
936 /* Try to get the paddr from /proc/self/pagemap */
937 static uint64_t
938 vtophys_get_paddr_pagemap(uint64_t vaddr)
939 {
940 	uintptr_t paddr;
941 
942 	/* Silence static analyzers */
943 	assert(vaddr != 0);
944 	paddr = rte_mem_virt2iova((void *)vaddr);
945 	if (paddr == RTE_BAD_IOVA) {
946 		/*
947 		 * The vaddr may be valid but doesn't have a backing page
948 		 * assigned yet.  Touch the page to ensure a backing page
949 		 * gets assigned, then try to translate again.
950 		 */
951 		rte_atomic64_read((rte_atomic64_t *)vaddr);
952 		paddr = rte_mem_virt2iova((void *)vaddr);
953 	}
954 	if (paddr == RTE_BAD_IOVA) {
955 		/* Unable to get to the physical address. */
956 		return SPDK_VTOPHYS_ERROR;
957 	}
958 
959 	return paddr;
960 }
961 
962 /* Try to get the paddr from pci devices */
963 static uint64_t
964 vtophys_get_paddr_pci(uint64_t vaddr)
965 {
966 	struct spdk_vtophys_pci_device *vtophys_dev;
967 	uintptr_t paddr;
968 	struct rte_pci_device	*dev;
969 	struct rte_mem_resource *res;
970 	unsigned r;
971 
972 	pthread_mutex_lock(&g_vtophys_pci_devices_mutex);
973 	TAILQ_FOREACH(vtophys_dev, &g_vtophys_pci_devices, tailq) {
974 		dev = vtophys_dev->pci_device;
975 
976 		for (r = 0; r < PCI_MAX_RESOURCE; r++) {
977 			res = &dev->mem_resource[r];
978 			if (res->phys_addr && vaddr >= (uint64_t)res->addr &&
979 			    vaddr < (uint64_t)res->addr + res->len) {
980 				paddr = res->phys_addr + (vaddr - (uint64_t)res->addr);
981 				DEBUG_PRINT("%s: %p -> %p\n", __func__, (void *)vaddr,
982 					    (void *)paddr);
983 				pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
984 				return paddr;
985 			}
986 		}
987 	}
988 	pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
989 
990 	return  SPDK_VTOPHYS_ERROR;
991 }
992 
993 static int
994 vtophys_notify(void *cb_ctx, struct spdk_mem_map *map,
995 	       enum spdk_mem_map_notify_action action,
996 	       void *vaddr, size_t len)
997 {
998 	int rc = 0, pci_phys = 0;
999 	uint64_t paddr;
1000 
1001 	if ((uintptr_t)vaddr & ~MASK_256TB) {
1002 		DEBUG_PRINT("invalid usermode virtual address %p\n", vaddr);
1003 		return -EINVAL;
1004 	}
1005 
1006 	if (((uintptr_t)vaddr & MASK_2MB) || (len & MASK_2MB)) {
1007 		DEBUG_PRINT("invalid parameters, vaddr=%p len=%ju\n",
1008 			    vaddr, len);
1009 		return -EINVAL;
1010 	}
1011 
1012 	/* Get the physical address from the DPDK memsegs */
1013 	paddr = vtophys_get_paddr_memseg((uint64_t)vaddr);
1014 
1015 	switch (action) {
1016 	case SPDK_MEM_MAP_NOTIFY_REGISTER:
1017 		if (paddr == SPDK_VTOPHYS_ERROR) {
1018 			/* This is not an address that DPDK is managing. */
1019 #if VFIO_ENABLED
1020 			enum rte_iova_mode iova_mode;
1021 
1022 #if RTE_VERSION >= RTE_VERSION_NUM(19, 11, 0, 0)
1023 			iova_mode = rte_eal_iova_mode();
1024 #else
1025 			iova_mode = rte_eal_get_configuration()->iova_mode;
1026 #endif
1027 
1028 			if (spdk_iommu_is_enabled() && iova_mode == RTE_IOVA_VA) {
1029 				/* We'll use the virtual address as the iova to match DPDK. */
1030 				paddr = (uint64_t)vaddr;
1031 				rc = vtophys_iommu_map_dma((uint64_t)vaddr, paddr, len);
1032 				if (rc) {
1033 					return -EFAULT;
1034 				}
1035 				while (len > 0) {
1036 					rc = spdk_mem_map_set_translation(map, (uint64_t)vaddr, VALUE_2MB, paddr);
1037 					if (rc != 0) {
1038 						return rc;
1039 					}
1040 					vaddr += VALUE_2MB;
1041 					paddr += VALUE_2MB;
1042 					len -= VALUE_2MB;
1043 				}
1044 			} else
1045 #endif
1046 			{
1047 				/* Get the physical address from /proc/self/pagemap. */
1048 				paddr = vtophys_get_paddr_pagemap((uint64_t)vaddr);
1049 				if (paddr == SPDK_VTOPHYS_ERROR) {
1050 					/* Get the physical address from PCI devices */
1051 					paddr = vtophys_get_paddr_pci((uint64_t)vaddr);
1052 					if (paddr == SPDK_VTOPHYS_ERROR) {
1053 						DEBUG_PRINT("could not get phys addr for %p\n", vaddr);
1054 						return -EFAULT;
1055 					}
1056 					/* The beginning of this address range points to a PCI resource,
1057 					 * so the rest must point to a PCI resource as well.
1058 					 */
1059 					pci_phys = 1;
1060 				}
1061 
1062 				/* Get paddr for each 2MB chunk in this address range */
1063 				while (len > 0) {
1064 					/* Get the physical address from /proc/self/pagemap. */
1065 					if (pci_phys) {
1066 						paddr = vtophys_get_paddr_pci((uint64_t)vaddr);
1067 					} else {
1068 						paddr = vtophys_get_paddr_pagemap((uint64_t)vaddr);
1069 					}
1070 
1071 					if (paddr == SPDK_VTOPHYS_ERROR) {
1072 						DEBUG_PRINT("could not get phys addr for %p\n", vaddr);
1073 						return -EFAULT;
1074 					}
1075 
1076 					/* Since PCI paddr can break the 2MiB physical alignment skip this check for that. */
1077 					if (!pci_phys && (paddr & MASK_2MB)) {
1078 						DEBUG_PRINT("invalid paddr 0x%" PRIx64 " - must be 2MB aligned\n", paddr);
1079 						return -EINVAL;
1080 					}
1081 #if VFIO_ENABLED
1082 					/* If the IOMMU is on, but DPDK is using iova-mode=pa, we want to register this memory
1083 					 * with the IOMMU using the physical address to match. */
1084 					if (spdk_iommu_is_enabled()) {
1085 						rc = vtophys_iommu_map_dma((uint64_t)vaddr, paddr, VALUE_2MB);
1086 						if (rc) {
1087 							DEBUG_PRINT("Unable to assign vaddr %p to paddr 0x%" PRIx64 "\n", vaddr, paddr);
1088 							return -EFAULT;
1089 						}
1090 					}
1091 #endif
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 		} else {
1103 			/* This is an address managed by DPDK. Just setup the translations. */
1104 			while (len > 0) {
1105 				paddr = vtophys_get_paddr_memseg((uint64_t)vaddr);
1106 				if (paddr == SPDK_VTOPHYS_ERROR) {
1107 					DEBUG_PRINT("could not get phys addr for %p\n", vaddr);
1108 					return -EFAULT;
1109 				}
1110 
1111 				rc = spdk_mem_map_set_translation(map, (uint64_t)vaddr, VALUE_2MB, paddr);
1112 				if (rc != 0) {
1113 					return rc;
1114 				}
1115 
1116 				vaddr += VALUE_2MB;
1117 				len -= VALUE_2MB;
1118 			}
1119 		}
1120 
1121 		break;
1122 	case SPDK_MEM_MAP_NOTIFY_UNREGISTER:
1123 #if VFIO_ENABLED
1124 		if (paddr == SPDK_VTOPHYS_ERROR) {
1125 			/*
1126 			 * This is not an address that DPDK is managing. If vfio is enabled,
1127 			 * we need to unmap the range from the IOMMU
1128 			 */
1129 			if (spdk_iommu_is_enabled()) {
1130 				uint64_t buffer_len = len;
1131 				uint8_t *va = vaddr;
1132 				enum rte_iova_mode iova_mode;
1133 
1134 #if RTE_VERSION >= RTE_VERSION_NUM(19, 11, 0, 0)
1135 				iova_mode = rte_eal_iova_mode();
1136 #else
1137 				iova_mode = rte_eal_get_configuration()->iova_mode;
1138 #endif
1139 				/*
1140 				 * In virtual address mode, the region is contiguous and can be done in
1141 				 * one unmap.
1142 				 */
1143 				if (iova_mode == RTE_IOVA_VA) {
1144 					paddr = spdk_mem_map_translate(map, (uint64_t)va, &buffer_len);
1145 					if (buffer_len != len || paddr != (uintptr_t)va) {
1146 						DEBUG_PRINT("Unmapping %p with length %lu failed because "
1147 							    "translation had address 0x%" PRIx64 " and length %lu\n",
1148 							    va, len, paddr, buffer_len);
1149 						return -EINVAL;
1150 					}
1151 					rc = vtophys_iommu_unmap_dma(paddr, len);
1152 					if (rc) {
1153 						DEBUG_PRINT("Failed to iommu unmap paddr 0x%" PRIx64 "\n", paddr);
1154 						return -EFAULT;
1155 					}
1156 				} else if (iova_mode == RTE_IOVA_PA) {
1157 					/* Get paddr for each 2MB chunk in this address range */
1158 					while (buffer_len > 0) {
1159 						paddr = spdk_mem_map_translate(map, (uint64_t)va, NULL);
1160 
1161 						if (paddr == SPDK_VTOPHYS_ERROR || buffer_len < VALUE_2MB) {
1162 							DEBUG_PRINT("could not get phys addr for %p\n", va);
1163 							return -EFAULT;
1164 						}
1165 
1166 						rc = vtophys_iommu_unmap_dma(paddr, VALUE_2MB);
1167 						if (rc) {
1168 							DEBUG_PRINT("Failed to iommu unmap paddr 0x%" PRIx64 "\n", paddr);
1169 							return -EFAULT;
1170 						}
1171 
1172 						va += VALUE_2MB;
1173 						buffer_len -= VALUE_2MB;
1174 					}
1175 				}
1176 			}
1177 		}
1178 #endif
1179 		while (len > 0) {
1180 			rc = spdk_mem_map_clear_translation(map, (uint64_t)vaddr, VALUE_2MB);
1181 			if (rc != 0) {
1182 				return rc;
1183 			}
1184 
1185 			vaddr += VALUE_2MB;
1186 			len -= VALUE_2MB;
1187 		}
1188 
1189 		break;
1190 	default:
1191 		SPDK_UNREACHABLE();
1192 	}
1193 
1194 	return rc;
1195 }
1196 
1197 static int
1198 vtophys_check_contiguous_entries(uint64_t paddr1, uint64_t paddr2)
1199 {
1200 	/* This function is always called with paddrs for two subsequent
1201 	 * 2MB chunks in virtual address space, so those chunks will be only
1202 	 * physically contiguous if the physical addresses are 2MB apart
1203 	 * from each other as well.
1204 	 */
1205 	return (paddr2 - paddr1 == VALUE_2MB);
1206 }
1207 
1208 #if VFIO_ENABLED
1209 
1210 static bool
1211 vfio_enabled(void)
1212 {
1213 	return rte_vfio_is_enabled("vfio_pci");
1214 }
1215 
1216 /* Check if IOMMU is enabled on the system */
1217 static bool
1218 has_iommu_groups(void)
1219 {
1220 	struct dirent *d;
1221 	int count = 0;
1222 	DIR *dir = opendir("/sys/kernel/iommu_groups");
1223 
1224 	if (dir == NULL) {
1225 		return false;
1226 	}
1227 
1228 	while (count < 3 && (d = readdir(dir)) != NULL) {
1229 		count++;
1230 	}
1231 
1232 	closedir(dir);
1233 	/* there will always be ./ and ../ entries */
1234 	return count > 2;
1235 }
1236 
1237 static bool
1238 vfio_noiommu_enabled(void)
1239 {
1240 	return rte_vfio_noiommu_is_enabled();
1241 }
1242 
1243 static void
1244 vtophys_iommu_init(void)
1245 {
1246 	char proc_fd_path[PATH_MAX + 1];
1247 	char link_path[PATH_MAX + 1];
1248 	const char vfio_path[] = "/dev/vfio/vfio";
1249 	DIR *dir;
1250 	struct dirent *d;
1251 
1252 	if (!vfio_enabled()) {
1253 		return;
1254 	}
1255 
1256 	if (vfio_noiommu_enabled()) {
1257 		g_vfio.noiommu_enabled = true;
1258 	} else if (!has_iommu_groups()) {
1259 		return;
1260 	}
1261 
1262 	dir = opendir("/proc/self/fd");
1263 	if (!dir) {
1264 		DEBUG_PRINT("Failed to open /proc/self/fd (%d)\n", errno);
1265 		return;
1266 	}
1267 
1268 	while ((d = readdir(dir)) != NULL) {
1269 		if (d->d_type != DT_LNK) {
1270 			continue;
1271 		}
1272 
1273 		snprintf(proc_fd_path, sizeof(proc_fd_path), "/proc/self/fd/%s", d->d_name);
1274 		if (readlink(proc_fd_path, link_path, sizeof(link_path)) != (sizeof(vfio_path) - 1)) {
1275 			continue;
1276 		}
1277 
1278 		if (memcmp(link_path, vfio_path, sizeof(vfio_path) - 1) == 0) {
1279 			sscanf(d->d_name, "%d", &g_vfio.fd);
1280 			break;
1281 		}
1282 	}
1283 
1284 	closedir(dir);
1285 
1286 	if (g_vfio.fd < 0) {
1287 		DEBUG_PRINT("Failed to discover DPDK VFIO container fd.\n");
1288 		return;
1289 	}
1290 
1291 	g_vfio.enabled = true;
1292 
1293 	return;
1294 }
1295 #endif
1296 
1297 void
1298 vtophys_pci_device_added(struct rte_pci_device *pci_device)
1299 {
1300 	struct spdk_vtophys_pci_device *vtophys_dev;
1301 
1302 	pthread_mutex_lock(&g_vtophys_pci_devices_mutex);
1303 
1304 	vtophys_dev = calloc(1, sizeof(*vtophys_dev));
1305 	if (vtophys_dev) {
1306 		vtophys_dev->pci_device = pci_device;
1307 		TAILQ_INSERT_TAIL(&g_vtophys_pci_devices, vtophys_dev, tailq);
1308 	} else {
1309 		DEBUG_PRINT("Memory allocation error\n");
1310 	}
1311 	pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
1312 
1313 #if VFIO_ENABLED
1314 	struct spdk_vfio_dma_map *dma_map;
1315 	int ret;
1316 
1317 	if (!g_vfio.enabled) {
1318 		return;
1319 	}
1320 
1321 	pthread_mutex_lock(&g_vfio.mutex);
1322 	g_vfio.device_ref++;
1323 	if (g_vfio.device_ref > 1) {
1324 		pthread_mutex_unlock(&g_vfio.mutex);
1325 		return;
1326 	}
1327 
1328 	/* This is the first SPDK device using DPDK vfio. This means that the first
1329 	 * IOMMU group might have been just been added to the DPDK vfio container.
1330 	 * From this point it is certain that the memory can be mapped now.
1331 	 */
1332 	TAILQ_FOREACH(dma_map, &g_vfio.maps, tailq) {
1333 		ret = ioctl(g_vfio.fd, VFIO_IOMMU_MAP_DMA, &dma_map->map);
1334 		if (ret) {
1335 			DEBUG_PRINT("Cannot update DMA mapping, error %d\n", errno);
1336 			break;
1337 		}
1338 	}
1339 	pthread_mutex_unlock(&g_vfio.mutex);
1340 #endif
1341 }
1342 
1343 void
1344 vtophys_pci_device_removed(struct rte_pci_device *pci_device)
1345 {
1346 	struct spdk_vtophys_pci_device *vtophys_dev;
1347 
1348 	pthread_mutex_lock(&g_vtophys_pci_devices_mutex);
1349 	TAILQ_FOREACH(vtophys_dev, &g_vtophys_pci_devices, tailq) {
1350 		if (vtophys_dev->pci_device == pci_device) {
1351 			TAILQ_REMOVE(&g_vtophys_pci_devices, vtophys_dev, tailq);
1352 			free(vtophys_dev);
1353 			break;
1354 		}
1355 	}
1356 	pthread_mutex_unlock(&g_vtophys_pci_devices_mutex);
1357 
1358 #if VFIO_ENABLED
1359 	struct spdk_vfio_dma_map *dma_map;
1360 	int ret;
1361 
1362 	if (!g_vfio.enabled) {
1363 		return;
1364 	}
1365 
1366 	pthread_mutex_lock(&g_vfio.mutex);
1367 	assert(g_vfio.device_ref > 0);
1368 	g_vfio.device_ref--;
1369 	if (g_vfio.device_ref > 0) {
1370 		pthread_mutex_unlock(&g_vfio.mutex);
1371 		return;
1372 	}
1373 
1374 	/* This is the last SPDK device using DPDK vfio. If DPDK doesn't have
1375 	 * any additional devices using it's vfio container, all the mappings
1376 	 * will be automatically removed by the Linux vfio driver. We unmap
1377 	 * the memory manually to be able to easily re-map it later regardless
1378 	 * of other, external factors.
1379 	 */
1380 	TAILQ_FOREACH(dma_map, &g_vfio.maps, tailq) {
1381 		ret = ioctl(g_vfio.fd, VFIO_IOMMU_UNMAP_DMA, &dma_map->unmap);
1382 		if (ret) {
1383 			DEBUG_PRINT("Cannot unmap DMA memory, error %d\n", errno);
1384 			break;
1385 		}
1386 	}
1387 	pthread_mutex_unlock(&g_vfio.mutex);
1388 #endif
1389 }
1390 
1391 int
1392 vtophys_init(void)
1393 {
1394 	const struct spdk_mem_map_ops vtophys_map_ops = {
1395 		.notify_cb = vtophys_notify,
1396 		.are_contiguous = vtophys_check_contiguous_entries,
1397 	};
1398 
1399 	const struct spdk_mem_map_ops phys_ref_map_ops = {
1400 		.notify_cb = NULL,
1401 		.are_contiguous = NULL,
1402 	};
1403 
1404 #if VFIO_ENABLED
1405 	vtophys_iommu_init();
1406 #endif
1407 
1408 	g_phys_ref_map = spdk_mem_map_alloc(0, &phys_ref_map_ops, NULL);
1409 	if (g_phys_ref_map == NULL) {
1410 		DEBUG_PRINT("phys_ref map allocation failed.\n");
1411 		return -ENOMEM;
1412 	}
1413 
1414 	g_vtophys_map = spdk_mem_map_alloc(SPDK_VTOPHYS_ERROR, &vtophys_map_ops, NULL);
1415 	if (g_vtophys_map == NULL) {
1416 		DEBUG_PRINT("vtophys map allocation failed\n");
1417 		return -ENOMEM;
1418 	}
1419 	return 0;
1420 }
1421 
1422 uint64_t
1423 spdk_vtophys(void *buf, uint64_t *size)
1424 {
1425 	uint64_t vaddr, paddr_2mb;
1426 
1427 	vaddr = (uint64_t)buf;
1428 	paddr_2mb = spdk_mem_map_translate(g_vtophys_map, vaddr, size);
1429 
1430 	/*
1431 	 * SPDK_VTOPHYS_ERROR has all bits set, so if the lookup returned SPDK_VTOPHYS_ERROR,
1432 	 * we will still bitwise-or it with the buf offset below, but the result will still be
1433 	 * SPDK_VTOPHYS_ERROR. However now that we do + rather than | (due to PCI vtophys being
1434 	 * unaligned) we must now check the return value before addition.
1435 	 */
1436 	SPDK_STATIC_ASSERT(SPDK_VTOPHYS_ERROR == UINT64_C(-1), "SPDK_VTOPHYS_ERROR should be all 1s");
1437 	if (paddr_2mb == SPDK_VTOPHYS_ERROR) {
1438 		return SPDK_VTOPHYS_ERROR;
1439 	} else {
1440 		return paddr_2mb + (vaddr & MASK_2MB);
1441 	}
1442 }
1443