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