New upstream version 18.08
[deb_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
18 #include "mlx5.h"
19 #include "mlx5_mr.h"
20 #include "mlx5_rxtx.h"
21 #include "mlx5_glue.h"
22
23 struct mr_find_contig_memsegs_data {
24         uintptr_t addr;
25         uintptr_t start;
26         uintptr_t end;
27         const struct rte_memseg_list *msl;
28 };
29
30 struct mr_update_mp_data {
31         struct rte_eth_dev *dev;
32         struct mlx5_mr_ctrl *mr_ctrl;
33         int ret;
34 };
35
36 /**
37  * Expand B-tree table to a given size. Can't be called with holding
38  * memory_hotplug_lock or priv->mr.rwlock due to rte_realloc().
39  *
40  * @param bt
41  *   Pointer to B-tree structure.
42  * @param n
43  *   Number of entries for expansion.
44  *
45  * @return
46  *   0 on success, -1 on failure.
47  */
48 static int
49 mr_btree_expand(struct mlx5_mr_btree *bt, int n)
50 {
51         void *mem;
52         int ret = 0;
53
54         if (n <= bt->size)
55                 return ret;
56         /*
57          * Downside of directly using rte_realloc() is that SOCKET_ID_ANY is
58          * used inside if there's no room to expand. Because this is a quite
59          * rare case and a part of very slow path, it is very acceptable.
60          * Initially cache_bh[] will be given practically enough space and once
61          * it is expanded, expansion wouldn't be needed again ever.
62          */
63         mem = rte_realloc(bt->table, n * sizeof(struct mlx5_mr_cache), 0);
64         if (mem == NULL) {
65                 /* Not an error, B-tree search will be skipped. */
66                 DRV_LOG(WARNING, "failed to expand MR B-tree (%p) table",
67                         (void *)bt);
68                 ret = -1;
69         } else {
70                 DRV_LOG(DEBUG, "expanded MR B-tree table (size=%u)", n);
71                 bt->table = mem;
72                 bt->size = n;
73         }
74         return ret;
75 }
76
77 /**
78  * Look up LKey from given B-tree lookup table, store the last index and return
79  * searched LKey.
80  *
81  * @param bt
82  *   Pointer to B-tree structure.
83  * @param[out] idx
84  *   Pointer to index. Even on search failure, returns index where it stops
85  *   searching so that index can be used when inserting a new entry.
86  * @param addr
87  *   Search key.
88  *
89  * @return
90  *   Searched LKey on success, UINT32_MAX on no match.
91  */
92 static uint32_t
93 mr_btree_lookup(struct mlx5_mr_btree *bt, uint16_t *idx, uintptr_t addr)
94 {
95         struct mlx5_mr_cache *lkp_tbl;
96         uint16_t n;
97         uint16_t base = 0;
98
99         assert(bt != NULL);
100         lkp_tbl = *bt->table;
101         n = bt->len;
102         /* First entry must be NULL for comparison. */
103         assert(bt->len > 0 || (lkp_tbl[0].start == 0 &&
104                                lkp_tbl[0].lkey == UINT32_MAX));
105         /* Binary search. */
106         do {
107                 register uint16_t delta = n >> 1;
108
109                 if (addr < lkp_tbl[base + delta].start) {
110                         n = delta;
111                 } else {
112                         base += delta;
113                         n -= delta;
114                 }
115         } while (n > 1);
116         assert(addr >= lkp_tbl[base].start);
117         *idx = base;
118         if (addr < lkp_tbl[base].end)
119                 return lkp_tbl[base].lkey;
120         /* Not found. */
121         return UINT32_MAX;
122 }
123
124 /**
125  * Insert an entry to B-tree lookup table.
126  *
127  * @param bt
128  *   Pointer to B-tree structure.
129  * @param entry
130  *   Pointer to new entry to insert.
131  *
132  * @return
133  *   0 on success, -1 on failure.
134  */
135 static int
136 mr_btree_insert(struct mlx5_mr_btree *bt, struct mlx5_mr_cache *entry)
137 {
138         struct mlx5_mr_cache *lkp_tbl;
139         uint16_t idx = 0;
140         size_t shift;
141
142         assert(bt != NULL);
143         assert(bt->len <= bt->size);
144         assert(bt->len > 0);
145         lkp_tbl = *bt->table;
146         /* Find out the slot for insertion. */
147         if (mr_btree_lookup(bt, &idx, entry->start) != UINT32_MAX) {
148                 DRV_LOG(DEBUG,
149                         "abort insertion to B-tree(%p): already exist at"
150                         " idx=%u [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
151                         (void *)bt, idx, entry->start, entry->end, entry->lkey);
152                 /* Already exist, return. */
153                 return 0;
154         }
155         /* If table is full, return error. */
156         if (unlikely(bt->len == bt->size)) {
157                 bt->overflow = 1;
158                 return -1;
159         }
160         /* Insert entry. */
161         ++idx;
162         shift = (bt->len - idx) * sizeof(struct mlx5_mr_cache);
163         if (shift)
164                 memmove(&lkp_tbl[idx + 1], &lkp_tbl[idx], shift);
165         lkp_tbl[idx] = *entry;
166         bt->len++;
167         DRV_LOG(DEBUG,
168                 "inserted B-tree(%p)[%u],"
169                 " [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
170                 (void *)bt, idx, entry->start, entry->end, entry->lkey);
171         return 0;
172 }
173
174 /**
175  * Initialize B-tree and allocate memory for lookup table.
176  *
177  * @param bt
178  *   Pointer to B-tree structure.
179  * @param n
180  *   Number of entries to allocate.
181  * @param socket
182  *   NUMA socket on which memory must be allocated.
183  *
184  * @return
185  *   0 on success, a negative errno value otherwise and rte_errno is set.
186  */
187 int
188 mlx5_mr_btree_init(struct mlx5_mr_btree *bt, int n, int socket)
189 {
190         if (bt == NULL) {
191                 rte_errno = EINVAL;
192                 return -rte_errno;
193         }
194         assert(!bt->table && !bt->size);
195         memset(bt, 0, sizeof(*bt));
196         bt->table = rte_calloc_socket("B-tree table",
197                                       n, sizeof(struct mlx5_mr_cache),
198                                       0, socket);
199         if (bt->table == NULL) {
200                 rte_errno = ENOMEM;
201                 DEBUG("failed to allocate memory for btree cache on socket %d",
202                       socket);
203                 return -rte_errno;
204         }
205         bt->size = n;
206         /* First entry must be NULL for binary search. */
207         (*bt->table)[bt->len++] = (struct mlx5_mr_cache) {
208                 .lkey = UINT32_MAX,
209         };
210         DEBUG("initialized B-tree %p with table %p",
211               (void *)bt, (void *)bt->table);
212         return 0;
213 }
214
215 /**
216  * Free B-tree resources.
217  *
218  * @param bt
219  *   Pointer to B-tree structure.
220  */
221 void
222 mlx5_mr_btree_free(struct mlx5_mr_btree *bt)
223 {
224         if (bt == NULL)
225                 return;
226         DEBUG("freeing B-tree %p with table %p",
227               (void *)bt, (void *)bt->table);
228         rte_free(bt->table);
229         memset(bt, 0, sizeof(*bt));
230 }
231
232 /**
233  * Dump all the entries in a B-tree
234  *
235  * @param bt
236  *   Pointer to B-tree structure.
237  */
238 void
239 mlx5_mr_btree_dump(struct mlx5_mr_btree *bt __rte_unused)
240 {
241 #ifndef NDEBUG
242         int idx;
243         struct mlx5_mr_cache *lkp_tbl;
244
245         if (bt == NULL)
246                 return;
247         lkp_tbl = *bt->table;
248         for (idx = 0; idx < bt->len; ++idx) {
249                 struct mlx5_mr_cache *entry = &lkp_tbl[idx];
250
251                 DEBUG("B-tree(%p)[%u],"
252                       " [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
253                       (void *)bt, idx, entry->start, entry->end, entry->lkey);
254         }
255 #endif
256 }
257
258 /**
259  * Find virtually contiguous memory chunk in a given MR.
260  *
261  * @param dev
262  *   Pointer to MR structure.
263  * @param[out] entry
264  *   Pointer to returning MR cache entry. If not found, this will not be
265  *   updated.
266  * @param start_idx
267  *   Start index of the memseg bitmap.
268  *
269  * @return
270  *   Next index to go on lookup.
271  */
272 static int
273 mr_find_next_chunk(struct mlx5_mr *mr, struct mlx5_mr_cache *entry,
274                    int base_idx)
275 {
276         uintptr_t start = 0;
277         uintptr_t end = 0;
278         uint32_t idx = 0;
279
280         for (idx = base_idx; idx < mr->ms_bmp_n; ++idx) {
281                 if (rte_bitmap_get(mr->ms_bmp, idx)) {
282                         const struct rte_memseg_list *msl;
283                         const struct rte_memseg *ms;
284
285                         msl = mr->msl;
286                         ms = rte_fbarray_get(&msl->memseg_arr,
287                                              mr->ms_base_idx + idx);
288                         assert(msl->page_sz == ms->hugepage_sz);
289                         if (!start)
290                                 start = ms->addr_64;
291                         end = ms->addr_64 + ms->hugepage_sz;
292                 } else if (start) {
293                         /* Passed the end of a fragment. */
294                         break;
295                 }
296         }
297         if (start) {
298                 /* Found one chunk. */
299                 entry->start = start;
300                 entry->end = end;
301                 entry->lkey = rte_cpu_to_be_32(mr->ibv_mr->lkey);
302         }
303         return idx;
304 }
305
306 /**
307  * Insert a MR to the global B-tree cache. It may fail due to low-on-memory.
308  * Then, this entry will have to be searched by mr_lookup_dev_list() in
309  * mlx5_mr_create() on miss.
310  *
311  * @param dev
312  *   Pointer to Ethernet device.
313  * @param mr
314  *   Pointer to MR to insert.
315  *
316  * @return
317  *   0 on success, -1 on failure.
318  */
319 static int
320 mr_insert_dev_cache(struct rte_eth_dev *dev, struct mlx5_mr *mr)
321 {
322         struct priv *priv = dev->data->dev_private;
323         unsigned int n;
324
325         DRV_LOG(DEBUG, "port %u inserting MR(%p) to global cache",
326                 dev->data->port_id, (void *)mr);
327         for (n = 0; n < mr->ms_bmp_n; ) {
328                 struct mlx5_mr_cache entry = { 0, };
329
330                 /* Find a contiguous chunk and advance the index. */
331                 n = mr_find_next_chunk(mr, &entry, n);
332                 if (!entry.end)
333                         break;
334                 if (mr_btree_insert(&priv->mr.cache, &entry) < 0) {
335                         /*
336                          * Overflowed, but the global table cannot be expanded
337                          * because of deadlock.
338                          */
339                         return -1;
340                 }
341         }
342         return 0;
343 }
344
345 /**
346  * Look up address in the original global MR list.
347  *
348  * @param dev
349  *   Pointer to Ethernet device.
350  * @param[out] entry
351  *   Pointer to returning MR cache entry. If no match, this will not be updated.
352  * @param addr
353  *   Search key.
354  *
355  * @return
356  *   Found MR on match, NULL otherwise.
357  */
358 static struct mlx5_mr *
359 mr_lookup_dev_list(struct rte_eth_dev *dev, struct mlx5_mr_cache *entry,
360                    uintptr_t addr)
361 {
362         struct priv *priv = dev->data->dev_private;
363         struct mlx5_mr *mr;
364
365         /* Iterate all the existing MRs. */
366         LIST_FOREACH(mr, &priv->mr.mr_list, mr) {
367                 unsigned int n;
368
369                 if (mr->ms_n == 0)
370                         continue;
371                 for (n = 0; n < mr->ms_bmp_n; ) {
372                         struct mlx5_mr_cache ret = { 0, };
373
374                         n = mr_find_next_chunk(mr, &ret, n);
375                         if (addr >= ret.start && addr < ret.end) {
376                                 /* Found. */
377                                 *entry = ret;
378                                 return mr;
379                         }
380                 }
381         }
382         return NULL;
383 }
384
385 /**
386  * Look up address on device.
387  *
388  * @param dev
389  *   Pointer to Ethernet device.
390  * @param[out] entry
391  *   Pointer to returning MR cache entry. If no match, this will not be updated.
392  * @param addr
393  *   Search key.
394  *
395  * @return
396  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
397  */
398 static uint32_t
399 mr_lookup_dev(struct rte_eth_dev *dev, struct mlx5_mr_cache *entry,
400               uintptr_t addr)
401 {
402         struct priv *priv = dev->data->dev_private;
403         uint16_t idx;
404         uint32_t lkey = UINT32_MAX;
405         struct mlx5_mr *mr;
406
407         /*
408          * If the global cache has overflowed since it failed to expand the
409          * B-tree table, it can't have all the existing MRs. Then, the address
410          * has to be searched by traversing the original MR list instead, which
411          * is very slow path. Otherwise, the global cache is all inclusive.
412          */
413         if (!unlikely(priv->mr.cache.overflow)) {
414                 lkey = mr_btree_lookup(&priv->mr.cache, &idx, addr);
415                 if (lkey != UINT32_MAX)
416                         *entry = (*priv->mr.cache.table)[idx];
417         } else {
418                 /* Falling back to the slowest path. */
419                 mr = mr_lookup_dev_list(dev, entry, addr);
420                 if (mr != NULL)
421                         lkey = entry->lkey;
422         }
423         assert(lkey == UINT32_MAX || (addr >= entry->start &&
424                                       addr < entry->end));
425         return lkey;
426 }
427
428 /**
429  * Free MR resources. MR lock must not be held to avoid a deadlock. rte_free()
430  * can raise memory free event and the callback function will spin on the lock.
431  *
432  * @param mr
433  *   Pointer to MR to free.
434  */
435 static void
436 mr_free(struct mlx5_mr *mr)
437 {
438         if (mr == NULL)
439                 return;
440         DRV_LOG(DEBUG, "freeing MR(%p):", (void *)mr);
441         if (mr->ibv_mr != NULL)
442                 claim_zero(mlx5_glue->dereg_mr(mr->ibv_mr));
443         if (mr->ms_bmp != NULL)
444                 rte_bitmap_free(mr->ms_bmp);
445         rte_free(mr);
446 }
447
448 /**
449  * Releass resources of detached MR having no online entry.
450  *
451  * @param dev
452  *   Pointer to Ethernet device.
453  */
454 static void
455 mlx5_mr_garbage_collect(struct rte_eth_dev *dev)
456 {
457         struct priv *priv = dev->data->dev_private;
458         struct mlx5_mr *mr_next;
459         struct mlx5_mr_list free_list = LIST_HEAD_INITIALIZER(free_list);
460
461         /* Must be called from the primary process. */
462         assert(rte_eal_process_type() == RTE_PROC_PRIMARY);
463         /*
464          * MR can't be freed with holding the lock because rte_free() could call
465          * memory free callback function. This will be a deadlock situation.
466          */
467         rte_rwlock_write_lock(&priv->mr.rwlock);
468         /* Detach the whole free list and release it after unlocking. */
469         free_list = priv->mr.mr_free_list;
470         LIST_INIT(&priv->mr.mr_free_list);
471         rte_rwlock_write_unlock(&priv->mr.rwlock);
472         /* Release resources. */
473         mr_next = LIST_FIRST(&free_list);
474         while (mr_next != NULL) {
475                 struct mlx5_mr *mr = mr_next;
476
477                 mr_next = LIST_NEXT(mr, mr);
478                 mr_free(mr);
479         }
480 }
481
482 /* Called during rte_memseg_contig_walk() by mlx5_mr_create(). */
483 static int
484 mr_find_contig_memsegs_cb(const struct rte_memseg_list *msl,
485                           const struct rte_memseg *ms, size_t len, void *arg)
486 {
487         struct mr_find_contig_memsegs_data *data = arg;
488
489         if (data->addr < ms->addr_64 || data->addr >= ms->addr_64 + len)
490                 return 0;
491         /* Found, save it and stop walking. */
492         data->start = ms->addr_64;
493         data->end = ms->addr_64 + len;
494         data->msl = msl;
495         return 1;
496 }
497
498 /**
499  * Create a new global Memroy Region (MR) for a missing virtual address.
500  * Register entire virtually contiguous memory chunk around the address.
501  *
502  * @param dev
503  *   Pointer to Ethernet device.
504  * @param[out] entry
505  *   Pointer to returning MR cache entry, found in the global cache or newly
506  *   created. If failed to create one, this will not be updated.
507  * @param addr
508  *   Target virtual address to register.
509  *
510  * @return
511  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
512  */
513 static uint32_t
514 mlx5_mr_create(struct rte_eth_dev *dev, struct mlx5_mr_cache *entry,
515                uintptr_t addr)
516 {
517         struct priv *priv = dev->data->dev_private;
518         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
519         const struct rte_memseg_list *msl;
520         const struct rte_memseg *ms;
521         struct mlx5_mr *mr = NULL;
522         size_t len;
523         uint32_t ms_n;
524         uint32_t bmp_size;
525         void *bmp_mem;
526         int ms_idx_shift = -1;
527         unsigned int n;
528         struct mr_find_contig_memsegs_data data = {
529                 .addr = addr,
530         };
531         struct mr_find_contig_memsegs_data data_re;
532
533         DRV_LOG(DEBUG, "port %u creating a MR using address (%p)",
534                 dev->data->port_id, (void *)addr);
535         if (rte_eal_process_type() != RTE_PROC_PRIMARY) {
536                 DRV_LOG(WARNING,
537                         "port %u using address (%p) of unregistered mempool"
538                         " in secondary process, please create mempool"
539                         " before rte_eth_dev_start()",
540                         dev->data->port_id, (void *)addr);
541                 rte_errno = EPERM;
542                 goto err_nolock;
543         }
544         /*
545          * Release detached MRs if any. This can't be called with holding either
546          * memory_hotplug_lock or priv->mr.rwlock. MRs on the free list have
547          * been detached by the memory free event but it couldn't be released
548          * inside the callback due to deadlock. As a result, releasing resources
549          * is quite opportunistic.
550          */
551         mlx5_mr_garbage_collect(dev);
552         /*
553          * Find out a contiguous virtual address chunk in use, to which the
554          * given address belongs, in order to register maximum range. In the
555          * best case where mempools are not dynamically recreated and
556          * '--socket-mem' is speicified as an EAL option, it is very likely to
557          * have only one MR(LKey) per a socket and per a hugepage-size even
558          * though the system memory is highly fragmented.
559          */
560         if (!rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data)) {
561                 DRV_LOG(WARNING,
562                         "port %u unable to find virtually contiguous"
563                         " chunk for address (%p)."
564                         " rte_memseg_contig_walk() failed.",
565                         dev->data->port_id, (void *)addr);
566                 rte_errno = ENXIO;
567                 goto err_nolock;
568         }
569 alloc_resources:
570         /* Addresses must be page-aligned. */
571         assert(rte_is_aligned((void *)data.start, data.msl->page_sz));
572         assert(rte_is_aligned((void *)data.end, data.msl->page_sz));
573         msl = data.msl;
574         ms = rte_mem_virt2memseg((void *)data.start, msl);
575         len = data.end - data.start;
576         assert(msl->page_sz == ms->hugepage_sz);
577         /* Number of memsegs in the range. */
578         ms_n = len / msl->page_sz;
579         DEBUG("port %u extending %p to [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
580               " page_sz=0x%" PRIx64 ", ms_n=%u",
581               dev->data->port_id, (void *)addr,
582               data.start, data.end, msl->page_sz, ms_n);
583         /* Size of memory for bitmap. */
584         bmp_size = rte_bitmap_get_memory_footprint(ms_n);
585         mr = rte_zmalloc_socket(NULL,
586                                 RTE_ALIGN_CEIL(sizeof(*mr),
587                                                RTE_CACHE_LINE_SIZE) +
588                                 bmp_size,
589                                 RTE_CACHE_LINE_SIZE, msl->socket_id);
590         if (mr == NULL) {
591                 DEBUG("port %u unable to allocate memory for a new MR of"
592                       " address (%p).",
593                       dev->data->port_id, (void *)addr);
594                 rte_errno = ENOMEM;
595                 goto err_nolock;
596         }
597         mr->msl = msl;
598         /*
599          * Save the index of the first memseg and initialize memseg bitmap. To
600          * see if a memseg of ms_idx in the memseg-list is still valid, check:
601          *      rte_bitmap_get(mr->bmp, ms_idx - mr->ms_base_idx)
602          */
603         mr->ms_base_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
604         bmp_mem = RTE_PTR_ALIGN_CEIL(mr + 1, RTE_CACHE_LINE_SIZE);
605         mr->ms_bmp = rte_bitmap_init(ms_n, bmp_mem, bmp_size);
606         if (mr->ms_bmp == NULL) {
607                 DEBUG("port %u unable to initialize bitamp for a new MR of"
608                       " address (%p).",
609                       dev->data->port_id, (void *)addr);
610                 rte_errno = EINVAL;
611                 goto err_nolock;
612         }
613         /*
614          * Should recheck whether the extended contiguous chunk is still valid.
615          * Because memory_hotplug_lock can't be held if there's any memory
616          * related calls in a critical path, resource allocation above can't be
617          * locked. If the memory has been changed at this point, try again with
618          * just single page. If not, go on with the big chunk atomically from
619          * here.
620          */
621         rte_rwlock_read_lock(&mcfg->memory_hotplug_lock);
622         data_re = data;
623         if (len > msl->page_sz &&
624             !rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data_re)) {
625                 DEBUG("port %u unable to find virtually contiguous"
626                       " chunk for address (%p)."
627                       " rte_memseg_contig_walk() failed.",
628                       dev->data->port_id, (void *)addr);
629                 rte_errno = ENXIO;
630                 goto err_memlock;
631         }
632         if (data.start != data_re.start || data.end != data_re.end) {
633                 /*
634                  * The extended contiguous chunk has been changed. Try again
635                  * with single memseg instead.
636                  */
637                 data.start = RTE_ALIGN_FLOOR(addr, msl->page_sz);
638                 data.end = data.start + msl->page_sz;
639                 rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
640                 mr_free(mr);
641                 goto alloc_resources;
642         }
643         assert(data.msl == data_re.msl);
644         rte_rwlock_write_lock(&priv->mr.rwlock);
645         /*
646          * Check the address is really missing. If other thread already created
647          * one or it is not found due to overflow, abort and return.
648          */
649         if (mr_lookup_dev(dev, entry, addr) != UINT32_MAX) {
650                 /*
651                  * Insert to the global cache table. It may fail due to
652                  * low-on-memory. Then, this entry will have to be searched
653                  * here again.
654                  */
655                 mr_btree_insert(&priv->mr.cache, entry);
656                 DEBUG("port %u found MR for %p on final lookup, abort",
657                       dev->data->port_id, (void *)addr);
658                 rte_rwlock_write_unlock(&priv->mr.rwlock);
659                 rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
660                 /*
661                  * Must be unlocked before calling rte_free() because
662                  * mlx5_mr_mem_event_free_cb() can be called inside.
663                  */
664                 mr_free(mr);
665                 return entry->lkey;
666         }
667         /*
668          * Trim start and end addresses for verbs MR. Set bits for registering
669          * memsegs but exclude already registered ones. Bitmap can be
670          * fragmented.
671          */
672         for (n = 0; n < ms_n; ++n) {
673                 uintptr_t start;
674                 struct mlx5_mr_cache ret = { 0, };
675
676                 start = data_re.start + n * msl->page_sz;
677                 /* Exclude memsegs already registered by other MRs. */
678                 if (mr_lookup_dev(dev, &ret, start) == UINT32_MAX) {
679                         /*
680                          * Start from the first unregistered memseg in the
681                          * extended range.
682                          */
683                         if (ms_idx_shift == -1) {
684                                 mr->ms_base_idx += n;
685                                 data.start = start;
686                                 ms_idx_shift = n;
687                         }
688                         data.end = start + msl->page_sz;
689                         rte_bitmap_set(mr->ms_bmp, n - ms_idx_shift);
690                         ++mr->ms_n;
691                 }
692         }
693         len = data.end - data.start;
694         mr->ms_bmp_n = len / msl->page_sz;
695         assert(ms_idx_shift + mr->ms_bmp_n <= ms_n);
696         /*
697          * Finally create a verbs MR for the memory chunk. ibv_reg_mr() can be
698          * called with holding the memory lock because it doesn't use
699          * mlx5_alloc_buf_extern() which eventually calls rte_malloc_socket()
700          * through mlx5_alloc_verbs_buf().
701          */
702         mr->ibv_mr = mlx5_glue->reg_mr(priv->pd, (void *)data.start, len,
703                                        IBV_ACCESS_LOCAL_WRITE);
704         if (mr->ibv_mr == NULL) {
705                 DEBUG("port %u fail to create a verbs MR for address (%p)",
706                       dev->data->port_id, (void *)addr);
707                 rte_errno = EINVAL;
708                 goto err_mrlock;
709         }
710         assert((uintptr_t)mr->ibv_mr->addr == data.start);
711         assert(mr->ibv_mr->length == len);
712         LIST_INSERT_HEAD(&priv->mr.mr_list, mr, mr);
713         DEBUG("port %u MR CREATED (%p) for %p:\n"
714               "  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
715               " lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
716               dev->data->port_id, (void *)mr, (void *)addr,
717               data.start, data.end, rte_cpu_to_be_32(mr->ibv_mr->lkey),
718               mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
719         /* Insert to the global cache table. */
720         mr_insert_dev_cache(dev, mr);
721         /* Fill in output data. */
722         mr_lookup_dev(dev, entry, addr);
723         /* Lookup can't fail. */
724         assert(entry->lkey != UINT32_MAX);
725         rte_rwlock_write_unlock(&priv->mr.rwlock);
726         rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
727         return entry->lkey;
728 err_mrlock:
729         rte_rwlock_write_unlock(&priv->mr.rwlock);
730 err_memlock:
731         rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
732 err_nolock:
733         /*
734          * In case of error, as this can be called in a datapath, a warning
735          * message per an error is preferable instead. Must be unlocked before
736          * calling rte_free() because mlx5_mr_mem_event_free_cb() can be called
737          * inside.
738          */
739         mr_free(mr);
740         return UINT32_MAX;
741 }
742
743 /**
744  * Rebuild the global B-tree cache of device from the original MR list.
745  *
746  * @param dev
747  *   Pointer to Ethernet device.
748  */
749 static void
750 mr_rebuild_dev_cache(struct rte_eth_dev *dev)
751 {
752         struct priv *priv = dev->data->dev_private;
753         struct mlx5_mr *mr;
754
755         DRV_LOG(DEBUG, "port %u rebuild dev cache[]", dev->data->port_id);
756         /* Flush cache to rebuild. */
757         priv->mr.cache.len = 1;
758         priv->mr.cache.overflow = 0;
759         /* Iterate all the existing MRs. */
760         LIST_FOREACH(mr, &priv->mr.mr_list, mr)
761                 if (mr_insert_dev_cache(dev, mr) < 0)
762                         return;
763 }
764
765 /**
766  * Callback for memory free event. Iterate freed memsegs and check whether it
767  * belongs to an existing MR. If found, clear the bit from bitmap of MR. As a
768  * result, the MR would be fragmented. If it becomes empty, the MR will be freed
769  * later by mlx5_mr_garbage_collect(). Even if this callback is called from a
770  * secondary process, the garbage collector will be called in primary process
771  * as the secondary process can't call mlx5_mr_create().
772  *
773  * The global cache must be rebuilt if there's any change and this event has to
774  * be propagated to dataplane threads to flush the local caches.
775  *
776  * @param dev
777  *   Pointer to Ethernet device.
778  * @param addr
779  *   Address of freed memory.
780  * @param len
781  *   Size of freed memory.
782  */
783 static void
784 mlx5_mr_mem_event_free_cb(struct rte_eth_dev *dev, const void *addr, size_t len)
785 {
786         struct priv *priv = dev->data->dev_private;
787         const struct rte_memseg_list *msl;
788         struct mlx5_mr *mr;
789         int ms_n;
790         int i;
791         int rebuild = 0;
792
793         DEBUG("port %u free callback: addr=%p, len=%zu",
794               dev->data->port_id, addr, len);
795         msl = rte_mem_virt2memseg_list(addr);
796         /* addr and len must be page-aligned. */
797         assert((uintptr_t)addr == RTE_ALIGN((uintptr_t)addr, msl->page_sz));
798         assert(len == RTE_ALIGN(len, msl->page_sz));
799         ms_n = len / msl->page_sz;
800         rte_rwlock_write_lock(&priv->mr.rwlock);
801         /* Clear bits of freed memsegs from MR. */
802         for (i = 0; i < ms_n; ++i) {
803                 const struct rte_memseg *ms;
804                 struct mlx5_mr_cache entry;
805                 uintptr_t start;
806                 int ms_idx;
807                 uint32_t pos;
808
809                 /* Find MR having this memseg. */
810                 start = (uintptr_t)addr + i * msl->page_sz;
811                 mr = mr_lookup_dev_list(dev, &entry, start);
812                 if (mr == NULL)
813                         continue;
814                 ms = rte_mem_virt2memseg((void *)start, msl);
815                 assert(ms != NULL);
816                 assert(msl->page_sz == ms->hugepage_sz);
817                 ms_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
818                 pos = ms_idx - mr->ms_base_idx;
819                 assert(rte_bitmap_get(mr->ms_bmp, pos));
820                 assert(pos < mr->ms_bmp_n);
821                 DEBUG("port %u MR(%p): clear bitmap[%u] for addr %p",
822                       dev->data->port_id, (void *)mr, pos, (void *)start);
823                 rte_bitmap_clear(mr->ms_bmp, pos);
824                 if (--mr->ms_n == 0) {
825                         LIST_REMOVE(mr, mr);
826                         LIST_INSERT_HEAD(&priv->mr.mr_free_list, mr, mr);
827                         DEBUG("port %u remove MR(%p) from list",
828                               dev->data->port_id, (void *)mr);
829                 }
830                 /*
831                  * MR is fragmented or will be freed. the global cache must be
832                  * rebuilt.
833                  */
834                 rebuild = 1;
835         }
836         if (rebuild) {
837                 mr_rebuild_dev_cache(dev);
838                 /*
839                  * Flush local caches by propagating invalidation across cores.
840                  * rte_smp_wmb() is enough to synchronize this event. If one of
841                  * freed memsegs is seen by other core, that means the memseg
842                  * has been allocated by allocator, which will come after this
843                  * free call. Therefore, this store instruction (incrementing
844                  * generation below) will be guaranteed to be seen by other core
845                  * before the core sees the newly allocated memory.
846                  */
847                 ++priv->mr.dev_gen;
848                 DEBUG("broadcasting local cache flush, gen=%d",
849                       priv->mr.dev_gen);
850                 rte_smp_wmb();
851         }
852         rte_rwlock_write_unlock(&priv->mr.rwlock);
853 }
854
855 /**
856  * Callback for memory event. This can be called from both primary and secondary
857  * process.
858  *
859  * @param event_type
860  *   Memory event type.
861  * @param addr
862  *   Address of memory.
863  * @param len
864  *   Size of memory.
865  */
866 void
867 mlx5_mr_mem_event_cb(enum rte_mem_event event_type, const void *addr,
868                      size_t len, void *arg __rte_unused)
869 {
870         struct priv *priv;
871         struct mlx5_dev_list *dev_list = &mlx5_shared_data->mem_event_cb_list;
872
873         switch (event_type) {
874         case RTE_MEM_EVENT_FREE:
875                 rte_rwlock_write_lock(&mlx5_shared_data->mem_event_rwlock);
876                 /* Iterate all the existing mlx5 devices. */
877                 LIST_FOREACH(priv, dev_list, mem_event_cb)
878                         mlx5_mr_mem_event_free_cb(ETH_DEV(priv), addr, len);
879                 rte_rwlock_write_unlock(&mlx5_shared_data->mem_event_rwlock);
880                 break;
881         case RTE_MEM_EVENT_ALLOC:
882         default:
883                 break;
884         }
885 }
886
887 /**
888  * Look up address in the global MR cache table. If not found, create a new MR.
889  * Insert the found/created entry to local bottom-half cache table.
890  *
891  * @param dev
892  *   Pointer to Ethernet device.
893  * @param mr_ctrl
894  *   Pointer to per-queue MR control structure.
895  * @param[out] entry
896  *   Pointer to returning MR cache entry, found in the global cache or newly
897  *   created. If failed to create one, this is not written.
898  * @param addr
899  *   Search key.
900  *
901  * @return
902  *   Searched LKey on success, UINT32_MAX on no match.
903  */
904 static uint32_t
905 mlx5_mr_lookup_dev(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
906                    struct mlx5_mr_cache *entry, uintptr_t addr)
907 {
908         struct priv *priv = dev->data->dev_private;
909         struct mlx5_mr_btree *bt = &mr_ctrl->cache_bh;
910         uint16_t idx;
911         uint32_t lkey;
912
913         /* If local cache table is full, try to double it. */
914         if (unlikely(bt->len == bt->size))
915                 mr_btree_expand(bt, bt->size << 1);
916         /* Look up in the global cache. */
917         rte_rwlock_read_lock(&priv->mr.rwlock);
918         lkey = mr_btree_lookup(&priv->mr.cache, &idx, addr);
919         if (lkey != UINT32_MAX) {
920                 /* Found. */
921                 *entry = (*priv->mr.cache.table)[idx];
922                 rte_rwlock_read_unlock(&priv->mr.rwlock);
923                 /*
924                  * Update local cache. Even if it fails, return the found entry
925                  * to update top-half cache. Next time, this entry will be found
926                  * in the global cache.
927                  */
928                 mr_btree_insert(bt, entry);
929                 return lkey;
930         }
931         rte_rwlock_read_unlock(&priv->mr.rwlock);
932         /* First time to see the address? Create a new MR. */
933         lkey = mlx5_mr_create(dev, entry, addr);
934         /*
935          * Update the local cache if successfully created a new global MR. Even
936          * if failed to create one, there's no action to take in this datapath
937          * code. As returning LKey is invalid, this will eventually make HW
938          * fail.
939          */
940         if (lkey != UINT32_MAX)
941                 mr_btree_insert(bt, entry);
942         return lkey;
943 }
944
945 /**
946  * Bottom-half of LKey search on datapath. Firstly search in cache_bh[] and if
947  * misses, search in the global MR cache table and update the new entry to
948  * per-queue local caches.
949  *
950  * @param dev
951  *   Pointer to Ethernet device.
952  * @param mr_ctrl
953  *   Pointer to per-queue MR control structure.
954  * @param addr
955  *   Search key.
956  *
957  * @return
958  *   Searched LKey on success, UINT32_MAX on no match.
959  */
960 static uint32_t
961 mlx5_mr_addr2mr_bh(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
962                    uintptr_t addr)
963 {
964         uint32_t lkey;
965         uint16_t bh_idx = 0;
966         /* Victim in top-half cache to replace with new entry. */
967         struct mlx5_mr_cache *repl = &mr_ctrl->cache[mr_ctrl->head];
968
969         /* Binary-search MR translation table. */
970         lkey = mr_btree_lookup(&mr_ctrl->cache_bh, &bh_idx, addr);
971         /* Update top-half cache. */
972         if (likely(lkey != UINT32_MAX)) {
973                 *repl = (*mr_ctrl->cache_bh.table)[bh_idx];
974         } else {
975                 /*
976                  * If missed in local lookup table, search in the global cache
977                  * and local cache_bh[] will be updated inside if possible.
978                  * Top-half cache entry will also be updated.
979                  */
980                 lkey = mlx5_mr_lookup_dev(dev, mr_ctrl, repl, addr);
981                 if (unlikely(lkey == UINT32_MAX))
982                         return UINT32_MAX;
983         }
984         /* Update the most recently used entry. */
985         mr_ctrl->mru = mr_ctrl->head;
986         /* Point to the next victim, the oldest. */
987         mr_ctrl->head = (mr_ctrl->head + 1) % MLX5_MR_CACHE_N;
988         return lkey;
989 }
990
991 /**
992  * Bottom-half of LKey search on Rx.
993  *
994  * @param rxq
995  *   Pointer to Rx queue structure.
996  * @param addr
997  *   Search key.
998  *
999  * @return
1000  *   Searched LKey on success, UINT32_MAX on no match.
1001  */
1002 uint32_t
1003 mlx5_rx_addr2mr_bh(struct mlx5_rxq_data *rxq, uintptr_t addr)
1004 {
1005         struct mlx5_rxq_ctrl *rxq_ctrl =
1006                 container_of(rxq, struct mlx5_rxq_ctrl, rxq);
1007         struct mlx5_mr_ctrl *mr_ctrl = &rxq->mr_ctrl;
1008         struct priv *priv = rxq_ctrl->priv;
1009
1010         DRV_LOG(DEBUG,
1011                 "Rx queue %u: miss on top-half, mru=%u, head=%u, addr=%p",
1012                 rxq_ctrl->idx, mr_ctrl->mru, mr_ctrl->head, (void *)addr);
1013         return mlx5_mr_addr2mr_bh(ETH_DEV(priv), mr_ctrl, addr);
1014 }
1015
1016 /**
1017  * Bottom-half of LKey search on Tx.
1018  *
1019  * @param txq
1020  *   Pointer to Tx queue structure.
1021  * @param addr
1022  *   Search key.
1023  *
1024  * @return
1025  *   Searched LKey on success, UINT32_MAX on no match.
1026  */
1027 uint32_t
1028 mlx5_tx_addr2mr_bh(struct mlx5_txq_data *txq, uintptr_t addr)
1029 {
1030         struct mlx5_txq_ctrl *txq_ctrl =
1031                 container_of(txq, struct mlx5_txq_ctrl, txq);
1032         struct mlx5_mr_ctrl *mr_ctrl = &txq->mr_ctrl;
1033         struct priv *priv = txq_ctrl->priv;
1034
1035         DRV_LOG(DEBUG,
1036                 "Tx queue %u: miss on top-half, mru=%u, head=%u, addr=%p",
1037                 txq_ctrl->idx, mr_ctrl->mru, mr_ctrl->head, (void *)addr);
1038         return mlx5_mr_addr2mr_bh(ETH_DEV(priv), mr_ctrl, addr);
1039 }
1040
1041 /**
1042  * Flush all of the local cache entries.
1043  *
1044  * @param mr_ctrl
1045  *   Pointer to per-queue MR control structure.
1046  */
1047 void
1048 mlx5_mr_flush_local_cache(struct mlx5_mr_ctrl *mr_ctrl)
1049 {
1050         /* Reset the most-recently-used index. */
1051         mr_ctrl->mru = 0;
1052         /* Reset the linear search array. */
1053         mr_ctrl->head = 0;
1054         memset(mr_ctrl->cache, 0, sizeof(mr_ctrl->cache));
1055         /* Reset the B-tree table. */
1056         mr_ctrl->cache_bh.len = 1;
1057         mr_ctrl->cache_bh.overflow = 0;
1058         /* Update the generation number. */
1059         mr_ctrl->cur_gen = *mr_ctrl->dev_gen_ptr;
1060         DRV_LOG(DEBUG, "mr_ctrl(%p): flushed, cur_gen=%d",
1061                 (void *)mr_ctrl, mr_ctrl->cur_gen);
1062 }
1063
1064 /* Called during rte_mempool_mem_iter() by mlx5_mr_update_mp(). */
1065 static void
1066 mlx5_mr_update_mp_cb(struct rte_mempool *mp __rte_unused, void *opaque,
1067                      struct rte_mempool_memhdr *memhdr,
1068                      unsigned mem_idx __rte_unused)
1069 {
1070         struct mr_update_mp_data *data = opaque;
1071         uint32_t lkey;
1072
1073         /* Stop iteration if failed in the previous walk. */
1074         if (data->ret < 0)
1075                 return;
1076         /* Register address of the chunk and update local caches. */
1077         lkey = mlx5_mr_addr2mr_bh(data->dev, data->mr_ctrl,
1078                                   (uintptr_t)memhdr->addr);
1079         if (lkey == UINT32_MAX)
1080                 data->ret = -1;
1081 }
1082
1083 /**
1084  * Register entire memory chunks in a Mempool.
1085  *
1086  * @param dev
1087  *   Pointer to Ethernet device.
1088  * @param mr_ctrl
1089  *   Pointer to per-queue MR control structure.
1090  * @param mp
1091  *   Pointer to registering Mempool.
1092  *
1093  * @return
1094  *   0 on success, -1 on failure.
1095  */
1096 int
1097 mlx5_mr_update_mp(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
1098                   struct rte_mempool *mp)
1099 {
1100         struct mr_update_mp_data data = {
1101                 .dev = dev,
1102                 .mr_ctrl = mr_ctrl,
1103                 .ret = 0,
1104         };
1105
1106         rte_mempool_mem_iter(mp, mlx5_mr_update_mp_cb, &data);
1107         return data.ret;
1108 }
1109
1110 /**
1111  * Dump all the created MRs and the global cache entries.
1112  *
1113  * @param dev
1114  *   Pointer to Ethernet device.
1115  */
1116 void
1117 mlx5_mr_dump_dev(struct rte_eth_dev *dev __rte_unused)
1118 {
1119 #ifndef NDEBUG
1120         struct priv *priv = dev->data->dev_private;
1121         struct mlx5_mr *mr;
1122         int mr_n = 0;
1123         int chunk_n = 0;
1124
1125         rte_rwlock_read_lock(&priv->mr.rwlock);
1126         /* Iterate all the existing MRs. */
1127         LIST_FOREACH(mr, &priv->mr.mr_list, mr) {
1128                 unsigned int n;
1129
1130                 DEBUG("port %u MR[%u], LKey = 0x%x, ms_n = %u, ms_bmp_n = %u",
1131                       dev->data->port_id, mr_n++,
1132                       rte_cpu_to_be_32(mr->ibv_mr->lkey),
1133                       mr->ms_n, mr->ms_bmp_n);
1134                 if (mr->ms_n == 0)
1135                         continue;
1136                 for (n = 0; n < mr->ms_bmp_n; ) {
1137                         struct mlx5_mr_cache ret = { 0, };
1138
1139                         n = mr_find_next_chunk(mr, &ret, n);
1140                         if (!ret.end)
1141                                 break;
1142                         DEBUG("  chunk[%u], [0x%" PRIxPTR ", 0x%" PRIxPTR ")",
1143                               chunk_n++, ret.start, ret.end);
1144                 }
1145         }
1146         DEBUG("port %u dumping global cache", dev->data->port_id);
1147         mlx5_mr_btree_dump(&priv->mr.cache);
1148         rte_rwlock_read_unlock(&priv->mr.rwlock);
1149 #endif
1150 }
1151
1152 /**
1153  * Release all the created MRs and resources. Remove device from memory callback
1154  * list.
1155  *
1156  * @param dev
1157  *   Pointer to Ethernet device.
1158  */
1159 void
1160 mlx5_mr_release(struct rte_eth_dev *dev)
1161 {
1162         struct priv *priv = dev->data->dev_private;
1163         struct mlx5_mr *mr_next = LIST_FIRST(&priv->mr.mr_list);
1164
1165         /* Remove from memory callback device list. */
1166         rte_rwlock_write_lock(&mlx5_shared_data->mem_event_rwlock);
1167         LIST_REMOVE(priv, mem_event_cb);
1168         rte_rwlock_write_unlock(&mlx5_shared_data->mem_event_rwlock);
1169         if (rte_log_get_level(mlx5_logtype) == RTE_LOG_DEBUG)
1170                 mlx5_mr_dump_dev(dev);
1171         rte_rwlock_write_lock(&priv->mr.rwlock);
1172         /* Detach from MR list and move to free list. */
1173         while (mr_next != NULL) {
1174                 struct mlx5_mr *mr = mr_next;
1175
1176                 mr_next = LIST_NEXT(mr, mr);
1177                 LIST_REMOVE(mr, mr);
1178                 LIST_INSERT_HEAD(&priv->mr.mr_free_list, mr, mr);
1179         }
1180         LIST_INIT(&priv->mr.mr_list);
1181         /* Free global cache. */
1182         mlx5_mr_btree_free(&priv->mr.cache);
1183         rte_rwlock_write_unlock(&priv->mr.rwlock);
1184         /* Free all remaining MRs. */
1185         mlx5_mr_garbage_collect(dev);
1186 }