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