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