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