rculfhash: set minimum table size, add todo about helping resize
[urcu.git] / rculfhash.c
1 /*
2 * rculfhash.c
3 *
4 * Userspace RCU library - Lock-Free Resizable RCU Hash Table
5 *
6 * Copyright 2010-2011 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23 /*
24 * Based on the following articles:
25 * - Ori Shalev and Nir Shavit. Split-ordered lists: Lock-free
26 * extensible hash tables. J. ACM 53, 3 (May 2006), 379-405.
27 * - Michael, M. M. High performance dynamic lock-free hash tables
28 * and list-based sets. In Proceedings of the fourteenth annual ACM
29 * symposium on Parallel algorithms and architectures, ACM Press,
30 * (2002), 73-82.
31 *
32 * Some specificities of this Lock-Free Resizable RCU Hash Table
33 * implementation:
34 *
35 * - RCU read-side critical section allows readers to perform hash
36 * table lookups and use the returned objects safely by delaying
37 * memory reclaim of a grace period.
38 * - Add and remove operations are lock-free, and do not need to
39 * allocate memory. They need to be executed within RCU read-side
40 * critical section to ensure the objects they read are valid and to
41 * deal with the cmpxchg ABA problem.
42 * - add and add_unique operations are supported. add_unique checks if
43 * the node key already exists in the hash table. It ensures no key
44 * duplicata exists.
45 * - The resize operation executes concurrently with add/remove/lookup.
46 * - Hash table nodes are contained within a split-ordered list. This
47 * list is ordered by incrementing reversed-bits-hash value.
48 * - An index of dummy nodes is kept. These dummy nodes are the hash
49 * table "buckets", and they are also chained together in the
50 * split-ordered list, which allows recursive expansion.
51 * - The resize operation for small tables only allows expanding the hash table.
52 * It is triggered automatically by detecting long chains in the add
53 * operation.
54 * - The resize operation for larger tables (and available through an
55 * API) allows both expanding and shrinking the hash table.
56 * - Per-CPU Split-counters are used to keep track of the number of
57 * nodes within the hash table for automatic resize triggering.
58 * - Resize operation initiated by long chain detection is executed by a
59 * call_rcu thread, which keeps lock-freedom of add and remove.
60 * - Resize operations are protected by a mutex.
61 * - The removal operation is split in two parts: first, a "removed"
62 * flag is set in the next pointer within the node to remove. Then,
63 * a "garbage collection" is performed in the bucket containing the
64 * removed node (from the start of the bucket up to the removed node).
65 * All encountered nodes with "removed" flag set in their next
66 * pointers are removed from the linked-list. If the cmpxchg used for
67 * removal fails (due to concurrent garbage-collection or concurrent
68 * add), we retry from the beginning of the bucket. This ensures that
69 * the node with "removed" flag set is removed from the hash table
70 * (not visible to lookups anymore) before the RCU read-side critical
71 * section held across removal ends. Furthermore, this ensures that
72 * the node with "removed" flag set is removed from the linked-list
73 * before its memory is reclaimed. Only the thread which removal
74 * successfully set the "removed" flag (with a cmpxchg) into a node's
75 * next pointer is considered to have succeeded its removal (and thus
76 * owns the node to reclaim). Because we garbage-collect starting from
77 * an invariant node (the start-of-bucket dummy node) up to the
78 * "removed" node (or find a reverse-hash that is higher), we are sure
79 * that a successful traversal of the chain leads to a chain that is
80 * present in the linked-list (the start node is never removed) and
81 * that is does not contain the "removed" node anymore, even if
82 * concurrent delete/add operations are changing the structure of the
83 * list concurrently.
84 * - The add operation performs gargage collection of buckets if it
85 * encounters nodes with removed flag set in the bucket where it wants
86 * to add its new node. This ensures lock-freedom of add operation by
87 * helping the remover unlink nodes from the list rather than to wait
88 * for it do to so.
89 * - A RCU "order table" indexed by log2(hash index) is copied and
90 * expanded by the resize operation. This order table allows finding
91 * the "dummy node" tables.
92 * - There is one dummy node table per hash index order. The size of
93 * each dummy node table is half the number of hashes contained in
94 * this order.
95 * - call_rcu is used to garbage-collect the old order table.
96 * - The per-order dummy node tables contain a compact version of the
97 * hash table nodes. These tables are invariant after they are
98 * populated into the hash table.
99 *
100 * A bit of ascii art explanation:
101 *
102 * Order index is the off-by-one compare to the actual power of 2 because
103 * we use index 0 to deal with the 0 special-case.
104 *
105 * This shows the nodes for a small table ordered by reversed bits:
106 *
107 * bits reverse
108 * 0 000 000
109 * 4 100 001
110 * 2 010 010
111 * 6 110 011
112 * 1 001 100
113 * 5 101 101
114 * 3 011 110
115 * 7 111 111
116 *
117 * This shows the nodes in order of non-reversed bits, linked by
118 * reversed-bit order.
119 *
120 * order bits reverse
121 * 0 0 000 000
122 * |
123 * 1 | 1 001 100 <-
124 * | | |
125 * 2 | | 2 010 010 |
126 * | | | 3 011 110 <- |
127 * | | | | | |
128 * 3 -> | | | 4 100 001 | |
129 * -> | | 5 101 101 |
130 * -> | 6 110 011
131 * -> 7 111 111
132 */
133
134 #define _LGPL_SOURCE
135 #include <stdlib.h>
136 #include <errno.h>
137 #include <assert.h>
138 #include <stdio.h>
139 #include <stdint.h>
140 #include <string.h>
141
142 #include "config.h"
143 #include <urcu.h>
144 #include <urcu-call-rcu.h>
145 #include <urcu/arch.h>
146 #include <urcu/uatomic.h>
147 #include <urcu/jhash.h>
148 #include <urcu/compiler.h>
149 #include <urcu/rculfhash.h>
150 #include <stdio.h>
151 #include <pthread.h>
152
153 #ifdef DEBUG
154 #define dbg_printf(fmt, args...) printf("[debug rculfhash] " fmt, ## args)
155 #else
156 #define dbg_printf(fmt, args...)
157 #endif
158
159 /*
160 * Per-CPU split-counters lazily update the global counter each 1024
161 * addition/removal. It automatically keeps track of resize required.
162 * We use the bucket length as indicator for need to expand for small
163 * tables and machines lacking per-cpu data suppport.
164 */
165 #define COUNT_COMMIT_ORDER 10
166 #define CHAIN_LEN_TARGET 1
167 #define CHAIN_LEN_RESIZE_THRESHOLD 3
168
169 /*
170 * Define the minimum table size. Protects against hash table resize overload
171 * when too many entries are added quickly before the resize can complete.
172 * This is especially the case if the table could be shrinked to a size of 1.
173 * TODO: we might want to make the add/remove operations help the resize to
174 * add or remove dummy nodes when a resize is ongoing to ensure upper-bound on
175 * chain length.
176 */
177 #define MIN_TABLE_SIZE 128
178
179 #ifndef max
180 #define max(a, b) ((a) > (b) ? (a) : (b))
181 #endif
182
183 /*
184 * The removed flag needs to be updated atomically with the pointer.
185 * The dummy flag does not require to be updated atomically with the
186 * pointer, but it is added as a pointer low bit flag to save space.
187 */
188 #define REMOVED_FLAG (1UL << 0)
189 #define DUMMY_FLAG (1UL << 1)
190 #define FLAGS_MASK ((1UL << 2) - 1)
191
192 struct ht_items_count {
193 unsigned long add, remove;
194 } __attribute__((aligned(CAA_CACHE_LINE_SIZE)));
195
196 struct rcu_level {
197 struct rcu_head head;
198 struct _cds_lfht_node nodes[0];
199 };
200
201 struct rcu_table {
202 unsigned long size; /* always a power of 2 */
203 unsigned long resize_target;
204 int resize_initiated;
205 struct rcu_head head;
206 struct rcu_level *tbl[0];
207 };
208
209 struct cds_lfht {
210 struct rcu_table *t; /* shared */
211 cds_lfht_hash_fct hash_fct;
212 cds_lfht_compare_fct compare_fct;
213 unsigned long hash_seed;
214 pthread_mutex_t resize_mutex; /* resize mutex: add/del mutex */
215 unsigned int in_progress_resize, in_progress_destroy;
216 void (*cds_lfht_call_rcu)(struct rcu_head *head,
217 void (*func)(struct rcu_head *head));
218 void (*cds_lfht_synchronize_rcu)(void);
219 unsigned long count; /* global approximate item count */
220 struct ht_items_count *percpu_count; /* per-cpu item count */
221 };
222
223 struct rcu_resize_work {
224 struct rcu_head head;
225 struct cds_lfht *ht;
226 };
227
228 /*
229 * Algorithm to reverse bits in a word by lookup table, extended to
230 * 64-bit words.
231 * Source:
232 * http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
233 * Originally from Public Domain.
234 */
235
236 static const uint8_t BitReverseTable256[256] =
237 {
238 #define R2(n) (n), (n) + 2*64, (n) + 1*64, (n) + 3*64
239 #define R4(n) R2(n), R2((n) + 2*16), R2((n) + 1*16), R2((n) + 3*16)
240 #define R6(n) R4(n), R4((n) + 2*4 ), R4((n) + 1*4 ), R4((n) + 3*4 )
241 R6(0), R6(2), R6(1), R6(3)
242 };
243 #undef R2
244 #undef R4
245 #undef R6
246
247 static
248 uint8_t bit_reverse_u8(uint8_t v)
249 {
250 return BitReverseTable256[v];
251 }
252
253 static __attribute__((unused))
254 uint32_t bit_reverse_u32(uint32_t v)
255 {
256 return ((uint32_t) bit_reverse_u8(v) << 24) |
257 ((uint32_t) bit_reverse_u8(v >> 8) << 16) |
258 ((uint32_t) bit_reverse_u8(v >> 16) << 8) |
259 ((uint32_t) bit_reverse_u8(v >> 24));
260 }
261
262 static __attribute__((unused))
263 uint64_t bit_reverse_u64(uint64_t v)
264 {
265 return ((uint64_t) bit_reverse_u8(v) << 56) |
266 ((uint64_t) bit_reverse_u8(v >> 8) << 48) |
267 ((uint64_t) bit_reverse_u8(v >> 16) << 40) |
268 ((uint64_t) bit_reverse_u8(v >> 24) << 32) |
269 ((uint64_t) bit_reverse_u8(v >> 32) << 24) |
270 ((uint64_t) bit_reverse_u8(v >> 40) << 16) |
271 ((uint64_t) bit_reverse_u8(v >> 48) << 8) |
272 ((uint64_t) bit_reverse_u8(v >> 56));
273 }
274
275 static
276 unsigned long bit_reverse_ulong(unsigned long v)
277 {
278 #if (CAA_BITS_PER_LONG == 32)
279 return bit_reverse_u32(v);
280 #else
281 return bit_reverse_u64(v);
282 #endif
283 }
284
285 /*
286 * fls: returns the position of the most significant bit.
287 * Returns 0 if no bit is set, else returns the position of the most
288 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
289 */
290 #if defined(__i386) || defined(__x86_64)
291 static inline
292 unsigned int fls_u32(uint32_t x)
293 {
294 int r;
295
296 asm("bsrl %1,%0\n\t"
297 "jnz 1f\n\t"
298 "movl $-1,%0\n\t"
299 "1:\n\t"
300 : "=r" (r) : "rm" (x));
301 return r + 1;
302 }
303 #define HAS_FLS_U32
304 #endif
305
306 #if defined(__x86_64)
307 static inline
308 unsigned int fls_u64(uint64_t x)
309 {
310 long r;
311
312 asm("bsrq %1,%0\n\t"
313 "jnz 1f\n\t"
314 "movq $-1,%0\n\t"
315 "1:\n\t"
316 : "=r" (r) : "rm" (x));
317 return r + 1;
318 }
319 #define HAS_FLS_U64
320 #endif
321
322 #ifndef HAS_FLS_U64
323 static __attribute__((unused))
324 unsigned int fls_u64(uint64_t x)
325 {
326 unsigned int r = 64;
327
328 if (!x)
329 return 0;
330
331 if (!(x & 0xFFFFFFFF00000000ULL)) {
332 x <<= 32;
333 r -= 32;
334 }
335 if (!(x & 0xFFFF000000000000ULL)) {
336 x <<= 16;
337 r -= 16;
338 }
339 if (!(x & 0xFF00000000000000ULL)) {
340 x <<= 8;
341 r -= 8;
342 }
343 if (!(x & 0xF000000000000000ULL)) {
344 x <<= 4;
345 r -= 4;
346 }
347 if (!(x & 0xC000000000000000ULL)) {
348 x <<= 2;
349 r -= 2;
350 }
351 if (!(x & 0x8000000000000000ULL)) {
352 x <<= 1;
353 r -= 1;
354 }
355 return r;
356 }
357 #endif
358
359 #ifndef HAS_FLS_U32
360 static __attribute__((unused))
361 unsigned int fls_u32(uint32_t x)
362 {
363 unsigned int r = 32;
364
365 if (!x)
366 return 0;
367 if (!(x & 0xFFFF0000U)) {
368 x <<= 16;
369 r -= 16;
370 }
371 if (!(x & 0xFF000000U)) {
372 x <<= 8;
373 r -= 8;
374 }
375 if (!(x & 0xF0000000U)) {
376 x <<= 4;
377 r -= 4;
378 }
379 if (!(x & 0xC0000000U)) {
380 x <<= 2;
381 r -= 2;
382 }
383 if (!(x & 0x80000000U)) {
384 x <<= 1;
385 r -= 1;
386 }
387 return r;
388 }
389 #endif
390
391 unsigned int fls_ulong(unsigned long x)
392 {
393 #if (CAA_BITS_PER_lONG == 32)
394 return fls_u32(x);
395 #else
396 return fls_u64(x);
397 #endif
398 }
399
400 int get_count_order_u32(uint32_t x)
401 {
402 int order;
403
404 order = fls_u32(x) - 1;
405 if (x & (x - 1))
406 order++;
407 return order;
408 }
409
410 int get_count_order_ulong(unsigned long x)
411 {
412 int order;
413
414 order = fls_ulong(x) - 1;
415 if (x & (x - 1))
416 order++;
417 return order;
418 }
419
420 static
421 void cds_lfht_resize_lazy(struct cds_lfht *ht, struct rcu_table *t, int growth);
422
423 /*
424 * If the sched_getcpu() and sysconf(_SC_NPROCESSORS_CONF) calls are
425 * available, then we support hash table item accounting.
426 * In the unfortunate event the number of CPUs reported would be
427 * inaccurate, we use modulo arithmetic on the number of CPUs we got.
428 */
429 #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF)
430
431 static
432 void cds_lfht_resize_lazy_count(struct cds_lfht *ht, struct rcu_table *t,
433 unsigned long count);
434
435 static long nr_cpus_mask = -1;
436
437 static
438 struct ht_items_count *alloc_per_cpu_items_count(void)
439 {
440 struct ht_items_count *count;
441
442 switch (nr_cpus_mask) {
443 case -2:
444 return NULL;
445 case -1:
446 {
447 long maxcpus;
448
449 maxcpus = sysconf(_SC_NPROCESSORS_CONF);
450 if (maxcpus <= 0) {
451 nr_cpus_mask = -2;
452 return NULL;
453 }
454 /*
455 * round up number of CPUs to next power of two, so we
456 * can use & for modulo.
457 */
458 maxcpus = 1UL << get_count_order_ulong(maxcpus);
459 nr_cpus_mask = maxcpus - 1;
460 }
461 /* Fall-through */
462 default:
463 return calloc(nr_cpus_mask + 1, sizeof(*count));
464 }
465 }
466
467 static
468 void free_per_cpu_items_count(struct ht_items_count *count)
469 {
470 free(count);
471 }
472
473 static
474 int ht_get_cpu(void)
475 {
476 int cpu;
477
478 assert(nr_cpus_mask >= 0);
479 cpu = sched_getcpu();
480 if (unlikely(cpu < 0))
481 return cpu;
482 else
483 return cpu & nr_cpus_mask;
484 }
485
486 static
487 void ht_count_add(struct cds_lfht *ht, struct rcu_table *t)
488 {
489 unsigned long percpu_count;
490 int cpu;
491
492 if (unlikely(!ht->percpu_count))
493 return;
494 cpu = ht_get_cpu();
495 if (unlikely(cpu < 0))
496 return;
497 percpu_count = uatomic_add_return(&ht->percpu_count[cpu].add, 1);
498 if (unlikely(!(percpu_count & ((1UL << COUNT_COMMIT_ORDER) - 1)))) {
499 unsigned long count;
500
501 dbg_printf("add percpu %lu\n", percpu_count);
502 count = uatomic_add_return(&ht->count,
503 1UL << COUNT_COMMIT_ORDER);
504 /* If power of 2 */
505 if (!(count & (count - 1))) {
506 if ((count >> CHAIN_LEN_RESIZE_THRESHOLD)
507 < t->size)
508 return;
509 dbg_printf("add set global %lu\n", count);
510 cds_lfht_resize_lazy_count(ht, t,
511 count >> (CHAIN_LEN_TARGET - 1));
512 }
513 }
514 }
515
516 static
517 void ht_count_remove(struct cds_lfht *ht, struct rcu_table *t)
518 {
519 unsigned long percpu_count;
520 int cpu;
521
522 if (unlikely(!ht->percpu_count))
523 return;
524 cpu = ht_get_cpu();
525 if (unlikely(cpu < 0))
526 return;
527 percpu_count = uatomic_add_return(&ht->percpu_count[cpu].remove, -1);
528 if (unlikely(!(percpu_count & ((1UL << COUNT_COMMIT_ORDER) - 1)))) {
529 unsigned long count;
530
531 dbg_printf("remove percpu %lu\n", percpu_count);
532 count = uatomic_add_return(&ht->count,
533 -(1UL << COUNT_COMMIT_ORDER));
534 /* If power of 2 */
535 if (!(count & (count - 1))) {
536 if ((count >> CHAIN_LEN_RESIZE_THRESHOLD)
537 >= t->size)
538 return;
539 dbg_printf("remove set global %lu\n", count);
540 cds_lfht_resize_lazy_count(ht, t,
541 count >> (CHAIN_LEN_TARGET - 1));
542 }
543 }
544 }
545
546 #else /* #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF) */
547
548 static const long nr_cpus_mask = -1;
549
550 static
551 struct ht_items_count *alloc_per_cpu_items_count(void)
552 {
553 return NULL;
554 }
555
556 static
557 void free_per_cpu_items_count(struct ht_items_count *count)
558 {
559 }
560
561 static
562 void ht_count_add(struct cds_lfht *ht, struct rcu_table *t)
563 {
564 }
565
566 static
567 void ht_count_remove(struct cds_lfht *ht, struct rcu_table *t)
568 {
569 }
570
571 #endif /* #else #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF) */
572
573
574 static
575 void check_resize(struct cds_lfht *ht, struct rcu_table *t,
576 uint32_t chain_len)
577 {
578 unsigned long count;
579
580 count = uatomic_read(&ht->count);
581 /*
582 * Use bucket-local length for small table expand and for
583 * environments lacking per-cpu data support.
584 */
585 if (count >= (1UL << COUNT_COMMIT_ORDER))
586 return;
587 if (chain_len > 100)
588 dbg_printf("WARNING: large chain length: %u.\n",
589 chain_len);
590 if (chain_len >= CHAIN_LEN_RESIZE_THRESHOLD)
591 cds_lfht_resize_lazy(ht, t,
592 get_count_order_u32(chain_len - (CHAIN_LEN_TARGET - 1)));
593 }
594
595 static
596 struct cds_lfht_node *clear_flag(struct cds_lfht_node *node)
597 {
598 return (struct cds_lfht_node *) (((unsigned long) node) & ~FLAGS_MASK);
599 }
600
601 static
602 int is_removed(struct cds_lfht_node *node)
603 {
604 return ((unsigned long) node) & REMOVED_FLAG;
605 }
606
607 static
608 struct cds_lfht_node *flag_removed(struct cds_lfht_node *node)
609 {
610 return (struct cds_lfht_node *) (((unsigned long) node) | REMOVED_FLAG);
611 }
612
613 static
614 int is_dummy(struct cds_lfht_node *node)
615 {
616 return ((unsigned long) node) & DUMMY_FLAG;
617 }
618
619 static
620 struct cds_lfht_node *flag_dummy(struct cds_lfht_node *node)
621 {
622 return (struct cds_lfht_node *) (((unsigned long) node) | DUMMY_FLAG);
623 }
624
625 static
626 unsigned long _uatomic_max(unsigned long *ptr, unsigned long v)
627 {
628 unsigned long old1, old2;
629
630 old1 = uatomic_read(ptr);
631 do {
632 old2 = old1;
633 if (old2 >= v)
634 return old2;
635 } while ((old1 = uatomic_cmpxchg(ptr, old2, v)) != old2);
636 return v;
637 }
638
639 static
640 void cds_lfht_free_table_cb(struct rcu_head *head)
641 {
642 struct rcu_table *t =
643 caa_container_of(head, struct rcu_table, head);
644 free(t);
645 }
646
647 static
648 void cds_lfht_free_level(struct rcu_head *head)
649 {
650 struct rcu_level *l =
651 caa_container_of(head, struct rcu_level, head);
652 free(l);
653 }
654
655 /*
656 * Remove all logically deleted nodes from a bucket up to a certain node key.
657 */
658 static
659 void _cds_lfht_gc_bucket(struct cds_lfht_node *dummy, struct cds_lfht_node *node)
660 {
661 struct cds_lfht_node *iter_prev, *iter, *next, *new_next;
662
663 for (;;) {
664 iter_prev = dummy;
665 /* We can always skip the dummy node initially */
666 iter = rcu_dereference(iter_prev->p.next);
667 assert(iter_prev->p.reverse_hash <= node->p.reverse_hash);
668 for (;;) {
669 if (unlikely(!clear_flag(iter)))
670 return;
671 if (likely(clear_flag(iter)->p.reverse_hash > node->p.reverse_hash))
672 return;
673 next = rcu_dereference(clear_flag(iter)->p.next);
674 if (likely(is_removed(next)))
675 break;
676 iter_prev = clear_flag(iter);
677 iter = next;
678 }
679 assert(!is_removed(iter));
680 if (is_dummy(iter))
681 new_next = flag_dummy(clear_flag(next));
682 else
683 new_next = clear_flag(next);
684 (void) uatomic_cmpxchg(&iter_prev->p.next, iter, new_next);
685 }
686 }
687
688 static
689 struct cds_lfht_node *_cds_lfht_add(struct cds_lfht *ht, struct rcu_table *t,
690 struct cds_lfht_node *node, int unique, int dummy)
691 {
692 struct cds_lfht_node *iter_prev, *iter, *next, *new_node, *new_next,
693 *dummy_node;
694 struct _cds_lfht_node *lookup;
695 unsigned long hash, index, order;
696
697 if (!t->size) {
698 assert(dummy);
699 node->p.next = flag_dummy(NULL);
700 return node; /* Initial first add (head) */
701 }
702 hash = bit_reverse_ulong(node->p.reverse_hash);
703 for (;;) {
704 uint32_t chain_len = 0;
705
706 /*
707 * iter_prev points to the non-removed node prior to the
708 * insert location.
709 */
710 index = hash & (t->size - 1);
711 order = get_count_order_ulong(index + 1);
712 lookup = &t->tbl[order]->nodes[index & ((!order ? 0 : (1UL << (order - 1))) - 1)];
713 iter_prev = (struct cds_lfht_node *) lookup;
714 /* We can always skip the dummy node initially */
715 iter = rcu_dereference(iter_prev->p.next);
716 assert(iter_prev->p.reverse_hash <= node->p.reverse_hash);
717 for (;;) {
718 if (unlikely(!clear_flag(iter)))
719 goto insert;
720 if (likely(clear_flag(iter)->p.reverse_hash > node->p.reverse_hash))
721 goto insert;
722 next = rcu_dereference(clear_flag(iter)->p.next);
723 if (unlikely(is_removed(next)))
724 goto gc_node;
725 if (unique
726 && !is_dummy(next)
727 && !ht->compare_fct(node->key, node->key_len,
728 clear_flag(iter)->key,
729 clear_flag(iter)->key_len))
730 return clear_flag(iter);
731 /* Only account for identical reverse hash once */
732 if (iter_prev->p.reverse_hash != clear_flag(iter)->p.reverse_hash
733 && !is_dummy(next))
734 check_resize(ht, t, ++chain_len);
735 iter_prev = clear_flag(iter);
736 iter = next;
737 }
738 insert:
739 assert(node != clear_flag(iter));
740 assert(!is_removed(iter_prev));
741 assert(iter_prev != node);
742 if (!dummy)
743 node->p.next = clear_flag(iter);
744 else
745 node->p.next = flag_dummy(clear_flag(iter));
746 if (is_dummy(iter))
747 new_node = flag_dummy(node);
748 else
749 new_node = node;
750 if (uatomic_cmpxchg(&iter_prev->p.next, iter,
751 new_node) != iter)
752 continue; /* retry */
753 else
754 goto gc_end;
755 gc_node:
756 assert(!is_removed(iter));
757 if (is_dummy(iter))
758 new_next = flag_dummy(clear_flag(next));
759 else
760 new_next = clear_flag(next);
761 (void) uatomic_cmpxchg(&iter_prev->p.next, iter, new_next);
762 /* retry */
763 }
764 gc_end:
765 /* Garbage collect logically removed nodes in the bucket */
766 index = hash & (t->size - 1);
767 order = get_count_order_ulong(index + 1);
768 lookup = &t->tbl[order]->nodes[index & (!order ? 0 : ((1UL << (order - 1)) - 1))];
769 dummy_node = (struct cds_lfht_node *) lookup;
770 _cds_lfht_gc_bucket(dummy_node, node);
771 return node;
772 }
773
774 static
775 int _cds_lfht_remove(struct cds_lfht *ht, struct rcu_table *t,
776 struct cds_lfht_node *node, int dummy_removal)
777 {
778 struct cds_lfht_node *dummy, *next, *old;
779 struct _cds_lfht_node *lookup;
780 int flagged = 0;
781 unsigned long hash, index, order;
782
783 /* logically delete the node */
784 old = rcu_dereference(node->p.next);
785 do {
786 next = old;
787 if (unlikely(is_removed(next)))
788 goto end;
789 if (dummy_removal)
790 assert(is_dummy(next));
791 else
792 assert(!is_dummy(next));
793 old = uatomic_cmpxchg(&node->p.next, next,
794 flag_removed(next));
795 } while (old != next);
796
797 /* We performed the (logical) deletion. */
798 flagged = 1;
799
800 if (dummy_removal)
801 node = clear_flag(node);
802
803 /*
804 * Ensure that the node is not visible to readers anymore: lookup for
805 * the node, and remove it (along with any other logically removed node)
806 * if found.
807 */
808 hash = bit_reverse_ulong(node->p.reverse_hash);
809 assert(t->size > 0);
810 index = hash & (t->size - 1);
811 order = get_count_order_ulong(index + 1);
812 lookup = &t->tbl[order]->nodes[index & (!order ? 0 : ((1UL << (order - 1)) - 1))];
813 dummy = (struct cds_lfht_node *) lookup;
814 _cds_lfht_gc_bucket(dummy, node);
815 end:
816 /*
817 * Only the flagging action indicated that we (and no other)
818 * removed the node from the hash.
819 */
820 if (flagged) {
821 assert(is_removed(rcu_dereference(node->p.next)));
822 return 0;
823 } else
824 return -ENOENT;
825 }
826
827 static
828 void init_table(struct cds_lfht *ht, struct rcu_table *t,
829 unsigned long first_order, unsigned long len_order)
830 {
831 unsigned long i, end_order;
832
833 dbg_printf("init table: first_order %lu end_order %lu\n",
834 first_order, first_order + len_order);
835 end_order = first_order + len_order;
836 t->size = !first_order ? 0 : (1UL << (first_order - 1));
837 for (i = first_order; i < end_order; i++) {
838 unsigned long j, len;
839
840 len = !i ? 1 : 1UL << (i - 1);
841 dbg_printf("init order %lu len: %lu\n", i, len);
842 t->tbl[i] = calloc(1, sizeof(struct rcu_level)
843 + (len * sizeof(struct _cds_lfht_node)));
844 for (j = 0; j < len; j++) {
845 struct cds_lfht_node *new_node =
846 (struct cds_lfht_node *) &t->tbl[i]->nodes[j];
847
848 dbg_printf("init entry: i %lu j %lu hash %lu\n",
849 i, j, !i ? 0 : (1UL << (i - 1)) + j);
850 new_node->p.reverse_hash =
851 bit_reverse_ulong(!i ? 0 : (1UL << (i - 1)) + j);
852 (void) _cds_lfht_add(ht, t, new_node, 0, 1);
853 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
854 break;
855 }
856 /* Update table size */
857 t->size = !i ? 1 : (1UL << i);
858 dbg_printf("init new size: %lu\n", t->size);
859 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
860 break;
861 }
862 t->resize_target = t->size;
863 t->resize_initiated = 0;
864 }
865
866 static
867 void fini_table(struct cds_lfht *ht, struct rcu_table *t,
868 unsigned long first_order, unsigned long len_order)
869 {
870 long i, end_order;
871
872 dbg_printf("fini table: first_order %lu end_order %lu\n",
873 first_order, first_order + len_order);
874 end_order = first_order + len_order;
875 assert(first_order > 0);
876 assert(t->size == (1UL << (end_order - 1)));
877 for (i = end_order - 1; i >= first_order; i--) {
878 unsigned long j, len;
879
880 len = !i ? 1 : 1UL << (i - 1);
881 dbg_printf("fini order %lu len: %lu\n", i, len);
882 /* Update table size */
883 t->size = 1UL << (i - 1);
884 /* Unlink */
885 for (j = 0; j < len; j++) {
886 struct cds_lfht_node *new_node =
887 (struct cds_lfht_node *) &t->tbl[i]->nodes[j];
888
889 dbg_printf("fini entry: i %lu j %lu hash %lu\n",
890 i, j, !i ? 0 : (1UL << (i - 1)) + j);
891 new_node->p.reverse_hash =
892 bit_reverse_ulong(!i ? 0 : (1UL << (i - 1)) + j);
893 (void) _cds_lfht_remove(ht, t, new_node, 1);
894 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
895 break;
896 }
897 ht->cds_lfht_call_rcu(&t->tbl[i]->head, cds_lfht_free_level);
898 dbg_printf("fini new size: %lu\n", t->size);
899 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
900 break;
901 }
902 t->resize_target = t->size;
903 t->resize_initiated = 0;
904 }
905
906 struct cds_lfht *cds_lfht_new(cds_lfht_hash_fct hash_fct,
907 cds_lfht_compare_fct compare_fct,
908 unsigned long hash_seed,
909 unsigned long init_size,
910 void (*cds_lfht_call_rcu)(struct rcu_head *head,
911 void (*func)(struct rcu_head *head)),
912 void (*cds_lfht_synchronize_rcu)(void))
913 {
914 struct cds_lfht *ht;
915 unsigned long order;
916
917 /* init_size must be power of two */
918 if (init_size && (init_size & (init_size - 1)))
919 return NULL;
920 ht = calloc(1, sizeof(struct cds_lfht));
921 ht->hash_fct = hash_fct;
922 ht->compare_fct = compare_fct;
923 ht->hash_seed = hash_seed;
924 ht->cds_lfht_call_rcu = cds_lfht_call_rcu;
925 ht->cds_lfht_synchronize_rcu = cds_lfht_synchronize_rcu;
926 ht->in_progress_resize = 0;
927 ht->percpu_count = alloc_per_cpu_items_count();
928 /* this mutex should not nest in read-side C.S. */
929 pthread_mutex_init(&ht->resize_mutex, NULL);
930 order = get_count_order_ulong(max(init_size, MIN_TABLE_SIZE)) + 1;
931 ht->t = calloc(1, sizeof(struct cds_lfht)
932 + (order * sizeof(struct rcu_level *)));
933 ht->t->size = 0;
934 pthread_mutex_lock(&ht->resize_mutex);
935 init_table(ht, ht->t, 0, order);
936 pthread_mutex_unlock(&ht->resize_mutex);
937 return ht;
938 }
939
940 struct cds_lfht_node *cds_lfht_lookup(struct cds_lfht *ht, void *key, size_t key_len)
941 {
942 struct rcu_table *t;
943 struct cds_lfht_node *node, *next;
944 struct _cds_lfht_node *lookup;
945 unsigned long hash, reverse_hash, index, order;
946
947 hash = ht->hash_fct(key, key_len, ht->hash_seed);
948 reverse_hash = bit_reverse_ulong(hash);
949
950 t = rcu_dereference(ht->t);
951 index = hash & (t->size - 1);
952 order = get_count_order_ulong(index + 1);
953 lookup = &t->tbl[order]->nodes[index & (!order ? 0 : ((1UL << (order - 1))) - 1)];
954 dbg_printf("lookup hash %lu index %lu order %lu aridx %lu\n",
955 hash, index, order, index & (!order ? 0 : ((1UL << (order - 1)) - 1)));
956 node = (struct cds_lfht_node *) lookup;
957 for (;;) {
958 if (unlikely(!node))
959 break;
960 if (unlikely(node->p.reverse_hash > reverse_hash)) {
961 node = NULL;
962 break;
963 }
964 next = rcu_dereference(node->p.next);
965 if (likely(!is_removed(next))
966 && !is_dummy(next)
967 && likely(!ht->compare_fct(node->key, node->key_len, key, key_len))) {
968 break;
969 }
970 node = clear_flag(next);
971 }
972 assert(!node || !is_dummy(rcu_dereference(node->p.next)));
973 return node;
974 }
975
976 struct cds_lfht_node *cds_lfht_next(struct cds_lfht *ht,
977 struct cds_lfht_node *node)
978 {
979 struct cds_lfht_node *next;
980 unsigned long reverse_hash;
981 void *key;
982 size_t key_len;
983
984 reverse_hash = node->p.reverse_hash;
985 key = node->key;
986 key_len = node->key_len;
987 next = rcu_dereference(node->p.next);
988 node = clear_flag(next);
989
990 for (;;) {
991 if (unlikely(!node))
992 break;
993 if (unlikely(node->p.reverse_hash > reverse_hash)) {
994 node = NULL;
995 break;
996 }
997 next = rcu_dereference(node->p.next);
998 if (likely(!is_removed(next))
999 && !is_dummy(next)
1000 && likely(!ht->compare_fct(node->key, node->key_len, key, key_len))) {
1001 break;
1002 }
1003 node = clear_flag(next);
1004 }
1005 assert(!node || !is_dummy(rcu_dereference(node->p.next)));
1006 return node;
1007 }
1008
1009 void cds_lfht_add(struct cds_lfht *ht, struct cds_lfht_node *node)
1010 {
1011 struct rcu_table *t;
1012 unsigned long hash;
1013
1014 hash = ht->hash_fct(node->key, node->key_len, ht->hash_seed);
1015 node->p.reverse_hash = bit_reverse_ulong((unsigned long) hash);
1016
1017 t = rcu_dereference(ht->t);
1018 (void) _cds_lfht_add(ht, t, node, 0, 0);
1019 ht_count_add(ht, t);
1020 }
1021
1022 struct cds_lfht_node *cds_lfht_add_unique(struct cds_lfht *ht,
1023 struct cds_lfht_node *node)
1024 {
1025 struct rcu_table *t;
1026 unsigned long hash;
1027 struct cds_lfht_node *ret;
1028
1029 hash = ht->hash_fct(node->key, node->key_len, ht->hash_seed);
1030 node->p.reverse_hash = bit_reverse_ulong((unsigned long) hash);
1031
1032 t = rcu_dereference(ht->t);
1033 ret = _cds_lfht_add(ht, t, node, 1, 0);
1034 if (ret != node)
1035 ht_count_add(ht, t);
1036 return ret;
1037 }
1038
1039 int cds_lfht_remove(struct cds_lfht *ht, struct cds_lfht_node *node)
1040 {
1041 struct rcu_table *t;
1042 int ret;
1043
1044 t = rcu_dereference(ht->t);
1045 ret = _cds_lfht_remove(ht, t, node, 0);
1046 if (!ret)
1047 ht_count_remove(ht, t);
1048 return ret;
1049 }
1050
1051 static
1052 int cds_lfht_delete_dummy(struct cds_lfht *ht)
1053 {
1054 struct rcu_table *t;
1055 struct cds_lfht_node *node;
1056 struct _cds_lfht_node *lookup;
1057 unsigned long order, i;
1058
1059 t = ht->t;
1060 /* Check that the table is empty */
1061 lookup = &t->tbl[0]->nodes[0];
1062 node = (struct cds_lfht_node *) lookup;
1063 do {
1064 node = clear_flag(node)->p.next;
1065 if (!is_dummy(node))
1066 return -EPERM;
1067 assert(!is_removed(node));
1068 } while (clear_flag(node));
1069 /* Internal sanity check: all nodes left should be dummy */
1070 for (order = 0; order < get_count_order_ulong(t->size) + 1; order++) {
1071 unsigned long len;
1072
1073 len = !order ? 1 : 1UL << (order - 1);
1074 for (i = 0; i < len; i++) {
1075 dbg_printf("delete order %lu i %lu hash %lu\n",
1076 order, i,
1077 bit_reverse_ulong(t->tbl[order]->nodes[i].reverse_hash));
1078 assert(is_dummy(t->tbl[order]->nodes[i].next));
1079 }
1080 free(t->tbl[order]);
1081 }
1082 return 0;
1083 }
1084
1085 /*
1086 * Should only be called when no more concurrent readers nor writers can
1087 * possibly access the table.
1088 */
1089 int cds_lfht_destroy(struct cds_lfht *ht)
1090 {
1091 int ret;
1092
1093 /* Wait for in-flight resize operations to complete */
1094 CMM_STORE_SHARED(ht->in_progress_destroy, 1);
1095 while (uatomic_read(&ht->in_progress_resize))
1096 poll(NULL, 0, 100); /* wait for 100ms */
1097 ret = cds_lfht_delete_dummy(ht);
1098 if (ret)
1099 return ret;
1100 free(ht->t);
1101 free_per_cpu_items_count(ht->percpu_count);
1102 free(ht);
1103 return ret;
1104 }
1105
1106 void cds_lfht_count_nodes(struct cds_lfht *ht,
1107 unsigned long *count,
1108 unsigned long *removed)
1109 {
1110 struct rcu_table *t;
1111 struct cds_lfht_node *node, *next;
1112 struct _cds_lfht_node *lookup;
1113 unsigned long nr_dummy = 0;
1114
1115 *count = 0;
1116 *removed = 0;
1117
1118 t = rcu_dereference(ht->t);
1119 /* Count non-dummy nodes in the table */
1120 lookup = &t->tbl[0]->nodes[0];
1121 node = (struct cds_lfht_node *) lookup;
1122 do {
1123 next = rcu_dereference(node->p.next);
1124 if (is_removed(next)) {
1125 assert(!is_dummy(next));
1126 (*removed)++;
1127 } else if (!is_dummy(next))
1128 (*count)++;
1129 else
1130 (nr_dummy)++;
1131 node = clear_flag(next);
1132 } while (node);
1133 dbg_printf("number of dummy nodes: %lu\n", nr_dummy);
1134 }
1135
1136 /* called with resize mutex held */
1137 static
1138 void _do_cds_lfht_grow(struct cds_lfht *ht, struct rcu_table *old_t,
1139 unsigned long old_size, unsigned long new_size)
1140 {
1141 unsigned long old_order, new_order;
1142 struct rcu_table *new_t;
1143
1144 old_order = get_count_order_ulong(old_size) + 1;
1145 new_order = get_count_order_ulong(new_size) + 1;
1146 printf("resize from %lu (order %lu) to %lu (order %lu) buckets\n",
1147 old_size, old_order, new_size, new_order);
1148 new_t = malloc(sizeof(struct cds_lfht)
1149 + (new_order * sizeof(struct rcu_level *)));
1150 assert(new_size > old_size);
1151 memcpy(&new_t->tbl, &old_t->tbl,
1152 old_order * sizeof(struct rcu_level *));
1153 init_table(ht, new_t, old_order, new_order - old_order);
1154 /* Changing table and size atomically wrt lookups */
1155 rcu_assign_pointer(ht->t, new_t);
1156 ht->cds_lfht_call_rcu(&old_t->head, cds_lfht_free_table_cb);
1157 }
1158
1159 /* called with resize mutex held */
1160 static
1161 void _do_cds_lfht_shrink(struct cds_lfht *ht, struct rcu_table *old_t,
1162 unsigned long old_size, unsigned long new_size)
1163 {
1164 unsigned long old_order, new_order;
1165 struct rcu_table *new_t;
1166
1167 new_size = max(new_size, MIN_TABLE_SIZE);
1168 old_order = get_count_order_ulong(old_size) + 1;
1169 new_order = get_count_order_ulong(new_size) + 1;
1170 printf("resize from %lu (order %lu) to %lu (order %lu) buckets\n",
1171 old_size, old_order, new_size, new_order);
1172 new_t = malloc(sizeof(struct cds_lfht)
1173 + (new_order * sizeof(struct rcu_level *)));
1174 assert(new_size < old_size);
1175 memcpy(&new_t->tbl, &old_t->tbl,
1176 new_order * sizeof(struct rcu_level *));
1177 new_t->size = !new_order ? 1 : (1UL << (new_order - 1));
1178 new_t->resize_target = new_t->size;
1179 new_t->resize_initiated = 0;
1180
1181 /* Changing table and size atomically wrt lookups */
1182 rcu_assign_pointer(ht->t, new_t);
1183
1184 /*
1185 * We need to wait for all reader threads to reach Q.S. (and
1186 * thus use the new table for lookups) before we can start
1187 * releasing the old dummy nodes.
1188 */
1189 ht->cds_lfht_synchronize_rcu();
1190
1191 /* Unlink and remove all now-unused dummy node pointers. */
1192 fini_table(ht, old_t, new_order, old_order - new_order);
1193 ht->cds_lfht_call_rcu(&old_t->head, cds_lfht_free_table_cb);
1194 }
1195
1196
1197 /* called with resize mutex held */
1198 static
1199 void _do_cds_lfht_resize(struct cds_lfht *ht)
1200 {
1201 unsigned long new_size, old_size;
1202 struct rcu_table *old_t;
1203
1204 old_t = ht->t;
1205 old_size = old_t->size;
1206 new_size = CMM_LOAD_SHARED(old_t->resize_target);
1207 if (old_size < new_size)
1208 _do_cds_lfht_grow(ht, old_t, old_size, new_size);
1209 else if (old_size > new_size)
1210 _do_cds_lfht_shrink(ht, old_t, old_size, new_size);
1211 else
1212 CMM_STORE_SHARED(old_t->resize_initiated, 0);
1213 }
1214
1215 static
1216 unsigned long resize_target_update(struct rcu_table *t,
1217 int growth_order)
1218 {
1219 return _uatomic_max(&t->resize_target,
1220 t->size << growth_order);
1221 }
1222
1223 static
1224 unsigned long resize_target_update_count(struct rcu_table *t,
1225 unsigned long count)
1226 {
1227 count = max(count, MIN_TABLE_SIZE);
1228 return uatomic_set(&t->resize_target, count);
1229 }
1230
1231 void cds_lfht_resize(struct cds_lfht *ht, unsigned long new_size)
1232 {
1233 struct rcu_table *t = rcu_dereference(ht->t);
1234 unsigned long target_size;
1235
1236 target_size = resize_target_update_count(t, new_size);
1237 CMM_STORE_SHARED(t->resize_initiated, 1);
1238 pthread_mutex_lock(&ht->resize_mutex);
1239 _do_cds_lfht_resize(ht);
1240 pthread_mutex_unlock(&ht->resize_mutex);
1241 }
1242
1243 static
1244 void do_resize_cb(struct rcu_head *head)
1245 {
1246 struct rcu_resize_work *work =
1247 caa_container_of(head, struct rcu_resize_work, head);
1248 struct cds_lfht *ht = work->ht;
1249
1250 pthread_mutex_lock(&ht->resize_mutex);
1251 _do_cds_lfht_resize(ht);
1252 pthread_mutex_unlock(&ht->resize_mutex);
1253 free(work);
1254 cmm_smp_mb(); /* finish resize before decrement */
1255 uatomic_dec(&ht->in_progress_resize);
1256 }
1257
1258 static
1259 void cds_lfht_resize_lazy(struct cds_lfht *ht, struct rcu_table *t, int growth)
1260 {
1261 struct rcu_resize_work *work;
1262 unsigned long target_size;
1263
1264 target_size = resize_target_update(t, growth);
1265 if (!CMM_LOAD_SHARED(t->resize_initiated) && t->size < target_size) {
1266 uatomic_inc(&ht->in_progress_resize);
1267 cmm_smp_mb(); /* increment resize count before calling it */
1268 work = malloc(sizeof(*work));
1269 work->ht = ht;
1270 ht->cds_lfht_call_rcu(&work->head, do_resize_cb);
1271 CMM_STORE_SHARED(t->resize_initiated, 1);
1272 }
1273 }
1274
1275 #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF)
1276
1277 static
1278 void cds_lfht_resize_lazy_count(struct cds_lfht *ht, struct rcu_table *t,
1279 unsigned long count)
1280 {
1281 struct rcu_resize_work *work;
1282 unsigned long target_size;
1283
1284 target_size = resize_target_update_count(t, count);
1285 if (!CMM_LOAD_SHARED(t->resize_initiated)) {
1286 uatomic_inc(&ht->in_progress_resize);
1287 cmm_smp_mb(); /* increment resize count before calling it */
1288 work = malloc(sizeof(*work));
1289 work->ht = ht;
1290 ht->cds_lfht_call_rcu(&work->head, do_resize_cb);
1291 CMM_STORE_SHARED(t->resize_initiated, 1);
1292 }
1293 }
1294
1295 #endif
This page took 0.05425 seconds and 5 git commands to generate.