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