vppinfra: use heap to store bihash data
[vpp.git] / src / vppinfra / bihash_template.h
1 /*
2   Copyright (c) 2014 Cisco and/or its affiliates.
3
4   * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15 */
16
17 /** @cond DOCUMENTATION_IS_IN_BIHASH_DOC_H */
18
19 /*
20  * Note: to instantiate the template multiple times in a single file,
21  * #undef __included_bihash_template_h__...
22  */
23 #ifndef __included_bihash_template_h__
24 #define __included_bihash_template_h__
25
26 #include <vppinfra/heap.h>
27 #include <vppinfra/format.h>
28 #include <vppinfra/pool.h>
29 #include <vppinfra/cache.h>
30 #include <vppinfra/lock.h>
31
32 #ifndef BIHASH_TYPE
33 #error BIHASH_TYPE not defined
34 #endif
35
36 #ifdef BIHASH_32_64_SVM
37 #undef HAVE_MEMFD_CREATE
38 #include <vppinfra/linux/syscall.h>
39 #include <fcntl.h>
40 #define F_LINUX_SPECIFIC_BASE 1024
41 #define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9)
42 #define F_SEAL_SHRINK (2)
43 /* Max page size 2**16 due to refcount width  */
44 #define BIHASH_FREELIST_LENGTH 17
45 #endif
46
47 /* default is 2MB, use 30 for 1GB */
48 #ifndef BIHASH_LOG2_HUGEPAGE_SIZE
49 #define BIHASH_LOG2_HUGEPAGE_SIZE 21
50 #endif
51
52 #define _bv(a,b) a##b
53 #define __bv(a,b) _bv(a,b)
54 #define BV(a) __bv(a,BIHASH_TYPE)
55
56 #define _bvt(a,b) a##b##_t
57 #define __bvt(a,b) _bvt(a,b)
58 #define BVT(a) __bvt(a,BIHASH_TYPE)
59
60 #define _bvs(a,b) struct a##b
61 #define __bvs(a,b) _bvs(a,b)
62 #define BVS(a) __bvs(a,BIHASH_TYPE)
63
64 #if _LP64 == 0
65 #define OVERFLOW_ASSERT(x) ASSERT(((x) & 0xFFFFFFFF00000000ULL) == 0)
66 #define u64_to_pointer(x) (void *)(u32)((x))
67 #define pointer_to_u64(x) (u64)(u32)((x))
68 #else
69 #define OVERFLOW_ASSERT(x)
70 #define u64_to_pointer(x) (void *)((x))
71 #define pointer_to_u64(x) (u64)((x))
72 #endif
73
74 typedef struct BV (clib_bihash_value)
75 {
76   union
77   {
78     BVT (clib_bihash_kv) kvp[BIHASH_KVP_PER_PAGE];
79     u64 next_free_as_u64;
80   };
81 } BVT (clib_bihash_value);
82
83 #define BIHASH_BUCKET_OFFSET_BITS 36
84
85 typedef struct
86 {
87   union
88   {
89     struct
90     {
91       u64 offset:BIHASH_BUCKET_OFFSET_BITS;
92       u64 lock:1;
93       u64 linear_search:1;
94       u64 log2_pages:8;
95       u64 refcnt:16;
96     };
97     u64 as_u64;
98   };
99 } BVT (clib_bihash_bucket);
100
101 STATIC_ASSERT_SIZEOF (BVT (clib_bihash_bucket), sizeof (u64));
102
103 /* *INDENT-OFF* */
104 typedef CLIB_PACKED (struct {
105   /*
106    * Backing store allocation. Since bihash manages its own
107    * freelists, we simple dole out memory starting from alloc_arena[alloc_arena_next].
108    */
109   u64 alloc_arena_next; /* Next offset from alloc_arena to allocate, definitely NOT a constant */
110   u64 alloc_arena_size; /* Size of the arena */
111   u64 alloc_arena_mapped;       /* Size of the mapped memory in the arena */
112   /* Two SVM pointers stored as 8-byte integers */
113   u64 alloc_lock_as_u64;
114   u64 buckets_as_u64;
115   /* freelist list-head arrays/vectors */
116   u64 freelists_as_u64;
117   u32 nbuckets; /* Number of buckets */
118   /* Set when header valid */
119   volatile u32 ready;
120   u64 pad[1];
121 }) BVT (clib_bihash_shared_header);
122 /* *INDENT-ON* */
123
124 STATIC_ASSERT_SIZEOF (BVT (clib_bihash_shared_header), 8 * sizeof (u64));
125
126 typedef
127 BVS (clib_bihash_alloc_chunk)
128 {
129   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
130
131   /* chunk size */
132   uword size;
133
134   /* pointer to the next allocation */
135   u8 *next_alloc;
136
137   /* number of bytes left in this chunk */
138   uword bytes_left;
139
140   /* doubly linked list of heap allocated chunks */
141   BVS (clib_bihash_alloc_chunk) * prev, *next;
142
143 } BVT (clib_bihash_alloc_chunk);
144
145 typedef
146 BVS (clib_bihash)
147 {
148   BVT (clib_bihash_bucket) * buckets;
149   volatile u32 *alloc_lock;
150
151   BVT (clib_bihash_value) ** working_copies;
152   int *working_copy_lengths;
153   BVT (clib_bihash_bucket) saved_bucket;
154
155   u32 nbuckets;
156   u32 log2_nbuckets;
157   u64 memory_size;
158   u8 *name;
159   void *heap;
160   BVT (clib_bihash_alloc_chunk) * chunks;
161
162   u64 *freelists;
163
164 #if BIHASH_32_64_SVM
165   BVT (clib_bihash_shared_header) * sh;
166   int memfd;
167 #else
168   BVT (clib_bihash_shared_header) sh;
169 #endif
170
171   u64 alloc_arena;              /* Base of the allocation arena */
172   volatile u8 instantiated;
173
174   /**
175     * A custom format function to print the Key and Value of bihash_key instead of default hexdump
176     */
177   format_function_t *fmt_fn;
178
179   /** Optional statistics-gathering callback */
180 #if BIHASH_ENABLE_STATS
181   void (*inc_stats_callback) (BVS (clib_bihash) *, int stat_id, u64 count);
182
183   /** Statistics callback context (e.g. address of stats data structure) */
184   void *inc_stats_context;
185 #endif
186
187 } BVT (clib_bihash);
188
189 typedef struct
190 {
191   BVT (clib_bihash) * h;
192   char *name;
193   u32 nbuckets;
194   uword memory_size;
195   format_function_t *fmt_fn;
196   u8 instantiate_immediately;
197   u8 dont_add_to_all_bihash_list;
198 } BVT (clib_bihash_init2_args);
199
200 extern void **clib_all_bihashes;
201
202 #if BIHASH_32_64_SVM
203 #undef alloc_arena_next
204 #undef alloc_arena_size
205 #undef alloc_arena_mapped
206 #undef alloc_arena
207 #undef CLIB_BIHASH_READY_MAGIC
208 #define alloc_arena_next(h) (((h)->sh)->alloc_arena_next)
209 #define alloc_arena_size(h) (((h)->sh)->alloc_arena_size)
210 #define alloc_arena_mapped(h) (((h)->sh)->alloc_arena_mapped)
211 #define alloc_arena(h) ((h)->alloc_arena)
212 #define CLIB_BIHASH_READY_MAGIC 0xFEEDFACE
213 #else
214 #undef alloc_arena_next
215 #undef alloc_arena_size
216 #undef alloc_arena_mapped
217 #undef alloc_arena
218 #undef CLIB_BIHASH_READY_MAGIC
219 #define alloc_arena_next(h) ((h)->sh.alloc_arena_next)
220 #define alloc_arena_size(h) ((h)->sh.alloc_arena_size)
221 #define alloc_arena_mapped(h) ((h)->sh.alloc_arena_mapped)
222 #define alloc_arena(h) ((h)->alloc_arena)
223 #define CLIB_BIHASH_READY_MAGIC 0
224 #endif
225
226 #ifndef BIHASH_STAT_IDS
227 #define BIHASH_STAT_IDS 1
228
229 #define foreach_bihash_stat                     \
230 _(alloc_add)                                    \
231 _(add)                                          \
232 _(split_add)                                    \
233 _(replace)                                      \
234 _(update)                                       \
235 _(del)                                          \
236 _(del_free)                                     \
237 _(linear)                                       \
238 _(resplit)                                      \
239 _(working_copy_lost)                            \
240 _(splits)                       /* must be last */
241
242 typedef enum
243 {
244 #define _(a) BIHASH_STAT_##a,
245   foreach_bihash_stat
246 #undef _
247     BIHASH_STAT_N_STATS,
248 } BVT (clib_bihash_stat_id);
249 #endif /* BIHASH_STAT_IDS */
250
251 static inline void BV (clib_bihash_increment_stat) (BVT (clib_bihash) * h,
252                                                     int stat_id, u64 count)
253 {
254 #if BIHASH_ENABLE_STATS
255   if (PREDICT_FALSE (h->inc_stats_callback != 0))
256     h->inc_stats_callback (h, stat_id, count);
257 #endif
258 }
259
260 #if BIHASH_ENABLE_STATS
261 static inline void BV (clib_bihash_set_stats_callback)
262   (BVT (clib_bihash) * h, void (*cb) (BVT (clib_bihash) *, int, u64),
263    void *ctx)
264 {
265   h->inc_stats_callback = cb;
266   h->inc_stats_context = ctx;
267 }
268 #endif
269
270
271 static inline void BV (clib_bihash_alloc_lock) (BVT (clib_bihash) * h)
272 {
273   while (__atomic_test_and_set (h->alloc_lock, __ATOMIC_ACQUIRE))
274     CLIB_PAUSE ();
275 }
276
277 static inline void BV (clib_bihash_alloc_unlock) (BVT (clib_bihash) * h)
278 {
279   __atomic_clear (h->alloc_lock, __ATOMIC_RELEASE);
280 }
281
282 static inline void BV (clib_bihash_lock_bucket) (BVT (clib_bihash_bucket) * b)
283 {
284   /* *INDENT-OFF* */
285   BVT (clib_bihash_bucket) mask = { .lock = 1 };
286   /* *INDENT-ON* */
287   u64 old;
288
289 try_again:
290   old = clib_atomic_fetch_or (&b->as_u64, mask.as_u64);
291
292   if (PREDICT_FALSE (old & mask.as_u64))
293     {
294       /* somebody else flipped the bit, try again */
295       CLIB_PAUSE ();
296       goto try_again;
297     }
298 }
299
300 static inline void BV (clib_bihash_unlock_bucket)
301   (BVT (clib_bihash_bucket) * b)
302 {
303   b->lock = 0;
304 }
305
306 static inline void *BV (clib_bihash_get_value) (BVT (clib_bihash) * h,
307                                                 uword offset)
308 {
309   u8 *hp = (u8 *) (uword) alloc_arena (h);
310   u8 *vp = hp + offset;
311
312   return (void *) vp;
313 }
314
315 static inline int BV (clib_bihash_bucket_is_empty)
316   (BVT (clib_bihash_bucket) * b)
317 {
318   /* Note: applied to locked buckets, test offset */
319   if (BIHASH_KVP_AT_BUCKET_LEVEL == 0)
320     return b->offset == 0;
321   else
322     return (b->log2_pages == 0 && b->refcnt == 1);
323 }
324
325 static inline uword BV (clib_bihash_get_offset) (BVT (clib_bihash) * h,
326                                                  void *v)
327 {
328   u8 *hp, *vp;
329
330   hp = (u8 *) (uword) alloc_arena (h);
331   vp = (u8 *) v;
332
333   return vp - hp;
334 }
335
336 void BV (clib_bihash_init)
337   (BVT (clib_bihash) * h, char *name, u32 nbuckets, uword memory_size);
338
339 void BV (clib_bihash_init2) (BVT (clib_bihash_init2_args) * a);
340
341 #if BIHASH_32_64_SVM
342 void BV (clib_bihash_initiator_init_svm)
343   (BVT (clib_bihash) * h, char *name, u32 nbuckets, u64 memory_size);
344 void BV (clib_bihash_responder_init_svm)
345   (BVT (clib_bihash) * h, char *name, int fd);
346 #endif
347
348 void BV (clib_bihash_set_kvp_format_fn) (BVT (clib_bihash) * h,
349                                          format_function_t * fmt_fn);
350
351 void BV (clib_bihash_free) (BVT (clib_bihash) * h);
352
353 int BV (clib_bihash_add_del) (BVT (clib_bihash) * h,
354                               BVT (clib_bihash_kv) * add_v, int is_add);
355 int BV (clib_bihash_add_or_overwrite_stale) (BVT (clib_bihash) * h,
356                                              BVT (clib_bihash_kv) * add_v,
357                                              int (*is_stale_cb) (BVT
358                                                                  (clib_bihash_kv)
359                                                                  *, void *),
360                                              void *arg);
361 int BV (clib_bihash_search) (BVT (clib_bihash) * h,
362                              BVT (clib_bihash_kv) * search_v,
363                              BVT (clib_bihash_kv) * return_v);
364
365 #define BIHASH_WALK_STOP 0
366 #define BIHASH_WALK_CONTINUE 1
367
368 typedef
369   int (*BV (clib_bihash_foreach_key_value_pair_cb)) (BVT (clib_bihash_kv) *,
370                                                      void *);
371 void BV (clib_bihash_foreach_key_value_pair) (BVT (clib_bihash) * h,
372                                               BV
373                                               (clib_bihash_foreach_key_value_pair_cb)
374                                               cb, void *arg);
375 void *clib_all_bihash_set_heap (void);
376 void clib_bihash_copied (void *dst, void *src);
377
378 format_function_t BV (format_bihash);
379 format_function_t BV (format_bihash_kvp);
380 format_function_t BV (format_bihash_lru);
381
382 static inline
383 BVT (clib_bihash_bucket) *
384 BV (clib_bihash_get_bucket) (BVT (clib_bihash) * h, u64 hash)
385 {
386 #if BIHASH_KVP_AT_BUCKET_LEVEL
387   uword offset;
388   offset = (hash & (h->nbuckets - 1));
389   offset = offset * (sizeof (BVT (clib_bihash_bucket))
390                      + (BIHASH_KVP_PER_PAGE * sizeof (BVT (clib_bihash_kv))));
391   return ((BVT (clib_bihash_bucket) *) (((u8 *) h->buckets) + offset));
392 #else
393   return h->buckets + (hash & (h->nbuckets - 1));
394 #endif
395 }
396
397 static inline int BV (clib_bihash_search_inline_with_hash)
398   (BVT (clib_bihash) * h, u64 hash, BVT (clib_bihash_kv) * key_result)
399 {
400   BVT (clib_bihash_value) * v;
401   BVT (clib_bihash_bucket) * b;
402   int i, limit;
403
404   /* *INDENT-OFF* */
405   static const BVT (clib_bihash_bucket) mask = {
406     .linear_search = 1,
407     .log2_pages = -1
408   };
409   /* *INDENT-ON* */
410
411 #if BIHASH_LAZY_INSTANTIATE
412   if (PREDICT_FALSE (h->instantiated == 0))
413     return -1;
414 #endif
415
416   b = BV (clib_bihash_get_bucket) (h, hash);
417
418   if (PREDICT_FALSE (BV (clib_bihash_bucket_is_empty) (b)))
419     return -1;
420
421   if (PREDICT_FALSE (b->lock))
422     {
423       volatile BVT (clib_bihash_bucket) * bv = b;
424       while (bv->lock)
425         CLIB_PAUSE ();
426     }
427
428   v = BV (clib_bihash_get_value) (h, b->offset);
429
430   /* If the bucket has unresolvable collisions, use linear search */
431   limit = BIHASH_KVP_PER_PAGE;
432
433   if (PREDICT_FALSE (b->as_u64 & mask.as_u64))
434     {
435       if (PREDICT_FALSE (b->linear_search))
436         limit <<= b->log2_pages;
437       else
438         v += extract_bits (hash, h->log2_nbuckets, b->log2_pages);
439     }
440
441   for (i = 0; i < limit; i++)
442     {
443       if (BV (clib_bihash_key_compare) (v->kvp[i].key, key_result->key))
444         {
445           *key_result = v->kvp[i];
446           return 0;
447         }
448     }
449   return -1;
450 }
451
452 static inline int BV (clib_bihash_search_inline)
453   (BVT (clib_bihash) * h, BVT (clib_bihash_kv) * key_result)
454 {
455   u64 hash;
456
457   hash = BV (clib_bihash_hash) (key_result);
458
459   return BV (clib_bihash_search_inline_with_hash) (h, hash, key_result);
460 }
461
462 static inline void BV (clib_bihash_prefetch_bucket)
463   (BVT (clib_bihash) * h, u64 hash)
464 {
465   CLIB_PREFETCH (BV (clib_bihash_get_bucket) (h, hash),
466                  BIHASH_BUCKET_PREFETCH_CACHE_LINES * CLIB_CACHE_LINE_BYTES,
467                  LOAD);
468 }
469
470 static inline void BV (clib_bihash_prefetch_data)
471   (BVT (clib_bihash) * h, u64 hash)
472 {
473   BVT (clib_bihash_value) * v;
474   BVT (clib_bihash_bucket) * b;
475
476 #if BIHASH_LAZY_INSTANTIATE
477   if (PREDICT_FALSE (h->instantiated == 0))
478     return;
479 #endif
480
481   b = BV (clib_bihash_get_bucket) (h, hash);
482
483   if (PREDICT_FALSE (BV (clib_bihash_bucket_is_empty) (b)))
484     return;
485
486   v = BV (clib_bihash_get_value) (h, b->offset);
487
488   if (PREDICT_FALSE (b->log2_pages && b->linear_search == 0))
489     v += extract_bits (hash, h->log2_nbuckets, b->log2_pages);
490
491   CLIB_PREFETCH (v, BIHASH_KVP_PER_PAGE * sizeof (BVT (clib_bihash_kv)),
492                  LOAD);
493 }
494
495 static inline int BV (clib_bihash_search_inline_2_with_hash)
496   (BVT (clib_bihash) * h,
497    u64 hash, BVT (clib_bihash_kv) * search_key, BVT (clib_bihash_kv) * valuep)
498 {
499   BVT (clib_bihash_value) * v;
500   BVT (clib_bihash_bucket) * b;
501   int i, limit;
502
503 /* *INDENT-OFF* */
504   static const BVT (clib_bihash_bucket) mask = {
505     .linear_search = 1,
506     .log2_pages = -1
507   };
508 /* *INDENT-ON* */
509
510   ASSERT (valuep);
511
512 #if BIHASH_LAZY_INSTANTIATE
513   if (PREDICT_FALSE (h->instantiated == 0))
514     return -1;
515 #endif
516
517   b = BV (clib_bihash_get_bucket) (h, hash);
518
519   if (PREDICT_FALSE (BV (clib_bihash_bucket_is_empty) (b)))
520     return -1;
521
522   if (PREDICT_FALSE (b->lock))
523     {
524       volatile BVT (clib_bihash_bucket) * bv = b;
525       while (bv->lock)
526         CLIB_PAUSE ();
527     }
528
529   v = BV (clib_bihash_get_value) (h, b->offset);
530
531   /* If the bucket has unresolvable collisions, use linear search */
532   limit = BIHASH_KVP_PER_PAGE;
533
534   if (PREDICT_FALSE (b->as_u64 & mask.as_u64))
535     {
536       if (PREDICT_FALSE (b->linear_search))
537         limit <<= b->log2_pages;
538       else
539         v += extract_bits (hash, h->log2_nbuckets, b->log2_pages);
540     }
541
542   for (i = 0; i < limit; i++)
543     {
544       if (BV (clib_bihash_key_compare) (v->kvp[i].key, search_key->key))
545         {
546           *valuep = v->kvp[i];
547           return 0;
548         }
549     }
550   return -1;
551 }
552
553 static inline int BV (clib_bihash_search_inline_2)
554   (BVT (clib_bihash) * h,
555    BVT (clib_bihash_kv) * search_key, BVT (clib_bihash_kv) * valuep)
556 {
557   u64 hash;
558
559   hash = BV (clib_bihash_hash) (search_key);
560
561   return BV (clib_bihash_search_inline_2_with_hash) (h, hash, search_key,
562                                                      valuep);
563 }
564
565
566 #endif /* __included_bihash_template_h__ */
567
568 /** @endcond */
569
570 /*
571  * fd.io coding-style-patch-verification: ON
572  *
573  * Local Variables:
574  * eval: (c-set-style "gnu")
575  * End:
576  */