rculfhash: Simplify lookup_bucket()
[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/compiler.h>
148 #include <urcu/rculfhash.h>
149 #include <stdio.h>
150 #include <pthread.h>
151
152 #ifdef DEBUG
153 #define dbg_printf(fmt, args...) printf("[debug rculfhash] " fmt, ## args)
154 #else
155 #define dbg_printf(fmt, args...)
156 #endif
157
158 /*
159 * Per-CPU split-counters lazily update the global counter each 1024
160 * addition/removal. It automatically keeps track of resize required.
161 * We use the bucket length as indicator for need to expand for small
162 * tables and machines lacking per-cpu data suppport.
163 */
164 #define COUNT_COMMIT_ORDER 10
165 #define CHAIN_LEN_TARGET 1
166 #define CHAIN_LEN_RESIZE_THRESHOLD 3
167
168 /*
169 * Define the minimum table size.
170 */
171 #define MIN_TABLE_SIZE 1
172
173 #if (CAA_BITS_PER_LONG == 32)
174 #define MAX_TABLE_ORDER 32
175 #else
176 #define MAX_TABLE_ORDER 64
177 #endif
178
179 /*
180 * Minimum number of dummy nodes to touch per thread to parallelize grow/shrink.
181 */
182 #define MIN_PARTITION_PER_THREAD_ORDER 12
183 #define MIN_PARTITION_PER_THREAD (1UL << MIN_PARTITION_PER_THREAD_ORDER)
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 * It indicates that no node must attach to the node scheduled for
196 * removal, and that node garbage collection must be performed.
197 * The dummy flag does not require to be updated atomically with the
198 * pointer, but it is added as a pointer low bit flag to save space.
199 */
200 #define REMOVED_FLAG (1UL << 0)
201 #define DUMMY_FLAG (1UL << 1)
202 #define FLAGS_MASK ((1UL << 2) - 1)
203
204 /* Value of the end pointer. Should not interact with flags. */
205 #define END_VALUE NULL
206
207 struct ht_items_count {
208 unsigned long add, del;
209 } __attribute__((aligned(CAA_CACHE_LINE_SIZE)));
210
211 struct rcu_level {
212 /* Note: manually update allocation length when adding a field */
213 struct _cds_lfht_node nodes[0];
214 };
215
216 struct rcu_table {
217 unsigned long size; /* always a power of 2, shared (RCU) */
218 unsigned long resize_target;
219 int resize_initiated;
220 struct rcu_level *tbl[MAX_TABLE_ORDER];
221 };
222
223 struct cds_lfht {
224 struct rcu_table t;
225 cds_lfht_hash_fct hash_fct;
226 cds_lfht_compare_fct compare_fct;
227 unsigned long hash_seed;
228 int flags;
229 /*
230 * We need to put the work threads offline (QSBR) when taking this
231 * mutex, because we use synchronize_rcu within this mutex critical
232 * section, which waits on read-side critical sections, and could
233 * therefore cause grace-period deadlock if we hold off RCU G.P.
234 * completion.
235 */
236 pthread_mutex_t resize_mutex; /* resize mutex: add/del mutex */
237 unsigned int in_progress_resize, in_progress_destroy;
238 void (*cds_lfht_call_rcu)(struct rcu_head *head,
239 void (*func)(struct rcu_head *head));
240 void (*cds_lfht_synchronize_rcu)(void);
241 void (*cds_lfht_rcu_read_lock)(void);
242 void (*cds_lfht_rcu_read_unlock)(void);
243 void (*cds_lfht_rcu_thread_offline)(void);
244 void (*cds_lfht_rcu_thread_online)(void);
245 void (*cds_lfht_rcu_register_thread)(void);
246 void (*cds_lfht_rcu_unregister_thread)(void);
247 pthread_attr_t *resize_attr; /* Resize threads attributes */
248 long count; /* global approximate item count */
249 struct ht_items_count *percpu_count; /* per-cpu item count */
250 };
251
252 struct rcu_resize_work {
253 struct rcu_head head;
254 struct cds_lfht *ht;
255 };
256
257 struct partition_resize_work {
258 pthread_t thread_id;
259 struct cds_lfht *ht;
260 unsigned long i, start, len;
261 void (*fct)(struct cds_lfht *ht, unsigned long i,
262 unsigned long start, unsigned long len);
263 };
264
265 enum add_mode {
266 ADD_DEFAULT = 0,
267 ADD_UNIQUE = 1,
268 ADD_REPLACE = 2,
269 };
270
271 static
272 struct cds_lfht_node *_cds_lfht_add(struct cds_lfht *ht,
273 unsigned long size,
274 struct cds_lfht_node *node,
275 enum add_mode mode, int dummy);
276
277 /*
278 * Algorithm to reverse bits in a word by lookup table, extended to
279 * 64-bit words.
280 * Source:
281 * http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
282 * Originally from Public Domain.
283 */
284
285 static const uint8_t BitReverseTable256[256] =
286 {
287 #define R2(n) (n), (n) + 2*64, (n) + 1*64, (n) + 3*64
288 #define R4(n) R2(n), R2((n) + 2*16), R2((n) + 1*16), R2((n) + 3*16)
289 #define R6(n) R4(n), R4((n) + 2*4 ), R4((n) + 1*4 ), R4((n) + 3*4 )
290 R6(0), R6(2), R6(1), R6(3)
291 };
292 #undef R2
293 #undef R4
294 #undef R6
295
296 static
297 uint8_t bit_reverse_u8(uint8_t v)
298 {
299 return BitReverseTable256[v];
300 }
301
302 static __attribute__((unused))
303 uint32_t bit_reverse_u32(uint32_t v)
304 {
305 return ((uint32_t) bit_reverse_u8(v) << 24) |
306 ((uint32_t) bit_reverse_u8(v >> 8) << 16) |
307 ((uint32_t) bit_reverse_u8(v >> 16) << 8) |
308 ((uint32_t) bit_reverse_u8(v >> 24));
309 }
310
311 static __attribute__((unused))
312 uint64_t bit_reverse_u64(uint64_t v)
313 {
314 return ((uint64_t) bit_reverse_u8(v) << 56) |
315 ((uint64_t) bit_reverse_u8(v >> 8) << 48) |
316 ((uint64_t) bit_reverse_u8(v >> 16) << 40) |
317 ((uint64_t) bit_reverse_u8(v >> 24) << 32) |
318 ((uint64_t) bit_reverse_u8(v >> 32) << 24) |
319 ((uint64_t) bit_reverse_u8(v >> 40) << 16) |
320 ((uint64_t) bit_reverse_u8(v >> 48) << 8) |
321 ((uint64_t) bit_reverse_u8(v >> 56));
322 }
323
324 static
325 unsigned long bit_reverse_ulong(unsigned long v)
326 {
327 #if (CAA_BITS_PER_LONG == 32)
328 return bit_reverse_u32(v);
329 #else
330 return bit_reverse_u64(v);
331 #endif
332 }
333
334 /*
335 * fls: returns the position of the most significant bit.
336 * Returns 0 if no bit is set, else returns the position of the most
337 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
338 */
339 #if defined(__i386) || defined(__x86_64)
340 static inline
341 unsigned int fls_u32(uint32_t x)
342 {
343 int r;
344
345 asm("bsrl %1,%0\n\t"
346 "jnz 1f\n\t"
347 "movl $-1,%0\n\t"
348 "1:\n\t"
349 : "=r" (r) : "rm" (x));
350 return r + 1;
351 }
352 #define HAS_FLS_U32
353 #endif
354
355 #if defined(__x86_64)
356 static inline
357 unsigned int fls_u64(uint64_t x)
358 {
359 long r;
360
361 asm("bsrq %1,%0\n\t"
362 "jnz 1f\n\t"
363 "movq $-1,%0\n\t"
364 "1:\n\t"
365 : "=r" (r) : "rm" (x));
366 return r + 1;
367 }
368 #define HAS_FLS_U64
369 #endif
370
371 #ifndef HAS_FLS_U64
372 static __attribute__((unused))
373 unsigned int fls_u64(uint64_t x)
374 {
375 unsigned int r = 64;
376
377 if (!x)
378 return 0;
379
380 if (!(x & 0xFFFFFFFF00000000ULL)) {
381 x <<= 32;
382 r -= 32;
383 }
384 if (!(x & 0xFFFF000000000000ULL)) {
385 x <<= 16;
386 r -= 16;
387 }
388 if (!(x & 0xFF00000000000000ULL)) {
389 x <<= 8;
390 r -= 8;
391 }
392 if (!(x & 0xF000000000000000ULL)) {
393 x <<= 4;
394 r -= 4;
395 }
396 if (!(x & 0xC000000000000000ULL)) {
397 x <<= 2;
398 r -= 2;
399 }
400 if (!(x & 0x8000000000000000ULL)) {
401 x <<= 1;
402 r -= 1;
403 }
404 return r;
405 }
406 #endif
407
408 #ifndef HAS_FLS_U32
409 static __attribute__((unused))
410 unsigned int fls_u32(uint32_t x)
411 {
412 unsigned int r = 32;
413
414 if (!x)
415 return 0;
416 if (!(x & 0xFFFF0000U)) {
417 x <<= 16;
418 r -= 16;
419 }
420 if (!(x & 0xFF000000U)) {
421 x <<= 8;
422 r -= 8;
423 }
424 if (!(x & 0xF0000000U)) {
425 x <<= 4;
426 r -= 4;
427 }
428 if (!(x & 0xC0000000U)) {
429 x <<= 2;
430 r -= 2;
431 }
432 if (!(x & 0x80000000U)) {
433 x <<= 1;
434 r -= 1;
435 }
436 return r;
437 }
438 #endif
439
440 unsigned int fls_ulong(unsigned long x)
441 {
442 #if (CAA_BITS_PER_lONG == 32)
443 return fls_u32(x);
444 #else
445 return fls_u64(x);
446 #endif
447 }
448
449 /*
450 * Return the minimum order for which x <= (1UL << order).
451 * Return -1 if x is 0.
452 */
453 int get_count_order_u32(uint32_t x)
454 {
455 if (!x)
456 return -1;
457
458 return fls_u32(x - 1);
459 }
460
461 /*
462 * Return the minimum order for which x <= (1UL << order).
463 * Return -1 if x is 0.
464 */
465 int get_count_order_ulong(unsigned long x)
466 {
467 if (!x)
468 return -1;
469
470 return fls_ulong(x - 1);
471 }
472
473 #ifdef POISON_FREE
474 #define poison_free(ptr) \
475 do { \
476 memset(ptr, 0x42, sizeof(*(ptr))); \
477 free(ptr); \
478 } while (0)
479 #else
480 #define poison_free(ptr) free(ptr)
481 #endif
482
483 static
484 void cds_lfht_resize_lazy(struct cds_lfht *ht, unsigned long size, int growth);
485
486 /*
487 * If the sched_getcpu() and sysconf(_SC_NPROCESSORS_CONF) calls are
488 * available, then we support hash table item accounting.
489 * In the unfortunate event the number of CPUs reported would be
490 * inaccurate, we use modulo arithmetic on the number of CPUs we got.
491 */
492 #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF)
493
494 static
495 void cds_lfht_resize_lazy_count(struct cds_lfht *ht, unsigned long size,
496 unsigned long count);
497
498 static long nr_cpus_mask = -1;
499
500 static
501 struct ht_items_count *alloc_per_cpu_items_count(void)
502 {
503 struct ht_items_count *count;
504
505 switch (nr_cpus_mask) {
506 case -2:
507 return NULL;
508 case -1:
509 {
510 long maxcpus;
511
512 maxcpus = sysconf(_SC_NPROCESSORS_CONF);
513 if (maxcpus <= 0) {
514 nr_cpus_mask = -2;
515 return NULL;
516 }
517 /*
518 * round up number of CPUs to next power of two, so we
519 * can use & for modulo.
520 */
521 maxcpus = 1UL << get_count_order_ulong(maxcpus);
522 nr_cpus_mask = maxcpus - 1;
523 }
524 /* Fall-through */
525 default:
526 return calloc(nr_cpus_mask + 1, sizeof(*count));
527 }
528 }
529
530 static
531 void free_per_cpu_items_count(struct ht_items_count *count)
532 {
533 poison_free(count);
534 }
535
536 static
537 int ht_get_cpu(void)
538 {
539 int cpu;
540
541 assert(nr_cpus_mask >= 0);
542 cpu = sched_getcpu();
543 if (unlikely(cpu < 0))
544 return cpu;
545 else
546 return cpu & nr_cpus_mask;
547 }
548
549 static
550 void ht_count_add(struct cds_lfht *ht, unsigned long size)
551 {
552 unsigned long percpu_count;
553 int cpu;
554
555 if (unlikely(!ht->percpu_count))
556 return;
557 cpu = ht_get_cpu();
558 if (unlikely(cpu < 0))
559 return;
560 percpu_count = uatomic_add_return(&ht->percpu_count[cpu].add, 1);
561 if (unlikely(!(percpu_count & ((1UL << COUNT_COMMIT_ORDER) - 1)))) {
562 long count;
563
564 dbg_printf("add percpu %lu\n", percpu_count);
565 count = uatomic_add_return(&ht->count,
566 1UL << COUNT_COMMIT_ORDER);
567 /* If power of 2 */
568 if (!(count & (count - 1))) {
569 if ((count >> CHAIN_LEN_RESIZE_THRESHOLD) < size)
570 return;
571 dbg_printf("add set global %ld\n", count);
572 cds_lfht_resize_lazy_count(ht, size,
573 count >> (CHAIN_LEN_TARGET - 1));
574 }
575 }
576 }
577
578 static
579 void ht_count_del(struct cds_lfht *ht, unsigned long size)
580 {
581 unsigned long percpu_count;
582 int cpu;
583
584 if (unlikely(!ht->percpu_count))
585 return;
586 cpu = ht_get_cpu();
587 if (unlikely(cpu < 0))
588 return;
589 percpu_count = uatomic_add_return(&ht->percpu_count[cpu].del, 1);
590 if (unlikely(!(percpu_count & ((1UL << COUNT_COMMIT_ORDER) - 1)))) {
591 long count;
592
593 dbg_printf("del percpu %lu\n", percpu_count);
594 count = uatomic_add_return(&ht->count,
595 -(1UL << COUNT_COMMIT_ORDER));
596 /* If power of 2 */
597 if (!(count & (count - 1))) {
598 if ((count >> CHAIN_LEN_RESIZE_THRESHOLD) >= size)
599 return;
600 dbg_printf("del set global %ld\n", count);
601 /*
602 * Don't shrink table if the number of nodes is below a
603 * certain threshold.
604 */
605 if (count < (1UL << COUNT_COMMIT_ORDER) * (nr_cpus_mask + 1))
606 return;
607 cds_lfht_resize_lazy_count(ht, size,
608 count >> (CHAIN_LEN_TARGET - 1));
609 }
610 }
611 }
612
613 #else /* #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF) */
614
615 static const long nr_cpus_mask = -2;
616
617 static
618 struct ht_items_count *alloc_per_cpu_items_count(void)
619 {
620 return NULL;
621 }
622
623 static
624 void free_per_cpu_items_count(struct ht_items_count *count)
625 {
626 }
627
628 static
629 void ht_count_add(struct cds_lfht *ht, unsigned long size)
630 {
631 }
632
633 static
634 void ht_count_del(struct cds_lfht *ht, unsigned long size)
635 {
636 }
637
638 #endif /* #else #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF) */
639
640
641 static
642 void check_resize(struct cds_lfht *ht, unsigned long size, uint32_t chain_len)
643 {
644 unsigned long count;
645
646 if (!(ht->flags & CDS_LFHT_AUTO_RESIZE))
647 return;
648 count = uatomic_read(&ht->count);
649 /*
650 * Use bucket-local length for small table expand and for
651 * environments lacking per-cpu data support.
652 */
653 if (count >= (1UL << COUNT_COMMIT_ORDER))
654 return;
655 if (chain_len > 100)
656 dbg_printf("WARNING: large chain length: %u.\n",
657 chain_len);
658 if (chain_len >= CHAIN_LEN_RESIZE_THRESHOLD)
659 cds_lfht_resize_lazy(ht, size,
660 get_count_order_u32(chain_len - (CHAIN_LEN_TARGET - 1)));
661 }
662
663 static
664 struct cds_lfht_node *clear_flag(struct cds_lfht_node *node)
665 {
666 return (struct cds_lfht_node *) (((unsigned long) node) & ~FLAGS_MASK);
667 }
668
669 static
670 int is_removed(struct cds_lfht_node *node)
671 {
672 return ((unsigned long) node) & REMOVED_FLAG;
673 }
674
675 static
676 struct cds_lfht_node *flag_removed(struct cds_lfht_node *node)
677 {
678 return (struct cds_lfht_node *) (((unsigned long) node) | REMOVED_FLAG);
679 }
680
681 static
682 int is_dummy(struct cds_lfht_node *node)
683 {
684 return ((unsigned long) node) & DUMMY_FLAG;
685 }
686
687 static
688 struct cds_lfht_node *flag_dummy(struct cds_lfht_node *node)
689 {
690 return (struct cds_lfht_node *) (((unsigned long) node) | DUMMY_FLAG);
691 }
692
693 static
694 struct cds_lfht_node *get_end(void)
695 {
696 return (struct cds_lfht_node *) END_VALUE;
697 }
698
699 static
700 int is_end(struct cds_lfht_node *node)
701 {
702 return clear_flag(node) == (struct cds_lfht_node *) END_VALUE;
703 }
704
705 static
706 unsigned long _uatomic_max(unsigned long *ptr, unsigned long v)
707 {
708 unsigned long old1, old2;
709
710 old1 = uatomic_read(ptr);
711 do {
712 old2 = old1;
713 if (old2 >= v)
714 return old2;
715 } while ((old1 = uatomic_cmpxchg(ptr, old2, v)) != old2);
716 return v;
717 }
718
719 static
720 struct _cds_lfht_node *lookup_bucket(struct cds_lfht *ht, unsigned long size,
721 unsigned long hash)
722 {
723 unsigned long index, order;
724
725 assert(size > 0);
726 index = hash & (size - 1);
727 /*
728 * equivalent to get_count_order_ulong(index + 1), but optimizes
729 * away the non-existing 0 special-case for
730 * get_count_order_ulong.
731 */
732 order = fls_ulong(index);
733
734 dbg_printf("lookup hash %lu index %lu order %lu aridx %lu\n",
735 hash, index, order, index & (!order ? 0 : ((1UL << (order - 1)) - 1)));
736
737 return &ht->t.tbl[order]->nodes[index & (!order ? 0 : ((1UL << (order - 1)) - 1))];
738 }
739
740 /*
741 * Remove all logically deleted nodes from a bucket up to a certain node key.
742 */
743 static
744 void _cds_lfht_gc_bucket(struct cds_lfht_node *dummy, struct cds_lfht_node *node)
745 {
746 struct cds_lfht_node *iter_prev, *iter, *next, *new_next;
747
748 assert(!is_dummy(dummy));
749 assert(!is_removed(dummy));
750 assert(!is_dummy(node));
751 assert(!is_removed(node));
752 for (;;) {
753 iter_prev = dummy;
754 /* We can always skip the dummy node initially */
755 iter = rcu_dereference(iter_prev->p.next);
756 assert(iter_prev->p.reverse_hash <= node->p.reverse_hash);
757 /*
758 * We should never be called with dummy (start of chain)
759 * and logically removed node (end of path compression
760 * marker) being the actual same node. This would be a
761 * bug in the algorithm implementation.
762 */
763 assert(dummy != node);
764 for (;;) {
765 if (unlikely(is_end(iter)))
766 return;
767 if (likely(clear_flag(iter)->p.reverse_hash > node->p.reverse_hash))
768 return;
769 next = rcu_dereference(clear_flag(iter)->p.next);
770 if (likely(is_removed(next)))
771 break;
772 iter_prev = clear_flag(iter);
773 iter = next;
774 }
775 assert(!is_removed(iter));
776 if (is_dummy(iter))
777 new_next = flag_dummy(clear_flag(next));
778 else
779 new_next = clear_flag(next);
780 if (is_removed(iter))
781 new_next = flag_removed(new_next);
782 (void) uatomic_cmpxchg(&iter_prev->p.next, iter, new_next);
783 }
784 return;
785 }
786
787 static
788 int _cds_lfht_replace(struct cds_lfht *ht, unsigned long size,
789 struct cds_lfht_node *old_node,
790 struct cds_lfht_node *ret_next,
791 struct cds_lfht_node *new_node)
792 {
793 struct cds_lfht_node *dummy, *old_next;
794 struct _cds_lfht_node *lookup;
795 int flagged = 0;
796
797 if (!old_node) /* Return -ENOENT if asked to replace NULL node */
798 goto end;
799
800 assert(!is_removed(old_node));
801 assert(!is_dummy(old_node));
802 assert(!is_removed(new_node));
803 assert(!is_dummy(new_node));
804 assert(new_node != old_node);
805 do {
806 /* Insert after node to be replaced */
807 old_next = ret_next;
808 if (is_removed(old_next)) {
809 /*
810 * Too late, the old node has been removed under us
811 * between lookup and replace. Fail.
812 */
813 goto end;
814 }
815 assert(!is_dummy(old_next));
816 assert(new_node != clear_flag(old_next));
817 new_node->p.next = clear_flag(old_next);
818 /*
819 * Here is the whole trick for lock-free replace: we add
820 * the replacement node _after_ the node we want to
821 * replace by atomically setting its next pointer at the
822 * same time we set its removal flag. Given that
823 * the lookups/get next use an iterator aware of the
824 * next pointer, they will either skip the old node due
825 * to the removal flag and see the new node, or use
826 * the old node, but will not see the new one.
827 */
828 ret_next = uatomic_cmpxchg(&old_node->p.next,
829 old_next, flag_removed(new_node));
830 } while (ret_next != old_next);
831
832 /* We performed the replacement. */
833 flagged = 1;
834
835 /*
836 * Ensure that the old node is not visible to readers anymore:
837 * lookup for the node, and remove it (along with any other
838 * logically removed node) if found.
839 */
840 lookup = lookup_bucket(ht, size, bit_reverse_ulong(old_node->p.reverse_hash));
841 dummy = (struct cds_lfht_node *) lookup;
842 _cds_lfht_gc_bucket(dummy, new_node);
843 end:
844 /*
845 * Only the flagging action indicated that we (and no other)
846 * replaced the node from the hash table.
847 */
848 if (flagged) {
849 assert(is_removed(rcu_dereference(old_node->p.next)));
850 return 0;
851 } else {
852 return -ENOENT;
853 }
854 }
855
856 static
857 struct cds_lfht_node *_cds_lfht_add(struct cds_lfht *ht,
858 unsigned long size,
859 struct cds_lfht_node *node,
860 enum add_mode mode, int dummy)
861 {
862 struct cds_lfht_node *iter_prev, *iter, *next, *new_node, *new_next,
863 *return_node;
864 struct _cds_lfht_node *lookup;
865
866 assert(!is_dummy(node));
867 assert(!is_removed(node));
868 if (!size) {
869 assert(dummy);
870 node->p.next = flag_dummy(get_end());
871 return node; /* Initial first add (head) */
872 }
873 lookup = lookup_bucket(ht, size, bit_reverse_ulong(node->p.reverse_hash));
874 for (;;) {
875 uint32_t chain_len = 0;
876
877 /*
878 * iter_prev points to the non-removed node prior to the
879 * insert location.
880 */
881 iter_prev = (struct cds_lfht_node *) lookup;
882 /* We can always skip the dummy node initially */
883 iter = rcu_dereference(iter_prev->p.next);
884 assert(iter_prev->p.reverse_hash <= node->p.reverse_hash);
885 for (;;) {
886 if (unlikely(is_end(iter)))
887 goto insert;
888 if (likely(clear_flag(iter)->p.reverse_hash > node->p.reverse_hash))
889 goto insert;
890 next = rcu_dereference(clear_flag(iter)->p.next);
891 if (unlikely(is_removed(next)))
892 goto gc_node;
893 if ((mode == ADD_UNIQUE || mode == ADD_REPLACE)
894 && !is_dummy(next)
895 && !ht->compare_fct(node->key, node->key_len,
896 clear_flag(iter)->key,
897 clear_flag(iter)->key_len)) {
898 if (mode == ADD_UNIQUE)
899 return clear_flag(iter);
900 else /* mode == ADD_REPLACE */
901 goto replace;
902 }
903 /* Only account for identical reverse hash once */
904 if (iter_prev->p.reverse_hash != clear_flag(iter)->p.reverse_hash
905 && !is_dummy(next))
906 check_resize(ht, size, ++chain_len);
907 iter_prev = clear_flag(iter);
908 iter = next;
909 }
910
911 insert:
912 assert(node != clear_flag(iter));
913 assert(!is_removed(iter_prev));
914 assert(!is_removed(iter));
915 assert(iter_prev != node);
916 if (!dummy)
917 node->p.next = clear_flag(iter);
918 else
919 node->p.next = flag_dummy(clear_flag(iter));
920 if (is_dummy(iter))
921 new_node = flag_dummy(node);
922 else
923 new_node = node;
924 if (uatomic_cmpxchg(&iter_prev->p.next, iter,
925 new_node) != iter) {
926 continue; /* retry */
927 } else {
928 if (mode == ADD_REPLACE)
929 return_node = NULL;
930 else /* ADD_DEFAULT and ADD_UNIQUE */
931 return_node = node;
932 goto end;
933 }
934
935 replace:
936
937 if (!_cds_lfht_replace(ht, size, clear_flag(iter), next,
938 node)) {
939 return_node = clear_flag(iter);
940 goto end; /* gc already done */
941 } else {
942 continue; /* retry */
943 }
944
945 gc_node:
946 assert(!is_removed(iter));
947 if (is_dummy(iter))
948 new_next = flag_dummy(clear_flag(next));
949 else
950 new_next = clear_flag(next);
951 (void) uatomic_cmpxchg(&iter_prev->p.next, iter, new_next);
952 /* retry */
953 }
954 end:
955 return return_node;
956 }
957
958 static
959 int _cds_lfht_del(struct cds_lfht *ht, unsigned long size,
960 struct cds_lfht_node *node,
961 int dummy_removal)
962 {
963 struct cds_lfht_node *dummy, *next, *old;
964 struct _cds_lfht_node *lookup;
965 int flagged = 0;
966
967 if (!node) /* Return -ENOENT if asked to delete NULL node */
968 goto end;
969
970 /* logically delete the node */
971 assert(!is_dummy(node));
972 assert(!is_removed(node));
973 old = rcu_dereference(node->p.next);
974 do {
975 struct cds_lfht_node *new_next;
976
977 next = old;
978 if (unlikely(is_removed(next)))
979 goto end;
980 if (dummy_removal)
981 assert(is_dummy(next));
982 else
983 assert(!is_dummy(next));
984 new_next = flag_removed(next);
985 old = uatomic_cmpxchg(&node->p.next, next, new_next);
986 } while (old != next);
987
988 /* We performed the (logical) deletion. */
989 flagged = 1;
990
991 /*
992 * Ensure that the node is not visible to readers anymore: lookup for
993 * the node, and remove it (along with any other logically removed node)
994 * if found.
995 */
996 lookup = lookup_bucket(ht, size, bit_reverse_ulong(node->p.reverse_hash));
997 dummy = (struct cds_lfht_node *) lookup;
998 _cds_lfht_gc_bucket(dummy, node);
999 end:
1000 /*
1001 * Only the flagging action indicated that we (and no other)
1002 * removed the node from the hash.
1003 */
1004 if (flagged) {
1005 assert(is_removed(rcu_dereference(node->p.next)));
1006 return 0;
1007 } else {
1008 return -ENOENT;
1009 }
1010 }
1011
1012 static
1013 void *partition_resize_thread(void *arg)
1014 {
1015 struct partition_resize_work *work = arg;
1016
1017 work->ht->cds_lfht_rcu_register_thread();
1018 work->fct(work->ht, work->i, work->start, work->len);
1019 work->ht->cds_lfht_rcu_unregister_thread();
1020 return NULL;
1021 }
1022
1023 static
1024 void partition_resize_helper(struct cds_lfht *ht, unsigned long i,
1025 unsigned long len,
1026 void (*fct)(struct cds_lfht *ht, unsigned long i,
1027 unsigned long start, unsigned long len))
1028 {
1029 unsigned long partition_len;
1030 struct partition_resize_work *work;
1031 int thread, ret;
1032 unsigned long nr_threads;
1033
1034 /*
1035 * Note: nr_cpus_mask + 1 is always power of 2.
1036 * We spawn just the number of threads we need to satisfy the minimum
1037 * partition size, up to the number of CPUs in the system.
1038 */
1039 if (nr_cpus_mask > 0) {
1040 nr_threads = min(nr_cpus_mask + 1,
1041 len >> MIN_PARTITION_PER_THREAD_ORDER);
1042 } else {
1043 nr_threads = 1;
1044 }
1045 partition_len = len >> get_count_order_ulong(nr_threads);
1046 work = calloc(nr_threads, sizeof(*work));
1047 assert(work);
1048 for (thread = 0; thread < nr_threads; thread++) {
1049 work[thread].ht = ht;
1050 work[thread].i = i;
1051 work[thread].len = partition_len;
1052 work[thread].start = thread * partition_len;
1053 work[thread].fct = fct;
1054 ret = pthread_create(&(work[thread].thread_id), ht->resize_attr,
1055 partition_resize_thread, &work[thread]);
1056 assert(!ret);
1057 }
1058 for (thread = 0; thread < nr_threads; thread++) {
1059 ret = pthread_join(work[thread].thread_id, NULL);
1060 assert(!ret);
1061 }
1062 free(work);
1063 }
1064
1065 /*
1066 * Holding RCU read lock to protect _cds_lfht_add against memory
1067 * reclaim that could be performed by other call_rcu worker threads (ABA
1068 * problem).
1069 *
1070 * When we reach a certain length, we can split this population phase over
1071 * many worker threads, based on the number of CPUs available in the system.
1072 * This should therefore take care of not having the expand lagging behind too
1073 * many concurrent insertion threads by using the scheduler's ability to
1074 * schedule dummy node population fairly with insertions.
1075 */
1076 static
1077 void init_table_populate_partition(struct cds_lfht *ht, unsigned long i,
1078 unsigned long start, unsigned long len)
1079 {
1080 unsigned long j;
1081
1082 ht->cds_lfht_rcu_read_lock();
1083 for (j = start; j < start + len; j++) {
1084 struct cds_lfht_node *new_node =
1085 (struct cds_lfht_node *) &ht->t.tbl[i]->nodes[j];
1086
1087 dbg_printf("init populate: i %lu j %lu hash %lu\n",
1088 i, j, !i ? 0 : (1UL << (i - 1)) + j);
1089 new_node->p.reverse_hash =
1090 bit_reverse_ulong(!i ? 0 : (1UL << (i - 1)) + j);
1091 (void) _cds_lfht_add(ht, !i ? 0 : (1UL << (i - 1)),
1092 new_node, ADD_DEFAULT, 1);
1093 }
1094 ht->cds_lfht_rcu_read_unlock();
1095 }
1096
1097 static
1098 void init_table_populate(struct cds_lfht *ht, unsigned long i,
1099 unsigned long len)
1100 {
1101 assert(nr_cpus_mask != -1);
1102 if (nr_cpus_mask < 0 || len < 2 * MIN_PARTITION_PER_THREAD) {
1103 ht->cds_lfht_rcu_thread_online();
1104 init_table_populate_partition(ht, i, 0, len);
1105 ht->cds_lfht_rcu_thread_offline();
1106 return;
1107 }
1108 partition_resize_helper(ht, i, len, init_table_populate_partition);
1109 }
1110
1111 static
1112 void init_table(struct cds_lfht *ht,
1113 unsigned long first_order, unsigned long len_order)
1114 {
1115 unsigned long i, end_order;
1116
1117 dbg_printf("init table: first_order %lu end_order %lu\n",
1118 first_order, first_order + len_order);
1119 end_order = first_order + len_order;
1120 for (i = first_order; i < end_order; i++) {
1121 unsigned long len;
1122
1123 len = !i ? 1 : 1UL << (i - 1);
1124 dbg_printf("init order %lu len: %lu\n", i, len);
1125
1126 /* Stop expand if the resize target changes under us */
1127 if (CMM_LOAD_SHARED(ht->t.resize_target) < (!i ? 1 : (1UL << i)))
1128 break;
1129
1130 ht->t.tbl[i] = calloc(1, len * sizeof(struct _cds_lfht_node));
1131 assert(ht->t.tbl[i]);
1132
1133 /*
1134 * Set all dummy nodes reverse hash values for a level and
1135 * link all dummy nodes into the table.
1136 */
1137 init_table_populate(ht, i, len);
1138
1139 /*
1140 * Update table size.
1141 */
1142 cmm_smp_wmb(); /* populate data before RCU size */
1143 CMM_STORE_SHARED(ht->t.size, !i ? 1 : (1UL << i));
1144
1145 dbg_printf("init new size: %lu\n", !i ? 1 : (1UL << i));
1146 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
1147 break;
1148 }
1149 }
1150
1151 /*
1152 * Holding RCU read lock to protect _cds_lfht_remove against memory
1153 * reclaim that could be performed by other call_rcu worker threads (ABA
1154 * problem).
1155 * For a single level, we logically remove and garbage collect each node.
1156 *
1157 * As a design choice, we perform logical removal and garbage collection on a
1158 * node-per-node basis to simplify this algorithm. We also assume keeping good
1159 * cache locality of the operation would overweight possible performance gain
1160 * that could be achieved by batching garbage collection for multiple levels.
1161 * However, this would have to be justified by benchmarks.
1162 *
1163 * Concurrent removal and add operations are helping us perform garbage
1164 * collection of logically removed nodes. We guarantee that all logically
1165 * removed nodes have been garbage-collected (unlinked) before call_rcu is
1166 * invoked to free a hole level of dummy nodes (after a grace period).
1167 *
1168 * Logical removal and garbage collection can therefore be done in batch or on a
1169 * node-per-node basis, as long as the guarantee above holds.
1170 *
1171 * When we reach a certain length, we can split this removal over many worker
1172 * threads, based on the number of CPUs available in the system. This should
1173 * take care of not letting resize process lag behind too many concurrent
1174 * updater threads actively inserting into the hash table.
1175 */
1176 static
1177 void remove_table_partition(struct cds_lfht *ht, unsigned long i,
1178 unsigned long start, unsigned long len)
1179 {
1180 unsigned long j;
1181
1182 ht->cds_lfht_rcu_read_lock();
1183 for (j = start; j < start + len; j++) {
1184 struct cds_lfht_node *fini_node =
1185 (struct cds_lfht_node *) &ht->t.tbl[i]->nodes[j];
1186
1187 dbg_printf("remove entry: i %lu j %lu hash %lu\n",
1188 i, j, !i ? 0 : (1UL << (i - 1)) + j);
1189 fini_node->p.reverse_hash =
1190 bit_reverse_ulong(!i ? 0 : (1UL << (i - 1)) + j);
1191 (void) _cds_lfht_del(ht, !i ? 0 : (1UL << (i - 1)),
1192 fini_node, 1);
1193 }
1194 ht->cds_lfht_rcu_read_unlock();
1195 }
1196
1197 static
1198 void remove_table(struct cds_lfht *ht, unsigned long i, unsigned long len)
1199 {
1200
1201 assert(nr_cpus_mask != -1);
1202 if (nr_cpus_mask < 0 || len < 2 * MIN_PARTITION_PER_THREAD) {
1203 ht->cds_lfht_rcu_thread_online();
1204 remove_table_partition(ht, i, 0, len);
1205 ht->cds_lfht_rcu_thread_offline();
1206 return;
1207 }
1208 partition_resize_helper(ht, i, len, remove_table_partition);
1209 }
1210
1211 static
1212 void fini_table(struct cds_lfht *ht,
1213 unsigned long first_order, unsigned long len_order)
1214 {
1215 long i, end_order;
1216 void *free_by_rcu = NULL;
1217
1218 dbg_printf("fini table: first_order %lu end_order %lu\n",
1219 first_order, first_order + len_order);
1220 end_order = first_order + len_order;
1221 assert(first_order > 0);
1222 for (i = end_order - 1; i >= first_order; i--) {
1223 unsigned long len;
1224
1225 len = !i ? 1 : 1UL << (i - 1);
1226 dbg_printf("fini order %lu len: %lu\n", i, len);
1227
1228 /* Stop shrink if the resize target changes under us */
1229 if (CMM_LOAD_SHARED(ht->t.resize_target) > (1UL << (i - 1)))
1230 break;
1231
1232 cmm_smp_wmb(); /* populate data before RCU size */
1233 CMM_STORE_SHARED(ht->t.size, 1UL << (i - 1));
1234
1235 /*
1236 * We need to wait for all add operations to reach Q.S. (and
1237 * thus use the new table for lookups) before we can start
1238 * releasing the old dummy nodes. Otherwise their lookup will
1239 * return a logically removed node as insert position.
1240 */
1241 ht->cds_lfht_synchronize_rcu();
1242 if (free_by_rcu)
1243 free(free_by_rcu);
1244
1245 /*
1246 * Set "removed" flag in dummy nodes about to be removed.
1247 * Unlink all now-logically-removed dummy node pointers.
1248 * Concurrent add/remove operation are helping us doing
1249 * the gc.
1250 */
1251 remove_table(ht, i, len);
1252
1253 free_by_rcu = ht->t.tbl[i];
1254
1255 dbg_printf("fini new size: %lu\n", 1UL << i);
1256 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
1257 break;
1258 }
1259
1260 if (free_by_rcu) {
1261 ht->cds_lfht_synchronize_rcu();
1262 free(free_by_rcu);
1263 }
1264 }
1265
1266 struct cds_lfht *_cds_lfht_new(cds_lfht_hash_fct hash_fct,
1267 cds_lfht_compare_fct compare_fct,
1268 unsigned long hash_seed,
1269 unsigned long init_size,
1270 int flags,
1271 void (*cds_lfht_call_rcu)(struct rcu_head *head,
1272 void (*func)(struct rcu_head *head)),
1273 void (*cds_lfht_synchronize_rcu)(void),
1274 void (*cds_lfht_rcu_read_lock)(void),
1275 void (*cds_lfht_rcu_read_unlock)(void),
1276 void (*cds_lfht_rcu_thread_offline)(void),
1277 void (*cds_lfht_rcu_thread_online)(void),
1278 void (*cds_lfht_rcu_register_thread)(void),
1279 void (*cds_lfht_rcu_unregister_thread)(void),
1280 pthread_attr_t *attr)
1281 {
1282 struct cds_lfht *ht;
1283 unsigned long order;
1284
1285 /* init_size must be power of two */
1286 if (init_size && (init_size & (init_size - 1)))
1287 return NULL;
1288 ht = calloc(1, sizeof(struct cds_lfht));
1289 assert(ht);
1290 ht->hash_fct = hash_fct;
1291 ht->compare_fct = compare_fct;
1292 ht->hash_seed = hash_seed;
1293 ht->cds_lfht_call_rcu = cds_lfht_call_rcu;
1294 ht->cds_lfht_synchronize_rcu = cds_lfht_synchronize_rcu;
1295 ht->cds_lfht_rcu_read_lock = cds_lfht_rcu_read_lock;
1296 ht->cds_lfht_rcu_read_unlock = cds_lfht_rcu_read_unlock;
1297 ht->cds_lfht_rcu_thread_offline = cds_lfht_rcu_thread_offline;
1298 ht->cds_lfht_rcu_thread_online = cds_lfht_rcu_thread_online;
1299 ht->cds_lfht_rcu_register_thread = cds_lfht_rcu_register_thread;
1300 ht->cds_lfht_rcu_unregister_thread = cds_lfht_rcu_unregister_thread;
1301 ht->resize_attr = attr;
1302 ht->percpu_count = alloc_per_cpu_items_count();
1303 /* this mutex should not nest in read-side C.S. */
1304 pthread_mutex_init(&ht->resize_mutex, NULL);
1305 order = get_count_order_ulong(max(init_size, MIN_TABLE_SIZE)) + 1;
1306 ht->flags = flags;
1307 ht->cds_lfht_rcu_thread_offline();
1308 pthread_mutex_lock(&ht->resize_mutex);
1309 ht->t.resize_target = 1UL << (order - 1);
1310 init_table(ht, 0, order);
1311 pthread_mutex_unlock(&ht->resize_mutex);
1312 ht->cds_lfht_rcu_thread_online();
1313 return ht;
1314 }
1315
1316 void cds_lfht_lookup(struct cds_lfht *ht, void *key, size_t key_len,
1317 struct cds_lfht_iter *iter)
1318 {
1319 struct cds_lfht_node *node, *next, *dummy_node;
1320 struct _cds_lfht_node *lookup;
1321 unsigned long hash, reverse_hash, size;
1322
1323 hash = ht->hash_fct(key, key_len, ht->hash_seed);
1324 reverse_hash = bit_reverse_ulong(hash);
1325
1326 size = rcu_dereference(ht->t.size);
1327 lookup = lookup_bucket(ht, size, hash);
1328 dummy_node = (struct cds_lfht_node *) lookup;
1329 /* We can always skip the dummy node initially */
1330 node = rcu_dereference(dummy_node->p.next);
1331 node = clear_flag(node);
1332 for (;;) {
1333 if (unlikely(is_end(node))) {
1334 node = next = NULL;
1335 break;
1336 }
1337 if (unlikely(node->p.reverse_hash > reverse_hash)) {
1338 node = next = NULL;
1339 break;
1340 }
1341 next = rcu_dereference(node->p.next);
1342 if (likely(!is_removed(next))
1343 && !is_dummy(next)
1344 && likely(!ht->compare_fct(node->key, node->key_len, key, key_len))) {
1345 break;
1346 }
1347 node = clear_flag(next);
1348 }
1349 assert(!node || !is_dummy(rcu_dereference(node->p.next)));
1350 iter->node = node;
1351 iter->next = next;
1352 }
1353
1354 void cds_lfht_next_duplicate(struct cds_lfht *ht, struct cds_lfht_iter *iter)
1355 {
1356 struct cds_lfht_node *node, *next;
1357 unsigned long reverse_hash;
1358 void *key;
1359 size_t key_len;
1360
1361 node = iter->node;
1362 reverse_hash = node->p.reverse_hash;
1363 key = node->key;
1364 key_len = node->key_len;
1365 next = iter->next;
1366 node = clear_flag(next);
1367
1368 for (;;) {
1369 if (unlikely(is_end(node))) {
1370 node = next = NULL;
1371 break;
1372 }
1373 if (unlikely(node->p.reverse_hash > reverse_hash)) {
1374 node = next = NULL;
1375 break;
1376 }
1377 next = rcu_dereference(node->p.next);
1378 if (likely(!is_removed(next))
1379 && !is_dummy(next)
1380 && likely(!ht->compare_fct(node->key, node->key_len, key, key_len))) {
1381 break;
1382 }
1383 node = clear_flag(next);
1384 }
1385 assert(!node || !is_dummy(rcu_dereference(node->p.next)));
1386 iter->node = node;
1387 iter->next = next;
1388 }
1389
1390 void cds_lfht_next(struct cds_lfht *ht, struct cds_lfht_iter *iter)
1391 {
1392 struct cds_lfht_node *node, *next;
1393
1394 node = clear_flag(iter->next);
1395 for (;;) {
1396 if (unlikely(is_end(node))) {
1397 node = next = NULL;
1398 break;
1399 }
1400 next = rcu_dereference(node->p.next);
1401 if (likely(!is_removed(next))
1402 && !is_dummy(next)) {
1403 break;
1404 }
1405 node = clear_flag(next);
1406 }
1407 assert(!node || !is_dummy(rcu_dereference(node->p.next)));
1408 iter->node = node;
1409 iter->next = next;
1410 }
1411
1412 void cds_lfht_first(struct cds_lfht *ht, struct cds_lfht_iter *iter)
1413 {
1414 struct _cds_lfht_node *lookup;
1415
1416 /*
1417 * Get next after first dummy node. The first dummy node is the
1418 * first node of the linked list.
1419 */
1420 lookup = &ht->t.tbl[0]->nodes[0];
1421 iter->next = lookup->next;
1422 cds_lfht_next(ht, iter);
1423 }
1424
1425 void cds_lfht_add(struct cds_lfht *ht, struct cds_lfht_node *node)
1426 {
1427 unsigned long hash, size;
1428
1429 hash = ht->hash_fct(node->key, node->key_len, ht->hash_seed);
1430 node->p.reverse_hash = bit_reverse_ulong((unsigned long) hash);
1431
1432 size = rcu_dereference(ht->t.size);
1433 (void) _cds_lfht_add(ht, size, node, ADD_DEFAULT, 0);
1434 ht_count_add(ht, size);
1435 }
1436
1437 struct cds_lfht_node *cds_lfht_add_unique(struct cds_lfht *ht,
1438 struct cds_lfht_node *node)
1439 {
1440 unsigned long hash, size;
1441 struct cds_lfht_node *ret;
1442
1443 hash = ht->hash_fct(node->key, node->key_len, ht->hash_seed);
1444 node->p.reverse_hash = bit_reverse_ulong((unsigned long) hash);
1445
1446 size = rcu_dereference(ht->t.size);
1447 ret = _cds_lfht_add(ht, size, node, ADD_UNIQUE, 0);
1448 if (ret == node)
1449 ht_count_add(ht, size);
1450 return ret;
1451 }
1452
1453 struct cds_lfht_node *cds_lfht_add_replace(struct cds_lfht *ht,
1454 struct cds_lfht_node *node)
1455 {
1456 unsigned long hash, size;
1457 struct cds_lfht_node *ret;
1458
1459 hash = ht->hash_fct(node->key, node->key_len, ht->hash_seed);
1460 node->p.reverse_hash = bit_reverse_ulong((unsigned long) hash);
1461
1462 size = rcu_dereference(ht->t.size);
1463 ret = _cds_lfht_add(ht, size, node, ADD_REPLACE, 0);
1464 if (ret == NULL)
1465 ht_count_add(ht, size);
1466 return ret;
1467 }
1468
1469 int cds_lfht_replace(struct cds_lfht *ht, struct cds_lfht_iter *old_iter,
1470 struct cds_lfht_node *new_node)
1471 {
1472 unsigned long size;
1473
1474 size = rcu_dereference(ht->t.size);
1475 return _cds_lfht_replace(ht, size, old_iter->node, old_iter->next,
1476 new_node);
1477 }
1478
1479 int cds_lfht_del(struct cds_lfht *ht, struct cds_lfht_iter *iter)
1480 {
1481 unsigned long size;
1482 int ret;
1483
1484 size = rcu_dereference(ht->t.size);
1485 ret = _cds_lfht_del(ht, size, iter->node, 0);
1486 if (!ret)
1487 ht_count_del(ht, size);
1488 return ret;
1489 }
1490
1491 static
1492 int cds_lfht_delete_dummy(struct cds_lfht *ht)
1493 {
1494 struct cds_lfht_node *node;
1495 struct _cds_lfht_node *lookup;
1496 unsigned long order, i, size;
1497
1498 /* Check that the table is empty */
1499 lookup = &ht->t.tbl[0]->nodes[0];
1500 node = (struct cds_lfht_node *) lookup;
1501 do {
1502 node = clear_flag(node)->p.next;
1503 if (!is_dummy(node))
1504 return -EPERM;
1505 assert(!is_removed(node));
1506 } while (!is_end(node));
1507 /*
1508 * size accessed without rcu_dereference because hash table is
1509 * being destroyed.
1510 */
1511 size = ht->t.size;
1512 /* Internal sanity check: all nodes left should be dummy */
1513 for (order = 0; order < get_count_order_ulong(size) + 1; order++) {
1514 unsigned long len;
1515
1516 len = !order ? 1 : 1UL << (order - 1);
1517 for (i = 0; i < len; i++) {
1518 dbg_printf("delete order %lu i %lu hash %lu\n",
1519 order, i,
1520 bit_reverse_ulong(ht->t.tbl[order]->nodes[i].reverse_hash));
1521 assert(is_dummy(ht->t.tbl[order]->nodes[i].next));
1522 }
1523 poison_free(ht->t.tbl[order]);
1524 }
1525 return 0;
1526 }
1527
1528 /*
1529 * Should only be called when no more concurrent readers nor writers can
1530 * possibly access the table.
1531 */
1532 int cds_lfht_destroy(struct cds_lfht *ht, pthread_attr_t **attr)
1533 {
1534 int ret;
1535
1536 /* Wait for in-flight resize operations to complete */
1537 _CMM_STORE_SHARED(ht->in_progress_destroy, 1);
1538 cmm_smp_mb(); /* Store destroy before load resize */
1539 while (uatomic_read(&ht->in_progress_resize))
1540 poll(NULL, 0, 100); /* wait for 100ms */
1541 ret = cds_lfht_delete_dummy(ht);
1542 if (ret)
1543 return ret;
1544 free_per_cpu_items_count(ht->percpu_count);
1545 if (attr)
1546 *attr = ht->resize_attr;
1547 poison_free(ht);
1548 return ret;
1549 }
1550
1551 void cds_lfht_count_nodes(struct cds_lfht *ht,
1552 long *approx_before,
1553 unsigned long *count,
1554 unsigned long *removed,
1555 long *approx_after)
1556 {
1557 struct cds_lfht_node *node, *next;
1558 struct _cds_lfht_node *lookup;
1559 unsigned long nr_dummy = 0;
1560
1561 *approx_before = 0;
1562 if (nr_cpus_mask >= 0) {
1563 int i;
1564
1565 for (i = 0; i < nr_cpus_mask + 1; i++) {
1566 *approx_before += uatomic_read(&ht->percpu_count[i].add);
1567 *approx_before -= uatomic_read(&ht->percpu_count[i].del);
1568 }
1569 }
1570
1571 *count = 0;
1572 *removed = 0;
1573
1574 /* Count non-dummy nodes in the table */
1575 lookup = &ht->t.tbl[0]->nodes[0];
1576 node = (struct cds_lfht_node *) lookup;
1577 do {
1578 next = rcu_dereference(node->p.next);
1579 if (is_removed(next)) {
1580 if (!is_dummy(next))
1581 (*removed)++;
1582 else
1583 (nr_dummy)++;
1584 } else if (!is_dummy(next))
1585 (*count)++;
1586 else
1587 (nr_dummy)++;
1588 node = clear_flag(next);
1589 } while (!is_end(node));
1590 dbg_printf("number of dummy nodes: %lu\n", nr_dummy);
1591 *approx_after = 0;
1592 if (nr_cpus_mask >= 0) {
1593 int i;
1594
1595 for (i = 0; i < nr_cpus_mask + 1; i++) {
1596 *approx_after += uatomic_read(&ht->percpu_count[i].add);
1597 *approx_after -= uatomic_read(&ht->percpu_count[i].del);
1598 }
1599 }
1600 }
1601
1602 /* called with resize mutex held */
1603 static
1604 void _do_cds_lfht_grow(struct cds_lfht *ht,
1605 unsigned long old_size, unsigned long new_size)
1606 {
1607 unsigned long old_order, new_order;
1608
1609 old_order = get_count_order_ulong(old_size) + 1;
1610 new_order = get_count_order_ulong(new_size) + 1;
1611 dbg_printf("resize from %lu (order %lu) to %lu (order %lu) buckets\n",
1612 old_size, old_order, new_size, new_order);
1613 assert(new_size > old_size);
1614 init_table(ht, old_order, new_order - old_order);
1615 }
1616
1617 /* called with resize mutex held */
1618 static
1619 void _do_cds_lfht_shrink(struct cds_lfht *ht,
1620 unsigned long old_size, unsigned long new_size)
1621 {
1622 unsigned long old_order, new_order;
1623
1624 new_size = max(new_size, MIN_TABLE_SIZE);
1625 old_order = get_count_order_ulong(old_size) + 1;
1626 new_order = get_count_order_ulong(new_size) + 1;
1627 dbg_printf("resize from %lu (order %lu) to %lu (order %lu) buckets\n",
1628 old_size, old_order, new_size, new_order);
1629 assert(new_size < old_size);
1630
1631 /* Remove and unlink all dummy nodes to remove. */
1632 fini_table(ht, new_order, old_order - new_order);
1633 }
1634
1635
1636 /* called with resize mutex held */
1637 static
1638 void _do_cds_lfht_resize(struct cds_lfht *ht)
1639 {
1640 unsigned long new_size, old_size;
1641
1642 /*
1643 * Resize table, re-do if the target size has changed under us.
1644 */
1645 do {
1646 assert(uatomic_read(&ht->in_progress_resize));
1647 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
1648 break;
1649 ht->t.resize_initiated = 1;
1650 old_size = ht->t.size;
1651 new_size = CMM_LOAD_SHARED(ht->t.resize_target);
1652 if (old_size < new_size)
1653 _do_cds_lfht_grow(ht, old_size, new_size);
1654 else if (old_size > new_size)
1655 _do_cds_lfht_shrink(ht, old_size, new_size);
1656 ht->t.resize_initiated = 0;
1657 /* write resize_initiated before read resize_target */
1658 cmm_smp_mb();
1659 } while (ht->t.size != CMM_LOAD_SHARED(ht->t.resize_target));
1660 }
1661
1662 static
1663 unsigned long resize_target_update(struct cds_lfht *ht, unsigned long size,
1664 int growth_order)
1665 {
1666 return _uatomic_max(&ht->t.resize_target,
1667 size << growth_order);
1668 }
1669
1670 static
1671 void resize_target_update_count(struct cds_lfht *ht,
1672 unsigned long count)
1673 {
1674 count = max(count, MIN_TABLE_SIZE);
1675 uatomic_set(&ht->t.resize_target, count);
1676 }
1677
1678 void cds_lfht_resize(struct cds_lfht *ht, unsigned long new_size)
1679 {
1680 resize_target_update_count(ht, new_size);
1681 CMM_STORE_SHARED(ht->t.resize_initiated, 1);
1682 ht->cds_lfht_rcu_thread_offline();
1683 pthread_mutex_lock(&ht->resize_mutex);
1684 _do_cds_lfht_resize(ht);
1685 pthread_mutex_unlock(&ht->resize_mutex);
1686 ht->cds_lfht_rcu_thread_online();
1687 }
1688
1689 static
1690 void do_resize_cb(struct rcu_head *head)
1691 {
1692 struct rcu_resize_work *work =
1693 caa_container_of(head, struct rcu_resize_work, head);
1694 struct cds_lfht *ht = work->ht;
1695
1696 ht->cds_lfht_rcu_thread_offline();
1697 pthread_mutex_lock(&ht->resize_mutex);
1698 _do_cds_lfht_resize(ht);
1699 pthread_mutex_unlock(&ht->resize_mutex);
1700 ht->cds_lfht_rcu_thread_online();
1701 poison_free(work);
1702 cmm_smp_mb(); /* finish resize before decrement */
1703 uatomic_dec(&ht->in_progress_resize);
1704 }
1705
1706 static
1707 void cds_lfht_resize_lazy(struct cds_lfht *ht, unsigned long size, int growth)
1708 {
1709 struct rcu_resize_work *work;
1710 unsigned long target_size;
1711
1712 target_size = resize_target_update(ht, size, growth);
1713 /* Store resize_target before read resize_initiated */
1714 cmm_smp_mb();
1715 if (!CMM_LOAD_SHARED(ht->t.resize_initiated) && size < target_size) {
1716 uatomic_inc(&ht->in_progress_resize);
1717 cmm_smp_mb(); /* increment resize count before load destroy */
1718 if (CMM_LOAD_SHARED(ht->in_progress_destroy)) {
1719 uatomic_dec(&ht->in_progress_resize);
1720 return;
1721 }
1722 work = malloc(sizeof(*work));
1723 work->ht = ht;
1724 ht->cds_lfht_call_rcu(&work->head, do_resize_cb);
1725 CMM_STORE_SHARED(ht->t.resize_initiated, 1);
1726 }
1727 }
1728
1729 #if defined(HAVE_SCHED_GETCPU) && defined(HAVE_SYSCONF)
1730
1731 static
1732 void cds_lfht_resize_lazy_count(struct cds_lfht *ht, unsigned long size,
1733 unsigned long count)
1734 {
1735 struct rcu_resize_work *work;
1736
1737 if (!(ht->flags & CDS_LFHT_AUTO_RESIZE))
1738 return;
1739 resize_target_update_count(ht, count);
1740 /* Store resize_target before read resize_initiated */
1741 cmm_smp_mb();
1742 if (!CMM_LOAD_SHARED(ht->t.resize_initiated)) {
1743 uatomic_inc(&ht->in_progress_resize);
1744 cmm_smp_mb(); /* increment resize count before load destroy */
1745 if (CMM_LOAD_SHARED(ht->in_progress_destroy)) {
1746 uatomic_dec(&ht->in_progress_resize);
1747 return;
1748 }
1749 work = malloc(sizeof(*work));
1750 work->ht = ht;
1751 ht->cds_lfht_call_rcu(&work->head, do_resize_cb);
1752 CMM_STORE_SHARED(ht->t.resize_initiated, 1);
1753 }
1754 }
1755
1756 #endif
This page took 0.065364 seconds and 5 git commands to generate.