xref: /dpdk/drivers/common/mlx5/mlx5_common_mr.c (revision c81e3f21d1ea05e5123278b15d9d5e1257b6ba99)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2016 6WIND S.A.
3  * Copyright 2020 Mellanox Technologies, Ltd
4  */
5 #include <rte_eal_memconfig.h>
6 #include <rte_errno.h>
7 #include <rte_mempool.h>
8 #include <rte_malloc.h>
9 #include <rte_rwlock.h>
10 
11 #include "mlx5_glue.h"
12 #include "mlx5_common_mp.h"
13 #include "mlx5_common_mr.h"
14 #include "mlx5_common_utils.h"
15 
16 struct mr_find_contig_memsegs_data {
17 	uintptr_t addr;
18 	uintptr_t start;
19 	uintptr_t end;
20 	const struct rte_memseg_list *msl;
21 };
22 
23 /**
24  * Expand B-tree table to a given size. Can't be called with holding
25  * memory_hotplug_lock or share_cache.rwlock due to rte_realloc().
26  *
27  * @param bt
28  *   Pointer to B-tree structure.
29  * @param n
30  *   Number of entries for expansion.
31  *
32  * @return
33  *   0 on success, -1 on failure.
34  */
35 static int
36 mr_btree_expand(struct mlx5_mr_btree *bt, int n)
37 {
38 	void *mem;
39 	int ret = 0;
40 
41 	if (n <= bt->size)
42 		return ret;
43 	/*
44 	 * Downside of directly using rte_realloc() is that SOCKET_ID_ANY is
45 	 * used inside if there's no room to expand. Because this is a quite
46 	 * rare case and a part of very slow path, it is very acceptable.
47 	 * Initially cache_bh[] will be given practically enough space and once
48 	 * it is expanded, expansion wouldn't be needed again ever.
49 	 */
50 	mem = rte_realloc(bt->table, n * sizeof(struct mr_cache_entry), 0);
51 	if (mem == NULL) {
52 		/* Not an error, B-tree search will be skipped. */
53 		DRV_LOG(WARNING, "failed to expand MR B-tree (%p) table",
54 			(void *)bt);
55 		ret = -1;
56 	} else {
57 		DRV_LOG(DEBUG, "expanded MR B-tree table (size=%u)", n);
58 		bt->table = mem;
59 		bt->size = n;
60 	}
61 	return ret;
62 }
63 
64 /**
65  * Look up LKey from given B-tree lookup table, store the last index and return
66  * searched LKey.
67  *
68  * @param bt
69  *   Pointer to B-tree structure.
70  * @param[out] idx
71  *   Pointer to index. Even on search failure, returns index where it stops
72  *   searching so that index can be used when inserting a new entry.
73  * @param addr
74  *   Search key.
75  *
76  * @return
77  *   Searched LKey on success, UINT32_MAX on no match.
78  */
79 static uint32_t
80 mr_btree_lookup(struct mlx5_mr_btree *bt, uint16_t *idx, uintptr_t addr)
81 {
82 	struct mr_cache_entry *lkp_tbl;
83 	uint16_t n;
84 	uint16_t base = 0;
85 
86 	MLX5_ASSERT(bt != NULL);
87 	lkp_tbl = *bt->table;
88 	n = bt->len;
89 	/* First entry must be NULL for comparison. */
90 	MLX5_ASSERT(bt->len > 0 || (lkp_tbl[0].start == 0 &&
91 				    lkp_tbl[0].lkey == UINT32_MAX));
92 	/* Binary search. */
93 	do {
94 		register uint16_t delta = n >> 1;
95 
96 		if (addr < lkp_tbl[base + delta].start) {
97 			n = delta;
98 		} else {
99 			base += delta;
100 			n -= delta;
101 		}
102 	} while (n > 1);
103 	MLX5_ASSERT(addr >= lkp_tbl[base].start);
104 	*idx = base;
105 	if (addr < lkp_tbl[base].end)
106 		return lkp_tbl[base].lkey;
107 	/* Not found. */
108 	return UINT32_MAX;
109 }
110 
111 /**
112  * Insert an entry to B-tree lookup table.
113  *
114  * @param bt
115  *   Pointer to B-tree structure.
116  * @param entry
117  *   Pointer to new entry to insert.
118  *
119  * @return
120  *   0 on success, -1 on failure.
121  */
122 static int
123 mr_btree_insert(struct mlx5_mr_btree *bt, struct mr_cache_entry *entry)
124 {
125 	struct mr_cache_entry *lkp_tbl;
126 	uint16_t idx = 0;
127 	size_t shift;
128 
129 	MLX5_ASSERT(bt != NULL);
130 	MLX5_ASSERT(bt->len <= bt->size);
131 	MLX5_ASSERT(bt->len > 0);
132 	lkp_tbl = *bt->table;
133 	/* Find out the slot for insertion. */
134 	if (mr_btree_lookup(bt, &idx, entry->start) != UINT32_MAX) {
135 		DRV_LOG(DEBUG,
136 			"abort insertion to B-tree(%p): already exist at"
137 			" idx=%u [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
138 			(void *)bt, idx, entry->start, entry->end, entry->lkey);
139 		/* Already exist, return. */
140 		return 0;
141 	}
142 	/* If table is full, return error. */
143 	if (unlikely(bt->len == bt->size)) {
144 		bt->overflow = 1;
145 		return -1;
146 	}
147 	/* Insert entry. */
148 	++idx;
149 	shift = (bt->len - idx) * sizeof(struct mr_cache_entry);
150 	if (shift)
151 		memmove(&lkp_tbl[idx + 1], &lkp_tbl[idx], shift);
152 	lkp_tbl[idx] = *entry;
153 	bt->len++;
154 	DRV_LOG(DEBUG,
155 		"inserted B-tree(%p)[%u],"
156 		" [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
157 		(void *)bt, idx, entry->start, entry->end, entry->lkey);
158 	return 0;
159 }
160 
161 /**
162  * Initialize B-tree and allocate memory for lookup table.
163  *
164  * @param bt
165  *   Pointer to B-tree structure.
166  * @param n
167  *   Number of entries to allocate.
168  * @param socket
169  *   NUMA socket on which memory must be allocated.
170  *
171  * @return
172  *   0 on success, a negative errno value otherwise and rte_errno is set.
173  */
174 int
175 mlx5_mr_btree_init(struct mlx5_mr_btree *bt, int n, int socket)
176 {
177 	if (bt == NULL) {
178 		rte_errno = EINVAL;
179 		return -rte_errno;
180 	}
181 	MLX5_ASSERT(!bt->table && !bt->size);
182 	memset(bt, 0, sizeof(*bt));
183 	bt->table = rte_calloc_socket("B-tree table",
184 				      n, sizeof(struct mr_cache_entry),
185 				      0, socket);
186 	if (bt->table == NULL) {
187 		rte_errno = ENOMEM;
188 		DEBUG("failed to allocate memory for btree cache on socket %d",
189 		      socket);
190 		return -rte_errno;
191 	}
192 	bt->size = n;
193 	/* First entry must be NULL for binary search. */
194 	(*bt->table)[bt->len++] = (struct mr_cache_entry) {
195 		.lkey = UINT32_MAX,
196 	};
197 	DEBUG("initialized B-tree %p with table %p",
198 	      (void *)bt, (void *)bt->table);
199 	return 0;
200 }
201 
202 /**
203  * Free B-tree resources.
204  *
205  * @param bt
206  *   Pointer to B-tree structure.
207  */
208 void
209 mlx5_mr_btree_free(struct mlx5_mr_btree *bt)
210 {
211 	if (bt == NULL)
212 		return;
213 	DEBUG("freeing B-tree %p with table %p",
214 	      (void *)bt, (void *)bt->table);
215 	rte_free(bt->table);
216 	memset(bt, 0, sizeof(*bt));
217 }
218 
219 /**
220  * Dump all the entries in a B-tree
221  *
222  * @param bt
223  *   Pointer to B-tree structure.
224  */
225 void
226 mlx5_mr_btree_dump(struct mlx5_mr_btree *bt __rte_unused)
227 {
228 #ifdef RTE_LIBRTE_MLX5_DEBUG
229 	int idx;
230 	struct mr_cache_entry *lkp_tbl;
231 
232 	if (bt == NULL)
233 		return;
234 	lkp_tbl = *bt->table;
235 	for (idx = 0; idx < bt->len; ++idx) {
236 		struct mr_cache_entry *entry = &lkp_tbl[idx];
237 
238 		DEBUG("B-tree(%p)[%u],"
239 		      " [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
240 		      (void *)bt, idx, entry->start, entry->end, entry->lkey);
241 	}
242 #endif
243 }
244 
245 /**
246  * Find virtually contiguous memory chunk in a given MR.
247  *
248  * @param dev
249  *   Pointer to MR structure.
250  * @param[out] entry
251  *   Pointer to returning MR cache entry. If not found, this will not be
252  *   updated.
253  * @param start_idx
254  *   Start index of the memseg bitmap.
255  *
256  * @return
257  *   Next index to go on lookup.
258  */
259 static int
260 mr_find_next_chunk(struct mlx5_mr *mr, struct mr_cache_entry *entry,
261 		   int base_idx)
262 {
263 	uintptr_t start = 0;
264 	uintptr_t end = 0;
265 	uint32_t idx = 0;
266 
267 	/* MR for external memory doesn't have memseg list. */
268 	if (mr->msl == NULL) {
269 		struct ibv_mr *ibv_mr = mr->ibv_mr;
270 
271 		MLX5_ASSERT(mr->ms_bmp_n == 1);
272 		MLX5_ASSERT(mr->ms_n == 1);
273 		MLX5_ASSERT(base_idx == 0);
274 		/*
275 		 * Can't search it from memseg list but get it directly from
276 		 * verbs MR as there's only one chunk.
277 		 */
278 		entry->start = (uintptr_t)ibv_mr->addr;
279 		entry->end = (uintptr_t)ibv_mr->addr + mr->ibv_mr->length;
280 		entry->lkey = rte_cpu_to_be_32(mr->ibv_mr->lkey);
281 		/* Returning 1 ends iteration. */
282 		return 1;
283 	}
284 	for (idx = base_idx; idx < mr->ms_bmp_n; ++idx) {
285 		if (rte_bitmap_get(mr->ms_bmp, idx)) {
286 			const struct rte_memseg_list *msl;
287 			const struct rte_memseg *ms;
288 
289 			msl = mr->msl;
290 			ms = rte_fbarray_get(&msl->memseg_arr,
291 					     mr->ms_base_idx + idx);
292 			MLX5_ASSERT(msl->page_sz == ms->hugepage_sz);
293 			if (!start)
294 				start = ms->addr_64;
295 			end = ms->addr_64 + ms->hugepage_sz;
296 		} else if (start) {
297 			/* Passed the end of a fragment. */
298 			break;
299 		}
300 	}
301 	if (start) {
302 		/* Found one chunk. */
303 		entry->start = start;
304 		entry->end = end;
305 		entry->lkey = rte_cpu_to_be_32(mr->ibv_mr->lkey);
306 	}
307 	return idx;
308 }
309 
310 /**
311  * Insert a MR to the global B-tree cache. It may fail due to low-on-memory.
312  * Then, this entry will have to be searched by mr_lookup_list() in
313  * mlx5_mr_create() on miss.
314  *
315  * @param share_cache
316  *   Pointer to a global shared MR cache.
317  * @param mr
318  *   Pointer to MR to insert.
319  *
320  * @return
321  *   0 on success, -1 on failure.
322  */
323 int
324 mlx5_mr_insert_cache(struct mlx5_mr_share_cache *share_cache,
325 		     struct mlx5_mr *mr)
326 {
327 	unsigned int n;
328 
329 	DRV_LOG(DEBUG, "Inserting MR(%p) to global cache(%p)",
330 		(void *)mr, (void *)share_cache);
331 	for (n = 0; n < mr->ms_bmp_n; ) {
332 		struct mr_cache_entry entry;
333 
334 		memset(&entry, 0, sizeof(entry));
335 		/* Find a contiguous chunk and advance the index. */
336 		n = mr_find_next_chunk(mr, &entry, n);
337 		if (!entry.end)
338 			break;
339 		if (mr_btree_insert(&share_cache->cache, &entry) < 0) {
340 			/*
341 			 * Overflowed, but the global table cannot be expanded
342 			 * because of deadlock.
343 			 */
344 			return -1;
345 		}
346 	}
347 	return 0;
348 }
349 
350 /**
351  * Look up address in the original global MR list.
352  *
353  * @param share_cache
354  *   Pointer to a global shared MR cache.
355  * @param[out] entry
356  *   Pointer to returning MR cache entry. If no match, this will not be updated.
357  * @param addr
358  *   Search key.
359  *
360  * @return
361  *   Found MR on match, NULL otherwise.
362  */
363 struct mlx5_mr *
364 mlx5_mr_lookup_list(struct mlx5_mr_share_cache *share_cache,
365 		    struct mr_cache_entry *entry, uintptr_t addr)
366 {
367 	struct mlx5_mr *mr;
368 
369 	/* Iterate all the existing MRs. */
370 	LIST_FOREACH(mr, &share_cache->mr_list, mr) {
371 		unsigned int n;
372 
373 		if (mr->ms_n == 0)
374 			continue;
375 		for (n = 0; n < mr->ms_bmp_n; ) {
376 			struct mr_cache_entry ret;
377 
378 			memset(&ret, 0, sizeof(ret));
379 			n = mr_find_next_chunk(mr, &ret, n);
380 			if (addr >= ret.start && addr < ret.end) {
381 				/* Found. */
382 				*entry = ret;
383 				return mr;
384 			}
385 		}
386 	}
387 	return NULL;
388 }
389 
390 /**
391  * Look up address on global MR cache.
392  *
393  * @param share_cache
394  *   Pointer to a global shared MR cache.
395  * @param[out] entry
396  *   Pointer to returning MR cache entry. If no match, this will not be updated.
397  * @param addr
398  *   Search key.
399  *
400  * @return
401  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
402  */
403 uint32_t
404 mlx5_mr_lookup_cache(struct mlx5_mr_share_cache *share_cache,
405 		     struct mr_cache_entry *entry, uintptr_t addr)
406 {
407 	uint16_t idx;
408 	uint32_t lkey = UINT32_MAX;
409 	struct mlx5_mr *mr;
410 
411 	/*
412 	 * If the global cache has overflowed since it failed to expand the
413 	 * B-tree table, it can't have all the existing MRs. Then, the address
414 	 * has to be searched by traversing the original MR list instead, which
415 	 * is very slow path. Otherwise, the global cache is all inclusive.
416 	 */
417 	if (!unlikely(share_cache->cache.overflow)) {
418 		lkey = mr_btree_lookup(&share_cache->cache, &idx, addr);
419 		if (lkey != UINT32_MAX)
420 			*entry = (*share_cache->cache.table)[idx];
421 	} else {
422 		/* Falling back to the slowest path. */
423 		mr = mlx5_mr_lookup_list(share_cache, entry, addr);
424 		if (mr != NULL)
425 			lkey = entry->lkey;
426 	}
427 	MLX5_ASSERT(lkey == UINT32_MAX || (addr >= entry->start &&
428 					   addr < entry->end));
429 	return lkey;
430 }
431 
432 /**
433  * Free MR resources. MR lock must not be held to avoid a deadlock. rte_free()
434  * can raise memory free event and the callback function will spin on the lock.
435  *
436  * @param mr
437  *   Pointer to MR to free.
438  */
439 static void
440 mr_free(struct mlx5_mr *mr)
441 {
442 	if (mr == NULL)
443 		return;
444 	DRV_LOG(DEBUG, "freeing MR(%p):", (void *)mr);
445 	if (mr->ibv_mr != NULL)
446 		claim_zero(mlx5_glue->dereg_mr(mr->ibv_mr));
447 	if (mr->ms_bmp != NULL)
448 		rte_bitmap_free(mr->ms_bmp);
449 	rte_free(mr);
450 }
451 
452 void
453 mlx5_mr_rebuild_cache(struct mlx5_mr_share_cache *share_cache)
454 {
455 	struct mlx5_mr *mr;
456 
457 	DRV_LOG(DEBUG, "Rebuild dev cache[] %p", (void *)share_cache);
458 	/* Flush cache to rebuild. */
459 	share_cache->cache.len = 1;
460 	share_cache->cache.overflow = 0;
461 	/* Iterate all the existing MRs. */
462 	LIST_FOREACH(mr, &share_cache->mr_list, mr)
463 		if (mlx5_mr_insert_cache(share_cache, mr) < 0)
464 			return;
465 }
466 
467 /**
468  * Release resources of detached MR having no online entry.
469  *
470  * @param share_cache
471  *   Pointer to a global shared MR cache.
472  */
473 static void
474 mlx5_mr_garbage_collect(struct mlx5_mr_share_cache *share_cache)
475 {
476 	struct mlx5_mr *mr_next;
477 	struct mlx5_mr_list free_list = LIST_HEAD_INITIALIZER(free_list);
478 
479 	/* Must be called from the primary process. */
480 	MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
481 	/*
482 	 * MR can't be freed with holding the lock because rte_free() could call
483 	 * memory free callback function. This will be a deadlock situation.
484 	 */
485 	rte_rwlock_write_lock(&share_cache->rwlock);
486 	/* Detach the whole free list and release it after unlocking. */
487 	free_list = share_cache->mr_free_list;
488 	LIST_INIT(&share_cache->mr_free_list);
489 	rte_rwlock_write_unlock(&share_cache->rwlock);
490 	/* Release resources. */
491 	mr_next = LIST_FIRST(&free_list);
492 	while (mr_next != NULL) {
493 		struct mlx5_mr *mr = mr_next;
494 
495 		mr_next = LIST_NEXT(mr, mr);
496 		mr_free(mr);
497 	}
498 }
499 
500 /* Called during rte_memseg_contig_walk() by mlx5_mr_create(). */
501 static int
502 mr_find_contig_memsegs_cb(const struct rte_memseg_list *msl,
503 			  const struct rte_memseg *ms, size_t len, void *arg)
504 {
505 	struct mr_find_contig_memsegs_data *data = arg;
506 
507 	if (data->addr < ms->addr_64 || data->addr >= ms->addr_64 + len)
508 		return 0;
509 	/* Found, save it and stop walking. */
510 	data->start = ms->addr_64;
511 	data->end = ms->addr_64 + len;
512 	data->msl = msl;
513 	return 1;
514 }
515 
516 /**
517  * Create a new global Memory Region (MR) for a missing virtual address.
518  * This API should be called on a secondary process, then a request is sent to
519  * the primary process in order to create a MR for the address. As the global MR
520  * list is on the shared memory, following LKey lookup should succeed unless the
521  * request fails.
522  *
523  * @param pd
524  *   Pointer to ibv_pd of a device (net, regex, vdpa,...).
525  * @param share_cache
526  *   Pointer to a global shared MR cache.
527  * @param[out] entry
528  *   Pointer to returning MR cache entry, found in the global cache or newly
529  *   created. If failed to create one, this will not be updated.
530  * @param addr
531  *   Target virtual address to register.
532  * @param mr_ext_memseg_en
533  *   Configurable flag about external memory segment enable or not.
534  *
535  * @return
536  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
537  */
538 static uint32_t
539 mlx5_mr_create_secondary(struct ibv_pd *pd __rte_unused,
540 			 struct mlx5_mp_id *mp_id,
541 			 struct mlx5_mr_share_cache *share_cache,
542 			 struct mr_cache_entry *entry, uintptr_t addr,
543 			 unsigned int mr_ext_memseg_en __rte_unused)
544 {
545 	int ret;
546 
547 	DEBUG("port %u requesting MR creation for address (%p)",
548 	      mp_id->port_id, (void *)addr);
549 	ret = mlx5_mp_req_mr_create(mp_id, addr);
550 	if (ret) {
551 		DEBUG("Fail to request MR creation for address (%p)",
552 		      (void *)addr);
553 		return UINT32_MAX;
554 	}
555 	rte_rwlock_read_lock(&share_cache->rwlock);
556 	/* Fill in output data. */
557 	mlx5_mr_lookup_cache(share_cache, entry, addr);
558 	/* Lookup can't fail. */
559 	MLX5_ASSERT(entry->lkey != UINT32_MAX);
560 	rte_rwlock_read_unlock(&share_cache->rwlock);
561 	DEBUG("MR CREATED by primary process for %p:\n"
562 	      "  [0x%" PRIxPTR ", 0x%" PRIxPTR "), lkey=0x%x",
563 	      (void *)addr, entry->start, entry->end, entry->lkey);
564 	return entry->lkey;
565 }
566 
567 /**
568  * Create a new global Memory Region (MR) for a missing virtual address.
569  * Register entire virtually contiguous memory chunk around the address.
570  *
571  * @param pd
572  *   Pointer to ibv_pd of a device (net, regex, vdpa,...).
573  * @param share_cache
574  *   Pointer to a global shared MR cache.
575  * @param[out] entry
576  *   Pointer to returning MR cache entry, found in the global cache or newly
577  *   created. If failed to create one, this will not be updated.
578  * @param addr
579  *   Target virtual address to register.
580  * @param mr_ext_memseg_en
581  *   Configurable flag about external memory segment enable or not.
582  *
583  * @return
584  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
585  */
586 uint32_t
587 mlx5_mr_create_primary(struct ibv_pd *pd,
588 		       struct mlx5_mr_share_cache *share_cache,
589 		       struct mr_cache_entry *entry, uintptr_t addr,
590 		       unsigned int mr_ext_memseg_en)
591 {
592 	struct mr_find_contig_memsegs_data data = {.addr = addr, };
593 	struct mr_find_contig_memsegs_data data_re;
594 	const struct rte_memseg_list *msl;
595 	const struct rte_memseg *ms;
596 	struct mlx5_mr *mr = NULL;
597 	int ms_idx_shift = -1;
598 	uint32_t bmp_size;
599 	void *bmp_mem;
600 	uint32_t ms_n;
601 	uint32_t n;
602 	size_t len;
603 
604 	DRV_LOG(DEBUG, "Creating a MR using address (%p)", (void *)addr);
605 	/*
606 	 * Release detached MRs if any. This can't be called with holding either
607 	 * memory_hotplug_lock or share_cache->rwlock. MRs on the free list have
608 	 * been detached by the memory free event but it couldn't be released
609 	 * inside the callback due to deadlock. As a result, releasing resources
610 	 * is quite opportunistic.
611 	 */
612 	mlx5_mr_garbage_collect(share_cache);
613 	/*
614 	 * If enabled, find out a contiguous virtual address chunk in use, to
615 	 * which the given address belongs, in order to register maximum range.
616 	 * In the best case where mempools are not dynamically recreated and
617 	 * '--socket-mem' is specified as an EAL option, it is very likely to
618 	 * have only one MR(LKey) per a socket and per a hugepage-size even
619 	 * though the system memory is highly fragmented. As the whole memory
620 	 * chunk will be pinned by kernel, it can't be reused unless entire
621 	 * chunk is freed from EAL.
622 	 *
623 	 * If disabled, just register one memseg (page). Then, memory
624 	 * consumption will be minimized but it may drop performance if there
625 	 * are many MRs to lookup on the datapath.
626 	 */
627 	if (!mr_ext_memseg_en) {
628 		data.msl = rte_mem_virt2memseg_list((void *)addr);
629 		data.start = RTE_ALIGN_FLOOR(addr, data.msl->page_sz);
630 		data.end = data.start + data.msl->page_sz;
631 	} else if (!rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data)) {
632 		DRV_LOG(WARNING,
633 			"Unable to find virtually contiguous"
634 			" chunk for address (%p)."
635 			" rte_memseg_contig_walk() failed.", (void *)addr);
636 		rte_errno = ENXIO;
637 		goto err_nolock;
638 	}
639 alloc_resources:
640 	/* Addresses must be page-aligned. */
641 	MLX5_ASSERT(data.msl);
642 	MLX5_ASSERT(rte_is_aligned((void *)data.start, data.msl->page_sz));
643 	MLX5_ASSERT(rte_is_aligned((void *)data.end, data.msl->page_sz));
644 	msl = data.msl;
645 	ms = rte_mem_virt2memseg((void *)data.start, msl);
646 	len = data.end - data.start;
647 	MLX5_ASSERT(ms);
648 	MLX5_ASSERT(msl->page_sz == ms->hugepage_sz);
649 	/* Number of memsegs in the range. */
650 	ms_n = len / msl->page_sz;
651 	DEBUG("Extending %p to [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
652 	      " page_sz=0x%" PRIx64 ", ms_n=%u",
653 	      (void *)addr, data.start, data.end, msl->page_sz, ms_n);
654 	/* Size of memory for bitmap. */
655 	bmp_size = rte_bitmap_get_memory_footprint(ms_n);
656 	mr = rte_zmalloc_socket(NULL,
657 				RTE_ALIGN_CEIL(sizeof(*mr),
658 					       RTE_CACHE_LINE_SIZE) +
659 				bmp_size,
660 				RTE_CACHE_LINE_SIZE, msl->socket_id);
661 	if (mr == NULL) {
662 		DEBUG("Unable to allocate memory for a new MR of"
663 		      " address (%p).", (void *)addr);
664 		rte_errno = ENOMEM;
665 		goto err_nolock;
666 	}
667 	mr->msl = msl;
668 	/*
669 	 * Save the index of the first memseg and initialize memseg bitmap. To
670 	 * see if a memseg of ms_idx in the memseg-list is still valid, check:
671 	 *	rte_bitmap_get(mr->bmp, ms_idx - mr->ms_base_idx)
672 	 */
673 	mr->ms_base_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
674 	bmp_mem = RTE_PTR_ALIGN_CEIL(mr + 1, RTE_CACHE_LINE_SIZE);
675 	mr->ms_bmp = rte_bitmap_init(ms_n, bmp_mem, bmp_size);
676 	if (mr->ms_bmp == NULL) {
677 		DEBUG("Unable to initialize bitmap for a new MR of"
678 		      " address (%p).", (void *)addr);
679 		rte_errno = EINVAL;
680 		goto err_nolock;
681 	}
682 	/*
683 	 * Should recheck whether the extended contiguous chunk is still valid.
684 	 * Because memory_hotplug_lock can't be held if there's any memory
685 	 * related calls in a critical path, resource allocation above can't be
686 	 * locked. If the memory has been changed at this point, try again with
687 	 * just single page. If not, go on with the big chunk atomically from
688 	 * here.
689 	 */
690 	rte_mcfg_mem_read_lock();
691 	data_re = data;
692 	if (len > msl->page_sz &&
693 	    !rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data_re)) {
694 		DEBUG("Unable to find virtually contiguous"
695 		      " chunk for address (%p)."
696 		      " rte_memseg_contig_walk() failed.", (void *)addr);
697 		rte_errno = ENXIO;
698 		goto err_memlock;
699 	}
700 	if (data.start != data_re.start || data.end != data_re.end) {
701 		/*
702 		 * The extended contiguous chunk has been changed. Try again
703 		 * with single memseg instead.
704 		 */
705 		data.start = RTE_ALIGN_FLOOR(addr, msl->page_sz);
706 		data.end = data.start + msl->page_sz;
707 		rte_mcfg_mem_read_unlock();
708 		mr_free(mr);
709 		goto alloc_resources;
710 	}
711 	MLX5_ASSERT(data.msl == data_re.msl);
712 	rte_rwlock_write_lock(&share_cache->rwlock);
713 	/*
714 	 * Check the address is really missing. If other thread already created
715 	 * one or it is not found due to overflow, abort and return.
716 	 */
717 	if (mlx5_mr_lookup_cache(share_cache, entry, addr) != UINT32_MAX) {
718 		/*
719 		 * Insert to the global cache table. It may fail due to
720 		 * low-on-memory. Then, this entry will have to be searched
721 		 * here again.
722 		 */
723 		mr_btree_insert(&share_cache->cache, entry);
724 		DEBUG("Found MR for %p on final lookup, abort", (void *)addr);
725 		rte_rwlock_write_unlock(&share_cache->rwlock);
726 		rte_mcfg_mem_read_unlock();
727 		/*
728 		 * Must be unlocked before calling rte_free() because
729 		 * mlx5_mr_mem_event_free_cb() can be called inside.
730 		 */
731 		mr_free(mr);
732 		return entry->lkey;
733 	}
734 	/*
735 	 * Trim start and end addresses for verbs MR. Set bits for registering
736 	 * memsegs but exclude already registered ones. Bitmap can be
737 	 * fragmented.
738 	 */
739 	for (n = 0; n < ms_n; ++n) {
740 		uintptr_t start;
741 		struct mr_cache_entry ret;
742 
743 		memset(&ret, 0, sizeof(ret));
744 		start = data_re.start + n * msl->page_sz;
745 		/* Exclude memsegs already registered by other MRs. */
746 		if (mlx5_mr_lookup_cache(share_cache, &ret, start) ==
747 		    UINT32_MAX) {
748 			/*
749 			 * Start from the first unregistered memseg in the
750 			 * extended range.
751 			 */
752 			if (ms_idx_shift == -1) {
753 				mr->ms_base_idx += n;
754 				data.start = start;
755 				ms_idx_shift = n;
756 			}
757 			data.end = start + msl->page_sz;
758 			rte_bitmap_set(mr->ms_bmp, n - ms_idx_shift);
759 			++mr->ms_n;
760 		}
761 	}
762 	len = data.end - data.start;
763 	mr->ms_bmp_n = len / msl->page_sz;
764 	MLX5_ASSERT(ms_idx_shift + mr->ms_bmp_n <= ms_n);
765 	/*
766 	 * Finally create a verbs MR for the memory chunk. ibv_reg_mr() can be
767 	 * called with holding the memory lock because it doesn't use
768 	 * mlx5_alloc_buf_extern() which eventually calls rte_malloc_socket()
769 	 * through mlx5_alloc_verbs_buf().
770 	 */
771 	mr->ibv_mr = mlx5_glue->reg_mr(pd, (void *)data.start, len,
772 				       IBV_ACCESS_LOCAL_WRITE |
773 					   IBV_ACCESS_RELAXED_ORDERING);
774 	if (mr->ibv_mr == NULL) {
775 		DEBUG("Fail to create a verbs MR for address (%p)",
776 		      (void *)addr);
777 		rte_errno = EINVAL;
778 		goto err_mrlock;
779 	}
780 	MLX5_ASSERT((uintptr_t)mr->ibv_mr->addr == data.start);
781 	MLX5_ASSERT(mr->ibv_mr->length == len);
782 	LIST_INSERT_HEAD(&share_cache->mr_list, mr, mr);
783 	DEBUG("MR CREATED (%p) for %p:\n"
784 	      "  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
785 	      " lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
786 	      (void *)mr, (void *)addr, data.start, data.end,
787 	      rte_cpu_to_be_32(mr->ibv_mr->lkey),
788 	      mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
789 	/* Insert to the global cache table. */
790 	mlx5_mr_insert_cache(share_cache, mr);
791 	/* Fill in output data. */
792 	mlx5_mr_lookup_cache(share_cache, entry, addr);
793 	/* Lookup can't fail. */
794 	MLX5_ASSERT(entry->lkey != UINT32_MAX);
795 	rte_rwlock_write_unlock(&share_cache->rwlock);
796 	rte_mcfg_mem_read_unlock();
797 	return entry->lkey;
798 err_mrlock:
799 	rte_rwlock_write_unlock(&share_cache->rwlock);
800 err_memlock:
801 	rte_mcfg_mem_read_unlock();
802 err_nolock:
803 	/*
804 	 * In case of error, as this can be called in a datapath, a warning
805 	 * message per an error is preferable instead. Must be unlocked before
806 	 * calling rte_free() because mlx5_mr_mem_event_free_cb() can be called
807 	 * inside.
808 	 */
809 	mr_free(mr);
810 	return UINT32_MAX;
811 }
812 
813 /**
814  * Create a new global Memory Region (MR) for a missing virtual address.
815  * This can be called from primary and secondary process.
816  *
817  * @param pd
818  *   Pointer to ibv_pd of a device (net, regex, vdpa,...).
819  * @param share_cache
820  *   Pointer to a global shared MR cache.
821  * @param[out] entry
822  *   Pointer to returning MR cache entry, found in the global cache or newly
823  *   created. If failed to create one, this will not be updated.
824  * @param addr
825  *   Target virtual address to register.
826  *
827  * @return
828  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
829  */
830 static uint32_t
831 mlx5_mr_create(struct ibv_pd *pd, struct mlx5_mp_id *mp_id,
832 	       struct mlx5_mr_share_cache *share_cache,
833 	       struct mr_cache_entry *entry, uintptr_t addr,
834 	       unsigned int mr_ext_memseg_en)
835 {
836 	uint32_t ret = 0;
837 
838 	switch (rte_eal_process_type()) {
839 	case RTE_PROC_PRIMARY:
840 		ret = mlx5_mr_create_primary(pd, share_cache, entry,
841 					     addr, mr_ext_memseg_en);
842 		break;
843 	case RTE_PROC_SECONDARY:
844 		ret = mlx5_mr_create_secondary(pd, mp_id, share_cache, entry,
845 					       addr, mr_ext_memseg_en);
846 		break;
847 	default:
848 		break;
849 	}
850 	return ret;
851 }
852 
853 /**
854  * Look up address in the global MR cache table. If not found, create a new MR.
855  * Insert the found/created entry to local bottom-half cache table.
856  *
857  * @param pd
858  *   Pointer to ibv_pd of a device (net, regex, vdpa,...).
859  * @param share_cache
860  *   Pointer to a global shared MR cache.
861  * @param mr_ctrl
862  *   Pointer to per-queue MR control structure.
863  * @param[out] entry
864  *   Pointer to returning MR cache entry, found in the global cache or newly
865  *   created. If failed to create one, this is not written.
866  * @param addr
867  *   Search key.
868  *
869  * @return
870  *   Searched LKey on success, UINT32_MAX on no match.
871  */
872 static uint32_t
873 mr_lookup_caches(struct ibv_pd *pd, struct mlx5_mp_id *mp_id,
874 		 struct mlx5_mr_share_cache *share_cache,
875 		 struct mlx5_mr_ctrl *mr_ctrl,
876 		 struct mr_cache_entry *entry, uintptr_t addr,
877 		 unsigned int mr_ext_memseg_en)
878 {
879 	struct mlx5_mr_btree *bt = &mr_ctrl->cache_bh;
880 	uint32_t lkey;
881 	uint16_t idx;
882 
883 	/* If local cache table is full, try to double it. */
884 	if (unlikely(bt->len == bt->size))
885 		mr_btree_expand(bt, bt->size << 1);
886 	/* Look up in the global cache. */
887 	rte_rwlock_read_lock(&share_cache->rwlock);
888 	lkey = mr_btree_lookup(&share_cache->cache, &idx, addr);
889 	if (lkey != UINT32_MAX) {
890 		/* Found. */
891 		*entry = (*share_cache->cache.table)[idx];
892 		rte_rwlock_read_unlock(&share_cache->rwlock);
893 		/*
894 		 * Update local cache. Even if it fails, return the found entry
895 		 * to update top-half cache. Next time, this entry will be found
896 		 * in the global cache.
897 		 */
898 		mr_btree_insert(bt, entry);
899 		return lkey;
900 	}
901 	rte_rwlock_read_unlock(&share_cache->rwlock);
902 	/* First time to see the address? Create a new MR. */
903 	lkey = mlx5_mr_create(pd, mp_id, share_cache, entry, addr,
904 			      mr_ext_memseg_en);
905 	/*
906 	 * Update the local cache if successfully created a new global MR. Even
907 	 * if failed to create one, there's no action to take in this datapath
908 	 * code. As returning LKey is invalid, this will eventually make HW
909 	 * fail.
910 	 */
911 	if (lkey != UINT32_MAX)
912 		mr_btree_insert(bt, entry);
913 	return lkey;
914 }
915 
916 /**
917  * Bottom-half of LKey search on datapath. First search in cache_bh[] and if
918  * misses, search in the global MR cache table and update the new entry to
919  * per-queue local caches.
920  *
921  * @param pd
922  *   Pointer to ibv_pd of a device (net, regex, vdpa,...).
923  * @param share_cache
924  *   Pointer to a global shared MR cache.
925  * @param mr_ctrl
926  *   Pointer to per-queue MR control structure.
927  * @param addr
928  *   Search key.
929  *
930  * @return
931  *   Searched LKey on success, UINT32_MAX on no match.
932  */
933 uint32_t mlx5_mr_addr2mr_bh(struct ibv_pd *pd, struct mlx5_mp_id *mp_id,
934 			    struct mlx5_mr_share_cache *share_cache,
935 			    struct mlx5_mr_ctrl *mr_ctrl,
936 			    uintptr_t addr, unsigned int mr_ext_memseg_en)
937 {
938 	uint32_t lkey;
939 	uint16_t bh_idx = 0;
940 	/* Victim in top-half cache to replace with new entry. */
941 	struct mr_cache_entry *repl = &mr_ctrl->cache[mr_ctrl->head];
942 
943 	/* Binary-search MR translation table. */
944 	lkey = mr_btree_lookup(&mr_ctrl->cache_bh, &bh_idx, addr);
945 	/* Update top-half cache. */
946 	if (likely(lkey != UINT32_MAX)) {
947 		*repl = (*mr_ctrl->cache_bh.table)[bh_idx];
948 	} else {
949 		/*
950 		 * If missed in local lookup table, search in the global cache
951 		 * and local cache_bh[] will be updated inside if possible.
952 		 * Top-half cache entry will also be updated.
953 		 */
954 		lkey = mr_lookup_caches(pd, mp_id, share_cache, mr_ctrl,
955 					repl, addr, mr_ext_memseg_en);
956 		if (unlikely(lkey == UINT32_MAX))
957 			return UINT32_MAX;
958 	}
959 	/* Update the most recently used entry. */
960 	mr_ctrl->mru = mr_ctrl->head;
961 	/* Point to the next victim, the oldest. */
962 	mr_ctrl->head = (mr_ctrl->head + 1) % MLX5_MR_CACHE_N;
963 	return lkey;
964 }
965 
966 /**
967  * Release all the created MRs and resources on global MR cache of a device.
968  * list.
969  *
970  * @param share_cache
971  *   Pointer to a global shared MR cache.
972  */
973 void
974 mlx5_mr_release_cache(struct mlx5_mr_share_cache *share_cache)
975 {
976 	struct mlx5_mr *mr_next;
977 
978 	rte_rwlock_write_lock(&share_cache->rwlock);
979 	/* Detach from MR list and move to free list. */
980 	mr_next = LIST_FIRST(&share_cache->mr_list);
981 	while (mr_next != NULL) {
982 		struct mlx5_mr *mr = mr_next;
983 
984 		mr_next = LIST_NEXT(mr, mr);
985 		LIST_REMOVE(mr, mr);
986 		LIST_INSERT_HEAD(&share_cache->mr_free_list, mr, mr);
987 	}
988 	LIST_INIT(&share_cache->mr_list);
989 	/* Free global cache. */
990 	mlx5_mr_btree_free(&share_cache->cache);
991 	rte_rwlock_write_unlock(&share_cache->rwlock);
992 	/* Free all remaining MRs. */
993 	mlx5_mr_garbage_collect(share_cache);
994 }
995 
996 /**
997  * Flush all of the local cache entries.
998  *
999  * @param mr_ctrl
1000  *   Pointer to per-queue MR local cache.
1001  */
1002 void
1003 mlx5_mr_flush_local_cache(struct mlx5_mr_ctrl *mr_ctrl)
1004 {
1005 	/* Reset the most-recently-used index. */
1006 	mr_ctrl->mru = 0;
1007 	/* Reset the linear search array. */
1008 	mr_ctrl->head = 0;
1009 	memset(mr_ctrl->cache, 0, sizeof(mr_ctrl->cache));
1010 	/* Reset the B-tree table. */
1011 	mr_ctrl->cache_bh.len = 1;
1012 	mr_ctrl->cache_bh.overflow = 0;
1013 	/* Update the generation number. */
1014 	mr_ctrl->cur_gen = *mr_ctrl->dev_gen_ptr;
1015 	DRV_LOG(DEBUG, "mr_ctrl(%p): flushed, cur_gen=%d",
1016 		(void *)mr_ctrl, mr_ctrl->cur_gen);
1017 }
1018 
1019 /**
1020  * Creates a memory region for external memory, that is memory which is not
1021  * part of the DPDK memory segments.
1022  *
1023  * @param pd
1024  *   Pointer to ibv_pd of a device (net, regex, vdpa,...).
1025  * @param addr
1026  *   Starting virtual address of memory.
1027  * @param len
1028  *   Length of memory segment being mapped.
1029  * @param socked_id
1030  *   Socket to allocate heap memory for the control structures.
1031  *
1032  * @return
1033  *   Pointer to MR structure on success, NULL otherwise.
1034  */
1035 struct mlx5_mr *
1036 mlx5_create_mr_ext(struct ibv_pd *pd, uintptr_t addr, size_t len, int socket_id)
1037 {
1038 	struct mlx5_mr *mr = NULL;
1039 
1040 	mr = rte_zmalloc_socket(NULL,
1041 				RTE_ALIGN_CEIL(sizeof(*mr),
1042 					       RTE_CACHE_LINE_SIZE),
1043 				RTE_CACHE_LINE_SIZE, socket_id);
1044 	if (mr == NULL)
1045 		return NULL;
1046 	mr->ibv_mr = mlx5_glue->reg_mr(pd, (void *)addr, len,
1047 				       IBV_ACCESS_LOCAL_WRITE |
1048 					   IBV_ACCESS_RELAXED_ORDERING);
1049 	if (mr->ibv_mr == NULL) {
1050 		DRV_LOG(WARNING,
1051 			"Fail to create a verbs MR for address (%p)",
1052 			(void *)addr);
1053 		rte_free(mr);
1054 		return NULL;
1055 	}
1056 	mr->msl = NULL; /* Mark it is external memory. */
1057 	mr->ms_bmp = NULL;
1058 	mr->ms_n = 1;
1059 	mr->ms_bmp_n = 1;
1060 	DRV_LOG(DEBUG,
1061 		"MR CREATED (%p) for external memory %p:\n"
1062 		"  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
1063 		" lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
1064 		(void *)mr, (void *)addr,
1065 		addr, addr + len, rte_cpu_to_be_32(mr->ibv_mr->lkey),
1066 		mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
1067 	return mr;
1068 }
1069 
1070 /**
1071  * Dump all the created MRs and the global cache entries.
1072  *
1073  * @param sh
1074  *   Pointer to Ethernet device shared context.
1075  */
1076 void
1077 mlx5_mr_dump_cache(struct mlx5_mr_share_cache *share_cache __rte_unused)
1078 {
1079 #ifdef RTE_LIBRTE_MLX5_DEBUG
1080 	struct mlx5_mr *mr;
1081 	int mr_n = 0;
1082 	int chunk_n = 0;
1083 
1084 	rte_rwlock_read_lock(&share_cache->rwlock);
1085 	/* Iterate all the existing MRs. */
1086 	LIST_FOREACH(mr, &share_cache->mr_list, mr) {
1087 		unsigned int n;
1088 
1089 		DEBUG("MR[%u], LKey = 0x%x, ms_n = %u, ms_bmp_n = %u",
1090 		      mr_n++, rte_cpu_to_be_32(mr->ibv_mr->lkey),
1091 		      mr->ms_n, mr->ms_bmp_n);
1092 		if (mr->ms_n == 0)
1093 			continue;
1094 		for (n = 0; n < mr->ms_bmp_n; ) {
1095 			struct mr_cache_entry ret = { 0, };
1096 
1097 			n = mr_find_next_chunk(mr, &ret, n);
1098 			if (!ret.end)
1099 				break;
1100 			DEBUG("  chunk[%u], [0x%" PRIxPTR ", 0x%" PRIxPTR ")",
1101 			      chunk_n++, ret.start, ret.end);
1102 		}
1103 	}
1104 	DEBUG("Dumping global cache %p", (void *)share_cache);
1105 	mlx5_mr_btree_dump(&share_cache->cache);
1106 	rte_rwlock_read_unlock(&share_cache->rwlock);
1107 #endif
1108 }
1109