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