xref: /f-stack/dpdk/drivers/net/mlx4/mlx4_mr.c (revision 16d80a6d)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2017 6WIND S.A.
3  * Copyright 2017 Mellanox Technologies, Ltd
4  */
5 
6 /**
7  * @file
8  * Memory management functions for mlx4 driver.
9  */
10 
11 #include <assert.h>
12 #include <errno.h>
13 #include <inttypes.h>
14 #include <stddef.h>
15 #include <stdint.h>
16 #include <string.h>
17 
18 /* Verbs headers do not support -pedantic. */
19 #ifdef PEDANTIC
20 #pragma GCC diagnostic ignored "-Wpedantic"
21 #endif
22 #include <infiniband/verbs.h>
23 #ifdef PEDANTIC
24 #pragma GCC diagnostic error "-Wpedantic"
25 #endif
26 
27 #include <rte_branch_prediction.h>
28 #include <rte_common.h>
29 #include <rte_errno.h>
30 #include <rte_malloc.h>
31 #include <rte_memory.h>
32 #include <rte_mempool.h>
33 #include <rte_rwlock.h>
34 
35 #include "mlx4_glue.h"
36 #include "mlx4_mr.h"
37 #include "mlx4_rxtx.h"
38 #include "mlx4_utils.h"
39 
40 struct mr_find_contig_memsegs_data {
41 	uintptr_t addr;
42 	uintptr_t start;
43 	uintptr_t end;
44 	const struct rte_memseg_list *msl;
45 };
46 
47 struct mr_update_mp_data {
48 	struct rte_eth_dev *dev;
49 	struct mlx4_mr_ctrl *mr_ctrl;
50 	int ret;
51 };
52 
53 /**
54  * Expand B-tree table to a given size. Can't be called with holding
55  * memory_hotplug_lock or priv->mr.rwlock due to rte_realloc().
56  *
57  * @param bt
58  *   Pointer to B-tree structure.
59  * @param n
60  *   Number of entries for expansion.
61  *
62  * @return
63  *   0 on success, -1 on failure.
64  */
65 static int
66 mr_btree_expand(struct mlx4_mr_btree *bt, int n)
67 {
68 	void *mem;
69 	int ret = 0;
70 
71 	if (n <= bt->size)
72 		return ret;
73 	/*
74 	 * Downside of directly using rte_realloc() is that SOCKET_ID_ANY is
75 	 * used inside if there's no room to expand. Because this is a quite
76 	 * rare case and a part of very slow path, it is very acceptable.
77 	 * Initially cache_bh[] will be given practically enough space and once
78 	 * it is expanded, expansion wouldn't be needed again ever.
79 	 */
80 	mem = rte_realloc(bt->table, n * sizeof(struct mlx4_mr_cache), 0);
81 	if (mem == NULL) {
82 		/* Not an error, B-tree search will be skipped. */
83 		WARN("failed to expand MR B-tree (%p) table", (void *)bt);
84 		ret = -1;
85 	} else {
86 		DEBUG("expanded MR B-tree table (size=%u)", n);
87 		bt->table = mem;
88 		bt->size = n;
89 	}
90 	return ret;
91 }
92 
93 /**
94  * Look up LKey from given B-tree lookup table, store the last index and return
95  * searched LKey.
96  *
97  * @param bt
98  *   Pointer to B-tree structure.
99  * @param[out] idx
100  *   Pointer to index. Even on search failure, returns index where it stops
101  *   searching so that index can be used when inserting a new entry.
102  * @param addr
103  *   Search key.
104  *
105  * @return
106  *   Searched LKey on success, UINT32_MAX on no match.
107  */
108 static uint32_t
109 mr_btree_lookup(struct mlx4_mr_btree *bt, uint16_t *idx, uintptr_t addr)
110 {
111 	struct mlx4_mr_cache *lkp_tbl;
112 	uint16_t n;
113 	uint16_t base = 0;
114 
115 	assert(bt != NULL);
116 	lkp_tbl = *bt->table;
117 	n = bt->len;
118 	/* First entry must be NULL for comparison. */
119 	assert(bt->len > 0 || (lkp_tbl[0].start == 0 &&
120 			       lkp_tbl[0].lkey == UINT32_MAX));
121 	/* Binary search. */
122 	do {
123 		register uint16_t delta = n >> 1;
124 
125 		if (addr < lkp_tbl[base + delta].start) {
126 			n = delta;
127 		} else {
128 			base += delta;
129 			n -= delta;
130 		}
131 	} while (n > 1);
132 	assert(addr >= lkp_tbl[base].start);
133 	*idx = base;
134 	if (addr < lkp_tbl[base].end)
135 		return lkp_tbl[base].lkey;
136 	/* Not found. */
137 	return UINT32_MAX;
138 }
139 
140 /**
141  * Insert an entry to B-tree lookup table.
142  *
143  * @param bt
144  *   Pointer to B-tree structure.
145  * @param entry
146  *   Pointer to new entry to insert.
147  *
148  * @return
149  *   0 on success, -1 on failure.
150  */
151 static int
152 mr_btree_insert(struct mlx4_mr_btree *bt, struct mlx4_mr_cache *entry)
153 {
154 	struct mlx4_mr_cache *lkp_tbl;
155 	uint16_t idx = 0;
156 	size_t shift;
157 
158 	assert(bt != NULL);
159 	assert(bt->len <= bt->size);
160 	assert(bt->len > 0);
161 	lkp_tbl = *bt->table;
162 	/* Find out the slot for insertion. */
163 	if (mr_btree_lookup(bt, &idx, entry->start) != UINT32_MAX) {
164 		DEBUG("abort insertion to B-tree(%p): already exist at"
165 		      " idx=%u [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
166 		      (void *)bt, idx, entry->start, entry->end, entry->lkey);
167 		/* Already exist, return. */
168 		return 0;
169 	}
170 	/* If table is full, return error. */
171 	if (unlikely(bt->len == bt->size)) {
172 		bt->overflow = 1;
173 		return -1;
174 	}
175 	/* Insert entry. */
176 	++idx;
177 	shift = (bt->len - idx) * sizeof(struct mlx4_mr_cache);
178 	if (shift)
179 		memmove(&lkp_tbl[idx + 1], &lkp_tbl[idx], shift);
180 	lkp_tbl[idx] = *entry;
181 	bt->len++;
182 	DEBUG("inserted B-tree(%p)[%u],"
183 	      " [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
184 	      (void *)bt, idx, entry->start, entry->end, entry->lkey);
185 	return 0;
186 }
187 
188 /**
189  * Initialize B-tree and allocate memory for lookup table.
190  *
191  * @param bt
192  *   Pointer to B-tree structure.
193  * @param n
194  *   Number of entries to allocate.
195  * @param socket
196  *   NUMA socket on which memory must be allocated.
197  *
198  * @return
199  *   0 on success, a negative errno value otherwise and rte_errno is set.
200  */
201 int
202 mlx4_mr_btree_init(struct mlx4_mr_btree *bt, int n, int socket)
203 {
204 	if (bt == NULL) {
205 		rte_errno = EINVAL;
206 		return -rte_errno;
207 	}
208 	memset(bt, 0, sizeof(*bt));
209 	bt->table = rte_calloc_socket("B-tree table",
210 				      n, sizeof(struct mlx4_mr_cache),
211 				      0, socket);
212 	if (bt->table == NULL) {
213 		rte_errno = ENOMEM;
214 		ERROR("failed to allocate memory for btree cache on socket %d",
215 		      socket);
216 		return -rte_errno;
217 	}
218 	bt->size = n;
219 	/* First entry must be NULL for binary search. */
220 	(*bt->table)[bt->len++] = (struct mlx4_mr_cache) {
221 		.lkey = UINT32_MAX,
222 	};
223 	DEBUG("initialized B-tree %p with table %p",
224 	      (void *)bt, (void *)bt->table);
225 	return 0;
226 }
227 
228 /**
229  * Free B-tree resources.
230  *
231  * @param bt
232  *   Pointer to B-tree structure.
233  */
234 void
235 mlx4_mr_btree_free(struct mlx4_mr_btree *bt)
236 {
237 	if (bt == NULL)
238 		return;
239 	DEBUG("freeing B-tree %p with table %p", (void *)bt, (void *)bt->table);
240 	rte_free(bt->table);
241 	memset(bt, 0, sizeof(*bt));
242 }
243 
244 #ifndef NDEBUG
245 /**
246  * Dump all the entries in a B-tree
247  *
248  * @param bt
249  *   Pointer to B-tree structure.
250  */
251 void
252 mlx4_mr_btree_dump(struct mlx4_mr_btree *bt)
253 {
254 	int idx;
255 	struct mlx4_mr_cache *lkp_tbl;
256 
257 	if (bt == NULL)
258 		return;
259 	lkp_tbl = *bt->table;
260 	for (idx = 0; idx < bt->len; ++idx) {
261 		struct mlx4_mr_cache *entry = &lkp_tbl[idx];
262 
263 		DEBUG("B-tree(%p)[%u],"
264 		      " [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
265 		      (void *)bt, idx, entry->start, entry->end, entry->lkey);
266 	}
267 }
268 #endif
269 
270 /**
271  * Find virtually contiguous memory chunk in a given MR.
272  *
273  * @param dev
274  *   Pointer to MR structure.
275  * @param[out] entry
276  *   Pointer to returning MR cache entry. If not found, this will not be
277  *   updated.
278  * @param start_idx
279  *   Start index of the memseg bitmap.
280  *
281  * @return
282  *   Next index to go on lookup.
283  */
284 static int
285 mr_find_next_chunk(struct mlx4_mr *mr, struct mlx4_mr_cache *entry,
286 		   int base_idx)
287 {
288 	uintptr_t start = 0;
289 	uintptr_t end = 0;
290 	uint32_t idx = 0;
291 
292 	/* MR for external memory doesn't have memseg list. */
293 	if (mr->msl == NULL) {
294 		struct ibv_mr *ibv_mr = mr->ibv_mr;
295 
296 		assert(mr->ms_bmp_n == 1);
297 		assert(mr->ms_n == 1);
298 		assert(base_idx == 0);
299 		/*
300 		 * Can't search it from memseg list but get it directly from
301 		 * verbs MR as there's only one chunk.
302 		 */
303 		entry->start = (uintptr_t)ibv_mr->addr;
304 		entry->end = (uintptr_t)ibv_mr->addr + mr->ibv_mr->length;
305 		entry->lkey = rte_cpu_to_be_32(mr->ibv_mr->lkey);
306 		/* Returning 1 ends iteration. */
307 		return 1;
308 	}
309 	for (idx = base_idx; idx < mr->ms_bmp_n; ++idx) {
310 		if (rte_bitmap_get(mr->ms_bmp, idx)) {
311 			const struct rte_memseg_list *msl;
312 			const struct rte_memseg *ms;
313 
314 			msl = mr->msl;
315 			ms = rte_fbarray_get(&msl->memseg_arr,
316 					     mr->ms_base_idx + idx);
317 			assert(msl->page_sz == ms->hugepage_sz);
318 			if (!start)
319 				start = ms->addr_64;
320 			end = ms->addr_64 + ms->hugepage_sz;
321 		} else if (start) {
322 			/* Passed the end of a fragment. */
323 			break;
324 		}
325 	}
326 	if (start) {
327 		/* Found one chunk. */
328 		entry->start = start;
329 		entry->end = end;
330 		entry->lkey = rte_cpu_to_be_32(mr->ibv_mr->lkey);
331 	}
332 	return idx;
333 }
334 
335 /**
336  * Insert a MR to the global B-tree cache. It may fail due to low-on-memory.
337  * Then, this entry will have to be searched by mr_lookup_dev_list() in
338  * mlx4_mr_create() on miss.
339  *
340  * @param dev
341  *   Pointer to Ethernet device.
342  * @param mr
343  *   Pointer to MR to insert.
344  *
345  * @return
346  *   0 on success, -1 on failure.
347  */
348 static int
349 mr_insert_dev_cache(struct rte_eth_dev *dev, struct mlx4_mr *mr)
350 {
351 	struct mlx4_priv *priv = dev->data->dev_private;
352 	unsigned int n;
353 
354 	DEBUG("port %u inserting MR(%p) to global cache",
355 	      dev->data->port_id, (void *)mr);
356 	for (n = 0; n < mr->ms_bmp_n; ) {
357 		struct mlx4_mr_cache entry;
358 
359 		memset(&entry, 0, sizeof(entry));
360 		/* Find a contiguous chunk and advance the index. */
361 		n = mr_find_next_chunk(mr, &entry, n);
362 		if (!entry.end)
363 			break;
364 		if (mr_btree_insert(&priv->mr.cache, &entry) < 0) {
365 			/*
366 			 * Overflowed, but the global table cannot be expanded
367 			 * because of deadlock.
368 			 */
369 			return -1;
370 		}
371 	}
372 	return 0;
373 }
374 
375 /**
376  * Look up address in the original global MR list.
377  *
378  * @param dev
379  *   Pointer to Ethernet device.
380  * @param[out] entry
381  *   Pointer to returning MR cache entry. If no match, this will not be updated.
382  * @param addr
383  *   Search key.
384  *
385  * @return
386  *   Found MR on match, NULL otherwise.
387  */
388 static struct mlx4_mr *
389 mr_lookup_dev_list(struct rte_eth_dev *dev, struct mlx4_mr_cache *entry,
390 		   uintptr_t addr)
391 {
392 	struct mlx4_priv *priv = dev->data->dev_private;
393 	struct mlx4_mr *mr;
394 
395 	/* Iterate all the existing MRs. */
396 	LIST_FOREACH(mr, &priv->mr.mr_list, mr) {
397 		unsigned int n;
398 
399 		if (mr->ms_n == 0)
400 			continue;
401 		for (n = 0; n < mr->ms_bmp_n; ) {
402 			struct mlx4_mr_cache ret;
403 
404 			memset(&ret, 0, sizeof(ret));
405 			n = mr_find_next_chunk(mr, &ret, n);
406 			if (addr >= ret.start && addr < ret.end) {
407 				/* Found. */
408 				*entry = ret;
409 				return mr;
410 			}
411 		}
412 	}
413 	return NULL;
414 }
415 
416 /**
417  * Look up address on device.
418  *
419  * @param dev
420  *   Pointer to Ethernet device.
421  * @param[out] entry
422  *   Pointer to returning MR cache entry. If no match, this will not be updated.
423  * @param addr
424  *   Search key.
425  *
426  * @return
427  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
428  */
429 static uint32_t
430 mr_lookup_dev(struct rte_eth_dev *dev, struct mlx4_mr_cache *entry,
431 	      uintptr_t addr)
432 {
433 	struct mlx4_priv *priv = dev->data->dev_private;
434 	uint16_t idx;
435 	uint32_t lkey = UINT32_MAX;
436 	struct mlx4_mr *mr;
437 
438 	/*
439 	 * If the global cache has overflowed since it failed to expand the
440 	 * B-tree table, it can't have all the existing MRs. Then, the address
441 	 * has to be searched by traversing the original MR list instead, which
442 	 * is very slow path. Otherwise, the global cache is all inclusive.
443 	 */
444 	if (!unlikely(priv->mr.cache.overflow)) {
445 		lkey = mr_btree_lookup(&priv->mr.cache, &idx, addr);
446 		if (lkey != UINT32_MAX)
447 			*entry = (*priv->mr.cache.table)[idx];
448 	} else {
449 		/* Falling back to the slowest path. */
450 		mr = mr_lookup_dev_list(dev, entry, addr);
451 		if (mr != NULL)
452 			lkey = entry->lkey;
453 	}
454 	assert(lkey == UINT32_MAX || (addr >= entry->start &&
455 				      addr < entry->end));
456 	return lkey;
457 }
458 
459 /**
460  * Free MR resources. MR lock must not be held to avoid a deadlock. rte_free()
461  * can raise memory free event and the callback function will spin on the lock.
462  *
463  * @param mr
464  *   Pointer to MR to free.
465  */
466 static void
467 mr_free(struct mlx4_mr *mr)
468 {
469 	if (mr == NULL)
470 		return;
471 	DEBUG("freeing MR(%p):", (void *)mr);
472 	if (mr->ibv_mr != NULL)
473 		claim_zero(mlx4_glue->dereg_mr(mr->ibv_mr));
474 	if (mr->ms_bmp != NULL)
475 		rte_bitmap_free(mr->ms_bmp);
476 	rte_free(mr);
477 }
478 
479 /**
480  * Release resources of detached MR having no online entry.
481  *
482  * @param dev
483  *   Pointer to Ethernet device.
484  */
485 static void
486 mlx4_mr_garbage_collect(struct rte_eth_dev *dev)
487 {
488 	struct mlx4_priv *priv = dev->data->dev_private;
489 	struct mlx4_mr *mr_next;
490 	struct mlx4_mr_list free_list = LIST_HEAD_INITIALIZER(free_list);
491 
492 	/*
493 	 * MR can't be freed with holding the lock because rte_free() could call
494 	 * memory free callback function. This will be a deadlock situation.
495 	 */
496 	rte_rwlock_write_lock(&priv->mr.rwlock);
497 	/* Detach the whole free list and release it after unlocking. */
498 	free_list = priv->mr.mr_free_list;
499 	LIST_INIT(&priv->mr.mr_free_list);
500 	rte_rwlock_write_unlock(&priv->mr.rwlock);
501 	/* Release resources. */
502 	mr_next = LIST_FIRST(&free_list);
503 	while (mr_next != NULL) {
504 		struct mlx4_mr *mr = mr_next;
505 
506 		mr_next = LIST_NEXT(mr, mr);
507 		mr_free(mr);
508 	}
509 }
510 
511 /* Called during rte_memseg_contig_walk() by mlx4_mr_create(). */
512 static int
513 mr_find_contig_memsegs_cb(const struct rte_memseg_list *msl,
514 			  const struct rte_memseg *ms, size_t len, void *arg)
515 {
516 	struct mr_find_contig_memsegs_data *data = arg;
517 
518 	if (data->addr < ms->addr_64 || data->addr >= ms->addr_64 + len)
519 		return 0;
520 	/* Found, save it and stop walking. */
521 	data->start = ms->addr_64;
522 	data->end = ms->addr_64 + len;
523 	data->msl = msl;
524 	return 1;
525 }
526 
527 /**
528  * Create a new global Memory Region (MR) for a missing virtual address.
529  * Register entire virtually contiguous memory chunk around the address.
530  *
531  * @param dev
532  *   Pointer to Ethernet device.
533  * @param[out] entry
534  *   Pointer to returning MR cache entry, found in the global cache or newly
535  *   created. If failed to create one, this will not be updated.
536  * @param addr
537  *   Target virtual address to register.
538  *
539  * @return
540  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
541  */
542 static uint32_t
543 mlx4_mr_create(struct rte_eth_dev *dev, struct mlx4_mr_cache *entry,
544 	       uintptr_t addr)
545 {
546 	struct mlx4_priv *priv = dev->data->dev_private;
547 	struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
548 	const struct rte_memseg_list *msl;
549 	const struct rte_memseg *ms;
550 	struct mlx4_mr *mr = NULL;
551 	size_t len;
552 	uint32_t ms_n;
553 	uint32_t bmp_size;
554 	void *bmp_mem;
555 	int ms_idx_shift = -1;
556 	unsigned int n;
557 	struct mr_find_contig_memsegs_data data = {
558 		.addr = addr,
559 	};
560 	struct mr_find_contig_memsegs_data data_re;
561 
562 	DEBUG("port %u creating a MR using address (%p)",
563 	      dev->data->port_id, (void *)addr);
564 	/*
565 	 * Release detached MRs if any. This can't be called with holding either
566 	 * memory_hotplug_lock or priv->mr.rwlock. MRs on the free list have
567 	 * been detached by the memory free event but it couldn't be released
568 	 * inside the callback due to deadlock. As a result, releasing resources
569 	 * is quite opportunistic.
570 	 */
571 	mlx4_mr_garbage_collect(dev);
572 	/*
573 	 * Find out a contiguous virtual address chunk in use, to which the
574 	 * given address belongs, in order to register maximum range. In the
575 	 * best case where mempools are not dynamically recreated and
576 	 * '--socket-mem' is specified as an EAL option, it is very likely to
577 	 * have only one MR(LKey) per a socket and per a hugepage-size even
578 	 * though the system memory is highly fragmented.
579 	 */
580 	if (!rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data)) {
581 		WARN("port %u unable to find virtually contiguous"
582 		     " chunk for address (%p)."
583 		     " rte_memseg_contig_walk() failed.",
584 		     dev->data->port_id, (void *)addr);
585 		rte_errno = ENXIO;
586 		goto err_nolock;
587 	}
588 alloc_resources:
589 	/* Addresses must be page-aligned. */
590 	assert(rte_is_aligned((void *)data.start, data.msl->page_sz));
591 	assert(rte_is_aligned((void *)data.end, data.msl->page_sz));
592 	msl = data.msl;
593 	ms = rte_mem_virt2memseg((void *)data.start, msl);
594 	len = data.end - data.start;
595 	assert(msl->page_sz == ms->hugepage_sz);
596 	/* Number of memsegs in the range. */
597 	ms_n = len / msl->page_sz;
598 	DEBUG("port %u extending %p to [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
599 	      " page_sz=0x%" PRIx64 ", ms_n=%u",
600 	      dev->data->port_id, (void *)addr,
601 	      data.start, data.end, msl->page_sz, ms_n);
602 	/* Size of memory for bitmap. */
603 	bmp_size = rte_bitmap_get_memory_footprint(ms_n);
604 	mr = rte_zmalloc_socket(NULL,
605 				RTE_ALIGN_CEIL(sizeof(*mr),
606 					       RTE_CACHE_LINE_SIZE) +
607 				bmp_size,
608 				RTE_CACHE_LINE_SIZE, msl->socket_id);
609 	if (mr == NULL) {
610 		WARN("port %u unable to allocate memory for a new MR of"
611 		     " address (%p).",
612 		     dev->data->port_id, (void *)addr);
613 		rte_errno = ENOMEM;
614 		goto err_nolock;
615 	}
616 	mr->msl = msl;
617 	/*
618 	 * Save the index of the first memseg and initialize memseg bitmap. To
619 	 * see if a memseg of ms_idx in the memseg-list is still valid, check:
620 	 *	rte_bitmap_get(mr->bmp, ms_idx - mr->ms_base_idx)
621 	 */
622 	mr->ms_base_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
623 	bmp_mem = RTE_PTR_ALIGN_CEIL(mr + 1, RTE_CACHE_LINE_SIZE);
624 	mr->ms_bmp = rte_bitmap_init(ms_n, bmp_mem, bmp_size);
625 	if (mr->ms_bmp == NULL) {
626 		WARN("port %u unable to initialize bitmap for a new MR of"
627 		     " address (%p).",
628 		     dev->data->port_id, (void *)addr);
629 		rte_errno = EINVAL;
630 		goto err_nolock;
631 	}
632 	/*
633 	 * Should recheck whether the extended contiguous chunk is still valid.
634 	 * Because memory_hotplug_lock can't be held if there's any memory
635 	 * related calls in a critical path, resource allocation above can't be
636 	 * locked. If the memory has been changed at this point, try again with
637 	 * just single page. If not, go on with the big chunk atomically from
638 	 * here.
639 	 */
640 	rte_rwlock_read_lock(&mcfg->memory_hotplug_lock);
641 	data_re = data;
642 	if (len > msl->page_sz &&
643 	    !rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data_re)) {
644 		WARN("port %u unable to find virtually contiguous"
645 		     " chunk for address (%p)."
646 		     " rte_memseg_contig_walk() failed.",
647 		     dev->data->port_id, (void *)addr);
648 		rte_errno = ENXIO;
649 		goto err_memlock;
650 	}
651 	if (data.start != data_re.start || data.end != data_re.end) {
652 		/*
653 		 * The extended contiguous chunk has been changed. Try again
654 		 * with single memseg instead.
655 		 */
656 		data.start = RTE_ALIGN_FLOOR(addr, msl->page_sz);
657 		data.end = data.start + msl->page_sz;
658 		rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
659 		mr_free(mr);
660 		goto alloc_resources;
661 	}
662 	assert(data.msl == data_re.msl);
663 	rte_rwlock_write_lock(&priv->mr.rwlock);
664 	/*
665 	 * Check the address is really missing. If other thread already created
666 	 * one or it is not found due to overflow, abort and return.
667 	 */
668 	if (mr_lookup_dev(dev, entry, addr) != UINT32_MAX) {
669 		/*
670 		 * Insert to the global cache table. It may fail due to
671 		 * low-on-memory. Then, this entry will have to be searched
672 		 * here again.
673 		 */
674 		mr_btree_insert(&priv->mr.cache, entry);
675 		DEBUG("port %u found MR for %p on final lookup, abort",
676 		      dev->data->port_id, (void *)addr);
677 		rte_rwlock_write_unlock(&priv->mr.rwlock);
678 		rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
679 		/*
680 		 * Must be unlocked before calling rte_free() because
681 		 * mlx4_mr_mem_event_free_cb() can be called inside.
682 		 */
683 		mr_free(mr);
684 		return entry->lkey;
685 	}
686 	/*
687 	 * Trim start and end addresses for verbs MR. Set bits for registering
688 	 * memsegs but exclude already registered ones. Bitmap can be
689 	 * fragmented.
690 	 */
691 	for (n = 0; n < ms_n; ++n) {
692 		uintptr_t start;
693 		struct mlx4_mr_cache ret;
694 
695 		memset(&ret, 0, sizeof(ret));
696 		start = data_re.start + n * msl->page_sz;
697 		/* Exclude memsegs already registered by other MRs. */
698 		if (mr_lookup_dev(dev, &ret, start) == UINT32_MAX) {
699 			/*
700 			 * Start from the first unregistered memseg in the
701 			 * extended range.
702 			 */
703 			if (ms_idx_shift == -1) {
704 				mr->ms_base_idx += n;
705 				data.start = start;
706 				ms_idx_shift = n;
707 			}
708 			data.end = start + msl->page_sz;
709 			rte_bitmap_set(mr->ms_bmp, n - ms_idx_shift);
710 			++mr->ms_n;
711 		}
712 	}
713 	len = data.end - data.start;
714 	mr->ms_bmp_n = len / msl->page_sz;
715 	assert(ms_idx_shift + mr->ms_bmp_n <= ms_n);
716 	/*
717 	 * Finally create a verbs MR for the memory chunk. ibv_reg_mr() can be
718 	 * called with holding the memory lock because it doesn't use
719 	 * mlx4_alloc_buf_extern() which eventually calls rte_malloc_socket()
720 	 * through mlx4_alloc_verbs_buf().
721 	 */
722 	mr->ibv_mr = mlx4_glue->reg_mr(priv->pd, (void *)data.start, len,
723 				       IBV_ACCESS_LOCAL_WRITE);
724 	if (mr->ibv_mr == NULL) {
725 		WARN("port %u fail to create a verbs MR for address (%p)",
726 		     dev->data->port_id, (void *)addr);
727 		rte_errno = EINVAL;
728 		goto err_mrlock;
729 	}
730 	assert((uintptr_t)mr->ibv_mr->addr == data.start);
731 	assert(mr->ibv_mr->length == len);
732 	LIST_INSERT_HEAD(&priv->mr.mr_list, mr, mr);
733 	DEBUG("port %u MR CREATED (%p) for %p:\n"
734 	      "  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
735 	      " lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
736 	      dev->data->port_id, (void *)mr, (void *)addr,
737 	      data.start, data.end, rte_cpu_to_be_32(mr->ibv_mr->lkey),
738 	      mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
739 	/* Insert to the global cache table. */
740 	mr_insert_dev_cache(dev, mr);
741 	/* Fill in output data. */
742 	mr_lookup_dev(dev, entry, addr);
743 	/* Lookup can't fail. */
744 	assert(entry->lkey != UINT32_MAX);
745 	rte_rwlock_write_unlock(&priv->mr.rwlock);
746 	rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
747 	return entry->lkey;
748 err_mrlock:
749 	rte_rwlock_write_unlock(&priv->mr.rwlock);
750 err_memlock:
751 	rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
752 err_nolock:
753 	/*
754 	 * In case of error, as this can be called in a datapath, a warning
755 	 * message per an error is preferable instead. Must be unlocked before
756 	 * calling rte_free() because mlx4_mr_mem_event_free_cb() can be called
757 	 * inside.
758 	 */
759 	mr_free(mr);
760 	return UINT32_MAX;
761 }
762 
763 /**
764  * Rebuild the global B-tree cache of device from the original MR list.
765  *
766  * @param dev
767  *   Pointer to Ethernet device.
768  */
769 static void
770 mr_rebuild_dev_cache(struct rte_eth_dev *dev)
771 {
772 	struct mlx4_priv *priv = dev->data->dev_private;
773 	struct mlx4_mr *mr;
774 
775 	DEBUG("port %u rebuild dev cache[]", dev->data->port_id);
776 	/* Flush cache to rebuild. */
777 	priv->mr.cache.len = 1;
778 	priv->mr.cache.overflow = 0;
779 	/* Iterate all the existing MRs. */
780 	LIST_FOREACH(mr, &priv->mr.mr_list, mr)
781 		if (mr_insert_dev_cache(dev, mr) < 0)
782 			return;
783 }
784 
785 /**
786  * Callback for memory free event. Iterate freed memsegs and check whether it
787  * belongs to an existing MR. If found, clear the bit from bitmap of MR. As a
788  * result, the MR would be fragmented. If it becomes empty, the MR will be freed
789  * later by mlx4_mr_garbage_collect().
790  *
791  * The global cache must be rebuilt if there's any change and this event has to
792  * be propagated to dataplane threads to flush the local caches.
793  *
794  * @param dev
795  *   Pointer to Ethernet device.
796  * @param addr
797  *   Address of freed memory.
798  * @param len
799  *   Size of freed memory.
800  */
801 static void
802 mlx4_mr_mem_event_free_cb(struct rte_eth_dev *dev, const void *addr, size_t len)
803 {
804 	struct mlx4_priv *priv = dev->data->dev_private;
805 	const struct rte_memseg_list *msl;
806 	struct mlx4_mr *mr;
807 	int ms_n;
808 	int i;
809 	int rebuild = 0;
810 
811 	DEBUG("port %u free callback: addr=%p, len=%zu",
812 	      dev->data->port_id, addr, len);
813 	msl = rte_mem_virt2memseg_list(addr);
814 	/* addr and len must be page-aligned. */
815 	assert((uintptr_t)addr == RTE_ALIGN((uintptr_t)addr, msl->page_sz));
816 	assert(len == RTE_ALIGN(len, msl->page_sz));
817 	ms_n = len / msl->page_sz;
818 	rte_rwlock_write_lock(&priv->mr.rwlock);
819 	/* Clear bits of freed memsegs from MR. */
820 	for (i = 0; i < ms_n; ++i) {
821 		const struct rte_memseg *ms;
822 		struct mlx4_mr_cache entry;
823 		uintptr_t start;
824 		int ms_idx;
825 		uint32_t pos;
826 
827 		/* Find MR having this memseg. */
828 		start = (uintptr_t)addr + i * msl->page_sz;
829 		mr = mr_lookup_dev_list(dev, &entry, start);
830 		if (mr == NULL)
831 			continue;
832 		assert(mr->msl); /* Can't be external memory. */
833 		ms = rte_mem_virt2memseg((void *)start, msl);
834 		assert(ms != NULL);
835 		assert(msl->page_sz == ms->hugepage_sz);
836 		ms_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
837 		pos = ms_idx - mr->ms_base_idx;
838 		assert(rte_bitmap_get(mr->ms_bmp, pos));
839 		assert(pos < mr->ms_bmp_n);
840 		DEBUG("port %u MR(%p): clear bitmap[%u] for addr %p",
841 		      dev->data->port_id, (void *)mr, pos, (void *)start);
842 		rte_bitmap_clear(mr->ms_bmp, pos);
843 		if (--mr->ms_n == 0) {
844 			LIST_REMOVE(mr, mr);
845 			LIST_INSERT_HEAD(&priv->mr.mr_free_list, mr, mr);
846 			DEBUG("port %u remove MR(%p) from list",
847 			      dev->data->port_id, (void *)mr);
848 		}
849 		/*
850 		 * MR is fragmented or will be freed. the global cache must be
851 		 * rebuilt.
852 		 */
853 		rebuild = 1;
854 	}
855 	if (rebuild) {
856 		mr_rebuild_dev_cache(dev);
857 		/*
858 		 * Flush local caches by propagating invalidation across cores.
859 		 * rte_smp_wmb() is enough to synchronize this event. If one of
860 		 * freed memsegs is seen by other core, that means the memseg
861 		 * has been allocated by allocator, which will come after this
862 		 * free call. Therefore, this store instruction (incrementing
863 		 * generation below) will be guaranteed to be seen by other core
864 		 * before the core sees the newly allocated memory.
865 		 */
866 		++priv->mr.dev_gen;
867 		DEBUG("broadcasting local cache flush, gen=%d",
868 		      priv->mr.dev_gen);
869 		rte_smp_wmb();
870 	}
871 	rte_rwlock_write_unlock(&priv->mr.rwlock);
872 #ifndef NDEBUG
873 	if (rebuild)
874 		mlx4_mr_dump_dev(dev);
875 #endif
876 }
877 
878 /**
879  * Callback for memory event.
880  *
881  * @param event_type
882  *   Memory event type.
883  * @param addr
884  *   Address of memory.
885  * @param len
886  *   Size of memory.
887  */
888 void
889 mlx4_mr_mem_event_cb(enum rte_mem_event event_type, const void *addr,
890 		     size_t len, void *arg __rte_unused)
891 {
892 	struct mlx4_priv *priv;
893 
894 	switch (event_type) {
895 	case RTE_MEM_EVENT_FREE:
896 		rte_rwlock_read_lock(&mlx4_mem_event_rwlock);
897 		/* Iterate all the existing mlx4 devices. */
898 		LIST_FOREACH(priv, &mlx4_mem_event_cb_list, mem_event_cb)
899 			mlx4_mr_mem_event_free_cb(ETH_DEV(priv), addr, len);
900 		rte_rwlock_read_unlock(&mlx4_mem_event_rwlock);
901 		break;
902 	case RTE_MEM_EVENT_ALLOC:
903 	default:
904 		break;
905 	}
906 }
907 
908 /**
909  * Look up address in the global MR cache table. If not found, create a new MR.
910  * Insert the found/created entry to local bottom-half cache table.
911  *
912  * @param dev
913  *   Pointer to Ethernet device.
914  * @param mr_ctrl
915  *   Pointer to per-queue MR control structure.
916  * @param[out] entry
917  *   Pointer to returning MR cache entry, found in the global cache or newly
918  *   created. If failed to create one, this is not written.
919  * @param addr
920  *   Search key.
921  *
922  * @return
923  *   Searched LKey on success, UINT32_MAX on no match.
924  */
925 static uint32_t
926 mlx4_mr_lookup_dev(struct rte_eth_dev *dev, struct mlx4_mr_ctrl *mr_ctrl,
927 		   struct mlx4_mr_cache *entry, uintptr_t addr)
928 {
929 	struct mlx4_priv *priv = dev->data->dev_private;
930 	struct mlx4_mr_btree *bt = &mr_ctrl->cache_bh;
931 	uint16_t idx;
932 	uint32_t lkey;
933 
934 	/* If local cache table is full, try to double it. */
935 	if (unlikely(bt->len == bt->size))
936 		mr_btree_expand(bt, bt->size << 1);
937 	/* Look up in the global cache. */
938 	rte_rwlock_read_lock(&priv->mr.rwlock);
939 	lkey = mr_btree_lookup(&priv->mr.cache, &idx, addr);
940 	if (lkey != UINT32_MAX) {
941 		/* Found. */
942 		*entry = (*priv->mr.cache.table)[idx];
943 		rte_rwlock_read_unlock(&priv->mr.rwlock);
944 		/*
945 		 * Update local cache. Even if it fails, return the found entry
946 		 * to update top-half cache. Next time, this entry will be found
947 		 * in the global cache.
948 		 */
949 		mr_btree_insert(bt, entry);
950 		return lkey;
951 	}
952 	rte_rwlock_read_unlock(&priv->mr.rwlock);
953 	/* First time to see the address? Create a new MR. */
954 	lkey = mlx4_mr_create(dev, entry, addr);
955 	/*
956 	 * Update the local cache if successfully created a new global MR. Even
957 	 * if failed to create one, there's no action to take in this datapath
958 	 * code. As returning LKey is invalid, this will eventually make HW
959 	 * fail.
960 	 */
961 	if (lkey != UINT32_MAX)
962 		mr_btree_insert(bt, entry);
963 	return lkey;
964 }
965 
966 /**
967  * Bottom-half of LKey search on datapath. Firstly search in cache_bh[] and if
968  * misses, search in the global MR cache table and update the new entry to
969  * per-queue local caches.
970  *
971  * @param dev
972  *   Pointer to Ethernet device.
973  * @param mr_ctrl
974  *   Pointer to per-queue MR control structure.
975  * @param addr
976  *   Search key.
977  *
978  * @return
979  *   Searched LKey on success, UINT32_MAX on no match.
980  */
981 static uint32_t
982 mlx4_mr_addr2mr_bh(struct rte_eth_dev *dev, struct mlx4_mr_ctrl *mr_ctrl,
983 		   uintptr_t addr)
984 {
985 	uint32_t lkey;
986 	uint16_t bh_idx = 0;
987 	/* Victim in top-half cache to replace with new entry. */
988 	struct mlx4_mr_cache *repl = &mr_ctrl->cache[mr_ctrl->head];
989 
990 	/* Binary-search MR translation table. */
991 	lkey = mr_btree_lookup(&mr_ctrl->cache_bh, &bh_idx, addr);
992 	/* Update top-half cache. */
993 	if (likely(lkey != UINT32_MAX)) {
994 		*repl = (*mr_ctrl->cache_bh.table)[bh_idx];
995 	} else {
996 		/*
997 		 * If missed in local lookup table, search in the global cache
998 		 * and local cache_bh[] will be updated inside if possible.
999 		 * Top-half cache entry will also be updated.
1000 		 */
1001 		lkey = mlx4_mr_lookup_dev(dev, mr_ctrl, repl, addr);
1002 		if (unlikely(lkey == UINT32_MAX))
1003 			return UINT32_MAX;
1004 	}
1005 	/* Update the most recently used entry. */
1006 	mr_ctrl->mru = mr_ctrl->head;
1007 	/* Point to the next victim, the oldest. */
1008 	mr_ctrl->head = (mr_ctrl->head + 1) % MLX4_MR_CACHE_N;
1009 	return lkey;
1010 }
1011 
1012 /**
1013  * Bottom-half of LKey search on Rx.
1014  *
1015  * @param rxq
1016  *   Pointer to Rx queue structure.
1017  * @param addr
1018  *   Search key.
1019  *
1020  * @return
1021  *   Searched LKey on success, UINT32_MAX on no match.
1022  */
1023 uint32_t
1024 mlx4_rx_addr2mr_bh(struct rxq *rxq, uintptr_t addr)
1025 {
1026 	struct mlx4_mr_ctrl *mr_ctrl = &rxq->mr_ctrl;
1027 	struct mlx4_priv *priv = rxq->priv;
1028 
1029 	return mlx4_mr_addr2mr_bh(ETH_DEV(priv), mr_ctrl, addr);
1030 }
1031 
1032 /**
1033  * Bottom-half of LKey search on Tx.
1034  *
1035  * @param txq
1036  *   Pointer to Tx queue structure.
1037  * @param addr
1038  *   Search key.
1039  *
1040  * @return
1041  *   Searched LKey on success, UINT32_MAX on no match.
1042  */
1043 static uint32_t
1044 mlx4_tx_addr2mr_bh(struct txq *txq, uintptr_t addr)
1045 {
1046 	struct mlx4_mr_ctrl *mr_ctrl = &txq->mr_ctrl;
1047 	struct mlx4_priv *priv = txq->priv;
1048 
1049 	return mlx4_mr_addr2mr_bh(ETH_DEV(priv), mr_ctrl, addr);
1050 }
1051 
1052 /**
1053  * Bottom-half of LKey search on Tx. If it can't be searched in the memseg
1054  * list, register the mempool of the mbuf as externally allocated memory.
1055  *
1056  * @param txq
1057  *   Pointer to Tx queue structure.
1058  * @param mb
1059  *   Pointer to mbuf.
1060  *
1061  * @return
1062  *   Searched LKey on success, UINT32_MAX on no match.
1063  */
1064 uint32_t
1065 mlx4_tx_mb2mr_bh(struct txq *txq, struct rte_mbuf *mb)
1066 {
1067 	uintptr_t addr = (uintptr_t)mb->buf_addr;
1068 	uint32_t lkey;
1069 
1070 	lkey = mlx4_tx_addr2mr_bh(txq, addr);
1071 	if (lkey == UINT32_MAX && rte_errno == ENXIO) {
1072 		/* Mempool may have externally allocated memory. */
1073 		return mlx4_tx_update_ext_mp(txq, addr, mlx4_mb2mp(mb));
1074 	}
1075 	return lkey;
1076 }
1077 
1078 /**
1079  * Flush all of the local cache entries.
1080  *
1081  * @param mr_ctrl
1082  *   Pointer to per-queue MR control structure.
1083  */
1084 void
1085 mlx4_mr_flush_local_cache(struct mlx4_mr_ctrl *mr_ctrl)
1086 {
1087 	/* Reset the most-recently-used index. */
1088 	mr_ctrl->mru = 0;
1089 	/* Reset the linear search array. */
1090 	mr_ctrl->head = 0;
1091 	memset(mr_ctrl->cache, 0, sizeof(mr_ctrl->cache));
1092 	/* Reset the B-tree table. */
1093 	mr_ctrl->cache_bh.len = 1;
1094 	mr_ctrl->cache_bh.overflow = 0;
1095 	/* Update the generation number. */
1096 	mr_ctrl->cur_gen = *mr_ctrl->dev_gen_ptr;
1097 	DEBUG("mr_ctrl(%p): flushed, cur_gen=%d",
1098 	      (void *)mr_ctrl, mr_ctrl->cur_gen);
1099 }
1100 
1101 /**
1102  * Called during rte_mempool_mem_iter() by mlx4_mr_update_ext_mp().
1103  *
1104  * Externally allocated chunk is registered and a MR is created for the chunk.
1105  * The MR object is added to the global list. If memseg list of a MR object
1106  * (mr->msl) is null, the MR object can be regarded as externally allocated
1107  * memory.
1108  *
1109  * Once external memory is registered, it should be static. If the memory is
1110  * freed and the virtual address range has different physical memory mapped
1111  * again, it may cause crash on device due to the wrong translation entry. PMD
1112  * can't track the free event of the external memory for now.
1113  */
1114 static void
1115 mlx4_mr_update_ext_mp_cb(struct rte_mempool *mp, void *opaque,
1116 			 struct rte_mempool_memhdr *memhdr,
1117 			 unsigned mem_idx __rte_unused)
1118 {
1119 	struct mr_update_mp_data *data = opaque;
1120 	struct rte_eth_dev *dev = data->dev;
1121 	struct mlx4_priv *priv = dev->data->dev_private;
1122 	struct mlx4_mr_ctrl *mr_ctrl = data->mr_ctrl;
1123 	struct mlx4_mr *mr = NULL;
1124 	uintptr_t addr = (uintptr_t)memhdr->addr;
1125 	size_t len = memhdr->len;
1126 	struct mlx4_mr_cache entry;
1127 	uint32_t lkey;
1128 
1129 	/* If already registered, it should return. */
1130 	rte_rwlock_read_lock(&priv->mr.rwlock);
1131 	lkey = mr_lookup_dev(dev, &entry, addr);
1132 	rte_rwlock_read_unlock(&priv->mr.rwlock);
1133 	if (lkey != UINT32_MAX)
1134 		return;
1135 	mr = rte_zmalloc_socket(NULL,
1136 				RTE_ALIGN_CEIL(sizeof(*mr),
1137 					       RTE_CACHE_LINE_SIZE),
1138 				RTE_CACHE_LINE_SIZE, mp->socket_id);
1139 	if (mr == NULL) {
1140 		WARN("port %u unable to allocate memory for a new MR of"
1141 		     " mempool (%s).",
1142 		     dev->data->port_id, mp->name);
1143 		data->ret = -1;
1144 		return;
1145 	}
1146 	DEBUG("port %u register MR for chunk #%d of mempool (%s)",
1147 	      dev->data->port_id, mem_idx, mp->name);
1148 	mr->ibv_mr = mlx4_glue->reg_mr(priv->pd, (void *)addr, len,
1149 				       IBV_ACCESS_LOCAL_WRITE);
1150 	if (mr->ibv_mr == NULL) {
1151 		WARN("port %u fail to create a verbs MR for address (%p)",
1152 		     dev->data->port_id, (void *)addr);
1153 		rte_free(mr);
1154 		data->ret = -1;
1155 		return;
1156 	}
1157 	mr->msl = NULL; /* Mark it is external memory. */
1158 	mr->ms_bmp = NULL;
1159 	mr->ms_n = 1;
1160 	mr->ms_bmp_n = 1;
1161 	rte_rwlock_write_lock(&priv->mr.rwlock);
1162 	LIST_INSERT_HEAD(&priv->mr.mr_list, mr, mr);
1163 	DEBUG("port %u MR CREATED (%p) for external memory %p:\n"
1164 	      "  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
1165 	      " lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
1166 	      dev->data->port_id, (void *)mr, (void *)addr,
1167 	      addr, addr + len, rte_cpu_to_be_32(mr->ibv_mr->lkey),
1168 	      mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
1169 	/* Insert to the global cache table. */
1170 	mr_insert_dev_cache(dev, mr);
1171 	rte_rwlock_write_unlock(&priv->mr.rwlock);
1172 	/* Insert to the local cache table */
1173 	mlx4_mr_addr2mr_bh(dev, mr_ctrl, addr);
1174 }
1175 
1176 /**
1177  * Register MR for entire memory chunks in a Mempool having externally allocated
1178  * memory and fill in local cache.
1179  *
1180  * @param dev
1181  *   Pointer to Ethernet device.
1182  * @param mr_ctrl
1183  *   Pointer to per-queue MR control structure.
1184  * @param mp
1185  *   Pointer to registering Mempool.
1186  *
1187  * @return
1188  *   0 on success, -1 on failure.
1189  */
1190 static uint32_t
1191 mlx4_mr_update_ext_mp(struct rte_eth_dev *dev, struct mlx4_mr_ctrl *mr_ctrl,
1192 		      struct rte_mempool *mp)
1193 {
1194 	struct mr_update_mp_data data = {
1195 		.dev = dev,
1196 		.mr_ctrl = mr_ctrl,
1197 		.ret = 0,
1198 	};
1199 
1200 	rte_mempool_mem_iter(mp, mlx4_mr_update_ext_mp_cb, &data);
1201 	return data.ret;
1202 }
1203 
1204 /**
1205  * Register MR entire memory chunks in a Mempool having externally allocated
1206  * memory and search LKey of the address to return.
1207  *
1208  * @param dev
1209  *   Pointer to Ethernet device.
1210  * @param addr
1211  *   Search key.
1212  * @param mp
1213  *   Pointer to registering Mempool where addr belongs.
1214  *
1215  * @return
1216  *   LKey for address on success, UINT32_MAX on failure.
1217  */
1218 uint32_t
1219 mlx4_tx_update_ext_mp(struct txq *txq, uintptr_t addr, struct rte_mempool *mp)
1220 {
1221 	struct mlx4_mr_ctrl *mr_ctrl = &txq->mr_ctrl;
1222 	struct mlx4_priv *priv = txq->priv;
1223 
1224 	mlx4_mr_update_ext_mp(ETH_DEV(priv), mr_ctrl, mp);
1225 	return mlx4_tx_addr2mr_bh(txq, addr);
1226 }
1227 
1228 /* Called during rte_mempool_mem_iter() by mlx4_mr_update_mp(). */
1229 static void
1230 mlx4_mr_update_mp_cb(struct rte_mempool *mp __rte_unused, void *opaque,
1231 		     struct rte_mempool_memhdr *memhdr,
1232 		     unsigned mem_idx __rte_unused)
1233 {
1234 	struct mr_update_mp_data *data = opaque;
1235 	uint32_t lkey;
1236 
1237 	/* Stop iteration if failed in the previous walk. */
1238 	if (data->ret < 0)
1239 		return;
1240 	/* Register address of the chunk and update local caches. */
1241 	lkey = mlx4_mr_addr2mr_bh(data->dev, data->mr_ctrl,
1242 				  (uintptr_t)memhdr->addr);
1243 	if (lkey == UINT32_MAX)
1244 		data->ret = -1;
1245 }
1246 
1247 /**
1248  * Register entire memory chunks in a Mempool.
1249  *
1250  * @param dev
1251  *   Pointer to Ethernet device.
1252  * @param mr_ctrl
1253  *   Pointer to per-queue MR control structure.
1254  * @param mp
1255  *   Pointer to registering Mempool.
1256  *
1257  * @return
1258  *   0 on success, -1 on failure.
1259  */
1260 int
1261 mlx4_mr_update_mp(struct rte_eth_dev *dev, struct mlx4_mr_ctrl *mr_ctrl,
1262 		  struct rte_mempool *mp)
1263 {
1264 	struct mr_update_mp_data data = {
1265 		.dev = dev,
1266 		.mr_ctrl = mr_ctrl,
1267 		.ret = 0,
1268 	};
1269 
1270 	rte_mempool_mem_iter(mp, mlx4_mr_update_mp_cb, &data);
1271 	if (data.ret < 0 && rte_errno == ENXIO) {
1272 		/* Mempool may have externally allocated memory. */
1273 		return mlx4_mr_update_ext_mp(dev, mr_ctrl, mp);
1274 	}
1275 	return data.ret;
1276 }
1277 
1278 #ifndef NDEBUG
1279 /**
1280  * Dump all the created MRs and the global cache entries.
1281  *
1282  * @param dev
1283  *   Pointer to Ethernet device.
1284  */
1285 void
1286 mlx4_mr_dump_dev(struct rte_eth_dev *dev)
1287 {
1288 	struct mlx4_priv *priv = dev->data->dev_private;
1289 	struct mlx4_mr *mr;
1290 	int mr_n = 0;
1291 	int chunk_n = 0;
1292 
1293 	rte_rwlock_read_lock(&priv->mr.rwlock);
1294 	/* Iterate all the existing MRs. */
1295 	LIST_FOREACH(mr, &priv->mr.mr_list, mr) {
1296 		unsigned int n;
1297 
1298 		DEBUG("port %u MR[%u], LKey = 0x%x, ms_n = %u, ms_bmp_n = %u",
1299 		      dev->data->port_id, mr_n++,
1300 		      rte_cpu_to_be_32(mr->ibv_mr->lkey),
1301 		      mr->ms_n, mr->ms_bmp_n);
1302 		if (mr->ms_n == 0)
1303 			continue;
1304 		for (n = 0; n < mr->ms_bmp_n; ) {
1305 			struct mlx4_mr_cache ret;
1306 
1307 			memset(&ret, 0, sizeof(ret));
1308 			n = mr_find_next_chunk(mr, &ret, n);
1309 			if (!ret.end)
1310 				break;
1311 			DEBUG("  chunk[%u], [0x%" PRIxPTR ", 0x%" PRIxPTR ")",
1312 			      chunk_n++, ret.start, ret.end);
1313 		}
1314 	}
1315 	DEBUG("port %u dumping global cache", dev->data->port_id);
1316 	mlx4_mr_btree_dump(&priv->mr.cache);
1317 	rte_rwlock_read_unlock(&priv->mr.rwlock);
1318 }
1319 #endif
1320 
1321 /**
1322  * Release all the created MRs and resources. Remove device from memory callback
1323  * list.
1324  *
1325  * @param dev
1326  *   Pointer to Ethernet device.
1327  */
1328 void
1329 mlx4_mr_release(struct rte_eth_dev *dev)
1330 {
1331 	struct mlx4_priv *priv = dev->data->dev_private;
1332 	struct mlx4_mr *mr_next;
1333 
1334 	/* Remove from memory callback device list. */
1335 	rte_rwlock_write_lock(&mlx4_mem_event_rwlock);
1336 	LIST_REMOVE(priv, mem_event_cb);
1337 	rte_rwlock_write_unlock(&mlx4_mem_event_rwlock);
1338 #ifndef NDEBUG
1339 	mlx4_mr_dump_dev(dev);
1340 #endif
1341 	rte_rwlock_write_lock(&priv->mr.rwlock);
1342 	/* Detach from MR list and move to free list. */
1343 	mr_next = LIST_FIRST(&priv->mr.mr_list);
1344 	while (mr_next != NULL) {
1345 		struct mlx4_mr *mr = mr_next;
1346 
1347 		mr_next = LIST_NEXT(mr, mr);
1348 		LIST_REMOVE(mr, mr);
1349 		LIST_INSERT_HEAD(&priv->mr.mr_free_list, mr, mr);
1350 	}
1351 	LIST_INIT(&priv->mr.mr_list);
1352 	/* Free global cache. */
1353 	mlx4_mr_btree_free(&priv->mr.cache);
1354 	rte_rwlock_write_unlock(&priv->mr.rwlock);
1355 	/* Free all remaining MRs. */
1356 	mlx4_mr_garbage_collect(dev);
1357 }
1358