Adding a format function for bihash init routine to format the key, value, when verbo...
[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 void BV (clib_bihash_init)
19   (BVT (clib_bihash) * h, char *name, u32 nbuckets, uword memory_size)
20 {
21   void *oldheap;
22   int i;
23
24   nbuckets = 1 << (max_log2 (nbuckets));
25
26   h->name = (u8 *) name;
27   h->nbuckets = nbuckets;
28   h->log2_nbuckets = max_log2 (nbuckets);
29   h->cache_hits = 0;
30   h->cache_misses = 0;
31
32   h->mheap = mheap_alloc (0 /* use VM */ , memory_size);
33
34   oldheap = clib_mem_set_heap (h->mheap);
35   vec_validate_aligned (h->buckets, nbuckets - 1, CLIB_CACHE_LINE_BYTES);
36   h->writer_lock = clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES,
37                                            CLIB_CACHE_LINE_BYTES);
38   h->writer_lock[0] = 0;
39
40   for (i = 0; i < nbuckets; i++)
41     BV (clib_bihash_reset_cache) (h->buckets + i);
42
43   clib_mem_set_heap (oldheap);
44
45   h->fmt_fn = NULL;
46 }
47
48 void BV (clib_bihash_set_kvp_format_fn) (BVT (clib_bihash) * h,
49                                          format_function_t * fmt_fn)
50 {
51   h->fmt_fn = fmt_fn;
52 }
53
54 void BV (clib_bihash_free) (BVT (clib_bihash) * h)
55 {
56   mheap_free (h->mheap);
57   memset (h, 0, sizeof (*h));
58 }
59
60 static
61 BVT (clib_bihash_value) *
62 BV (value_alloc) (BVT (clib_bihash) * h, u32 log2_pages)
63 {
64   BVT (clib_bihash_value) * rv = 0;
65   void *oldheap;
66
67   ASSERT (h->writer_lock[0]);
68   if (log2_pages >= vec_len (h->freelists) || h->freelists[log2_pages] == 0)
69     {
70       oldheap = clib_mem_set_heap (h->mheap);
71
72       vec_validate (h->freelists, log2_pages);
73       rv = clib_mem_alloc_aligned ((sizeof (*rv) * (1 << log2_pages)),
74                                    CLIB_CACHE_LINE_BYTES);
75       clib_mem_set_heap (oldheap);
76       goto initialize;
77     }
78   rv = h->freelists[log2_pages];
79   h->freelists[log2_pages] = rv->next_free;
80
81 initialize:
82   ASSERT (rv);
83   /*
84    * Latest gcc complains that the length arg is zero
85    * if we replace (1<<log2_pages) with vec_len(rv).
86    * No clue.
87    */
88   memset (rv, 0xff, sizeof (*rv) * (1 << log2_pages));
89   return rv;
90 }
91
92 static void
93 BV (value_free) (BVT (clib_bihash) * h, BVT (clib_bihash_value) * v,
94                  u32 log2_pages)
95 {
96   ASSERT (h->writer_lock[0]);
97
98   ASSERT (vec_len (h->freelists) > log2_pages);
99
100   v->next_free = h->freelists[log2_pages];
101   h->freelists[log2_pages] = v;
102 }
103
104 static inline void
105 BV (make_working_copy) (BVT (clib_bihash) * h, BVT (clib_bihash_bucket) * b)
106 {
107   BVT (clib_bihash_value) * v;
108   BVT (clib_bihash_bucket) working_bucket __attribute__ ((aligned (8)));
109   void *oldheap;
110   BVT (clib_bihash_value) * working_copy;
111   u32 thread_index = os_get_thread_index ();
112   int log2_working_copy_length;
113
114   if (thread_index >= vec_len (h->working_copies))
115     {
116       oldheap = clib_mem_set_heap (h->mheap);
117       vec_validate (h->working_copies, thread_index);
118       vec_validate_init_empty (h->working_copy_lengths, thread_index, ~0);
119       clib_mem_set_heap (oldheap);
120     }
121
122   /*
123    * working_copies are per-cpu so that near-simultaneous
124    * updates from multiple threads will not result in sporadic, spurious
125    * lookup failures.
126    */
127   working_copy = h->working_copies[thread_index];
128   log2_working_copy_length = h->working_copy_lengths[thread_index];
129
130   h->saved_bucket.as_u64 = b->as_u64;
131   oldheap = clib_mem_set_heap (h->mheap);
132
133   if (b->log2_pages > log2_working_copy_length)
134     {
135       if (working_copy)
136         clib_mem_free (working_copy);
137
138       working_copy = clib_mem_alloc_aligned
139         (sizeof (working_copy[0]) * (1 << b->log2_pages),
140          CLIB_CACHE_LINE_BYTES);
141       h->working_copy_lengths[thread_index] = b->log2_pages;
142       h->working_copies[thread_index] = working_copy;
143     }
144
145   clib_mem_set_heap (oldheap);
146
147   /* Lock the bucket... */
148   while (BV (clib_bihash_lock_bucket) (b) == 0)
149     ;
150
151   v = BV (clib_bihash_get_value) (h, b->offset);
152
153   clib_memcpy (working_copy, v, sizeof (*v) * (1 << b->log2_pages));
154   working_bucket.as_u64 = b->as_u64;
155   working_bucket.offset = BV (clib_bihash_get_offset) (h, working_copy);
156   CLIB_MEMORY_BARRIER ();
157   b->as_u64 = working_bucket.as_u64;
158   h->working_copies[thread_index] = working_copy;
159 }
160
161 static
162 BVT (clib_bihash_value) *
163 BV (split_and_rehash)
164   (BVT (clib_bihash) * h,
165    BVT (clib_bihash_value) * old_values, u32 old_log2_pages,
166    u32 new_log2_pages)
167 {
168   BVT (clib_bihash_value) * new_values, *new_v;
169   int i, j, length_in_kvs;
170
171   new_values = BV (value_alloc) (h, new_log2_pages);
172   length_in_kvs = (1 << old_log2_pages) * BIHASH_KVP_PER_PAGE;
173
174   for (i = 0; i < length_in_kvs; i++)
175     {
176       u64 new_hash;
177
178       /* Entry not in use? Forget it */
179       if (BV (clib_bihash_is_free) (&(old_values->kvp[i])))
180         continue;
181
182       /* rehash the item onto its new home-page */
183       new_hash = BV (clib_bihash_hash) (&(old_values->kvp[i]));
184       new_hash >>= h->log2_nbuckets;
185       new_hash &= (1 << new_log2_pages) - 1;
186       new_v = &new_values[new_hash];
187
188       /* Across the new home-page */
189       for (j = 0; j < BIHASH_KVP_PER_PAGE; j++)
190         {
191           /* Empty slot */
192           if (BV (clib_bihash_is_free) (&(new_v->kvp[j])))
193             {
194               clib_memcpy (&(new_v->kvp[j]), &(old_values->kvp[i]),
195                            sizeof (new_v->kvp[j]));
196               goto doublebreak;
197             }
198         }
199       /* Crap. Tell caller to try again */
200       BV (value_free) (h, new_values, new_log2_pages);
201       return 0;
202     doublebreak:;
203     }
204
205   return new_values;
206 }
207
208 static
209 BVT (clib_bihash_value) *
210 BV (split_and_rehash_linear)
211   (BVT (clib_bihash) * h,
212    BVT (clib_bihash_value) * old_values, u32 old_log2_pages,
213    u32 new_log2_pages)
214 {
215   BVT (clib_bihash_value) * new_values;
216   int i, j, new_length, old_length;
217
218   new_values = BV (value_alloc) (h, new_log2_pages);
219   new_length = (1 << new_log2_pages) * BIHASH_KVP_PER_PAGE;
220   old_length = (1 << old_log2_pages) * BIHASH_KVP_PER_PAGE;
221
222   j = 0;
223   /* Across the old value array */
224   for (i = 0; i < old_length; i++)
225     {
226       /* Find a free slot in the new linear scan bucket */
227       for (; j < new_length; j++)
228         {
229           /* Old value not in use? Forget it. */
230           if (BV (clib_bihash_is_free) (&(old_values->kvp[i])))
231             goto doublebreak;
232
233           /* New value should never be in use */
234           if (BV (clib_bihash_is_free) (&(new_values->kvp[j])))
235             {
236               /* Copy the old value and move along */
237               clib_memcpy (&(new_values->kvp[j]), &(old_values->kvp[i]),
238                            sizeof (new_values->kvp[j]));
239               j++;
240               goto doublebreak;
241             }
242         }
243       /* This should never happen... */
244       clib_warning ("BUG: linear rehash failed!");
245       BV (value_free) (h, new_values, new_log2_pages);
246       return 0;
247
248     doublebreak:;
249     }
250   return new_values;
251 }
252
253 int BV (clib_bihash_add_del)
254   (BVT (clib_bihash) * h, BVT (clib_bihash_kv) * add_v, int is_add)
255 {
256   u32 bucket_index;
257   BVT (clib_bihash_bucket) * b, tmp_b;
258   BVT (clib_bihash_value) * v, *new_v, *save_new_v, *working_copy;
259   int rv = 0;
260   int i, limit;
261   u64 hash, new_hash;
262   u32 new_log2_pages, old_log2_pages;
263   u32 thread_index = os_get_thread_index ();
264   int mark_bucket_linear;
265   int resplit_once;
266
267   hash = BV (clib_bihash_hash) (add_v);
268
269   bucket_index = hash & (h->nbuckets - 1);
270   b = &h->buckets[bucket_index];
271
272   hash >>= h->log2_nbuckets;
273
274   tmp_b.linear_search = 0;
275
276   while (__sync_lock_test_and_set (h->writer_lock, 1))
277     ;
278
279   /* First elt in the bucket? */
280   if (b->offset == 0)
281     {
282       if (is_add == 0)
283         {
284           rv = -1;
285           goto unlock;
286         }
287
288       v = BV (value_alloc) (h, 0);
289
290       *v->kvp = *add_v;
291       tmp_b.as_u64 = 0;
292       tmp_b.offset = BV (clib_bihash_get_offset) (h, v);
293
294       b->as_u64 = tmp_b.as_u64;
295       goto unlock;
296     }
297
298   /* Note: this leaves the cache disabled */
299   BV (make_working_copy) (h, b);
300
301   v = BV (clib_bihash_get_value) (h, h->saved_bucket.offset);
302
303   limit = BIHASH_KVP_PER_PAGE;
304   v += (b->linear_search == 0) ? hash & ((1 << b->log2_pages) - 1) : 0;
305   if (b->linear_search)
306     limit <<= b->log2_pages;
307
308   if (is_add)
309     {
310       /*
311        * For obvious (in hindsight) reasons, see if we're supposed to
312        * replace an existing key, then look for an empty slot.
313        */
314       for (i = 0; i < limit; i++)
315         {
316           if (!memcmp (&(v->kvp[i]), &add_v->key, sizeof (add_v->key)))
317             {
318               clib_memcpy (&(v->kvp[i]), add_v, sizeof (*add_v));
319               CLIB_MEMORY_BARRIER ();
320               /* Restore the previous (k,v) pairs */
321               b->as_u64 = h->saved_bucket.as_u64;
322               goto unlock;
323             }
324         }
325       for (i = 0; i < limit; i++)
326         {
327           if (BV (clib_bihash_is_free) (&(v->kvp[i])))
328             {
329               clib_memcpy (&(v->kvp[i]), add_v, sizeof (*add_v));
330               CLIB_MEMORY_BARRIER ();
331               b->as_u64 = h->saved_bucket.as_u64;
332               goto unlock;
333             }
334         }
335       /* no room at the inn... split case... */
336     }
337   else
338     {
339       for (i = 0; i < limit; i++)
340         {
341           if (!memcmp (&(v->kvp[i]), &add_v->key, sizeof (add_v->key)))
342             {
343               memset (&(v->kvp[i]), 0xff, sizeof (*(add_v)));
344               CLIB_MEMORY_BARRIER ();
345               b->as_u64 = h->saved_bucket.as_u64;
346               goto unlock;
347             }
348         }
349       rv = -3;
350       b->as_u64 = h->saved_bucket.as_u64;
351       goto unlock;
352     }
353
354   old_log2_pages = h->saved_bucket.log2_pages;
355   new_log2_pages = old_log2_pages + 1;
356   mark_bucket_linear = 0;
357
358   working_copy = h->working_copies[thread_index];
359   resplit_once = 0;
360
361   new_v = BV (split_and_rehash) (h, working_copy, old_log2_pages,
362                                  new_log2_pages);
363   if (new_v == 0)
364     {
365     try_resplit:
366       resplit_once = 1;
367       new_log2_pages++;
368       /* Try re-splitting. If that fails, fall back to linear search */
369       new_v = BV (split_and_rehash) (h, working_copy, old_log2_pages,
370                                      new_log2_pages);
371       if (new_v == 0)
372         {
373         mark_linear:
374           new_log2_pages--;
375           /* pinned collisions, use linear search */
376           new_v =
377             BV (split_and_rehash_linear) (h, working_copy, old_log2_pages,
378                                           new_log2_pages);
379           mark_bucket_linear = 1;
380         }
381     }
382
383   /* Try to add the new entry */
384   save_new_v = new_v;
385   new_hash = BV (clib_bihash_hash) (add_v);
386   limit = BIHASH_KVP_PER_PAGE;
387   if (mark_bucket_linear)
388     limit <<= new_log2_pages;
389   new_hash >>= h->log2_nbuckets;
390   new_hash &= (1 << new_log2_pages) - 1;
391   new_v += mark_bucket_linear ? 0 : new_hash;
392
393   for (i = 0; i < limit; i++)
394     {
395       if (BV (clib_bihash_is_free) (&(new_v->kvp[i])))
396         {
397           clib_memcpy (&(new_v->kvp[i]), add_v, sizeof (*add_v));
398           goto expand_ok;
399         }
400     }
401
402   /* Crap. Try again */
403   BV (value_free) (h, save_new_v, new_log2_pages);
404   /*
405    * If we've already doubled the size of the bucket once,
406    * fall back to linear search now.
407    */
408   if (resplit_once)
409     goto mark_linear;
410   else
411     goto try_resplit;
412
413 expand_ok:
414   /* Keep track of the number of linear-scan buckets */
415   if (tmp_b.linear_search ^ mark_bucket_linear)
416     h->linear_buckets += (mark_bucket_linear == 1) ? 1 : -1;
417
418   tmp_b.log2_pages = new_log2_pages;
419   tmp_b.offset = BV (clib_bihash_get_offset) (h, save_new_v);
420   tmp_b.linear_search = mark_bucket_linear;
421
422   CLIB_MEMORY_BARRIER ();
423   b->as_u64 = tmp_b.as_u64;
424   v = BV (clib_bihash_get_value) (h, h->saved_bucket.offset);
425   BV (value_free) (h, v, old_log2_pages);
426
427 unlock:
428   BV (clib_bihash_reset_cache) (b);
429   BV (clib_bihash_unlock_bucket) (b);
430   CLIB_MEMORY_BARRIER ();
431   h->writer_lock[0] = 0;
432   return rv;
433 }
434
435 int BV (clib_bihash_search)
436   (BVT (clib_bihash) * h,
437    BVT (clib_bihash_kv) * search_key, BVT (clib_bihash_kv) * valuep)
438 {
439   u64 hash;
440   u32 bucket_index;
441   BVT (clib_bihash_value) * v;
442 #if BIHASH_KVP_CACHE_SIZE > 0
443   BVT (clib_bihash_kv) * kvp;
444 #endif
445   BVT (clib_bihash_bucket) * b;
446   int i, limit;
447
448   ASSERT (valuep);
449
450   hash = BV (clib_bihash_hash) (search_key);
451
452   bucket_index = hash & (h->nbuckets - 1);
453   b = &h->buckets[bucket_index];
454
455   if (b->offset == 0)
456     return -1;
457
458 #if BIHASH_KVP_CACHE_SIZE > 0
459   /* Check the cache, if currently enabled */
460   if (PREDICT_TRUE ((b->cache_lru & (1 << 15)) == 0))
461     {
462       limit = BIHASH_KVP_CACHE_SIZE;
463       kvp = b->cache;
464       for (i = 0; i < limit; i++)
465         {
466           if (BV (clib_bihash_key_compare) (kvp[i].key, search_key->key))
467             {
468               *valuep = kvp[i];
469               h->cache_hits++;
470               return 0;
471             }
472         }
473     }
474 #endif
475
476   hash >>= h->log2_nbuckets;
477
478   v = BV (clib_bihash_get_value) (h, b->offset);
479   limit = BIHASH_KVP_PER_PAGE;
480   v += (b->linear_search == 0) ? hash & ((1 << b->log2_pages) - 1) : 0;
481   if (PREDICT_FALSE (b->linear_search))
482     limit <<= b->log2_pages;
483
484   for (i = 0; i < limit; i++)
485     {
486       if (BV (clib_bihash_key_compare) (v->kvp[i].key, search_key->key))
487         {
488           *valuep = v->kvp[i];
489
490 #if BIHASH_KVP_CACHE_SIZE > 0
491           u8 cache_slot;
492           /* Shut off the cache */
493           if (BV (clib_bihash_lock_bucket) (b))
494             {
495               cache_slot = BV (clib_bihash_get_lru) (b);
496               b->cache[cache_slot] = v->kvp[i];
497               BV (clib_bihash_update_lru) (b, cache_slot);
498
499               /* Reenable the cache */
500               BV (clib_bihash_unlock_bucket) (b);
501               h->cache_misses++;
502             }
503 #endif
504           return 0;
505         }
506     }
507   return -1;
508 }
509
510 u8 *BV (format_bihash_lru) (u8 * s, va_list * args)
511 {
512 #if BIHASH_KVP_SIZE > 0
513   int i;
514   BVT (clib_bihash_bucket) * b = va_arg (*args, BVT (clib_bihash_bucket) *);
515   u16 cache_lru = b->cache_lru;
516
517   s = format (s, "cache %s, order ", cache_lru & (1 << 15) ? "on" : "off");
518
519   for (i = 0; i < BIHASH_KVP_CACHE_SIZE; i++)
520     s = format (s, "[%d] ", ((cache_lru >> (3 * i)) & 7));
521
522   return (s);
523 #else
524   return format (s, "cache not configured");
525 #endif
526 }
527
528 void
529 BV (clib_bihash_update_lru_not_inline) (BVT (clib_bihash_bucket) * b, u8 slot)
530 {
531 #if BIHASH_KVP_SIZE > 0
532   BV (clib_bihash_update_lru) (b, slot);
533 #endif
534 }
535
536 u8 *BV (format_bihash) (u8 * s, va_list * args)
537 {
538   BVT (clib_bihash) * h = va_arg (*args, BVT (clib_bihash) *);
539   int verbose = va_arg (*args, int);
540   BVT (clib_bihash_bucket) * b;
541   BVT (clib_bihash_value) * v;
542   int i, j, k;
543   u64 active_elements = 0;
544
545   s = format (s, "Hash table %s\n", h->name ? h->name : (u8 *) "(unnamed)");
546
547   for (i = 0; i < h->nbuckets; i++)
548     {
549       b = &h->buckets[i];
550       if (b->offset == 0)
551         {
552           if (verbose > 1)
553             s = format (s, "[%d]: empty\n", i);
554           continue;
555         }
556
557       if (verbose)
558         {
559           s = format (s, "[%d]: heap offset %d, len %d, linear %d\n", i,
560                       b->offset, (1 << b->log2_pages), b->linear_search);
561         }
562
563       v = BV (clib_bihash_get_value) (h, b->offset);
564       for (j = 0; j < (1 << b->log2_pages); j++)
565         {
566           for (k = 0; k < BIHASH_KVP_PER_PAGE; k++)
567             {
568               if (BV (clib_bihash_is_free) (&v->kvp[k]))
569                 {
570                   if (verbose > 1)
571                     s = format (s, "    %d: empty\n",
572                                 j * BIHASH_KVP_PER_PAGE + k);
573                   continue;
574                 }
575               if (verbose)
576                 {
577                   if (h->fmt_fn)
578                     {
579                       s = format (s, "    %d: %U\n",
580                                   j * BIHASH_KVP_PER_PAGE + k,
581                                   h->fmt_fn, &(v->kvp[k]));
582                     }
583                   else
584                     {
585                       s = format (s, "    %d: %U\n",
586                                   j * BIHASH_KVP_PER_PAGE + k,
587                                   BV (format_bihash_kvp), &(v->kvp[k]));
588                     }
589                 }
590               active_elements++;
591             }
592           v++;
593         }
594     }
595
596   s = format (s, "    %lld active elements\n", active_elements);
597   s = format (s, "    %d free lists\n", vec_len (h->freelists));
598   s = format (s, "    %d linear search buckets\n", h->linear_buckets);
599   s = format (s, "    %lld cache hits, %lld cache misses\n",
600               h->cache_hits, h->cache_misses);
601   return s;
602 }
603
604 void BV (clib_bihash_foreach_key_value_pair)
605   (BVT (clib_bihash) * h, void *callback, void *arg)
606 {
607   int i, j, k;
608   BVT (clib_bihash_bucket) * b;
609   BVT (clib_bihash_value) * v;
610   void (*fp) (BVT (clib_bihash_kv) *, void *) = callback;
611
612   for (i = 0; i < h->nbuckets; i++)
613     {
614       b = &h->buckets[i];
615       if (b->offset == 0)
616         continue;
617
618       v = BV (clib_bihash_get_value) (h, b->offset);
619       for (j = 0; j < (1 << b->log2_pages); j++)
620         {
621           for (k = 0; k < BIHASH_KVP_PER_PAGE; k++)
622             {
623               if (BV (clib_bihash_is_free) (&v->kvp[k]))
624                 continue;
625
626               (*fp) (&v->kvp[k], arg);
627             }
628           v++;
629         }
630     }
631 }
632
633 /** @endcond */
634
635 /*
636  * fd.io coding-style-patch-verification: ON
637  *
638  * Local Variables:
639  * eval: (c-set-style "gnu")
640  * End:
641  */