mempool: fix slow allocation of large mempools
[dpdk.git] / lib / librte_hash / rte_cuckoo_hash.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2016 Intel Corporation
3  * Copyright(c) 2018 Arm Limited
4  */
5
6 #include <string.h>
7 #include <stdint.h>
8 #include <errno.h>
9 #include <stdio.h>
10 #include <stdarg.h>
11 #include <sys/queue.h>
12
13 #include <rte_common.h>
14 #include <rte_memory.h>         /* for definition of RTE_CACHE_LINE_SIZE */
15 #include <rte_log.h>
16 #include <rte_prefetch.h>
17 #include <rte_branch_prediction.h>
18 #include <rte_malloc.h>
19 #include <rte_eal.h>
20 #include <rte_eal_memconfig.h>
21 #include <rte_per_lcore.h>
22 #include <rte_errno.h>
23 #include <rte_string_fns.h>
24 #include <rte_cpuflags.h>
25 #include <rte_rwlock.h>
26 #include <rte_spinlock.h>
27 #include <rte_ring.h>
28 #include <rte_compat.h>
29 #include <rte_vect.h>
30 #include <rte_tailq.h>
31
32 #include "rte_hash.h"
33 #include "rte_cuckoo_hash.h"
34
35 #define FOR_EACH_BUCKET(CURRENT_BKT, START_BUCKET)                            \
36         for (CURRENT_BKT = START_BUCKET;                                      \
37                 CURRENT_BKT != NULL;                                          \
38                 CURRENT_BKT = CURRENT_BKT->next)
39
40 TAILQ_HEAD(rte_hash_list, rte_tailq_entry);
41
42 static struct rte_tailq_elem rte_hash_tailq = {
43         .name = "RTE_HASH",
44 };
45 EAL_REGISTER_TAILQ(rte_hash_tailq)
46
47 struct rte_hash *
48 rte_hash_find_existing(const char *name)
49 {
50         struct rte_hash *h = NULL;
51         struct rte_tailq_entry *te;
52         struct rte_hash_list *hash_list;
53
54         hash_list = RTE_TAILQ_CAST(rte_hash_tailq.head, rte_hash_list);
55
56         rte_mcfg_tailq_read_lock();
57         TAILQ_FOREACH(te, hash_list, next) {
58                 h = (struct rte_hash *) te->data;
59                 if (strncmp(name, h->name, RTE_HASH_NAMESIZE) == 0)
60                         break;
61         }
62         rte_mcfg_tailq_read_unlock();
63
64         if (te == NULL) {
65                 rte_errno = ENOENT;
66                 return NULL;
67         }
68         return h;
69 }
70
71 static inline struct rte_hash_bucket *
72 rte_hash_get_last_bkt(struct rte_hash_bucket *lst_bkt)
73 {
74         while (lst_bkt->next != NULL)
75                 lst_bkt = lst_bkt->next;
76         return lst_bkt;
77 }
78
79 void rte_hash_set_cmp_func(struct rte_hash *h, rte_hash_cmp_eq_t func)
80 {
81         h->cmp_jump_table_idx = KEY_CUSTOM;
82         h->rte_hash_custom_cmp_eq = func;
83 }
84
85 static inline int
86 rte_hash_cmp_eq(const void *key1, const void *key2, const struct rte_hash *h)
87 {
88         if (h->cmp_jump_table_idx == KEY_CUSTOM)
89                 return h->rte_hash_custom_cmp_eq(key1, key2, h->key_len);
90         else
91                 return cmp_jump_table[h->cmp_jump_table_idx](key1, key2, h->key_len);
92 }
93
94 /*
95  * We use higher 16 bits of hash as the signature value stored in table.
96  * We use the lower bits for the primary bucket
97  * location. Then we XOR primary bucket location and the signature
98  * to get the secondary bucket location. This is same as
99  * proposed in Bin Fan, et al's paper
100  * "MemC3: Compact and Concurrent MemCache with Dumber Caching and
101  * Smarter Hashing". The benefit to use
102  * XOR is that one could derive the alternative bucket location
103  * by only using the current bucket location and the signature.
104  */
105 static inline uint16_t
106 get_short_sig(const hash_sig_t hash)
107 {
108         return hash >> 16;
109 }
110
111 static inline uint32_t
112 get_prim_bucket_index(const struct rte_hash *h, const hash_sig_t hash)
113 {
114         return hash & h->bucket_bitmask;
115 }
116
117 static inline uint32_t
118 get_alt_bucket_index(const struct rte_hash *h,
119                         uint32_t cur_bkt_idx, uint16_t sig)
120 {
121         return (cur_bkt_idx ^ sig) & h->bucket_bitmask;
122 }
123
124 struct rte_hash *
125 rte_hash_create(const struct rte_hash_parameters *params)
126 {
127         struct rte_hash *h = NULL;
128         struct rte_tailq_entry *te = NULL;
129         struct rte_hash_list *hash_list;
130         struct rte_ring *r = NULL;
131         struct rte_ring *r_ext = NULL;
132         char hash_name[RTE_HASH_NAMESIZE];
133         void *k = NULL;
134         void *buckets = NULL;
135         void *buckets_ext = NULL;
136         char ring_name[RTE_RING_NAMESIZE];
137         char ext_ring_name[RTE_RING_NAMESIZE];
138         unsigned num_key_slots;
139         unsigned i;
140         unsigned int hw_trans_mem_support = 0, use_local_cache = 0;
141         unsigned int ext_table_support = 0;
142         unsigned int readwrite_concur_support = 0;
143         unsigned int writer_takes_lock = 0;
144         unsigned int no_free_on_del = 0;
145         uint32_t *ext_bkt_to_free = NULL;
146         uint32_t *tbl_chng_cnt = NULL;
147         unsigned int readwrite_concur_lf_support = 0;
148
149         rte_hash_function default_hash_func = (rte_hash_function)rte_jhash;
150
151         hash_list = RTE_TAILQ_CAST(rte_hash_tailq.head, rte_hash_list);
152
153         if (params == NULL) {
154                 RTE_LOG(ERR, HASH, "rte_hash_create has no parameters\n");
155                 return NULL;
156         }
157
158         /* Check for valid parameters */
159         if ((params->entries > RTE_HASH_ENTRIES_MAX) ||
160                         (params->entries < RTE_HASH_BUCKET_ENTRIES) ||
161                         (params->key_len == 0)) {
162                 rte_errno = EINVAL;
163                 RTE_LOG(ERR, HASH, "rte_hash_create has invalid parameters\n");
164                 return NULL;
165         }
166
167         /* Validate correct usage of extra options */
168         if ((params->extra_flag & RTE_HASH_EXTRA_FLAGS_RW_CONCURRENCY) &&
169             (params->extra_flag & RTE_HASH_EXTRA_FLAGS_RW_CONCURRENCY_LF)) {
170                 rte_errno = EINVAL;
171                 RTE_LOG(ERR, HASH, "rte_hash_create: choose rw concurrency or "
172                         "rw concurrency lock free\n");
173                 return NULL;
174         }
175
176         /* Check extra flags field to check extra options. */
177         if (params->extra_flag & RTE_HASH_EXTRA_FLAGS_TRANS_MEM_SUPPORT)
178                 hw_trans_mem_support = 1;
179
180         if (params->extra_flag & RTE_HASH_EXTRA_FLAGS_MULTI_WRITER_ADD) {
181                 use_local_cache = 1;
182                 writer_takes_lock = 1;
183         }
184
185         if (params->extra_flag & RTE_HASH_EXTRA_FLAGS_RW_CONCURRENCY) {
186                 readwrite_concur_support = 1;
187                 writer_takes_lock = 1;
188         }
189
190         if (params->extra_flag & RTE_HASH_EXTRA_FLAGS_EXT_TABLE)
191                 ext_table_support = 1;
192
193         if (params->extra_flag & RTE_HASH_EXTRA_FLAGS_NO_FREE_ON_DEL)
194                 no_free_on_del = 1;
195
196         if (params->extra_flag & RTE_HASH_EXTRA_FLAGS_RW_CONCURRENCY_LF) {
197                 readwrite_concur_lf_support = 1;
198                 /* Enable not freeing internal memory/index on delete */
199                 no_free_on_del = 1;
200         }
201
202         /* Store all keys and leave the first entry as a dummy entry for lookup_bulk */
203         if (use_local_cache)
204                 /*
205                  * Increase number of slots by total number of indices
206                  * that can be stored in the lcore caches
207                  * except for the first cache
208                  */
209                 num_key_slots = params->entries + (RTE_MAX_LCORE - 1) *
210                                         (LCORE_CACHE_SIZE - 1) + 1;
211         else
212                 num_key_slots = params->entries + 1;
213
214         snprintf(ring_name, sizeof(ring_name), "HT_%s", params->name);
215         /* Create ring (Dummy slot index is not enqueued) */
216         r = rte_ring_create(ring_name, rte_align32pow2(num_key_slots),
217                         params->socket_id, 0);
218         if (r == NULL) {
219                 RTE_LOG(ERR, HASH, "memory allocation failed\n");
220                 goto err;
221         }
222
223         const uint32_t num_buckets = rte_align32pow2(params->entries) /
224                                                 RTE_HASH_BUCKET_ENTRIES;
225
226         /* Create ring for extendable buckets. */
227         if (ext_table_support) {
228                 snprintf(ext_ring_name, sizeof(ext_ring_name), "HT_EXT_%s",
229                                                                 params->name);
230                 r_ext = rte_ring_create(ext_ring_name,
231                                 rte_align32pow2(num_buckets + 1),
232                                 params->socket_id, 0);
233
234                 if (r_ext == NULL) {
235                         RTE_LOG(ERR, HASH, "ext buckets memory allocation "
236                                                                 "failed\n");
237                         goto err;
238                 }
239         }
240
241         snprintf(hash_name, sizeof(hash_name), "HT_%s", params->name);
242
243         rte_mcfg_tailq_write_lock();
244
245         /* guarantee there's no existing: this is normally already checked
246          * by ring creation above */
247         TAILQ_FOREACH(te, hash_list, next) {
248                 h = (struct rte_hash *) te->data;
249                 if (strncmp(params->name, h->name, RTE_HASH_NAMESIZE) == 0)
250                         break;
251         }
252         h = NULL;
253         if (te != NULL) {
254                 rte_errno = EEXIST;
255                 te = NULL;
256                 goto err_unlock;
257         }
258
259         te = rte_zmalloc("HASH_TAILQ_ENTRY", sizeof(*te), 0);
260         if (te == NULL) {
261                 RTE_LOG(ERR, HASH, "tailq entry allocation failed\n");
262                 goto err_unlock;
263         }
264
265         h = (struct rte_hash *)rte_zmalloc_socket(hash_name, sizeof(struct rte_hash),
266                                         RTE_CACHE_LINE_SIZE, params->socket_id);
267
268         if (h == NULL) {
269                 RTE_LOG(ERR, HASH, "memory allocation failed\n");
270                 goto err_unlock;
271         }
272
273         buckets = rte_zmalloc_socket(NULL,
274                                 num_buckets * sizeof(struct rte_hash_bucket),
275                                 RTE_CACHE_LINE_SIZE, params->socket_id);
276
277         if (buckets == NULL) {
278                 RTE_LOG(ERR, HASH, "buckets memory allocation failed\n");
279                 goto err_unlock;
280         }
281
282         /* Allocate same number of extendable buckets */
283         if (ext_table_support) {
284                 buckets_ext = rte_zmalloc_socket(NULL,
285                                 num_buckets * sizeof(struct rte_hash_bucket),
286                                 RTE_CACHE_LINE_SIZE, params->socket_id);
287                 if (buckets_ext == NULL) {
288                         RTE_LOG(ERR, HASH, "ext buckets memory allocation "
289                                                         "failed\n");
290                         goto err_unlock;
291                 }
292                 /* Populate ext bkt ring. We reserve 0 similar to the
293                  * key-data slot, just in case in future we want to
294                  * use bucket index for the linked list and 0 means NULL
295                  * for next bucket
296                  */
297                 for (i = 1; i <= num_buckets; i++)
298                         rte_ring_sp_enqueue(r_ext, (void *)((uintptr_t) i));
299
300                 if (readwrite_concur_lf_support) {
301                         ext_bkt_to_free = rte_zmalloc(NULL, sizeof(uint32_t) *
302                                                                 num_key_slots, 0);
303                         if (ext_bkt_to_free == NULL) {
304                                 RTE_LOG(ERR, HASH, "ext bkt to free memory allocation "
305                                                                 "failed\n");
306                                 goto err_unlock;
307                         }
308                 }
309         }
310
311         const uint32_t key_entry_size =
312                 RTE_ALIGN(sizeof(struct rte_hash_key) + params->key_len,
313                           KEY_ALIGNMENT);
314         const uint64_t key_tbl_size = (uint64_t) key_entry_size * num_key_slots;
315
316         k = rte_zmalloc_socket(NULL, key_tbl_size,
317                         RTE_CACHE_LINE_SIZE, params->socket_id);
318
319         if (k == NULL) {
320                 RTE_LOG(ERR, HASH, "memory allocation failed\n");
321                 goto err_unlock;
322         }
323
324         tbl_chng_cnt = rte_zmalloc_socket(NULL, sizeof(uint32_t),
325                         RTE_CACHE_LINE_SIZE, params->socket_id);
326
327         if (tbl_chng_cnt == NULL) {
328                 RTE_LOG(ERR, HASH, "memory allocation failed\n");
329                 goto err_unlock;
330         }
331
332 /*
333  * If x86 architecture is used, select appropriate compare function,
334  * which may use x86 intrinsics, otherwise use memcmp
335  */
336 #if defined(RTE_ARCH_X86) || defined(RTE_ARCH_ARM64)
337         /* Select function to compare keys */
338         switch (params->key_len) {
339         case 16:
340                 h->cmp_jump_table_idx = KEY_16_BYTES;
341                 break;
342         case 32:
343                 h->cmp_jump_table_idx = KEY_32_BYTES;
344                 break;
345         case 48:
346                 h->cmp_jump_table_idx = KEY_48_BYTES;
347                 break;
348         case 64:
349                 h->cmp_jump_table_idx = KEY_64_BYTES;
350                 break;
351         case 80:
352                 h->cmp_jump_table_idx = KEY_80_BYTES;
353                 break;
354         case 96:
355                 h->cmp_jump_table_idx = KEY_96_BYTES;
356                 break;
357         case 112:
358                 h->cmp_jump_table_idx = KEY_112_BYTES;
359                 break;
360         case 128:
361                 h->cmp_jump_table_idx = KEY_128_BYTES;
362                 break;
363         default:
364                 /* If key is not multiple of 16, use generic memcmp */
365                 h->cmp_jump_table_idx = KEY_OTHER_BYTES;
366         }
367 #else
368         h->cmp_jump_table_idx = KEY_OTHER_BYTES;
369 #endif
370
371         if (use_local_cache) {
372                 h->local_free_slots = rte_zmalloc_socket(NULL,
373                                 sizeof(struct lcore_cache) * RTE_MAX_LCORE,
374                                 RTE_CACHE_LINE_SIZE, params->socket_id);
375         }
376
377         /* Default hash function */
378 #if defined(RTE_ARCH_X86)
379         default_hash_func = (rte_hash_function)rte_hash_crc;
380 #elif defined(RTE_ARCH_ARM64)
381         if (rte_cpu_get_flag_enabled(RTE_CPUFLAG_CRC32))
382                 default_hash_func = (rte_hash_function)rte_hash_crc;
383 #endif
384         /* Setup hash context */
385         strlcpy(h->name, params->name, sizeof(h->name));
386         h->entries = params->entries;
387         h->key_len = params->key_len;
388         h->key_entry_size = key_entry_size;
389         h->hash_func_init_val = params->hash_func_init_val;
390
391         h->num_buckets = num_buckets;
392         h->bucket_bitmask = h->num_buckets - 1;
393         h->buckets = buckets;
394         h->buckets_ext = buckets_ext;
395         h->free_ext_bkts = r_ext;
396         h->hash_func = (params->hash_func == NULL) ?
397                 default_hash_func : params->hash_func;
398         h->key_store = k;
399         h->free_slots = r;
400         h->ext_bkt_to_free = ext_bkt_to_free;
401         h->tbl_chng_cnt = tbl_chng_cnt;
402         *h->tbl_chng_cnt = 0;
403         h->hw_trans_mem_support = hw_trans_mem_support;
404         h->use_local_cache = use_local_cache;
405         h->readwrite_concur_support = readwrite_concur_support;
406         h->ext_table_support = ext_table_support;
407         h->writer_takes_lock = writer_takes_lock;
408         h->no_free_on_del = no_free_on_del;
409         h->readwrite_concur_lf_support = readwrite_concur_lf_support;
410
411 #if defined(RTE_ARCH_X86)
412         if (rte_cpu_get_flag_enabled(RTE_CPUFLAG_SSE2))
413                 h->sig_cmp_fn = RTE_HASH_COMPARE_SSE;
414         else
415 #elif defined(RTE_ARCH_ARM64)
416         if (rte_cpu_get_flag_enabled(RTE_CPUFLAG_NEON))
417                 h->sig_cmp_fn = RTE_HASH_COMPARE_NEON;
418         else
419 #endif
420                 h->sig_cmp_fn = RTE_HASH_COMPARE_SCALAR;
421
422         /* Writer threads need to take the lock when:
423          * 1) RTE_HASH_EXTRA_FLAGS_RW_CONCURRENCY is enabled OR
424          * 2) RTE_HASH_EXTRA_FLAGS_MULTI_WRITER_ADD is enabled
425          */
426         if (h->writer_takes_lock) {
427                 h->readwrite_lock = rte_malloc(NULL, sizeof(rte_rwlock_t),
428                                                 RTE_CACHE_LINE_SIZE);
429                 if (h->readwrite_lock == NULL)
430                         goto err_unlock;
431
432                 rte_rwlock_init(h->readwrite_lock);
433         }
434
435         /* Populate free slots ring. Entry zero is reserved for key misses. */
436         for (i = 1; i < num_key_slots; i++)
437                 rte_ring_sp_enqueue(r, (void *)((uintptr_t) i));
438
439         te->data = (void *) h;
440         TAILQ_INSERT_TAIL(hash_list, te, next);
441         rte_mcfg_tailq_write_unlock();
442
443         return h;
444 err_unlock:
445         rte_mcfg_tailq_write_unlock();
446 err:
447         rte_ring_free(r);
448         rte_ring_free(r_ext);
449         rte_free(te);
450         rte_free(h);
451         rte_free(buckets);
452         rte_free(buckets_ext);
453         rte_free(k);
454         rte_free(tbl_chng_cnt);
455         rte_free(ext_bkt_to_free);
456         return NULL;
457 }
458
459 void
460 rte_hash_free(struct rte_hash *h)
461 {
462         struct rte_tailq_entry *te;
463         struct rte_hash_list *hash_list;
464
465         if (h == NULL)
466                 return;
467
468         hash_list = RTE_TAILQ_CAST(rte_hash_tailq.head, rte_hash_list);
469
470         rte_mcfg_tailq_write_lock();
471
472         /* find out tailq entry */
473         TAILQ_FOREACH(te, hash_list, next) {
474                 if (te->data == (void *) h)
475                         break;
476         }
477
478         if (te == NULL) {
479                 rte_mcfg_tailq_write_unlock();
480                 return;
481         }
482
483         TAILQ_REMOVE(hash_list, te, next);
484
485         rte_mcfg_tailq_write_unlock();
486
487         if (h->use_local_cache)
488                 rte_free(h->local_free_slots);
489         if (h->writer_takes_lock)
490                 rte_free(h->readwrite_lock);
491         rte_ring_free(h->free_slots);
492         rte_ring_free(h->free_ext_bkts);
493         rte_free(h->key_store);
494         rte_free(h->buckets);
495         rte_free(h->buckets_ext);
496         rte_free(h->tbl_chng_cnt);
497         rte_free(h->ext_bkt_to_free);
498         rte_free(h);
499         rte_free(te);
500 }
501
502 hash_sig_t
503 rte_hash_hash(const struct rte_hash *h, const void *key)
504 {
505         /* calc hash result by key */
506         return h->hash_func(key, h->key_len, h->hash_func_init_val);
507 }
508
509 int32_t
510 rte_hash_count(const struct rte_hash *h)
511 {
512         uint32_t tot_ring_cnt, cached_cnt = 0;
513         uint32_t i, ret;
514
515         if (h == NULL)
516                 return -EINVAL;
517
518         if (h->use_local_cache) {
519                 tot_ring_cnt = h->entries + (RTE_MAX_LCORE - 1) *
520                                         (LCORE_CACHE_SIZE - 1);
521                 for (i = 0; i < RTE_MAX_LCORE; i++)
522                         cached_cnt += h->local_free_slots[i].len;
523
524                 ret = tot_ring_cnt - rte_ring_count(h->free_slots) -
525                                                                 cached_cnt;
526         } else {
527                 tot_ring_cnt = h->entries;
528                 ret = tot_ring_cnt - rte_ring_count(h->free_slots);
529         }
530         return ret;
531 }
532
533 /* Read write locks implemented using rte_rwlock */
534 static inline void
535 __hash_rw_writer_lock(const struct rte_hash *h)
536 {
537         if (h->writer_takes_lock && h->hw_trans_mem_support)
538                 rte_rwlock_write_lock_tm(h->readwrite_lock);
539         else if (h->writer_takes_lock)
540                 rte_rwlock_write_lock(h->readwrite_lock);
541 }
542
543 static inline void
544 __hash_rw_reader_lock(const struct rte_hash *h)
545 {
546         if (h->readwrite_concur_support && h->hw_trans_mem_support)
547                 rte_rwlock_read_lock_tm(h->readwrite_lock);
548         else if (h->readwrite_concur_support)
549                 rte_rwlock_read_lock(h->readwrite_lock);
550 }
551
552 static inline void
553 __hash_rw_writer_unlock(const struct rte_hash *h)
554 {
555         if (h->writer_takes_lock && h->hw_trans_mem_support)
556                 rte_rwlock_write_unlock_tm(h->readwrite_lock);
557         else if (h->writer_takes_lock)
558                 rte_rwlock_write_unlock(h->readwrite_lock);
559 }
560
561 static inline void
562 __hash_rw_reader_unlock(const struct rte_hash *h)
563 {
564         if (h->readwrite_concur_support && h->hw_trans_mem_support)
565                 rte_rwlock_read_unlock_tm(h->readwrite_lock);
566         else if (h->readwrite_concur_support)
567                 rte_rwlock_read_unlock(h->readwrite_lock);
568 }
569
570 void
571 rte_hash_reset(struct rte_hash *h)
572 {
573         uint32_t tot_ring_cnt, i;
574
575         if (h == NULL)
576                 return;
577
578         __hash_rw_writer_lock(h);
579         memset(h->buckets, 0, h->num_buckets * sizeof(struct rte_hash_bucket));
580         memset(h->key_store, 0, h->key_entry_size * (h->entries + 1));
581         *h->tbl_chng_cnt = 0;
582
583         /* reset the free ring */
584         rte_ring_reset(h->free_slots);
585
586         /* flush free extendable bucket ring and memory */
587         if (h->ext_table_support) {
588                 memset(h->buckets_ext, 0, h->num_buckets *
589                                                 sizeof(struct rte_hash_bucket));
590                 rte_ring_reset(h->free_ext_bkts);
591         }
592
593         /* Repopulate the free slots ring. Entry zero is reserved for key misses */
594         if (h->use_local_cache)
595                 tot_ring_cnt = h->entries + (RTE_MAX_LCORE - 1) *
596                                         (LCORE_CACHE_SIZE - 1);
597         else
598                 tot_ring_cnt = h->entries;
599
600         for (i = 1; i < tot_ring_cnt + 1; i++)
601                 rte_ring_sp_enqueue(h->free_slots, (void *)((uintptr_t) i));
602
603         /* Repopulate the free ext bkt ring. */
604         if (h->ext_table_support) {
605                 for (i = 1; i <= h->num_buckets; i++)
606                         rte_ring_sp_enqueue(h->free_ext_bkts,
607                                                 (void *)((uintptr_t) i));
608         }
609
610         if (h->use_local_cache) {
611                 /* Reset local caches per lcore */
612                 for (i = 0; i < RTE_MAX_LCORE; i++)
613                         h->local_free_slots[i].len = 0;
614         }
615         __hash_rw_writer_unlock(h);
616 }
617
618 /*
619  * Function called to enqueue back an index in the cache/ring,
620  * as slot has not being used and it can be used in the
621  * next addition attempt.
622  */
623 static inline void
624 enqueue_slot_back(const struct rte_hash *h,
625                 struct lcore_cache *cached_free_slots,
626                 void *slot_id)
627 {
628         if (h->use_local_cache) {
629                 cached_free_slots->objs[cached_free_slots->len] = slot_id;
630                 cached_free_slots->len++;
631         } else
632                 rte_ring_sp_enqueue(h->free_slots, slot_id);
633 }
634
635 /* Search a key from bucket and update its data.
636  * Writer holds the lock before calling this.
637  */
638 static inline int32_t
639 search_and_update(const struct rte_hash *h, void *data, const void *key,
640         struct rte_hash_bucket *bkt, uint16_t sig)
641 {
642         int i;
643         struct rte_hash_key *k, *keys = h->key_store;
644
645         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
646                 if (bkt->sig_current[i] == sig) {
647                         k = (struct rte_hash_key *) ((char *)keys +
648                                         bkt->key_idx[i] * h->key_entry_size);
649                         if (rte_hash_cmp_eq(key, k->key, h) == 0) {
650                                 /* The store to application data at *data
651                                  * should not leak after the store to pdata
652                                  * in the key store. i.e. pdata is the guard
653                                  * variable. Release the application data
654                                  * to the readers.
655                                  */
656                                 __atomic_store_n(&k->pdata,
657                                         data,
658                                         __ATOMIC_RELEASE);
659                                 /*
660                                  * Return index where key is stored,
661                                  * subtracting the first dummy index
662                                  */
663                                 return bkt->key_idx[i] - 1;
664                         }
665                 }
666         }
667         return -1;
668 }
669
670 /* Only tries to insert at one bucket (@prim_bkt) without trying to push
671  * buckets around.
672  * return 1 if matching existing key, return 0 if succeeds, return -1 for no
673  * empty entry.
674  */
675 static inline int32_t
676 rte_hash_cuckoo_insert_mw(const struct rte_hash *h,
677                 struct rte_hash_bucket *prim_bkt,
678                 struct rte_hash_bucket *sec_bkt,
679                 const struct rte_hash_key *key, void *data,
680                 uint16_t sig, uint32_t new_idx,
681                 int32_t *ret_val)
682 {
683         unsigned int i;
684         struct rte_hash_bucket *cur_bkt;
685         int32_t ret;
686
687         __hash_rw_writer_lock(h);
688         /* Check if key was inserted after last check but before this
689          * protected region in case of inserting duplicated keys.
690          */
691         ret = search_and_update(h, data, key, prim_bkt, sig);
692         if (ret != -1) {
693                 __hash_rw_writer_unlock(h);
694                 *ret_val = ret;
695                 return 1;
696         }
697
698         FOR_EACH_BUCKET(cur_bkt, sec_bkt) {
699                 ret = search_and_update(h, data, key, cur_bkt, sig);
700                 if (ret != -1) {
701                         __hash_rw_writer_unlock(h);
702                         *ret_val = ret;
703                         return 1;
704                 }
705         }
706
707         /* Insert new entry if there is room in the primary
708          * bucket.
709          */
710         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
711                 /* Check if slot is available */
712                 if (likely(prim_bkt->key_idx[i] == EMPTY_SLOT)) {
713                         prim_bkt->sig_current[i] = sig;
714                         /* Store to signature and key should not
715                          * leak after the store to key_idx. i.e.
716                          * key_idx is the guard variable for signature
717                          * and key.
718                          */
719                         __atomic_store_n(&prim_bkt->key_idx[i],
720                                          new_idx,
721                                          __ATOMIC_RELEASE);
722                         break;
723                 }
724         }
725         __hash_rw_writer_unlock(h);
726
727         if (i != RTE_HASH_BUCKET_ENTRIES)
728                 return 0;
729
730         /* no empty entry */
731         return -1;
732 }
733
734 /* Shift buckets along provided cuckoo_path (@leaf and @leaf_slot) and fill
735  * the path head with new entry (sig, alt_hash, new_idx)
736  * return 1 if matched key found, return -1 if cuckoo path invalided and fail,
737  * return 0 if succeeds.
738  */
739 static inline int
740 rte_hash_cuckoo_move_insert_mw(const struct rte_hash *h,
741                         struct rte_hash_bucket *bkt,
742                         struct rte_hash_bucket *alt_bkt,
743                         const struct rte_hash_key *key, void *data,
744                         struct queue_node *leaf, uint32_t leaf_slot,
745                         uint16_t sig, uint32_t new_idx,
746                         int32_t *ret_val)
747 {
748         uint32_t prev_alt_bkt_idx;
749         struct rte_hash_bucket *cur_bkt;
750         struct queue_node *prev_node, *curr_node = leaf;
751         struct rte_hash_bucket *prev_bkt, *curr_bkt = leaf->bkt;
752         uint32_t prev_slot, curr_slot = leaf_slot;
753         int32_t ret;
754
755         __hash_rw_writer_lock(h);
756
757         /* In case empty slot was gone before entering protected region */
758         if (curr_bkt->key_idx[curr_slot] != EMPTY_SLOT) {
759                 __hash_rw_writer_unlock(h);
760                 return -1;
761         }
762
763         /* Check if key was inserted after last check but before this
764          * protected region.
765          */
766         ret = search_and_update(h, data, key, bkt, sig);
767         if (ret != -1) {
768                 __hash_rw_writer_unlock(h);
769                 *ret_val = ret;
770                 return 1;
771         }
772
773         FOR_EACH_BUCKET(cur_bkt, alt_bkt) {
774                 ret = search_and_update(h, data, key, cur_bkt, sig);
775                 if (ret != -1) {
776                         __hash_rw_writer_unlock(h);
777                         *ret_val = ret;
778                         return 1;
779                 }
780         }
781
782         while (likely(curr_node->prev != NULL)) {
783                 prev_node = curr_node->prev;
784                 prev_bkt = prev_node->bkt;
785                 prev_slot = curr_node->prev_slot;
786
787                 prev_alt_bkt_idx = get_alt_bucket_index(h,
788                                         prev_node->cur_bkt_idx,
789                                         prev_bkt->sig_current[prev_slot]);
790
791                 if (unlikely(&h->buckets[prev_alt_bkt_idx]
792                                 != curr_bkt)) {
793                         /* revert it to empty, otherwise duplicated keys */
794                         __atomic_store_n(&curr_bkt->key_idx[curr_slot],
795                                 EMPTY_SLOT,
796                                 __ATOMIC_RELEASE);
797                         __hash_rw_writer_unlock(h);
798                         return -1;
799                 }
800
801                 if (h->readwrite_concur_lf_support) {
802                         /* Inform the previous move. The current move need
803                          * not be informed now as the current bucket entry
804                          * is present in both primary and secondary.
805                          * Since there is one writer, load acquires on
806                          * tbl_chng_cnt are not required.
807                          */
808                         __atomic_store_n(h->tbl_chng_cnt,
809                                          *h->tbl_chng_cnt + 1,
810                                          __ATOMIC_RELEASE);
811                         /* The store to sig_current should not
812                          * move above the store to tbl_chng_cnt.
813                          */
814                         __atomic_thread_fence(__ATOMIC_RELEASE);
815                 }
816
817                 /* Need to swap current/alt sig to allow later
818                  * Cuckoo insert to move elements back to its
819                  * primary bucket if available
820                  */
821                 curr_bkt->sig_current[curr_slot] =
822                         prev_bkt->sig_current[prev_slot];
823                 /* Release the updated bucket entry */
824                 __atomic_store_n(&curr_bkt->key_idx[curr_slot],
825                         prev_bkt->key_idx[prev_slot],
826                         __ATOMIC_RELEASE);
827
828                 curr_slot = prev_slot;
829                 curr_node = prev_node;
830                 curr_bkt = curr_node->bkt;
831         }
832
833         if (h->readwrite_concur_lf_support) {
834                 /* Inform the previous move. The current move need
835                  * not be informed now as the current bucket entry
836                  * is present in both primary and secondary.
837                  * Since there is one writer, load acquires on
838                  * tbl_chng_cnt are not required.
839                  */
840                 __atomic_store_n(h->tbl_chng_cnt,
841                                  *h->tbl_chng_cnt + 1,
842                                  __ATOMIC_RELEASE);
843                 /* The store to sig_current should not
844                  * move above the store to tbl_chng_cnt.
845                  */
846                 __atomic_thread_fence(__ATOMIC_RELEASE);
847         }
848
849         curr_bkt->sig_current[curr_slot] = sig;
850         /* Release the new bucket entry */
851         __atomic_store_n(&curr_bkt->key_idx[curr_slot],
852                          new_idx,
853                          __ATOMIC_RELEASE);
854
855         __hash_rw_writer_unlock(h);
856
857         return 0;
858
859 }
860
861 /*
862  * Make space for new key, using bfs Cuckoo Search and Multi-Writer safe
863  * Cuckoo
864  */
865 static inline int
866 rte_hash_cuckoo_make_space_mw(const struct rte_hash *h,
867                         struct rte_hash_bucket *bkt,
868                         struct rte_hash_bucket *sec_bkt,
869                         const struct rte_hash_key *key, void *data,
870                         uint16_t sig, uint32_t bucket_idx,
871                         uint32_t new_idx, int32_t *ret_val)
872 {
873         unsigned int i;
874         struct queue_node queue[RTE_HASH_BFS_QUEUE_MAX_LEN];
875         struct queue_node *tail, *head;
876         struct rte_hash_bucket *curr_bkt, *alt_bkt;
877         uint32_t cur_idx, alt_idx;
878
879         tail = queue;
880         head = queue + 1;
881         tail->bkt = bkt;
882         tail->prev = NULL;
883         tail->prev_slot = -1;
884         tail->cur_bkt_idx = bucket_idx;
885
886         /* Cuckoo bfs Search */
887         while (likely(tail != head && head <
888                                         queue + RTE_HASH_BFS_QUEUE_MAX_LEN -
889                                         RTE_HASH_BUCKET_ENTRIES)) {
890                 curr_bkt = tail->bkt;
891                 cur_idx = tail->cur_bkt_idx;
892                 for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
893                         if (curr_bkt->key_idx[i] == EMPTY_SLOT) {
894                                 int32_t ret = rte_hash_cuckoo_move_insert_mw(h,
895                                                 bkt, sec_bkt, key, data,
896                                                 tail, i, sig,
897                                                 new_idx, ret_val);
898                                 if (likely(ret != -1))
899                                         return ret;
900                         }
901
902                         /* Enqueue new node and keep prev node info */
903                         alt_idx = get_alt_bucket_index(h, cur_idx,
904                                                 curr_bkt->sig_current[i]);
905                         alt_bkt = &(h->buckets[alt_idx]);
906                         head->bkt = alt_bkt;
907                         head->cur_bkt_idx = alt_idx;
908                         head->prev = tail;
909                         head->prev_slot = i;
910                         head++;
911                 }
912                 tail++;
913         }
914
915         return -ENOSPC;
916 }
917
918 static inline int32_t
919 __rte_hash_add_key_with_hash(const struct rte_hash *h, const void *key,
920                                                 hash_sig_t sig, void *data)
921 {
922         uint16_t short_sig;
923         uint32_t prim_bucket_idx, sec_bucket_idx;
924         struct rte_hash_bucket *prim_bkt, *sec_bkt, *cur_bkt;
925         struct rte_hash_key *new_k, *keys = h->key_store;
926         void *slot_id = NULL;
927         void *ext_bkt_id = NULL;
928         uint32_t new_idx, bkt_id;
929         int ret;
930         unsigned n_slots;
931         unsigned lcore_id;
932         unsigned int i;
933         struct lcore_cache *cached_free_slots = NULL;
934         int32_t ret_val;
935         struct rte_hash_bucket *last;
936
937         short_sig = get_short_sig(sig);
938         prim_bucket_idx = get_prim_bucket_index(h, sig);
939         sec_bucket_idx = get_alt_bucket_index(h, prim_bucket_idx, short_sig);
940         prim_bkt = &h->buckets[prim_bucket_idx];
941         sec_bkt = &h->buckets[sec_bucket_idx];
942         rte_prefetch0(prim_bkt);
943         rte_prefetch0(sec_bkt);
944
945         /* Check if key is already inserted in primary location */
946         __hash_rw_writer_lock(h);
947         ret = search_and_update(h, data, key, prim_bkt, short_sig);
948         if (ret != -1) {
949                 __hash_rw_writer_unlock(h);
950                 return ret;
951         }
952
953         /* Check if key is already inserted in secondary location */
954         FOR_EACH_BUCKET(cur_bkt, sec_bkt) {
955                 ret = search_and_update(h, data, key, cur_bkt, short_sig);
956                 if (ret != -1) {
957                         __hash_rw_writer_unlock(h);
958                         return ret;
959                 }
960         }
961
962         __hash_rw_writer_unlock(h);
963
964         /* Did not find a match, so get a new slot for storing the new key */
965         if (h->use_local_cache) {
966                 lcore_id = rte_lcore_id();
967                 cached_free_slots = &h->local_free_slots[lcore_id];
968                 /* Try to get a free slot from the local cache */
969                 if (cached_free_slots->len == 0) {
970                         /* Need to get another burst of free slots from global ring */
971                         n_slots = rte_ring_mc_dequeue_burst(h->free_slots,
972                                         cached_free_slots->objs,
973                                         LCORE_CACHE_SIZE, NULL);
974                         if (n_slots == 0) {
975                                 return -ENOSPC;
976                         }
977
978                         cached_free_slots->len += n_slots;
979                 }
980
981                 /* Get a free slot from the local cache */
982                 cached_free_slots->len--;
983                 slot_id = cached_free_slots->objs[cached_free_slots->len];
984         } else {
985                 if (rte_ring_sc_dequeue(h->free_slots, &slot_id) != 0) {
986                         return -ENOSPC;
987                 }
988         }
989
990         new_k = RTE_PTR_ADD(keys, (uintptr_t)slot_id * h->key_entry_size);
991         new_idx = (uint32_t)((uintptr_t) slot_id);
992         /* The store to application data (by the application) at *data should
993          * not leak after the store of pdata in the key store. i.e. pdata is
994          * the guard variable. Release the application data to the readers.
995          */
996         __atomic_store_n(&new_k->pdata,
997                 data,
998                 __ATOMIC_RELEASE);
999         /* Copy key */
1000         memcpy(new_k->key, key, h->key_len);
1001
1002         /* Find an empty slot and insert */
1003         ret = rte_hash_cuckoo_insert_mw(h, prim_bkt, sec_bkt, key, data,
1004                                         short_sig, new_idx, &ret_val);
1005         if (ret == 0)
1006                 return new_idx - 1;
1007         else if (ret == 1) {
1008                 enqueue_slot_back(h, cached_free_slots, slot_id);
1009                 return ret_val;
1010         }
1011
1012         /* Primary bucket full, need to make space for new entry */
1013         ret = rte_hash_cuckoo_make_space_mw(h, prim_bkt, sec_bkt, key, data,
1014                                 short_sig, prim_bucket_idx, new_idx, &ret_val);
1015         if (ret == 0)
1016                 return new_idx - 1;
1017         else if (ret == 1) {
1018                 enqueue_slot_back(h, cached_free_slots, slot_id);
1019                 return ret_val;
1020         }
1021
1022         /* Also search secondary bucket to get better occupancy */
1023         ret = rte_hash_cuckoo_make_space_mw(h, sec_bkt, prim_bkt, key, data,
1024                                 short_sig, sec_bucket_idx, new_idx, &ret_val);
1025
1026         if (ret == 0)
1027                 return new_idx - 1;
1028         else if (ret == 1) {
1029                 enqueue_slot_back(h, cached_free_slots, slot_id);
1030                 return ret_val;
1031         }
1032
1033         /* if ext table not enabled, we failed the insertion */
1034         if (!h->ext_table_support) {
1035                 enqueue_slot_back(h, cached_free_slots, slot_id);
1036                 return ret;
1037         }
1038
1039         /* Now we need to go through the extendable bucket. Protection is needed
1040          * to protect all extendable bucket processes.
1041          */
1042         __hash_rw_writer_lock(h);
1043         /* We check for duplicates again since could be inserted before the lock */
1044         ret = search_and_update(h, data, key, prim_bkt, short_sig);
1045         if (ret != -1) {
1046                 enqueue_slot_back(h, cached_free_slots, slot_id);
1047                 goto failure;
1048         }
1049
1050         FOR_EACH_BUCKET(cur_bkt, sec_bkt) {
1051                 ret = search_and_update(h, data, key, cur_bkt, short_sig);
1052                 if (ret != -1) {
1053                         enqueue_slot_back(h, cached_free_slots, slot_id);
1054                         goto failure;
1055                 }
1056         }
1057
1058         /* Search sec and ext buckets to find an empty entry to insert. */
1059         FOR_EACH_BUCKET(cur_bkt, sec_bkt) {
1060                 for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
1061                         /* Check if slot is available */
1062                         if (likely(cur_bkt->key_idx[i] == EMPTY_SLOT)) {
1063                                 cur_bkt->sig_current[i] = short_sig;
1064                                 /* Store to signature and key should not
1065                                  * leak after the store to key_idx. i.e.
1066                                  * key_idx is the guard variable for signature
1067                                  * and key.
1068                                  */
1069                                 __atomic_store_n(&cur_bkt->key_idx[i],
1070                                                  new_idx,
1071                                                  __ATOMIC_RELEASE);
1072                                 __hash_rw_writer_unlock(h);
1073                                 return new_idx - 1;
1074                         }
1075                 }
1076         }
1077
1078         /* Failed to get an empty entry from extendable buckets. Link a new
1079          * extendable bucket. We first get a free bucket from ring.
1080          */
1081         if (rte_ring_sc_dequeue(h->free_ext_bkts, &ext_bkt_id) != 0) {
1082                 ret = -ENOSPC;
1083                 goto failure;
1084         }
1085
1086         bkt_id = (uint32_t)((uintptr_t)ext_bkt_id) - 1;
1087         /* Use the first location of the new bucket */
1088         (h->buckets_ext[bkt_id]).sig_current[0] = short_sig;
1089         /* Store to signature and key should not leak after
1090          * the store to key_idx. i.e. key_idx is the guard variable
1091          * for signature and key.
1092          */
1093         __atomic_store_n(&(h->buckets_ext[bkt_id]).key_idx[0],
1094                          new_idx,
1095                          __ATOMIC_RELEASE);
1096         /* Link the new bucket to sec bucket linked list */
1097         last = rte_hash_get_last_bkt(sec_bkt);
1098         last->next = &h->buckets_ext[bkt_id];
1099         __hash_rw_writer_unlock(h);
1100         return new_idx - 1;
1101
1102 failure:
1103         __hash_rw_writer_unlock(h);
1104         return ret;
1105
1106 }
1107
1108 int32_t
1109 rte_hash_add_key_with_hash(const struct rte_hash *h,
1110                         const void *key, hash_sig_t sig)
1111 {
1112         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
1113         return __rte_hash_add_key_with_hash(h, key, sig, 0);
1114 }
1115
1116 int32_t
1117 rte_hash_add_key(const struct rte_hash *h, const void *key)
1118 {
1119         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
1120         return __rte_hash_add_key_with_hash(h, key, rte_hash_hash(h, key), 0);
1121 }
1122
1123 int
1124 rte_hash_add_key_with_hash_data(const struct rte_hash *h,
1125                         const void *key, hash_sig_t sig, void *data)
1126 {
1127         int ret;
1128
1129         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
1130         ret = __rte_hash_add_key_with_hash(h, key, sig, data);
1131         if (ret >= 0)
1132                 return 0;
1133         else
1134                 return ret;
1135 }
1136
1137 int
1138 rte_hash_add_key_data(const struct rte_hash *h, const void *key, void *data)
1139 {
1140         int ret;
1141
1142         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
1143
1144         ret = __rte_hash_add_key_with_hash(h, key, rte_hash_hash(h, key), data);
1145         if (ret >= 0)
1146                 return 0;
1147         else
1148                 return ret;
1149 }
1150
1151 /* Search one bucket to find the match key - uses rw lock */
1152 static inline int32_t
1153 search_one_bucket_l(const struct rte_hash *h, const void *key,
1154                 uint16_t sig, void **data,
1155                 const struct rte_hash_bucket *bkt)
1156 {
1157         int i;
1158         struct rte_hash_key *k, *keys = h->key_store;
1159
1160         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
1161                 if (bkt->sig_current[i] == sig &&
1162                                 bkt->key_idx[i] != EMPTY_SLOT) {
1163                         k = (struct rte_hash_key *) ((char *)keys +
1164                                         bkt->key_idx[i] * h->key_entry_size);
1165
1166                         if (rte_hash_cmp_eq(key, k->key, h) == 0) {
1167                                 if (data != NULL)
1168                                         *data = k->pdata;
1169                                 /*
1170                                  * Return index where key is stored,
1171                                  * subtracting the first dummy index
1172                                  */
1173                                 return bkt->key_idx[i] - 1;
1174                         }
1175                 }
1176         }
1177         return -1;
1178 }
1179
1180 /* Search one bucket to find the match key */
1181 static inline int32_t
1182 search_one_bucket_lf(const struct rte_hash *h, const void *key, uint16_t sig,
1183                         void **data, const struct rte_hash_bucket *bkt)
1184 {
1185         int i;
1186         uint32_t key_idx;
1187         struct rte_hash_key *k, *keys = h->key_store;
1188
1189         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
1190                 /* Signature comparison is done before the acquire-load
1191                  * of the key index to achieve better performance.
1192                  * This can result in the reader loading old signature
1193                  * (which matches), while the key_idx is updated to a
1194                  * value that belongs to a new key. However, the full
1195                  * key comparison will ensure that the lookup fails.
1196                  */
1197                 if (bkt->sig_current[i] == sig) {
1198                         key_idx = __atomic_load_n(&bkt->key_idx[i],
1199                                           __ATOMIC_ACQUIRE);
1200                         if (key_idx != EMPTY_SLOT) {
1201                                 k = (struct rte_hash_key *) ((char *)keys +
1202                                                 key_idx * h->key_entry_size);
1203
1204                                 if (rte_hash_cmp_eq(key, k->key, h) == 0) {
1205                                         if (data != NULL) {
1206                                                 *data = __atomic_load_n(
1207                                                         &k->pdata,
1208                                                         __ATOMIC_ACQUIRE);
1209                                         }
1210                                         /*
1211                                          * Return index where key is stored,
1212                                          * subtracting the first dummy index
1213                                          */
1214                                         return key_idx - 1;
1215                                 }
1216                         }
1217                 }
1218         }
1219         return -1;
1220 }
1221
1222 static inline int32_t
1223 __rte_hash_lookup_with_hash_l(const struct rte_hash *h, const void *key,
1224                                 hash_sig_t sig, void **data)
1225 {
1226         uint32_t prim_bucket_idx, sec_bucket_idx;
1227         struct rte_hash_bucket *bkt, *cur_bkt;
1228         int ret;
1229         uint16_t short_sig;
1230
1231         short_sig = get_short_sig(sig);
1232         prim_bucket_idx = get_prim_bucket_index(h, sig);
1233         sec_bucket_idx = get_alt_bucket_index(h, prim_bucket_idx, short_sig);
1234
1235         bkt = &h->buckets[prim_bucket_idx];
1236
1237         __hash_rw_reader_lock(h);
1238
1239         /* Check if key is in primary location */
1240         ret = search_one_bucket_l(h, key, short_sig, data, bkt);
1241         if (ret != -1) {
1242                 __hash_rw_reader_unlock(h);
1243                 return ret;
1244         }
1245         /* Calculate secondary hash */
1246         bkt = &h->buckets[sec_bucket_idx];
1247
1248         /* Check if key is in secondary location */
1249         FOR_EACH_BUCKET(cur_bkt, bkt) {
1250                 ret = search_one_bucket_l(h, key, short_sig,
1251                                         data, cur_bkt);
1252                 if (ret != -1) {
1253                         __hash_rw_reader_unlock(h);
1254                         return ret;
1255                 }
1256         }
1257
1258         __hash_rw_reader_unlock(h);
1259
1260         return -ENOENT;
1261 }
1262
1263 static inline int32_t
1264 __rte_hash_lookup_with_hash_lf(const struct rte_hash *h, const void *key,
1265                                         hash_sig_t sig, void **data)
1266 {
1267         uint32_t prim_bucket_idx, sec_bucket_idx;
1268         struct rte_hash_bucket *bkt, *cur_bkt;
1269         uint32_t cnt_b, cnt_a;
1270         int ret;
1271         uint16_t short_sig;
1272
1273         short_sig = get_short_sig(sig);
1274         prim_bucket_idx = get_prim_bucket_index(h, sig);
1275         sec_bucket_idx = get_alt_bucket_index(h, prim_bucket_idx, short_sig);
1276
1277         do {
1278                 /* Load the table change counter before the lookup
1279                  * starts. Acquire semantics will make sure that
1280                  * loads in search_one_bucket are not hoisted.
1281                  */
1282                 cnt_b = __atomic_load_n(h->tbl_chng_cnt,
1283                                 __ATOMIC_ACQUIRE);
1284
1285                 /* Check if key is in primary location */
1286                 bkt = &h->buckets[prim_bucket_idx];
1287                 ret = search_one_bucket_lf(h, key, short_sig, data, bkt);
1288                 if (ret != -1) {
1289                         __hash_rw_reader_unlock(h);
1290                         return ret;
1291                 }
1292                 /* Calculate secondary hash */
1293                 bkt = &h->buckets[sec_bucket_idx];
1294
1295                 /* Check if key is in secondary location */
1296                 FOR_EACH_BUCKET(cur_bkt, bkt) {
1297                         ret = search_one_bucket_lf(h, key, short_sig,
1298                                                 data, cur_bkt);
1299                         if (ret != -1) {
1300                                 __hash_rw_reader_unlock(h);
1301                                 return ret;
1302                         }
1303                 }
1304
1305                 /* The loads of sig_current in search_one_bucket
1306                  * should not move below the load from tbl_chng_cnt.
1307                  */
1308                 __atomic_thread_fence(__ATOMIC_ACQUIRE);
1309                 /* Re-read the table change counter to check if the
1310                  * table has changed during search. If yes, re-do
1311                  * the search.
1312                  * This load should not get hoisted. The load
1313                  * acquires on cnt_b, key index in primary bucket
1314                  * and key index in secondary bucket will make sure
1315                  * that it does not get hoisted.
1316                  */
1317                 cnt_a = __atomic_load_n(h->tbl_chng_cnt,
1318                                         __ATOMIC_ACQUIRE);
1319         } while (cnt_b != cnt_a);
1320
1321         return -ENOENT;
1322 }
1323
1324 static inline int32_t
1325 __rte_hash_lookup_with_hash(const struct rte_hash *h, const void *key,
1326                                         hash_sig_t sig, void **data)
1327 {
1328         if (h->readwrite_concur_lf_support)
1329                 return __rte_hash_lookup_with_hash_lf(h, key, sig, data);
1330         else
1331                 return __rte_hash_lookup_with_hash_l(h, key, sig, data);
1332 }
1333
1334 int32_t
1335 rte_hash_lookup_with_hash(const struct rte_hash *h,
1336                         const void *key, hash_sig_t sig)
1337 {
1338         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
1339         return __rte_hash_lookup_with_hash(h, key, sig, NULL);
1340 }
1341
1342 int32_t
1343 rte_hash_lookup(const struct rte_hash *h, const void *key)
1344 {
1345         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
1346         return __rte_hash_lookup_with_hash(h, key, rte_hash_hash(h, key), NULL);
1347 }
1348
1349 int
1350 rte_hash_lookup_with_hash_data(const struct rte_hash *h,
1351                         const void *key, hash_sig_t sig, void **data)
1352 {
1353         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
1354         return __rte_hash_lookup_with_hash(h, key, sig, data);
1355 }
1356
1357 int
1358 rte_hash_lookup_data(const struct rte_hash *h, const void *key, void **data)
1359 {
1360         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
1361         return __rte_hash_lookup_with_hash(h, key, rte_hash_hash(h, key), data);
1362 }
1363
1364 static inline void
1365 remove_entry(const struct rte_hash *h, struct rte_hash_bucket *bkt, unsigned i)
1366 {
1367         unsigned lcore_id, n_slots;
1368         struct lcore_cache *cached_free_slots;
1369
1370         if (h->use_local_cache) {
1371                 lcore_id = rte_lcore_id();
1372                 cached_free_slots = &h->local_free_slots[lcore_id];
1373                 /* Cache full, need to free it. */
1374                 if (cached_free_slots->len == LCORE_CACHE_SIZE) {
1375                         /* Need to enqueue the free slots in global ring. */
1376                         n_slots = rte_ring_mp_enqueue_burst(h->free_slots,
1377                                                 cached_free_slots->objs,
1378                                                 LCORE_CACHE_SIZE, NULL);
1379                         ERR_IF_TRUE((n_slots == 0),
1380                                 "%s: could not enqueue free slots in global ring\n",
1381                                 __func__);
1382                         cached_free_slots->len -= n_slots;
1383                 }
1384                 /* Put index of new free slot in cache. */
1385                 cached_free_slots->objs[cached_free_slots->len] =
1386                                 (void *)((uintptr_t)bkt->key_idx[i]);
1387                 cached_free_slots->len++;
1388         } else {
1389                 rte_ring_sp_enqueue(h->free_slots,
1390                                 (void *)((uintptr_t)bkt->key_idx[i]));
1391         }
1392 }
1393
1394 /* Compact the linked list by moving key from last entry in linked list to the
1395  * empty slot.
1396  */
1397 static inline void
1398 __rte_hash_compact_ll(const struct rte_hash *h,
1399                         struct rte_hash_bucket *cur_bkt, int pos) {
1400         int i;
1401         struct rte_hash_bucket *last_bkt;
1402
1403         if (!cur_bkt->next)
1404                 return;
1405
1406         last_bkt = rte_hash_get_last_bkt(cur_bkt);
1407
1408         for (i = RTE_HASH_BUCKET_ENTRIES - 1; i >= 0; i--) {
1409                 if (last_bkt->key_idx[i] != EMPTY_SLOT) {
1410                         cur_bkt->sig_current[pos] = last_bkt->sig_current[i];
1411                         __atomic_store_n(&cur_bkt->key_idx[pos],
1412                                          last_bkt->key_idx[i],
1413                                          __ATOMIC_RELEASE);
1414                         if (h->readwrite_concur_lf_support) {
1415                                 /* Inform the readers that the table has changed
1416                                  * Since there is one writer, load acquire on
1417                                  * tbl_chng_cnt is not required.
1418                                  */
1419                                 __atomic_store_n(h->tbl_chng_cnt,
1420                                          *h->tbl_chng_cnt + 1,
1421                                          __ATOMIC_RELEASE);
1422                                 /* The store to sig_current should
1423                                  * not move above the store to tbl_chng_cnt.
1424                                  */
1425                                 __atomic_thread_fence(__ATOMIC_RELEASE);
1426                         }
1427                         last_bkt->sig_current[i] = NULL_SIGNATURE;
1428                         __atomic_store_n(&last_bkt->key_idx[i],
1429                                          EMPTY_SLOT,
1430                                          __ATOMIC_RELEASE);
1431                         return;
1432                 }
1433         }
1434 }
1435
1436 /* Search one bucket and remove the matched key.
1437  * Writer is expected to hold the lock while calling this
1438  * function.
1439  */
1440 static inline int32_t
1441 search_and_remove(const struct rte_hash *h, const void *key,
1442                         struct rte_hash_bucket *bkt, uint16_t sig, int *pos)
1443 {
1444         struct rte_hash_key *k, *keys = h->key_store;
1445         unsigned int i;
1446         uint32_t key_idx;
1447
1448         /* Check if key is in bucket */
1449         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
1450                 key_idx = __atomic_load_n(&bkt->key_idx[i],
1451                                           __ATOMIC_ACQUIRE);
1452                 if (bkt->sig_current[i] == sig && key_idx != EMPTY_SLOT) {
1453                         k = (struct rte_hash_key *) ((char *)keys +
1454                                         key_idx * h->key_entry_size);
1455                         if (rte_hash_cmp_eq(key, k->key, h) == 0) {
1456                                 bkt->sig_current[i] = NULL_SIGNATURE;
1457                                 /* Free the key store index if
1458                                  * no_free_on_del is disabled.
1459                                  */
1460                                 if (!h->no_free_on_del)
1461                                         remove_entry(h, bkt, i);
1462
1463                                 __atomic_store_n(&bkt->key_idx[i],
1464                                                  EMPTY_SLOT,
1465                                                  __ATOMIC_RELEASE);
1466
1467                                 *pos = i;
1468                                 /*
1469                                  * Return index where key is stored,
1470                                  * subtracting the first dummy index
1471                                  */
1472                                 return key_idx - 1;
1473                         }
1474                 }
1475         }
1476         return -1;
1477 }
1478
1479 static inline int32_t
1480 __rte_hash_del_key_with_hash(const struct rte_hash *h, const void *key,
1481                                                 hash_sig_t sig)
1482 {
1483         uint32_t prim_bucket_idx, sec_bucket_idx;
1484         struct rte_hash_bucket *prim_bkt, *sec_bkt, *prev_bkt, *last_bkt;
1485         struct rte_hash_bucket *cur_bkt;
1486         int pos;
1487         int32_t ret, i;
1488         uint16_t short_sig;
1489
1490         short_sig = get_short_sig(sig);
1491         prim_bucket_idx = get_prim_bucket_index(h, sig);
1492         sec_bucket_idx = get_alt_bucket_index(h, prim_bucket_idx, short_sig);
1493         prim_bkt = &h->buckets[prim_bucket_idx];
1494
1495         __hash_rw_writer_lock(h);
1496         /* look for key in primary bucket */
1497         ret = search_and_remove(h, key, prim_bkt, short_sig, &pos);
1498         if (ret != -1) {
1499                 __rte_hash_compact_ll(h, prim_bkt, pos);
1500                 last_bkt = prim_bkt->next;
1501                 prev_bkt = prim_bkt;
1502                 goto return_bkt;
1503         }
1504
1505         /* Calculate secondary hash */
1506         sec_bkt = &h->buckets[sec_bucket_idx];
1507
1508         FOR_EACH_BUCKET(cur_bkt, sec_bkt) {
1509                 ret = search_and_remove(h, key, cur_bkt, short_sig, &pos);
1510                 if (ret != -1) {
1511                         __rte_hash_compact_ll(h, cur_bkt, pos);
1512                         last_bkt = sec_bkt->next;
1513                         prev_bkt = sec_bkt;
1514                         goto return_bkt;
1515                 }
1516         }
1517
1518         __hash_rw_writer_unlock(h);
1519         return -ENOENT;
1520
1521 /* Search last bucket to see if empty to be recycled */
1522 return_bkt:
1523         if (!last_bkt) {
1524                 __hash_rw_writer_unlock(h);
1525                 return ret;
1526         }
1527         while (last_bkt->next) {
1528                 prev_bkt = last_bkt;
1529                 last_bkt = last_bkt->next;
1530         }
1531
1532         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
1533                 if (last_bkt->key_idx[i] != EMPTY_SLOT)
1534                         break;
1535         }
1536         /* found empty bucket and recycle */
1537         if (i == RTE_HASH_BUCKET_ENTRIES) {
1538                 prev_bkt->next = NULL;
1539                 uint32_t index = last_bkt - h->buckets_ext + 1;
1540                 /* Recycle the empty bkt if
1541                  * no_free_on_del is disabled.
1542                  */
1543                 if (h->no_free_on_del)
1544                         /* Store index of an empty ext bkt to be recycled
1545                          * on calling rte_hash_del_xxx APIs.
1546                          * When lock free read-write concurrency is enabled,
1547                          * an empty ext bkt cannot be put into free list
1548                          * immediately (as readers might be using it still).
1549                          * Hence freeing of the ext bkt is piggy-backed to
1550                          * freeing of the key index.
1551                          */
1552                         h->ext_bkt_to_free[ret] = index;
1553                 else
1554                         rte_ring_sp_enqueue(h->free_ext_bkts, (void *)(uintptr_t)index);
1555         }
1556         __hash_rw_writer_unlock(h);
1557         return ret;
1558 }
1559
1560 int32_t
1561 rte_hash_del_key_with_hash(const struct rte_hash *h,
1562                         const void *key, hash_sig_t sig)
1563 {
1564         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
1565         return __rte_hash_del_key_with_hash(h, key, sig);
1566 }
1567
1568 int32_t
1569 rte_hash_del_key(const struct rte_hash *h, const void *key)
1570 {
1571         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
1572         return __rte_hash_del_key_with_hash(h, key, rte_hash_hash(h, key));
1573 }
1574
1575 int
1576 rte_hash_get_key_with_position(const struct rte_hash *h, const int32_t position,
1577                                void **key)
1578 {
1579         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
1580
1581         struct rte_hash_key *k, *keys = h->key_store;
1582         k = (struct rte_hash_key *) ((char *) keys + (position + 1) *
1583                                      h->key_entry_size);
1584         *key = k->key;
1585
1586         if (position !=
1587             __rte_hash_lookup_with_hash(h, *key, rte_hash_hash(h, *key),
1588                                         NULL)) {
1589                 return -ENOENT;
1590         }
1591
1592         return 0;
1593 }
1594
1595 int
1596 rte_hash_free_key_with_position(const struct rte_hash *h,
1597                                 const int32_t position)
1598 {
1599         /* Key index where key is stored, adding the first dummy index */
1600         uint32_t key_idx = position + 1;
1601
1602         RETURN_IF_TRUE(((h == NULL) || (key_idx == EMPTY_SLOT)), -EINVAL);
1603
1604         unsigned int lcore_id, n_slots;
1605         struct lcore_cache *cached_free_slots;
1606         const uint32_t total_entries = h->use_local_cache ?
1607                 h->entries + (RTE_MAX_LCORE - 1) * (LCORE_CACHE_SIZE - 1) + 1
1608                                                         : h->entries + 1;
1609
1610         /* Out of bounds */
1611         if (key_idx >= total_entries)
1612                 return -EINVAL;
1613         if (h->ext_table_support && h->readwrite_concur_lf_support) {
1614                 uint32_t index = h->ext_bkt_to_free[position];
1615                 if (index) {
1616                         /* Recycle empty ext bkt to free list. */
1617                         rte_ring_sp_enqueue(h->free_ext_bkts, (void *)(uintptr_t)index);
1618                         h->ext_bkt_to_free[position] = 0;
1619                 }
1620         }
1621
1622         if (h->use_local_cache) {
1623                 lcore_id = rte_lcore_id();
1624                 cached_free_slots = &h->local_free_slots[lcore_id];
1625                 /* Cache full, need to free it. */
1626                 if (cached_free_slots->len == LCORE_CACHE_SIZE) {
1627                         /* Need to enqueue the free slots in global ring. */
1628                         n_slots = rte_ring_mp_enqueue_burst(h->free_slots,
1629                                                 cached_free_slots->objs,
1630                                                 LCORE_CACHE_SIZE, NULL);
1631                         RETURN_IF_TRUE((n_slots == 0), -EFAULT);
1632                         cached_free_slots->len -= n_slots;
1633                 }
1634                 /* Put index of new free slot in cache. */
1635                 cached_free_slots->objs[cached_free_slots->len] =
1636                                         (void *)((uintptr_t)key_idx);
1637                 cached_free_slots->len++;
1638         } else {
1639                 rte_ring_sp_enqueue(h->free_slots,
1640                                 (void *)((uintptr_t)key_idx));
1641         }
1642
1643         return 0;
1644 }
1645
1646 static inline void
1647 compare_signatures(uint32_t *prim_hash_matches, uint32_t *sec_hash_matches,
1648                         const struct rte_hash_bucket *prim_bkt,
1649                         const struct rte_hash_bucket *sec_bkt,
1650                         uint16_t sig,
1651                         enum rte_hash_sig_compare_function sig_cmp_fn)
1652 {
1653         unsigned int i;
1654
1655         /* For match mask the first bit of every two bits indicates the match */
1656         switch (sig_cmp_fn) {
1657 #if defined(RTE_MACHINE_CPUFLAG_SSE2)
1658         case RTE_HASH_COMPARE_SSE:
1659                 /* Compare all signatures in the bucket */
1660                 *prim_hash_matches = _mm_movemask_epi8(_mm_cmpeq_epi16(
1661                                 _mm_load_si128(
1662                                         (__m128i const *)prim_bkt->sig_current),
1663                                 _mm_set1_epi16(sig)));
1664                 /* Compare all signatures in the bucket */
1665                 *sec_hash_matches = _mm_movemask_epi8(_mm_cmpeq_epi16(
1666                                 _mm_load_si128(
1667                                         (__m128i const *)sec_bkt->sig_current),
1668                                 _mm_set1_epi16(sig)));
1669                 break;
1670 #elif defined(RTE_MACHINE_CPUFLAG_NEON)
1671         case RTE_HASH_COMPARE_NEON: {
1672                 uint16x8_t vmat, vsig, x;
1673                 int16x8_t shift = {-15, -13, -11, -9, -7, -5, -3, -1};
1674
1675                 vsig = vld1q_dup_u16((uint16_t const *)&sig);
1676                 /* Compare all signatures in the primary bucket */
1677                 vmat = vceqq_u16(vsig,
1678                         vld1q_u16((uint16_t const *)prim_bkt->sig_current));
1679                 x = vshlq_u16(vandq_u16(vmat, vdupq_n_u16(0x8000)), shift);
1680                 *prim_hash_matches = (uint32_t)(vaddvq_u16(x));
1681                 /* Compare all signatures in the secondary bucket */
1682                 vmat = vceqq_u16(vsig,
1683                         vld1q_u16((uint16_t const *)sec_bkt->sig_current));
1684                 x = vshlq_u16(vandq_u16(vmat, vdupq_n_u16(0x8000)), shift);
1685                 *sec_hash_matches = (uint32_t)(vaddvq_u16(x));
1686                 }
1687                 break;
1688 #endif
1689         default:
1690                 for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
1691                         *prim_hash_matches |=
1692                                 ((sig == prim_bkt->sig_current[i]) << (i << 1));
1693                         *sec_hash_matches |=
1694                                 ((sig == sec_bkt->sig_current[i]) << (i << 1));
1695                 }
1696         }
1697 }
1698
1699 #define PREFETCH_OFFSET 4
1700 static inline void
1701 __rte_hash_lookup_bulk_l(const struct rte_hash *h, const void **keys,
1702                         int32_t num_keys, int32_t *positions,
1703                         uint64_t *hit_mask, void *data[])
1704 {
1705         uint64_t hits = 0;
1706         int32_t i;
1707         int32_t ret;
1708         uint32_t prim_hash[RTE_HASH_LOOKUP_BULK_MAX];
1709         uint32_t prim_index[RTE_HASH_LOOKUP_BULK_MAX];
1710         uint32_t sec_index[RTE_HASH_LOOKUP_BULK_MAX];
1711         uint16_t sig[RTE_HASH_LOOKUP_BULK_MAX];
1712         const struct rte_hash_bucket *primary_bkt[RTE_HASH_LOOKUP_BULK_MAX];
1713         const struct rte_hash_bucket *secondary_bkt[RTE_HASH_LOOKUP_BULK_MAX];
1714         uint32_t prim_hitmask[RTE_HASH_LOOKUP_BULK_MAX] = {0};
1715         uint32_t sec_hitmask[RTE_HASH_LOOKUP_BULK_MAX] = {0};
1716         struct rte_hash_bucket *cur_bkt, *next_bkt;
1717
1718         /* Prefetch first keys */
1719         for (i = 0; i < PREFETCH_OFFSET && i < num_keys; i++)
1720                 rte_prefetch0(keys[i]);
1721
1722         /*
1723          * Prefetch rest of the keys, calculate primary and
1724          * secondary bucket and prefetch them
1725          */
1726         for (i = 0; i < (num_keys - PREFETCH_OFFSET); i++) {
1727                 rte_prefetch0(keys[i + PREFETCH_OFFSET]);
1728
1729                 prim_hash[i] = rte_hash_hash(h, keys[i]);
1730
1731                 sig[i] = get_short_sig(prim_hash[i]);
1732                 prim_index[i] = get_prim_bucket_index(h, prim_hash[i]);
1733                 sec_index[i] = get_alt_bucket_index(h, prim_index[i], sig[i]);
1734
1735                 primary_bkt[i] = &h->buckets[prim_index[i]];
1736                 secondary_bkt[i] = &h->buckets[sec_index[i]];
1737
1738                 rte_prefetch0(primary_bkt[i]);
1739                 rte_prefetch0(secondary_bkt[i]);
1740         }
1741
1742         /* Calculate and prefetch rest of the buckets */
1743         for (; i < num_keys; i++) {
1744                 prim_hash[i] = rte_hash_hash(h, keys[i]);
1745
1746                 sig[i] = get_short_sig(prim_hash[i]);
1747                 prim_index[i] = get_prim_bucket_index(h, prim_hash[i]);
1748                 sec_index[i] = get_alt_bucket_index(h, prim_index[i], sig[i]);
1749
1750                 primary_bkt[i] = &h->buckets[prim_index[i]];
1751                 secondary_bkt[i] = &h->buckets[sec_index[i]];
1752
1753                 rte_prefetch0(primary_bkt[i]);
1754                 rte_prefetch0(secondary_bkt[i]);
1755         }
1756
1757         __hash_rw_reader_lock(h);
1758
1759         /* Compare signatures and prefetch key slot of first hit */
1760         for (i = 0; i < num_keys; i++) {
1761                 compare_signatures(&prim_hitmask[i], &sec_hitmask[i],
1762                         primary_bkt[i], secondary_bkt[i],
1763                         sig[i], h->sig_cmp_fn);
1764
1765                 if (prim_hitmask[i]) {
1766                         uint32_t first_hit =
1767                                         __builtin_ctzl(prim_hitmask[i])
1768                                         >> 1;
1769                         uint32_t key_idx =
1770                                 primary_bkt[i]->key_idx[first_hit];
1771                         const struct rte_hash_key *key_slot =
1772                                 (const struct rte_hash_key *)(
1773                                 (const char *)h->key_store +
1774                                 key_idx * h->key_entry_size);
1775                         rte_prefetch0(key_slot);
1776                         continue;
1777                 }
1778
1779                 if (sec_hitmask[i]) {
1780                         uint32_t first_hit =
1781                                         __builtin_ctzl(sec_hitmask[i])
1782                                         >> 1;
1783                         uint32_t key_idx =
1784                                 secondary_bkt[i]->key_idx[first_hit];
1785                         const struct rte_hash_key *key_slot =
1786                                 (const struct rte_hash_key *)(
1787                                 (const char *)h->key_store +
1788                                 key_idx * h->key_entry_size);
1789                         rte_prefetch0(key_slot);
1790                 }
1791         }
1792
1793         /* Compare keys, first hits in primary first */
1794         for (i = 0; i < num_keys; i++) {
1795                 positions[i] = -ENOENT;
1796                 while (prim_hitmask[i]) {
1797                         uint32_t hit_index =
1798                                         __builtin_ctzl(prim_hitmask[i])
1799                                         >> 1;
1800                         uint32_t key_idx =
1801                                 primary_bkt[i]->key_idx[hit_index];
1802                         const struct rte_hash_key *key_slot =
1803                                 (const struct rte_hash_key *)(
1804                                 (const char *)h->key_store +
1805                                 key_idx * h->key_entry_size);
1806
1807                         /*
1808                          * If key index is 0, do not compare key,
1809                          * as it is checking the dummy slot
1810                          */
1811                         if (!!key_idx &
1812                                 !rte_hash_cmp_eq(
1813                                         key_slot->key, keys[i], h)) {
1814                                 if (data != NULL)
1815                                         data[i] = key_slot->pdata;
1816
1817                                 hits |= 1ULL << i;
1818                                 positions[i] = key_idx - 1;
1819                                 goto next_key;
1820                         }
1821                         prim_hitmask[i] &= ~(3ULL << (hit_index << 1));
1822                 }
1823
1824                 while (sec_hitmask[i]) {
1825                         uint32_t hit_index =
1826                                         __builtin_ctzl(sec_hitmask[i])
1827                                         >> 1;
1828                         uint32_t key_idx =
1829                                 secondary_bkt[i]->key_idx[hit_index];
1830                         const struct rte_hash_key *key_slot =
1831                                 (const struct rte_hash_key *)(
1832                                 (const char *)h->key_store +
1833                                 key_idx * h->key_entry_size);
1834
1835                         /*
1836                          * If key index is 0, do not compare key,
1837                          * as it is checking the dummy slot
1838                          */
1839
1840                         if (!!key_idx &
1841                                 !rte_hash_cmp_eq(
1842                                         key_slot->key, keys[i], h)) {
1843                                 if (data != NULL)
1844                                         data[i] = key_slot->pdata;
1845
1846                                 hits |= 1ULL << i;
1847                                 positions[i] = key_idx - 1;
1848                                 goto next_key;
1849                         }
1850                         sec_hitmask[i] &= ~(3ULL << (hit_index << 1));
1851                 }
1852 next_key:
1853                 continue;
1854         }
1855
1856         /* all found, do not need to go through ext bkt */
1857         if ((hits == ((1ULL << num_keys) - 1)) || !h->ext_table_support) {
1858                 if (hit_mask != NULL)
1859                         *hit_mask = hits;
1860                 __hash_rw_reader_unlock(h);
1861                 return;
1862         }
1863
1864         /* need to check ext buckets for match */
1865         for (i = 0; i < num_keys; i++) {
1866                 if ((hits & (1ULL << i)) != 0)
1867                         continue;
1868                 next_bkt = secondary_bkt[i]->next;
1869                 FOR_EACH_BUCKET(cur_bkt, next_bkt) {
1870                         if (data != NULL)
1871                                 ret = search_one_bucket_l(h, keys[i],
1872                                                 sig[i], &data[i], cur_bkt);
1873                         else
1874                                 ret = search_one_bucket_l(h, keys[i],
1875                                                 sig[i], NULL, cur_bkt);
1876                         if (ret != -1) {
1877                                 positions[i] = ret;
1878                                 hits |= 1ULL << i;
1879                                 break;
1880                         }
1881                 }
1882         }
1883
1884         __hash_rw_reader_unlock(h);
1885
1886         if (hit_mask != NULL)
1887                 *hit_mask = hits;
1888 }
1889
1890 static inline void
1891 __rte_hash_lookup_bulk_lf(const struct rte_hash *h, const void **keys,
1892                         int32_t num_keys, int32_t *positions,
1893                         uint64_t *hit_mask, void *data[])
1894 {
1895         uint64_t hits = 0;
1896         int32_t i;
1897         int32_t ret;
1898         uint32_t prim_hash[RTE_HASH_LOOKUP_BULK_MAX];
1899         uint32_t prim_index[RTE_HASH_LOOKUP_BULK_MAX];
1900         uint32_t sec_index[RTE_HASH_LOOKUP_BULK_MAX];
1901         uint16_t sig[RTE_HASH_LOOKUP_BULK_MAX];
1902         const struct rte_hash_bucket *primary_bkt[RTE_HASH_LOOKUP_BULK_MAX];
1903         const struct rte_hash_bucket *secondary_bkt[RTE_HASH_LOOKUP_BULK_MAX];
1904         uint32_t prim_hitmask[RTE_HASH_LOOKUP_BULK_MAX] = {0};
1905         uint32_t sec_hitmask[RTE_HASH_LOOKUP_BULK_MAX] = {0};
1906         struct rte_hash_bucket *cur_bkt, *next_bkt;
1907         uint32_t cnt_b, cnt_a;
1908
1909         /* Prefetch first keys */
1910         for (i = 0; i < PREFETCH_OFFSET && i < num_keys; i++)
1911                 rte_prefetch0(keys[i]);
1912
1913         /*
1914          * Prefetch rest of the keys, calculate primary and
1915          * secondary bucket and prefetch them
1916          */
1917         for (i = 0; i < (num_keys - PREFETCH_OFFSET); i++) {
1918                 rte_prefetch0(keys[i + PREFETCH_OFFSET]);
1919
1920                 prim_hash[i] = rte_hash_hash(h, keys[i]);
1921
1922                 sig[i] = get_short_sig(prim_hash[i]);
1923                 prim_index[i] = get_prim_bucket_index(h, prim_hash[i]);
1924                 sec_index[i] = get_alt_bucket_index(h, prim_index[i], sig[i]);
1925
1926                 primary_bkt[i] = &h->buckets[prim_index[i]];
1927                 secondary_bkt[i] = &h->buckets[sec_index[i]];
1928
1929                 rte_prefetch0(primary_bkt[i]);
1930                 rte_prefetch0(secondary_bkt[i]);
1931         }
1932
1933         /* Calculate and prefetch rest of the buckets */
1934         for (; i < num_keys; i++) {
1935                 prim_hash[i] = rte_hash_hash(h, keys[i]);
1936
1937                 sig[i] = get_short_sig(prim_hash[i]);
1938                 prim_index[i] = get_prim_bucket_index(h, prim_hash[i]);
1939                 sec_index[i] = get_alt_bucket_index(h, prim_index[i], sig[i]);
1940
1941                 primary_bkt[i] = &h->buckets[prim_index[i]];
1942                 secondary_bkt[i] = &h->buckets[sec_index[i]];
1943
1944                 rte_prefetch0(primary_bkt[i]);
1945                 rte_prefetch0(secondary_bkt[i]);
1946         }
1947
1948         for (i = 0; i < num_keys; i++)
1949                 positions[i] = -ENOENT;
1950
1951         do {
1952                 /* Load the table change counter before the lookup
1953                  * starts. Acquire semantics will make sure that
1954                  * loads in compare_signatures are not hoisted.
1955                  */
1956                 cnt_b = __atomic_load_n(h->tbl_chng_cnt,
1957                                         __ATOMIC_ACQUIRE);
1958
1959                 /* Compare signatures and prefetch key slot of first hit */
1960                 for (i = 0; i < num_keys; i++) {
1961                         compare_signatures(&prim_hitmask[i], &sec_hitmask[i],
1962                                 primary_bkt[i], secondary_bkt[i],
1963                                 sig[i], h->sig_cmp_fn);
1964
1965                         if (prim_hitmask[i]) {
1966                                 uint32_t first_hit =
1967                                                 __builtin_ctzl(prim_hitmask[i])
1968                                                 >> 1;
1969                                 uint32_t key_idx =
1970                                         primary_bkt[i]->key_idx[first_hit];
1971                                 const struct rte_hash_key *key_slot =
1972                                         (const struct rte_hash_key *)(
1973                                         (const char *)h->key_store +
1974                                         key_idx * h->key_entry_size);
1975                                 rte_prefetch0(key_slot);
1976                                 continue;
1977                         }
1978
1979                         if (sec_hitmask[i]) {
1980                                 uint32_t first_hit =
1981                                                 __builtin_ctzl(sec_hitmask[i])
1982                                                 >> 1;
1983                                 uint32_t key_idx =
1984                                         secondary_bkt[i]->key_idx[first_hit];
1985                                 const struct rte_hash_key *key_slot =
1986                                         (const struct rte_hash_key *)(
1987                                         (const char *)h->key_store +
1988                                         key_idx * h->key_entry_size);
1989                                 rte_prefetch0(key_slot);
1990                         }
1991                 }
1992
1993                 /* Compare keys, first hits in primary first */
1994                 for (i = 0; i < num_keys; i++) {
1995                         while (prim_hitmask[i]) {
1996                                 uint32_t hit_index =
1997                                                 __builtin_ctzl(prim_hitmask[i])
1998                                                 >> 1;
1999                                 uint32_t key_idx =
2000                                 __atomic_load_n(
2001                                         &primary_bkt[i]->key_idx[hit_index],
2002                                         __ATOMIC_ACQUIRE);
2003                                 const struct rte_hash_key *key_slot =
2004                                         (const struct rte_hash_key *)(
2005                                         (const char *)h->key_store +
2006                                         key_idx * h->key_entry_size);
2007
2008                                 /*
2009                                  * If key index is 0, do not compare key,
2010                                  * as it is checking the dummy slot
2011                                  */
2012                                 if (!!key_idx &
2013                                         !rte_hash_cmp_eq(
2014                                                 key_slot->key, keys[i], h)) {
2015                                         if (data != NULL)
2016                                                 data[i] = __atomic_load_n(
2017                                                         &key_slot->pdata,
2018                                                         __ATOMIC_ACQUIRE);
2019
2020                                         hits |= 1ULL << i;
2021                                         positions[i] = key_idx - 1;
2022                                         goto next_key;
2023                                 }
2024                                 prim_hitmask[i] &= ~(3ULL << (hit_index << 1));
2025                         }
2026
2027                         while (sec_hitmask[i]) {
2028                                 uint32_t hit_index =
2029                                                 __builtin_ctzl(sec_hitmask[i])
2030                                                 >> 1;
2031                                 uint32_t key_idx =
2032                                 __atomic_load_n(
2033                                         &secondary_bkt[i]->key_idx[hit_index],
2034                                         __ATOMIC_ACQUIRE);
2035                                 const struct rte_hash_key *key_slot =
2036                                         (const struct rte_hash_key *)(
2037                                         (const char *)h->key_store +
2038                                         key_idx * h->key_entry_size);
2039
2040                                 /*
2041                                  * If key index is 0, do not compare key,
2042                                  * as it is checking the dummy slot
2043                                  */
2044
2045                                 if (!!key_idx &
2046                                         !rte_hash_cmp_eq(
2047                                                 key_slot->key, keys[i], h)) {
2048                                         if (data != NULL)
2049                                                 data[i] = __atomic_load_n(
2050                                                         &key_slot->pdata,
2051                                                         __ATOMIC_ACQUIRE);
2052
2053                                         hits |= 1ULL << i;
2054                                         positions[i] = key_idx - 1;
2055                                         goto next_key;
2056                                 }
2057                                 sec_hitmask[i] &= ~(3ULL << (hit_index << 1));
2058                         }
2059 next_key:
2060                         continue;
2061                 }
2062
2063                 /* all found, do not need to go through ext bkt */
2064                 if (hits == ((1ULL << num_keys) - 1)) {
2065                         if (hit_mask != NULL)
2066                                 *hit_mask = hits;
2067                         return;
2068                 }
2069                 /* need to check ext buckets for match */
2070                 if (h->ext_table_support) {
2071                         for (i = 0; i < num_keys; i++) {
2072                                 if ((hits & (1ULL << i)) != 0)
2073                                         continue;
2074                                 next_bkt = secondary_bkt[i]->next;
2075                                 FOR_EACH_BUCKET(cur_bkt, next_bkt) {
2076                                         if (data != NULL)
2077                                                 ret = search_one_bucket_lf(h,
2078                                                         keys[i], sig[i],
2079                                                         &data[i], cur_bkt);
2080                                         else
2081                                                 ret = search_one_bucket_lf(h,
2082                                                                 keys[i], sig[i],
2083                                                                 NULL, cur_bkt);
2084                                         if (ret != -1) {
2085                                                 positions[i] = ret;
2086                                                 hits |= 1ULL << i;
2087                                                 break;
2088                                         }
2089                                 }
2090                         }
2091                 }
2092                 /* The loads of sig_current in compare_signatures
2093                  * should not move below the load from tbl_chng_cnt.
2094                  */
2095                 __atomic_thread_fence(__ATOMIC_ACQUIRE);
2096                 /* Re-read the table change counter to check if the
2097                  * table has changed during search. If yes, re-do
2098                  * the search.
2099                  * This load should not get hoisted. The load
2100                  * acquires on cnt_b, primary key index and secondary
2101                  * key index will make sure that it does not get
2102                  * hoisted.
2103                  */
2104                 cnt_a = __atomic_load_n(h->tbl_chng_cnt,
2105                                         __ATOMIC_ACQUIRE);
2106         } while (cnt_b != cnt_a);
2107
2108         if (hit_mask != NULL)
2109                 *hit_mask = hits;
2110 }
2111
2112 static inline void
2113 __rte_hash_lookup_bulk(const struct rte_hash *h, const void **keys,
2114                         int32_t num_keys, int32_t *positions,
2115                         uint64_t *hit_mask, void *data[])
2116 {
2117         if (h->readwrite_concur_lf_support)
2118                 __rte_hash_lookup_bulk_lf(h, keys, num_keys, positions,
2119                                           hit_mask, data);
2120         else
2121                 __rte_hash_lookup_bulk_l(h, keys, num_keys, positions,
2122                                          hit_mask, data);
2123 }
2124
2125 int
2126 rte_hash_lookup_bulk(const struct rte_hash *h, const void **keys,
2127                       uint32_t num_keys, int32_t *positions)
2128 {
2129         RETURN_IF_TRUE(((h == NULL) || (keys == NULL) || (num_keys == 0) ||
2130                         (num_keys > RTE_HASH_LOOKUP_BULK_MAX) ||
2131                         (positions == NULL)), -EINVAL);
2132
2133         __rte_hash_lookup_bulk(h, keys, num_keys, positions, NULL, NULL);
2134         return 0;
2135 }
2136
2137 int
2138 rte_hash_lookup_bulk_data(const struct rte_hash *h, const void **keys,
2139                       uint32_t num_keys, uint64_t *hit_mask, void *data[])
2140 {
2141         RETURN_IF_TRUE(((h == NULL) || (keys == NULL) || (num_keys == 0) ||
2142                         (num_keys > RTE_HASH_LOOKUP_BULK_MAX) ||
2143                         (hit_mask == NULL)), -EINVAL);
2144
2145         int32_t positions[num_keys];
2146
2147         __rte_hash_lookup_bulk(h, keys, num_keys, positions, hit_mask, data);
2148
2149         /* Return number of hits */
2150         return __builtin_popcountl(*hit_mask);
2151 }
2152
2153 int32_t
2154 rte_hash_iterate(const struct rte_hash *h, const void **key, void **data, uint32_t *next)
2155 {
2156         uint32_t bucket_idx, idx, position;
2157         struct rte_hash_key *next_key;
2158
2159         RETURN_IF_TRUE(((h == NULL) || (next == NULL)), -EINVAL);
2160
2161         const uint32_t total_entries_main = h->num_buckets *
2162                                                         RTE_HASH_BUCKET_ENTRIES;
2163         const uint32_t total_entries = total_entries_main << 1;
2164
2165         /* Out of bounds of all buckets (both main table and ext table) */
2166         if (*next >= total_entries_main)
2167                 goto extend_table;
2168
2169         /* Calculate bucket and index of current iterator */
2170         bucket_idx = *next / RTE_HASH_BUCKET_ENTRIES;
2171         idx = *next % RTE_HASH_BUCKET_ENTRIES;
2172
2173         /* If current position is empty, go to the next one */
2174         while ((position = __atomic_load_n(&h->buckets[bucket_idx].key_idx[idx],
2175                                         __ATOMIC_ACQUIRE)) == EMPTY_SLOT) {
2176                 (*next)++;
2177                 /* End of table */
2178                 if (*next == total_entries_main)
2179                         goto extend_table;
2180                 bucket_idx = *next / RTE_HASH_BUCKET_ENTRIES;
2181                 idx = *next % RTE_HASH_BUCKET_ENTRIES;
2182         }
2183
2184         __hash_rw_reader_lock(h);
2185         next_key = (struct rte_hash_key *) ((char *)h->key_store +
2186                                 position * h->key_entry_size);
2187         /* Return key and data */
2188         *key = next_key->key;
2189         *data = next_key->pdata;
2190
2191         __hash_rw_reader_unlock(h);
2192
2193         /* Increment iterator */
2194         (*next)++;
2195
2196         return position - 1;
2197
2198 /* Begin to iterate extendable buckets */
2199 extend_table:
2200         /* Out of total bound or if ext bucket feature is not enabled */
2201         if (*next >= total_entries || !h->ext_table_support)
2202                 return -ENOENT;
2203
2204         bucket_idx = (*next - total_entries_main) / RTE_HASH_BUCKET_ENTRIES;
2205         idx = (*next - total_entries_main) % RTE_HASH_BUCKET_ENTRIES;
2206
2207         while ((position = h->buckets_ext[bucket_idx].key_idx[idx]) == EMPTY_SLOT) {
2208                 (*next)++;
2209                 if (*next == total_entries)
2210                         return -ENOENT;
2211                 bucket_idx = (*next - total_entries_main) /
2212                                                 RTE_HASH_BUCKET_ENTRIES;
2213                 idx = (*next - total_entries_main) % RTE_HASH_BUCKET_ENTRIES;
2214         }
2215         __hash_rw_reader_lock(h);
2216         next_key = (struct rte_hash_key *) ((char *)h->key_store +
2217                                 position * h->key_entry_size);
2218         /* Return key and data */
2219         *key = next_key->key;
2220         *data = next_key->pdata;
2221
2222         __hash_rw_reader_unlock(h);
2223
2224         /* Increment iterator */
2225         (*next)++;
2226         return position - 1;
2227 }