89bfc8b6b56acc675f369e55e837a8d8c07c998d
[vpp.git] / src / vppinfra / bihash_template.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 /** @cond DOCUMENTATION_IS_IN_BIHASH_DOC_H */
17
18 #ifndef MAP_HUGE_SHIFT
19 #define MAP_HUGE_SHIFT 26
20 #endif
21
22 static inline void *BV (alloc_aligned) (BVT (clib_bihash) * h, uword nbytes)
23 {
24   uword rv;
25
26   /* Round to an even number of cache lines */
27   nbytes += CLIB_CACHE_LINE_BYTES - 1;
28   nbytes &= ~(CLIB_CACHE_LINE_BYTES - 1);
29
30   rv = alloc_arena_next (h);
31   alloc_arena_next (h) += nbytes;
32
33   if (alloc_arena_next (h) > alloc_arena_size (h))
34     os_out_of_memory ();
35
36   if (alloc_arena_next (h) > alloc_arena_mapped (h))
37     {
38       void *base, *rv;
39       uword alloc = alloc_arena_next (h) - alloc_arena_mapped (h);
40       int mmap_flags = MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS;
41       int mmap_flags_huge = (mmap_flags | MAP_HUGETLB |
42                              BIHASH_LOG2_HUGEPAGE_SIZE << MAP_HUGE_SHIFT);
43
44       /* new allocation is 25% of existing one */
45       if (alloc_arena_mapped (h) >> 2 > alloc)
46         alloc = alloc_arena_mapped (h) >> 2;
47
48       /* round allocation to page size */
49       alloc = round_pow2 (alloc, 1 << BIHASH_LOG2_HUGEPAGE_SIZE);
50
51       base = (void *) (uword) (alloc_arena (h) + alloc_arena_mapped (h));
52
53       rv = mmap (base, alloc, PROT_READ | PROT_WRITE, mmap_flags_huge, -1, 0);
54
55       /* fallback - maybe we are still able to allocate normal pages */
56       if (rv == MAP_FAILED)
57         rv = mmap (base, alloc, PROT_READ | PROT_WRITE, mmap_flags, -1, 0);
58
59       if (rv == MAP_FAILED)
60         os_out_of_memory ();
61
62       alloc_arena_mapped (h) += alloc;
63     }
64
65   return (void *) (uword) (rv + alloc_arena (h));
66 }
67
68 static void BV (clib_bihash_instantiate) (BVT (clib_bihash) * h)
69 {
70   uword bucket_size;
71
72   alloc_arena (h) = clib_mem_vm_reserve (0, h->memory_size,
73                                          BIHASH_LOG2_HUGEPAGE_SIZE);
74   if (alloc_arena (h) == ~0)
75     os_out_of_memory ();
76   alloc_arena_next (h) = 0;
77   alloc_arena_size (h) = h->memory_size;
78   alloc_arena_mapped (h) = 0;
79
80   bucket_size = h->nbuckets * sizeof (h->buckets[0]);
81
82   if (BIHASH_KVP_AT_BUCKET_LEVEL)
83     bucket_size +=
84       h->nbuckets * BIHASH_KVP_PER_PAGE * sizeof (BVT (clib_bihash_kv));
85
86   h->buckets = BV (alloc_aligned) (h, bucket_size);
87
88   if (BIHASH_KVP_AT_BUCKET_LEVEL)
89     {
90       int i;
91       BVT (clib_bihash_bucket) * b;
92
93       b = h->buckets;
94
95       for (i = 0; i < h->nbuckets; i++)
96         {
97           b->offset = BV (clib_bihash_get_offset) (h, (void *) (b + 1));
98           b->refcnt = 1;
99           /* Mark all elements free */
100           clib_memset ((b + 1), 0xff,
101                        BIHASH_KVP_PER_PAGE * sizeof (BVT (clib_bihash_kv)));
102
103           /* Compute next bucket start address */
104           b = (void *) (((uword) b) + sizeof (*b) +
105                         (BIHASH_KVP_PER_PAGE *
106                          sizeof (BVT (clib_bihash_kv))));
107         }
108     }
109   CLIB_MEMORY_BARRIER ();
110   h->instantiated = 1;
111 }
112
113 void BV (clib_bihash_init2) (BVT (clib_bihash_init2_args) * a)
114 {
115   int i;
116   void *oldheap;
117   BVT (clib_bihash) * h = a->h;
118
119   a->nbuckets = 1 << (max_log2 (a->nbuckets));
120
121   h->name = (u8 *) a->name;
122   h->nbuckets = a->nbuckets;
123   h->log2_nbuckets = max_log2 (a->nbuckets);
124   h->memory_size = a->memory_size;
125   h->instantiated = 0;
126   h->fmt_fn = a->fmt_fn;
127
128   alloc_arena (h) = 0;
129
130   /*
131    * Make sure the requested size is rational. The max table
132    * size without playing the alignment card is 64 Gbytes.
133    * If someone starts complaining that's not enough, we can shift
134    * the offset by CLIB_LOG2_CACHE_LINE_BYTES...
135    */
136   ASSERT (h->memory_size < (1ULL << BIHASH_BUCKET_OFFSET_BITS));
137
138   /* Add this hash table to the list */
139   if (a->dont_add_to_all_bihash_list == 0)
140     {
141       for (i = 0; i < vec_len (clib_all_bihashes); i++)
142         if (clib_all_bihashes[i] == h)
143           goto do_lock;
144       oldheap = clib_all_bihash_set_heap ();
145       vec_add1 (clib_all_bihashes, (void *) h);
146       clib_mem_set_heap (oldheap);
147     }
148
149 do_lock:
150   if (h->alloc_lock)
151     clib_mem_free ((void *) h->alloc_lock);
152
153   /*
154    * Set up the lock now, so we can use it to make the first add
155    * thread-safe
156    */
157   h->alloc_lock = clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES,
158                                           CLIB_CACHE_LINE_BYTES);
159   h->alloc_lock[0] = 0;
160
161 #if BIHASH_LAZY_INSTANTIATE
162   if (a->instantiate_immediately)
163 #endif
164     BV (clib_bihash_instantiate) (h);
165 }
166
167 void BV (clib_bihash_init)
168   (BVT (clib_bihash) * h, char *name, u32 nbuckets, uword memory_size)
169 {
170   BVT (clib_bihash_init2_args) _a, *a = &_a;
171
172   memset (a, 0, sizeof (*a));
173
174   a->h = h;
175   a->name = name;
176   a->nbuckets = nbuckets;
177   a->memory_size = memory_size;
178
179   BV (clib_bihash_init2) (a);
180 }
181
182 #if BIHASH_32_64_SVM
183 #if !defined (MFD_ALLOW_SEALING)
184 #define MFD_ALLOW_SEALING 0x0002U
185 #endif
186
187 void BV (clib_bihash_master_init_svm)
188   (BVT (clib_bihash) * h, char *name, u32 nbuckets, u64 memory_size)
189 {
190   uword bucket_size;
191   u8 *mmap_addr;
192   vec_header_t *freelist_vh;
193   int fd;
194
195   ASSERT (memory_size < (1ULL << 32));
196   /* Set up for memfd sharing */
197   if ((fd = memfd_create (name, MFD_ALLOW_SEALING)) == -1)
198     {
199       clib_unix_warning ("memfd_create");
200       return;
201     }
202
203   if (ftruncate (fd, memory_size) < 0)
204     {
205       clib_unix_warning ("ftruncate");
206       return;
207     }
208
209   /* Not mission-critical, complain and continue */
210   if ((fcntl (fd, F_ADD_SEALS, F_SEAL_SHRINK)) == -1)
211     clib_unix_warning ("fcntl (F_ADD_SEALS)");
212
213   mmap_addr = mmap (0, memory_size,
214                     PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 /* offset */ );
215
216   if (mmap_addr == MAP_FAILED)
217     {
218       clib_unix_warning ("mmap failed");
219       ASSERT (0);
220     }
221
222   h->sh = (void *) mmap_addr;
223   h->memfd = fd;
224   nbuckets = 1 << (max_log2 (nbuckets));
225
226   h->name = (u8 *) name;
227   h->sh->nbuckets = h->nbuckets = nbuckets;
228   h->log2_nbuckets = max_log2 (nbuckets);
229
230   alloc_arena (h) = (u64) (uword) mmap_addr;
231   alloc_arena_next (h) = CLIB_CACHE_LINE_BYTES;
232   alloc_arena_size (h) = memory_size;
233
234   bucket_size = nbuckets * sizeof (h->buckets[0]);
235   h->buckets = BV (alloc_aligned) (h, bucket_size);
236   h->sh->buckets_as_u64 = (u64) BV (clib_bihash_get_offset) (h, h->buckets);
237
238   h->alloc_lock = BV (alloc_aligned) (h, CLIB_CACHE_LINE_BYTES);
239   h->alloc_lock[0] = 0;
240
241   h->sh->alloc_lock_as_u64 =
242     (u64) BV (clib_bihash_get_offset) (h, (void *) h->alloc_lock);
243   freelist_vh =
244     BV (alloc_aligned) (h,
245                         sizeof (vec_header_t) +
246                         BIHASH_FREELIST_LENGTH * sizeof (u64));
247   freelist_vh->len = BIHASH_FREELIST_LENGTH;
248   h->sh->freelists_as_u64 =
249     (u64) BV (clib_bihash_get_offset) (h, freelist_vh->vector_data);
250   h->freelists = (void *) (freelist_vh->vector_data);
251
252   h->fmt_fn = NULL;
253   h->instantiated = 1;
254 }
255
256 void BV (clib_bihash_slave_init_svm)
257   (BVT (clib_bihash) * h, char *name, int fd)
258 {
259   u8 *mmap_addr;
260   u64 memory_size;
261   BVT (clib_bihash_shared_header) * sh;
262
263   /* Trial mapping, to learn the segment size */
264   mmap_addr = mmap (0, 4096, PROT_READ, MAP_SHARED, fd, 0 /* offset */ );
265   if (mmap_addr == MAP_FAILED)
266     {
267       clib_unix_warning ("trial mmap failed");
268       ASSERT (0);
269     }
270
271   sh = (BVT (clib_bihash_shared_header) *) mmap_addr;
272
273   memory_size = sh->alloc_arena_size;
274
275   munmap (mmap_addr, 4096);
276
277   /* Actual mapping, at the required size */
278   mmap_addr = mmap (0, memory_size,
279                     PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 /* offset */ );
280
281   if (mmap_addr == MAP_FAILED)
282     {
283       clib_unix_warning ("mmap failed");
284       ASSERT (0);
285     }
286
287   (void) close (fd);
288
289   h->sh = (void *) mmap_addr;
290   alloc_arena (h) = (u64) (uword) mmap_addr;
291   h->memfd = -1;
292
293   h->name = (u8 *) name;
294   h->buckets = BV (clib_bihash_get_value) (h, h->sh->buckets_as_u64);
295   h->nbuckets = h->sh->nbuckets;
296   h->log2_nbuckets = max_log2 (h->nbuckets);
297
298   h->alloc_lock = BV (clib_bihash_get_value) (h, h->sh->alloc_lock_as_u64);
299   h->freelists = BV (clib_bihash_get_value) (h, h->sh->freelists_as_u64);
300   h->fmt_fn = NULL;
301 }
302 #endif /* BIHASH_32_64_SVM */
303
304 void BV (clib_bihash_set_kvp_format_fn) (BVT (clib_bihash) * h,
305                                          format_function_t * fmt_fn)
306 {
307   h->fmt_fn = fmt_fn;
308 }
309
310 void BV (clib_bihash_free) (BVT (clib_bihash) * h)
311 {
312   int i;
313
314   if (PREDICT_FALSE (h->instantiated == 0))
315     goto never_initialized;
316
317   h->instantiated = 0;
318   vec_free (h->working_copies);
319   vec_free (h->working_copy_lengths);
320 #if BIHASH_32_64_SVM == 0
321   vec_free (h->freelists);
322 #else
323   if (h->memfd > 0)
324     (void) close (h->memfd);
325 #endif
326   clib_mem_vm_free ((void *) (uword) (alloc_arena (h)), alloc_arena_size (h));
327 never_initialized:
328   clib_memset (h, 0, sizeof (*h));
329   for (i = 0; i < vec_len (clib_all_bihashes); i++)
330     {
331       if ((void *) h == clib_all_bihashes[i])
332         {
333           vec_delete (clib_all_bihashes, 1, i);
334           return;
335         }
336     }
337   clib_warning ("Couldn't find hash table %llx on clib_all_bihashes...",
338                 (u64) (uword) h);
339 }
340
341 static
342 BVT (clib_bihash_value) *
343 BV (value_alloc) (BVT (clib_bihash) * h, u32 log2_pages)
344 {
345   BVT (clib_bihash_value) * rv = 0;
346
347   ASSERT (h->alloc_lock[0]);
348
349 #if BIHASH_32_64_SVM
350   ASSERT (log2_pages < vec_len (h->freelists));
351 #endif
352
353   if (log2_pages >= vec_len (h->freelists) || h->freelists[log2_pages] == 0)
354     {
355       vec_validate_init_empty (h->freelists, log2_pages, 0);
356       rv = BV (alloc_aligned) (h, (sizeof (*rv) * (1 << log2_pages)));
357       goto initialize;
358     }
359   rv = BV (clib_bihash_get_value) (h, (uword) h->freelists[log2_pages]);
360   h->freelists[log2_pages] = rv->next_free_as_u64;
361
362 initialize:
363   ASSERT (rv);
364   /*
365    * Latest gcc complains that the length arg is zero
366    * if we replace (1<<log2_pages) with vec_len(rv).
367    * No clue.
368    */
369   clib_memset (rv, 0xff, sizeof (*rv) * (1 << log2_pages));
370   return rv;
371 }
372
373 static void
374 BV (value_free) (BVT (clib_bihash) * h, BVT (clib_bihash_value) * v,
375                  u32 log2_pages)
376 {
377   ASSERT (h->alloc_lock[0]);
378
379   ASSERT (vec_len (h->freelists) > log2_pages);
380
381   if (CLIB_DEBUG > 0)
382     clib_memset (v, 0xFE, sizeof (*v) * (1 << log2_pages));
383
384   v->next_free_as_u64 = (u64) h->freelists[log2_pages];
385   h->freelists[log2_pages] = (u64) BV (clib_bihash_get_offset) (h, v);
386 }
387
388 static inline void
389 BV (make_working_copy) (BVT (clib_bihash) * h, BVT (clib_bihash_bucket) * b)
390 {
391   BVT (clib_bihash_value) * v;
392   BVT (clib_bihash_bucket) working_bucket __attribute__ ((aligned (8)));
393   BVT (clib_bihash_value) * working_copy;
394   u32 thread_index = os_get_thread_index ();
395   int log2_working_copy_length;
396
397   ASSERT (h->alloc_lock[0]);
398
399   if (thread_index >= vec_len (h->working_copies))
400     {
401       vec_validate (h->working_copies, thread_index);
402       vec_validate_init_empty (h->working_copy_lengths, thread_index, ~0);
403     }
404
405   /*
406    * working_copies are per-cpu so that near-simultaneous
407    * updates from multiple threads will not result in sporadic, spurious
408    * lookup failures.
409    */
410   working_copy = h->working_copies[thread_index];
411   log2_working_copy_length = h->working_copy_lengths[thread_index];
412
413   h->saved_bucket.as_u64 = b->as_u64;
414
415   if (b->log2_pages > log2_working_copy_length)
416     {
417       /*
418        * It's not worth the bookkeeping to free working copies
419        *   if (working_copy)
420        *     clib_mem_free (working_copy);
421        */
422       working_copy = BV (alloc_aligned)
423         (h, sizeof (working_copy[0]) * (1 << b->log2_pages));
424       h->working_copy_lengths[thread_index] = b->log2_pages;
425       h->working_copies[thread_index] = working_copy;
426
427       BV (clib_bihash_increment_stat) (h, BIHASH_STAT_working_copy_lost,
428                                        1ULL << b->log2_pages);
429     }
430
431   v = BV (clib_bihash_get_value) (h, b->offset);
432
433   clib_memcpy_fast (working_copy, v, sizeof (*v) * (1 << b->log2_pages));
434   working_bucket.as_u64 = b->as_u64;
435   working_bucket.offset = BV (clib_bihash_get_offset) (h, working_copy);
436   CLIB_MEMORY_BARRIER ();
437   b->as_u64 = working_bucket.as_u64;
438   h->working_copies[thread_index] = working_copy;
439 }
440
441 static
442 BVT (clib_bihash_value) *
443 BV (split_and_rehash)
444   (BVT (clib_bihash) * h,
445    BVT (clib_bihash_value) * old_values, u32 old_log2_pages,
446    u32 new_log2_pages)
447 {
448   BVT (clib_bihash_value) * new_values, *new_v;
449   int i, j, length_in_kvs;
450
451   ASSERT (h->alloc_lock[0]);
452
453   new_values = BV (value_alloc) (h, new_log2_pages);
454   length_in_kvs = (1 << old_log2_pages) * BIHASH_KVP_PER_PAGE;
455
456   for (i = 0; i < length_in_kvs; i++)
457     {
458       u64 new_hash;
459
460       /* Entry not in use? Forget it */
461       if (BV (clib_bihash_is_free) (&(old_values->kvp[i])))
462         continue;
463
464       /* rehash the item onto its new home-page */
465       new_hash = BV (clib_bihash_hash) (&(old_values->kvp[i]));
466       new_hash >>= h->log2_nbuckets;
467       new_hash &= (1 << new_log2_pages) - 1;
468       new_v = &new_values[new_hash];
469
470       /* Across the new home-page */
471       for (j = 0; j < BIHASH_KVP_PER_PAGE; j++)
472         {
473           /* Empty slot */
474           if (BV (clib_bihash_is_free) (&(new_v->kvp[j])))
475             {
476               clib_memcpy_fast (&(new_v->kvp[j]), &(old_values->kvp[i]),
477                                 sizeof (new_v->kvp[j]));
478               goto doublebreak;
479             }
480         }
481       /* Crap. Tell caller to try again */
482       BV (value_free) (h, new_values, new_log2_pages);
483       return 0;
484     doublebreak:;
485     }
486
487   return new_values;
488 }
489
490 static
491 BVT (clib_bihash_value) *
492 BV (split_and_rehash_linear)
493   (BVT (clib_bihash) * h,
494    BVT (clib_bihash_value) * old_values, u32 old_log2_pages,
495    u32 new_log2_pages)
496 {
497   BVT (clib_bihash_value) * new_values;
498   int i, j, new_length, old_length;
499
500   ASSERT (h->alloc_lock[0]);
501
502   new_values = BV (value_alloc) (h, new_log2_pages);
503   new_length = (1 << new_log2_pages) * BIHASH_KVP_PER_PAGE;
504   old_length = (1 << old_log2_pages) * BIHASH_KVP_PER_PAGE;
505
506   j = 0;
507   /* Across the old value array */
508   for (i = 0; i < old_length; i++)
509     {
510       /* Find a free slot in the new linear scan bucket */
511       for (; j < new_length; j++)
512         {
513           /* Old value not in use? Forget it. */
514           if (BV (clib_bihash_is_free) (&(old_values->kvp[i])))
515             goto doublebreak;
516
517           /* New value should never be in use */
518           if (BV (clib_bihash_is_free) (&(new_values->kvp[j])))
519             {
520               /* Copy the old value and move along */
521               clib_memcpy_fast (&(new_values->kvp[j]), &(old_values->kvp[i]),
522                                 sizeof (new_values->kvp[j]));
523               j++;
524               goto doublebreak;
525             }
526         }
527       /* This should never happen... */
528       clib_warning ("BUG: linear rehash failed!");
529       BV (value_free) (h, new_values, new_log2_pages);
530       return 0;
531
532     doublebreak:;
533     }
534   return new_values;
535 }
536
537 static inline int BV (clib_bihash_add_del_inline)
538   (BVT (clib_bihash) * h, BVT (clib_bihash_kv) * add_v, int is_add,
539    int (*is_stale_cb) (BVT (clib_bihash_kv) *, void *), void *arg)
540 {
541   BVT (clib_bihash_bucket) * b, tmp_b;
542   BVT (clib_bihash_value) * v, *new_v, *save_new_v, *working_copy;
543   int i, limit;
544   u64 hash, new_hash;
545   u32 new_log2_pages, old_log2_pages;
546   u32 thread_index = os_get_thread_index ();
547   int mark_bucket_linear;
548   int resplit_once;
549
550   /*
551    * Create the table (is_add=1,2), or flunk the request now (is_add=0)
552    * Use the alloc_lock to protect the instantiate operation.
553    */
554   if (PREDICT_FALSE (h->instantiated == 0))
555     {
556       if (is_add == 0)
557         return (-1);
558
559       BV (clib_bihash_alloc_lock) (h);
560       if (h->instantiated == 0)
561         BV (clib_bihash_instantiate) (h);
562       BV (clib_bihash_alloc_unlock) (h);
563     }
564
565   hash = BV (clib_bihash_hash) (add_v);
566
567   b = BV (clib_bihash_get_bucket) (h, hash);
568
569   hash >>= h->log2_nbuckets;
570
571   BV (clib_bihash_lock_bucket) (b);
572
573   /* First elt in the bucket? */
574   if (BIHASH_KVP_AT_BUCKET_LEVEL == 0 && BV (clib_bihash_bucket_is_empty) (b))
575     {
576       if (is_add == 0)
577         {
578           BV (clib_bihash_unlock_bucket) (b);
579           return (-1);
580         }
581
582       BV (clib_bihash_alloc_lock) (h);
583       v = BV (value_alloc) (h, 0);
584       BV (clib_bihash_alloc_unlock) (h);
585
586       *v->kvp = *add_v;
587       tmp_b.as_u64 = 0;         /* clears bucket lock */
588       tmp_b.offset = BV (clib_bihash_get_offset) (h, v);
589       tmp_b.refcnt = 1;
590       CLIB_MEMORY_BARRIER ();
591
592       b->as_u64 = tmp_b.as_u64; /* unlocks the bucket */
593       BV (clib_bihash_increment_stat) (h, BIHASH_STAT_alloc_add, 1);
594
595       return (0);
596     }
597
598   /* WARNING: we're still looking at the live copy... */
599   limit = BIHASH_KVP_PER_PAGE;
600   v = BV (clib_bihash_get_value) (h, b->offset);
601
602   v += (b->linear_search == 0) ? hash & ((1 << b->log2_pages) - 1) : 0;
603   if (b->linear_search)
604     limit <<= b->log2_pages;
605
606   if (is_add)
607     {
608       /*
609        * Because reader threads are looking at live data,
610        * we have to be extra careful. Readers do NOT hold the
611        * bucket lock. We need to be SLOWER than a search, past the
612        * point where readers CHECK the bucket lock.
613        */
614
615       /*
616        * For obvious (in hindsight) reasons, see if we're supposed to
617        * replace an existing key, then look for an empty slot.
618        */
619       for (i = 0; i < limit; i++)
620         {
621           if (BV (clib_bihash_key_compare) (v->kvp[i].key, add_v->key))
622             {
623               /* Add but do not overwrite? */
624               if (is_add == 2)
625                 {
626                   BV (clib_bihash_unlock_bucket) (b);
627                   return (-2);
628                 }
629
630               CLIB_MEMORY_BARRIER ();   /* Add a delay */
631               clib_memcpy_fast (&(v->kvp[i]), add_v, sizeof (*add_v));
632               BV (clib_bihash_unlock_bucket) (b);
633               BV (clib_bihash_increment_stat) (h, BIHASH_STAT_replace, 1);
634               return (0);
635             }
636         }
637       /*
638        * Look for an empty slot. If found, use it
639        */
640       for (i = 0; i < limit; i++)
641         {
642           if (BV (clib_bihash_is_free) (&(v->kvp[i])))
643             {
644               /*
645                * Copy the value first, so that if a reader manages
646                * to match the new key, the value will be right...
647                */
648               clib_memcpy_fast (&(v->kvp[i].value),
649                                 &add_v->value, sizeof (add_v->value));
650               CLIB_MEMORY_BARRIER ();   /* Make sure the value has settled */
651               clib_memcpy_fast (&(v->kvp[i]), &add_v->key,
652                                 sizeof (add_v->key));
653               b->refcnt++;
654               ASSERT (b->refcnt > 0);
655               BV (clib_bihash_unlock_bucket) (b);
656               BV (clib_bihash_increment_stat) (h, BIHASH_STAT_add, 1);
657               return (0);
658             }
659         }
660       /* look for stale data to overwrite */
661       if (is_stale_cb)
662         {
663           for (i = 0; i < limit; i++)
664             {
665               if (is_stale_cb (&(v->kvp[i]), arg))
666                 {
667                   CLIB_MEMORY_BARRIER ();
668                   clib_memcpy_fast (&(v->kvp[i]), add_v, sizeof (*add_v));
669                   BV (clib_bihash_unlock_bucket) (b);
670                   BV (clib_bihash_increment_stat) (h, BIHASH_STAT_replace, 1);
671                   return (0);
672                 }
673             }
674         }
675       /* Out of space in this bucket, split the bucket... */
676     }
677   else                          /* delete case */
678     {
679       for (i = 0; i < limit; i++)
680         {
681           /* Found the key? Kill it... */
682           if (BV (clib_bihash_key_compare) (v->kvp[i].key, add_v->key))
683             {
684               clib_memset (&(v->kvp[i]), 0xff, sizeof (*(add_v)));
685               /* Is the bucket empty? */
686               if (PREDICT_TRUE (b->refcnt > 1))
687                 {
688                   b->refcnt--;
689                   /* Switch back to the bucket-level kvp array? */
690                   if (BIHASH_KVP_AT_BUCKET_LEVEL && b->refcnt == 1
691                       && b->log2_pages > 0)
692                     {
693                       tmp_b.as_u64 = b->as_u64;
694                       b->offset = BV (clib_bihash_get_offset)
695                         (h, (void *) (b + 1));
696                       b->linear_search = 0;
697                       b->log2_pages = 0;
698                       /* Clean up the bucket-level kvp array */
699                       clib_memset
700                         ((b + 1), 0xff,
701                          BIHASH_KVP_PER_PAGE * sizeof (BVT (clib_bihash_kv)));
702                       BV (clib_bihash_unlock_bucket) (b);
703                       BV (clib_bihash_increment_stat) (h, BIHASH_STAT_del, 1);
704                       goto free_backing_store;
705                     }
706
707                   BV (clib_bihash_unlock_bucket) (b);
708                   BV (clib_bihash_increment_stat) (h, BIHASH_STAT_del, 1);
709                   return (0);
710                 }
711               else              /* yes, free it */
712                 {
713                   /* Save old bucket value, need log2_pages to free it */
714                   tmp_b.as_u64 = b->as_u64;
715                   CLIB_MEMORY_BARRIER ();
716
717                   /* Kill and unlock the bucket */
718                   b->as_u64 = 0;
719
720                 free_backing_store:
721                   /* And free the backing storage */
722                   BV (clib_bihash_alloc_lock) (h);
723                   /* Note: v currently points into the middle of the bucket */
724                   v = BV (clib_bihash_get_value) (h, tmp_b.offset);
725                   BV (value_free) (h, v, tmp_b.log2_pages);
726                   BV (clib_bihash_alloc_unlock) (h);
727                   BV (clib_bihash_increment_stat) (h, BIHASH_STAT_del_free,
728                                                    1);
729                   return (0);
730                 }
731             }
732         }
733       /* Not found... */
734       BV (clib_bihash_unlock_bucket) (b);
735       return (-3);
736     }
737
738   /* Move readers to a (locked) temp copy of the bucket */
739   BV (clib_bihash_alloc_lock) (h);
740   BV (make_working_copy) (h, b);
741
742   v = BV (clib_bihash_get_value) (h, h->saved_bucket.offset);
743
744   old_log2_pages = h->saved_bucket.log2_pages;
745   new_log2_pages = old_log2_pages + 1;
746   mark_bucket_linear = 0;
747   BV (clib_bihash_increment_stat) (h, BIHASH_STAT_split_add, 1);
748   BV (clib_bihash_increment_stat) (h, BIHASH_STAT_splits, old_log2_pages);
749
750   working_copy = h->working_copies[thread_index];
751   resplit_once = 0;
752   BV (clib_bihash_increment_stat) (h, BIHASH_STAT_splits, 1);
753
754   new_v = BV (split_and_rehash) (h, working_copy, old_log2_pages,
755                                  new_log2_pages);
756   if (new_v == 0)
757     {
758     try_resplit:
759       resplit_once = 1;
760       new_log2_pages++;
761       /* Try re-splitting. If that fails, fall back to linear search */
762       new_v = BV (split_and_rehash) (h, working_copy, old_log2_pages,
763                                      new_log2_pages);
764       if (new_v == 0)
765         {
766         mark_linear:
767           new_log2_pages--;
768           /* pinned collisions, use linear search */
769           new_v =
770             BV (split_and_rehash_linear) (h, working_copy, old_log2_pages,
771                                           new_log2_pages);
772           mark_bucket_linear = 1;
773           BV (clib_bihash_increment_stat) (h, BIHASH_STAT_linear, 1);
774         }
775       BV (clib_bihash_increment_stat) (h, BIHASH_STAT_resplit, 1);
776       BV (clib_bihash_increment_stat) (h, BIHASH_STAT_splits,
777                                        old_log2_pages + 1);
778     }
779
780   /* Try to add the new entry */
781   save_new_v = new_v;
782   new_hash = BV (clib_bihash_hash) (add_v);
783   limit = BIHASH_KVP_PER_PAGE;
784   if (mark_bucket_linear)
785     limit <<= new_log2_pages;
786   new_hash >>= h->log2_nbuckets;
787   new_hash &= (1 << new_log2_pages) - 1;
788   new_v += mark_bucket_linear ? 0 : new_hash;
789
790   for (i = 0; i < limit; i++)
791     {
792       if (BV (clib_bihash_is_free) (&(new_v->kvp[i])))
793         {
794           clib_memcpy_fast (&(new_v->kvp[i]), add_v, sizeof (*add_v));
795           goto expand_ok;
796         }
797     }
798
799   /* Crap. Try again */
800   BV (value_free) (h, save_new_v, new_log2_pages);
801   /*
802    * If we've already doubled the size of the bucket once,
803    * fall back to linear search now.
804    */
805   if (resplit_once)
806     goto mark_linear;
807   else
808     goto try_resplit;
809
810 expand_ok:
811   tmp_b.log2_pages = new_log2_pages;
812   tmp_b.offset = BV (clib_bihash_get_offset) (h, save_new_v);
813   tmp_b.linear_search = mark_bucket_linear;
814 #if BIHASH_KVP_AT_BUCKET_LEVEL
815   /* Compensate for permanent refcount bump at the bucket level */
816   if (new_log2_pages > 0)
817 #endif
818     tmp_b.refcnt = h->saved_bucket.refcnt + 1;
819   ASSERT (tmp_b.refcnt > 0);
820   tmp_b.lock = 0;
821   CLIB_MEMORY_BARRIER ();
822   b->as_u64 = tmp_b.as_u64;
823
824 #if BIHASH_KVP_AT_BUCKET_LEVEL
825   if (h->saved_bucket.log2_pages > 0)
826     {
827 #endif
828
829       /* free the old bucket, except at the bucket level if so configured */
830       v = BV (clib_bihash_get_value) (h, h->saved_bucket.offset);
831       BV (value_free) (h, v, h->saved_bucket.log2_pages);
832
833 #if BIHASH_KVP_AT_BUCKET_LEVEL
834     }
835 #endif
836
837
838   BV (clib_bihash_alloc_unlock) (h);
839   return (0);
840 }
841
842 int BV (clib_bihash_add_del)
843   (BVT (clib_bihash) * h, BVT (clib_bihash_kv) * add_v, int is_add)
844 {
845   return BV (clib_bihash_add_del_inline) (h, add_v, is_add, 0, 0);
846 }
847
848 int BV (clib_bihash_add_or_overwrite_stale)
849   (BVT (clib_bihash) * h, BVT (clib_bihash_kv) * add_v,
850    int (*stale_callback) (BVT (clib_bihash_kv) *, void *), void *arg)
851 {
852   return BV (clib_bihash_add_del_inline) (h, add_v, 1, stale_callback, arg);
853 }
854
855 int BV (clib_bihash_search)
856   (BVT (clib_bihash) * h,
857    BVT (clib_bihash_kv) * search_key, BVT (clib_bihash_kv) * valuep)
858 {
859   u64 hash;
860   BVT (clib_bihash_value) * v;
861   BVT (clib_bihash_bucket) * b;
862   int i, limit;
863
864   ASSERT (valuep);
865
866 #if BIHASH_LAZY_INSTANTIATE
867   if (PREDICT_FALSE (alloc_arena (h) == 0))
868     return -1;
869 #endif
870
871   hash = BV (clib_bihash_hash) (search_key);
872
873   b = BV (clib_bihash_get_bucket) (h, hash);
874
875   if (BV (clib_bihash_bucket_is_empty) (b))
876     return -1;
877
878   if (PREDICT_FALSE (b->lock))
879     {
880       volatile BVT (clib_bihash_bucket) * bv = b;
881       while (bv->lock)
882         CLIB_PAUSE ();
883     }
884
885   hash >>= h->log2_nbuckets;
886
887   v = BV (clib_bihash_get_value) (h, b->offset);
888   limit = BIHASH_KVP_PER_PAGE;
889   v += (b->linear_search == 0) ? hash & ((1 << b->log2_pages) - 1) : 0;
890   if (PREDICT_FALSE (b->linear_search))
891     limit <<= b->log2_pages;
892
893   for (i = 0; i < limit; i++)
894     {
895       if (BV (clib_bihash_key_compare) (v->kvp[i].key, search_key->key))
896         {
897           *valuep = v->kvp[i];
898           return 0;
899         }
900     }
901   return -1;
902 }
903
904 u8 *BV (format_bihash) (u8 * s, va_list * args)
905 {
906   BVT (clib_bihash) * h = va_arg (*args, BVT (clib_bihash) *);
907   int verbose = va_arg (*args, int);
908   BVT (clib_bihash_bucket) * b;
909   BVT (clib_bihash_value) * v;
910   int i, j, k;
911   u64 active_elements = 0;
912   u64 active_buckets = 0;
913   u64 linear_buckets = 0;
914   u64 used_bytes;
915
916   s = format (s, "Hash table %s\n", h->name ? h->name : (u8 *) "(unnamed)");
917
918 #if BIHASH_LAZY_INSTANTIATE
919   if (PREDICT_FALSE (alloc_arena (h) == 0))
920     return format (s, "[empty, uninitialized]");
921 #endif
922
923   for (i = 0; i < h->nbuckets; i++)
924     {
925       b = BV (clib_bihash_get_bucket) (h, i);
926       if (BV (clib_bihash_bucket_is_empty) (b))
927         {
928           if (verbose > 1)
929             s = format (s, "[%d]: empty\n", i);
930           continue;
931         }
932
933       active_buckets++;
934
935       if (b->linear_search)
936         linear_buckets++;
937
938       if (verbose)
939         {
940           s = format
941             (s, "[%d]: heap offset %lld, len %d, refcnt %d, linear %d\n", i,
942              b->offset, (1 << b->log2_pages), b->refcnt, b->linear_search);
943         }
944
945       v = BV (clib_bihash_get_value) (h, b->offset);
946       for (j = 0; j < (1 << b->log2_pages); j++)
947         {
948           for (k = 0; k < BIHASH_KVP_PER_PAGE; k++)
949             {
950               if (BV (clib_bihash_is_free) (&v->kvp[k]))
951                 {
952                   if (verbose > 1)
953                     s = format (s, "    %d: empty\n",
954                                 j * BIHASH_KVP_PER_PAGE + k);
955                   continue;
956                 }
957               if (verbose)
958                 {
959                   if (h->fmt_fn)
960                     {
961                       s = format (s, "    %d: %U\n",
962                                   j * BIHASH_KVP_PER_PAGE + k,
963                                   h->fmt_fn, &(v->kvp[k]), verbose);
964                     }
965                   else
966                     {
967                       s = format (s, "    %d: %U\n",
968                                   j * BIHASH_KVP_PER_PAGE + k,
969                                   BV (format_bihash_kvp), &(v->kvp[k]));
970                     }
971                 }
972               active_elements++;
973             }
974           v++;
975         }
976     }
977
978   s = format (s, "    %lld active elements %lld active buckets\n",
979               active_elements, active_buckets);
980   s = format (s, "    %d free lists\n", vec_len (h->freelists));
981
982   for (i = 0; i < vec_len (h->freelists); i++)
983     {
984       u32 nfree = 0;
985       BVT (clib_bihash_value) * free_elt;
986       u64 free_elt_as_u64 = h->freelists[i];
987
988       while (free_elt_as_u64)
989         {
990           free_elt = BV (clib_bihash_get_value) (h, free_elt_as_u64);
991           nfree++;
992           free_elt_as_u64 = free_elt->next_free_as_u64;
993         }
994
995       if (nfree || verbose)
996         s = format (s, "       [len %d] %u free elts\n", 1 << i, nfree);
997     }
998
999   s = format (s, "    %lld linear search buckets\n", linear_buckets);
1000   used_bytes = alloc_arena_next (h);
1001   s = format (s,
1002               "    arena: base %llx, next %llx\n"
1003               "           used %lld b (%lld Mbytes) of %lld b (%lld Mbytes)\n",
1004               alloc_arena (h), alloc_arena_next (h),
1005               used_bytes, used_bytes >> 20,
1006               alloc_arena_size (h), alloc_arena_size (h) >> 20);
1007   return s;
1008 }
1009
1010 void BV (clib_bihash_foreach_key_value_pair)
1011   (BVT (clib_bihash) * h,
1012    BV (clib_bihash_foreach_key_value_pair_cb) cb, void *arg)
1013 {
1014   int i, j, k;
1015   BVT (clib_bihash_bucket) * b;
1016   BVT (clib_bihash_value) * v;
1017
1018
1019 #if BIHASH_LAZY_INSTANTIATE
1020   if (PREDICT_FALSE (alloc_arena (h) == 0))
1021     return;
1022 #endif
1023
1024   for (i = 0; i < h->nbuckets; i++)
1025     {
1026       b = BV (clib_bihash_get_bucket) (h, i);
1027       if (BV (clib_bihash_bucket_is_empty) (b))
1028         continue;
1029
1030       v = BV (clib_bihash_get_value) (h, b->offset);
1031       for (j = 0; j < (1 << b->log2_pages); j++)
1032         {
1033           for (k = 0; k < BIHASH_KVP_PER_PAGE; k++)
1034             {
1035               if (BV (clib_bihash_is_free) (&v->kvp[k]))
1036                 continue;
1037
1038               if (BIHASH_WALK_STOP == cb (&v->kvp[k], arg))
1039                 return;
1040               /*
1041                * In case the callback deletes the last entry in the bucket...
1042                */
1043               if (BV (clib_bihash_bucket_is_empty) (b))
1044                 goto doublebreak;
1045             }
1046           v++;
1047         }
1048     doublebreak:
1049       ;
1050     }
1051 }
1052
1053 /** @endcond */
1054
1055 /*
1056  * fd.io coding-style-patch-verification: ON
1057  *
1058  * Local Variables:
1059  * eval: (c-set-style "gnu")
1060  * End:
1061  */