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