5b2b8ddeb098bdf50269e5e72b911eb532a4675c
[dpdk.git] / lib / librte_hash / rte_cuckoo_hash.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2016 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <string.h>
35 #include <stdint.h>
36 #include <errno.h>
37 #include <stdio.h>
38 #include <stdarg.h>
39 #include <sys/queue.h>
40
41 #include <rte_common.h>
42 #include <rte_memory.h>         /* for definition of RTE_CACHE_LINE_SIZE */
43 #include <rte_log.h>
44 #include <rte_memcpy.h>
45 #include <rte_prefetch.h>
46 #include <rte_branch_prediction.h>
47 #include <rte_memzone.h>
48 #include <rte_malloc.h>
49 #include <rte_eal.h>
50 #include <rte_eal_memconfig.h>
51 #include <rte_per_lcore.h>
52 #include <rte_errno.h>
53 #include <rte_string_fns.h>
54 #include <rte_cpuflags.h>
55 #include <rte_log.h>
56 #include <rte_rwlock.h>
57 #include <rte_spinlock.h>
58 #include <rte_ring.h>
59 #include <rte_compat.h>
60 #include <rte_pause.h>
61
62 #include "rte_hash.h"
63 #include "rte_cuckoo_hash.h"
64
65 #if defined(RTE_ARCH_X86)
66 #include "rte_cuckoo_hash_x86.h"
67 #endif
68
69 TAILQ_HEAD(rte_hash_list, rte_tailq_entry);
70
71 static struct rte_tailq_elem rte_hash_tailq = {
72         .name = "RTE_HASH",
73 };
74 EAL_REGISTER_TAILQ(rte_hash_tailq)
75
76 struct rte_hash *
77 rte_hash_find_existing(const char *name)
78 {
79         struct rte_hash *h = NULL;
80         struct rte_tailq_entry *te;
81         struct rte_hash_list *hash_list;
82
83         hash_list = RTE_TAILQ_CAST(rte_hash_tailq.head, rte_hash_list);
84
85         rte_rwlock_read_lock(RTE_EAL_TAILQ_RWLOCK);
86         TAILQ_FOREACH(te, hash_list, next) {
87                 h = (struct rte_hash *) te->data;
88                 if (strncmp(name, h->name, RTE_HASH_NAMESIZE) == 0)
89                         break;
90         }
91         rte_rwlock_read_unlock(RTE_EAL_TAILQ_RWLOCK);
92
93         if (te == NULL) {
94                 rte_errno = ENOENT;
95                 return NULL;
96         }
97         return h;
98 }
99
100 void rte_hash_set_cmp_func(struct rte_hash *h, rte_hash_cmp_eq_t func)
101 {
102         h->cmp_jump_table_idx = KEY_CUSTOM;
103         h->rte_hash_custom_cmp_eq = func;
104 }
105
106 static inline int
107 rte_hash_cmp_eq(const void *key1, const void *key2, const struct rte_hash *h)
108 {
109         if (h->cmp_jump_table_idx == KEY_CUSTOM)
110                 return h->rte_hash_custom_cmp_eq(key1, key2, h->key_len);
111         else
112                 return cmp_jump_table[h->cmp_jump_table_idx](key1, key2, h->key_len);
113 }
114
115 struct rte_hash *
116 rte_hash_create(const struct rte_hash_parameters *params)
117 {
118         struct rte_hash *h = NULL;
119         struct rte_tailq_entry *te = NULL;
120         struct rte_hash_list *hash_list;
121         struct rte_ring *r = NULL;
122         char hash_name[RTE_HASH_NAMESIZE];
123         void *k = NULL;
124         void *buckets = NULL;
125         char ring_name[RTE_RING_NAMESIZE];
126         unsigned num_key_slots;
127         unsigned hw_trans_mem_support = 0;
128         unsigned i;
129
130         hash_list = RTE_TAILQ_CAST(rte_hash_tailq.head, rte_hash_list);
131
132         if (params == NULL) {
133                 RTE_LOG(ERR, HASH, "rte_hash_create has no parameters\n");
134                 return NULL;
135         }
136
137         /* Check for valid parameters */
138         if ((params->entries > RTE_HASH_ENTRIES_MAX) ||
139                         (params->entries < RTE_HASH_BUCKET_ENTRIES) ||
140                         !rte_is_power_of_2(RTE_HASH_BUCKET_ENTRIES) ||
141                         (params->key_len == 0)) {
142                 rte_errno = EINVAL;
143                 RTE_LOG(ERR, HASH, "rte_hash_create has invalid parameters\n");
144                 return NULL;
145         }
146
147         /* Check extra flags field to check extra options. */
148         if (params->extra_flag & RTE_HASH_EXTRA_FLAGS_TRANS_MEM_SUPPORT)
149                 hw_trans_mem_support = 1;
150
151         /* Store all keys and leave the first entry as a dummy entry for lookup_bulk */
152         if (hw_trans_mem_support)
153                 /*
154                  * Increase number of slots by total number of indices
155                  * that can be stored in the lcore caches
156                  * except for the first cache
157                  */
158                 num_key_slots = params->entries + (RTE_MAX_LCORE - 1) *
159                                         LCORE_CACHE_SIZE + 1;
160         else
161                 num_key_slots = params->entries + 1;
162
163         snprintf(ring_name, sizeof(ring_name), "HT_%s", params->name);
164         /* Create ring (Dummy slot index is not enqueued) */
165         r = rte_ring_create(ring_name, rte_align32pow2(num_key_slots - 1),
166                         params->socket_id, 0);
167         if (r == NULL) {
168                 RTE_LOG(ERR, HASH, "memory allocation failed\n");
169                 goto err;
170         }
171
172         snprintf(hash_name, sizeof(hash_name), "HT_%s", params->name);
173
174         rte_rwlock_write_lock(RTE_EAL_TAILQ_RWLOCK);
175
176         /* guarantee there's no existing: this is normally already checked
177          * by ring creation above */
178         TAILQ_FOREACH(te, hash_list, next) {
179                 h = (struct rte_hash *) te->data;
180                 if (strncmp(params->name, h->name, RTE_HASH_NAMESIZE) == 0)
181                         break;
182         }
183         h = NULL;
184         if (te != NULL) {
185                 rte_errno = EEXIST;
186                 te = NULL;
187                 goto err_unlock;
188         }
189
190         te = rte_zmalloc("HASH_TAILQ_ENTRY", sizeof(*te), 0);
191         if (te == NULL) {
192                 RTE_LOG(ERR, HASH, "tailq entry allocation failed\n");
193                 goto err_unlock;
194         }
195
196         h = (struct rte_hash *)rte_zmalloc_socket(hash_name, sizeof(struct rte_hash),
197                                         RTE_CACHE_LINE_SIZE, params->socket_id);
198
199         if (h == NULL) {
200                 RTE_LOG(ERR, HASH, "memory allocation failed\n");
201                 goto err_unlock;
202         }
203
204         const uint32_t num_buckets = rte_align32pow2(params->entries)
205                                         / RTE_HASH_BUCKET_ENTRIES;
206
207         buckets = rte_zmalloc_socket(NULL,
208                                 num_buckets * sizeof(struct rte_hash_bucket),
209                                 RTE_CACHE_LINE_SIZE, params->socket_id);
210
211         if (buckets == NULL) {
212                 RTE_LOG(ERR, HASH, "memory allocation failed\n");
213                 goto err_unlock;
214         }
215
216         const uint32_t key_entry_size = sizeof(struct rte_hash_key) + params->key_len;
217         const uint64_t key_tbl_size = (uint64_t) key_entry_size * num_key_slots;
218
219         k = rte_zmalloc_socket(NULL, key_tbl_size,
220                         RTE_CACHE_LINE_SIZE, params->socket_id);
221
222         if (k == NULL) {
223                 RTE_LOG(ERR, HASH, "memory allocation failed\n");
224                 goto err_unlock;
225         }
226
227 /*
228  * If x86 architecture is used, select appropriate compare function,
229  * which may use x86 intrinsics, otherwise use memcmp
230  */
231 #if defined(RTE_ARCH_X86) || defined(RTE_ARCH_ARM64)
232         /* Select function to compare keys */
233         switch (params->key_len) {
234         case 16:
235                 h->cmp_jump_table_idx = KEY_16_BYTES;
236                 break;
237         case 32:
238                 h->cmp_jump_table_idx = KEY_32_BYTES;
239                 break;
240         case 48:
241                 h->cmp_jump_table_idx = KEY_48_BYTES;
242                 break;
243         case 64:
244                 h->cmp_jump_table_idx = KEY_64_BYTES;
245                 break;
246         case 80:
247                 h->cmp_jump_table_idx = KEY_80_BYTES;
248                 break;
249         case 96:
250                 h->cmp_jump_table_idx = KEY_96_BYTES;
251                 break;
252         case 112:
253                 h->cmp_jump_table_idx = KEY_112_BYTES;
254                 break;
255         case 128:
256                 h->cmp_jump_table_idx = KEY_128_BYTES;
257                 break;
258         default:
259                 /* If key is not multiple of 16, use generic memcmp */
260                 h->cmp_jump_table_idx = KEY_OTHER_BYTES;
261         }
262 #else
263         h->cmp_jump_table_idx = KEY_OTHER_BYTES;
264 #endif
265
266         if (hw_trans_mem_support) {
267                 h->local_free_slots = rte_zmalloc_socket(NULL,
268                                 sizeof(struct lcore_cache) * RTE_MAX_LCORE,
269                                 RTE_CACHE_LINE_SIZE, params->socket_id);
270         }
271
272         /* Setup hash context */
273         snprintf(h->name, sizeof(h->name), "%s", params->name);
274         h->entries = params->entries;
275         h->key_len = params->key_len;
276         h->key_entry_size = key_entry_size;
277         h->hash_func_init_val = params->hash_func_init_val;
278
279         h->num_buckets = num_buckets;
280         h->bucket_bitmask = h->num_buckets - 1;
281         h->buckets = buckets;
282         h->hash_func = (params->hash_func == NULL) ?
283                 DEFAULT_HASH_FUNC : params->hash_func;
284         h->key_store = k;
285         h->free_slots = r;
286         h->hw_trans_mem_support = hw_trans_mem_support;
287
288 #if defined(RTE_ARCH_X86)
289         if (rte_cpu_get_flag_enabled(RTE_CPUFLAG_AVX2))
290                 h->sig_cmp_fn = RTE_HASH_COMPARE_AVX2;
291         else if (rte_cpu_get_flag_enabled(RTE_CPUFLAG_SSE2))
292                 h->sig_cmp_fn = RTE_HASH_COMPARE_SSE;
293         else
294 #endif
295                 h->sig_cmp_fn = RTE_HASH_COMPARE_SCALAR;
296
297         /* Turn on multi-writer only with explicit flat from user and TM
298          * support.
299          */
300         if (params->extra_flag & RTE_HASH_EXTRA_FLAGS_MULTI_WRITER_ADD) {
301                 if (h->hw_trans_mem_support) {
302                         h->add_key = ADD_KEY_MULTIWRITER_TM;
303                 } else {
304                         h->add_key = ADD_KEY_MULTIWRITER;
305                         h->multiwriter_lock = rte_malloc(NULL,
306                                                         sizeof(rte_spinlock_t),
307                                                         LCORE_CACHE_SIZE);
308                         rte_spinlock_init(h->multiwriter_lock);
309                 }
310         } else
311                 h->add_key = ADD_KEY_SINGLEWRITER;
312
313         /* Populate free slots ring. Entry zero is reserved for key misses. */
314         for (i = 1; i < params->entries + 1; i++)
315                 rte_ring_sp_enqueue(r, (void *)((uintptr_t) i));
316
317         te->data = (void *) h;
318         TAILQ_INSERT_TAIL(hash_list, te, next);
319         rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
320
321         return h;
322 err_unlock:
323         rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
324 err:
325         rte_ring_free(r);
326         rte_free(te);
327         rte_free(h);
328         rte_free(buckets);
329         rte_free(k);
330         return NULL;
331 }
332
333 void
334 rte_hash_free(struct rte_hash *h)
335 {
336         struct rte_tailq_entry *te;
337         struct rte_hash_list *hash_list;
338
339         if (h == NULL)
340                 return;
341
342         hash_list = RTE_TAILQ_CAST(rte_hash_tailq.head, rte_hash_list);
343
344         rte_rwlock_write_lock(RTE_EAL_TAILQ_RWLOCK);
345
346         /* find out tailq entry */
347         TAILQ_FOREACH(te, hash_list, next) {
348                 if (te->data == (void *) h)
349                         break;
350         }
351
352         if (te == NULL) {
353                 rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
354                 return;
355         }
356
357         TAILQ_REMOVE(hash_list, te, next);
358
359         rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
360
361         if (h->hw_trans_mem_support)
362                 rte_free(h->local_free_slots);
363
364         if (h->add_key == ADD_KEY_MULTIWRITER)
365                 rte_free(h->multiwriter_lock);
366         rte_ring_free(h->free_slots);
367         rte_free(h->key_store);
368         rte_free(h->buckets);
369         rte_free(h);
370         rte_free(te);
371 }
372
373 hash_sig_t
374 rte_hash_hash(const struct rte_hash *h, const void *key)
375 {
376         /* calc hash result by key */
377         return h->hash_func(key, h->key_len, h->hash_func_init_val);
378 }
379
380 /* Calc the secondary hash value from the primary hash value of a given key */
381 static inline hash_sig_t
382 rte_hash_secondary_hash(const hash_sig_t primary_hash)
383 {
384         static const unsigned all_bits_shift = 12;
385         static const unsigned alt_bits_xor = 0x5bd1e995;
386
387         uint32_t tag = primary_hash >> all_bits_shift;
388
389         return primary_hash ^ ((tag + 1) * alt_bits_xor);
390 }
391
392 void
393 rte_hash_reset(struct rte_hash *h)
394 {
395         void *ptr;
396         unsigned i;
397
398         if (h == NULL)
399                 return;
400
401         memset(h->buckets, 0, h->num_buckets * sizeof(struct rte_hash_bucket));
402         memset(h->key_store, 0, h->key_entry_size * (h->entries + 1));
403
404         /* clear the free ring */
405         while (rte_ring_dequeue(h->free_slots, &ptr) == 0)
406                 rte_pause();
407
408         /* Repopulate the free slots ring. Entry zero is reserved for key misses */
409         for (i = 1; i < h->entries + 1; i++)
410                 rte_ring_sp_enqueue(h->free_slots, (void *)((uintptr_t) i));
411
412         if (h->hw_trans_mem_support) {
413                 /* Reset local caches per lcore */
414                 for (i = 0; i < RTE_MAX_LCORE; i++)
415                         h->local_free_slots[i].len = 0;
416         }
417 }
418
419 /* Search for an entry that can be pushed to its alternative location */
420 static inline int
421 make_space_bucket(const struct rte_hash *h, struct rte_hash_bucket *bkt)
422 {
423         static unsigned int nr_pushes;
424         unsigned i, j;
425         int ret;
426         uint32_t next_bucket_idx;
427         struct rte_hash_bucket *next_bkt[RTE_HASH_BUCKET_ENTRIES];
428
429         /*
430          * Push existing item (search for bucket with space in
431          * alternative locations) to its alternative location
432          */
433         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
434                 /* Search for space in alternative locations */
435                 next_bucket_idx = bkt->sig_alt[i] & h->bucket_bitmask;
436                 next_bkt[i] = &h->buckets[next_bucket_idx];
437                 for (j = 0; j < RTE_HASH_BUCKET_ENTRIES; j++) {
438                         if (next_bkt[i]->key_idx[j] == EMPTY_SLOT)
439                                 break;
440                 }
441
442                 if (j != RTE_HASH_BUCKET_ENTRIES)
443                         break;
444         }
445
446         /* Alternative location has spare room (end of recursive function) */
447         if (i != RTE_HASH_BUCKET_ENTRIES) {
448                 next_bkt[i]->sig_alt[j] = bkt->sig_current[i];
449                 next_bkt[i]->sig_current[j] = bkt->sig_alt[i];
450                 next_bkt[i]->key_idx[j] = bkt->key_idx[i];
451                 return i;
452         }
453
454         /* Pick entry that has not been pushed yet */
455         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++)
456                 if (bkt->flag[i] == 0)
457                         break;
458
459         /* All entries have been pushed, so entry cannot be added */
460         if (i == RTE_HASH_BUCKET_ENTRIES || nr_pushes > RTE_HASH_MAX_PUSHES)
461                 return -ENOSPC;
462
463         /* Set flag to indicate that this entry is going to be pushed */
464         bkt->flag[i] = 1;
465
466         nr_pushes++;
467         /* Need room in alternative bucket to insert the pushed entry */
468         ret = make_space_bucket(h, next_bkt[i]);
469         /*
470          * After recursive function.
471          * Clear flags and insert the pushed entry
472          * in its alternative location if successful,
473          * or return error
474          */
475         bkt->flag[i] = 0;
476         nr_pushes = 0;
477         if (ret >= 0) {
478                 next_bkt[i]->sig_alt[ret] = bkt->sig_current[i];
479                 next_bkt[i]->sig_current[ret] = bkt->sig_alt[i];
480                 next_bkt[i]->key_idx[ret] = bkt->key_idx[i];
481                 return i;
482         } else
483                 return ret;
484
485 }
486
487 /*
488  * Function called to enqueue back an index in the cache/ring,
489  * as slot has not being used and it can be used in the
490  * next addition attempt.
491  */
492 static inline void
493 enqueue_slot_back(const struct rte_hash *h,
494                 struct lcore_cache *cached_free_slots,
495                 void *slot_id)
496 {
497         if (h->hw_trans_mem_support) {
498                 cached_free_slots->objs[cached_free_slots->len] = slot_id;
499                 cached_free_slots->len++;
500         } else
501                 rte_ring_sp_enqueue(h->free_slots, slot_id);
502 }
503
504 static inline int32_t
505 __rte_hash_add_key_with_hash(const struct rte_hash *h, const void *key,
506                                                 hash_sig_t sig, void *data)
507 {
508         hash_sig_t alt_hash;
509         uint32_t prim_bucket_idx, sec_bucket_idx;
510         unsigned i;
511         struct rte_hash_bucket *prim_bkt, *sec_bkt;
512         struct rte_hash_key *new_k, *k, *keys = h->key_store;
513         void *slot_id = NULL;
514         uint32_t new_idx;
515         int ret;
516         unsigned n_slots;
517         unsigned lcore_id;
518         struct lcore_cache *cached_free_slots = NULL;
519
520         if (h->add_key == ADD_KEY_MULTIWRITER)
521                 rte_spinlock_lock(h->multiwriter_lock);
522
523         prim_bucket_idx = sig & h->bucket_bitmask;
524         prim_bkt = &h->buckets[prim_bucket_idx];
525         rte_prefetch0(prim_bkt);
526
527         alt_hash = rte_hash_secondary_hash(sig);
528         sec_bucket_idx = alt_hash & h->bucket_bitmask;
529         sec_bkt = &h->buckets[sec_bucket_idx];
530         rte_prefetch0(sec_bkt);
531
532         /* Get a new slot for storing the new key */
533         if (h->hw_trans_mem_support) {
534                 lcore_id = rte_lcore_id();
535                 cached_free_slots = &h->local_free_slots[lcore_id];
536                 /* Try to get a free slot from the local cache */
537                 if (cached_free_slots->len == 0) {
538                         /* Need to get another burst of free slots from global ring */
539                         n_slots = rte_ring_mc_dequeue_burst(h->free_slots,
540                                         cached_free_slots->objs,
541                                         LCORE_CACHE_SIZE, NULL);
542                         if (n_slots == 0) {
543                                 ret = -ENOSPC;
544                                 goto failure;
545                         }
546
547                         cached_free_slots->len += n_slots;
548                 }
549
550                 /* Get a free slot from the local cache */
551                 cached_free_slots->len--;
552                 slot_id = cached_free_slots->objs[cached_free_slots->len];
553         } else {
554                 if (rte_ring_sc_dequeue(h->free_slots, &slot_id) != 0) {
555                         ret = -ENOSPC;
556                         goto failure;
557                 }
558         }
559
560         new_k = RTE_PTR_ADD(keys, (uintptr_t)slot_id * h->key_entry_size);
561         rte_prefetch0(new_k);
562         new_idx = (uint32_t)((uintptr_t) slot_id);
563
564         /* Check if key is already inserted in primary location */
565         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
566                 if (prim_bkt->sig_current[i] == sig &&
567                                 prim_bkt->sig_alt[i] == alt_hash) {
568                         k = (struct rte_hash_key *) ((char *)keys +
569                                         prim_bkt->key_idx[i] * h->key_entry_size);
570                         if (rte_hash_cmp_eq(key, k->key, h) == 0) {
571                                 /* Enqueue index of free slot back in the ring. */
572                                 enqueue_slot_back(h, cached_free_slots, slot_id);
573                                 /* Update data */
574                                 k->pdata = data;
575                                 /*
576                                  * Return index where key is stored,
577                                  * subtracting the first dummy index
578                                  */
579                                 return prim_bkt->key_idx[i] - 1;
580                         }
581                 }
582         }
583
584         /* Check if key is already inserted in secondary location */
585         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
586                 if (sec_bkt->sig_alt[i] == sig &&
587                                 sec_bkt->sig_current[i] == alt_hash) {
588                         k = (struct rte_hash_key *) ((char *)keys +
589                                         sec_bkt->key_idx[i] * h->key_entry_size);
590                         if (rte_hash_cmp_eq(key, k->key, h) == 0) {
591                                 /* Enqueue index of free slot back in the ring. */
592                                 enqueue_slot_back(h, cached_free_slots, slot_id);
593                                 /* Update data */
594                                 k->pdata = data;
595                                 /*
596                                  * Return index where key is stored,
597                                  * subtracting the first dummy index
598                                  */
599                                 return sec_bkt->key_idx[i] - 1;
600                         }
601                 }
602         }
603
604         /* Copy key */
605         rte_memcpy(new_k->key, key, h->key_len);
606         new_k->pdata = data;
607
608 #if defined(RTE_ARCH_X86) /* currently only x86 support HTM */
609         if (h->add_key == ADD_KEY_MULTIWRITER_TM) {
610                 ret = rte_hash_cuckoo_insert_mw_tm(prim_bkt,
611                                 sig, alt_hash, new_idx);
612                 if (ret >= 0)
613                         return new_idx - 1;
614
615                 /* Primary bucket full, need to make space for new entry */
616                 ret = rte_hash_cuckoo_make_space_mw_tm(h, prim_bkt, sig,
617                                                         alt_hash, new_idx);
618
619                 if (ret >= 0)
620                         return new_idx - 1;
621
622                 /* Also search secondary bucket to get better occupancy */
623                 ret = rte_hash_cuckoo_make_space_mw_tm(h, sec_bkt, sig,
624                                                         alt_hash, new_idx);
625
626                 if (ret >= 0)
627                         return new_idx - 1;
628         } else {
629 #endif
630                 for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
631                         /* Check if slot is available */
632                         if (likely(prim_bkt->key_idx[i] == EMPTY_SLOT)) {
633                                 prim_bkt->sig_current[i] = sig;
634                                 prim_bkt->sig_alt[i] = alt_hash;
635                                 prim_bkt->key_idx[i] = new_idx;
636                                 break;
637                         }
638                 }
639
640                 if (i != RTE_HASH_BUCKET_ENTRIES) {
641                         if (h->add_key == ADD_KEY_MULTIWRITER)
642                                 rte_spinlock_unlock(h->multiwriter_lock);
643                         return new_idx - 1;
644                 }
645
646                 /* Primary bucket full, need to make space for new entry
647                  * After recursive function.
648                  * Insert the new entry in the position of the pushed entry
649                  * if successful or return error and
650                  * store the new slot back in the ring
651                  */
652                 ret = make_space_bucket(h, prim_bkt);
653                 if (ret >= 0) {
654                         prim_bkt->sig_current[ret] = sig;
655                         prim_bkt->sig_alt[ret] = alt_hash;
656                         prim_bkt->key_idx[ret] = new_idx;
657                         if (h->add_key == ADD_KEY_MULTIWRITER)
658                                 rte_spinlock_unlock(h->multiwriter_lock);
659                         return new_idx - 1;
660                 }
661 #if defined(RTE_ARCH_X86)
662         }
663 #endif
664         /* Error in addition, store new slot back in the ring and return error */
665         enqueue_slot_back(h, cached_free_slots, (void *)((uintptr_t) new_idx));
666
667 failure:
668         if (h->add_key == ADD_KEY_MULTIWRITER)
669                 rte_spinlock_unlock(h->multiwriter_lock);
670         return ret;
671 }
672
673 int32_t
674 rte_hash_add_key_with_hash(const struct rte_hash *h,
675                         const void *key, hash_sig_t sig)
676 {
677         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
678         return __rte_hash_add_key_with_hash(h, key, sig, 0);
679 }
680
681 int32_t
682 rte_hash_add_key(const struct rte_hash *h, const void *key)
683 {
684         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
685         return __rte_hash_add_key_with_hash(h, key, rte_hash_hash(h, key), 0);
686 }
687
688 int
689 rte_hash_add_key_with_hash_data(const struct rte_hash *h,
690                         const void *key, hash_sig_t sig, void *data)
691 {
692         int ret;
693
694         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
695         ret = __rte_hash_add_key_with_hash(h, key, sig, data);
696         if (ret >= 0)
697                 return 0;
698         else
699                 return ret;
700 }
701
702 int
703 rte_hash_add_key_data(const struct rte_hash *h, const void *key, void *data)
704 {
705         int ret;
706
707         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
708
709         ret = __rte_hash_add_key_with_hash(h, key, rte_hash_hash(h, key), data);
710         if (ret >= 0)
711                 return 0;
712         else
713                 return ret;
714 }
715 static inline int32_t
716 __rte_hash_lookup_with_hash(const struct rte_hash *h, const void *key,
717                                         hash_sig_t sig, void **data)
718 {
719         uint32_t bucket_idx;
720         hash_sig_t alt_hash;
721         unsigned i;
722         struct rte_hash_bucket *bkt;
723         struct rte_hash_key *k, *keys = h->key_store;
724
725         bucket_idx = sig & h->bucket_bitmask;
726         bkt = &h->buckets[bucket_idx];
727
728         /* Check if key is in primary location */
729         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
730                 if (bkt->sig_current[i] == sig &&
731                                 bkt->key_idx[i] != EMPTY_SLOT) {
732                         k = (struct rte_hash_key *) ((char *)keys +
733                                         bkt->key_idx[i] * h->key_entry_size);
734                         if (rte_hash_cmp_eq(key, k->key, h) == 0) {
735                                 if (data != NULL)
736                                         *data = k->pdata;
737                                 /*
738                                  * Return index where key is stored,
739                                  * subtracting the first dummy index
740                                  */
741                                 return bkt->key_idx[i] - 1;
742                         }
743                 }
744         }
745
746         /* Calculate secondary hash */
747         alt_hash = rte_hash_secondary_hash(sig);
748         bucket_idx = alt_hash & h->bucket_bitmask;
749         bkt = &h->buckets[bucket_idx];
750
751         /* Check if key is in secondary location */
752         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
753                 if (bkt->sig_current[i] == alt_hash &&
754                                 bkt->sig_alt[i] == sig) {
755                         k = (struct rte_hash_key *) ((char *)keys +
756                                         bkt->key_idx[i] * h->key_entry_size);
757                         if (rte_hash_cmp_eq(key, k->key, h) == 0) {
758                                 if (data != NULL)
759                                         *data = k->pdata;
760                                 /*
761                                  * Return index where key is stored,
762                                  * subtracting the first dummy index
763                                  */
764                                 return bkt->key_idx[i] - 1;
765                         }
766                 }
767         }
768
769         return -ENOENT;
770 }
771
772 int32_t
773 rte_hash_lookup_with_hash(const struct rte_hash *h,
774                         const void *key, hash_sig_t sig)
775 {
776         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
777         return __rte_hash_lookup_with_hash(h, key, sig, NULL);
778 }
779
780 int32_t
781 rte_hash_lookup(const struct rte_hash *h, const void *key)
782 {
783         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
784         return __rte_hash_lookup_with_hash(h, key, rte_hash_hash(h, key), NULL);
785 }
786
787 int
788 rte_hash_lookup_with_hash_data(const struct rte_hash *h,
789                         const void *key, hash_sig_t sig, void **data)
790 {
791         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
792         return __rte_hash_lookup_with_hash(h, key, sig, data);
793 }
794
795 int
796 rte_hash_lookup_data(const struct rte_hash *h, const void *key, void **data)
797 {
798         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
799         return __rte_hash_lookup_with_hash(h, key, rte_hash_hash(h, key), data);
800 }
801
802 static inline void
803 remove_entry(const struct rte_hash *h, struct rte_hash_bucket *bkt, unsigned i)
804 {
805         unsigned lcore_id, n_slots;
806         struct lcore_cache *cached_free_slots;
807
808         bkt->sig_current[i] = NULL_SIGNATURE;
809         bkt->sig_alt[i] = NULL_SIGNATURE;
810         if (h->hw_trans_mem_support) {
811                 lcore_id = rte_lcore_id();
812                 cached_free_slots = &h->local_free_slots[lcore_id];
813                 /* Cache full, need to free it. */
814                 if (cached_free_slots->len == LCORE_CACHE_SIZE) {
815                         /* Need to enqueue the free slots in global ring. */
816                         n_slots = rte_ring_mp_enqueue_burst(h->free_slots,
817                                                 cached_free_slots->objs,
818                                                 LCORE_CACHE_SIZE, NULL);
819                         cached_free_slots->len -= n_slots;
820                 }
821                 /* Put index of new free slot in cache. */
822                 cached_free_slots->objs[cached_free_slots->len] =
823                                 (void *)((uintptr_t)bkt->key_idx[i]);
824                 cached_free_slots->len++;
825         } else {
826                 rte_ring_sp_enqueue(h->free_slots,
827                                 (void *)((uintptr_t)bkt->key_idx[i]));
828         }
829 }
830
831 static inline int32_t
832 __rte_hash_del_key_with_hash(const struct rte_hash *h, const void *key,
833                                                 hash_sig_t sig)
834 {
835         uint32_t bucket_idx;
836         hash_sig_t alt_hash;
837         unsigned i;
838         struct rte_hash_bucket *bkt;
839         struct rte_hash_key *k, *keys = h->key_store;
840         int32_t ret;
841
842         bucket_idx = sig & h->bucket_bitmask;
843         bkt = &h->buckets[bucket_idx];
844
845         /* Check if key is in primary location */
846         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
847                 if (bkt->sig_current[i] == sig &&
848                                 bkt->key_idx[i] != EMPTY_SLOT) {
849                         k = (struct rte_hash_key *) ((char *)keys +
850                                         bkt->key_idx[i] * h->key_entry_size);
851                         if (rte_hash_cmp_eq(key, k->key, h) == 0) {
852                                 remove_entry(h, bkt, i);
853
854                                 /*
855                                  * Return index where key is stored,
856                                  * subtracting the first dummy index
857                                  */
858                                 ret = bkt->key_idx[i] - 1;
859                                 bkt->key_idx[i] = EMPTY_SLOT;
860                                 return ret;
861                         }
862                 }
863         }
864
865         /* Calculate secondary hash */
866         alt_hash = rte_hash_secondary_hash(sig);
867         bucket_idx = alt_hash & h->bucket_bitmask;
868         bkt = &h->buckets[bucket_idx];
869
870         /* Check if key is in secondary location */
871         for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
872                 if (bkt->sig_current[i] == alt_hash &&
873                                 bkt->key_idx[i] != EMPTY_SLOT) {
874                         k = (struct rte_hash_key *) ((char *)keys +
875                                         bkt->key_idx[i] * h->key_entry_size);
876                         if (rte_hash_cmp_eq(key, k->key, h) == 0) {
877                                 remove_entry(h, bkt, i);
878
879                                 /*
880                                  * Return index where key is stored,
881                                  * subtracting the first dummy index
882                                  */
883                                 ret = bkt->key_idx[i] - 1;
884                                 bkt->key_idx[i] = EMPTY_SLOT;
885                                 return ret;
886                         }
887                 }
888         }
889
890         return -ENOENT;
891 }
892
893 int32_t
894 rte_hash_del_key_with_hash(const struct rte_hash *h,
895                         const void *key, hash_sig_t sig)
896 {
897         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
898         return __rte_hash_del_key_with_hash(h, key, sig);
899 }
900
901 int32_t
902 rte_hash_del_key(const struct rte_hash *h, const void *key)
903 {
904         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
905         return __rte_hash_del_key_with_hash(h, key, rte_hash_hash(h, key));
906 }
907
908 int
909 rte_hash_get_key_with_position(const struct rte_hash *h, const int32_t position,
910                                void **key)
911 {
912         RETURN_IF_TRUE(((h == NULL) || (key == NULL)), -EINVAL);
913
914         struct rte_hash_key *k, *keys = h->key_store;
915         k = (struct rte_hash_key *) ((char *) keys + (position + 1) *
916                                      h->key_entry_size);
917         *key = k->key;
918
919         if (position !=
920             __rte_hash_lookup_with_hash(h, *key, rte_hash_hash(h, *key),
921                                         NULL)) {
922                 return -ENOENT;
923         }
924
925         return 0;
926 }
927
928 static inline void
929 compare_signatures(uint32_t *prim_hash_matches, uint32_t *sec_hash_matches,
930                         const struct rte_hash_bucket *prim_bkt,
931                         const struct rte_hash_bucket *sec_bkt,
932                         hash_sig_t prim_hash, hash_sig_t sec_hash,
933                         enum rte_hash_sig_compare_function sig_cmp_fn)
934 {
935         unsigned int i;
936
937         switch (sig_cmp_fn) {
938 #ifdef RTE_MACHINE_CPUFLAG_AVX2
939         case RTE_HASH_COMPARE_AVX2:
940                 *prim_hash_matches = _mm256_movemask_ps((__m256)_mm256_cmpeq_epi32(
941                                 _mm256_load_si256(
942                                         (__m256i const *)prim_bkt->sig_current),
943                                 _mm256_set1_epi32(prim_hash)));
944                 *sec_hash_matches = _mm256_movemask_ps((__m256)_mm256_cmpeq_epi32(
945                                 _mm256_load_si256(
946                                         (__m256i const *)sec_bkt->sig_current),
947                                 _mm256_set1_epi32(sec_hash)));
948                 break;
949 #endif
950 #ifdef RTE_MACHINE_CPUFLAG_SSE2
951         case RTE_HASH_COMPARE_SSE:
952                 /* Compare the first 4 signatures in the bucket */
953                 *prim_hash_matches = _mm_movemask_ps((__m128)_mm_cmpeq_epi16(
954                                 _mm_load_si128(
955                                         (__m128i const *)prim_bkt->sig_current),
956                                 _mm_set1_epi32(prim_hash)));
957                 *prim_hash_matches |= (_mm_movemask_ps((__m128)_mm_cmpeq_epi16(
958                                 _mm_load_si128(
959                                         (__m128i const *)&prim_bkt->sig_current[4]),
960                                 _mm_set1_epi32(prim_hash)))) << 4;
961                 /* Compare the first 4 signatures in the bucket */
962                 *sec_hash_matches = _mm_movemask_ps((__m128)_mm_cmpeq_epi16(
963                                 _mm_load_si128(
964                                         (__m128i const *)sec_bkt->sig_current),
965                                 _mm_set1_epi32(sec_hash)));
966                 *sec_hash_matches |= (_mm_movemask_ps((__m128)_mm_cmpeq_epi16(
967                                 _mm_load_si128(
968                                         (__m128i const *)&sec_bkt->sig_current[4]),
969                                 _mm_set1_epi32(sec_hash)))) << 4;
970                 break;
971 #endif
972         default:
973                 for (i = 0; i < RTE_HASH_BUCKET_ENTRIES; i++) {
974                         *prim_hash_matches |=
975                                 ((prim_hash == prim_bkt->sig_current[i]) << i);
976                         *sec_hash_matches |=
977                                 ((sec_hash == sec_bkt->sig_current[i]) << i);
978                 }
979         }
980
981 }
982
983 #define PREFETCH_OFFSET 4
984 static inline void
985 __rte_hash_lookup_bulk(const struct rte_hash *h, const void **keys,
986                         int32_t num_keys, int32_t *positions,
987                         uint64_t *hit_mask, void *data[])
988 {
989         uint64_t hits = 0;
990         int32_t i;
991         uint32_t prim_hash[RTE_HASH_LOOKUP_BULK_MAX];
992         uint32_t sec_hash[RTE_HASH_LOOKUP_BULK_MAX];
993         const struct rte_hash_bucket *primary_bkt[RTE_HASH_LOOKUP_BULK_MAX];
994         const struct rte_hash_bucket *secondary_bkt[RTE_HASH_LOOKUP_BULK_MAX];
995         uint32_t prim_hitmask[RTE_HASH_LOOKUP_BULK_MAX] = {0};
996         uint32_t sec_hitmask[RTE_HASH_LOOKUP_BULK_MAX] = {0};
997
998         /* Prefetch first keys */
999         for (i = 0; i < PREFETCH_OFFSET && i < num_keys; i++)
1000                 rte_prefetch0(keys[i]);
1001
1002         /*
1003          * Prefetch rest of the keys, calculate primary and
1004          * secondary bucket and prefetch them
1005          */
1006         for (i = 0; i < (num_keys - PREFETCH_OFFSET); i++) {
1007                 rte_prefetch0(keys[i + PREFETCH_OFFSET]);
1008
1009                 prim_hash[i] = rte_hash_hash(h, keys[i]);
1010                 sec_hash[i] = rte_hash_secondary_hash(prim_hash[i]);
1011
1012                 primary_bkt[i] = &h->buckets[prim_hash[i] & h->bucket_bitmask];
1013                 secondary_bkt[i] = &h->buckets[sec_hash[i] & h->bucket_bitmask];
1014
1015                 rte_prefetch0(primary_bkt[i]);
1016                 rte_prefetch0(secondary_bkt[i]);
1017         }
1018
1019         /* Calculate and prefetch rest of the buckets */
1020         for (; i < num_keys; i++) {
1021                 prim_hash[i] = rte_hash_hash(h, keys[i]);
1022                 sec_hash[i] = rte_hash_secondary_hash(prim_hash[i]);
1023
1024                 primary_bkt[i] = &h->buckets[prim_hash[i] & h->bucket_bitmask];
1025                 secondary_bkt[i] = &h->buckets[sec_hash[i] & h->bucket_bitmask];
1026
1027                 rte_prefetch0(primary_bkt[i]);
1028                 rte_prefetch0(secondary_bkt[i]);
1029         }
1030
1031         /* Compare signatures and prefetch key slot of first hit */
1032         for (i = 0; i < num_keys; i++) {
1033                 compare_signatures(&prim_hitmask[i], &sec_hitmask[i],
1034                                 primary_bkt[i], secondary_bkt[i],
1035                                 prim_hash[i], sec_hash[i], h->sig_cmp_fn);
1036
1037                 if (prim_hitmask[i]) {
1038                         uint32_t first_hit = __builtin_ctzl(prim_hitmask[i]);
1039                         uint32_t key_idx = primary_bkt[i]->key_idx[first_hit];
1040                         const struct rte_hash_key *key_slot =
1041                                 (const struct rte_hash_key *)(
1042                                 (const char *)h->key_store +
1043                                 key_idx * h->key_entry_size);
1044                         rte_prefetch0(key_slot);
1045                         continue;
1046                 }
1047
1048                 if (sec_hitmask[i]) {
1049                         uint32_t first_hit = __builtin_ctzl(sec_hitmask[i]);
1050                         uint32_t key_idx = secondary_bkt[i]->key_idx[first_hit];
1051                         const struct rte_hash_key *key_slot =
1052                                 (const struct rte_hash_key *)(
1053                                 (const char *)h->key_store +
1054                                 key_idx * h->key_entry_size);
1055                         rte_prefetch0(key_slot);
1056                 }
1057         }
1058
1059         /* Compare keys, first hits in primary first */
1060         for (i = 0; i < num_keys; i++) {
1061                 positions[i] = -ENOENT;
1062                 while (prim_hitmask[i]) {
1063                         uint32_t hit_index = __builtin_ctzl(prim_hitmask[i]);
1064
1065                         uint32_t key_idx = primary_bkt[i]->key_idx[hit_index];
1066                         const struct rte_hash_key *key_slot =
1067                                 (const struct rte_hash_key *)(
1068                                 (const char *)h->key_store +
1069                                 key_idx * h->key_entry_size);
1070                         /*
1071                          * If key index is 0, do not compare key,
1072                          * as it is checking the dummy slot
1073                          */
1074                         if (!!key_idx & !rte_hash_cmp_eq(key_slot->key, keys[i], h)) {
1075                                 if (data != NULL)
1076                                         data[i] = key_slot->pdata;
1077
1078                                 hits |= 1ULL << i;
1079                                 positions[i] = key_idx - 1;
1080                                 goto next_key;
1081                         }
1082                         prim_hitmask[i] &= ~(1 << (hit_index));
1083                 }
1084
1085                 while (sec_hitmask[i]) {
1086                         uint32_t hit_index = __builtin_ctzl(sec_hitmask[i]);
1087
1088                         uint32_t key_idx = secondary_bkt[i]->key_idx[hit_index];
1089                         const struct rte_hash_key *key_slot =
1090                                 (const struct rte_hash_key *)(
1091                                 (const char *)h->key_store +
1092                                 key_idx * h->key_entry_size);
1093                         /*
1094                          * If key index is 0, do not compare key,
1095                          * as it is checking the dummy slot
1096                          */
1097
1098                         if (!!key_idx & !rte_hash_cmp_eq(key_slot->key, keys[i], h)) {
1099                                 if (data != NULL)
1100                                         data[i] = key_slot->pdata;
1101
1102                                 hits |= 1ULL << i;
1103                                 positions[i] = key_idx - 1;
1104                                 goto next_key;
1105                         }
1106                         sec_hitmask[i] &= ~(1 << (hit_index));
1107                 }
1108
1109 next_key:
1110                 continue;
1111         }
1112
1113         if (hit_mask != NULL)
1114                 *hit_mask = hits;
1115 }
1116
1117 int
1118 rte_hash_lookup_bulk(const struct rte_hash *h, const void **keys,
1119                       uint32_t num_keys, int32_t *positions)
1120 {
1121         RETURN_IF_TRUE(((h == NULL) || (keys == NULL) || (num_keys == 0) ||
1122                         (num_keys > RTE_HASH_LOOKUP_BULK_MAX) ||
1123                         (positions == NULL)), -EINVAL);
1124
1125         __rte_hash_lookup_bulk(h, keys, num_keys, positions, NULL, NULL);
1126         return 0;
1127 }
1128
1129 int
1130 rte_hash_lookup_bulk_data(const struct rte_hash *h, const void **keys,
1131                       uint32_t num_keys, uint64_t *hit_mask, void *data[])
1132 {
1133         RETURN_IF_TRUE(((h == NULL) || (keys == NULL) || (num_keys == 0) ||
1134                         (num_keys > RTE_HASH_LOOKUP_BULK_MAX) ||
1135                         (hit_mask == NULL)), -EINVAL);
1136
1137         int32_t positions[num_keys];
1138
1139         __rte_hash_lookup_bulk(h, keys, num_keys, positions, hit_mask, data);
1140
1141         /* Return number of hits */
1142         return __builtin_popcountl(*hit_mask);
1143 }
1144
1145 int32_t
1146 rte_hash_iterate(const struct rte_hash *h, const void **key, void **data, uint32_t *next)
1147 {
1148         uint32_t bucket_idx, idx, position;
1149         struct rte_hash_key *next_key;
1150
1151         RETURN_IF_TRUE(((h == NULL) || (next == NULL)), -EINVAL);
1152
1153         const uint32_t total_entries = h->num_buckets * RTE_HASH_BUCKET_ENTRIES;
1154         /* Out of bounds */
1155         if (*next >= total_entries)
1156                 return -ENOENT;
1157
1158         /* Calculate bucket and index of current iterator */
1159         bucket_idx = *next / RTE_HASH_BUCKET_ENTRIES;
1160         idx = *next % RTE_HASH_BUCKET_ENTRIES;
1161
1162         /* If current position is empty, go to the next one */
1163         while (h->buckets[bucket_idx].key_idx[idx] == EMPTY_SLOT) {
1164                 (*next)++;
1165                 /* End of table */
1166                 if (*next == total_entries)
1167                         return -ENOENT;
1168                 bucket_idx = *next / RTE_HASH_BUCKET_ENTRIES;
1169                 idx = *next % RTE_HASH_BUCKET_ENTRIES;
1170         }
1171
1172         /* Get position of entry in key table */
1173         position = h->buckets[bucket_idx].key_idx[idx];
1174         next_key = (struct rte_hash_key *) ((char *)h->key_store +
1175                                 position * h->key_entry_size);
1176         /* Return key and data */
1177         *key = next_key->key;
1178         *data = next_key->pdata;
1179
1180         /* Increment iterator */
1181         (*next)++;
1182
1183         return position - 1;
1184 }