net/mlx5: support PCI device DMA map and unmap
[dpdk.git] / drivers / net / mlx5 / mlx5_mr.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2016 6WIND S.A.
3  * Copyright 2016 Mellanox Technologies, Ltd
4  */
5
6 #ifdef PEDANTIC
7 #pragma GCC diagnostic ignored "-Wpedantic"
8 #endif
9 #include <infiniband/verbs.h>
10 #ifdef PEDANTIC
11 #pragma GCC diagnostic error "-Wpedantic"
12 #endif
13
14 #include <rte_mempool.h>
15 #include <rte_malloc.h>
16 #include <rte_rwlock.h>
17 #include <rte_bus_pci.h>
18
19 #include "mlx5.h"
20 #include "mlx5_mr.h"
21 #include "mlx5_rxtx.h"
22 #include "mlx5_glue.h"
23
24 struct mr_find_contig_memsegs_data {
25         uintptr_t addr;
26         uintptr_t start;
27         uintptr_t end;
28         const struct rte_memseg_list *msl;
29 };
30
31 struct mr_update_mp_data {
32         struct rte_eth_dev *dev;
33         struct mlx5_mr_ctrl *mr_ctrl;
34         int ret;
35 };
36
37 /**
38  * Expand B-tree table to a given size. Can't be called with holding
39  * memory_hotplug_lock or priv->mr.rwlock due to rte_realloc().
40  *
41  * @param bt
42  *   Pointer to B-tree structure.
43  * @param n
44  *   Number of entries for expansion.
45  *
46  * @return
47  *   0 on success, -1 on failure.
48  */
49 static int
50 mr_btree_expand(struct mlx5_mr_btree *bt, int n)
51 {
52         void *mem;
53         int ret = 0;
54
55         if (n <= bt->size)
56                 return ret;
57         /*
58          * Downside of directly using rte_realloc() is that SOCKET_ID_ANY is
59          * used inside if there's no room to expand. Because this is a quite
60          * rare case and a part of very slow path, it is very acceptable.
61          * Initially cache_bh[] will be given practically enough space and once
62          * it is expanded, expansion wouldn't be needed again ever.
63          */
64         mem = rte_realloc(bt->table, n * sizeof(struct mlx5_mr_cache), 0);
65         if (mem == NULL) {
66                 /* Not an error, B-tree search will be skipped. */
67                 DRV_LOG(WARNING, "failed to expand MR B-tree (%p) table",
68                         (void *)bt);
69                 ret = -1;
70         } else {
71                 DRV_LOG(DEBUG, "expanded MR B-tree table (size=%u)", n);
72                 bt->table = mem;
73                 bt->size = n;
74         }
75         return ret;
76 }
77
78 /**
79  * Look up LKey from given B-tree lookup table, store the last index and return
80  * searched LKey.
81  *
82  * @param bt
83  *   Pointer to B-tree structure.
84  * @param[out] idx
85  *   Pointer to index. Even on search failure, returns index where it stops
86  *   searching so that index can be used when inserting a new entry.
87  * @param addr
88  *   Search key.
89  *
90  * @return
91  *   Searched LKey on success, UINT32_MAX on no match.
92  */
93 static uint32_t
94 mr_btree_lookup(struct mlx5_mr_btree *bt, uint16_t *idx, uintptr_t addr)
95 {
96         struct mlx5_mr_cache *lkp_tbl;
97         uint16_t n;
98         uint16_t base = 0;
99
100         assert(bt != NULL);
101         lkp_tbl = *bt->table;
102         n = bt->len;
103         /* First entry must be NULL for comparison. */
104         assert(bt->len > 0 || (lkp_tbl[0].start == 0 &&
105                                lkp_tbl[0].lkey == UINT32_MAX));
106         /* Binary search. */
107         do {
108                 register uint16_t delta = n >> 1;
109
110                 if (addr < lkp_tbl[base + delta].start) {
111                         n = delta;
112                 } else {
113                         base += delta;
114                         n -= delta;
115                 }
116         } while (n > 1);
117         assert(addr >= lkp_tbl[base].start);
118         *idx = base;
119         if (addr < lkp_tbl[base].end)
120                 return lkp_tbl[base].lkey;
121         /* Not found. */
122         return UINT32_MAX;
123 }
124
125 /**
126  * Insert an entry to B-tree lookup table.
127  *
128  * @param bt
129  *   Pointer to B-tree structure.
130  * @param entry
131  *   Pointer to new entry to insert.
132  *
133  * @return
134  *   0 on success, -1 on failure.
135  */
136 static int
137 mr_btree_insert(struct mlx5_mr_btree *bt, struct mlx5_mr_cache *entry)
138 {
139         struct mlx5_mr_cache *lkp_tbl;
140         uint16_t idx = 0;
141         size_t shift;
142
143         assert(bt != NULL);
144         assert(bt->len <= bt->size);
145         assert(bt->len > 0);
146         lkp_tbl = *bt->table;
147         /* Find out the slot for insertion. */
148         if (mr_btree_lookup(bt, &idx, entry->start) != UINT32_MAX) {
149                 DRV_LOG(DEBUG,
150                         "abort insertion to B-tree(%p): already exist at"
151                         " idx=%u [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
152                         (void *)bt, idx, entry->start, entry->end, entry->lkey);
153                 /* Already exist, return. */
154                 return 0;
155         }
156         /* If table is full, return error. */
157         if (unlikely(bt->len == bt->size)) {
158                 bt->overflow = 1;
159                 return -1;
160         }
161         /* Insert entry. */
162         ++idx;
163         shift = (bt->len - idx) * sizeof(struct mlx5_mr_cache);
164         if (shift)
165                 memmove(&lkp_tbl[idx + 1], &lkp_tbl[idx], shift);
166         lkp_tbl[idx] = *entry;
167         bt->len++;
168         DRV_LOG(DEBUG,
169                 "inserted B-tree(%p)[%u],"
170                 " [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
171                 (void *)bt, idx, entry->start, entry->end, entry->lkey);
172         return 0;
173 }
174
175 /**
176  * Initialize B-tree and allocate memory for lookup table.
177  *
178  * @param bt
179  *   Pointer to B-tree structure.
180  * @param n
181  *   Number of entries to allocate.
182  * @param socket
183  *   NUMA socket on which memory must be allocated.
184  *
185  * @return
186  *   0 on success, a negative errno value otherwise and rte_errno is set.
187  */
188 int
189 mlx5_mr_btree_init(struct mlx5_mr_btree *bt, int n, int socket)
190 {
191         if (bt == NULL) {
192                 rte_errno = EINVAL;
193                 return -rte_errno;
194         }
195         assert(!bt->table && !bt->size);
196         memset(bt, 0, sizeof(*bt));
197         bt->table = rte_calloc_socket("B-tree table",
198                                       n, sizeof(struct mlx5_mr_cache),
199                                       0, socket);
200         if (bt->table == NULL) {
201                 rte_errno = ENOMEM;
202                 DEBUG("failed to allocate memory for btree cache on socket %d",
203                       socket);
204                 return -rte_errno;
205         }
206         bt->size = n;
207         /* First entry must be NULL for binary search. */
208         (*bt->table)[bt->len++] = (struct mlx5_mr_cache) {
209                 .lkey = UINT32_MAX,
210         };
211         DEBUG("initialized B-tree %p with table %p",
212               (void *)bt, (void *)bt->table);
213         return 0;
214 }
215
216 /**
217  * Free B-tree resources.
218  *
219  * @param bt
220  *   Pointer to B-tree structure.
221  */
222 void
223 mlx5_mr_btree_free(struct mlx5_mr_btree *bt)
224 {
225         if (bt == NULL)
226                 return;
227         DEBUG("freeing B-tree %p with table %p",
228               (void *)bt, (void *)bt->table);
229         rte_free(bt->table);
230         memset(bt, 0, sizeof(*bt));
231 }
232
233 /**
234  * Dump all the entries in a B-tree
235  *
236  * @param bt
237  *   Pointer to B-tree structure.
238  */
239 void
240 mlx5_mr_btree_dump(struct mlx5_mr_btree *bt __rte_unused)
241 {
242 #ifndef NDEBUG
243         int idx;
244         struct mlx5_mr_cache *lkp_tbl;
245
246         if (bt == NULL)
247                 return;
248         lkp_tbl = *bt->table;
249         for (idx = 0; idx < bt->len; ++idx) {
250                 struct mlx5_mr_cache *entry = &lkp_tbl[idx];
251
252                 DEBUG("B-tree(%p)[%u],"
253                       " [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
254                       (void *)bt, idx, entry->start, entry->end, entry->lkey);
255         }
256 #endif
257 }
258
259 /**
260  * Find virtually contiguous memory chunk in a given MR.
261  *
262  * @param dev
263  *   Pointer to MR structure.
264  * @param[out] entry
265  *   Pointer to returning MR cache entry. If not found, this will not be
266  *   updated.
267  * @param start_idx
268  *   Start index of the memseg bitmap.
269  *
270  * @return
271  *   Next index to go on lookup.
272  */
273 static int
274 mr_find_next_chunk(struct mlx5_mr *mr, struct mlx5_mr_cache *entry,
275                    int base_idx)
276 {
277         uintptr_t start = 0;
278         uintptr_t end = 0;
279         uint32_t idx = 0;
280
281         /* MR for external memory doesn't have memseg list. */
282         if (mr->msl == NULL) {
283                 struct ibv_mr *ibv_mr = mr->ibv_mr;
284
285                 assert(mr->ms_bmp_n == 1);
286                 assert(mr->ms_n == 1);
287                 assert(base_idx == 0);
288                 /*
289                  * Can't search it from memseg list but get it directly from
290                  * verbs MR as there's only one chunk.
291                  */
292                 entry->start = (uintptr_t)ibv_mr->addr;
293                 entry->end = (uintptr_t)ibv_mr->addr + mr->ibv_mr->length;
294                 entry->lkey = rte_cpu_to_be_32(mr->ibv_mr->lkey);
295                 /* Returning 1 ends iteration. */
296                 return 1;
297         }
298         for (idx = base_idx; idx < mr->ms_bmp_n; ++idx) {
299                 if (rte_bitmap_get(mr->ms_bmp, idx)) {
300                         const struct rte_memseg_list *msl;
301                         const struct rte_memseg *ms;
302
303                         msl = mr->msl;
304                         ms = rte_fbarray_get(&msl->memseg_arr,
305                                              mr->ms_base_idx + idx);
306                         assert(msl->page_sz == ms->hugepage_sz);
307                         if (!start)
308                                 start = ms->addr_64;
309                         end = ms->addr_64 + ms->hugepage_sz;
310                 } else if (start) {
311                         /* Passed the end of a fragment. */
312                         break;
313                 }
314         }
315         if (start) {
316                 /* Found one chunk. */
317                 entry->start = start;
318                 entry->end = end;
319                 entry->lkey = rte_cpu_to_be_32(mr->ibv_mr->lkey);
320         }
321         return idx;
322 }
323
324 /**
325  * Insert a MR to the global B-tree cache. It may fail due to low-on-memory.
326  * Then, this entry will have to be searched by mr_lookup_dev_list() in
327  * mlx5_mr_create() on miss.
328  *
329  * @param dev
330  *   Pointer to Ethernet device.
331  * @param mr
332  *   Pointer to MR to insert.
333  *
334  * @return
335  *   0 on success, -1 on failure.
336  */
337 static int
338 mr_insert_dev_cache(struct rte_eth_dev *dev, struct mlx5_mr *mr)
339 {
340         struct mlx5_priv *priv = dev->data->dev_private;
341         unsigned int n;
342
343         DRV_LOG(DEBUG, "port %u inserting MR(%p) to global cache",
344                 dev->data->port_id, (void *)mr);
345         for (n = 0; n < mr->ms_bmp_n; ) {
346                 struct mlx5_mr_cache entry;
347
348                 memset(&entry, 0, sizeof(entry));
349                 /* Find a contiguous chunk and advance the index. */
350                 n = mr_find_next_chunk(mr, &entry, n);
351                 if (!entry.end)
352                         break;
353                 if (mr_btree_insert(&priv->mr.cache, &entry) < 0) {
354                         /*
355                          * Overflowed, but the global table cannot be expanded
356                          * because of deadlock.
357                          */
358                         return -1;
359                 }
360         }
361         return 0;
362 }
363
364 /**
365  * Look up address in the original global MR list.
366  *
367  * @param dev
368  *   Pointer to Ethernet device.
369  * @param[out] entry
370  *   Pointer to returning MR cache entry. If no match, this will not be updated.
371  * @param addr
372  *   Search key.
373  *
374  * @return
375  *   Found MR on match, NULL otherwise.
376  */
377 static struct mlx5_mr *
378 mr_lookup_dev_list(struct rte_eth_dev *dev, struct mlx5_mr_cache *entry,
379                    uintptr_t addr)
380 {
381         struct mlx5_priv *priv = dev->data->dev_private;
382         struct mlx5_mr *mr;
383
384         /* Iterate all the existing MRs. */
385         LIST_FOREACH(mr, &priv->mr.mr_list, mr) {
386                 unsigned int n;
387
388                 if (mr->ms_n == 0)
389                         continue;
390                 for (n = 0; n < mr->ms_bmp_n; ) {
391                         struct mlx5_mr_cache ret;
392
393                         memset(&ret, 0, sizeof(ret));
394                         n = mr_find_next_chunk(mr, &ret, n);
395                         if (addr >= ret.start && addr < ret.end) {
396                                 /* Found. */
397                                 *entry = ret;
398                                 return mr;
399                         }
400                 }
401         }
402         return NULL;
403 }
404
405 /**
406  * Look up address on device.
407  *
408  * @param dev
409  *   Pointer to Ethernet device.
410  * @param[out] entry
411  *   Pointer to returning MR cache entry. If no match, this will not be updated.
412  * @param addr
413  *   Search key.
414  *
415  * @return
416  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
417  */
418 static uint32_t
419 mr_lookup_dev(struct rte_eth_dev *dev, struct mlx5_mr_cache *entry,
420               uintptr_t addr)
421 {
422         struct mlx5_priv *priv = dev->data->dev_private;
423         uint16_t idx;
424         uint32_t lkey = UINT32_MAX;
425         struct mlx5_mr *mr;
426
427         /*
428          * If the global cache has overflowed since it failed to expand the
429          * B-tree table, it can't have all the existing MRs. Then, the address
430          * has to be searched by traversing the original MR list instead, which
431          * is very slow path. Otherwise, the global cache is all inclusive.
432          */
433         if (!unlikely(priv->mr.cache.overflow)) {
434                 lkey = mr_btree_lookup(&priv->mr.cache, &idx, addr);
435                 if (lkey != UINT32_MAX)
436                         *entry = (*priv->mr.cache.table)[idx];
437         } else {
438                 /* Falling back to the slowest path. */
439                 mr = mr_lookup_dev_list(dev, entry, addr);
440                 if (mr != NULL)
441                         lkey = entry->lkey;
442         }
443         assert(lkey == UINT32_MAX || (addr >= entry->start &&
444                                       addr < entry->end));
445         return lkey;
446 }
447
448 /**
449  * Free MR resources. MR lock must not be held to avoid a deadlock. rte_free()
450  * can raise memory free event and the callback function will spin on the lock.
451  *
452  * @param mr
453  *   Pointer to MR to free.
454  */
455 static void
456 mr_free(struct mlx5_mr *mr)
457 {
458         if (mr == NULL)
459                 return;
460         DRV_LOG(DEBUG, "freeing MR(%p):", (void *)mr);
461         if (mr->ibv_mr != NULL)
462                 claim_zero(mlx5_glue->dereg_mr(mr->ibv_mr));
463         if (mr->ms_bmp != NULL)
464                 rte_bitmap_free(mr->ms_bmp);
465         rte_free(mr);
466 }
467
468 /**
469  * Releass resources of detached MR having no online entry.
470  *
471  * @param dev
472  *   Pointer to Ethernet device.
473  */
474 static void
475 mlx5_mr_garbage_collect(struct rte_eth_dev *dev)
476 {
477         struct mlx5_priv *priv = dev->data->dev_private;
478         struct mlx5_mr *mr_next;
479         struct mlx5_mr_list free_list = LIST_HEAD_INITIALIZER(free_list);
480
481         /* Must be called from the primary process. */
482         assert(rte_eal_process_type() == RTE_PROC_PRIMARY);
483         /*
484          * MR can't be freed with holding the lock because rte_free() could call
485          * memory free callback function. This will be a deadlock situation.
486          */
487         rte_rwlock_write_lock(&priv->mr.rwlock);
488         /* Detach the whole free list and release it after unlocking. */
489         free_list = priv->mr.mr_free_list;
490         LIST_INIT(&priv->mr.mr_free_list);
491         rte_rwlock_write_unlock(&priv->mr.rwlock);
492         /* Release resources. */
493         mr_next = LIST_FIRST(&free_list);
494         while (mr_next != NULL) {
495                 struct mlx5_mr *mr = mr_next;
496
497                 mr_next = LIST_NEXT(mr, mr);
498                 mr_free(mr);
499         }
500 }
501
502 /* Called during rte_memseg_contig_walk() by mlx5_mr_create(). */
503 static int
504 mr_find_contig_memsegs_cb(const struct rte_memseg_list *msl,
505                           const struct rte_memseg *ms, size_t len, void *arg)
506 {
507         struct mr_find_contig_memsegs_data *data = arg;
508
509         if (data->addr < ms->addr_64 || data->addr >= ms->addr_64 + len)
510                 return 0;
511         /* Found, save it and stop walking. */
512         data->start = ms->addr_64;
513         data->end = ms->addr_64 + len;
514         data->msl = msl;
515         return 1;
516 }
517
518 /**
519  * Create a new global Memroy Region (MR) for a missing virtual address.
520  * Register entire virtually contiguous memory chunk around the address.
521  *
522  * @param dev
523  *   Pointer to Ethernet device.
524  * @param[out] entry
525  *   Pointer to returning MR cache entry, found in the global cache or newly
526  *   created. If failed to create one, this will not be updated.
527  * @param addr
528  *   Target virtual address to register.
529  *
530  * @return
531  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
532  */
533 static uint32_t
534 mlx5_mr_create(struct rte_eth_dev *dev, struct mlx5_mr_cache *entry,
535                uintptr_t addr)
536 {
537         struct mlx5_priv *priv = dev->data->dev_private;
538         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
539         const struct rte_memseg_list *msl;
540         const struct rte_memseg *ms;
541         struct mlx5_mr *mr = NULL;
542         size_t len;
543         uint32_t ms_n;
544         uint32_t bmp_size;
545         void *bmp_mem;
546         int ms_idx_shift = -1;
547         unsigned int n;
548         struct mr_find_contig_memsegs_data data = {
549                 .addr = addr,
550         };
551         struct mr_find_contig_memsegs_data data_re;
552
553         DRV_LOG(DEBUG, "port %u creating a MR using address (%p)",
554                 dev->data->port_id, (void *)addr);
555         if (rte_eal_process_type() != RTE_PROC_PRIMARY) {
556                 DRV_LOG(WARNING,
557                         "port %u using address (%p) of unregistered mempool"
558                         " in secondary process, please create mempool"
559                         " before rte_eth_dev_start()",
560                         dev->data->port_id, (void *)addr);
561                 rte_errno = EPERM;
562                 goto err_nolock;
563         }
564         /*
565          * Release detached MRs if any. This can't be called with holding either
566          * memory_hotplug_lock or priv->mr.rwlock. MRs on the free list have
567          * been detached by the memory free event but it couldn't be released
568          * inside the callback due to deadlock. As a result, releasing resources
569          * is quite opportunistic.
570          */
571         mlx5_mr_garbage_collect(dev);
572         /*
573          * Find out a contiguous virtual address chunk in use, to which the
574          * given address belongs, in order to register maximum range. In the
575          * best case where mempools are not dynamically recreated and
576          * '--socket-mem' is specified as an EAL option, it is very likely to
577          * have only one MR(LKey) per a socket and per a hugepage-size even
578          * though the system memory is highly fragmented.
579          */
580         if (!rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data)) {
581                 DRV_LOG(WARNING,
582                         "port %u unable to find virtually contiguous"
583                         " chunk for address (%p)."
584                         " rte_memseg_contig_walk() failed.",
585                         dev->data->port_id, (void *)addr);
586                 rte_errno = ENXIO;
587                 goto err_nolock;
588         }
589 alloc_resources:
590         /* Addresses must be page-aligned. */
591         assert(rte_is_aligned((void *)data.start, data.msl->page_sz));
592         assert(rte_is_aligned((void *)data.end, data.msl->page_sz));
593         msl = data.msl;
594         ms = rte_mem_virt2memseg((void *)data.start, msl);
595         len = data.end - data.start;
596         assert(msl->page_sz == ms->hugepage_sz);
597         /* Number of memsegs in the range. */
598         ms_n = len / msl->page_sz;
599         DEBUG("port %u extending %p to [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
600               " page_sz=0x%" PRIx64 ", ms_n=%u",
601               dev->data->port_id, (void *)addr,
602               data.start, data.end, msl->page_sz, ms_n);
603         /* Size of memory for bitmap. */
604         bmp_size = rte_bitmap_get_memory_footprint(ms_n);
605         mr = rte_zmalloc_socket(NULL,
606                                 RTE_ALIGN_CEIL(sizeof(*mr),
607                                                RTE_CACHE_LINE_SIZE) +
608                                 bmp_size,
609                                 RTE_CACHE_LINE_SIZE, msl->socket_id);
610         if (mr == NULL) {
611                 DEBUG("port %u unable to allocate memory for a new MR of"
612                       " address (%p).",
613                       dev->data->port_id, (void *)addr);
614                 rte_errno = ENOMEM;
615                 goto err_nolock;
616         }
617         mr->msl = msl;
618         /*
619          * Save the index of the first memseg and initialize memseg bitmap. To
620          * see if a memseg of ms_idx in the memseg-list is still valid, check:
621          *      rte_bitmap_get(mr->bmp, ms_idx - mr->ms_base_idx)
622          */
623         mr->ms_base_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
624         bmp_mem = RTE_PTR_ALIGN_CEIL(mr + 1, RTE_CACHE_LINE_SIZE);
625         mr->ms_bmp = rte_bitmap_init(ms_n, bmp_mem, bmp_size);
626         if (mr->ms_bmp == NULL) {
627                 DEBUG("port %u unable to initialize bitamp for a new MR of"
628                       " address (%p).",
629                       dev->data->port_id, (void *)addr);
630                 rte_errno = EINVAL;
631                 goto err_nolock;
632         }
633         /*
634          * Should recheck whether the extended contiguous chunk is still valid.
635          * Because memory_hotplug_lock can't be held if there's any memory
636          * related calls in a critical path, resource allocation above can't be
637          * locked. If the memory has been changed at this point, try again with
638          * just single page. If not, go on with the big chunk atomically from
639          * here.
640          */
641         rte_rwlock_read_lock(&mcfg->memory_hotplug_lock);
642         data_re = data;
643         if (len > msl->page_sz &&
644             !rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data_re)) {
645                 DEBUG("port %u unable to find virtually contiguous"
646                       " chunk for address (%p)."
647                       " rte_memseg_contig_walk() failed.",
648                       dev->data->port_id, (void *)addr);
649                 rte_errno = ENXIO;
650                 goto err_memlock;
651         }
652         if (data.start != data_re.start || data.end != data_re.end) {
653                 /*
654                  * The extended contiguous chunk has been changed. Try again
655                  * with single memseg instead.
656                  */
657                 data.start = RTE_ALIGN_FLOOR(addr, msl->page_sz);
658                 data.end = data.start + msl->page_sz;
659                 rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
660                 mr_free(mr);
661                 goto alloc_resources;
662         }
663         assert(data.msl == data_re.msl);
664         rte_rwlock_write_lock(&priv->mr.rwlock);
665         /*
666          * Check the address is really missing. If other thread already created
667          * one or it is not found due to overflow, abort and return.
668          */
669         if (mr_lookup_dev(dev, entry, addr) != UINT32_MAX) {
670                 /*
671                  * Insert to the global cache table. It may fail due to
672                  * low-on-memory. Then, this entry will have to be searched
673                  * here again.
674                  */
675                 mr_btree_insert(&priv->mr.cache, entry);
676                 DEBUG("port %u found MR for %p on final lookup, abort",
677                       dev->data->port_id, (void *)addr);
678                 rte_rwlock_write_unlock(&priv->mr.rwlock);
679                 rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
680                 /*
681                  * Must be unlocked before calling rte_free() because
682                  * mlx5_mr_mem_event_free_cb() can be called inside.
683                  */
684                 mr_free(mr);
685                 return entry->lkey;
686         }
687         /*
688          * Trim start and end addresses for verbs MR. Set bits for registering
689          * memsegs but exclude already registered ones. Bitmap can be
690          * fragmented.
691          */
692         for (n = 0; n < ms_n; ++n) {
693                 uintptr_t start;
694                 struct mlx5_mr_cache ret;
695
696                 memset(&ret, 0, sizeof(ret));
697                 start = data_re.start + n * msl->page_sz;
698                 /* Exclude memsegs already registered by other MRs. */
699                 if (mr_lookup_dev(dev, &ret, start) == UINT32_MAX) {
700                         /*
701                          * Start from the first unregistered memseg in the
702                          * extended range.
703                          */
704                         if (ms_idx_shift == -1) {
705                                 mr->ms_base_idx += n;
706                                 data.start = start;
707                                 ms_idx_shift = n;
708                         }
709                         data.end = start + msl->page_sz;
710                         rte_bitmap_set(mr->ms_bmp, n - ms_idx_shift);
711                         ++mr->ms_n;
712                 }
713         }
714         len = data.end - data.start;
715         mr->ms_bmp_n = len / msl->page_sz;
716         assert(ms_idx_shift + mr->ms_bmp_n <= ms_n);
717         /*
718          * Finally create a verbs MR for the memory chunk. ibv_reg_mr() can be
719          * called with holding the memory lock because it doesn't use
720          * mlx5_alloc_buf_extern() which eventually calls rte_malloc_socket()
721          * through mlx5_alloc_verbs_buf().
722          */
723         mr->ibv_mr = mlx5_glue->reg_mr(priv->pd, (void *)data.start, len,
724                                        IBV_ACCESS_LOCAL_WRITE);
725         if (mr->ibv_mr == NULL) {
726                 DEBUG("port %u fail to create a verbs MR for address (%p)",
727                       dev->data->port_id, (void *)addr);
728                 rte_errno = EINVAL;
729                 goto err_mrlock;
730         }
731         assert((uintptr_t)mr->ibv_mr->addr == data.start);
732         assert(mr->ibv_mr->length == len);
733         LIST_INSERT_HEAD(&priv->mr.mr_list, mr, mr);
734         DEBUG("port %u MR CREATED (%p) for %p:\n"
735               "  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
736               " lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
737               dev->data->port_id, (void *)mr, (void *)addr,
738               data.start, data.end, rte_cpu_to_be_32(mr->ibv_mr->lkey),
739               mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
740         /* Insert to the global cache table. */
741         mr_insert_dev_cache(dev, mr);
742         /* Fill in output data. */
743         mr_lookup_dev(dev, entry, addr);
744         /* Lookup can't fail. */
745         assert(entry->lkey != UINT32_MAX);
746         rte_rwlock_write_unlock(&priv->mr.rwlock);
747         rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
748         return entry->lkey;
749 err_mrlock:
750         rte_rwlock_write_unlock(&priv->mr.rwlock);
751 err_memlock:
752         rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
753 err_nolock:
754         /*
755          * In case of error, as this can be called in a datapath, a warning
756          * message per an error is preferable instead. Must be unlocked before
757          * calling rte_free() because mlx5_mr_mem_event_free_cb() can be called
758          * inside.
759          */
760         mr_free(mr);
761         return UINT32_MAX;
762 }
763
764 /**
765  * Rebuild the global B-tree cache of device from the original MR list.
766  *
767  * @param dev
768  *   Pointer to Ethernet device.
769  */
770 static void
771 mr_rebuild_dev_cache(struct rte_eth_dev *dev)
772 {
773         struct mlx5_priv *priv = dev->data->dev_private;
774         struct mlx5_mr *mr;
775
776         DRV_LOG(DEBUG, "port %u rebuild dev cache[]", dev->data->port_id);
777         /* Flush cache to rebuild. */
778         priv->mr.cache.len = 1;
779         priv->mr.cache.overflow = 0;
780         /* Iterate all the existing MRs. */
781         LIST_FOREACH(mr, &priv->mr.mr_list, mr)
782                 if (mr_insert_dev_cache(dev, mr) < 0)
783                         return;
784 }
785
786 /**
787  * Callback for memory free event. Iterate freed memsegs and check whether it
788  * belongs to an existing MR. If found, clear the bit from bitmap of MR. As a
789  * result, the MR would be fragmented. If it becomes empty, the MR will be freed
790  * later by mlx5_mr_garbage_collect(). Even if this callback is called from a
791  * secondary process, the garbage collector will be called in primary process
792  * as the secondary process can't call mlx5_mr_create().
793  *
794  * The global cache must be rebuilt if there's any change and this event has to
795  * be propagated to dataplane threads to flush the local caches.
796  *
797  * @param dev
798  *   Pointer to Ethernet device.
799  * @param addr
800  *   Address of freed memory.
801  * @param len
802  *   Size of freed memory.
803  */
804 static void
805 mlx5_mr_mem_event_free_cb(struct rte_eth_dev *dev, const void *addr, size_t len)
806 {
807         struct mlx5_priv *priv = dev->data->dev_private;
808         const struct rte_memseg_list *msl;
809         struct mlx5_mr *mr;
810         int ms_n;
811         int i;
812         int rebuild = 0;
813
814         DEBUG("port %u free callback: addr=%p, len=%zu",
815               dev->data->port_id, addr, len);
816         msl = rte_mem_virt2memseg_list(addr);
817         /* addr and len must be page-aligned. */
818         assert((uintptr_t)addr == RTE_ALIGN((uintptr_t)addr, msl->page_sz));
819         assert(len == RTE_ALIGN(len, msl->page_sz));
820         ms_n = len / msl->page_sz;
821         rte_rwlock_write_lock(&priv->mr.rwlock);
822         /* Clear bits of freed memsegs from MR. */
823         for (i = 0; i < ms_n; ++i) {
824                 const struct rte_memseg *ms;
825                 struct mlx5_mr_cache entry;
826                 uintptr_t start;
827                 int ms_idx;
828                 uint32_t pos;
829
830                 /* Find MR having this memseg. */
831                 start = (uintptr_t)addr + i * msl->page_sz;
832                 mr = mr_lookup_dev_list(dev, &entry, start);
833                 if (mr == NULL)
834                         continue;
835                 assert(mr->msl); /* Can't be external memory. */
836                 ms = rte_mem_virt2memseg((void *)start, msl);
837                 assert(ms != NULL);
838                 assert(msl->page_sz == ms->hugepage_sz);
839                 ms_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
840                 pos = ms_idx - mr->ms_base_idx;
841                 assert(rte_bitmap_get(mr->ms_bmp, pos));
842                 assert(pos < mr->ms_bmp_n);
843                 DEBUG("port %u MR(%p): clear bitmap[%u] for addr %p",
844                       dev->data->port_id, (void *)mr, pos, (void *)start);
845                 rte_bitmap_clear(mr->ms_bmp, pos);
846                 if (--mr->ms_n == 0) {
847                         LIST_REMOVE(mr, mr);
848                         LIST_INSERT_HEAD(&priv->mr.mr_free_list, mr, mr);
849                         DEBUG("port %u remove MR(%p) from list",
850                               dev->data->port_id, (void *)mr);
851                 }
852                 /*
853                  * MR is fragmented or will be freed. the global cache must be
854                  * rebuilt.
855                  */
856                 rebuild = 1;
857         }
858         if (rebuild) {
859                 mr_rebuild_dev_cache(dev);
860                 /*
861                  * Flush local caches by propagating invalidation across cores.
862                  * rte_smp_wmb() is enough to synchronize this event. If one of
863                  * freed memsegs is seen by other core, that means the memseg
864                  * has been allocated by allocator, which will come after this
865                  * free call. Therefore, this store instruction (incrementing
866                  * generation below) will be guaranteed to be seen by other core
867                  * before the core sees the newly allocated memory.
868                  */
869                 ++priv->mr.dev_gen;
870                 DEBUG("broadcasting local cache flush, gen=%d",
871                       priv->mr.dev_gen);
872                 rte_smp_wmb();
873         }
874         rte_rwlock_write_unlock(&priv->mr.rwlock);
875 }
876
877 /**
878  * Callback for memory event. This can be called from both primary and secondary
879  * process.
880  *
881  * @param event_type
882  *   Memory event type.
883  * @param addr
884  *   Address of memory.
885  * @param len
886  *   Size of memory.
887  */
888 void
889 mlx5_mr_mem_event_cb(enum rte_mem_event event_type, const void *addr,
890                      size_t len, void *arg __rte_unused)
891 {
892         struct mlx5_priv *priv;
893         struct mlx5_dev_list *dev_list = &mlx5_shared_data->mem_event_cb_list;
894
895         switch (event_type) {
896         case RTE_MEM_EVENT_FREE:
897                 rte_rwlock_write_lock(&mlx5_shared_data->mem_event_rwlock);
898                 /* Iterate all the existing mlx5 devices. */
899                 LIST_FOREACH(priv, dev_list, mem_event_cb)
900                         mlx5_mr_mem_event_free_cb(ETH_DEV(priv), addr, len);
901                 rte_rwlock_write_unlock(&mlx5_shared_data->mem_event_rwlock);
902                 break;
903         case RTE_MEM_EVENT_ALLOC:
904         default:
905                 break;
906         }
907 }
908
909 /**
910  * Look up address in the global MR cache table. If not found, create a new MR.
911  * Insert the found/created entry to local bottom-half cache table.
912  *
913  * @param dev
914  *   Pointer to Ethernet device.
915  * @param mr_ctrl
916  *   Pointer to per-queue MR control structure.
917  * @param[out] entry
918  *   Pointer to returning MR cache entry, found in the global cache or newly
919  *   created. If failed to create one, this is not written.
920  * @param addr
921  *   Search key.
922  *
923  * @return
924  *   Searched LKey on success, UINT32_MAX on no match.
925  */
926 static uint32_t
927 mlx5_mr_lookup_dev(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
928                    struct mlx5_mr_cache *entry, uintptr_t addr)
929 {
930         struct mlx5_priv *priv = dev->data->dev_private;
931         struct mlx5_mr_btree *bt = &mr_ctrl->cache_bh;
932         uint16_t idx;
933         uint32_t lkey;
934
935         /* If local cache table is full, try to double it. */
936         if (unlikely(bt->len == bt->size))
937                 mr_btree_expand(bt, bt->size << 1);
938         /* Look up in the global cache. */
939         rte_rwlock_read_lock(&priv->mr.rwlock);
940         lkey = mr_btree_lookup(&priv->mr.cache, &idx, addr);
941         if (lkey != UINT32_MAX) {
942                 /* Found. */
943                 *entry = (*priv->mr.cache.table)[idx];
944                 rte_rwlock_read_unlock(&priv->mr.rwlock);
945                 /*
946                  * Update local cache. Even if it fails, return the found entry
947                  * to update top-half cache. Next time, this entry will be found
948                  * in the global cache.
949                  */
950                 mr_btree_insert(bt, entry);
951                 return lkey;
952         }
953         rte_rwlock_read_unlock(&priv->mr.rwlock);
954         /* First time to see the address? Create a new MR. */
955         lkey = mlx5_mr_create(dev, entry, addr);
956         /*
957          * Update the local cache if successfully created a new global MR. Even
958          * if failed to create one, there's no action to take in this datapath
959          * code. As returning LKey is invalid, this will eventually make HW
960          * fail.
961          */
962         if (lkey != UINT32_MAX)
963                 mr_btree_insert(bt, entry);
964         return lkey;
965 }
966
967 /**
968  * Bottom-half of LKey search on datapath. Firstly search in cache_bh[] and if
969  * misses, search in the global MR cache table and update the new entry to
970  * per-queue local caches.
971  *
972  * @param dev
973  *   Pointer to Ethernet device.
974  * @param mr_ctrl
975  *   Pointer to per-queue MR control structure.
976  * @param addr
977  *   Search key.
978  *
979  * @return
980  *   Searched LKey on success, UINT32_MAX on no match.
981  */
982 static uint32_t
983 mlx5_mr_addr2mr_bh(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
984                    uintptr_t addr)
985 {
986         uint32_t lkey;
987         uint16_t bh_idx = 0;
988         /* Victim in top-half cache to replace with new entry. */
989         struct mlx5_mr_cache *repl = &mr_ctrl->cache[mr_ctrl->head];
990
991         /* Binary-search MR translation table. */
992         lkey = mr_btree_lookup(&mr_ctrl->cache_bh, &bh_idx, addr);
993         /* Update top-half cache. */
994         if (likely(lkey != UINT32_MAX)) {
995                 *repl = (*mr_ctrl->cache_bh.table)[bh_idx];
996         } else {
997                 /*
998                  * If missed in local lookup table, search in the global cache
999                  * and local cache_bh[] will be updated inside if possible.
1000                  * Top-half cache entry will also be updated.
1001                  */
1002                 lkey = mlx5_mr_lookup_dev(dev, mr_ctrl, repl, addr);
1003                 if (unlikely(lkey == UINT32_MAX))
1004                         return UINT32_MAX;
1005         }
1006         /* Update the most recently used entry. */
1007         mr_ctrl->mru = mr_ctrl->head;
1008         /* Point to the next victim, the oldest. */
1009         mr_ctrl->head = (mr_ctrl->head + 1) % MLX5_MR_CACHE_N;
1010         return lkey;
1011 }
1012
1013 /**
1014  * Bottom-half of LKey search on Rx.
1015  *
1016  * @param rxq
1017  *   Pointer to Rx 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 mlx5_rx_addr2mr_bh(struct mlx5_rxq_data *rxq, uintptr_t addr)
1026 {
1027         struct mlx5_rxq_ctrl *rxq_ctrl =
1028                 container_of(rxq, struct mlx5_rxq_ctrl, rxq);
1029         struct mlx5_mr_ctrl *mr_ctrl = &rxq->mr_ctrl;
1030         struct mlx5_priv *priv = rxq_ctrl->priv;
1031
1032         DRV_LOG(DEBUG,
1033                 "Rx queue %u: miss on top-half, mru=%u, head=%u, addr=%p",
1034                 rxq_ctrl->idx, mr_ctrl->mru, mr_ctrl->head, (void *)addr);
1035         return mlx5_mr_addr2mr_bh(ETH_DEV(priv), mr_ctrl, addr);
1036 }
1037
1038 /**
1039  * Bottom-half of LKey search on Tx.
1040  *
1041  * @param txq
1042  *   Pointer to Tx queue structure.
1043  * @param addr
1044  *   Search key.
1045  *
1046  * @return
1047  *   Searched LKey on success, UINT32_MAX on no match.
1048  */
1049 static uint32_t
1050 mlx5_tx_addr2mr_bh(struct mlx5_txq_data *txq, uintptr_t addr)
1051 {
1052         struct mlx5_txq_ctrl *txq_ctrl =
1053                 container_of(txq, struct mlx5_txq_ctrl, txq);
1054         struct mlx5_mr_ctrl *mr_ctrl = &txq->mr_ctrl;
1055         struct mlx5_priv *priv = txq_ctrl->priv;
1056
1057         DRV_LOG(DEBUG,
1058                 "Tx queue %u: miss on top-half, mru=%u, head=%u, addr=%p",
1059                 txq_ctrl->idx, mr_ctrl->mru, mr_ctrl->head, (void *)addr);
1060         return mlx5_mr_addr2mr_bh(ETH_DEV(priv), mr_ctrl, addr);
1061 }
1062
1063 /**
1064  * Bottom-half of LKey search on Tx. If it can't be searched in the memseg
1065  * list, register the mempool of the mbuf as externally allocated memory.
1066  *
1067  * @param txq
1068  *   Pointer to Tx queue structure.
1069  * @param mb
1070  *   Pointer to mbuf.
1071  *
1072  * @return
1073  *   Searched LKey on success, UINT32_MAX on no match.
1074  */
1075 uint32_t
1076 mlx5_tx_mb2mr_bh(struct mlx5_txq_data *txq, struct rte_mbuf *mb)
1077 {
1078         uintptr_t addr = (uintptr_t)mb->buf_addr;
1079         uint32_t lkey;
1080
1081         lkey = mlx5_tx_addr2mr_bh(txq, addr);
1082         if (lkey == UINT32_MAX && rte_errno == ENXIO) {
1083                 /* Mempool may have externally allocated memory. */
1084                 return mlx5_tx_update_ext_mp(txq, addr, mlx5_mb2mp(mb));
1085         }
1086         return lkey;
1087 }
1088
1089 /**
1090  * Flush all of the local cache entries.
1091  *
1092  * @param mr_ctrl
1093  *   Pointer to per-queue MR control structure.
1094  */
1095 void
1096 mlx5_mr_flush_local_cache(struct mlx5_mr_ctrl *mr_ctrl)
1097 {
1098         /* Reset the most-recently-used index. */
1099         mr_ctrl->mru = 0;
1100         /* Reset the linear search array. */
1101         mr_ctrl->head = 0;
1102         memset(mr_ctrl->cache, 0, sizeof(mr_ctrl->cache));
1103         /* Reset the B-tree table. */
1104         mr_ctrl->cache_bh.len = 1;
1105         mr_ctrl->cache_bh.overflow = 0;
1106         /* Update the generation number. */
1107         mr_ctrl->cur_gen = *mr_ctrl->dev_gen_ptr;
1108         DRV_LOG(DEBUG, "mr_ctrl(%p): flushed, cur_gen=%d",
1109                 (void *)mr_ctrl, mr_ctrl->cur_gen);
1110 }
1111
1112 /**
1113  * Creates a memory region for external memory, that is memory which is not
1114  * part of the DPDK memory segments.
1115  *
1116  * @param dev
1117  *   Pointer to the ethernet device.
1118  * @param addr
1119  *   Starting virtual address of memory.
1120  * @param len
1121  *   Length of memory segment being mapped.
1122  * @param socked_id
1123  *   Socket to allocate heap memory for the control structures.
1124  *
1125  * @return
1126  *   Pointer to MR structure on success, NULL otherwise.
1127  */
1128 static struct mlx5_mr *
1129 mlx5_create_mr_ext(struct rte_eth_dev *dev, uintptr_t addr, size_t len,
1130                    int socket_id)
1131 {
1132         struct mlx5_priv *priv = dev->data->dev_private;
1133         struct mlx5_mr *mr = NULL;
1134
1135         mr = rte_zmalloc_socket(NULL,
1136                                 RTE_ALIGN_CEIL(sizeof(*mr),
1137                                                RTE_CACHE_LINE_SIZE),
1138                                 RTE_CACHE_LINE_SIZE, socket_id);
1139         if (mr == NULL)
1140                 return NULL;
1141         mr->ibv_mr = mlx5_glue->reg_mr(priv->pd, (void *)addr, len,
1142                                        IBV_ACCESS_LOCAL_WRITE);
1143         if (mr->ibv_mr == NULL) {
1144                 DRV_LOG(WARNING,
1145                         "port %u fail to create a verbs MR for address (%p)",
1146                         dev->data->port_id, (void *)addr);
1147                 rte_free(mr);
1148                 return NULL;
1149         }
1150         mr->msl = NULL; /* Mark it is external memory. */
1151         mr->ms_bmp = NULL;
1152         mr->ms_n = 1;
1153         mr->ms_bmp_n = 1;
1154         DRV_LOG(DEBUG,
1155                 "port %u MR CREATED (%p) for external memory %p:\n"
1156                 "  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
1157                 " lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
1158                 dev->data->port_id, (void *)mr, (void *)addr,
1159                 addr, addr + len, rte_cpu_to_be_32(mr->ibv_mr->lkey),
1160                 mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
1161         return mr;
1162 }
1163
1164 /**
1165  * Called during rte_mempool_mem_iter() by mlx5_mr_update_ext_mp().
1166  *
1167  * Externally allocated chunk is registered and a MR is created for the chunk.
1168  * The MR object is added to the global list. If memseg list of a MR object
1169  * (mr->msl) is null, the MR object can be regarded as externally allocated
1170  * memory.
1171  *
1172  * Once external memory is registered, it should be static. If the memory is
1173  * freed and the virtual address range has different physical memory mapped
1174  * again, it may cause crash on device due to the wrong translation entry. PMD
1175  * can't track the free event of the external memory for now.
1176  */
1177 static void
1178 mlx5_mr_update_ext_mp_cb(struct rte_mempool *mp, void *opaque,
1179                          struct rte_mempool_memhdr *memhdr,
1180                          unsigned mem_idx __rte_unused)
1181 {
1182         struct mr_update_mp_data *data = opaque;
1183         struct rte_eth_dev *dev = data->dev;
1184         struct mlx5_priv *priv = dev->data->dev_private;
1185         struct mlx5_mr_ctrl *mr_ctrl = data->mr_ctrl;
1186         struct mlx5_mr *mr = NULL;
1187         uintptr_t addr = (uintptr_t)memhdr->addr;
1188         size_t len = memhdr->len;
1189         struct mlx5_mr_cache entry;
1190         uint32_t lkey;
1191
1192         /* If already registered, it should return. */
1193         rte_rwlock_read_lock(&priv->mr.rwlock);
1194         lkey = mr_lookup_dev(dev, &entry, addr);
1195         rte_rwlock_read_unlock(&priv->mr.rwlock);
1196         if (lkey != UINT32_MAX)
1197                 return;
1198         DRV_LOG(DEBUG, "port %u register MR for chunk #%d of mempool (%s)",
1199                 dev->data->port_id, mem_idx, mp->name);
1200         mr = mlx5_create_mr_ext(dev, addr, len, mp->socket_id);
1201         if (!mr) {
1202                 DRV_LOG(WARNING,
1203                         "port %u unable to allocate a new MR of"
1204                         " mempool (%s).",
1205                         dev->data->port_id, mp->name);
1206                 data->ret = -1;
1207                 return;
1208         }
1209         rte_rwlock_write_lock(&priv->mr.rwlock);
1210         LIST_INSERT_HEAD(&priv->mr.mr_list, mr, mr);
1211         /* Insert to the global cache table. */
1212         mr_insert_dev_cache(dev, mr);
1213         rte_rwlock_write_unlock(&priv->mr.rwlock);
1214         /* Insert to the local cache table */
1215         mlx5_mr_addr2mr_bh(dev, mr_ctrl, addr);
1216 }
1217
1218 /**
1219  * Finds the first ethdev that match the pci device.
1220  * The existence of multiple ethdev per pci device is only with representors.
1221  * On such case, it is enough to get only one of the ports as they all share
1222  * the same ibv context.
1223  *
1224  * @param pdev
1225  *   Pointer to the PCI device.
1226  *
1227  * @return
1228  *   Pointer to the ethdev if found, NULL otherwise.
1229  */
1230 static struct rte_eth_dev *
1231 pci_dev_to_eth_dev(struct rte_pci_device *pdev)
1232 {
1233         struct rte_dev_iterator it;
1234         struct rte_device *dev;
1235
1236         /**
1237          *  We really need to iterate all devices regardless of
1238          *  their owner.
1239          */
1240         RTE_DEV_FOREACH(dev, "class=eth", &it)
1241                 if (dev == &pdev->device)
1242                         return it.class_device;
1243         return NULL;
1244 }
1245
1246 /**
1247  * DPDK callback to DMA map external memory to a PCI device.
1248  *
1249  * @param pdev
1250  *   Pointer to the PCI device.
1251  * @param addr
1252  *   Starting virtual address of memory to be mapped.
1253  * @param iova
1254  *   Starting IOVA address of memory to be mapped.
1255  * @param len
1256  *   Length of memory segment being mapped.
1257  *
1258  * @return
1259  *   0 on success, negative value on error.
1260  */
1261 int
1262 mlx5_dma_map(struct rte_pci_device *pdev, void *addr,
1263              uint64_t iova __rte_unused, size_t len)
1264 {
1265         struct rte_eth_dev *dev;
1266         struct mlx5_mr *mr;
1267         struct mlx5_priv *priv;
1268
1269         dev = pci_dev_to_eth_dev(pdev);
1270         if (!dev) {
1271                 DRV_LOG(WARNING, "unable to find matching ethdev "
1272                                  "to PCI device %p", (void *)pdev);
1273                 rte_errno = ENODEV;
1274                 return -1;
1275         }
1276         priv = dev->data->dev_private;
1277         mr = mlx5_create_mr_ext(dev, (uintptr_t)addr, len, SOCKET_ID_ANY);
1278         if (!mr) {
1279                 DRV_LOG(WARNING,
1280                         "port %u unable to dma map", dev->data->port_id);
1281                 rte_errno = EINVAL;
1282                 return -1;
1283         }
1284         rte_rwlock_write_lock(&priv->mr.rwlock);
1285         LIST_INSERT_HEAD(&priv->mr.mr_list, mr, mr);
1286         /* Insert to the global cache table. */
1287         mr_insert_dev_cache(dev, mr);
1288         rte_rwlock_write_unlock(&priv->mr.rwlock);
1289         return 0;
1290 }
1291
1292 /**
1293  * DPDK callback to DMA unmap external memory to a PCI device.
1294  *
1295  * @param pdev
1296  *   Pointer to the PCI device.
1297  * @param addr
1298  *   Starting virtual address of memory to be unmapped.
1299  * @param iova
1300  *   Starting IOVA address of memory to be unmapped.
1301  * @param len
1302  *   Length of memory segment being unmapped.
1303  *
1304  * @return
1305  *   0 on success, negative value on error.
1306  */
1307 int
1308 mlx5_dma_unmap(struct rte_pci_device *pdev, void *addr,
1309                uint64_t iova __rte_unused, size_t len __rte_unused)
1310 {
1311         struct rte_eth_dev *dev;
1312         struct mlx5_priv *priv;
1313         struct mlx5_mr *mr;
1314         struct mlx5_mr_cache entry;
1315
1316         dev = pci_dev_to_eth_dev(pdev);
1317         if (!dev) {
1318                 DRV_LOG(WARNING, "unable to find matching ethdev "
1319                                  "to PCI device %p", (void *)pdev);
1320                 rte_errno = ENODEV;
1321                 return -1;
1322         }
1323         priv = dev->data->dev_private;
1324         rte_rwlock_read_lock(&priv->mr.rwlock);
1325         mr = mr_lookup_dev_list(dev, &entry, (uintptr_t)addr);
1326         if (!mr) {
1327                 rte_rwlock_read_unlock(&priv->mr.rwlock);
1328                 DRV_LOG(WARNING, "address 0x%" PRIxPTR " wasn't registered "
1329                                  "to PCI device %p", (uintptr_t)addr,
1330                                  (void *)pdev);
1331                 rte_errno = EINVAL;
1332                 return -1;
1333         }
1334         LIST_REMOVE(mr, mr);
1335         LIST_INSERT_HEAD(&priv->mr.mr_free_list, mr, mr);
1336         DEBUG("port %u remove MR(%p) from list", dev->data->port_id,
1337               (void *)mr);
1338         mr_rebuild_dev_cache(dev);
1339         /*
1340          * Flush local caches by propagating invalidation across cores.
1341          * rte_smp_wmb() is enough to synchronize this event. If one of
1342          * freed memsegs is seen by other core, that means the memseg
1343          * has been allocated by allocator, which will come after this
1344          * free call. Therefore, this store instruction (incrementing
1345          * generation below) will be guaranteed to be seen by other core
1346          * before the core sees the newly allocated memory.
1347          */
1348         ++priv->mr.dev_gen;
1349         DEBUG("broadcasting local cache flush, gen=%d",
1350                         priv->mr.dev_gen);
1351         rte_smp_wmb();
1352         rte_rwlock_read_unlock(&priv->mr.rwlock);
1353         return 0;
1354 }
1355
1356 /**
1357  * Register MR for entire memory chunks in a Mempool having externally allocated
1358  * memory and fill in local cache.
1359  *
1360  * @param dev
1361  *   Pointer to Ethernet device.
1362  * @param mr_ctrl
1363  *   Pointer to per-queue MR control structure.
1364  * @param mp
1365  *   Pointer to registering Mempool.
1366  *
1367  * @return
1368  *   0 on success, -1 on failure.
1369  */
1370 static uint32_t
1371 mlx5_mr_update_ext_mp(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
1372                       struct rte_mempool *mp)
1373 {
1374         struct mr_update_mp_data data = {
1375                 .dev = dev,
1376                 .mr_ctrl = mr_ctrl,
1377                 .ret = 0,
1378         };
1379
1380         rte_mempool_mem_iter(mp, mlx5_mr_update_ext_mp_cb, &data);
1381         return data.ret;
1382 }
1383
1384 /**
1385  * Register MR entire memory chunks in a Mempool having externally allocated
1386  * memory and search LKey of the address to return.
1387  *
1388  * @param dev
1389  *   Pointer to Ethernet device.
1390  * @param addr
1391  *   Search key.
1392  * @param mp
1393  *   Pointer to registering Mempool where addr belongs.
1394  *
1395  * @return
1396  *   LKey for address on success, UINT32_MAX on failure.
1397  */
1398 uint32_t
1399 mlx5_tx_update_ext_mp(struct mlx5_txq_data *txq, uintptr_t addr,
1400                       struct rte_mempool *mp)
1401 {
1402         struct mlx5_txq_ctrl *txq_ctrl =
1403                 container_of(txq, struct mlx5_txq_ctrl, txq);
1404         struct mlx5_mr_ctrl *mr_ctrl = &txq->mr_ctrl;
1405         struct mlx5_priv *priv = txq_ctrl->priv;
1406
1407         mlx5_mr_update_ext_mp(ETH_DEV(priv), mr_ctrl, mp);
1408         return mlx5_tx_addr2mr_bh(txq, addr);
1409 }
1410
1411 /* Called during rte_mempool_mem_iter() by mlx5_mr_update_mp(). */
1412 static void
1413 mlx5_mr_update_mp_cb(struct rte_mempool *mp __rte_unused, void *opaque,
1414                      struct rte_mempool_memhdr *memhdr,
1415                      unsigned mem_idx __rte_unused)
1416 {
1417         struct mr_update_mp_data *data = opaque;
1418         uint32_t lkey;
1419
1420         /* Stop iteration if failed in the previous walk. */
1421         if (data->ret < 0)
1422                 return;
1423         /* Register address of the chunk and update local caches. */
1424         lkey = mlx5_mr_addr2mr_bh(data->dev, data->mr_ctrl,
1425                                   (uintptr_t)memhdr->addr);
1426         if (lkey == UINT32_MAX)
1427                 data->ret = -1;
1428 }
1429
1430 /**
1431  * Register entire memory chunks in a Mempool.
1432  *
1433  * @param dev
1434  *   Pointer to Ethernet device.
1435  * @param mr_ctrl
1436  *   Pointer to per-queue MR control structure.
1437  * @param mp
1438  *   Pointer to registering Mempool.
1439  *
1440  * @return
1441  *   0 on success, -1 on failure.
1442  */
1443 int
1444 mlx5_mr_update_mp(struct rte_eth_dev *dev, struct mlx5_mr_ctrl *mr_ctrl,
1445                   struct rte_mempool *mp)
1446 {
1447         struct mr_update_mp_data data = {
1448                 .dev = dev,
1449                 .mr_ctrl = mr_ctrl,
1450                 .ret = 0,
1451         };
1452
1453         rte_mempool_mem_iter(mp, mlx5_mr_update_mp_cb, &data);
1454         if (data.ret < 0 && rte_errno == ENXIO) {
1455                 /* Mempool may have externally allocated memory. */
1456                 return mlx5_mr_update_ext_mp(dev, mr_ctrl, mp);
1457         }
1458         return data.ret;
1459 }
1460
1461 /**
1462  * Dump all the created MRs and the global cache entries.
1463  *
1464  * @param dev
1465  *   Pointer to Ethernet device.
1466  */
1467 void
1468 mlx5_mr_dump_dev(struct rte_eth_dev *dev __rte_unused)
1469 {
1470 #ifndef NDEBUG
1471         struct mlx5_priv *priv = dev->data->dev_private;
1472         struct mlx5_mr *mr;
1473         int mr_n = 0;
1474         int chunk_n = 0;
1475
1476         rte_rwlock_read_lock(&priv->mr.rwlock);
1477         /* Iterate all the existing MRs. */
1478         LIST_FOREACH(mr, &priv->mr.mr_list, mr) {
1479                 unsigned int n;
1480
1481                 DEBUG("port %u MR[%u], LKey = 0x%x, ms_n = %u, ms_bmp_n = %u",
1482                       dev->data->port_id, mr_n++,
1483                       rte_cpu_to_be_32(mr->ibv_mr->lkey),
1484                       mr->ms_n, mr->ms_bmp_n);
1485                 if (mr->ms_n == 0)
1486                         continue;
1487                 for (n = 0; n < mr->ms_bmp_n; ) {
1488                         struct mlx5_mr_cache ret = { 0, };
1489
1490                         n = mr_find_next_chunk(mr, &ret, n);
1491                         if (!ret.end)
1492                                 break;
1493                         DEBUG("  chunk[%u], [0x%" PRIxPTR ", 0x%" PRIxPTR ")",
1494                               chunk_n++, ret.start, ret.end);
1495                 }
1496         }
1497         DEBUG("port %u dumping global cache", dev->data->port_id);
1498         mlx5_mr_btree_dump(&priv->mr.cache);
1499         rte_rwlock_read_unlock(&priv->mr.rwlock);
1500 #endif
1501 }
1502
1503 /**
1504  * Release all the created MRs and resources. Remove device from memory callback
1505  * list.
1506  *
1507  * @param dev
1508  *   Pointer to Ethernet device.
1509  */
1510 void
1511 mlx5_mr_release(struct rte_eth_dev *dev)
1512 {
1513         struct mlx5_priv *priv = dev->data->dev_private;
1514         struct mlx5_mr *mr_next = LIST_FIRST(&priv->mr.mr_list);
1515
1516         /* Remove from memory callback device list. */
1517         rte_rwlock_write_lock(&mlx5_shared_data->mem_event_rwlock);
1518         LIST_REMOVE(priv, mem_event_cb);
1519         rte_rwlock_write_unlock(&mlx5_shared_data->mem_event_rwlock);
1520         if (rte_log_get_level(mlx5_logtype) == RTE_LOG_DEBUG)
1521                 mlx5_mr_dump_dev(dev);
1522         rte_rwlock_write_lock(&priv->mr.rwlock);
1523         /* Detach from MR list and move to free list. */
1524         while (mr_next != NULL) {
1525                 struct mlx5_mr *mr = mr_next;
1526
1527                 mr_next = LIST_NEXT(mr, mr);
1528                 LIST_REMOVE(mr, mr);
1529                 LIST_INSERT_HEAD(&priv->mr.mr_free_list, mr, mr);
1530         }
1531         LIST_INIT(&priv->mr.mr_list);
1532         /* Free global cache. */
1533         mlx5_mr_btree_free(&priv->mr.cache);
1534         rte_rwlock_write_unlock(&priv->mr.rwlock);
1535         /* Free all remaining MRs. */
1536         mlx5_mr_garbage_collect(dev);
1537 }