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