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