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