common/mlx5: extend flex parser capabilities
[dpdk.git] / drivers / common / mlx5 / mlx5_common_mr.c
index e894523..53a3e85 100644 (file)
@@ -2,16 +2,22 @@
  * Copyright 2016 6WIND S.A.
  * Copyright 2020 Mellanox Technologies, Ltd
  */
+#include <stddef.h>
+
 #include <rte_eal_memconfig.h>
+#include <rte_eal_paging.h>
 #include <rte_errno.h>
 #include <rte_mempool.h>
 #include <rte_malloc.h>
 #include <rte_rwlock.h>
 
 #include "mlx5_glue.h"
+#include "mlx5_common.h"
 #include "mlx5_common_mp.h"
 #include "mlx5_common_mr.h"
-#include "mlx5_common_utils.h"
+#include "mlx5_common_os.h"
+#include "mlx5_common_log.h"
+#include "mlx5_malloc.h"
 
 struct mr_find_contig_memsegs_data {
        uintptr_t addr;
@@ -20,6 +26,43 @@ struct mr_find_contig_memsegs_data {
        const struct rte_memseg_list *msl;
 };
 
+/* Virtual memory range. */
+struct mlx5_range {
+       uintptr_t start;
+       uintptr_t end;
+};
+
+/** Memory region for a mempool. */
+struct mlx5_mempool_mr {
+       struct mlx5_pmd_mr pmd_mr;
+       uint32_t refcnt; /**< Number of mempools sharing this MR. */
+};
+
+/* Mempool registration. */
+struct mlx5_mempool_reg {
+       LIST_ENTRY(mlx5_mempool_reg) next;
+       /** Registered mempool, used to designate registrations. */
+       struct rte_mempool *mp;
+       /** Memory regions for the address ranges of the mempool. */
+       struct mlx5_mempool_mr *mrs;
+       /** Number of memory regions. */
+       unsigned int mrs_n;
+};
+
+void
+mlx5_mprq_buf_free_cb(void *addr __rte_unused, void *opaque)
+{
+       struct mlx5_mprq_buf *buf = opaque;
+
+       if (__atomic_load_n(&buf->refcnt, __ATOMIC_RELAXED) == 1) {
+               rte_mempool_put(buf->mp, buf);
+       } else if (unlikely(__atomic_sub_fetch(&buf->refcnt, 1,
+                                              __ATOMIC_RELAXED) == 0)) {
+               __atomic_store_n(&buf->refcnt, 1, __ATOMIC_RELAXED);
+               rte_mempool_put(buf->mp, buf);
+       }
+}
+
 /**
  * Expand B-tree table to a given size. Can't be called with holding
  * memory_hotplug_lock or share_cache.rwlock due to rte_realloc().
@@ -47,7 +90,8 @@ mr_btree_expand(struct mlx5_mr_btree *bt, int n)
         * Initially cache_bh[] will be given practically enough space and once
         * it is expanded, expansion wouldn't be needed again ever.
         */
-       mem = rte_realloc(bt->table, n * sizeof(struct mr_cache_entry), 0);
+       mem = mlx5_realloc(bt->table, MLX5_MEM_RTE | MLX5_MEM_ZERO,
+                          n * sizeof(struct mr_cache_entry), 0, SOCKET_ID_ANY);
        if (mem == NULL) {
                /* Not an error, B-tree search will be skipped. */
                DRV_LOG(WARNING, "failed to expand MR B-tree (%p) table",
@@ -171,7 +215,7 @@ mr_btree_insert(struct mlx5_mr_btree *bt, struct mr_cache_entry *entry)
  * @return
  *   0 on success, a negative errno value otherwise and rte_errno is set.
  */
-int
+static int
 mlx5_mr_btree_init(struct mlx5_mr_btree *bt, int n, int socket)
 {
        if (bt == NULL) {
@@ -180,13 +224,14 @@ mlx5_mr_btree_init(struct mlx5_mr_btree *bt, int n, int socket)
        }
        MLX5_ASSERT(!bt->table && !bt->size);
        memset(bt, 0, sizeof(*bt));
-       bt->table = rte_calloc_socket("B-tree table",
-                                     n, sizeof(struct mr_cache_entry),
-                                     0, socket);
+       bt->table = mlx5_malloc(MLX5_MEM_RTE | MLX5_MEM_ZERO,
+                               sizeof(struct mr_cache_entry) * n,
+                               0, socket);
        if (bt->table == NULL) {
                rte_errno = ENOMEM;
-               DEBUG("failed to allocate memory for btree cache on socket %d",
-                     socket);
+               DRV_LOG(DEBUG,
+                       "failed to allocate memory for btree cache on socket "
+                       "%d", socket);
                return -rte_errno;
        }
        bt->size = n;
@@ -194,7 +239,7 @@ mlx5_mr_btree_init(struct mlx5_mr_btree *bt, int n, int socket)
        (*bt->table)[bt->len++] = (struct mr_cache_entry) {
                .lkey = UINT32_MAX,
        };
-       DEBUG("initialized B-tree %p with table %p",
+       DRV_LOG(DEBUG, "initialized B-tree %p with table %p",
              (void *)bt, (void *)bt->table);
        return 0;
 }
@@ -210,9 +255,9 @@ mlx5_mr_btree_free(struct mlx5_mr_btree *bt)
 {
        if (bt == NULL)
                return;
-       DEBUG("freeing B-tree %p with table %p",
+       DRV_LOG(DEBUG, "freeing B-tree %p with table %p",
              (void *)bt, (void *)bt->table);
-       rte_free(bt->table);
+       mlx5_free(bt->table);
        memset(bt, 0, sizeof(*bt));
 }
 
@@ -235,13 +280,41 @@ mlx5_mr_btree_dump(struct mlx5_mr_btree *bt __rte_unused)
        for (idx = 0; idx < bt->len; ++idx) {
                struct mr_cache_entry *entry = &lkp_tbl[idx];
 
-               DEBUG("B-tree(%p)[%u],"
+               DRV_LOG(DEBUG, "B-tree(%p)[%u],"
                      " [0x%" PRIxPTR ", 0x%" PRIxPTR ") lkey=0x%x",
                      (void *)bt, idx, entry->start, entry->end, entry->lkey);
        }
 #endif
 }
 
+/**
+ * Initialize per-queue MR control descriptor.
+ *
+ * @param mr_ctrl
+ *   Pointer to MR control structure.
+ * @param dev_gen_ptr
+ *   Pointer to generation number of global cache.
+ * @param socket
+ *   NUMA socket on which memory must be allocated.
+ *
+ * @return
+ *   0 on success, a negative errno value otherwise and rte_errno is set.
+ */
+int
+mlx5_mr_ctrl_init(struct mlx5_mr_ctrl *mr_ctrl, uint32_t *dev_gen_ptr,
+                 int socket)
+{
+       if (mr_ctrl == NULL) {
+               rte_errno = EINVAL;
+               return -rte_errno;
+       }
+       /* Save pointer of global generation number to check memory event. */
+       mr_ctrl->dev_gen_ptr = dev_gen_ptr;
+       /* Initialize B-tree and allocate memory for bottom-half cache table. */
+       return mlx5_mr_btree_init(&mr_ctrl->cache_bh, MLX5_MR_BTREE_CACHE_N,
+                                 socket);
+}
+
 /**
  * Find virtually contiguous memory chunk in a given MR.
  *
@@ -266,18 +339,16 @@ mr_find_next_chunk(struct mlx5_mr *mr, struct mr_cache_entry *entry,
 
        /* MR for external memory doesn't have memseg list. */
        if (mr->msl == NULL) {
-               struct ibv_mr *ibv_mr = mr->ibv_mr;
-
                MLX5_ASSERT(mr->ms_bmp_n == 1);
                MLX5_ASSERT(mr->ms_n == 1);
                MLX5_ASSERT(base_idx == 0);
                /*
                 * Can't search it from memseg list but get it directly from
-                * verbs MR as there's only one chunk.
+                * pmd_mr as there's only one chunk.
                 */
-               entry->start = (uintptr_t)ibv_mr->addr;
-               entry->end = (uintptr_t)ibv_mr->addr + mr->ibv_mr->length;
-               entry->lkey = rte_cpu_to_be_32(mr->ibv_mr->lkey);
+               entry->start = (uintptr_t)mr->pmd_mr.addr;
+               entry->end = (uintptr_t)mr->pmd_mr.addr + mr->pmd_mr.len;
+               entry->lkey = rte_cpu_to_be_32(mr->pmd_mr.lkey);
                /* Returning 1 ends iteration. */
                return 1;
        }
@@ -302,7 +373,7 @@ mr_find_next_chunk(struct mlx5_mr *mr, struct mr_cache_entry *entry,
                /* Found one chunk. */
                entry->start = start;
                entry->end = end;
-               entry->lkey = rte_cpu_to_be_32(mr->ibv_mr->lkey);
+               entry->lkey = rte_cpu_to_be_32(mr->pmd_mr.lkey);
        }
        return idx;
 }
@@ -400,7 +471,7 @@ mlx5_mr_lookup_list(struct mlx5_mr_share_cache *share_cache,
  * @return
  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
  */
-uint32_t
+static uint32_t
 mlx5_mr_lookup_cache(struct mlx5_mr_share_cache *share_cache,
                     struct mr_cache_entry *entry, uintptr_t addr)
 {
@@ -436,17 +507,16 @@ mlx5_mr_lookup_cache(struct mlx5_mr_share_cache *share_cache,
  * @param mr
  *   Pointer to MR to free.
  */
-static void
-mr_free(struct mlx5_mr *mr)
+void
+mlx5_mr_free(struct mlx5_mr *mr, mlx5_dereg_mr_t dereg_mr_cb)
 {
        if (mr == NULL)
                return;
        DRV_LOG(DEBUG, "freeing MR(%p):", (void *)mr);
-       if (mr->ibv_mr != NULL)
-               claim_zero(mlx5_glue->dereg_mr(mr->ibv_mr));
+       dereg_mr_cb(&mr->pmd_mr);
        if (mr->ms_bmp != NULL)
                rte_bitmap_free(mr->ms_bmp);
-       rte_free(mr);
+       mlx5_free(mr);
 }
 
 void
@@ -493,7 +563,7 @@ mlx5_mr_garbage_collect(struct mlx5_mr_share_cache *share_cache)
                struct mlx5_mr *mr = mr_next;
 
                mr_next = LIST_NEXT(mr, mr);
-               mr_free(mr);
+               mlx5_mr_free(mr, share_cache->dereg_mr_cb);
        }
 }
 
@@ -522,6 +592,8 @@ mr_find_contig_memsegs_cb(const struct rte_memseg_list *msl,
  *
  * @param pd
  *   Pointer to pd of a device (net, regex, vdpa,...).
+ * @param mp_id
+ *   Multi-process identifier, may be NULL for the primary process.
  * @param share_cache
  *   Pointer to a global shared MR cache.
  * @param[out] entry
@@ -544,11 +616,15 @@ mlx5_mr_create_secondary(void *pd __rte_unused,
 {
        int ret;
 
-       DEBUG("port %u requesting MR creation for address (%p)",
+       if (mp_id == NULL) {
+               rte_errno = EINVAL;
+               return UINT32_MAX;
+       }
+       DRV_LOG(DEBUG, "port %u requesting MR creation for address (%p)",
              mp_id->port_id, (void *)addr);
        ret = mlx5_mp_req_mr_create(mp_id, addr);
        if (ret) {
-               DEBUG("Fail to request MR creation for address (%p)",
+               DRV_LOG(DEBUG, "Fail to request MR creation for address (%p)",
                      (void *)addr);
                return UINT32_MAX;
        }
@@ -558,7 +634,7 @@ mlx5_mr_create_secondary(void *pd __rte_unused,
        /* Lookup can't fail. */
        MLX5_ASSERT(entry->lkey != UINT32_MAX);
        rte_rwlock_read_unlock(&share_cache->rwlock);
-       DEBUG("MR CREATED by primary process for %p:\n"
+       DRV_LOG(DEBUG, "MR CREATED by primary process for %p:\n"
              "  [0x%" PRIxPTR ", 0x%" PRIxPTR "), lkey=0x%x",
              (void *)addr, entry->start, entry->end, entry->lkey);
        return entry->lkey;
@@ -648,18 +724,16 @@ alloc_resources:
        MLX5_ASSERT(msl->page_sz == ms->hugepage_sz);
        /* Number of memsegs in the range. */
        ms_n = len / msl->page_sz;
-       DEBUG("Extending %p to [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
+       DRV_LOG(DEBUG, "Extending %p to [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
              " page_sz=0x%" PRIx64 ", ms_n=%u",
              (void *)addr, data.start, data.end, msl->page_sz, ms_n);
        /* Size of memory for bitmap. */
        bmp_size = rte_bitmap_get_memory_footprint(ms_n);
-       mr = rte_zmalloc_socket(NULL,
-                               RTE_ALIGN_CEIL(sizeof(*mr),
-                                              RTE_CACHE_LINE_SIZE) +
-                               bmp_size,
-                               RTE_CACHE_LINE_SIZE, msl->socket_id);
+       mr = mlx5_malloc(MLX5_MEM_RTE |  MLX5_MEM_ZERO,
+                        RTE_ALIGN_CEIL(sizeof(*mr), RTE_CACHE_LINE_SIZE) +
+                        bmp_size, RTE_CACHE_LINE_SIZE, msl->socket_id);
        if (mr == NULL) {
-               DEBUG("Unable to allocate memory for a new MR of"
+               DRV_LOG(DEBUG, "Unable to allocate memory for a new MR of"
                      " address (%p).", (void *)addr);
                rte_errno = ENOMEM;
                goto err_nolock;
@@ -674,7 +748,7 @@ alloc_resources:
        bmp_mem = RTE_PTR_ALIGN_CEIL(mr + 1, RTE_CACHE_LINE_SIZE);
        mr->ms_bmp = rte_bitmap_init(ms_n, bmp_mem, bmp_size);
        if (mr->ms_bmp == NULL) {
-               DEBUG("Unable to initialize bitmap for a new MR of"
+               DRV_LOG(DEBUG, "Unable to initialize bitmap for a new MR of"
                      " address (%p).", (void *)addr);
                rte_errno = EINVAL;
                goto err_nolock;
@@ -691,9 +765,9 @@ alloc_resources:
        data_re = data;
        if (len > msl->page_sz &&
            !rte_memseg_contig_walk(mr_find_contig_memsegs_cb, &data_re)) {
-               DEBUG("Unable to find virtually contiguous"
-                     " chunk for address (%p)."
-                     " rte_memseg_contig_walk() failed.", (void *)addr);
+               DRV_LOG(DEBUG,
+                       "Unable to find virtually contiguous chunk for address "
+                       "(%p). rte_memseg_contig_walk() failed.", (void *)addr);
                rte_errno = ENXIO;
                goto err_memlock;
        }
@@ -705,7 +779,7 @@ alloc_resources:
                data.start = RTE_ALIGN_FLOOR(addr, msl->page_sz);
                data.end = data.start + msl->page_sz;
                rte_mcfg_mem_read_unlock();
-               mr_free(mr);
+               mlx5_mr_free(mr, share_cache->dereg_mr_cb);
                goto alloc_resources;
        }
        MLX5_ASSERT(data.msl == data_re.msl);
@@ -721,14 +795,15 @@ alloc_resources:
                 * here again.
                 */
                mr_btree_insert(&share_cache->cache, entry);
-               DEBUG("Found MR for %p on final lookup, abort", (void *)addr);
+               DRV_LOG(DEBUG, "Found MR for %p on final lookup, abort",
+                       (void *)addr);
                rte_rwlock_write_unlock(&share_cache->rwlock);
                rte_mcfg_mem_read_unlock();
                /*
                 * Must be unlocked before calling rte_free() because
                 * mlx5_mr_mem_event_free_cb() can be called inside.
                 */
-               mr_free(mr);
+               mlx5_mr_free(mr, share_cache->dereg_mr_cb);
                return entry->lkey;
        }
        /*
@@ -763,29 +838,26 @@ alloc_resources:
        mr->ms_bmp_n = len / msl->page_sz;
        MLX5_ASSERT(ms_idx_shift + mr->ms_bmp_n <= ms_n);
        /*
-        * Finally create a verbs MR for the memory chunk. ibv_reg_mr() can be
-        * called with holding the memory lock because it doesn't use
+        * Finally create an MR for the memory chunk. Verbs: ibv_reg_mr() can
+        * be called with holding the memory lock because it doesn't use
         * mlx5_alloc_buf_extern() which eventually calls rte_malloc_socket()
         * through mlx5_alloc_verbs_buf().
         */
-       mr->ibv_mr = mlx5_glue->reg_mr(pd, (void *)data.start, len,
-                                      IBV_ACCESS_LOCAL_WRITE |
-                                      (haswell_broadwell_cpu ? 0 :
-                                      IBV_ACCESS_RELAXED_ORDERING));
-       if (mr->ibv_mr == NULL) {
-               DEBUG("Fail to create a verbs MR for address (%p)",
+       share_cache->reg_mr_cb(pd, (void *)data.start, len, &mr->pmd_mr);
+       if (mr->pmd_mr.obj == NULL) {
+               DRV_LOG(DEBUG, "Fail to create an MR for address (%p)",
                      (void *)addr);
                rte_errno = EINVAL;
                goto err_mrlock;
        }
-       MLX5_ASSERT((uintptr_t)mr->ibv_mr->addr == data.start);
-       MLX5_ASSERT(mr->ibv_mr->length == len);
+       MLX5_ASSERT((uintptr_t)mr->pmd_mr.addr == data.start);
+       MLX5_ASSERT(mr->pmd_mr.len);
        LIST_INSERT_HEAD(&share_cache->mr_list, mr, mr);
-       DEBUG("MR CREATED (%p) for %p:\n"
+       DRV_LOG(DEBUG, "MR CREATED (%p) for %p:\n"
              "  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
              " lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
              (void *)mr, (void *)addr, data.start, data.end,
-             rte_cpu_to_be_32(mr->ibv_mr->lkey),
+             rte_cpu_to_be_32(mr->pmd_mr.lkey),
              mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
        /* Insert to the global cache table. */
        mlx5_mr_insert_cache(share_cache, mr);
@@ -807,7 +879,7 @@ err_nolock:
         * calling rte_free() because mlx5_mr_mem_event_free_cb() can be called
         * inside.
         */
-       mr_free(mr);
+       mlx5_mr_free(mr, share_cache->dereg_mr_cb);
        return UINT32_MAX;
 }
 
@@ -817,6 +889,8 @@ err_nolock:
  *
  * @param pd
  *   Pointer to pd handle of a device (net, regex, vdpa,...).
+ * @param mp_id
+ *   Multi-process identifier, may be NULL for the primary process.
  * @param share_cache
  *   Pointer to a global shared MR cache.
  * @param[out] entry
@@ -824,6 +898,8 @@ err_nolock:
  *   created. If failed to create one, this will not be updated.
  * @param addr
  *   Target virtual address to register.
+ * @param mr_ext_memseg_en
+ *   Configurable flag about external memory segment enable or not.
  *
  * @return
  *   Searched LKey on success, UINT32_MAX on failure and rte_errno is set.
@@ -857,6 +933,8 @@ mlx5_mr_create(void *pd, struct mlx5_mp_id *mp_id,
  *
  * @param pd
  *   Pointer to pd of a device (net, regex, vdpa,...).
+ * @param mp_id
+ *   Multi-process identifier, may be NULL for the primary process.
  * @param share_cache
  *   Pointer to a global shared MR cache.
  * @param mr_ctrl
@@ -866,6 +944,8 @@ mlx5_mr_create(void *pd, struct mlx5_mp_id *mp_id,
  *   created. If failed to create one, this is not written.
  * @param addr
  *   Search key.
+ * @param mr_ext_memseg_en
+ *   Configurable flag about external memory segment enable or not.
  *
  * @return
  *   Searched LKey on success, UINT32_MAX on no match.
@@ -921,20 +1001,25 @@ mr_lookup_caches(void *pd, struct mlx5_mp_id *mp_id,
  *
  * @param pd
  *   Pointer to pd of a device (net, regex, vdpa,...).
+ * @param mp_id
+ *   Multi-process identifier, may be NULL for the primary process.
  * @param share_cache
  *   Pointer to a global shared MR cache.
  * @param mr_ctrl
  *   Pointer to per-queue MR control structure.
  * @param addr
  *   Search key.
+ * @param mr_ext_memseg_en
+ *   Configurable flag about external memory segment enable or not.
  *
  * @return
  *   Searched LKey on success, UINT32_MAX on no match.
  */
-uint32_t mlx5_mr_addr2mr_bh(void *pd, struct mlx5_mp_id *mp_id,
-                           struct mlx5_mr_share_cache *share_cache,
-                           struct mlx5_mr_ctrl *mr_ctrl,
-                           uintptr_t addr, unsigned int mr_ext_memseg_en)
+static uint32_t
+mlx5_mr_addr2mr_bh(void *pd, struct mlx5_mp_id *mp_id,
+                  struct mlx5_mr_share_cache *share_cache,
+                  struct mlx5_mr_ctrl *mr_ctrl, uintptr_t addr,
+                  unsigned int mr_ext_memseg_en)
 {
        uint32_t lkey;
        uint16_t bh_idx = 0;
@@ -965,7 +1050,7 @@ uint32_t mlx5_mr_addr2mr_bh(void *pd, struct mlx5_mp_id *mp_id,
 }
 
 /**
- * Release all the created MRs and resources on global MR cache of a device.
+ * Release all the created MRs and resources on global MR cache of a device
  * list.
  *
  * @param share_cache
@@ -994,6 +1079,31 @@ mlx5_mr_release_cache(struct mlx5_mr_share_cache *share_cache)
        mlx5_mr_garbage_collect(share_cache);
 }
 
+/**
+ * Initialize global MR cache of a device.
+ *
+ * @param share_cache
+ *   Pointer to a global shared MR cache.
+ * @param socket
+ *   NUMA socket on which memory must be allocated.
+ *
+ * @return
+ *   0 on success, a negative errno value otherwise and rte_errno is set.
+ */
+int
+mlx5_mr_create_cache(struct mlx5_mr_share_cache *share_cache, int socket)
+{
+       /* Set the reg_mr and dereg_mr callback functions */
+       mlx5_os_set_reg_mr_cb(&share_cache->reg_mr_cb,
+                             &share_cache->dereg_mr_cb);
+       rte_rwlock_init(&share_cache->rwlock);
+       rte_rwlock_init(&share_cache->mprwlock);
+       share_cache->mp_cb_registered = 0;
+       /* Initialize B-tree and allocate memory for global MR cache table. */
+       return mlx5_mr_btree_init(&share_cache->cache,
+                                 MLX5_MR_BTREE_CACHE_N * 2, socket);
+}
+
 /**
  * Flush all of the local cache entries.
  *
@@ -1034,25 +1144,22 @@ mlx5_mr_flush_local_cache(struct mlx5_mr_ctrl *mr_ctrl)
  *   Pointer to MR structure on success, NULL otherwise.
  */
 struct mlx5_mr *
-mlx5_create_mr_ext(void *pd, uintptr_t addr, size_t len, int socket_id)
+mlx5_create_mr_ext(void *pd, uintptr_t addr, size_t len, int socket_id,
+                  mlx5_reg_mr_t reg_mr_cb)
 {
        struct mlx5_mr *mr = NULL;
 
-       mr = rte_zmalloc_socket(NULL,
-                               RTE_ALIGN_CEIL(sizeof(*mr),
-                                              RTE_CACHE_LINE_SIZE),
-                               RTE_CACHE_LINE_SIZE, socket_id);
+       mr = mlx5_malloc(MLX5_MEM_RTE | MLX5_MEM_ZERO,
+                        RTE_ALIGN_CEIL(sizeof(*mr), RTE_CACHE_LINE_SIZE),
+                        RTE_CACHE_LINE_SIZE, socket_id);
        if (mr == NULL)
                return NULL;
-       mr->ibv_mr = mlx5_glue->reg_mr(pd, (void *)addr, len,
-                                      IBV_ACCESS_LOCAL_WRITE |
-                                      (haswell_broadwell_cpu ? 0 :
-                                      IBV_ACCESS_RELAXED_ORDERING));
-       if (mr->ibv_mr == NULL) {
+       reg_mr_cb(pd, (void *)addr, len, &mr->pmd_mr);
+       if (mr->pmd_mr.obj == NULL) {
                DRV_LOG(WARNING,
-                       "Fail to create a verbs MR for address (%p)",
+                       "Fail to create MR for address (%p)",
                        (void *)addr);
-               rte_free(mr);
+               mlx5_free(mr);
                return NULL;
        }
        mr->msl = NULL; /* Mark it is external memory. */
@@ -1064,16 +1171,105 @@ mlx5_create_mr_ext(void *pd, uintptr_t addr, size_t len, int socket_id)
                "  [0x%" PRIxPTR ", 0x%" PRIxPTR "),"
                " lkey=0x%x base_idx=%u ms_n=%u, ms_bmp_n=%u",
                (void *)mr, (void *)addr,
-               addr, addr + len, rte_cpu_to_be_32(mr->ibv_mr->lkey),
+               addr, addr + len, rte_cpu_to_be_32(mr->pmd_mr.lkey),
                mr->ms_base_idx, mr->ms_n, mr->ms_bmp_n);
        return mr;
 }
 
+/**
+ * Callback for memory free event. Iterate freed memsegs and check whether it
+ * belongs to an existing MR. If found, clear the bit from bitmap of MR. As a
+ * result, the MR would be fragmented. If it becomes empty, the MR will be freed
+ * later by mlx5_mr_garbage_collect(). Even if this callback is called from a
+ * secondary process, the garbage collector will be called in primary process
+ * as the secondary process can't call mlx5_mr_create().
+ *
+ * The global cache must be rebuilt if there's any change and this event has to
+ * be propagated to dataplane threads to flush the local caches.
+ *
+ * @param share_cache
+ *   Pointer to a global shared MR cache.
+ * @param ibdev_name
+ *   Name of ibv device.
+ * @param addr
+ *   Address of freed memory.
+ * @param len
+ *   Size of freed memory.
+ */
+void
+mlx5_free_mr_by_addr(struct mlx5_mr_share_cache *share_cache,
+                    const char *ibdev_name, const void *addr, size_t len)
+{
+       const struct rte_memseg_list *msl;
+       struct mlx5_mr *mr;
+       int ms_n;
+       int i;
+       int rebuild = 0;
+
+       DRV_LOG(DEBUG, "device %s free callback: addr=%p, len=%zu",
+               ibdev_name, addr, len);
+       msl = rte_mem_virt2memseg_list(addr);
+       /* addr and len must be page-aligned. */
+       MLX5_ASSERT((uintptr_t)addr ==
+                   RTE_ALIGN((uintptr_t)addr, msl->page_sz));
+       MLX5_ASSERT(len == RTE_ALIGN(len, msl->page_sz));
+       ms_n = len / msl->page_sz;
+       rte_rwlock_write_lock(&share_cache->rwlock);
+       /* Clear bits of freed memsegs from MR. */
+       for (i = 0; i < ms_n; ++i) {
+               const struct rte_memseg *ms;
+               struct mr_cache_entry entry;
+               uintptr_t start;
+               int ms_idx;
+               uint32_t pos;
+
+               /* Find MR having this memseg. */
+               start = (uintptr_t)addr + i * msl->page_sz;
+               mr = mlx5_mr_lookup_list(share_cache, &entry, start);
+               if (mr == NULL)
+                       continue;
+               MLX5_ASSERT(mr->msl); /* Can't be external memory. */
+               ms = rte_mem_virt2memseg((void *)start, msl);
+               MLX5_ASSERT(ms != NULL);
+               MLX5_ASSERT(msl->page_sz == ms->hugepage_sz);
+               ms_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
+               pos = ms_idx - mr->ms_base_idx;
+               MLX5_ASSERT(rte_bitmap_get(mr->ms_bmp, pos));
+               MLX5_ASSERT(pos < mr->ms_bmp_n);
+               DRV_LOG(DEBUG, "device %s MR(%p): clear bitmap[%u] for addr %p",
+                       ibdev_name, (void *)mr, pos, (void *)start);
+               rte_bitmap_clear(mr->ms_bmp, pos);
+               if (--mr->ms_n == 0) {
+                       LIST_REMOVE(mr, mr);
+                       LIST_INSERT_HEAD(&share_cache->mr_free_list, mr, mr);
+                       DRV_LOG(DEBUG, "device %s remove MR(%p) from list",
+                               ibdev_name, (void *)mr);
+               }
+               /*
+                * MR is fragmented or will be freed. the global cache must be
+                * rebuilt.
+                */
+               rebuild = 1;
+       }
+       if (rebuild) {
+               mlx5_mr_rebuild_cache(share_cache);
+               /*
+                * No explicit wmb is needed after updating dev_gen due to
+                * store-release ordering in unlock that provides the
+                * implicit barrier at the software visible level.
+                */
+               ++share_cache->dev_gen;
+               DRV_LOG(DEBUG, "broadcasting local cache flush, gen=%d",
+                       share_cache->dev_gen);
+       }
+       rte_rwlock_write_unlock(&share_cache->rwlock);
+}
+
 /**
  * Dump all the created MRs and the global cache entries.
  *
- * @param sh
- *   Pointer to Ethernet device shared context.
+ * @param share_cache
+ *   Pointer to a global shared MR cache.
  */
 void
 mlx5_mr_dump_cache(struct mlx5_mr_share_cache *share_cache __rte_unused)
@@ -1088,8 +1284,8 @@ mlx5_mr_dump_cache(struct mlx5_mr_share_cache *share_cache __rte_unused)
        LIST_FOREACH(mr, &share_cache->mr_list, mr) {
                unsigned int n;
 
-               DEBUG("MR[%u], LKey = 0x%x, ms_n = %u, ms_bmp_n = %u",
-                     mr_n++, rte_cpu_to_be_32(mr->ibv_mr->lkey),
+               DRV_LOG(DEBUG, "MR[%u], LKey = 0x%x, ms_n = %u, ms_bmp_n = %u",
+                     mr_n++, rte_cpu_to_be_32(mr->pmd_mr.lkey),
                      mr->ms_n, mr->ms_bmp_n);
                if (mr->ms_n == 0)
                        continue;
@@ -1099,12 +1295,649 @@ mlx5_mr_dump_cache(struct mlx5_mr_share_cache *share_cache __rte_unused)
                        n = mr_find_next_chunk(mr, &ret, n);
                        if (!ret.end)
                                break;
-                       DEBUG("  chunk[%u], [0x%" PRIxPTR ", 0x%" PRIxPTR ")",
-                             chunk_n++, ret.start, ret.end);
+                       DRV_LOG(DEBUG,
+                               "  chunk[%u], [0x%" PRIxPTR ", 0x%" PRIxPTR ")",
+                               chunk_n++, ret.start, ret.end);
                }
        }
-       DEBUG("Dumping global cache %p", (void *)share_cache);
+       DRV_LOG(DEBUG, "Dumping global cache %p", (void *)share_cache);
        mlx5_mr_btree_dump(&share_cache->cache);
        rte_rwlock_read_unlock(&share_cache->rwlock);
 #endif
 }
+
+static int
+mlx5_range_compare_start(const void *lhs, const void *rhs)
+{
+       const struct mlx5_range *r1 = lhs, *r2 = rhs;
+
+       if (r1->start > r2->start)
+               return 1;
+       else if (r1->start < r2->start)
+               return -1;
+       return 0;
+}
+
+static void
+mlx5_range_from_mempool_chunk(struct rte_mempool *mp, void *opaque,
+                             struct rte_mempool_memhdr *memhdr,
+                             unsigned int idx)
+{
+       struct mlx5_range *ranges = opaque, *range = &ranges[idx];
+       uint64_t page_size = rte_mem_page_size();
+
+       RTE_SET_USED(mp);
+       range->start = RTE_ALIGN_FLOOR((uintptr_t)memhdr->addr, page_size);
+       range->end = RTE_ALIGN_CEIL(range->start + memhdr->len, page_size);
+}
+
+/**
+ * Get VA-contiguous ranges of the mempool memory.
+ * Each range start and end is aligned to the system page size.
+ *
+ * @param[in] mp
+ *   Analyzed mempool.
+ * @param[out] out
+ *   Receives the ranges, caller must release it with free().
+ * @param[out] ount_n
+ *   Receives the number of @p out elements.
+ *
+ * @return
+ *   0 on success, (-1) on failure.
+ */
+static int
+mlx5_get_mempool_ranges(struct rte_mempool *mp, struct mlx5_range **out,
+                       unsigned int *out_n)
+{
+       struct mlx5_range *chunks;
+       unsigned int chunks_n = mp->nb_mem_chunks, contig_n, i;
+
+       /* Collect page-aligned memory ranges of the mempool. */
+       chunks = calloc(sizeof(chunks[0]), chunks_n);
+       if (chunks == NULL)
+               return -1;
+       rte_mempool_mem_iter(mp, mlx5_range_from_mempool_chunk, chunks);
+       /* Merge adjacent chunks and place them at the beginning. */
+       qsort(chunks, chunks_n, sizeof(chunks[0]), mlx5_range_compare_start);
+       contig_n = 1;
+       for (i = 1; i < chunks_n; i++)
+               if (chunks[i - 1].end != chunks[i].start) {
+                       chunks[contig_n - 1].end = chunks[i - 1].end;
+                       chunks[contig_n] = chunks[i];
+                       contig_n++;
+               }
+       /* Extend the last contiguous chunk to the end of the mempool. */
+       chunks[contig_n - 1].end = chunks[i - 1].end;
+       *out = chunks;
+       *out_n = contig_n;
+       return 0;
+}
+
+/**
+ * Analyze mempool memory to select memory ranges to register.
+ *
+ * @param[in] mp
+ *   Mempool to analyze.
+ * @param[out] out
+ *   Receives memory ranges to register, aligned to the system page size.
+ *   The caller must release them with free().
+ * @param[out] out_n
+ *   Receives the number of @p out items.
+ * @param[out] share_hugepage
+ *   Receives True if the entire pool resides within a single hugepage.
+ *
+ * @return
+ *   0 on success, (-1) on failure.
+ */
+static int
+mlx5_mempool_reg_analyze(struct rte_mempool *mp, struct mlx5_range **out,
+                        unsigned int *out_n, bool *share_hugepage)
+{
+       struct mlx5_range *ranges = NULL;
+       unsigned int i, ranges_n = 0;
+       struct rte_memseg_list *msl;
+
+       if (mlx5_get_mempool_ranges(mp, &ranges, &ranges_n) < 0) {
+               DRV_LOG(ERR, "Cannot get address ranges for mempool %s",
+                       mp->name);
+               return -1;
+       }
+       /* Check if the hugepage of the pool can be shared. */
+       *share_hugepage = false;
+       msl = rte_mem_virt2memseg_list((void *)ranges[0].start);
+       if (msl != NULL) {
+               uint64_t hugepage_sz = 0;
+
+               /* Check that all ranges are on pages of the same size. */
+               for (i = 0; i < ranges_n; i++) {
+                       if (hugepage_sz != 0 && hugepage_sz != msl->page_sz)
+                               break;
+                       hugepage_sz = msl->page_sz;
+               }
+               if (i == ranges_n) {
+                       /*
+                        * If the entire pool is within one hugepage,
+                        * combine all ranges into one of the hugepage size.
+                        */
+                       uintptr_t reg_start = ranges[0].start;
+                       uintptr_t reg_end = ranges[ranges_n - 1].end;
+                       uintptr_t hugepage_start =
+                               RTE_ALIGN_FLOOR(reg_start, hugepage_sz);
+                       uintptr_t hugepage_end = hugepage_start + hugepage_sz;
+                       if (reg_end < hugepage_end) {
+                               ranges[0].start = hugepage_start;
+                               ranges[0].end = hugepage_end;
+                               ranges_n = 1;
+                               *share_hugepage = true;
+                       }
+               }
+       }
+       *out = ranges;
+       *out_n = ranges_n;
+       return 0;
+}
+
+/** Create a registration object for the mempool. */
+static struct mlx5_mempool_reg *
+mlx5_mempool_reg_create(struct rte_mempool *mp, unsigned int mrs_n)
+{
+       struct mlx5_mempool_reg *mpr = NULL;
+
+       mpr = mlx5_malloc(MLX5_MEM_RTE | MLX5_MEM_ZERO,
+                         sizeof(*mpr) + mrs_n * sizeof(mpr->mrs[0]),
+                         RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
+       if (mpr == NULL) {
+               DRV_LOG(ERR, "Cannot allocate mempool %s registration object",
+                       mp->name);
+               return NULL;
+       }
+       mpr->mp = mp;
+       mpr->mrs = (struct mlx5_mempool_mr *)(mpr + 1);
+       mpr->mrs_n = mrs_n;
+       return mpr;
+}
+
+/**
+ * Destroy a mempool registration object.
+ *
+ * @param standalone
+ *   Whether @p mpr owns its MRs excludively, i.e. they are not shared.
+ */
+static void
+mlx5_mempool_reg_destroy(struct mlx5_mr_share_cache *share_cache,
+                        struct mlx5_mempool_reg *mpr, bool standalone)
+{
+       if (standalone) {
+               unsigned int i;
+
+               for (i = 0; i < mpr->mrs_n; i++)
+                       share_cache->dereg_mr_cb(&mpr->mrs[i].pmd_mr);
+       }
+       mlx5_free(mpr);
+}
+
+/** Find registration object of a mempool. */
+static struct mlx5_mempool_reg *
+mlx5_mempool_reg_lookup(struct mlx5_mr_share_cache *share_cache,
+                       struct rte_mempool *mp)
+{
+       struct mlx5_mempool_reg *mpr;
+
+       LIST_FOREACH(mpr, &share_cache->mempool_reg_list, next)
+               if (mpr->mp == mp)
+                       break;
+       return mpr;
+}
+
+/** Increment reference counters of MRs used in the registration. */
+static void
+mlx5_mempool_reg_attach(struct mlx5_mempool_reg *mpr)
+{
+       unsigned int i;
+
+       for (i = 0; i < mpr->mrs_n; i++)
+               __atomic_add_fetch(&mpr->mrs[i].refcnt, 1, __ATOMIC_RELAXED);
+}
+
+/**
+ * Decrement reference counters of MRs used in the registration.
+ *
+ * @return True if no more references to @p mpr MRs exist, False otherwise.
+ */
+static bool
+mlx5_mempool_reg_detach(struct mlx5_mempool_reg *mpr)
+{
+       unsigned int i;
+       bool ret = false;
+
+       for (i = 0; i < mpr->mrs_n; i++)
+               ret |= __atomic_sub_fetch(&mpr->mrs[i].refcnt, 1,
+                                         __ATOMIC_RELAXED) == 0;
+       return ret;
+}
+
+static int
+mlx5_mr_mempool_register_primary(struct mlx5_mr_share_cache *share_cache,
+                                void *pd, struct rte_mempool *mp)
+{
+       struct mlx5_range *ranges = NULL;
+       struct mlx5_mempool_reg *mpr, *new_mpr;
+       unsigned int i, ranges_n;
+       bool share_hugepage;
+       int ret = -1;
+
+       /* Early check to avoid unnecessary creation of MRs. */
+       rte_rwlock_read_lock(&share_cache->rwlock);
+       mpr = mlx5_mempool_reg_lookup(share_cache, mp);
+       rte_rwlock_read_unlock(&share_cache->rwlock);
+       if (mpr != NULL) {
+               DRV_LOG(DEBUG, "Mempool %s is already registered for PD %p",
+                       mp->name, pd);
+               rte_errno = EEXIST;
+               goto exit;
+       }
+       if (mlx5_mempool_reg_analyze(mp, &ranges, &ranges_n,
+                                    &share_hugepage) < 0) {
+               DRV_LOG(ERR, "Cannot get mempool %s memory ranges", mp->name);
+               rte_errno = ENOMEM;
+               goto exit;
+       }
+       new_mpr = mlx5_mempool_reg_create(mp, ranges_n);
+       if (new_mpr == NULL) {
+               DRV_LOG(ERR,
+                       "Cannot create a registration object for mempool %s in PD %p",
+                       mp->name, pd);
+               rte_errno = ENOMEM;
+               goto exit;
+       }
+       /*
+        * If the entire mempool fits in a single hugepage, the MR for this
+        * hugepage can be shared across mempools that also fit in it.
+        */
+       if (share_hugepage) {
+               rte_rwlock_write_lock(&share_cache->rwlock);
+               LIST_FOREACH(mpr, &share_cache->mempool_reg_list, next) {
+                       if (mpr->mrs[0].pmd_mr.addr == (void *)ranges[0].start)
+                               break;
+               }
+               if (mpr != NULL) {
+                       new_mpr->mrs = mpr->mrs;
+                       mlx5_mempool_reg_attach(new_mpr);
+                       LIST_INSERT_HEAD(&share_cache->mempool_reg_list,
+                                        new_mpr, next);
+               }
+               rte_rwlock_write_unlock(&share_cache->rwlock);
+               if (mpr != NULL) {
+                       DRV_LOG(DEBUG, "Shared MR %#x in PD %p for mempool %s with mempool %s",
+                               mpr->mrs[0].pmd_mr.lkey, pd, mp->name,
+                               mpr->mp->name);
+                       ret = 0;
+                       goto exit;
+               }
+       }
+       for (i = 0; i < ranges_n; i++) {
+               struct mlx5_mempool_mr *mr = &new_mpr->mrs[i];
+               const struct mlx5_range *range = &ranges[i];
+               size_t len = range->end - range->start;
+
+               if (share_cache->reg_mr_cb(pd, (void *)range->start, len,
+                   &mr->pmd_mr) < 0) {
+                       DRV_LOG(ERR,
+                               "Failed to create an MR in PD %p for address range "
+                               "[0x%" PRIxPTR ", 0x%" PRIxPTR "] (%zu bytes) for mempool %s",
+                               pd, range->start, range->end, len, mp->name);
+                       break;
+               }
+               DRV_LOG(DEBUG,
+                       "Created a new MR %#x in PD %p for address range "
+                       "[0x%" PRIxPTR ", 0x%" PRIxPTR "] (%zu bytes) for mempool %s",
+                       mr->pmd_mr.lkey, pd, range->start, range->end, len,
+                       mp->name);
+       }
+       if (i != ranges_n) {
+               mlx5_mempool_reg_destroy(share_cache, new_mpr, true);
+               rte_errno = EINVAL;
+               goto exit;
+       }
+       /* Concurrent registration is not supposed to happen. */
+       rte_rwlock_write_lock(&share_cache->rwlock);
+       mpr = mlx5_mempool_reg_lookup(share_cache, mp);
+       if (mpr == NULL) {
+               mlx5_mempool_reg_attach(new_mpr);
+               LIST_INSERT_HEAD(&share_cache->mempool_reg_list, new_mpr, next);
+               ret = 0;
+       }
+       rte_rwlock_write_unlock(&share_cache->rwlock);
+       if (mpr != NULL) {
+               DRV_LOG(DEBUG, "Mempool %s is already registered for PD %p",
+                       mp->name, pd);
+               mlx5_mempool_reg_destroy(share_cache, new_mpr, true);
+               rte_errno = EEXIST;
+               goto exit;
+       }
+exit:
+       free(ranges);
+       return ret;
+}
+
+static int
+mlx5_mr_mempool_register_secondary(struct mlx5_mr_share_cache *share_cache,
+                                  void *pd, struct rte_mempool *mp,
+                                  struct mlx5_mp_id *mp_id)
+{
+       if (mp_id == NULL) {
+               rte_errno = EINVAL;
+               return -1;
+       }
+       return mlx5_mp_req_mempool_reg(mp_id, share_cache, pd, mp, true);
+}
+
+/**
+ * Register the memory of a mempool in the protection domain.
+ *
+ * @param share_cache
+ *   Shared MR cache of the protection domain.
+ * @param pd
+ *   Protection domain object.
+ * @param mp
+ *   Mempool to register.
+ * @param mp_id
+ *   Multi-process identifier, may be NULL for the primary process.
+ *
+ * @return
+ *   0 on success, (-1) on failure and rte_errno is set.
+ */
+int
+mlx5_mr_mempool_register(struct mlx5_mr_share_cache *share_cache, void *pd,
+                        struct rte_mempool *mp, struct mlx5_mp_id *mp_id)
+{
+       if (mp->flags & RTE_MEMPOOL_F_NON_IO)
+               return 0;
+       switch (rte_eal_process_type()) {
+       case RTE_PROC_PRIMARY:
+               return mlx5_mr_mempool_register_primary(share_cache, pd, mp);
+       case RTE_PROC_SECONDARY:
+               return mlx5_mr_mempool_register_secondary(share_cache, pd, mp,
+                                                         mp_id);
+       default:
+               return -1;
+       }
+}
+
+static int
+mlx5_mr_mempool_unregister_primary(struct mlx5_mr_share_cache *share_cache,
+                                  struct rte_mempool *mp)
+{
+       struct mlx5_mempool_reg *mpr;
+       bool standalone = false;
+
+       rte_rwlock_write_lock(&share_cache->rwlock);
+       LIST_FOREACH(mpr, &share_cache->mempool_reg_list, next)
+               if (mpr->mp == mp) {
+                       LIST_REMOVE(mpr, next);
+                       standalone = mlx5_mempool_reg_detach(mpr);
+                       if (standalone)
+                               /*
+                                * The unlock operation below provides a memory
+                                * barrier due to its store-release semantics.
+                                */
+                               ++share_cache->dev_gen;
+                       break;
+               }
+       rte_rwlock_write_unlock(&share_cache->rwlock);
+       if (mpr == NULL) {
+               rte_errno = ENOENT;
+               return -1;
+       }
+       mlx5_mempool_reg_destroy(share_cache, mpr, standalone);
+       return 0;
+}
+
+static int
+mlx5_mr_mempool_unregister_secondary(struct mlx5_mr_share_cache *share_cache,
+                                    struct rte_mempool *mp,
+                                    struct mlx5_mp_id *mp_id)
+{
+       if (mp_id == NULL) {
+               rte_errno = EINVAL;
+               return -1;
+       }
+       return mlx5_mp_req_mempool_reg(mp_id, share_cache, NULL, mp, false);
+}
+
+/**
+ * Unregister the memory of a mempool from the protection domain.
+ *
+ * @param share_cache
+ *   Shared MR cache of the protection domain.
+ * @param mp
+ *   Mempool to unregister.
+ * @param mp_id
+ *   Multi-process identifier, may be NULL for the primary process.
+ *
+ * @return
+ *   0 on success, (-1) on failure and rte_errno is set.
+ */
+int
+mlx5_mr_mempool_unregister(struct mlx5_mr_share_cache *share_cache,
+                          struct rte_mempool *mp, struct mlx5_mp_id *mp_id)
+{
+       if (mp->flags & RTE_MEMPOOL_F_NON_IO)
+               return 0;
+       switch (rte_eal_process_type()) {
+       case RTE_PROC_PRIMARY:
+               return mlx5_mr_mempool_unregister_primary(share_cache, mp);
+       case RTE_PROC_SECONDARY:
+               return mlx5_mr_mempool_unregister_secondary(share_cache, mp,
+                                                           mp_id);
+       default:
+               return -1;
+       }
+}
+
+/**
+ * Lookup a MR key by and address in a registered mempool.
+ *
+ * @param mpr
+ *   Mempool registration object.
+ * @param addr
+ *   Address within the mempool.
+ * @param entry
+ *   Bottom-half cache entry to fill.
+ *
+ * @return
+ *   MR key or UINT32_MAX on failure, which can only happen
+ *   if the address is not from within the mempool.
+ */
+static uint32_t
+mlx5_mempool_reg_addr2mr(struct mlx5_mempool_reg *mpr, uintptr_t addr,
+                        struct mr_cache_entry *entry)
+{
+       uint32_t lkey = UINT32_MAX;
+       unsigned int i;
+
+       for (i = 0; i < mpr->mrs_n; i++) {
+               const struct mlx5_pmd_mr *mr = &mpr->mrs[i].pmd_mr;
+               uintptr_t mr_addr = (uintptr_t)mr->addr;
+
+               if (mr_addr <= addr) {
+                       lkey = rte_cpu_to_be_32(mr->lkey);
+                       entry->start = mr_addr;
+                       entry->end = mr_addr + mr->len;
+                       entry->lkey = lkey;
+                       break;
+               }
+       }
+       return lkey;
+}
+
+/**
+ * Update bottom-half cache from the list of mempool registrations.
+ *
+ * @param share_cache
+ *   Pointer to a global shared MR cache.
+ * @param mr_ctrl
+ *   Per-queue MR control handle.
+ * @param entry
+ *   Pointer to an entry in the bottom-half cache to update
+ *   with the MR lkey looked up.
+ * @param mp
+ *   Mempool containing the address.
+ * @param addr
+ *   Address to lookup.
+ * @return
+ *   MR lkey on success, UINT32_MAX on failure.
+ */
+static uint32_t
+mlx5_lookup_mempool_regs(struct mlx5_mr_share_cache *share_cache,
+                        struct mlx5_mr_ctrl *mr_ctrl,
+                        struct mr_cache_entry *entry,
+                        struct rte_mempool *mp, uintptr_t addr)
+{
+       struct mlx5_mr_btree *bt = &mr_ctrl->cache_bh;
+       struct mlx5_mempool_reg *mpr;
+       uint32_t lkey = UINT32_MAX;
+
+       /* If local cache table is full, try to double it. */
+       if (unlikely(bt->len == bt->size))
+               mr_btree_expand(bt, bt->size << 1);
+       /* Look up in mempool registrations. */
+       rte_rwlock_read_lock(&share_cache->rwlock);
+       mpr = mlx5_mempool_reg_lookup(share_cache, mp);
+       if (mpr != NULL)
+               lkey = mlx5_mempool_reg_addr2mr(mpr, addr, entry);
+       rte_rwlock_read_unlock(&share_cache->rwlock);
+       /*
+        * Update local cache. Even if it fails, return the found entry
+        * to update top-half cache. Next time, this entry will be found
+        * in the global cache.
+        */
+       if (lkey != UINT32_MAX)
+               mr_btree_insert(bt, entry);
+       return lkey;
+}
+
+/**
+ * Bottom-half lookup for the address from the mempool.
+ *
+ * @param share_cache
+ *   Pointer to a global shared MR cache.
+ * @param mr_ctrl
+ *   Per-queue MR control handle.
+ * @param mp
+ *   Mempool containing the address.
+ * @param addr
+ *   Address to lookup.
+ * @return
+ *   MR lkey on success, UINT32_MAX on failure.
+ */
+uint32_t
+mlx5_mr_mempool2mr_bh(struct mlx5_mr_share_cache *share_cache,
+                     struct mlx5_mr_ctrl *mr_ctrl,
+                     struct rte_mempool *mp, uintptr_t addr)
+{
+       struct mr_cache_entry *repl = &mr_ctrl->cache[mr_ctrl->head];
+       uint32_t lkey;
+       uint16_t bh_idx = 0;
+
+       /* Binary-search MR translation table. */
+       lkey = mr_btree_lookup(&mr_ctrl->cache_bh, &bh_idx, addr);
+       /* Update top-half cache. */
+       if (likely(lkey != UINT32_MAX)) {
+               *repl = (*mr_ctrl->cache_bh.table)[bh_idx];
+       } else {
+               lkey = mlx5_lookup_mempool_regs(share_cache, mr_ctrl, repl,
+                                               mp, addr);
+               /* Can only fail if the address is not from the mempool. */
+               if (unlikely(lkey == UINT32_MAX))
+                       return UINT32_MAX;
+       }
+       /* Update the most recently used entry. */
+       mr_ctrl->mru = mr_ctrl->head;
+       /* Point to the next victim, the oldest. */
+       mr_ctrl->head = (mr_ctrl->head + 1) % MLX5_MR_CACHE_N;
+       return lkey;
+}
+
+/**
+ * Bottom-half of LKey search on. If supported, lookup for the address from
+ * the mempool. Otherwise, search in old mechanism caches.
+ *
+ * @param cdev
+ *   Pointer to mlx5 device.
+ * @param mp_id
+ *   Multi-process identifier, may be NULL for the primary process.
+ * @param mr_ctrl
+ *   Pointer to per-queue MR control structure.
+ * @param mb
+ *   Pointer to mbuf.
+ *
+ * @return
+ *   Searched LKey on success, UINT32_MAX on no match.
+ */
+static uint32_t
+mlx5_mr_mb2mr_bh(struct mlx5_common_device *cdev, struct mlx5_mp_id *mp_id,
+                struct mlx5_mr_ctrl *mr_ctrl, struct rte_mbuf *mb)
+{
+       uint32_t lkey;
+       uintptr_t addr = (uintptr_t)mb->buf_addr;
+
+       if (cdev->config.mr_mempool_reg_en) {
+               struct rte_mempool *mp = NULL;
+               struct mlx5_mprq_buf *buf;
+
+               if (!RTE_MBUF_HAS_EXTBUF(mb)) {
+                       mp = mlx5_mb2mp(mb);
+               } else if (mb->shinfo->free_cb == mlx5_mprq_buf_free_cb) {
+                       /* Recover MPRQ mempool. */
+                       buf = mb->shinfo->fcb_opaque;
+                       mp = buf->mp;
+               }
+               if (mp != NULL) {
+                       lkey = mlx5_mr_mempool2mr_bh(&cdev->mr_scache,
+                                                    mr_ctrl, mp, addr);
+                       /*
+                        * Lookup can only fail on invalid input, e.g. "addr"
+                        * is not from "mp" or "mp" has MEMPOOL_F_NON_IO set.
+                        */
+                       if (lkey != UINT32_MAX)
+                               return lkey;
+               }
+               /* Fallback for generic mechanism in corner cases. */
+       }
+       return mlx5_mr_addr2mr_bh(cdev->pd, mp_id, &cdev->mr_scache, mr_ctrl,
+                                 addr, cdev->config.mr_ext_memseg_en);
+}
+
+/**
+ * Query LKey from a packet buffer.
+ *
+ * @param cdev
+ *   Pointer to the mlx5 device structure.
+ * @param mp_id
+ *   Multi-process identifier, may be NULL for the primary process.
+ * @param mr_ctrl
+ *   Pointer to per-queue MR control structure.
+ * @param mbuf
+ *   Pointer to mbuf.
+ *
+ * @return
+ *   Searched LKey on success, UINT32_MAX on no match.
+ */
+uint32_t
+mlx5_mr_mb2mr(struct mlx5_common_device *cdev, struct mlx5_mp_id *mp_id,
+             struct mlx5_mr_ctrl *mr_ctrl, struct rte_mbuf *mbuf)
+{
+       uint32_t lkey;
+
+       /* Check generation bit to see if there's any change on existing MRs. */
+       if (unlikely(*mr_ctrl->dev_gen_ptr != mr_ctrl->cur_gen))
+               mlx5_mr_flush_local_cache(mr_ctrl);
+       /* Linear search on MR cache array. */
+       lkey = mlx5_mr_lookup_lkey(mr_ctrl->cache, &mr_ctrl->mru,
+                                  MLX5_MR_CACHE_N, (uintptr_t)mbuf->buf_addr);
+       if (likely(lkey != UINT32_MAX))
+               return lkey;
+       /* Take slower bottom-half on miss. */
+       return mlx5_mr_mb2mr_bh(cdev, mp_id, mr_ctrl, mbuf);
+}