New upstream version 18.08
[deb_dpdk.git] / drivers / net / mlx4 / mlx4_mr.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2017 6WIND S.A.
3  * Copyright 2017 Mellanox Technologies, Ltd
4  */
5
6 /**
7  * @file
8  * Memory management functions for mlx4 driver.
9  */
10
11 #include <assert.h>
12 #include <errno.h>
13 #include <inttypes.h>
14 #include <stddef.h>
15 #include <stdint.h>
16 #include <string.h>
17
18 /* Verbs headers do not support -pedantic. */
19 #ifdef PEDANTIC
20 #pragma GCC diagnostic ignored "-Wpedantic"
21 #endif
22 #include <infiniband/verbs.h>
23 #ifdef PEDANTIC
24 #pragma GCC diagnostic error "-Wpedantic"
25 #endif
26
27 #include <rte_branch_prediction.h>
28 #include <rte_common.h>
29 #include <rte_errno.h>
30 #include <rte_malloc.h>
31 #include <rte_memory.h>
32 #include <rte_mempool.h>
33 #include <rte_rwlock.h>
34
35 #include "mlx4_glue.h"
36 #include "mlx4_mr.h"
37 #include "mlx4_rxtx.h"
38 #include "mlx4_utils.h"
39
40 struct mr_find_contig_memsegs_data {
41         uintptr_t addr;
42         uintptr_t start;
43         uintptr_t end;
44         const struct rte_memseg_list *msl;
45 };
46
47 struct mr_update_mp_data {
48         struct rte_eth_dev *dev;
49         struct mlx4_mr_ctrl *mr_ctrl;
50         int ret;
51 };
52
53 /**
54  * Expand B-tree table to a given size. Can't be called with holding
55  * memory_hotplug_lock or priv->mr.rwlock due to rte_realloc().
56  *
57  * @param bt
58  *   Pointer to B-tree structure.
59  * @param n
60  *   Number of entries for expansion.
61  *
62  * @return
63  *   0 on success, -1 on failure.
64  */
65 static int
66 mr_btree_expand(struct mlx4_mr_btree *bt, int n)
67 {
68         void *mem;
69         int ret = 0;
70
71         if (n <= bt->size)
72                 return ret;
73         /*
74          * Downside of directly using rte_realloc() is that SOCKET_ID_ANY is
75          * used inside if there's no room to expand. Because this is a quite
76          * rare case and a part of very slow path, it is very acceptable.
77          * Initially cache_bh[] will be given practically enough space and once
78          * it is expanded, expansion wouldn't be needed again ever.
79          */
80         mem = rte_realloc(bt->table, n * sizeof(struct mlx4_mr_cache), 0);
81         if (mem == NULL) {
82                 /* Not an error, B-tree search will be skipped. */
83                 WARN("failed to expand MR B-tree (%p) table", (void *)bt);
84                 ret = -1;
85         } else {
86                 DEBUG("expanded MR B-tree table (size=%u)", n);
87                 bt->table = mem;
88                 bt->size = n;
89         }
90         return ret;
91 }
92
93 /**
94  * Look up LKey from given B-tree lookup table, store the last index and return
95  * searched LKey.
96  *
97  * @param bt
98  *   Pointer to B-tree structure.
99  * @param[out] idx
100  *   Pointer to index. Even on search failure, returns index where it stops
101  *   searching so that index can be used when inserting a new entry.
102  * @param addr
103  *   Search key.
104  *
105  * @return
106  *   Searched LKey on success, UINT32_MAX on no match.
107  */
108 static uint32_t
109 mr_btree_lookup(struct mlx4_mr_btree *bt, uint16_t *idx, uintptr_t addr)
110 {
111         struct mlx4_mr_cache *lkp_tbl;
112         uint16_t n;
113         uint16_t base = 0;
114
115         assert(bt != NULL);
116         lkp_tbl = *bt->table;
117         n = bt->len;
118         /* First entry must be NULL for comparison. */
119         assert(bt->len > 0 || (lkp_tbl[0].start == 0 &&
120                                lkp_tbl[0].lkey == UINT32_MAX));
121         /* Binary search. */
122         do {
123                 register uint16_t delta = n >> 1;
124
125                 if (addr < lkp_tbl[base + delta].start) {
126                         n = delta;
127                 } else {
128                         base += delta;
129                         n -= delta;
130                 }
131         } while (n > 1);
132         assert(addr >= lkp_tbl[base].start);
133         *idx = base;
134         if (addr < lkp_tbl[base].end)
135                 return lkp_tbl[base].lkey;
136         /* Not found. */
137         return UINT32_MAX;
138 }
139
140 /**
141  * Insert an entry to B-tree lookup table.
142  *
143  * @param bt
144  *   Pointer to B-tree structure.
145  * @param entry
146  *   Pointer to new entry to insert.
147  *
148  * @return
149  *   0 on success, -1 on failure.
150  */
151 static int
152 mr_btree_insert(struct mlx4_mr_btree *bt, struct mlx4_mr_cache *entry)
153 {
154         struct mlx4_mr_cache *lkp_tbl;
155         uint16_t idx = 0;
156         size_t shift;
157
158         assert(bt != NULL);
159         assert(bt->len <= bt->size);
160         assert(bt->len > 0);
161         lkp_tbl = *bt->table;
162         /* Find out the slot for insertion. */
163         if (mr_btree_lookup(bt, &idx, entry->start) != UINT32_MAX) {
164                 DEBUG("abort insertion to B-tree(%p): already exist at"
165                       " idx=%u [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
166                       (void *)bt, idx, entry->start, entry->end, entry->lkey);
167                 /* Already exist, return. */
168                 return 0;
169         }
170         /* If table is full, return error. */
171         if (unlikely(bt->len == bt->size)) {
172                 bt->overflow = 1;
173                 return -1;
174         }
175         /* Insert entry. */
176         ++idx;
177         shift = (bt->len - idx) * sizeof(struct mlx4_mr_cache);
178         if (shift)
179                 memmove(&lkp_tbl[idx + 1], &lkp_tbl[idx], shift);
180         lkp_tbl[idx] = *entry;
181         bt->len++;
182         DEBUG("inserted B-tree(%p)[%u],"
183               " [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
184               (void *)bt, idx, entry->start, entry->end, entry->lkey);
185         return 0;
186 }
187
188 /**
189  * Initialize B-tree and allocate memory for lookup table.
190  *
191  * @param bt
192  *   Pointer to B-tree structure.
193  * @param n
194  *   Number of entries to allocate.
195  * @param socket
196  *   NUMA socket on which memory must be allocated.
197  *
198  * @return
199  *   0 on success, a negative errno value otherwise and rte_errno is set.
200  */
201 int
202 mlx4_mr_btree_init(struct mlx4_mr_btree *bt, int n, int socket)
203 {
204         if (bt == NULL) {
205                 rte_errno = EINVAL;
206                 return -rte_errno;
207         }
208         memset(bt, 0, sizeof(*bt));
209         bt->table = rte_calloc_socket("B-tree table",
210                                       n, sizeof(struct mlx4_mr_cache),
211                                       0, socket);
212         if (bt->table == NULL) {
213                 rte_errno = ENOMEM;
214                 ERROR("failed to allocate memory for btree cache on socket %d",
215                       socket);
216                 return -rte_errno;
217         }
218         bt->size = n;
219         /* First entry must be NULL for binary search. */
220         (*bt->table)[bt->len++] = (struct mlx4_mr_cache) {
221                 .lkey = UINT32_MAX,
222         };
223         DEBUG("initialized B-tree %p with table %p",
224               (void *)bt, (void *)bt->table);
225         return 0;
226 }
227
228 /**
229  * Free B-tree resources.
230  *
231  * @param bt
232  *   Pointer to B-tree structure.
233  */
234 void
235 mlx4_mr_btree_free(struct mlx4_mr_btree *bt)
236 {
237         if (bt == NULL)
238                 return;
239         DEBUG("freeing B-tree %p with table %p", (void *)bt, (void *)bt->table);
240         rte_free(bt->table);
241         memset(bt, 0, sizeof(*bt));
242 }
243
244 #ifndef NDEBUG
245 /**
246  * Dump all the entries in a B-tree
247  *
248  * @param bt
249  *   Pointer to B-tree structure.
250  */
251 void
252 mlx4_mr_btree_dump(struct mlx4_mr_btree *bt)
253 {
254         int idx;
255         struct mlx4_mr_cache *lkp_tbl;
256
257         if (bt == NULL)
258                 return;
259         lkp_tbl = *bt->table;
260         for (idx = 0; idx < bt->len; ++idx) {
261                 struct mlx4_mr_cache *entry = &lkp_tbl[idx];
262
263                 DEBUG("B-tree(%p)[%u],"
264                       " [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
265                       (void *)bt, idx, entry->start, entry->end, entry->lkey);
266         }
267 }
268 #endif
269
270 /**
271  * Find virtually contiguous memory chunk in a given MR.
272  *
273  * @param dev
274  *   Pointer to MR structure.
275  * @param[out] entry
276  *   Pointer to returning MR cache entry. If not found, this will not be
277  *   updated.
278  * @param start_idx
279  *   Start index of the memseg bitmap.
280  *
281  * @return
282  *   Next index to go on lookup.
283  */
284 static int
285 mr_find_next_chunk(struct mlx4_mr *mr, struct mlx4_mr_cache *entry,
286                    int base_idx)
287 {
288         uintptr_t start = 0;
289         uintptr_t end = 0;
290         uint32_t idx = 0;
291
292         for (idx = base_idx; idx < mr->ms_bmp_n; ++idx) {
293                 if (rte_bitmap_get(mr->ms_bmp, idx)) {
294                         const struct rte_memseg_list *msl;
295                         const struct rte_memseg *ms;
296
297                         msl = mr->msl;
298                         ms = rte_fbarray_get(&msl->memseg_arr,
299                                              mr->ms_base_idx + idx);
300                         assert(msl->page_sz == ms->hugepage_sz);
301                         if (!start)
302                                 start = ms->addr_64;
303                         end = ms->addr_64 + ms->hugepage_sz;
304                 } else if (start) {
305                         /* Passed the end of a fragment. */
306                         break;
307                 }
308         }
309         if (start) {
310                 /* Found one chunk. */
311                 entry->start = start;
312                 entry->end = end;
313                 entry->lkey = rte_cpu_to_be_32(mr->ibv_mr->lkey);
314         }
315         return idx;
316 }
317
318 /**
319  * Insert a MR to the global B-tree cache. It may fail due to low-on-memory.
320  * Then, this entry will have to be searched by mr_lookup_dev_list() in
321  * mlx4_mr_create() on miss.
322  *
323  * @param dev
324  *   Pointer to Ethernet device.
325  * @param mr
326  *   Pointer to MR to insert.
327  *
328  * @return
329  *   0 on success, -1 on failure.
330  */
331 static int
332 mr_insert_dev_cache(struct rte_eth_dev *dev, struct mlx4_mr *mr)
333 {
334         struct priv *priv = dev->data->dev_private;
335         unsigned int n;
336
337         DEBUG("port %u inserting MR(%p) to global cache",
338               dev->data->port_id, (void *)mr);
339         for (n = 0; n < mr->ms_bmp_n; ) {
340                 struct mlx4_mr_cache entry = { 0, };
341
342                 /* Find a contiguous chunk and advance the index. */
343                 n = mr_find_next_chunk(mr, &entry, n);
344                 if (!entry.end)
345                         break;
346                 if (mr_btree_insert(&priv->mr.cache, &entry) < 0) {
347                         /*
348                          * Overflowed, but the global table cannot be expanded
349                          * because of deadlock.
350                          */
351                         return -1;
352                 }
353         }
354         return 0;
355 }
356
357 /**
358  * Look up address in the original global MR list.
359  *
360  * @param dev
361  *   Pointer to Ethernet device.
362  * @param[out] entry
363  *   Pointer to returning MR cache entry. If no match, this will not be updated.
364  * @param addr
365  *   Search key.
366  *
367  * @return
368  *   Found MR on match, NULL otherwise.
369  */
370 static struct mlx4_mr *
371 mr_lookup_dev_list(struct rte_eth_dev *dev, struct mlx4_mr_cache *entry,
372                    uintptr_t addr)
373 {
374         struct priv *priv = dev->data->dev_private;
375         struct mlx4_mr *mr;
376
377         /* Iterate all the existing MRs. */
378         LIST_FOREACH(mr, &priv->mr.mr_list, mr) {
379                 unsigned int n;
380
381                 if (mr->ms_n == 0)
382                         continue;
383                 for (n = 0; n < mr->ms_bmp_n; ) {
384                         struct mlx4_mr_cache ret = { 0, };
385
386                         n = mr_find_next_chunk(mr, &ret, n);
387                         if (addr >= ret.start && addr < ret.end) {
388                                 /* Found. */
389                                 *entry = ret;
390                                 return mr;
391                         }
392                 }
393         }
394         return NULL;
395 }
396
397 /**
398  * Look up address on device.
399  *
400  * @param dev
401  *   Pointer to Ethernet device.
402  * @param[out] entry
403  *   Pointer to returning MR cache entry. If no match, this will not be updated.
404  * @param addr
405  *   Search key.
406  *
407  * @return
408  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
409  */
410 static uint32_t
411 mr_lookup_dev(struct rte_eth_dev *dev, struct mlx4_mr_cache *entry,
412               uintptr_t addr)
413 {
414         struct priv *priv = dev->data->dev_private;
415         uint16_t idx;
416         uint32_t lkey = UINT32_MAX;
417         struct mlx4_mr *mr;
418
419         /*
420          * If the global cache has overflowed since it failed to expand the
421          * B-tree table, it can't have all the existing MRs. Then, the address
422          * has to be searched by traversing the original MR list instead, which
423          * is very slow path. Otherwise, the global cache is all inclusive.
424          */
425         if (!unlikely(priv->mr.cache.overflow)) {
426                 lkey = mr_btree_lookup(&priv->mr.cache, &idx, addr);
427                 if (lkey != UINT32_MAX)
428                         *entry = (*priv->mr.cache.table)[idx];
429         } else {
430                 /* Falling back to the slowest path. */
431                 mr = mr_lookup_dev_list(dev, entry, addr);
432                 if (mr != NULL)
433                         lkey = entry->lkey;
434         }
435         assert(lkey == UINT32_MAX || (addr >= entry->start &&
436                                       addr < entry->end));
437         return lkey;
438 }
439
440 /**
441  * Free MR resources. MR lock must not be held to avoid a deadlock. rte_free()
442  * can raise memory free event and the callback function will spin on the lock.
443  *
444  * @param mr
445  *   Pointer to MR to free.
446  */
447 static void
448 mr_free(struct mlx4_mr *mr)
449 {
450         if (mr == NULL)
451                 return;
452         DEBUG("freeing MR(%p):", (void *)mr);
453         if (mr->ibv_mr != NULL)
454                 claim_zero(mlx4_glue->dereg_mr(mr->ibv_mr));
455         if (mr->ms_bmp != NULL)
456                 rte_bitmap_free(mr->ms_bmp);
457         rte_free(mr);
458 }
459
460 /**
461  * Releass resources of detached MR having no online entry.
462  *
463  * @param dev
464  *   Pointer to Ethernet device.
465  */
466 static void
467 mlx4_mr_garbage_collect(struct rte_eth_dev *dev)
468 {
469         struct priv *priv = dev->data->dev_private;
470         struct mlx4_mr *mr_next;
471         struct mlx4_mr_list free_list = LIST_HEAD_INITIALIZER(free_list);
472
473         /*
474          * MR can't be freed with holding the lock because rte_free() could call
475          * memory free callback function. This will be a deadlock situation.
476          */
477         rte_rwlock_write_lock(&priv->mr.rwlock);
478         /* Detach the whole free list and release it after unlocking. */
479         free_list = priv->mr.mr_free_list;
480         LIST_INIT(&priv->mr.mr_free_list);
481         rte_rwlock_write_unlock(&priv->mr.rwlock);
482         /* Release resources. */
483         mr_next = LIST_FIRST(&free_list);
484         while (mr_next != NULL) {
485                 struct mlx4_mr *mr = mr_next;
486
487                 mr_next = LIST_NEXT(mr, mr);
488                 mr_free(mr);
489         }
490 }
491
492 /* Called during rte_memseg_contig_walk() by mlx4_mr_create(). */
493 static int
494 mr_find_contig_memsegs_cb(const struct rte_memseg_list *msl,
495                           const struct rte_memseg *ms, size_t len, void *arg)
496 {
497         struct mr_find_contig_memsegs_data *data = arg;
498
499         if (data->addr < ms->addr_64 || data->addr >= ms->addr_64 + len)
500                 return 0;
501         /* Found, save it and stop walking. */
502         data->start = ms->addr_64;
503         data->end = ms->addr_64 + len;
504         data->msl = msl;
505         return 1;
506 }
507
508 /**
509  * Create a new global Memroy Region (MR) for a missing virtual address.
510  * Register entire virtually contiguous memory chunk around the address.
511  *
512  * @param dev
513  *   Pointer to Ethernet device.
514  * @param[out] entry
515  *   Pointer to returning MR cache entry, found in the global cache or newly
516  *   created. If failed to create one, this will not be updated.
517  * @param addr
518  *   Target virtual address to register.
519  *
520  * @return
521  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
522  */
523 static uint32_t
524 mlx4_mr_create(struct rte_eth_dev *dev, struct mlx4_mr_cache *entry,
525                uintptr_t addr)
526 {
527         struct priv *priv = dev->data->dev_private;
528         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
529         const struct rte_memseg_list *msl;
530         const struct rte_memseg *ms;
531         struct mlx4_mr *mr = NULL;
532         size_t len;
533         uint32_t ms_n;
534         uint32_t bmp_size;
535         void *bmp_mem;
536         int ms_idx_shift = -1;
537         unsigned int n;
538         struct mr_find_contig_memsegs_data data = {
539                 .addr = addr,
540         };
541         struct mr_find_contig_memsegs_data data_re;
542
543         DEBUG("port %u creating a MR using address (%p)",
544               dev->data->port_id, (void *)addr);
545         /*
546          * Release detached MRs if any. This can't be called with holding either
547          * memory_hotplug_lock or priv->mr.rwlock. MRs on the free list have
548          * been detached by the memory free event but it couldn't be released
549          * inside the callback due to deadlock. As a result, releasing resources
550          * is quite opportunistic.
551          */
552         mlx4_mr_garbage_collect(dev);
553         /*
554          * Find out a contiguous virtual address chunk in use, to which the
555          * given address belongs, in order to register maximum range. In the
556          * best case where mempools are not dynamically recreated and
557          * '--socket-mem' is speicified as an EAL option, it is very likely to
558          * have only one MR(LKey) per a socket and per a hugepage-size even
559          * though the system memory is highly fragmented.
560          */
561         if (!rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data)) {
562                 WARN("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                 WARN("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                 WARN("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                 WARN("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                  * mlx4_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 mlx4_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          * mlx4_alloc_buf_extern() which eventually calls rte_malloc_socket()
700          * through mlx4_alloc_verbs_buf().
701          */
702         mr->ibv_mr = mlx4_glue->reg_mr(priv->pd, (void *)data.start, len,
703                                        IBV_ACCESS_LOCAL_WRITE);
704         if (mr->ibv_mr == NULL) {
705                 WARN("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 mlx4_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 mlx4_mr *mr;
754
755         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 mlx4_mr_garbage_collect().
770  *
771  * The global cache must be rebuilt if there's any change and this event has to
772  * be propagated to dataplane threads to flush the local caches.
773  *
774  * @param dev
775  *   Pointer to Ethernet device.
776  * @param addr
777  *   Address of freed memory.
778  * @param len
779  *   Size of freed memory.
780  */
781 static void
782 mlx4_mr_mem_event_free_cb(struct rte_eth_dev *dev, const void *addr, size_t len)
783 {
784         struct priv *priv = dev->data->dev_private;
785         const struct rte_memseg_list *msl;
786         struct mlx4_mr *mr;
787         int ms_n;
788         int i;
789         int rebuild = 0;
790
791         DEBUG("port %u free callback: addr=%p, len=%zu",
792               dev->data->port_id, addr, len);
793         msl = rte_mem_virt2memseg_list(addr);
794         /* addr and len must be page-aligned. */
795         assert((uintptr_t)addr == RTE_ALIGN((uintptr_t)addr, msl->page_sz));
796         assert(len == RTE_ALIGN(len, msl->page_sz));
797         ms_n = len / msl->page_sz;
798         rte_rwlock_write_lock(&priv->mr.rwlock);
799         /* Clear bits of freed memsegs from MR. */
800         for (i = 0; i < ms_n; ++i) {
801                 const struct rte_memseg *ms;
802                 struct mlx4_mr_cache entry;
803                 uintptr_t start;
804                 int ms_idx;
805                 uint32_t pos;
806
807                 /* Find MR having this memseg. */
808                 start = (uintptr_t)addr + i * msl->page_sz;
809                 mr = mr_lookup_dev_list(dev, &entry, start);
810                 if (mr == NULL)
811                         continue;
812                 ms = rte_mem_virt2memseg((void *)start, msl);
813                 assert(ms != NULL);
814                 assert(msl->page_sz == ms->hugepage_sz);
815                 ms_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
816                 pos = ms_idx - mr->ms_base_idx;
817                 assert(rte_bitmap_get(mr->ms_bmp, pos));
818                 assert(pos < mr->ms_bmp_n);
819                 DEBUG("port %u MR(%p): clear bitmap[%u] for addr %p",
820                       dev->data->port_id, (void *)mr, pos, (void *)start);
821                 rte_bitmap_clear(mr->ms_bmp, pos);
822                 if (--mr->ms_n == 0) {
823                         LIST_REMOVE(mr, mr);
824                         LIST_INSERT_HEAD(&priv->mr.mr_free_list, mr, mr);
825                         DEBUG("port %u remove MR(%p) from list",
826                               dev->data->port_id, (void *)mr);
827                 }
828                 /*
829                  * MR is fragmented or will be freed. the global cache must be
830                  * rebuilt.
831                  */
832                 rebuild = 1;
833         }
834         if (rebuild) {
835                 mr_rebuild_dev_cache(dev);
836                 /*
837                  * Flush local caches by propagating invalidation across cores.
838                  * rte_smp_wmb() is enough to synchronize this event. If one of
839                  * freed memsegs is seen by other core, that means the memseg
840                  * has been allocated by allocator, which will come after this
841                  * free call. Therefore, this store instruction (incrementing
842                  * generation below) will be guaranteed to be seen by other core
843                  * before the core sees the newly allocated memory.
844                  */
845                 ++priv->mr.dev_gen;
846                 DEBUG("broadcasting local cache flush, gen=%d",
847                       priv->mr.dev_gen);
848                 rte_smp_wmb();
849         }
850         rte_rwlock_write_unlock(&priv->mr.rwlock);
851 #ifndef NDEBUG
852         if (rebuild)
853                 mlx4_mr_dump_dev(dev);
854 #endif
855 }
856
857 /**
858  * Callback for memory event.
859  *
860  * @param event_type
861  *   Memory event type.
862  * @param addr
863  *   Address of memory.
864  * @param len
865  *   Size of memory.
866  */
867 void
868 mlx4_mr_mem_event_cb(enum rte_mem_event event_type, const void *addr,
869                      size_t len, void *arg __rte_unused)
870 {
871         struct priv *priv;
872
873         switch (event_type) {
874         case RTE_MEM_EVENT_FREE:
875                 rte_rwlock_read_lock(&mlx4_mem_event_rwlock);
876                 /* Iterate all the existing mlx4 devices. */
877                 LIST_FOREACH(priv, &mlx4_mem_event_cb_list, mem_event_cb)
878                         mlx4_mr_mem_event_free_cb(priv->dev, addr, len);
879                 rte_rwlock_read_unlock(&mlx4_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 mlx4_mr_lookup_dev(struct rte_eth_dev *dev, struct mlx4_mr_ctrl *mr_ctrl,
906                    struct mlx4_mr_cache *entry, uintptr_t addr)
907 {
908         struct priv *priv = dev->data->dev_private;
909         struct mlx4_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 = mlx4_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 mlx4_mr_addr2mr_bh(struct rte_eth_dev *dev, struct mlx4_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 mlx4_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 = mlx4_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) % MLX4_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 mlx4_rx_addr2mr_bh(struct rxq *rxq, uintptr_t addr)
1004 {
1005         struct mlx4_mr_ctrl *mr_ctrl = &rxq->mr_ctrl;
1006         struct priv *priv = rxq->priv;
1007
1008         DEBUG("Rx queue %u: miss on top-half, mru=%u, head=%u, addr=%p",
1009               rxq->stats.idx, mr_ctrl->mru, mr_ctrl->head, (void *)addr);
1010         return mlx4_mr_addr2mr_bh(priv->dev, mr_ctrl, addr);
1011 }
1012
1013 /**
1014  * Bottom-half of LKey search on Tx.
1015  *
1016  * @param txq
1017  *   Pointer to Tx queue structure.
1018  * @param addr
1019  *   Search key.
1020  *
1021  * @return
1022  *   Searched LKey on success, UINT32_MAX on no match.
1023  */
1024 uint32_t
1025 mlx4_tx_addr2mr_bh(struct txq *txq, uintptr_t addr)
1026 {
1027         struct mlx4_mr_ctrl *mr_ctrl = &txq->mr_ctrl;
1028         struct priv *priv = txq->priv;
1029
1030         DEBUG("Tx queue %u: miss on top-half, mru=%u, head=%u, addr=%p",
1031               txq->stats.idx, mr_ctrl->mru, mr_ctrl->head, (void *)addr);
1032         return mlx4_mr_addr2mr_bh(priv->dev, mr_ctrl, addr);
1033 }
1034
1035 /**
1036  * Flush all of the local cache entries.
1037  *
1038  * @param mr_ctrl
1039  *   Pointer to per-queue MR control structure.
1040  */
1041 void
1042 mlx4_mr_flush_local_cache(struct mlx4_mr_ctrl *mr_ctrl)
1043 {
1044         /* Reset the most-recently-used index. */
1045         mr_ctrl->mru = 0;
1046         /* Reset the linear search array. */
1047         mr_ctrl->head = 0;
1048         memset(mr_ctrl->cache, 0, sizeof(mr_ctrl->cache));
1049         /* Reset the B-tree table. */
1050         mr_ctrl->cache_bh.len = 1;
1051         mr_ctrl->cache_bh.overflow = 0;
1052         /* Update the generation number. */
1053         mr_ctrl->cur_gen = *mr_ctrl->dev_gen_ptr;
1054         DEBUG("mr_ctrl(%p): flushed, cur_gen=%d",
1055               (void *)mr_ctrl, mr_ctrl->cur_gen);
1056 }
1057
1058 /* Called during rte_mempool_mem_iter() by mlx4_mr_update_mp(). */
1059 static void
1060 mlx4_mr_update_mp_cb(struct rte_mempool *mp __rte_unused, void *opaque,
1061                      struct rte_mempool_memhdr *memhdr,
1062                      unsigned mem_idx __rte_unused)
1063 {
1064         struct mr_update_mp_data *data = opaque;
1065         uint32_t lkey;
1066
1067         /* Stop iteration if failed in the previous walk. */
1068         if (data->ret < 0)
1069                 return;
1070         /* Register address of the chunk and update local caches. */
1071         lkey = mlx4_mr_addr2mr_bh(data->dev, data->mr_ctrl,
1072                                   (uintptr_t)memhdr->addr);
1073         if (lkey == UINT32_MAX)
1074                 data->ret = -1;
1075 }
1076
1077 /**
1078  * Register entire memory chunks in a Mempool.
1079  *
1080  * @param dev
1081  *   Pointer to Ethernet device.
1082  * @param mr_ctrl
1083  *   Pointer to per-queue MR control structure.
1084  * @param mp
1085  *   Pointer to registering Mempool.
1086  *
1087  * @return
1088  *   0 on success, -1 on failure.
1089  */
1090 int
1091 mlx4_mr_update_mp(struct rte_eth_dev *dev, struct mlx4_mr_ctrl *mr_ctrl,
1092                   struct rte_mempool *mp)
1093 {
1094         struct mr_update_mp_data data = {
1095                 .dev = dev,
1096                 .mr_ctrl = mr_ctrl,
1097                 .ret = 0,
1098         };
1099
1100         rte_mempool_mem_iter(mp, mlx4_mr_update_mp_cb, &data);
1101         return data.ret;
1102 }
1103
1104 #ifndef NDEBUG
1105 /**
1106  * Dump all the created MRs and the global cache entries.
1107  *
1108  * @param dev
1109  *   Pointer to Ethernet device.
1110  */
1111 void
1112 mlx4_mr_dump_dev(struct rte_eth_dev *dev)
1113 {
1114         struct priv *priv = dev->data->dev_private;
1115         struct mlx4_mr *mr;
1116         int mr_n = 0;
1117         int chunk_n = 0;
1118
1119         rte_rwlock_read_lock(&priv->mr.rwlock);
1120         /* Iterate all the existing MRs. */
1121         LIST_FOREACH(mr, &priv->mr.mr_list, mr) {
1122                 unsigned int n;
1123
1124                 DEBUG("port %u MR[%u], LKey = 0x%x, ms_n = %u, ms_bmp_n = %u",
1125                       dev->data->port_id, mr_n++,
1126                       rte_cpu_to_be_32(mr->ibv_mr->lkey),
1127                       mr->ms_n, mr->ms_bmp_n);
1128                 if (mr->ms_n == 0)
1129                         continue;
1130                 for (n = 0; n < mr->ms_bmp_n; ) {
1131                         struct mlx4_mr_cache ret = { 0, };
1132
1133                         n = mr_find_next_chunk(mr, &ret, n);
1134                         if (!ret.end)
1135                                 break;
1136                         DEBUG("  chunk[%u], [0x%" PRIxPTR ", 0x%" PRIxPTR ")",
1137                               chunk_n++, ret.start, ret.end);
1138                 }
1139         }
1140         DEBUG("port %u dumping global cache", dev->data->port_id);
1141         mlx4_mr_btree_dump(&priv->mr.cache);
1142         rte_rwlock_read_unlock(&priv->mr.rwlock);
1143 }
1144 #endif
1145
1146 /**
1147  * Release all the created MRs and resources. Remove device from memory callback
1148  * list.
1149  *
1150  * @param dev
1151  *   Pointer to Ethernet device.
1152  */
1153 void
1154 mlx4_mr_release(struct rte_eth_dev *dev)
1155 {
1156         struct priv *priv = dev->data->dev_private;
1157         struct mlx4_mr *mr_next = LIST_FIRST(&priv->mr.mr_list);
1158
1159         /* Remove from memory callback device list. */
1160         rte_rwlock_write_lock(&mlx4_mem_event_rwlock);
1161         LIST_REMOVE(priv, mem_event_cb);
1162         rte_rwlock_write_unlock(&mlx4_mem_event_rwlock);
1163 #ifndef NDEBUG
1164         mlx4_mr_dump_dev(dev);
1165 #endif
1166         rte_rwlock_write_lock(&priv->mr.rwlock);
1167         /* Detach from MR list and move to free list. */
1168         while (mr_next != NULL) {
1169                 struct mlx4_mr *mr = mr_next;
1170
1171                 mr_next = LIST_NEXT(mr, mr);
1172                 LIST_REMOVE(mr, mr);
1173                 LIST_INSERT_HEAD(&priv->mr.mr_free_list, mr, mr);
1174         }
1175         LIST_INIT(&priv->mr.mr_list);
1176         /* Free global cache. */
1177         mlx4_mr_btree_free(&priv->mr.cache);
1178         rte_rwlock_write_unlock(&priv->mr.rwlock);
1179         /* Free all remaining MRs. */
1180         mlx4_mr_garbage_collect(dev);
1181 }