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