ee4bea24c11340e5253612c51fad50c891020622
[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 /* For testing */
160 #define POISON_FREE
161
162 /*
163 * Per-CPU split-counters lazily update the global counter each 1024
164 * addition/removal. It automatically keeps track of resize required.
165 * We use the bucket length as indicator for need to expand for small
166 * tables and machines lacking per-cpu data suppport.
167 */
168 #define COUNT_COMMIT_ORDER 10
169 #define CHAIN_LEN_TARGET 1
170 #define CHAIN_LEN_RESIZE_THRESHOLD 3
171
172 /*
173 * Define the minimum table size. Protects against hash table resize overload
174 * when too many entries are added quickly before the resize can complete.
175 * This is especially the case if the table could be shrinked to a size of 1.
176 * TODO: we might want to make the add/remove operations help the resize to
177 * add or remove dummy nodes when a resize is ongoing to ensure upper-bound on
178 * chain length.
179 */
180 #define MIN_TABLE_SIZE 128
181
182 #ifndef max
183 #define max(a, b) ((a) > (b) ? (a) : (b))
184 #endif
185
186 /*
187 * The removed flag needs to be updated atomically with the pointer.
188 * The dummy flag does not require to be updated atomically with the
189 * pointer, but it is added as a pointer low bit flag to save space.
190 */
191 #define REMOVED_FLAG (1UL << 0)
192 #define DUMMY_FLAG (1UL << 1)
193 #define FLAGS_MASK ((1UL << 2) - 1)
194
195 struct ht_items_count {
196 unsigned long add, remove;
197 } __attribute__((aligned(CAA_CACHE_LINE_SIZE)));
198
199 struct rcu_level {
200 struct rcu_head head;
201 struct _cds_lfht_node nodes[0];
202 };
203
204 struct rcu_table {
205 unsigned long size; /* always a power of 2 */
206 unsigned long resize_target;
207 int resize_initiated;
208 struct rcu_head head;
209 struct rcu_level *tbl[0];
210 };
211
212 struct cds_lfht {
213 struct rcu_table *t; /* shared */
214 cds_lfht_hash_fct hash_fct;
215 cds_lfht_compare_fct compare_fct;
216 unsigned long hash_seed;
217 int flags;
218 pthread_mutex_t resize_mutex; /* resize mutex: add/del mutex */
219 unsigned int in_progress_resize, in_progress_destroy;
220 void (*cds_lfht_call_rcu)(struct rcu_head *head,
221 void (*func)(struct rcu_head *head));
222 void (*cds_lfht_synchronize_rcu)(void);
223 unsigned long count; /* global approximate item count */
224 struct ht_items_count *percpu_count; /* per-cpu item count */
225 };
226
227 struct rcu_resize_work {
228 struct rcu_head head;
229 struct cds_lfht *ht;
230 };
231
232 /*
233 * Algorithm to reverse bits in a word by lookup table, extended to
234 * 64-bit words.
235 * Source:
236 * http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
237 * Originally from Public Domain.
238 */
239
240 static const uint8_t BitReverseTable256[256] =
241 {
242 #define R2(n) (n), (n) + 2*64, (n) + 1*64, (n) + 3*64
243 #define R4(n) R2(n), R2((n) + 2*16), R2((n) + 1*16), R2((n) + 3*16)
244 #define R6(n) R4(n), R4((n) + 2*4 ), R4((n) + 1*4 ), R4((n) + 3*4 )
245 R6(0), R6(2), R6(1), R6(3)
246 };
247 #undef R2
248 #undef R4
249 #undef R6
250
251 static
252 uint8_t bit_reverse_u8(uint8_t v)
253 {
254 return BitReverseTable256[v];
255 }
256
257 static __attribute__((unused))
258 uint32_t bit_reverse_u32(uint32_t v)
259 {
260 return ((uint32_t) bit_reverse_u8(v) << 24) |
261 ((uint32_t) bit_reverse_u8(v >> 8) << 16) |
262 ((uint32_t) bit_reverse_u8(v >> 16) << 8) |
263 ((uint32_t) bit_reverse_u8(v >> 24));
264 }
265
266 static __attribute__((unused))
267 uint64_t bit_reverse_u64(uint64_t v)
268 {
269 return ((uint64_t) bit_reverse_u8(v) << 56) |
270 ((uint64_t) bit_reverse_u8(v >> 8) << 48) |
271 ((uint64_t) bit_reverse_u8(v >> 16) << 40) |
272 ((uint64_t) bit_reverse_u8(v >> 24) << 32) |
273 ((uint64_t) bit_reverse_u8(v >> 32) << 24) |
274 ((uint64_t) bit_reverse_u8(v >> 40) << 16) |
275 ((uint64_t) bit_reverse_u8(v >> 48) << 8) |
276 ((uint64_t) bit_reverse_u8(v >> 56));
277 }
278
279 static
280 unsigned long bit_reverse_ulong(unsigned long v)
281 {
282 #if (CAA_BITS_PER_LONG == 32)
283 return bit_reverse_u32(v);
284 #else
285 return bit_reverse_u64(v);
286 #endif
287 }
288
289 /*
290 * fls: returns the position of the most significant bit.
291 * Returns 0 if no bit is set, else returns the position of the most
292 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
293 */
294 #if defined(__i386) || defined(__x86_64)
295 static inline
296 unsigned int fls_u32(uint32_t x)
297 {
298 int r;
299
300 asm("bsrl %1,%0\n\t"
301 "jnz 1f\n\t"
302 "movl $-1,%0\n\t"
303 "1:\n\t"
304 : "=r" (r) : "rm" (x));
305 return r + 1;
306 }
307 #define HAS_FLS_U32
308 #endif
309
310 #if defined(__x86_64)
311 static inline
312 unsigned int fls_u64(uint64_t x)
313 {
314 long r;
315
316 asm("bsrq %1,%0\n\t"
317 "jnz 1f\n\t"
318 "movq $-1,%0\n\t"
319 "1:\n\t"
320 : "=r" (r) : "rm" (x));
321 return r + 1;
322 }
323 #define HAS_FLS_U64
324 #endif
325
326 #ifndef HAS_FLS_U64
327 static __attribute__((unused))
328 unsigned int fls_u64(uint64_t x)
329 {
330 unsigned int r = 64;
331
332 if (!x)
333 return 0;
334
335 if (!(x & 0xFFFFFFFF00000000ULL)) {
336 x <<= 32;
337 r -= 32;
338 }
339 if (!(x & 0xFFFF000000000000ULL)) {
340 x <<= 16;
341 r -= 16;
342 }
343 if (!(x & 0xFF00000000000000ULL)) {
344 x <<= 8;
345 r -= 8;
346 }
347 if (!(x & 0xF000000000000000ULL)) {
348 x <<= 4;
349 r -= 4;
350 }
351 if (!(x & 0xC000000000000000ULL)) {
352 x <<= 2;
353 r -= 2;
354 }
355 if (!(x & 0x8000000000000000ULL)) {
356 x <<= 1;
357 r -= 1;
358 }
359 return r;
360 }
361 #endif
362
363 #ifndef HAS_FLS_U32
364 static __attribute__((unused))
365 unsigned int fls_u32(uint32_t x)
366 {
367 unsigned int r = 32;
368
369 if (!x)
370 return 0;
371 if (!(x & 0xFFFF0000U)) {
372 x <<= 16;
373 r -= 16;
374 }
375 if (!(x & 0xFF000000U)) {
376 x <<= 8;
377 r -= 8;
378 }
379 if (!(x & 0xF0000000U)) {
380 x <<= 4;
381 r -= 4;
382 }
383 if (!(x & 0xC0000000U)) {
384 x <<= 2;
385 r -= 2;
386 }
387 if (!(x & 0x80000000U)) {
388 x <<= 1;
389 r -= 1;
390 }
391 return r;
392 }
393 #endif
394
395 unsigned int fls_ulong(unsigned long x)
396 {
397 #if (CAA_BITS_PER_lONG == 32)
398 return fls_u32(x);
399 #else
400 return fls_u64(x);
401 #endif
402 }
403
404 int get_count_order_u32(uint32_t x)
405 {
406 int order;
407
408 order = fls_u32(x) - 1;
409 if (x & (x - 1))
410 order++;
411 return order;
412 }
413
414 int get_count_order_ulong(unsigned long x)
415 {
416 int order;
417
418 order = fls_ulong(x) - 1;
419 if (x & (x - 1))
420 order++;
421 return order;
422 }
423
424 #ifdef POISON_FREE
425 #define poison_free(ptr) \
426 do { \
427 memset(ptr, 0x42, sizeof(*(ptr))); \
428 free(ptr); \
429 } while (0)
430 #else
431 #define poison_free(ptr) free(ptr)
432 #endif
433
434 static
435 void cds_lfht_resize_lazy(struct cds_lfht *ht, struct rcu_table *t, int growth);
436
437 /*
438 * If the sched_getcpu() and sysconf(_SC_NPROCESSORS_CONF) calls are
439 * available, then we support hash table item accounting.
440 * In the unfortunate event the number of CPUs reported would be
441 * inaccurate, we use modulo arithmetic on the number of CPUs we got.
442 */
443 #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF)
444
445 static
446 void cds_lfht_resize_lazy_count(struct cds_lfht *ht, struct rcu_table *t,
447 unsigned long count);
448
449 static long nr_cpus_mask = -1;
450
451 static
452 struct ht_items_count *alloc_per_cpu_items_count(void)
453 {
454 struct ht_items_count *count;
455
456 switch (nr_cpus_mask) {
457 case -2:
458 return NULL;
459 case -1:
460 {
461 long maxcpus;
462
463 maxcpus = sysconf(_SC_NPROCESSORS_CONF);
464 if (maxcpus <= 0) {
465 nr_cpus_mask = -2;
466 return NULL;
467 }
468 /*
469 * round up number of CPUs to next power of two, so we
470 * can use & for modulo.
471 */
472 maxcpus = 1UL << get_count_order_ulong(maxcpus);
473 nr_cpus_mask = maxcpus - 1;
474 }
475 /* Fall-through */
476 default:
477 return calloc(nr_cpus_mask + 1, sizeof(*count));
478 }
479 }
480
481 static
482 void free_per_cpu_items_count(struct ht_items_count *count)
483 {
484 poison_free(count);
485 }
486
487 static
488 int ht_get_cpu(void)
489 {
490 int cpu;
491
492 assert(nr_cpus_mask >= 0);
493 cpu = sched_getcpu();
494 if (unlikely(cpu < 0))
495 return cpu;
496 else
497 return cpu & nr_cpus_mask;
498 }
499
500 static
501 void ht_count_add(struct cds_lfht *ht, struct rcu_table *t)
502 {
503 unsigned long percpu_count;
504 int cpu;
505
506 if (unlikely(!ht->percpu_count))
507 return;
508 cpu = ht_get_cpu();
509 if (unlikely(cpu < 0))
510 return;
511 percpu_count = uatomic_add_return(&ht->percpu_count[cpu].add, 1);
512 if (unlikely(!(percpu_count & ((1UL << COUNT_COMMIT_ORDER) - 1)))) {
513 unsigned long count;
514
515 dbg_printf("add percpu %lu\n", percpu_count);
516 count = uatomic_add_return(&ht->count,
517 1UL << COUNT_COMMIT_ORDER);
518 /* If power of 2 */
519 if (!(count & (count - 1))) {
520 if ((count >> CHAIN_LEN_RESIZE_THRESHOLD)
521 < t->size)
522 return;
523 dbg_printf("add set global %lu\n", count);
524 cds_lfht_resize_lazy_count(ht, t,
525 count >> (CHAIN_LEN_TARGET - 1));
526 }
527 }
528 }
529
530 static
531 void ht_count_remove(struct cds_lfht *ht, struct rcu_table *t)
532 {
533 unsigned long percpu_count;
534 int cpu;
535
536 if (unlikely(!ht->percpu_count))
537 return;
538 cpu = ht_get_cpu();
539 if (unlikely(cpu < 0))
540 return;
541 percpu_count = uatomic_add_return(&ht->percpu_count[cpu].remove, -1);
542 if (unlikely(!(percpu_count & ((1UL << COUNT_COMMIT_ORDER) - 1)))) {
543 unsigned long count;
544
545 dbg_printf("remove percpu %lu\n", percpu_count);
546 count = uatomic_add_return(&ht->count,
547 -(1UL << COUNT_COMMIT_ORDER));
548 /* If power of 2 */
549 if (!(count & (count - 1))) {
550 if ((count >> CHAIN_LEN_RESIZE_THRESHOLD)
551 >= t->size)
552 return;
553 dbg_printf("remove set global %lu\n", count);
554 cds_lfht_resize_lazy_count(ht, t,
555 count >> (CHAIN_LEN_TARGET - 1));
556 }
557 }
558 }
559
560 #else /* #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF) */
561
562 static const long nr_cpus_mask = -1;
563
564 static
565 struct ht_items_count *alloc_per_cpu_items_count(void)
566 {
567 return NULL;
568 }
569
570 static
571 void free_per_cpu_items_count(struct ht_items_count *count)
572 {
573 }
574
575 static
576 void ht_count_add(struct cds_lfht *ht, struct rcu_table *t)
577 {
578 }
579
580 static
581 void ht_count_remove(struct cds_lfht *ht, struct rcu_table *t)
582 {
583 }
584
585 #endif /* #else #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF) */
586
587
588 static
589 void check_resize(struct cds_lfht *ht, struct rcu_table *t,
590 uint32_t chain_len)
591 {
592 unsigned long count;
593
594 if (!(ht->flags & CDS_LFHT_AUTO_RESIZE))
595 return;
596 count = uatomic_read(&ht->count);
597 /*
598 * Use bucket-local length for small table expand and for
599 * environments lacking per-cpu data support.
600 */
601 if (count >= (1UL << COUNT_COMMIT_ORDER))
602 return;
603 if (chain_len > 100)
604 dbg_printf("WARNING: large chain length: %u.\n",
605 chain_len);
606 if (chain_len >= CHAIN_LEN_RESIZE_THRESHOLD)
607 cds_lfht_resize_lazy(ht, t,
608 get_count_order_u32(chain_len - (CHAIN_LEN_TARGET - 1)));
609 }
610
611 static
612 struct cds_lfht_node *clear_flag(struct cds_lfht_node *node)
613 {
614 return (struct cds_lfht_node *) (((unsigned long) node) & ~FLAGS_MASK);
615 }
616
617 static
618 int is_removed(struct cds_lfht_node *node)
619 {
620 return ((unsigned long) node) & REMOVED_FLAG;
621 }
622
623 static
624 struct cds_lfht_node *flag_removed(struct cds_lfht_node *node)
625 {
626 return (struct cds_lfht_node *) (((unsigned long) node) | REMOVED_FLAG);
627 }
628
629 static
630 int is_dummy(struct cds_lfht_node *node)
631 {
632 return ((unsigned long) node) & DUMMY_FLAG;
633 }
634
635 static
636 struct cds_lfht_node *flag_dummy(struct cds_lfht_node *node)
637 {
638 return (struct cds_lfht_node *) (((unsigned long) node) | DUMMY_FLAG);
639 }
640
641 static
642 unsigned long _uatomic_max(unsigned long *ptr, unsigned long v)
643 {
644 unsigned long old1, old2;
645
646 old1 = uatomic_read(ptr);
647 do {
648 old2 = old1;
649 if (old2 >= v)
650 return old2;
651 } while ((old1 = uatomic_cmpxchg(ptr, old2, v)) != old2);
652 return v;
653 }
654
655 static
656 void cds_lfht_free_table_cb(struct rcu_head *head)
657 {
658 struct rcu_table *t =
659 caa_container_of(head, struct rcu_table, head);
660 poison_free(t);
661 }
662
663 static
664 void cds_lfht_free_level(struct rcu_head *head)
665 {
666 struct rcu_level *l =
667 caa_container_of(head, struct rcu_level, head);
668 poison_free(l);
669 }
670
671 /*
672 * Remove all logically deleted nodes from a bucket up to a certain node key.
673 */
674 static
675 void _cds_lfht_gc_bucket(struct cds_lfht_node *dummy, struct cds_lfht_node *node)
676 {
677 struct cds_lfht_node *iter_prev, *iter, *next, *new_next;
678
679 assert(!is_dummy(dummy));
680 assert(!is_removed(dummy));
681 assert(!is_dummy(node));
682 assert(!is_removed(node));
683 for (;;) {
684 iter_prev = dummy;
685 /* We can always skip the dummy node initially */
686 iter = rcu_dereference(iter_prev->p.next);
687 assert(iter_prev->p.reverse_hash <= node->p.reverse_hash);
688 /*
689 * We should never be called with dummy (start of chain)
690 * and logically removed node (end of path compression
691 * marker) being the actual same node. This would be a
692 * bug in the algorithm implementation.
693 */
694 assert(dummy != node);
695 for (;;) {
696 if (unlikely(!clear_flag(iter)))
697 return;
698 if (likely(clear_flag(iter)->p.reverse_hash > node->p.reverse_hash))
699 return;
700 next = rcu_dereference(clear_flag(iter)->p.next);
701 if (likely(is_removed(next)))
702 break;
703 iter_prev = clear_flag(iter);
704 iter = next;
705 }
706 assert(!is_removed(iter));
707 if (is_dummy(iter))
708 new_next = flag_dummy(clear_flag(next));
709 else
710 new_next = clear_flag(next);
711 (void) uatomic_cmpxchg(&iter_prev->p.next, iter, new_next);
712 }
713 }
714
715 static
716 struct cds_lfht_node *_cds_lfht_add(struct cds_lfht *ht, struct rcu_table *t,
717 struct cds_lfht_node *node, int unique, int dummy)
718 {
719 struct cds_lfht_node *iter_prev, *iter, *next, *new_node, *new_next,
720 *dummy_node;
721 struct _cds_lfht_node *lookup;
722 unsigned long hash, index, order;
723
724 assert(!is_dummy(node));
725 assert(!is_removed(node));
726 if (!t->size) {
727 assert(dummy);
728 node->p.next = flag_dummy(NULL);
729 return node; /* Initial first add (head) */
730 }
731 hash = bit_reverse_ulong(node->p.reverse_hash);
732 for (;;) {
733 uint32_t chain_len = 0;
734
735 /*
736 * iter_prev points to the non-removed node prior to the
737 * insert location.
738 */
739 index = hash & (t->size - 1);
740 order = get_count_order_ulong(index + 1);
741 lookup = &t->tbl[order]->nodes[index & ((!order ? 0 : (1UL << (order - 1))) - 1)];
742 iter_prev = (struct cds_lfht_node *) lookup;
743 /* We can always skip the dummy node initially */
744 iter = rcu_dereference(iter_prev->p.next);
745 assert(iter_prev->p.reverse_hash <= node->p.reverse_hash);
746 for (;;) {
747 /* TODO: check if removed */
748 if (unlikely(!clear_flag(iter)))
749 goto insert;
750 /* TODO: check if removed */
751 if (likely(clear_flag(iter)->p.reverse_hash > node->p.reverse_hash))
752 goto insert;
753 next = rcu_dereference(clear_flag(iter)->p.next);
754 if (unlikely(is_removed(next)))
755 goto gc_node;
756 if (unique
757 && !is_dummy(next)
758 && !ht->compare_fct(node->key, node->key_len,
759 clear_flag(iter)->key,
760 clear_flag(iter)->key_len))
761 return clear_flag(iter);
762 /* Only account for identical reverse hash once */
763 if (iter_prev->p.reverse_hash != clear_flag(iter)->p.reverse_hash
764 && !is_dummy(next))
765 check_resize(ht, t, ++chain_len);
766 iter_prev = clear_flag(iter);
767 iter = next;
768 }
769 insert:
770 assert(node != clear_flag(iter));
771 assert(!is_removed(iter_prev));
772 assert(!is_removed(iter));
773 assert(iter_prev != node);
774 if (!dummy)
775 node->p.next = clear_flag(iter);
776 else
777 node->p.next = flag_dummy(clear_flag(iter));
778 if (is_dummy(iter))
779 new_node = flag_dummy(node);
780 else
781 new_node = node;
782 if (uatomic_cmpxchg(&iter_prev->p.next, iter,
783 new_node) != iter)
784 continue; /* retry */
785 else
786 goto gc_end;
787 gc_node:
788 assert(!is_removed(iter));
789 if (is_dummy(iter))
790 new_next = flag_dummy(clear_flag(next));
791 else
792 new_next = clear_flag(next);
793 (void) uatomic_cmpxchg(&iter_prev->p.next, iter, new_next);
794 /* retry */
795 }
796 gc_end:
797 /* Garbage collect logically removed nodes in the bucket */
798 index = hash & (t->size - 1);
799 order = get_count_order_ulong(index + 1);
800 lookup = &t->tbl[order]->nodes[index & (!order ? 0 : ((1UL << (order - 1)) - 1))];
801 dummy_node = (struct cds_lfht_node *) lookup;
802 _cds_lfht_gc_bucket(dummy_node, node);
803 return node;
804 }
805
806 static
807 int _cds_lfht_remove(struct cds_lfht *ht, struct rcu_table *t,
808 struct cds_lfht_node *node, int dummy_removal)
809 {
810 struct cds_lfht_node *dummy, *next, *old;
811 struct _cds_lfht_node *lookup;
812 int flagged = 0;
813 unsigned long hash, index, order;
814
815 /* logically delete the node */
816 assert(!is_dummy(node));
817 assert(!is_removed(node));
818 old = rcu_dereference(node->p.next);
819 do {
820 next = old;
821 if (unlikely(is_removed(next)))
822 goto end;
823 if (dummy_removal)
824 assert(is_dummy(next));
825 else
826 assert(!is_dummy(next));
827 old = uatomic_cmpxchg(&node->p.next, next,
828 flag_removed(next));
829 } while (old != next);
830
831 /* We performed the (logical) deletion. */
832 flagged = 1;
833
834 /*
835 * Ensure that the node is not visible to readers anymore: lookup for
836 * the node, and remove it (along with any other logically removed node)
837 * if found.
838 */
839 hash = bit_reverse_ulong(node->p.reverse_hash);
840 assert(t->size > 0);
841 index = hash & (t->size - 1);
842 order = get_count_order_ulong(index + 1);
843 lookup = &t->tbl[order]->nodes[index & (!order ? 0 : ((1UL << (order - 1)) - 1))];
844 dummy = (struct cds_lfht_node *) lookup;
845 _cds_lfht_gc_bucket(dummy, node);
846 end:
847 /*
848 * Only the flagging action indicated that we (and no other)
849 * removed the node from the hash.
850 */
851 if (flagged) {
852 assert(is_removed(rcu_dereference(node->p.next)));
853 return 0;
854 } else
855 return -ENOENT;
856 }
857
858 static
859 void init_table(struct cds_lfht *ht, struct rcu_table *t,
860 unsigned long first_order, unsigned long len_order)
861 {
862 unsigned long i, end_order;
863
864 dbg_printf("init table: first_order %lu end_order %lu\n",
865 first_order, first_order + len_order);
866 end_order = first_order + len_order;
867 t->size = !first_order ? 0 : (1UL << (first_order - 1));
868 for (i = first_order; i < end_order; i++) {
869 unsigned long j, len;
870
871 len = !i ? 1 : 1UL << (i - 1);
872 dbg_printf("init order %lu len: %lu\n", i, len);
873 t->tbl[i] = calloc(1, sizeof(struct rcu_level)
874 + (len * sizeof(struct _cds_lfht_node)));
875 for (j = 0; j < len; j++) {
876 struct cds_lfht_node *new_node =
877 (struct cds_lfht_node *) &t->tbl[i]->nodes[j];
878
879 dbg_printf("init entry: i %lu j %lu hash %lu\n",
880 i, j, !i ? 0 : (1UL << (i - 1)) + j);
881 new_node->p.reverse_hash =
882 bit_reverse_ulong(!i ? 0 : (1UL << (i - 1)) + j);
883 (void) _cds_lfht_add(ht, t, new_node, 0, 1);
884 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
885 break;
886 }
887 /* Update table size */
888 t->size = !i ? 1 : (1UL << i);
889 dbg_printf("init new size: %lu\n", t->size);
890 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
891 break;
892 }
893 t->resize_target = t->size;
894 t->resize_initiated = 0;
895 }
896
897 static
898 void fini_table(struct cds_lfht *ht, struct rcu_table *t,
899 unsigned long first_order, unsigned long len_order)
900 {
901 long i, end_order;
902
903 dbg_printf("fini table: first_order %lu end_order %lu\n",
904 first_order, first_order + len_order);
905 end_order = first_order + len_order;
906 assert(first_order > 0);
907 assert(t->size == (1UL << (end_order - 1)));
908 for (i = end_order - 1; i >= first_order; i--) {
909 unsigned long j, len;
910
911 len = !i ? 1 : 1UL << (i - 1);
912 dbg_printf("fini order %lu len: %lu\n", i, len);
913 /*
914 * Update table size. Need to shrink this table prior to
915 * removal so gc lookups use non-logically-removed dummy
916 * nodes.
917 */
918 t->size = 1UL << (i - 1);
919 /* Unlink */
920 for (j = 0; j < len; j++) {
921 struct cds_lfht_node *fini_node =
922 (struct cds_lfht_node *) &t->tbl[i]->nodes[j];
923
924 dbg_printf("fini entry: i %lu j %lu hash %lu\n",
925 i, j, !i ? 0 : (1UL << (i - 1)) + j);
926 fini_node->p.reverse_hash =
927 bit_reverse_ulong(!i ? 0 : (1UL << (i - 1)) + j);
928 (void) _cds_lfht_remove(ht, t, fini_node, 1);
929 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
930 break;
931 }
932 ht->cds_lfht_call_rcu(&t->tbl[i]->head, cds_lfht_free_level);
933 dbg_printf("fini new size: %lu\n", t->size);
934 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
935 break;
936 }
937 t->resize_target = t->size;
938 t->resize_initiated = 0;
939 }
940
941 struct cds_lfht *cds_lfht_new(cds_lfht_hash_fct hash_fct,
942 cds_lfht_compare_fct compare_fct,
943 unsigned long hash_seed,
944 unsigned long init_size,
945 int flags,
946 void (*cds_lfht_call_rcu)(struct rcu_head *head,
947 void (*func)(struct rcu_head *head)),
948 void (*cds_lfht_synchronize_rcu)(void))
949 {
950 struct cds_lfht *ht;
951 unsigned long order;
952
953 /* init_size must be power of two */
954 if (init_size && (init_size & (init_size - 1)))
955 return NULL;
956 ht = calloc(1, sizeof(struct cds_lfht));
957 ht->hash_fct = hash_fct;
958 ht->compare_fct = compare_fct;
959 ht->hash_seed = hash_seed;
960 ht->cds_lfht_call_rcu = cds_lfht_call_rcu;
961 ht->cds_lfht_synchronize_rcu = cds_lfht_synchronize_rcu;
962 ht->in_progress_resize = 0;
963 ht->percpu_count = alloc_per_cpu_items_count();
964 /* this mutex should not nest in read-side C.S. */
965 pthread_mutex_init(&ht->resize_mutex, NULL);
966 order = get_count_order_ulong(max(init_size, MIN_TABLE_SIZE)) + 1;
967 ht->t = calloc(1, sizeof(struct cds_lfht)
968 + (order * sizeof(struct rcu_level *)));
969 ht->t->size = 0;
970 ht->flags = flags;
971 pthread_mutex_lock(&ht->resize_mutex);
972 init_table(ht, ht->t, 0, order);
973 pthread_mutex_unlock(&ht->resize_mutex);
974 return ht;
975 }
976
977 struct cds_lfht_node *cds_lfht_lookup(struct cds_lfht *ht, void *key, size_t key_len)
978 {
979 struct rcu_table *t;
980 struct cds_lfht_node *node, *next;
981 struct _cds_lfht_node *lookup;
982 unsigned long hash, reverse_hash, index, order;
983
984 hash = ht->hash_fct(key, key_len, ht->hash_seed);
985 reverse_hash = bit_reverse_ulong(hash);
986
987 t = rcu_dereference(ht->t);
988 index = hash & (t->size - 1);
989 order = get_count_order_ulong(index + 1);
990 lookup = &t->tbl[order]->nodes[index & (!order ? 0 : ((1UL << (order - 1))) - 1)];
991 dbg_printf("lookup hash %lu index %lu order %lu aridx %lu\n",
992 hash, index, order, index & (!order ? 0 : ((1UL << (order - 1)) - 1)));
993 node = (struct cds_lfht_node *) lookup;
994 for (;;) {
995 if (unlikely(!node))
996 break;
997 if (unlikely(node->p.reverse_hash > reverse_hash)) {
998 node = NULL;
999 break;
1000 }
1001 next = rcu_dereference(node->p.next);
1002 if (likely(!is_removed(next))
1003 && !is_dummy(next)
1004 && likely(!ht->compare_fct(node->key, node->key_len, key, key_len))) {
1005 break;
1006 }
1007 node = clear_flag(next);
1008 }
1009 assert(!node || !is_dummy(rcu_dereference(node->p.next)));
1010 return node;
1011 }
1012
1013 struct cds_lfht_node *cds_lfht_next(struct cds_lfht *ht,
1014 struct cds_lfht_node *node)
1015 {
1016 struct cds_lfht_node *next;
1017 unsigned long reverse_hash;
1018 void *key;
1019 size_t key_len;
1020
1021 reverse_hash = node->p.reverse_hash;
1022 key = node->key;
1023 key_len = node->key_len;
1024 next = rcu_dereference(node->p.next);
1025 node = clear_flag(next);
1026
1027 for (;;) {
1028 if (unlikely(!node))
1029 break;
1030 if (unlikely(node->p.reverse_hash > reverse_hash)) {
1031 node = NULL;
1032 break;
1033 }
1034 next = rcu_dereference(node->p.next);
1035 if (likely(!is_removed(next))
1036 && !is_dummy(next)
1037 && likely(!ht->compare_fct(node->key, node->key_len, key, key_len))) {
1038 break;
1039 }
1040 node = clear_flag(next);
1041 }
1042 assert(!node || !is_dummy(rcu_dereference(node->p.next)));
1043 return node;
1044 }
1045
1046 void cds_lfht_add(struct cds_lfht *ht, struct cds_lfht_node *node)
1047 {
1048 struct rcu_table *t;
1049 unsigned long hash;
1050
1051 hash = ht->hash_fct(node->key, node->key_len, ht->hash_seed);
1052 node->p.reverse_hash = bit_reverse_ulong((unsigned long) hash);
1053
1054 t = rcu_dereference(ht->t);
1055 (void) _cds_lfht_add(ht, t, node, 0, 0);
1056 ht_count_add(ht, t);
1057 }
1058
1059 struct cds_lfht_node *cds_lfht_add_unique(struct cds_lfht *ht,
1060 struct cds_lfht_node *node)
1061 {
1062 struct rcu_table *t;
1063 unsigned long hash;
1064 struct cds_lfht_node *ret;
1065
1066 hash = ht->hash_fct(node->key, node->key_len, ht->hash_seed);
1067 node->p.reverse_hash = bit_reverse_ulong((unsigned long) hash);
1068
1069 t = rcu_dereference(ht->t);
1070 ret = _cds_lfht_add(ht, t, node, 1, 0);
1071 if (ret != node)
1072 ht_count_add(ht, t);
1073 return ret;
1074 }
1075
1076 int cds_lfht_remove(struct cds_lfht *ht, struct cds_lfht_node *node)
1077 {
1078 struct rcu_table *t;
1079 int ret;
1080
1081 t = rcu_dereference(ht->t);
1082 ret = _cds_lfht_remove(ht, t, node, 0);
1083 if (!ret)
1084 ht_count_remove(ht, t);
1085 return ret;
1086 }
1087
1088 static
1089 int cds_lfht_delete_dummy(struct cds_lfht *ht)
1090 {
1091 struct rcu_table *t;
1092 struct cds_lfht_node *node;
1093 struct _cds_lfht_node *lookup;
1094 unsigned long order, i;
1095
1096 t = ht->t;
1097 /* Check that the table is empty */
1098 lookup = &t->tbl[0]->nodes[0];
1099 node = (struct cds_lfht_node *) lookup;
1100 do {
1101 node = clear_flag(node)->p.next;
1102 if (!is_dummy(node))
1103 return -EPERM;
1104 assert(!is_removed(node));
1105 } while (clear_flag(node));
1106 /* Internal sanity check: all nodes left should be dummy */
1107 for (order = 0; order < get_count_order_ulong(t->size) + 1; order++) {
1108 unsigned long len;
1109
1110 len = !order ? 1 : 1UL << (order - 1);
1111 for (i = 0; i < len; i++) {
1112 dbg_printf("delete order %lu i %lu hash %lu\n",
1113 order, i,
1114 bit_reverse_ulong(t->tbl[order]->nodes[i].reverse_hash));
1115 assert(is_dummy(t->tbl[order]->nodes[i].next));
1116 }
1117 poison_free(t->tbl[order]);
1118 }
1119 return 0;
1120 }
1121
1122 /*
1123 * Should only be called when no more concurrent readers nor writers can
1124 * possibly access the table.
1125 */
1126 int cds_lfht_destroy(struct cds_lfht *ht)
1127 {
1128 int ret;
1129
1130 /* Wait for in-flight resize operations to complete */
1131 CMM_STORE_SHARED(ht->in_progress_destroy, 1);
1132 while (uatomic_read(&ht->in_progress_resize))
1133 poll(NULL, 0, 100); /* wait for 100ms */
1134 ret = cds_lfht_delete_dummy(ht);
1135 if (ret)
1136 return ret;
1137 poison_free(ht->t);
1138 free_per_cpu_items_count(ht->percpu_count);
1139 poison_free(ht);
1140 return ret;
1141 }
1142
1143 void cds_lfht_count_nodes(struct cds_lfht *ht,
1144 unsigned long *count,
1145 unsigned long *removed)
1146 {
1147 struct rcu_table *t;
1148 struct cds_lfht_node *node, *next;
1149 struct _cds_lfht_node *lookup;
1150 unsigned long nr_dummy = 0;
1151
1152 *count = 0;
1153 *removed = 0;
1154
1155 t = rcu_dereference(ht->t);
1156 /* Count non-dummy nodes in the table */
1157 lookup = &t->tbl[0]->nodes[0];
1158 node = (struct cds_lfht_node *) lookup;
1159 do {
1160 next = rcu_dereference(node->p.next);
1161 if (is_removed(next)) {
1162 assert(!is_dummy(next));
1163 (*removed)++;
1164 } else if (!is_dummy(next))
1165 (*count)++;
1166 else
1167 (nr_dummy)++;
1168 node = clear_flag(next);
1169 } while (node);
1170 dbg_printf("number of dummy nodes: %lu\n", nr_dummy);
1171 }
1172
1173 /* called with resize mutex held */
1174 static
1175 void _do_cds_lfht_grow(struct cds_lfht *ht, struct rcu_table *old_t,
1176 unsigned long old_size, unsigned long new_size)
1177 {
1178 unsigned long old_order, new_order;
1179 struct rcu_table *new_t;
1180
1181 old_order = get_count_order_ulong(old_size) + 1;
1182 new_order = get_count_order_ulong(new_size) + 1;
1183 printf("resize from %lu (order %lu) to %lu (order %lu) buckets\n",
1184 old_size, old_order, new_size, new_order);
1185 new_t = malloc(sizeof(struct cds_lfht)
1186 + (new_order * sizeof(struct rcu_level *)));
1187 assert(new_size > old_size);
1188 memcpy(&new_t->tbl, &old_t->tbl,
1189 old_order * sizeof(struct rcu_level *));
1190 init_table(ht, new_t, old_order, new_order - old_order);
1191 /* Changing table and size atomically wrt lookups */
1192 rcu_assign_pointer(ht->t, new_t);
1193 ht->cds_lfht_call_rcu(&old_t->head, cds_lfht_free_table_cb);
1194 }
1195
1196 /* called with resize mutex held */
1197 static
1198 void _do_cds_lfht_shrink(struct cds_lfht *ht, struct rcu_table *old_t,
1199 unsigned long old_size, unsigned long new_size)
1200 {
1201 unsigned long old_order, new_order;
1202 struct rcu_table *new_t;
1203
1204 new_size = max(new_size, MIN_TABLE_SIZE);
1205 old_order = get_count_order_ulong(old_size) + 1;
1206 new_order = get_count_order_ulong(new_size) + 1;
1207 printf("resize from %lu (order %lu) to %lu (order %lu) buckets\n",
1208 old_size, old_order, new_size, new_order);
1209 new_t = malloc(sizeof(struct cds_lfht)
1210 + (new_order * sizeof(struct rcu_level *)));
1211 assert(new_size < old_size);
1212 memcpy(&new_t->tbl, &old_t->tbl,
1213 new_order * sizeof(struct rcu_level *));
1214 new_t->size = !new_order ? 1 : (1UL << (new_order - 1));
1215 assert(new_t->size == new_size);
1216 new_t->resize_target = new_t->size;
1217 new_t->resize_initiated = 0;
1218
1219 /* Changing table and size atomically wrt lookups */
1220 rcu_assign_pointer(ht->t, new_t);
1221
1222 /*
1223 * We need to wait for all add operations to reach Q.S. (and
1224 * thus use the new table for lookups) before we can start
1225 * releasing the old dummy nodes. Otherwise their lookup will
1226 * return a logically removed node as insert position.
1227 */
1228 ht->cds_lfht_synchronize_rcu();
1229
1230 /* Unlink and remove all now-unused dummy node pointers. */
1231 fini_table(ht, old_t, new_order, old_order - new_order);
1232 ht->cds_lfht_call_rcu(&old_t->head, cds_lfht_free_table_cb);
1233 }
1234
1235
1236 /* called with resize mutex held */
1237 static
1238 void _do_cds_lfht_resize(struct cds_lfht *ht)
1239 {
1240 unsigned long new_size, old_size;
1241 struct rcu_table *old_t;
1242
1243 old_t = ht->t;
1244 old_size = old_t->size;
1245 new_size = CMM_LOAD_SHARED(old_t->resize_target);
1246 if (old_size < new_size)
1247 _do_cds_lfht_grow(ht, old_t, old_size, new_size);
1248 else if (old_size > new_size)
1249 _do_cds_lfht_shrink(ht, old_t, old_size, new_size);
1250 else
1251 CMM_STORE_SHARED(old_t->resize_initiated, 0);
1252 }
1253
1254 static
1255 unsigned long resize_target_update(struct rcu_table *t,
1256 int growth_order)
1257 {
1258 return _uatomic_max(&t->resize_target,
1259 t->size << growth_order);
1260 }
1261
1262 static
1263 void resize_target_update_count(struct rcu_table *t,
1264 unsigned long count)
1265 {
1266 count = max(count, MIN_TABLE_SIZE);
1267 uatomic_set(&t->resize_target, count);
1268 }
1269
1270 void cds_lfht_resize(struct cds_lfht *ht, unsigned long new_size)
1271 {
1272 struct rcu_table *t = rcu_dereference(ht->t);
1273
1274 resize_target_update_count(t, new_size);
1275 CMM_STORE_SHARED(t->resize_initiated, 1);
1276 pthread_mutex_lock(&ht->resize_mutex);
1277 _do_cds_lfht_resize(ht);
1278 pthread_mutex_unlock(&ht->resize_mutex);
1279 }
1280
1281 static
1282 void do_resize_cb(struct rcu_head *head)
1283 {
1284 struct rcu_resize_work *work =
1285 caa_container_of(head, struct rcu_resize_work, head);
1286 struct cds_lfht *ht = work->ht;
1287
1288 pthread_mutex_lock(&ht->resize_mutex);
1289 _do_cds_lfht_resize(ht);
1290 pthread_mutex_unlock(&ht->resize_mutex);
1291 poison_free(work);
1292 cmm_smp_mb(); /* finish resize before decrement */
1293 uatomic_dec(&ht->in_progress_resize);
1294 }
1295
1296 static
1297 void cds_lfht_resize_lazy(struct cds_lfht *ht, struct rcu_table *t, int growth)
1298 {
1299 struct rcu_resize_work *work;
1300 unsigned long target_size;
1301
1302 target_size = resize_target_update(t, growth);
1303 if (!CMM_LOAD_SHARED(t->resize_initiated) && t->size < target_size) {
1304 uatomic_inc(&ht->in_progress_resize);
1305 cmm_smp_mb(); /* increment resize count before calling it */
1306 work = malloc(sizeof(*work));
1307 work->ht = ht;
1308 ht->cds_lfht_call_rcu(&work->head, do_resize_cb);
1309 CMM_STORE_SHARED(t->resize_initiated, 1);
1310 }
1311 }
1312
1313 #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF)
1314
1315 static
1316 void cds_lfht_resize_lazy_count(struct cds_lfht *ht, struct rcu_table *t,
1317 unsigned long count)
1318 {
1319 struct rcu_resize_work *work;
1320
1321 if (!(ht->flags & CDS_LFHT_AUTO_RESIZE))
1322 return;
1323 resize_target_update_count(t, count);
1324 if (!CMM_LOAD_SHARED(t->resize_initiated)) {
1325 uatomic_inc(&ht->in_progress_resize);
1326 cmm_smp_mb(); /* increment resize count before calling it */
1327 work = malloc(sizeof(*work));
1328 work->ht = ht;
1329 ht->cds_lfht_call_rcu(&work->head, do_resize_cb);
1330 CMM_STORE_SHARED(t->resize_initiated, 1);
1331 }
1332 }
1333
1334 #endif
This page took 0.062341 seconds and 4 git commands to generate.