08105a4430d7fe85f2dbaf25a1e8b74dd7f8cc6b
[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                 DRV_LOG(ERR,
202                         "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         DRV_LOG(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         DRV_LOG(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 static void
240 mlx5_mr_btree_dump(struct mlx5_mr_btree *bt)
241 {
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                 DRV_LOG(DEBUG,
252                         "B-tree(%p)[%u],"
253                         " [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
254                         (void *)bt, idx, entry->start, entry->end, entry->lkey);
255         }
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         DRV_LOG(DEBUG,
580                 "port %u extending %p to [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
581                 " page_sz=0x%" PRIx64 ", ms_n=%u",
582                 dev->data->port_id, (void *)addr,
583                 data.start, data.end, msl->page_sz, ms_n);
584         /* Size of memory for bitmap. */
585         bmp_size = rte_bitmap_get_memory_footprint(ms_n);
586         mr = rte_zmalloc_socket(NULL,
587                                 RTE_ALIGN_CEIL(sizeof(*mr),
588                                                RTE_CACHE_LINE_SIZE) +
589                                 bmp_size,
590                                 RTE_CACHE_LINE_SIZE, msl->socket_id);
591         if (mr == NULL) {
592                 DRV_LOG(WARNING,
593                         "port %u unable to allocate memory for a new MR of"
594                         " address (%p).",
595                         dev->data->port_id, (void *)addr);
596                 rte_errno = ENOMEM;
597                 goto err_nolock;
598         }
599         mr->msl = msl;
600         /*
601          * Save the index of the first memseg and initialize memseg bitmap. To
602          * see if a memseg of ms_idx in the memseg-list is still valid, check:
603          *      rte_bitmap_get(mr->bmp, ms_idx - mr->ms_base_idx)
604          */
605         mr->ms_base_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
606         bmp_mem = RTE_PTR_ALIGN_CEIL(mr + 1, RTE_CACHE_LINE_SIZE);
607         mr->ms_bmp = rte_bitmap_init(ms_n, bmp_mem, bmp_size);
608         if (mr->ms_bmp == NULL) {
609                 DRV_LOG(WARNING,
610                         "port %u unable to initialize bitamp for a new MR of"
611                         " address (%p).",
612                         dev->data->port_id, (void *)addr);
613                 rte_errno = EINVAL;
614                 goto err_nolock;
615         }
616         /*
617          * Should recheck whether the extended contiguous chunk is still valid.
618          * Because memory_hotplug_lock can't be held if there's any memory
619          * related calls in a critical path, resource allocation above can't be
620          * locked. If the memory has been changed at this point, try again with
621          * just single page. If not, go on with the big chunk atomically from
622          * here.
623          */
624         rte_rwlock_read_lock(&mcfg->memory_hotplug_lock);
625         data_re = data;
626         if (len > msl->page_sz &&
627             !rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data_re)) {
628                 DRV_LOG(WARNING,
629                         "port %u unable to find virtually contiguous"
630                         " chunk for address (%p)."
631                         " rte_memseg_contig_walk() failed.",
632                         dev->data->port_id, (void *)addr);
633                 rte_errno = ENXIO;
634                 goto err_memlock;
635         }
636         if (data.start != data_re.start || data.end != data_re.end) {
637                 /*
638                  * The extended contiguous chunk has been changed. Try again
639                  * with single memseg instead.
640                  */
641                 data.start = RTE_ALIGN_FLOOR(addr, msl->page_sz);
642                 data.end = data.start + msl->page_sz;
643                 rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
644                 mr_free(mr);
645                 goto alloc_resources;
646         }
647         assert(data.msl == data_re.msl);
648         rte_rwlock_write_lock(&priv->mr.rwlock);
649         /*
650          * Check the address is really missing. If other thread already created
651          * one or it is not found due to overflow, abort and return.
652          */
653         if (mr_lookup_dev(dev, entry, addr) != UINT32_MAX) {
654                 /*
655                  * Insert to the global cache table. It may fail due to
656                  * low-on-memory. Then, this entry will have to be searched
657                  * here again.
658                  */
659                 mr_btree_insert(&priv->mr.cache, entry);
660                 DRV_LOG(DEBUG,
661                         "port %u found MR for %p on final lookup, abort",
662                         dev->data->port_id, (void *)addr);
663                 rte_rwlock_write_unlock(&priv->mr.rwlock);
664                 rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
665                 /*
666                  * Must be unlocked before calling rte_free() because
667                  * mlx5_mr_mem_event_free_cb() can be called inside.
668                  */
669                 mr_free(mr);
670                 return entry->lkey;
671         }
672         /*
673          * Trim start and end addresses for verbs MR. Set bits for registering
674          * memsegs but exclude already registered ones. Bitmap can be
675          * fragmented.
676          */
677         for (n = 0; n < ms_n; ++n) {
678                 uintptr_t start;
679                 struct mlx5_mr_cache ret = { 0, };
680
681                 start = data_re.start + n * msl->page_sz;
682                 /* Exclude memsegs already registered by other MRs. */
683                 if (mr_lookup_dev(dev, &ret, start) == UINT32_MAX) {
684                         /*
685                          * Start from the first unregistered memseg in the
686                          * extended range.
687                          */
688                         if (ms_idx_shift == -1) {
689                                 mr->ms_base_idx += n;
690                                 data.start = start;
691                                 ms_idx_shift = n;
692                         }
693                         data.end = start + msl->page_sz;
694                         rte_bitmap_set(mr->ms_bmp, n - ms_idx_shift);
695                         ++mr->ms_n;
696                 }
697         }
698         len = data.end - data.start;
699         mr->ms_bmp_n = len / msl->page_sz;
700         assert(ms_idx_shift + mr->ms_bmp_n <= ms_n);
701         /*
702          * Finally create a verbs MR for the memory chunk. ibv_reg_mr() can be
703          * called with holding the memory lock because it doesn't use
704          * mlx5_alloc_buf_extern() which eventually calls rte_malloc_socket()
705          * through mlx5_alloc_verbs_buf().
706          */
707         mr->ibv_mr = mlx5_glue->reg_mr(priv->pd, (void *)data.start, len,
708                                        IBV_ACCESS_LOCAL_WRITE);
709         if (mr->ibv_mr == NULL) {
710                 DRV_LOG(WARNING,
711                         "port %u fail to create a verbs MR for address (%p)",
712                         dev->data->port_id, (void *)addr);
713                 rte_errno = EINVAL;
714                 goto err_mrlock;
715         }
716         assert((uintptr_t)mr->ibv_mr->addr == data.start);
717         assert(mr->ibv_mr->length == len);
718         LIST_INSERT_HEAD(&priv->mr.mr_list, mr, mr);
719         DRV_LOG(DEBUG,
720                 "port %u MR CREATED (%p) for %p:\n"
721                 "  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
722                 " lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
723                 dev->data->port_id, (void *)mr, (void *)addr,
724                 data.start, data.end, rte_cpu_to_be_32(mr->ibv_mr->lkey),
725                 mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
726         /* Insert to the global cache table. */
727         mr_insert_dev_cache(dev, mr);
728         /* Fill in output data. */
729         mr_lookup_dev(dev, entry, addr);
730         /* Lookup can't fail. */
731         assert(entry->lkey != UINT32_MAX);
732         rte_rwlock_write_unlock(&priv->mr.rwlock);
733         rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
734         return entry->lkey;
735 err_mrlock:
736         rte_rwlock_write_unlock(&priv->mr.rwlock);
737 err_memlock:
738         rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
739 err_nolock:
740         /*
741          * In case of error, as this can be called in a datapath, a warning
742          * message per an error is preferable instead. Must be unlocked before
743          * calling rte_free() because mlx5_mr_mem_event_free_cb() can be called
744          * inside.
745          */
746         mr_free(mr);
747         return UINT32_MAX;
748 }
749
750 /**
751  * Rebuild the global B-tree cache of device from the original MR list.
752  *
753  * @param dev
754  *   Pointer to Ethernet device.
755  */
756 static void
757 mr_rebuild_dev_cache(struct rte_eth_dev *dev)
758 {
759         struct priv *priv = dev->data->dev_private;
760         struct mlx5_mr *mr;
761
762         DRV_LOG(DEBUG, "port %u rebuild dev cache[]", dev->data->port_id);
763         /* Flush cache to rebuild. */
764         priv->mr.cache.len = 1;
765         priv->mr.cache.overflow = 0;
766         /* Iterate all the existing MRs. */
767         LIST_FOREACH(mr, &priv->mr.mr_list, mr)
768                 if (mr_insert_dev_cache(dev, mr) < 0)
769                         return;
770 }
771
772 /**
773  * Callback for memory free event. Iterate freed memsegs and check whether it
774  * belongs to an existing MR. If found, clear the bit from bitmap of MR. As a
775  * result, the MR would be fragmented. If it becomes empty, the MR will be freed
776  * later by mlx5_mr_garbage_collect(). Even if this callback is called from a
777  * secondary process, the garbage collector will be called in primary process
778  * as the secondary process can't call mlx5_mr_create().
779  *
780  * The global cache must be rebuilt if there's any change and this event has to
781  * be propagated to dataplane threads to flush the local caches.
782  *
783  * @param dev
784  *   Pointer to Ethernet device.
785  * @param addr
786  *   Address of freed memory.
787  * @param len
788  *   Size of freed memory.
789  */
790 static void
791 mlx5_mr_mem_event_free_cb(struct rte_eth_dev *dev, const void *addr, size_t len)
792 {
793         struct priv *priv = dev->data->dev_private;
794         const struct rte_memseg_list *msl;
795         struct mlx5_mr *mr;
796         int ms_n;
797         int i;
798         int rebuild = 0;
799
800         DRV_LOG(DEBUG, "port %u free callback: addr=%p, len=%zu",
801                 dev->data->port_id, addr, len);
802         msl = rte_mem_virt2memseg_list(addr);
803         /* addr and len must be page-aligned. */
804         assert((uintptr_t)addr == RTE_ALIGN((uintptr_t)addr, msl->page_sz));
805         assert(len == RTE_ALIGN(len, msl->page_sz));
806         ms_n = len / msl->page_sz;
807         rte_rwlock_write_lock(&priv->mr.rwlock);
808         /* Clear bits of freed memsegs from MR. */
809         for (i = 0; i < ms_n; ++i) {
810                 const struct rte_memseg *ms;
811                 struct mlx5_mr_cache entry;
812                 uintptr_t start;
813                 int ms_idx;
814                 uint32_t pos;
815
816                 /* Find MR having this memseg. */
817                 start = (uintptr_t)addr + i * msl->page_sz;
818                 mr = mr_lookup_dev_list(dev, &entry, start);
819                 if (mr == NULL)
820                         continue;
821                 ms = rte_mem_virt2memseg((void *)start, msl);
822                 assert(ms != NULL);
823                 assert(msl->page_sz == ms->hugepage_sz);
824                 ms_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
825                 pos = ms_idx - mr->ms_base_idx;
826                 assert(rte_bitmap_get(mr->ms_bmp, pos));
827                 assert(pos < mr->ms_bmp_n);
828                 DRV_LOG(DEBUG, "port %u MR(%p): clear bitmap[%u] for addr %p",
829                         dev->data->port_id, (void *)mr, pos, (void *)start);
830                 rte_bitmap_clear(mr->ms_bmp, pos);
831                 if (--mr->ms_n == 0) {
832                         LIST_REMOVE(mr, mr);
833                         LIST_INSERT_HEAD(&priv->mr.mr_free_list, mr, mr);
834                         DRV_LOG(DEBUG, "port %u remove MR(%p) from list",
835                                 dev->data->port_id, (void *)mr);
836                 }
837                 /*
838                  * MR is fragmented or will be freed. the global cache must be
839                  * rebuilt.
840                  */
841                 rebuild = 1;
842         }
843         if (rebuild) {
844                 mr_rebuild_dev_cache(dev);
845                 /*
846                  * Flush local caches by propagating invalidation across cores.
847                  * rte_smp_wmb() is enough to synchronize this event. If one of
848                  * freed memsegs is seen by other core, that means the memseg
849                  * has been allocated by allocator, which will come after this
850                  * free call. Therefore, this store instruction (incrementing
851                  * generation below) will be guaranteed to be seen by other core
852                  * before the core sees the newly allocated memory.
853                  */
854                 ++priv->mr.dev_gen;
855                 DRV_LOG(DEBUG, "broadcasting local cache flush, gen=%d",
856                         priv->mr.dev_gen);
857                 rte_smp_wmb();
858         }
859         rte_rwlock_write_unlock(&priv->mr.rwlock);
860         if (rebuild && rte_log_get_level(mlx5_logtype) == RTE_LOG_DEBUG)
861                 mlx5_mr_dump_dev(dev);
862 }
863
864 /**
865  * Callback for memory event. This can be called from both primary and secondary
866  * process.
867  *
868  * @param event_type
869  *   Memory event type.
870  * @param addr
871  *   Address of memory.
872  * @param len
873  *   Size of memory.
874  */
875 void
876 mlx5_mr_mem_event_cb(enum rte_mem_event event_type, const void *addr,
877                      size_t len, void *arg __rte_unused)
878 {
879         struct priv *priv;
880         struct mlx5_dev_list *dev_list = &mlx5_shared_data->mem_event_cb_list;
881
882         switch (event_type) {
883         case RTE_MEM_EVENT_FREE:
884                 rte_rwlock_write_lock(&mlx5_shared_data->mem_event_rwlock);
885                 /* Iterate all the existing mlx5 devices. */
886                 LIST_FOREACH(priv, dev_list, mem_event_cb)
887                         mlx5_mr_mem_event_free_cb(ETH_DEV(priv), addr, len);
888                 rte_rwlock_write_unlock(&mlx5_shared_data->mem_event_rwlock);
889                 break;
890         case RTE_MEM_EVENT_ALLOC:
891         default:
892                 break;
893         }
894 }
895
896 /**
897  * Look up address in the global MR cache table. If not found, create a new MR.
898  * Insert the found/created entry to local bottom-half cache table.
899  *
900  * @param dev
901  *   Pointer to Ethernet device.
902  * @param mr_ctrl
903  *   Pointer to per-queue MR control structure.
904  * @param[out] entry
905  *   Pointer to returning MR cache entry, found in the global cache or newly
906  *   created. If failed to create one, this is not written.
907  * @param addr
908  *   Search key.
909  *
910  * @return
911  *   Searched LKey on success, UINT32_MAX on no match.
912  */
913 static uint32_t
914 mlx5_mr_lookup_dev(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
915                    struct mlx5_mr_cache *entry, uintptr_t addr)
916 {
917         struct priv *priv = dev->data->dev_private;
918         struct mlx5_mr_btree *bt = &mr_ctrl->cache_bh;
919         uint16_t idx;
920         uint32_t lkey;
921
922         /* If local cache table is full, try to double it. */
923         if (unlikely(bt->len == bt->size))
924                 mr_btree_expand(bt, bt->size << 1);
925         /* Look up in the global cache. */
926         rte_rwlock_read_lock(&priv->mr.rwlock);
927         lkey = mr_btree_lookup(&priv->mr.cache, &idx, addr);
928         if (lkey != UINT32_MAX) {
929                 /* Found. */
930                 *entry = (*priv->mr.cache.table)[idx];
931                 rte_rwlock_read_unlock(&priv->mr.rwlock);
932                 /*
933                  * Update local cache. Even if it fails, return the found entry
934                  * to update top-half cache. Next time, this entry will be found
935                  * in the global cache.
936                  */
937                 mr_btree_insert(bt, entry);
938                 return lkey;
939         }
940         rte_rwlock_read_unlock(&priv->mr.rwlock);
941         /* First time to see the address? Create a new MR. */
942         lkey = mlx5_mr_create(dev, entry, addr);
943         /*
944          * Update the local cache if successfully created a new global MR. Even
945          * if failed to create one, there's no action to take in this datapath
946          * code. As returning LKey is invalid, this will eventually make HW
947          * fail.
948          */
949         if (lkey != UINT32_MAX)
950                 mr_btree_insert(bt, entry);
951         return lkey;
952 }
953
954 /**
955  * Bottom-half of LKey search on datapath. Firstly search in cache_bh[] and if
956  * misses, search in the global MR cache table and update the new entry to
957  * per-queue local caches.
958  *
959  * @param dev
960  *   Pointer to Ethernet device.
961  * @param mr_ctrl
962  *   Pointer to per-queue MR control structure.
963  * @param addr
964  *   Search key.
965  *
966  * @return
967  *   Searched LKey on success, UINT32_MAX on no match.
968  */
969 static uint32_t
970 mlx5_mr_addr2mr_bh(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
971                    uintptr_t addr)
972 {
973         uint32_t lkey;
974         uint16_t bh_idx = 0;
975         /* Victim in top-half cache to replace with new entry. */
976         struct mlx5_mr_cache *repl = &mr_ctrl->cache[mr_ctrl->head];
977
978         /* Binary-search MR translation table. */
979         lkey = mr_btree_lookup(&mr_ctrl->cache_bh, &bh_idx, addr);
980         /* Update top-half cache. */
981         if (likely(lkey != UINT32_MAX)) {
982                 *repl = (*mr_ctrl->cache_bh.table)[bh_idx];
983         } else {
984                 /*
985                  * If missed in local lookup table, search in the global cache
986                  * and local cache_bh[] will be updated inside if possible.
987                  * Top-half cache entry will also be updated.
988                  */
989                 lkey = mlx5_mr_lookup_dev(dev, mr_ctrl, repl, addr);
990                 if (unlikely(lkey == UINT32_MAX))
991                         return UINT32_MAX;
992         }
993         /* Update the most recently used entry. */
994         mr_ctrl->mru = mr_ctrl->head;
995         /* Point to the next victim, the oldest. */
996         mr_ctrl->head = (mr_ctrl->head + 1) % MLX5_MR_CACHE_N;
997         return lkey;
998 }
999
1000 /**
1001  * Bottom-half of LKey search on Rx.
1002  *
1003  * @param rxq
1004  *   Pointer to Rx queue structure.
1005  * @param addr
1006  *   Search key.
1007  *
1008  * @return
1009  *   Searched LKey on success, UINT32_MAX on no match.
1010  */
1011 uint32_t
1012 mlx5_rx_addr2mr_bh(struct mlx5_rxq_data *rxq, uintptr_t addr)
1013 {
1014         struct mlx5_rxq_ctrl *rxq_ctrl =
1015                 container_of(rxq, struct mlx5_rxq_ctrl, rxq);
1016         struct mlx5_mr_ctrl *mr_ctrl = &rxq->mr_ctrl;
1017         struct priv *priv = rxq_ctrl->priv;
1018
1019         DRV_LOG(DEBUG,
1020                 "Rx queue %u: miss on top-half, mru=%u, head=%u, addr=%p",
1021                 rxq_ctrl->idx, mr_ctrl->mru, mr_ctrl->head, (void *)addr);
1022         return mlx5_mr_addr2mr_bh(ETH_DEV(priv), mr_ctrl, addr);
1023 }
1024
1025 /**
1026  * Bottom-half of LKey search on Tx.
1027  *
1028  * @param txq
1029  *   Pointer to Tx queue structure.
1030  * @param addr
1031  *   Search key.
1032  *
1033  * @return
1034  *   Searched LKey on success, UINT32_MAX on no match.
1035  */
1036 uint32_t
1037 mlx5_tx_addr2mr_bh(struct mlx5_txq_data *txq, uintptr_t addr)
1038 {
1039         struct mlx5_txq_ctrl *txq_ctrl =
1040                 container_of(txq, struct mlx5_txq_ctrl, txq);
1041         struct mlx5_mr_ctrl *mr_ctrl = &txq->mr_ctrl;
1042         struct priv *priv = txq_ctrl->priv;
1043
1044         DRV_LOG(DEBUG,
1045                 "Tx queue %u: miss on top-half, mru=%u, head=%u, addr=%p",
1046                 txq_ctrl->idx, mr_ctrl->mru, mr_ctrl->head, (void *)addr);
1047         return mlx5_mr_addr2mr_bh(ETH_DEV(priv), mr_ctrl, addr);
1048 }
1049
1050 /**
1051  * Flush all of the local cache entries.
1052  *
1053  * @param mr_ctrl
1054  *   Pointer to per-queue MR control structure.
1055  */
1056 void
1057 mlx5_mr_flush_local_cache(struct mlx5_mr_ctrl *mr_ctrl)
1058 {
1059         /* Reset the most-recently-used index. */
1060         mr_ctrl->mru = 0;
1061         /* Reset the linear search array. */
1062         mr_ctrl->head = 0;
1063         memset(mr_ctrl->cache, 0, sizeof(mr_ctrl->cache));
1064         /* Reset the B-tree table. */
1065         mr_ctrl->cache_bh.len = 1;
1066         mr_ctrl->cache_bh.overflow = 0;
1067         /* Update the generation number. */
1068         mr_ctrl->cur_gen = *mr_ctrl->dev_gen_ptr;
1069         DRV_LOG(DEBUG, "mr_ctrl(%p): flushed, cur_gen=%d",
1070                 (void *)mr_ctrl, mr_ctrl->cur_gen);
1071 }
1072
1073 /* Called during rte_mempool_mem_iter() by mlx5_mr_update_mp(). */
1074 static void
1075 mlx5_mr_update_mp_cb(struct rte_mempool *mp __rte_unused, void *opaque,
1076                      struct rte_mempool_memhdr *memhdr,
1077                      unsigned mem_idx __rte_unused)
1078 {
1079         struct mr_update_mp_data *data = opaque;
1080         uint32_t lkey;
1081
1082         /* Stop iteration if failed in the previous walk. */
1083         if (data->ret < 0)
1084                 return;
1085         /* Register address of the chunk and update local caches. */
1086         lkey = mlx5_mr_addr2mr_bh(data->dev, data->mr_ctrl,
1087                                   (uintptr_t)memhdr->addr);
1088         if (lkey == UINT32_MAX)
1089                 data->ret = -1;
1090 }
1091
1092 /**
1093  * Register entire memory chunks in a Mempool.
1094  *
1095  * @param dev
1096  *   Pointer to Ethernet device.
1097  * @param mr_ctrl
1098  *   Pointer to per-queue MR control structure.
1099  * @param mp
1100  *   Pointer to registering Mempool.
1101  *
1102  * @return
1103  *   0 on success, -1 on failure.
1104  */
1105 int
1106 mlx5_mr_update_mp(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
1107                   struct rte_mempool *mp)
1108 {
1109         struct mr_update_mp_data data = {
1110                 .dev = dev,
1111                 .mr_ctrl = mr_ctrl,
1112                 .ret = 0,
1113         };
1114
1115         rte_mempool_mem_iter(mp, mlx5_mr_update_mp_cb, &data);
1116         return data.ret;
1117 }
1118
1119 /**
1120  * Dump all the created MRs and the global cache entries.
1121  *
1122  * @param dev
1123  *   Pointer to Ethernet device.
1124  */
1125 void
1126 mlx5_mr_dump_dev(struct rte_eth_dev *dev)
1127 {
1128         struct priv *priv = dev->data->dev_private;
1129         struct mlx5_mr *mr;
1130         int mr_n = 0;
1131         int chunk_n = 0;
1132
1133         rte_rwlock_read_lock(&priv->mr.rwlock);
1134         /* Iterate all the existing MRs. */
1135         LIST_FOREACH(mr, &priv->mr.mr_list, mr) {
1136                 unsigned int n;
1137
1138                 DRV_LOG(DEBUG,
1139                         "port %u MR[%u], LKey = 0x%x, ms_n = %u, ms_bmp_n = %u",
1140                         dev->data->port_id, mr_n++,
1141                         rte_cpu_to_be_32(mr->ibv_mr->lkey),
1142                         mr->ms_n, mr->ms_bmp_n);
1143                 if (mr->ms_n == 0)
1144                         continue;
1145                 for (n = 0; n < mr->ms_bmp_n; ) {
1146                         struct mlx5_mr_cache ret = { 0, };
1147
1148                         n = mr_find_next_chunk(mr, &ret, n);
1149                         if (!ret.end)
1150                                 break;
1151                         DRV_LOG(DEBUG,
1152                                 "  chunk[%u], [0x%" PRIxPTR ", 0x%" PRIxPTR ")",
1153                                 chunk_n++, ret.start, ret.end);
1154                 }
1155         }
1156         DRV_LOG(DEBUG, "port %u dumping global cache", dev->data->port_id);
1157         mlx5_mr_btree_dump(&priv->mr.cache);
1158         rte_rwlock_read_unlock(&priv->mr.rwlock);
1159 }
1160
1161 /**
1162  * Release all the created MRs and resources. Remove device from memory callback
1163  * list.
1164  *
1165  * @param dev
1166  *   Pointer to Ethernet device.
1167  */
1168 void
1169 mlx5_mr_release(struct rte_eth_dev *dev)
1170 {
1171         struct priv *priv = dev->data->dev_private;
1172         struct mlx5_mr *mr_next = LIST_FIRST(&priv->mr.mr_list);
1173
1174         /* Remove from memory callback device list. */
1175         rte_rwlock_write_lock(&mlx5_shared_data->mem_event_rwlock);
1176         LIST_REMOVE(priv, mem_event_cb);
1177         rte_rwlock_write_unlock(&mlx5_shared_data->mem_event_rwlock);
1178         if (rte_log_get_level(mlx5_logtype) == RTE_LOG_DEBUG)
1179                 mlx5_mr_dump_dev(dev);
1180         rte_rwlock_write_lock(&priv->mr.rwlock);
1181         /* Detach from MR list and move to free list. */
1182         while (mr_next != NULL) {
1183                 struct mlx5_mr *mr = mr_next;
1184
1185                 mr_next = LIST_NEXT(mr, mr);
1186                 LIST_REMOVE(mr, mr);
1187                 LIST_INSERT_HEAD(&priv->mr.mr_free_list, mr, mr);
1188         }
1189         LIST_INIT(&priv->mr.mr_list);
1190         /* Free global cache. */
1191         mlx5_mr_btree_free(&priv->mr.cache);
1192         rte_rwlock_write_unlock(&priv->mr.rwlock);
1193         /* Free all remaining MRs. */
1194         mlx5_mr_garbage_collect(dev);
1195 }