872d0591eaa20ee38bce6f1be6bce27424320200
[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         const struct rte_memseg_list *msl;
584         const struct rte_memseg *ms;
585         struct mlx5_mr *mr = NULL;
586         size_t len;
587         uint32_t ms_n;
588         uint32_t bmp_size;
589         void *bmp_mem;
590         int ms_idx_shift = -1;
591         unsigned int n;
592         struct mr_find_contig_memsegs_data data = {
593                 .addr = addr,
594         };
595         struct mr_find_contig_memsegs_data data_re;
596
597         DRV_LOG(DEBUG, "port %u creating a MR using address (%p)",
598                 dev->data->port_id, (void *)addr);
599         /*
600          * Release detached MRs if any. This can't be called with holding either
601          * memory_hotplug_lock or sh->mr.rwlock. MRs on the free list have
602          * been detached by the memory free event but it couldn't be released
603          * inside the callback due to deadlock. As a result, releasing resources
604          * is quite opportunistic.
605          */
606         mlx5_mr_garbage_collect(sh);
607         /*
608          * If enabled, find out a contiguous virtual address chunk in use, to
609          * which the given address belongs, in order to register maximum range.
610          * In the best case where mempools are not dynamically recreated and
611          * '--socket-mem' is specified as an EAL option, it is very likely to
612          * have only one MR(LKey) per a socket and per a hugepage-size even
613          * though the system memory is highly fragmented. As the whole memory
614          * chunk will be pinned by kernel, it can't be reused unless entire
615          * chunk is freed from EAL.
616          *
617          * If disabled, just register one memseg (page). Then, memory
618          * consumption will be minimized but it may drop performance if there
619          * are many MRs to lookup on the datapath.
620          */
621         if (!config->mr_ext_memseg_en) {
622                 data.msl = rte_mem_virt2memseg_list((void *)addr);
623                 data.start = RTE_ALIGN_FLOOR(addr, data.msl->page_sz);
624                 data.end = data.start + data.msl->page_sz;
625         } else if (!rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data)) {
626                 DRV_LOG(WARNING,
627                         "port %u unable to find virtually contiguous"
628                         " chunk for address (%p)."
629                         " rte_memseg_contig_walk() failed.",
630                         dev->data->port_id, (void *)addr);
631                 rte_errno = ENXIO;
632                 goto err_nolock;
633         }
634 alloc_resources:
635         /* Addresses must be page-aligned. */
636         assert(rte_is_aligned((void *)data.start, data.msl->page_sz));
637         assert(rte_is_aligned((void *)data.end, data.msl->page_sz));
638         msl = data.msl;
639         ms = rte_mem_virt2memseg((void *)data.start, msl);
640         len = data.end - data.start;
641         assert(msl->page_sz == ms->hugepage_sz);
642         /* Number of memsegs in the range. */
643         ms_n = len / msl->page_sz;
644         DEBUG("port %u extending %p to [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
645               " page_sz=0x%" PRIx64 ", ms_n=%u",
646               dev->data->port_id, (void *)addr,
647               data.start, data.end, msl->page_sz, ms_n);
648         /* Size of memory for bitmap. */
649         bmp_size = rte_bitmap_get_memory_footprint(ms_n);
650         mr = rte_zmalloc_socket(NULL,
651                                 RTE_ALIGN_CEIL(sizeof(*mr),
652                                                RTE_CACHE_LINE_SIZE) +
653                                 bmp_size,
654                                 RTE_CACHE_LINE_SIZE, msl->socket_id);
655         if (mr == NULL) {
656                 DEBUG("port %u unable to allocate memory for a new MR of"
657                       " address (%p).",
658                       dev->data->port_id, (void *)addr);
659                 rte_errno = ENOMEM;
660                 goto err_nolock;
661         }
662         mr->msl = msl;
663         /*
664          * Save the index of the first memseg and initialize memseg bitmap. To
665          * see if a memseg of ms_idx in the memseg-list is still valid, check:
666          *      rte_bitmap_get(mr->bmp, ms_idx - mr->ms_base_idx)
667          */
668         mr->ms_base_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
669         bmp_mem = RTE_PTR_ALIGN_CEIL(mr + 1, RTE_CACHE_LINE_SIZE);
670         mr->ms_bmp = rte_bitmap_init(ms_n, bmp_mem, bmp_size);
671         if (mr->ms_bmp == NULL) {
672                 DEBUG("port %u unable to initialize bitmap for a new MR of"
673                       " address (%p).",
674                       dev->data->port_id, (void *)addr);
675                 rte_errno = EINVAL;
676                 goto err_nolock;
677         }
678         /*
679          * Should recheck whether the extended contiguous chunk is still valid.
680          * Because memory_hotplug_lock can't be held if there's any memory
681          * related calls in a critical path, resource allocation above can't be
682          * locked. If the memory has been changed at this point, try again with
683          * just single page. If not, go on with the big chunk atomically from
684          * here.
685          */
686         rte_mcfg_mem_read_lock();
687         data_re = data;
688         if (len > msl->page_sz &&
689             !rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data_re)) {
690                 DEBUG("port %u unable to find virtually contiguous"
691                       " chunk for address (%p)."
692                       " rte_memseg_contig_walk() failed.",
693                       dev->data->port_id, (void *)addr);
694                 rte_errno = ENXIO;
695                 goto err_memlock;
696         }
697         if (data.start != data_re.start || data.end != data_re.end) {
698                 /*
699                  * The extended contiguous chunk has been changed. Try again
700                  * with single memseg instead.
701                  */
702                 data.start = RTE_ALIGN_FLOOR(addr, msl->page_sz);
703                 data.end = data.start + msl->page_sz;
704                 rte_mcfg_mem_read_unlock();
705                 mr_free(mr);
706                 goto alloc_resources;
707         }
708         assert(data.msl == data_re.msl);
709         rte_rwlock_write_lock(&sh->mr.rwlock);
710         /*
711          * Check the address is really missing. If other thread already created
712          * one or it is not found due to overflow, abort and return.
713          */
714         if (mr_lookup_dev(sh, entry, addr) != UINT32_MAX) {
715                 /*
716                  * Insert to the global cache table. It may fail due to
717                  * low-on-memory. Then, this entry will have to be searched
718                  * here again.
719                  */
720                 mr_btree_insert(&sh->mr.cache, entry);
721                 DEBUG("port %u found MR for %p on final lookup, abort",
722                       dev->data->port_id, (void *)addr);
723                 rte_rwlock_write_unlock(&sh->mr.rwlock);
724                 rte_mcfg_mem_read_unlock();
725                 /*
726                  * Must be unlocked before calling rte_free() because
727                  * mlx5_mr_mem_event_free_cb() can be called inside.
728                  */
729                 mr_free(mr);
730                 return entry->lkey;
731         }
732         /*
733          * Trim start and end addresses for verbs MR. Set bits for registering
734          * memsegs but exclude already registered ones. Bitmap can be
735          * fragmented.
736          */
737         for (n = 0; n < ms_n; ++n) {
738                 uintptr_t start;
739                 struct mlx5_mr_cache ret;
740
741                 memset(&ret, 0, sizeof(ret));
742                 start = data_re.start + n * msl->page_sz;
743                 /* Exclude memsegs already registered by other MRs. */
744                 if (mr_lookup_dev(sh, &ret, start) == UINT32_MAX) {
745                         /*
746                          * Start from the first unregistered memseg in the
747                          * extended range.
748                          */
749                         if (ms_idx_shift == -1) {
750                                 mr->ms_base_idx += n;
751                                 data.start = start;
752                                 ms_idx_shift = n;
753                         }
754                         data.end = start + msl->page_sz;
755                         rte_bitmap_set(mr->ms_bmp, n - ms_idx_shift);
756                         ++mr->ms_n;
757                 }
758         }
759         len = data.end - data.start;
760         mr->ms_bmp_n = len / msl->page_sz;
761         assert(ms_idx_shift + mr->ms_bmp_n <= ms_n);
762         /*
763          * Finally create a verbs MR for the memory chunk. ibv_reg_mr() can be
764          * called with holding the memory lock because it doesn't use
765          * mlx5_alloc_buf_extern() which eventually calls rte_malloc_socket()
766          * through mlx5_alloc_verbs_buf().
767          */
768         mr->ibv_mr = mlx5_glue->reg_mr(sh->pd, (void *)data.start, len,
769                                        IBV_ACCESS_LOCAL_WRITE);
770         if (mr->ibv_mr == NULL) {
771                 DEBUG("port %u fail to create a verbs MR for address (%p)",
772                       dev->data->port_id, (void *)addr);
773                 rte_errno = EINVAL;
774                 goto err_mrlock;
775         }
776         assert((uintptr_t)mr->ibv_mr->addr == data.start);
777         assert(mr->ibv_mr->length == len);
778         LIST_INSERT_HEAD(&sh->mr.mr_list, mr, mr);
779         DEBUG("port %u MR CREATED (%p) for %p:\n"
780               "  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
781               " lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
782               dev->data->port_id, (void *)mr, (void *)addr,
783               data.start, data.end, rte_cpu_to_be_32(mr->ibv_mr->lkey),
784               mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
785         /* Insert to the global cache table. */
786         mr_insert_dev_cache(sh, mr);
787         /* Fill in output data. */
788         mr_lookup_dev(sh, entry, addr);
789         /* Lookup can't fail. */
790         assert(entry->lkey != UINT32_MAX);
791         rte_rwlock_write_unlock(&sh->mr.rwlock);
792         rte_mcfg_mem_read_unlock();
793         return entry->lkey;
794 err_mrlock:
795         rte_rwlock_write_unlock(&sh->mr.rwlock);
796 err_memlock:
797         rte_mcfg_mem_read_unlock();
798 err_nolock:
799         /*
800          * In case of error, as this can be called in a datapath, a warning
801          * message per an error is preferable instead. Must be unlocked before
802          * calling rte_free() because mlx5_mr_mem_event_free_cb() can be called
803          * inside.
804          */
805         mr_free(mr);
806         return UINT32_MAX;
807 }
808
809 /**
810  * Create a new global Memory Region (MR) for a missing virtual address.
811  * This can be called from primary and secondary process.
812  *
813  * @param dev
814  *   Pointer to Ethernet device.
815  * @param[out] entry
816  *   Pointer to returning MR cache entry, found in the global cache or newly
817  *   created. If failed to create one, this will not be updated.
818  * @param addr
819  *   Target virtual address to register.
820  *
821  * @return
822  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
823  */
824 static uint32_t
825 mlx5_mr_create(struct rte_eth_dev *dev, struct mlx5_mr_cache *entry,
826                uintptr_t addr)
827 {
828         uint32_t ret = 0;
829
830         switch (rte_eal_process_type()) {
831         case RTE_PROC_PRIMARY:
832                 ret = mlx5_mr_create_primary(dev, entry, addr);
833                 break;
834         case RTE_PROC_SECONDARY:
835                 ret = mlx5_mr_create_secondary(dev, entry, addr);
836                 break;
837         default:
838                 break;
839         }
840         return ret;
841 }
842
843 /**
844  * Rebuild the global B-tree cache of device from the original MR list.
845  *
846  * @param sh
847  *   Pointer to Ethernet device shared context.
848  */
849 static void
850 mr_rebuild_dev_cache(struct mlx5_ibv_shared *sh)
851 {
852         struct mlx5_mr *mr;
853
854         DRV_LOG(DEBUG, "device %s rebuild dev cache[]", sh->ibdev_name);
855         /* Flush cache to rebuild. */
856         sh->mr.cache.len = 1;
857         sh->mr.cache.overflow = 0;
858         /* Iterate all the existing MRs. */
859         LIST_FOREACH(mr, &sh->mr.mr_list, mr)
860                 if (mr_insert_dev_cache(sh, mr) < 0)
861                         return;
862 }
863
864 /**
865  * Callback for memory free event. Iterate freed memsegs and check whether it
866  * belongs to an existing MR. If found, clear the bit from bitmap of MR. As a
867  * result, the MR would be fragmented. If it becomes empty, the MR will be freed
868  * later by mlx5_mr_garbage_collect(). Even if this callback is called from a
869  * secondary process, the garbage collector will be called in primary process
870  * as the secondary process can't call mlx5_mr_create().
871  *
872  * The global cache must be rebuilt if there's any change and this event has to
873  * be propagated to dataplane threads to flush the local caches.
874  *
875  * @param sh
876  *   Pointer to the Ethernet device shared context.
877  * @param addr
878  *   Address of freed memory.
879  * @param len
880  *   Size of freed memory.
881  */
882 static void
883 mlx5_mr_mem_event_free_cb(struct mlx5_ibv_shared *sh,
884                           const void *addr, size_t len)
885 {
886         const struct rte_memseg_list *msl;
887         struct mlx5_mr *mr;
888         int ms_n;
889         int i;
890         int rebuild = 0;
891
892         DEBUG("device %s free callback: addr=%p, len=%zu",
893               sh->ibdev_name, addr, len);
894         msl = rte_mem_virt2memseg_list(addr);
895         /* addr and len must be page-aligned. */
896         assert((uintptr_t)addr == RTE_ALIGN((uintptr_t)addr, msl->page_sz));
897         assert(len == RTE_ALIGN(len, msl->page_sz));
898         ms_n = len / msl->page_sz;
899         rte_rwlock_write_lock(&sh->mr.rwlock);
900         /* Clear bits of freed memsegs from MR. */
901         for (i = 0; i < ms_n; ++i) {
902                 const struct rte_memseg *ms;
903                 struct mlx5_mr_cache entry;
904                 uintptr_t start;
905                 int ms_idx;
906                 uint32_t pos;
907
908                 /* Find MR having this memseg. */
909                 start = (uintptr_t)addr + i * msl->page_sz;
910                 mr = mr_lookup_dev_list(sh, &entry, start);
911                 if (mr == NULL)
912                         continue;
913                 assert(mr->msl); /* Can't be external memory. */
914                 ms = rte_mem_virt2memseg((void *)start, msl);
915                 assert(ms != NULL);
916                 assert(msl->page_sz == ms->hugepage_sz);
917                 ms_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
918                 pos = ms_idx - mr->ms_base_idx;
919                 assert(rte_bitmap_get(mr->ms_bmp, pos));
920                 assert(pos < mr->ms_bmp_n);
921                 DEBUG("device %s MR(%p): clear bitmap[%u] for addr %p",
922                       sh->ibdev_name, (void *)mr, pos, (void *)start);
923                 rte_bitmap_clear(mr->ms_bmp, pos);
924                 if (--mr->ms_n == 0) {
925                         LIST_REMOVE(mr, mr);
926                         LIST_INSERT_HEAD(&sh->mr.mr_free_list, mr, mr);
927                         DEBUG("device %s remove MR(%p) from list",
928                               sh->ibdev_name, (void *)mr);
929                 }
930                 /*
931                  * MR is fragmented or will be freed. the global cache must be
932                  * rebuilt.
933                  */
934                 rebuild = 1;
935         }
936         if (rebuild) {
937                 mr_rebuild_dev_cache(sh);
938                 /*
939                  * Flush local caches by propagating invalidation across cores.
940                  * rte_smp_wmb() is enough to synchronize this event. If one of
941                  * freed memsegs is seen by other core, that means the memseg
942                  * has been allocated by allocator, which will come after this
943                  * free call. Therefore, this store instruction (incrementing
944                  * generation below) will be guaranteed to be seen by other core
945                  * before the core sees the newly allocated memory.
946                  */
947                 ++sh->mr.dev_gen;
948                 DEBUG("broadcasting local cache flush, gen=%d",
949                       sh->mr.dev_gen);
950                 rte_smp_wmb();
951         }
952         rte_rwlock_write_unlock(&sh->mr.rwlock);
953 }
954
955 /**
956  * Callback for memory event. This can be called from both primary and secondary
957  * process.
958  *
959  * @param event_type
960  *   Memory event type.
961  * @param addr
962  *   Address of memory.
963  * @param len
964  *   Size of memory.
965  */
966 void
967 mlx5_mr_mem_event_cb(enum rte_mem_event event_type, const void *addr,
968                      size_t len, void *arg __rte_unused)
969 {
970         struct mlx5_ibv_shared *sh;
971         struct mlx5_dev_list *dev_list = &mlx5_shared_data->mem_event_cb_list;
972
973         /* Must be called from the primary process. */
974         assert(rte_eal_process_type() == RTE_PROC_PRIMARY);
975         switch (event_type) {
976         case RTE_MEM_EVENT_FREE:
977                 rte_rwlock_write_lock(&mlx5_shared_data->mem_event_rwlock);
978                 /* Iterate all the existing mlx5 devices. */
979                 LIST_FOREACH(sh, dev_list, mem_event_cb)
980                         mlx5_mr_mem_event_free_cb(sh, addr, len);
981                 rte_rwlock_write_unlock(&mlx5_shared_data->mem_event_rwlock);
982                 break;
983         case RTE_MEM_EVENT_ALLOC:
984         default:
985                 break;
986         }
987 }
988
989 /**
990  * Look up address in the global MR cache table. If not found, create a new MR.
991  * Insert the found/created entry to local bottom-half cache table.
992  *
993  * @param dev
994  *   Pointer to Ethernet device.
995  * @param mr_ctrl
996  *   Pointer to per-queue MR control structure.
997  * @param[out] entry
998  *   Pointer to returning MR cache entry, found in the global cache or newly
999  *   created. If failed to create one, this is not written.
1000  * @param addr
1001  *   Search key.
1002  *
1003  * @return
1004  *   Searched LKey on success, UINT32_MAX on no match.
1005  */
1006 static uint32_t
1007 mlx5_mr_lookup_dev(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
1008                    struct mlx5_mr_cache *entry, uintptr_t addr)
1009 {
1010         struct mlx5_priv *priv = dev->data->dev_private;
1011         struct mlx5_ibv_shared *sh = priv->sh;
1012         struct mlx5_mr_btree *bt = &mr_ctrl->cache_bh;
1013         uint16_t idx;
1014         uint32_t lkey;
1015
1016         /* If local cache table is full, try to double it. */
1017         if (unlikely(bt->len == bt->size))
1018                 mr_btree_expand(bt, bt->size << 1);
1019         /* Look up in the global cache. */
1020         rte_rwlock_read_lock(&sh->mr.rwlock);
1021         lkey = mr_btree_lookup(&sh->mr.cache, &idx, addr);
1022         if (lkey != UINT32_MAX) {
1023                 /* Found. */
1024                 *entry = (*sh->mr.cache.table)[idx];
1025                 rte_rwlock_read_unlock(&sh->mr.rwlock);
1026                 /*
1027                  * Update local cache. Even if it fails, return the found entry
1028                  * to update top-half cache. Next time, this entry will be found
1029                  * in the global cache.
1030                  */
1031                 mr_btree_insert(bt, entry);
1032                 return lkey;
1033         }
1034         rte_rwlock_read_unlock(&sh->mr.rwlock);
1035         /* First time to see the address? Create a new MR. */
1036         lkey = mlx5_mr_create(dev, entry, addr);
1037         /*
1038          * Update the local cache if successfully created a new global MR. Even
1039          * if failed to create one, there's no action to take in this datapath
1040          * code. As returning LKey is invalid, this will eventually make HW
1041          * fail.
1042          */
1043         if (lkey != UINT32_MAX)
1044                 mr_btree_insert(bt, entry);
1045         return lkey;
1046 }
1047
1048 /**
1049  * Bottom-half of LKey search on datapath. Firstly search in cache_bh[] and if
1050  * misses, search in the global MR cache table and update the new entry to
1051  * per-queue local caches.
1052  *
1053  * @param dev
1054  *   Pointer to Ethernet device.
1055  * @param mr_ctrl
1056  *   Pointer to per-queue MR control structure.
1057  * @param addr
1058  *   Search key.
1059  *
1060  * @return
1061  *   Searched LKey on success, UINT32_MAX on no match.
1062  */
1063 static uint32_t
1064 mlx5_mr_addr2mr_bh(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
1065                    uintptr_t addr)
1066 {
1067         uint32_t lkey;
1068         uint16_t bh_idx = 0;
1069         /* Victim in top-half cache to replace with new entry. */
1070         struct mlx5_mr_cache *repl = &mr_ctrl->cache[mr_ctrl->head];
1071
1072         /* Binary-search MR translation table. */
1073         lkey = mr_btree_lookup(&mr_ctrl->cache_bh, &bh_idx, addr);
1074         /* Update top-half cache. */
1075         if (likely(lkey != UINT32_MAX)) {
1076                 *repl = (*mr_ctrl->cache_bh.table)[bh_idx];
1077         } else {
1078                 /*
1079                  * If missed in local lookup table, search in the global cache
1080                  * and local cache_bh[] will be updated inside if possible.
1081                  * Top-half cache entry will also be updated.
1082                  */
1083                 lkey = mlx5_mr_lookup_dev(dev, mr_ctrl, repl, addr);
1084                 if (unlikely(lkey == UINT32_MAX))
1085                         return UINT32_MAX;
1086         }
1087         /* Update the most recently used entry. */
1088         mr_ctrl->mru = mr_ctrl->head;
1089         /* Point to the next victim, the oldest. */
1090         mr_ctrl->head = (mr_ctrl->head + 1) % MLX5_MR_CACHE_N;
1091         return lkey;
1092 }
1093
1094 /**
1095  * Bottom-half of LKey search on Rx.
1096  *
1097  * @param rxq
1098  *   Pointer to Rx queue structure.
1099  * @param addr
1100  *   Search key.
1101  *
1102  * @return
1103  *   Searched LKey on success, UINT32_MAX on no match.
1104  */
1105 uint32_t
1106 mlx5_rx_addr2mr_bh(struct mlx5_rxq_data *rxq, uintptr_t addr)
1107 {
1108         struct mlx5_rxq_ctrl *rxq_ctrl =
1109                 container_of(rxq, struct mlx5_rxq_ctrl, rxq);
1110         struct mlx5_mr_ctrl *mr_ctrl = &rxq->mr_ctrl;
1111         struct mlx5_priv *priv = rxq_ctrl->priv;
1112
1113         return mlx5_mr_addr2mr_bh(ETH_DEV(priv), mr_ctrl, addr);
1114 }
1115
1116 /**
1117  * Bottom-half of LKey search on Tx.
1118  *
1119  * @param txq
1120  *   Pointer to Tx queue structure.
1121  * @param addr
1122  *   Search key.
1123  *
1124  * @return
1125  *   Searched LKey on success, UINT32_MAX on no match.
1126  */
1127 static uint32_t
1128 mlx5_tx_addr2mr_bh(struct mlx5_txq_data *txq, uintptr_t addr)
1129 {
1130         struct mlx5_txq_ctrl *txq_ctrl =
1131                 container_of(txq, struct mlx5_txq_ctrl, txq);
1132         struct mlx5_mr_ctrl *mr_ctrl = &txq->mr_ctrl;
1133         struct mlx5_priv *priv = txq_ctrl->priv;
1134
1135         return mlx5_mr_addr2mr_bh(ETH_DEV(priv), mr_ctrl, addr);
1136 }
1137
1138 /**
1139  * Bottom-half of LKey search on Tx. If it can't be searched in the memseg
1140  * list, register the mempool of the mbuf as externally allocated memory.
1141  *
1142  * @param txq
1143  *   Pointer to Tx queue structure.
1144  * @param mb
1145  *   Pointer to mbuf.
1146  *
1147  * @return
1148  *   Searched LKey on success, UINT32_MAX on no match.
1149  */
1150 uint32_t
1151 mlx5_tx_mb2mr_bh(struct mlx5_txq_data *txq, struct rte_mbuf *mb)
1152 {
1153         uintptr_t addr = (uintptr_t)mb->buf_addr;
1154         uint32_t lkey;
1155
1156         lkey = mlx5_tx_addr2mr_bh(txq, addr);
1157         if (lkey == UINT32_MAX && rte_errno == ENXIO) {
1158                 /* Mempool may have externally allocated memory. */
1159                 return mlx5_tx_update_ext_mp(txq, addr, mlx5_mb2mp(mb));
1160         }
1161         return lkey;
1162 }
1163
1164 /**
1165  * Flush all of the local cache entries.
1166  *
1167  * @param mr_ctrl
1168  *   Pointer to per-queue MR control structure.
1169  */
1170 void
1171 mlx5_mr_flush_local_cache(struct mlx5_mr_ctrl *mr_ctrl)
1172 {
1173         /* Reset the most-recently-used index. */
1174         mr_ctrl->mru = 0;
1175         /* Reset the linear search array. */
1176         mr_ctrl->head = 0;
1177         memset(mr_ctrl->cache, 0, sizeof(mr_ctrl->cache));
1178         /* Reset the B-tree table. */
1179         mr_ctrl->cache_bh.len = 1;
1180         mr_ctrl->cache_bh.overflow = 0;
1181         /* Update the generation number. */
1182         mr_ctrl->cur_gen = *mr_ctrl->dev_gen_ptr;
1183         DRV_LOG(DEBUG, "mr_ctrl(%p): flushed, cur_gen=%d",
1184                 (void *)mr_ctrl, mr_ctrl->cur_gen);
1185 }
1186
1187 /**
1188  * Creates a memory region for external memory, that is memory which is not
1189  * part of the DPDK memory segments.
1190  *
1191  * @param dev
1192  *   Pointer to the ethernet device.
1193  * @param addr
1194  *   Starting virtual address of memory.
1195  * @param len
1196  *   Length of memory segment being mapped.
1197  * @param socked_id
1198  *   Socket to allocate heap memory for the control structures.
1199  *
1200  * @return
1201  *   Pointer to MR structure on success, NULL otherwise.
1202  */
1203 static struct mlx5_mr *
1204 mlx5_create_mr_ext(struct rte_eth_dev *dev, uintptr_t addr, size_t len,
1205                    int socket_id)
1206 {
1207         struct mlx5_priv *priv = dev->data->dev_private;
1208         struct mlx5_mr *mr = NULL;
1209
1210         mr = rte_zmalloc_socket(NULL,
1211                                 RTE_ALIGN_CEIL(sizeof(*mr),
1212                                                RTE_CACHE_LINE_SIZE),
1213                                 RTE_CACHE_LINE_SIZE, socket_id);
1214         if (mr == NULL)
1215                 return NULL;
1216         mr->ibv_mr = mlx5_glue->reg_mr(priv->sh->pd, (void *)addr, len,
1217                                        IBV_ACCESS_LOCAL_WRITE);
1218         if (mr->ibv_mr == NULL) {
1219                 DRV_LOG(WARNING,
1220                         "port %u fail to create a verbs MR for address (%p)",
1221                         dev->data->port_id, (void *)addr);
1222                 rte_free(mr);
1223                 return NULL;
1224         }
1225         mr->msl = NULL; /* Mark it is external memory. */
1226         mr->ms_bmp = NULL;
1227         mr->ms_n = 1;
1228         mr->ms_bmp_n = 1;
1229         DRV_LOG(DEBUG,
1230                 "port %u MR CREATED (%p) for external memory %p:\n"
1231                 "  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
1232                 " lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
1233                 dev->data->port_id, (void *)mr, (void *)addr,
1234                 addr, addr + len, rte_cpu_to_be_32(mr->ibv_mr->lkey),
1235                 mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
1236         return mr;
1237 }
1238
1239 /**
1240  * Called during rte_mempool_mem_iter() by mlx5_mr_update_ext_mp().
1241  *
1242  * Externally allocated chunk is registered and a MR is created for the chunk.
1243  * The MR object is added to the global list. If memseg list of a MR object
1244  * (mr->msl) is null, the MR object can be regarded as externally allocated
1245  * memory.
1246  *
1247  * Once external memory is registered, it should be static. If the memory is
1248  * freed and the virtual address range has different physical memory mapped
1249  * again, it may cause crash on device due to the wrong translation entry. PMD
1250  * can't track the free event of the external memory for now.
1251  */
1252 static void
1253 mlx5_mr_update_ext_mp_cb(struct rte_mempool *mp, void *opaque,
1254                          struct rte_mempool_memhdr *memhdr,
1255                          unsigned mem_idx __rte_unused)
1256 {
1257         struct mr_update_mp_data *data = opaque;
1258         struct rte_eth_dev *dev = data->dev;
1259         struct mlx5_priv *priv = dev->data->dev_private;
1260         struct mlx5_ibv_shared *sh = priv->sh;
1261         struct mlx5_mr_ctrl *mr_ctrl = data->mr_ctrl;
1262         struct mlx5_mr *mr = NULL;
1263         uintptr_t addr = (uintptr_t)memhdr->addr;
1264         size_t len = memhdr->len;
1265         struct mlx5_mr_cache entry;
1266         uint32_t lkey;
1267
1268         assert(rte_eal_process_type() == RTE_PROC_PRIMARY);
1269         /* If already registered, it should return. */
1270         rte_rwlock_read_lock(&sh->mr.rwlock);
1271         lkey = mr_lookup_dev(sh, &entry, addr);
1272         rte_rwlock_read_unlock(&sh->mr.rwlock);
1273         if (lkey != UINT32_MAX)
1274                 return;
1275         DRV_LOG(DEBUG, "port %u register MR for chunk #%d of mempool (%s)",
1276                 dev->data->port_id, mem_idx, mp->name);
1277         mr = mlx5_create_mr_ext(dev, addr, len, mp->socket_id);
1278         if (!mr) {
1279                 DRV_LOG(WARNING,
1280                         "port %u unable to allocate a new MR of"
1281                         " mempool (%s).",
1282                         dev->data->port_id, mp->name);
1283                 data->ret = -1;
1284                 return;
1285         }
1286         rte_rwlock_write_lock(&sh->mr.rwlock);
1287         LIST_INSERT_HEAD(&sh->mr.mr_list, mr, mr);
1288         /* Insert to the global cache table. */
1289         mr_insert_dev_cache(sh, mr);
1290         rte_rwlock_write_unlock(&sh->mr.rwlock);
1291         /* Insert to the local cache table */
1292         mlx5_mr_addr2mr_bh(dev, mr_ctrl, addr);
1293 }
1294
1295 /**
1296  * Finds the first ethdev that match the pci device.
1297  * The existence of multiple ethdev per pci device is only with representors.
1298  * On such case, it is enough to get only one of the ports as they all share
1299  * the same ibv context.
1300  *
1301  * @param pdev
1302  *   Pointer to the PCI device.
1303  *
1304  * @return
1305  *   Pointer to the ethdev if found, NULL otherwise.
1306  */
1307 static struct rte_eth_dev *
1308 pci_dev_to_eth_dev(struct rte_pci_device *pdev)
1309 {
1310         uint16_t port_id;
1311
1312         RTE_ETH_FOREACH_DEV_OF(port_id, &pdev->device)
1313                 return &rte_eth_devices[port_id];
1314         return NULL;
1315 }
1316
1317 /**
1318  * DPDK callback to DMA map external memory to a PCI device.
1319  *
1320  * @param pdev
1321  *   Pointer to the PCI device.
1322  * @param addr
1323  *   Starting virtual address of memory to be mapped.
1324  * @param iova
1325  *   Starting IOVA address of memory to be mapped.
1326  * @param len
1327  *   Length of memory segment being mapped.
1328  *
1329  * @return
1330  *   0 on success, negative value on error.
1331  */
1332 int
1333 mlx5_dma_map(struct rte_pci_device *pdev, void *addr,
1334              uint64_t iova __rte_unused, size_t len)
1335 {
1336         struct rte_eth_dev *dev;
1337         struct mlx5_mr *mr;
1338         struct mlx5_priv *priv;
1339         struct mlx5_ibv_shared *sh;
1340
1341         dev = pci_dev_to_eth_dev(pdev);
1342         if (!dev) {
1343                 DRV_LOG(WARNING, "unable to find matching ethdev "
1344                                  "to PCI device %p", (void *)pdev);
1345                 rte_errno = ENODEV;
1346                 return -1;
1347         }
1348         priv = dev->data->dev_private;
1349         mr = mlx5_create_mr_ext(dev, (uintptr_t)addr, len, SOCKET_ID_ANY);
1350         if (!mr) {
1351                 DRV_LOG(WARNING,
1352                         "port %u unable to dma map", dev->data->port_id);
1353                 rte_errno = EINVAL;
1354                 return -1;
1355         }
1356         sh = priv->sh;
1357         rte_rwlock_write_lock(&sh->mr.rwlock);
1358         LIST_INSERT_HEAD(&sh->mr.mr_list, mr, mr);
1359         /* Insert to the global cache table. */
1360         mr_insert_dev_cache(sh, mr);
1361         rte_rwlock_write_unlock(&sh->mr.rwlock);
1362         return 0;
1363 }
1364
1365 /**
1366  * DPDK callback to DMA unmap external memory to a PCI device.
1367  *
1368  * @param pdev
1369  *   Pointer to the PCI device.
1370  * @param addr
1371  *   Starting virtual address of memory to be unmapped.
1372  * @param iova
1373  *   Starting IOVA address of memory to be unmapped.
1374  * @param len
1375  *   Length of memory segment being unmapped.
1376  *
1377  * @return
1378  *   0 on success, negative value on error.
1379  */
1380 int
1381 mlx5_dma_unmap(struct rte_pci_device *pdev, void *addr,
1382                uint64_t iova __rte_unused, size_t len __rte_unused)
1383 {
1384         struct rte_eth_dev *dev;
1385         struct mlx5_priv *priv;
1386         struct mlx5_ibv_shared *sh;
1387         struct mlx5_mr *mr;
1388         struct mlx5_mr_cache entry;
1389
1390         dev = pci_dev_to_eth_dev(pdev);
1391         if (!dev) {
1392                 DRV_LOG(WARNING, "unable to find matching ethdev "
1393                                  "to PCI device %p", (void *)pdev);
1394                 rte_errno = ENODEV;
1395                 return -1;
1396         }
1397         priv = dev->data->dev_private;
1398         sh = priv->sh;
1399         rte_rwlock_read_lock(&sh->mr.rwlock);
1400         mr = mr_lookup_dev_list(sh, &entry, (uintptr_t)addr);
1401         if (!mr) {
1402                 rte_rwlock_read_unlock(&sh->mr.rwlock);
1403                 DRV_LOG(WARNING, "address 0x%" PRIxPTR " wasn't registered "
1404                                  "to PCI device %p", (uintptr_t)addr,
1405                                  (void *)pdev);
1406                 rte_errno = EINVAL;
1407                 return -1;
1408         }
1409         LIST_REMOVE(mr, mr);
1410         LIST_INSERT_HEAD(&sh->mr.mr_free_list, mr, mr);
1411         DEBUG("port %u remove MR(%p) from list", dev->data->port_id,
1412               (void *)mr);
1413         mr_rebuild_dev_cache(sh);
1414         /*
1415          * Flush local caches by propagating invalidation across cores.
1416          * rte_smp_wmb() is enough to synchronize this event. If one of
1417          * freed memsegs is seen by other core, that means the memseg
1418          * has been allocated by allocator, which will come after this
1419          * free call. Therefore, this store instruction (incrementing
1420          * generation below) will be guaranteed to be seen by other core
1421          * before the core sees the newly allocated memory.
1422          */
1423         ++sh->mr.dev_gen;
1424         DEBUG("broadcasting local cache flush, gen=%d", sh->mr.dev_gen);
1425         rte_smp_wmb();
1426         rte_rwlock_read_unlock(&sh->mr.rwlock);
1427         return 0;
1428 }
1429
1430 /**
1431  * Register MR for entire memory chunks in a Mempool having externally allocated
1432  * memory and fill in local cache.
1433  *
1434  * @param dev
1435  *   Pointer to Ethernet device.
1436  * @param mr_ctrl
1437  *   Pointer to per-queue MR control structure.
1438  * @param mp
1439  *   Pointer to registering Mempool.
1440  *
1441  * @return
1442  *   0 on success, -1 on failure.
1443  */
1444 static uint32_t
1445 mlx5_mr_update_ext_mp(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
1446                       struct rte_mempool *mp)
1447 {
1448         struct mr_update_mp_data data = {
1449                 .dev = dev,
1450                 .mr_ctrl = mr_ctrl,
1451                 .ret = 0,
1452         };
1453
1454         rte_mempool_mem_iter(mp, mlx5_mr_update_ext_mp_cb, &data);
1455         return data.ret;
1456 }
1457
1458 /**
1459  * Register MR entire memory chunks in a Mempool having externally allocated
1460  * memory and search LKey of the address to return.
1461  *
1462  * @param dev
1463  *   Pointer to Ethernet device.
1464  * @param addr
1465  *   Search key.
1466  * @param mp
1467  *   Pointer to registering Mempool where addr belongs.
1468  *
1469  * @return
1470  *   LKey for address on success, UINT32_MAX on failure.
1471  */
1472 uint32_t
1473 mlx5_tx_update_ext_mp(struct mlx5_txq_data *txq, uintptr_t addr,
1474                       struct rte_mempool *mp)
1475 {
1476         struct mlx5_txq_ctrl *txq_ctrl =
1477                 container_of(txq, struct mlx5_txq_ctrl, txq);
1478         struct mlx5_mr_ctrl *mr_ctrl = &txq->mr_ctrl;
1479         struct mlx5_priv *priv = txq_ctrl->priv;
1480
1481         if (rte_eal_process_type() != RTE_PROC_PRIMARY) {
1482                 DRV_LOG(WARNING,
1483                         "port %u using address (%p) from unregistered mempool"
1484                         " having externally allocated memory"
1485                         " in secondary process, please create mempool"
1486                         " prior to rte_eth_dev_start()",
1487                         PORT_ID(priv), (void *)addr);
1488                 return UINT32_MAX;
1489         }
1490         mlx5_mr_update_ext_mp(ETH_DEV(priv), mr_ctrl, mp);
1491         return mlx5_tx_addr2mr_bh(txq, addr);
1492 }
1493
1494 /* Called during rte_mempool_mem_iter() by mlx5_mr_update_mp(). */
1495 static void
1496 mlx5_mr_update_mp_cb(struct rte_mempool *mp __rte_unused, void *opaque,
1497                      struct rte_mempool_memhdr *memhdr,
1498                      unsigned mem_idx __rte_unused)
1499 {
1500         struct mr_update_mp_data *data = opaque;
1501         uint32_t lkey;
1502
1503         /* Stop iteration if failed in the previous walk. */
1504         if (data->ret < 0)
1505                 return;
1506         /* Register address of the chunk and update local caches. */
1507         lkey = mlx5_mr_addr2mr_bh(data->dev, data->mr_ctrl,
1508                                   (uintptr_t)memhdr->addr);
1509         if (lkey == UINT32_MAX)
1510                 data->ret = -1;
1511 }
1512
1513 /**
1514  * Register entire memory chunks in a Mempool.
1515  *
1516  * @param dev
1517  *   Pointer to Ethernet device.
1518  * @param mr_ctrl
1519  *   Pointer to per-queue MR control structure.
1520  * @param mp
1521  *   Pointer to registering Mempool.
1522  *
1523  * @return
1524  *   0 on success, -1 on failure.
1525  */
1526 int
1527 mlx5_mr_update_mp(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
1528                   struct rte_mempool *mp)
1529 {
1530         struct mr_update_mp_data data = {
1531                 .dev = dev,
1532                 .mr_ctrl = mr_ctrl,
1533                 .ret = 0,
1534         };
1535
1536         rte_mempool_mem_iter(mp, mlx5_mr_update_mp_cb, &data);
1537         if (data.ret < 0 && rte_errno == ENXIO) {
1538                 /* Mempool may have externally allocated memory. */
1539                 return mlx5_mr_update_ext_mp(dev, mr_ctrl, mp);
1540         }
1541         return data.ret;
1542 }
1543
1544 /**
1545  * Dump all the created MRs and the global cache entries.
1546  *
1547  * @param sh
1548  *   Pointer to Ethernet device shared context.
1549  */
1550 void
1551 mlx5_mr_dump_dev(struct mlx5_ibv_shared *sh __rte_unused)
1552 {
1553 #ifndef NDEBUG
1554         struct mlx5_mr *mr;
1555         int mr_n = 0;
1556         int chunk_n = 0;
1557
1558         rte_rwlock_read_lock(&sh->mr.rwlock);
1559         /* Iterate all the existing MRs. */
1560         LIST_FOREACH(mr, &sh->mr.mr_list, mr) {
1561                 unsigned int n;
1562
1563                 DEBUG("device %s MR[%u], LKey = 0x%x, ms_n = %u, ms_bmp_n = %u",
1564                       sh->ibdev_name, mr_n++,
1565                       rte_cpu_to_be_32(mr->ibv_mr->lkey),
1566                       mr->ms_n, mr->ms_bmp_n);
1567                 if (mr->ms_n == 0)
1568                         continue;
1569                 for (n = 0; n < mr->ms_bmp_n; ) {
1570                         struct mlx5_mr_cache ret = { 0, };
1571
1572                         n = mr_find_next_chunk(mr, &ret, n);
1573                         if (!ret.end)
1574                                 break;
1575                         DEBUG("  chunk[%u], [0x%" PRIxPTR ", 0x%" PRIxPTR ")",
1576                               chunk_n++, ret.start, ret.end);
1577                 }
1578         }
1579         DEBUG("device %s dumping global cache", sh->ibdev_name);
1580         mlx5_mr_btree_dump(&sh->mr.cache);
1581         rte_rwlock_read_unlock(&sh->mr.rwlock);
1582 #endif
1583 }
1584
1585 /**
1586  * Release all the created MRs and resources for shared device context.
1587  * list.
1588  *
1589  * @param sh
1590  *   Pointer to Ethernet device shared context.
1591  */
1592 void
1593 mlx5_mr_release(struct mlx5_ibv_shared *sh)
1594 {
1595         struct mlx5_mr *mr_next;
1596
1597         if (rte_log_get_level(mlx5_logtype) == RTE_LOG_DEBUG)
1598                 mlx5_mr_dump_dev(sh);
1599         rte_rwlock_write_lock(&sh->mr.rwlock);
1600         /* Detach from MR list and move to free list. */
1601         mr_next = LIST_FIRST(&sh->mr.mr_list);
1602         while (mr_next != NULL) {
1603                 struct mlx5_mr *mr = mr_next;
1604
1605                 mr_next = LIST_NEXT(mr, mr);
1606                 LIST_REMOVE(mr, mr);
1607                 LIST_INSERT_HEAD(&sh->mr.mr_free_list, mr, mr);
1608         }
1609         LIST_INIT(&sh->mr.mr_list);
1610         /* Free global cache. */
1611         mlx5_mr_btree_free(&sh->mr.cache);
1612         rte_rwlock_write_unlock(&sh->mr.rwlock);
1613         /* Free all remaining MRs. */
1614         mlx5_mr_garbage_collect(sh);
1615 }