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