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