rculfhash: rename likely/unlikely (add caa_ prefix)
[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 cds_lfht_hash_fct hash_fct;
271 cds_lfht_compare_fct compare_fct;
272 unsigned long min_alloc_order;
273 unsigned long min_alloc_size;
274 unsigned long hash_seed;
275 int flags;
276 /*
277 * We need to put the work threads offline (QSBR) when taking this
278 * mutex, because we use synchronize_rcu within this mutex critical
279 * section, which waits on read-side critical sections, and could
280 * therefore cause grace-period deadlock if we hold off RCU G.P.
281 * completion.
282 */
283 pthread_mutex_t resize_mutex; /* resize mutex: add/del mutex */
284 unsigned int in_progress_resize, in_progress_destroy;
285 void (*cds_lfht_call_rcu)(struct rcu_head *head,
286 void (*func)(struct rcu_head *head));
287 void (*cds_lfht_synchronize_rcu)(void);
288 void (*cds_lfht_rcu_read_lock)(void);
289 void (*cds_lfht_rcu_read_unlock)(void);
290 void (*cds_lfht_rcu_thread_offline)(void);
291 void (*cds_lfht_rcu_thread_online)(void);
292 void (*cds_lfht_rcu_register_thread)(void);
293 void (*cds_lfht_rcu_unregister_thread)(void);
294 pthread_attr_t *resize_attr; /* Resize threads attributes */
295 long count; /* global approximate item count */
296 struct ht_items_count *split_count; /* split item count */
297 };
298
299 /*
300 * rcu_resize_work: Contains arguments passed to RCU worker thread
301 * responsible for performing lazy resize.
302 */
303 struct rcu_resize_work {
304 struct rcu_head head;
305 struct cds_lfht *ht;
306 };
307
308 /*
309 * partition_resize_work: Contains arguments passed to worker threads
310 * executing the hash table resize on partitions of the hash table
311 * assigned to each processor's worker thread.
312 */
313 struct partition_resize_work {
314 pthread_t thread_id;
315 struct cds_lfht *ht;
316 unsigned long i, start, len;
317 void (*fct)(struct cds_lfht *ht, unsigned long i,
318 unsigned long start, unsigned long len);
319 };
320
321 static
322 void _cds_lfht_add(struct cds_lfht *ht,
323 unsigned long size,
324 struct cds_lfht_node *node,
325 struct cds_lfht_iter *unique_ret,
326 int dummy);
327
328 /*
329 * Algorithm to reverse bits in a word by lookup table, extended to
330 * 64-bit words.
331 * Source:
332 * http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
333 * Originally from Public Domain.
334 */
335
336 static const uint8_t BitReverseTable256[256] =
337 {
338 #define R2(n) (n), (n) + 2*64, (n) + 1*64, (n) + 3*64
339 #define R4(n) R2(n), R2((n) + 2*16), R2((n) + 1*16), R2((n) + 3*16)
340 #define R6(n) R4(n), R4((n) + 2*4 ), R4((n) + 1*4 ), R4((n) + 3*4 )
341 R6(0), R6(2), R6(1), R6(3)
342 };
343 #undef R2
344 #undef R4
345 #undef R6
346
347 static
348 uint8_t bit_reverse_u8(uint8_t v)
349 {
350 return BitReverseTable256[v];
351 }
352
353 static __attribute__((unused))
354 uint32_t bit_reverse_u32(uint32_t v)
355 {
356 return ((uint32_t) bit_reverse_u8(v) << 24) |
357 ((uint32_t) bit_reverse_u8(v >> 8) << 16) |
358 ((uint32_t) bit_reverse_u8(v >> 16) << 8) |
359 ((uint32_t) bit_reverse_u8(v >> 24));
360 }
361
362 static __attribute__((unused))
363 uint64_t bit_reverse_u64(uint64_t v)
364 {
365 return ((uint64_t) bit_reverse_u8(v) << 56) |
366 ((uint64_t) bit_reverse_u8(v >> 8) << 48) |
367 ((uint64_t) bit_reverse_u8(v >> 16) << 40) |
368 ((uint64_t) bit_reverse_u8(v >> 24) << 32) |
369 ((uint64_t) bit_reverse_u8(v >> 32) << 24) |
370 ((uint64_t) bit_reverse_u8(v >> 40) << 16) |
371 ((uint64_t) bit_reverse_u8(v >> 48) << 8) |
372 ((uint64_t) bit_reverse_u8(v >> 56));
373 }
374
375 static
376 unsigned long bit_reverse_ulong(unsigned long v)
377 {
378 #if (CAA_BITS_PER_LONG == 32)
379 return bit_reverse_u32(v);
380 #else
381 return bit_reverse_u64(v);
382 #endif
383 }
384
385 /*
386 * fls: returns the position of the most significant bit.
387 * Returns 0 if no bit is set, else returns the position of the most
388 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
389 */
390 #if defined(__i386) || defined(__x86_64)
391 static inline
392 unsigned int fls_u32(uint32_t x)
393 {
394 int r;
395
396 asm("bsrl %1,%0\n\t"
397 "jnz 1f\n\t"
398 "movl $-1,%0\n\t"
399 "1:\n\t"
400 : "=r" (r) : "rm" (x));
401 return r + 1;
402 }
403 #define HAS_FLS_U32
404 #endif
405
406 #if defined(__x86_64)
407 static inline
408 unsigned int fls_u64(uint64_t x)
409 {
410 long r;
411
412 asm("bsrq %1,%0\n\t"
413 "jnz 1f\n\t"
414 "movq $-1,%0\n\t"
415 "1:\n\t"
416 : "=r" (r) : "rm" (x));
417 return r + 1;
418 }
419 #define HAS_FLS_U64
420 #endif
421
422 #ifndef HAS_FLS_U64
423 static __attribute__((unused))
424 unsigned int fls_u64(uint64_t x)
425 {
426 unsigned int r = 64;
427
428 if (!x)
429 return 0;
430
431 if (!(x & 0xFFFFFFFF00000000ULL)) {
432 x <<= 32;
433 r -= 32;
434 }
435 if (!(x & 0xFFFF000000000000ULL)) {
436 x <<= 16;
437 r -= 16;
438 }
439 if (!(x & 0xFF00000000000000ULL)) {
440 x <<= 8;
441 r -= 8;
442 }
443 if (!(x & 0xF000000000000000ULL)) {
444 x <<= 4;
445 r -= 4;
446 }
447 if (!(x & 0xC000000000000000ULL)) {
448 x <<= 2;
449 r -= 2;
450 }
451 if (!(x & 0x8000000000000000ULL)) {
452 x <<= 1;
453 r -= 1;
454 }
455 return r;
456 }
457 #endif
458
459 #ifndef HAS_FLS_U32
460 static __attribute__((unused))
461 unsigned int fls_u32(uint32_t x)
462 {
463 unsigned int r = 32;
464
465 if (!x)
466 return 0;
467 if (!(x & 0xFFFF0000U)) {
468 x <<= 16;
469 r -= 16;
470 }
471 if (!(x & 0xFF000000U)) {
472 x <<= 8;
473 r -= 8;
474 }
475 if (!(x & 0xF0000000U)) {
476 x <<= 4;
477 r -= 4;
478 }
479 if (!(x & 0xC0000000U)) {
480 x <<= 2;
481 r -= 2;
482 }
483 if (!(x & 0x80000000U)) {
484 x <<= 1;
485 r -= 1;
486 }
487 return r;
488 }
489 #endif
490
491 unsigned int fls_ulong(unsigned long x)
492 {
493 #if (CAA_BITS_PER_LONG == 32)
494 return fls_u32(x);
495 #else
496 return fls_u64(x);
497 #endif
498 }
499
500 /*
501 * Return the minimum order for which x <= (1UL << order).
502 * Return -1 if x is 0.
503 */
504 int get_count_order_u32(uint32_t x)
505 {
506 if (!x)
507 return -1;
508
509 return fls_u32(x - 1);
510 }
511
512 /*
513 * Return the minimum order for which x <= (1UL << order).
514 * Return -1 if x is 0.
515 */
516 int get_count_order_ulong(unsigned long x)
517 {
518 if (!x)
519 return -1;
520
521 return fls_ulong(x - 1);
522 }
523
524 #ifdef POISON_FREE
525 #define poison_free(ptr) \
526 do { \
527 if (ptr) { \
528 memset(ptr, 0x42, sizeof(*(ptr))); \
529 free(ptr); \
530 } \
531 } while (0)
532 #else
533 #define poison_free(ptr) free(ptr)
534 #endif
535
536 static
537 void cds_lfht_resize_lazy(struct cds_lfht *ht, unsigned long size, int growth);
538
539 static
540 void cds_lfht_resize_lazy_count(struct cds_lfht *ht, unsigned long size,
541 unsigned long count);
542
543 static long nr_cpus_mask = -1;
544 static long split_count_mask = -1;
545
546 #if defined(HAVE_SYSCONF)
547 static void ht_init_nr_cpus_mask(void)
548 {
549 long maxcpus;
550
551 maxcpus = sysconf(_SC_NPROCESSORS_CONF);
552 if (maxcpus <= 0) {
553 nr_cpus_mask = -2;
554 return;
555 }
556 /*
557 * round up number of CPUs to next power of two, so we
558 * can use & for modulo.
559 */
560 maxcpus = 1UL << get_count_order_ulong(maxcpus);
561 nr_cpus_mask = maxcpus - 1;
562 }
563 #else /* #if defined(HAVE_SYSCONF) */
564 static void ht_init_nr_cpus_mask(void)
565 {
566 nr_cpus_mask = -2;
567 }
568 #endif /* #else #if defined(HAVE_SYSCONF) */
569
570 static
571 void alloc_split_items_count(struct cds_lfht *ht)
572 {
573 struct ht_items_count *count;
574
575 if (nr_cpus_mask == -1) {
576 ht_init_nr_cpus_mask();
577 if (nr_cpus_mask < 0)
578 split_count_mask = DEFAULT_SPLIT_COUNT_MASK;
579 else
580 split_count_mask = nr_cpus_mask;
581 }
582
583 assert(split_count_mask >= 0);
584
585 if (ht->flags & CDS_LFHT_ACCOUNTING) {
586 ht->split_count = calloc(split_count_mask + 1, sizeof(*count));
587 assert(ht->split_count);
588 } else {
589 ht->split_count = NULL;
590 }
591 }
592
593 static
594 void free_split_items_count(struct cds_lfht *ht)
595 {
596 poison_free(ht->split_count);
597 }
598
599 #if defined(HAVE_SCHED_GETCPU)
600 static
601 int ht_get_split_count_index(unsigned long hash)
602 {
603 int cpu;
604
605 assert(split_count_mask >= 0);
606 cpu = sched_getcpu();
607 if (caa_unlikely(cpu < 0))
608 return hash & split_count_mask;
609 else
610 return cpu & split_count_mask;
611 }
612 #else /* #if defined(HAVE_SCHED_GETCPU) */
613 static
614 int ht_get_split_count_index(unsigned long hash)
615 {
616 return hash & split_count_mask;
617 }
618 #endif /* #else #if defined(HAVE_SCHED_GETCPU) */
619
620 static
621 void ht_count_add(struct cds_lfht *ht, unsigned long size, unsigned long hash)
622 {
623 unsigned long split_count;
624 int index;
625
626 if (caa_unlikely(!ht->split_count))
627 return;
628 index = ht_get_split_count_index(hash);
629 split_count = uatomic_add_return(&ht->split_count[index].add, 1);
630 if (caa_unlikely(!(split_count & ((1UL << COUNT_COMMIT_ORDER) - 1)))) {
631 long count;
632
633 dbg_printf("add split count %lu\n", split_count);
634 count = uatomic_add_return(&ht->count,
635 1UL << COUNT_COMMIT_ORDER);
636 /* If power of 2 */
637 if (!(count & (count - 1))) {
638 if ((count >> CHAIN_LEN_RESIZE_THRESHOLD) < size)
639 return;
640 dbg_printf("add set global %ld\n", count);
641 cds_lfht_resize_lazy_count(ht, size,
642 count >> (CHAIN_LEN_TARGET - 1));
643 }
644 }
645 }
646
647 static
648 void ht_count_del(struct cds_lfht *ht, unsigned long size, unsigned long hash)
649 {
650 unsigned long split_count;
651 int index;
652
653 if (caa_unlikely(!ht->split_count))
654 return;
655 index = ht_get_split_count_index(hash);
656 split_count = uatomic_add_return(&ht->split_count[index].del, 1);
657 if (caa_unlikely(!(split_count & ((1UL << COUNT_COMMIT_ORDER) - 1)))) {
658 long count;
659
660 dbg_printf("del split count %lu\n", split_count);
661 count = uatomic_add_return(&ht->count,
662 -(1UL << COUNT_COMMIT_ORDER));
663 /* If power of 2 */
664 if (!(count & (count - 1))) {
665 if ((count >> CHAIN_LEN_RESIZE_THRESHOLD) >= size)
666 return;
667 dbg_printf("del set global %ld\n", count);
668 /*
669 * Don't shrink table if the number of nodes is below a
670 * certain threshold.
671 */
672 if (count < (1UL << COUNT_COMMIT_ORDER) * (split_count_mask + 1))
673 return;
674 cds_lfht_resize_lazy_count(ht, size,
675 count >> (CHAIN_LEN_TARGET - 1));
676 }
677 }
678 }
679
680 static
681 void check_resize(struct cds_lfht *ht, unsigned long size, uint32_t chain_len)
682 {
683 unsigned long count;
684
685 if (!(ht->flags & CDS_LFHT_AUTO_RESIZE))
686 return;
687 count = uatomic_read(&ht->count);
688 /*
689 * Use bucket-local length for small table expand and for
690 * environments lacking per-cpu data support.
691 */
692 if (count >= (1UL << COUNT_COMMIT_ORDER))
693 return;
694 if (chain_len > 100)
695 dbg_printf("WARNING: large chain length: %u.\n",
696 chain_len);
697 if (chain_len >= CHAIN_LEN_RESIZE_THRESHOLD)
698 cds_lfht_resize_lazy(ht, size,
699 get_count_order_u32(chain_len - (CHAIN_LEN_TARGET - 1)));
700 }
701
702 static
703 struct cds_lfht_node *clear_flag(struct cds_lfht_node *node)
704 {
705 return (struct cds_lfht_node *) (((unsigned long) node) & ~FLAGS_MASK);
706 }
707
708 static
709 int is_removed(struct cds_lfht_node *node)
710 {
711 return ((unsigned long) node) & REMOVED_FLAG;
712 }
713
714 static
715 struct cds_lfht_node *flag_removed(struct cds_lfht_node *node)
716 {
717 return (struct cds_lfht_node *) (((unsigned long) node) | REMOVED_FLAG);
718 }
719
720 static
721 int is_dummy(struct cds_lfht_node *node)
722 {
723 return ((unsigned long) node) & DUMMY_FLAG;
724 }
725
726 static
727 struct cds_lfht_node *flag_dummy(struct cds_lfht_node *node)
728 {
729 return (struct cds_lfht_node *) (((unsigned long) node) | DUMMY_FLAG);
730 }
731
732 static
733 struct cds_lfht_node *get_end(void)
734 {
735 return (struct cds_lfht_node *) END_VALUE;
736 }
737
738 static
739 int is_end(struct cds_lfht_node *node)
740 {
741 return clear_flag(node) == (struct cds_lfht_node *) END_VALUE;
742 }
743
744 static
745 unsigned long _uatomic_max(unsigned long *ptr, 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 v;
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 unsigned long size,
895 struct cds_lfht_node *node,
896 struct cds_lfht_iter *unique_ret,
897 int dummy)
898 {
899 struct cds_lfht_node *iter_prev, *iter, *next, *new_node, *new_next,
900 *return_node;
901 struct _cds_lfht_node *lookup;
902
903 assert(!is_dummy(node));
904 assert(!is_removed(node));
905 lookup = lookup_bucket(ht, size, bit_reverse_ulong(node->p.reverse_hash));
906 for (;;) {
907 uint32_t chain_len = 0;
908
909 /*
910 * iter_prev points to the non-removed node prior to the
911 * insert location.
912 */
913 iter_prev = (struct cds_lfht_node *) lookup;
914 /* We can always skip the dummy node initially */
915 iter = rcu_dereference(iter_prev->p.next);
916 assert(iter_prev->p.reverse_hash <= node->p.reverse_hash);
917 for (;;) {
918 if (caa_unlikely(is_end(iter)))
919 goto insert;
920 if (caa_likely(clear_flag(iter)->p.reverse_hash > node->p.reverse_hash))
921 goto insert;
922
923 /* dummy node is the first node of the identical-hash-value chain */
924 if (dummy && clear_flag(iter)->p.reverse_hash == node->p.reverse_hash)
925 goto insert;
926
927 next = rcu_dereference(clear_flag(iter)->p.next);
928 if (caa_unlikely(is_removed(next)))
929 goto gc_node;
930
931 /* uniquely add */
932 if (unique_ret
933 && !is_dummy(next)
934 && clear_flag(iter)->p.reverse_hash == node->p.reverse_hash) {
935 struct cds_lfht_iter d_iter = { .node = node, .next = iter, };
936
937 /*
938 * uniquely adding inserts the node as the first
939 * node of the identical-hash-value node chain.
940 *
941 * This semantic ensures no duplicated keys
942 * should ever be observable in the table
943 * (including observe one node by one node
944 * by forward iterations)
945 */
946 cds_lfht_next_duplicate(ht, &d_iter);
947 if (!d_iter.node)
948 goto insert;
949
950 *unique_ret = d_iter;
951 return;
952 }
953
954 /* Only account for identical reverse hash once */
955 if (iter_prev->p.reverse_hash != clear_flag(iter)->p.reverse_hash
956 && !is_dummy(next))
957 check_resize(ht, size, ++chain_len);
958 iter_prev = clear_flag(iter);
959 iter = next;
960 }
961
962 insert:
963 assert(node != clear_flag(iter));
964 assert(!is_removed(iter_prev));
965 assert(!is_removed(iter));
966 assert(iter_prev != node);
967 if (!dummy)
968 node->p.next = clear_flag(iter);
969 else
970 node->p.next = flag_dummy(clear_flag(iter));
971 if (is_dummy(iter))
972 new_node = flag_dummy(node);
973 else
974 new_node = node;
975 if (uatomic_cmpxchg(&iter_prev->p.next, iter,
976 new_node) != iter) {
977 continue; /* retry */
978 } else {
979 return_node = node;
980 goto end;
981 }
982
983 gc_node:
984 assert(!is_removed(iter));
985 if (is_dummy(iter))
986 new_next = flag_dummy(clear_flag(next));
987 else
988 new_next = clear_flag(next);
989 (void) uatomic_cmpxchg(&iter_prev->p.next, iter, new_next);
990 /* retry */
991 }
992 end:
993 if (unique_ret) {
994 unique_ret->node = return_node;
995 /* unique_ret->next left unset, never used. */
996 }
997 }
998
999 static
1000 int _cds_lfht_del(struct cds_lfht *ht, unsigned long size,
1001 struct cds_lfht_node *node,
1002 int dummy_removal)
1003 {
1004 struct cds_lfht_node *dummy, *next, *old;
1005 struct _cds_lfht_node *lookup;
1006
1007 if (!node) /* Return -ENOENT if asked to delete NULL node */
1008 return -ENOENT;
1009
1010 /* logically delete the node */
1011 assert(!is_dummy(node));
1012 assert(!is_removed(node));
1013 old = rcu_dereference(node->p.next);
1014 do {
1015 struct cds_lfht_node *new_next;
1016
1017 next = old;
1018 if (caa_unlikely(is_removed(next)))
1019 return -ENOENT;
1020 if (dummy_removal)
1021 assert(is_dummy(next));
1022 else
1023 assert(!is_dummy(next));
1024 new_next = flag_removed(next);
1025 old = uatomic_cmpxchg(&node->p.next, next, new_next);
1026 } while (old != next);
1027 /* We performed the (logical) deletion. */
1028
1029 /*
1030 * Ensure that the node is not visible to readers anymore: lookup for
1031 * the node, and remove it (along with any other logically removed node)
1032 * if found.
1033 */
1034 lookup = lookup_bucket(ht, size, bit_reverse_ulong(node->p.reverse_hash));
1035 dummy = (struct cds_lfht_node *) lookup;
1036 _cds_lfht_gc_bucket(dummy, node);
1037
1038 assert(is_removed(rcu_dereference(node->p.next)));
1039 return 0;
1040 }
1041
1042 static
1043 void *partition_resize_thread(void *arg)
1044 {
1045 struct partition_resize_work *work = arg;
1046
1047 work->ht->cds_lfht_rcu_register_thread();
1048 work->fct(work->ht, work->i, work->start, work->len);
1049 work->ht->cds_lfht_rcu_unregister_thread();
1050 return NULL;
1051 }
1052
1053 static
1054 void partition_resize_helper(struct cds_lfht *ht, unsigned long i,
1055 unsigned long len,
1056 void (*fct)(struct cds_lfht *ht, unsigned long i,
1057 unsigned long start, unsigned long len))
1058 {
1059 unsigned long partition_len;
1060 struct partition_resize_work *work;
1061 int thread, ret;
1062 unsigned long nr_threads;
1063
1064 /*
1065 * Note: nr_cpus_mask + 1 is always power of 2.
1066 * We spawn just the number of threads we need to satisfy the minimum
1067 * partition size, up to the number of CPUs in the system.
1068 */
1069 if (nr_cpus_mask > 0) {
1070 nr_threads = min(nr_cpus_mask + 1,
1071 len >> MIN_PARTITION_PER_THREAD_ORDER);
1072 } else {
1073 nr_threads = 1;
1074 }
1075 partition_len = len >> get_count_order_ulong(nr_threads);
1076 work = calloc(nr_threads, sizeof(*work));
1077 assert(work);
1078 for (thread = 0; thread < nr_threads; thread++) {
1079 work[thread].ht = ht;
1080 work[thread].i = i;
1081 work[thread].len = partition_len;
1082 work[thread].start = thread * partition_len;
1083 work[thread].fct = fct;
1084 ret = pthread_create(&(work[thread].thread_id), ht->resize_attr,
1085 partition_resize_thread, &work[thread]);
1086 assert(!ret);
1087 }
1088 for (thread = 0; thread < nr_threads; thread++) {
1089 ret = pthread_join(work[thread].thread_id, NULL);
1090 assert(!ret);
1091 }
1092 free(work);
1093 }
1094
1095 /*
1096 * Holding RCU read lock to protect _cds_lfht_add against memory
1097 * reclaim that could be performed by other call_rcu worker threads (ABA
1098 * problem).
1099 *
1100 * When we reach a certain length, we can split this population phase over
1101 * many worker threads, based on the number of CPUs available in the system.
1102 * This should therefore take care of not having the expand lagging behind too
1103 * many concurrent insertion threads by using the scheduler's ability to
1104 * schedule dummy node population fairly with insertions.
1105 */
1106 static
1107 void init_table_populate_partition(struct cds_lfht *ht, unsigned long i,
1108 unsigned long start, unsigned long len)
1109 {
1110 unsigned long j;
1111
1112 assert(i > ht->min_alloc_order);
1113 ht->cds_lfht_rcu_read_lock();
1114 for (j = start; j < start + len; j++) {
1115 struct cds_lfht_node *new_node =
1116 (struct cds_lfht_node *) &ht->t.tbl[i]->nodes[j];
1117
1118 dbg_printf("init populate: i %lu j %lu hash %lu\n",
1119 i, j, (1UL << (i - 1)) + j);
1120 new_node->p.reverse_hash =
1121 bit_reverse_ulong((1UL << (i - 1)) + j);
1122 _cds_lfht_add(ht, 1UL << (i - 1),
1123 new_node, NULL, 1);
1124 }
1125 ht->cds_lfht_rcu_read_unlock();
1126 }
1127
1128 static
1129 void init_table_populate(struct cds_lfht *ht, unsigned long i,
1130 unsigned long len)
1131 {
1132 assert(nr_cpus_mask != -1);
1133 if (nr_cpus_mask < 0 || len < 2 * MIN_PARTITION_PER_THREAD) {
1134 ht->cds_lfht_rcu_thread_online();
1135 init_table_populate_partition(ht, i, 0, len);
1136 ht->cds_lfht_rcu_thread_offline();
1137 return;
1138 }
1139 partition_resize_helper(ht, i, len, init_table_populate_partition);
1140 }
1141
1142 static
1143 void init_table(struct cds_lfht *ht,
1144 unsigned long first_order, unsigned long last_order)
1145 {
1146 unsigned long i;
1147
1148 dbg_printf("init table: first_order %lu last_order %lu\n",
1149 first_order, last_order);
1150 assert(first_order > ht->min_alloc_order);
1151 for (i = first_order; i <= last_order; i++) {
1152 unsigned long len;
1153
1154 len = 1UL << (i - 1);
1155 dbg_printf("init order %lu len: %lu\n", i, len);
1156
1157 /* Stop expand if the resize target changes under us */
1158 if (CMM_LOAD_SHARED(ht->t.resize_target) < (1UL << i))
1159 break;
1160
1161 ht->t.tbl[i] = calloc(1, len * sizeof(struct _cds_lfht_node));
1162 assert(ht->t.tbl[i]);
1163
1164 /*
1165 * Set all dummy nodes reverse hash values for a level and
1166 * link all dummy nodes into the table.
1167 */
1168 init_table_populate(ht, i, len);
1169
1170 /*
1171 * Update table size.
1172 */
1173 cmm_smp_wmb(); /* populate data before RCU size */
1174 CMM_STORE_SHARED(ht->t.size, 1UL << i);
1175
1176 dbg_printf("init new size: %lu\n", 1UL << i);
1177 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
1178 break;
1179 }
1180 }
1181
1182 /*
1183 * Holding RCU read lock to protect _cds_lfht_remove against memory
1184 * reclaim that could be performed by other call_rcu worker threads (ABA
1185 * problem).
1186 * For a single level, we logically remove and garbage collect each node.
1187 *
1188 * As a design choice, we perform logical removal and garbage collection on a
1189 * node-per-node basis to simplify this algorithm. We also assume keeping good
1190 * cache locality of the operation would overweight possible performance gain
1191 * that could be achieved by batching garbage collection for multiple levels.
1192 * However, this would have to be justified by benchmarks.
1193 *
1194 * Concurrent removal and add operations are helping us perform garbage
1195 * collection of logically removed nodes. We guarantee that all logically
1196 * removed nodes have been garbage-collected (unlinked) before call_rcu is
1197 * invoked to free a hole level of dummy nodes (after a grace period).
1198 *
1199 * Logical removal and garbage collection can therefore be done in batch or on a
1200 * node-per-node basis, as long as the guarantee above holds.
1201 *
1202 * When we reach a certain length, we can split this removal over many worker
1203 * threads, based on the number of CPUs available in the system. This should
1204 * take care of not letting resize process lag behind too many concurrent
1205 * updater threads actively inserting into the hash table.
1206 */
1207 static
1208 void remove_table_partition(struct cds_lfht *ht, unsigned long i,
1209 unsigned long start, unsigned long len)
1210 {
1211 unsigned long j;
1212
1213 assert(i > ht->min_alloc_order);
1214 ht->cds_lfht_rcu_read_lock();
1215 for (j = start; j < start + len; j++) {
1216 struct cds_lfht_node *fini_node =
1217 (struct cds_lfht_node *) &ht->t.tbl[i]->nodes[j];
1218
1219 dbg_printf("remove entry: i %lu j %lu hash %lu\n",
1220 i, j, (1UL << (i - 1)) + j);
1221 fini_node->p.reverse_hash =
1222 bit_reverse_ulong((1UL << (i - 1)) + j);
1223 (void) _cds_lfht_del(ht, 1UL << (i - 1), fini_node, 1);
1224 }
1225 ht->cds_lfht_rcu_read_unlock();
1226 }
1227
1228 static
1229 void remove_table(struct cds_lfht *ht, unsigned long i, unsigned long len)
1230 {
1231
1232 assert(nr_cpus_mask != -1);
1233 if (nr_cpus_mask < 0 || len < 2 * MIN_PARTITION_PER_THREAD) {
1234 ht->cds_lfht_rcu_thread_online();
1235 remove_table_partition(ht, i, 0, len);
1236 ht->cds_lfht_rcu_thread_offline();
1237 return;
1238 }
1239 partition_resize_helper(ht, i, len, remove_table_partition);
1240 }
1241
1242 static
1243 void fini_table(struct cds_lfht *ht,
1244 unsigned long first_order, unsigned long last_order)
1245 {
1246 long i;
1247 void *free_by_rcu = NULL;
1248
1249 dbg_printf("fini table: first_order %lu last_order %lu\n",
1250 first_order, last_order);
1251 assert(first_order > ht->min_alloc_order);
1252 for (i = last_order; i >= first_order; i--) {
1253 unsigned long len;
1254
1255 len = 1UL << (i - 1);
1256 dbg_printf("fini order %lu len: %lu\n", i, len);
1257
1258 /* Stop shrink if the resize target changes under us */
1259 if (CMM_LOAD_SHARED(ht->t.resize_target) > (1UL << (i - 1)))
1260 break;
1261
1262 cmm_smp_wmb(); /* populate data before RCU size */
1263 CMM_STORE_SHARED(ht->t.size, 1UL << (i - 1));
1264
1265 /*
1266 * We need to wait for all add operations to reach Q.S. (and
1267 * thus use the new table for lookups) before we can start
1268 * releasing the old dummy nodes. Otherwise their lookup will
1269 * return a logically removed node as insert position.
1270 */
1271 ht->cds_lfht_synchronize_rcu();
1272 if (free_by_rcu)
1273 free(free_by_rcu);
1274
1275 /*
1276 * Set "removed" flag in dummy nodes about to be removed.
1277 * Unlink all now-logically-removed dummy node pointers.
1278 * Concurrent add/remove operation are helping us doing
1279 * the gc.
1280 */
1281 remove_table(ht, i, len);
1282
1283 free_by_rcu = ht->t.tbl[i];
1284
1285 dbg_printf("fini new size: %lu\n", 1UL << i);
1286 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
1287 break;
1288 }
1289
1290 if (free_by_rcu) {
1291 ht->cds_lfht_synchronize_rcu();
1292 free(free_by_rcu);
1293 }
1294 }
1295
1296 static
1297 void cds_lfht_create_dummy(struct cds_lfht *ht, unsigned long size)
1298 {
1299 struct _cds_lfht_node *prev, *node;
1300 unsigned long order, len, i, j;
1301
1302 ht->t.tbl[0] = calloc(1, ht->min_alloc_size * sizeof(struct _cds_lfht_node));
1303 assert(ht->t.tbl[0]);
1304
1305 dbg_printf("create dummy: order %lu index %lu hash %lu\n", 0, 0, 0);
1306 ht->t.tbl[0]->nodes[0].next = flag_dummy(get_end());
1307 ht->t.tbl[0]->nodes[0].reverse_hash = 0;
1308
1309 for (order = 1; order < get_count_order_ulong(size) + 1; order++) {
1310 len = 1UL << (order - 1);
1311 if (order <= ht->min_alloc_order) {
1312 ht->t.tbl[order] = (struct rcu_level *) (ht->t.tbl[0]->nodes + len);
1313 } else {
1314 ht->t.tbl[order] = calloc(1, len * sizeof(struct _cds_lfht_node));
1315 assert(ht->t.tbl[order]);
1316 }
1317
1318 i = 0;
1319 prev = ht->t.tbl[i]->nodes;
1320 for (j = 0; j < len; j++) {
1321 if (j & (j - 1)) { /* Between power of 2 */
1322 prev++;
1323 } else if (j) { /* At each power of 2 */
1324 i++;
1325 prev = ht->t.tbl[i]->nodes;
1326 }
1327
1328 node = &ht->t.tbl[order]->nodes[j];
1329 dbg_printf("create dummy: order %lu index %lu hash %lu\n",
1330 order, j, j + len);
1331 node->next = prev->next;
1332 assert(is_dummy(node->next));
1333 node->reverse_hash = bit_reverse_ulong(j + len);
1334 prev->next = flag_dummy((struct cds_lfht_node *)node);
1335 }
1336 }
1337 }
1338
1339 struct cds_lfht *_cds_lfht_new(cds_lfht_hash_fct hash_fct,
1340 cds_lfht_compare_fct compare_fct,
1341 unsigned long hash_seed,
1342 unsigned long init_size,
1343 unsigned long min_alloc_size,
1344 int flags,
1345 void (*cds_lfht_call_rcu)(struct rcu_head *head,
1346 void (*func)(struct rcu_head *head)),
1347 void (*cds_lfht_synchronize_rcu)(void),
1348 void (*cds_lfht_rcu_read_lock)(void),
1349 void (*cds_lfht_rcu_read_unlock)(void),
1350 void (*cds_lfht_rcu_thread_offline)(void),
1351 void (*cds_lfht_rcu_thread_online)(void),
1352 void (*cds_lfht_rcu_register_thread)(void),
1353 void (*cds_lfht_rcu_unregister_thread)(void),
1354 pthread_attr_t *attr)
1355 {
1356 struct cds_lfht *ht;
1357 unsigned long order;
1358
1359 /* min_alloc_size must be power of two */
1360 if (!min_alloc_size || (min_alloc_size & (min_alloc_size - 1)))
1361 return NULL;
1362 /* init_size must be power of two */
1363 if (!init_size || (init_size & (init_size - 1)))
1364 return NULL;
1365 min_alloc_size = max(min_alloc_size, MIN_TABLE_SIZE);
1366 init_size = max(init_size, min_alloc_size);
1367 ht = calloc(1, sizeof(struct cds_lfht));
1368 assert(ht);
1369 ht->flags = flags;
1370 ht->hash_fct = hash_fct;
1371 ht->compare_fct = compare_fct;
1372 ht->hash_seed = hash_seed;
1373 ht->cds_lfht_call_rcu = cds_lfht_call_rcu;
1374 ht->cds_lfht_synchronize_rcu = cds_lfht_synchronize_rcu;
1375 ht->cds_lfht_rcu_read_lock = cds_lfht_rcu_read_lock;
1376 ht->cds_lfht_rcu_read_unlock = cds_lfht_rcu_read_unlock;
1377 ht->cds_lfht_rcu_thread_offline = cds_lfht_rcu_thread_offline;
1378 ht->cds_lfht_rcu_thread_online = cds_lfht_rcu_thread_online;
1379 ht->cds_lfht_rcu_register_thread = cds_lfht_rcu_register_thread;
1380 ht->cds_lfht_rcu_unregister_thread = cds_lfht_rcu_unregister_thread;
1381 ht->resize_attr = attr;
1382 alloc_split_items_count(ht);
1383 /* this mutex should not nest in read-side C.S. */
1384 pthread_mutex_init(&ht->resize_mutex, NULL);
1385 order = get_count_order_ulong(init_size);
1386 ht->t.resize_target = 1UL << order;
1387 ht->min_alloc_size = min_alloc_size;
1388 ht->min_alloc_order = get_count_order_ulong(min_alloc_size);
1389 cds_lfht_create_dummy(ht, 1UL << order);
1390 ht->t.size = 1UL << order;
1391 return ht;
1392 }
1393
1394 void cds_lfht_lookup(struct cds_lfht *ht, void *key, size_t key_len,
1395 struct cds_lfht_iter *iter)
1396 {
1397 struct cds_lfht_node *node, *next, *dummy_node;
1398 struct _cds_lfht_node *lookup;
1399 unsigned long hash, reverse_hash, size;
1400
1401 hash = ht->hash_fct(key, key_len, ht->hash_seed);
1402 reverse_hash = bit_reverse_ulong(hash);
1403
1404 size = rcu_dereference(ht->t.size);
1405 lookup = lookup_bucket(ht, size, hash);
1406 dummy_node = (struct cds_lfht_node *) lookup;
1407 /* We can always skip the dummy node initially */
1408 node = rcu_dereference(dummy_node->p.next);
1409 node = clear_flag(node);
1410 for (;;) {
1411 if (caa_unlikely(is_end(node))) {
1412 node = next = NULL;
1413 break;
1414 }
1415 if (caa_unlikely(node->p.reverse_hash > reverse_hash)) {
1416 node = next = NULL;
1417 break;
1418 }
1419 next = rcu_dereference(node->p.next);
1420 assert(node == clear_flag(node));
1421 if (caa_likely(!is_removed(next))
1422 && !is_dummy(next)
1423 && node->p.reverse_hash == reverse_hash
1424 && caa_likely(!ht->compare_fct(node->key, node->key_len, key, key_len))) {
1425 break;
1426 }
1427 node = clear_flag(next);
1428 }
1429 assert(!node || !is_dummy(rcu_dereference(node->p.next)));
1430 iter->node = node;
1431 iter->next = next;
1432 }
1433
1434 void cds_lfht_next_duplicate(struct cds_lfht *ht, struct cds_lfht_iter *iter)
1435 {
1436 struct cds_lfht_node *node, *next;
1437 unsigned long reverse_hash;
1438 void *key;
1439 size_t key_len;
1440
1441 node = iter->node;
1442 reverse_hash = node->p.reverse_hash;
1443 key = node->key;
1444 key_len = node->key_len;
1445 next = iter->next;
1446 node = clear_flag(next);
1447
1448 for (;;) {
1449 if (caa_unlikely(is_end(node))) {
1450 node = next = NULL;
1451 break;
1452 }
1453 if (caa_unlikely(node->p.reverse_hash > reverse_hash)) {
1454 node = next = NULL;
1455 break;
1456 }
1457 next = rcu_dereference(node->p.next);
1458 if (caa_likely(!is_removed(next))
1459 && !is_dummy(next)
1460 && caa_likely(!ht->compare_fct(node->key, node->key_len, key, key_len))) {
1461 break;
1462 }
1463 node = clear_flag(next);
1464 }
1465 assert(!node || !is_dummy(rcu_dereference(node->p.next)));
1466 iter->node = node;
1467 iter->next = next;
1468 }
1469
1470 void cds_lfht_next(struct cds_lfht *ht, struct cds_lfht_iter *iter)
1471 {
1472 struct cds_lfht_node *node, *next;
1473
1474 node = clear_flag(iter->next);
1475 for (;;) {
1476 if (caa_unlikely(is_end(node))) {
1477 node = next = NULL;
1478 break;
1479 }
1480 next = rcu_dereference(node->p.next);
1481 if (caa_likely(!is_removed(next))
1482 && !is_dummy(next)) {
1483 break;
1484 }
1485 node = clear_flag(next);
1486 }
1487 assert(!node || !is_dummy(rcu_dereference(node->p.next)));
1488 iter->node = node;
1489 iter->next = next;
1490 }
1491
1492 void cds_lfht_first(struct cds_lfht *ht, struct cds_lfht_iter *iter)
1493 {
1494 struct _cds_lfht_node *lookup;
1495
1496 /*
1497 * Get next after first dummy node. The first dummy node is the
1498 * first node of the linked list.
1499 */
1500 lookup = &ht->t.tbl[0]->nodes[0];
1501 iter->next = lookup->next;
1502 cds_lfht_next(ht, iter);
1503 }
1504
1505 void cds_lfht_add(struct cds_lfht *ht, struct cds_lfht_node *node)
1506 {
1507 unsigned long hash, size;
1508
1509 hash = ht->hash_fct(node->key, node->key_len, ht->hash_seed);
1510 node->p.reverse_hash = bit_reverse_ulong((unsigned long) hash);
1511
1512 size = rcu_dereference(ht->t.size);
1513 _cds_lfht_add(ht, size, node, NULL, 0);
1514 ht_count_add(ht, size, hash);
1515 }
1516
1517 struct cds_lfht_node *cds_lfht_add_unique(struct cds_lfht *ht,
1518 struct cds_lfht_node *node)
1519 {
1520 unsigned long hash, size;
1521 struct cds_lfht_iter iter;
1522
1523 hash = ht->hash_fct(node->key, node->key_len, ht->hash_seed);
1524 node->p.reverse_hash = bit_reverse_ulong((unsigned long) hash);
1525
1526 size = rcu_dereference(ht->t.size);
1527 _cds_lfht_add(ht, size, node, &iter, 0);
1528 if (iter.node == node)
1529 ht_count_add(ht, size, hash);
1530 return iter.node;
1531 }
1532
1533 struct cds_lfht_node *cds_lfht_add_replace(struct cds_lfht *ht,
1534 struct cds_lfht_node *node)
1535 {
1536 unsigned long hash, size;
1537 struct cds_lfht_iter iter;
1538
1539 hash = ht->hash_fct(node->key, node->key_len, ht->hash_seed);
1540 node->p.reverse_hash = bit_reverse_ulong((unsigned long) hash);
1541
1542 size = rcu_dereference(ht->t.size);
1543 for (;;) {
1544 _cds_lfht_add(ht, size, node, &iter, 0);
1545 if (iter.node == node) {
1546 ht_count_add(ht, size, hash);
1547 return NULL;
1548 }
1549
1550 if (!_cds_lfht_replace(ht, size, iter.node, iter.next, node))
1551 return iter.node;
1552 }
1553 }
1554
1555 int cds_lfht_replace(struct cds_lfht *ht, struct cds_lfht_iter *old_iter,
1556 struct cds_lfht_node *new_node)
1557 {
1558 unsigned long size;
1559
1560 size = rcu_dereference(ht->t.size);
1561 return _cds_lfht_replace(ht, size, old_iter->node, old_iter->next,
1562 new_node);
1563 }
1564
1565 int cds_lfht_del(struct cds_lfht *ht, struct cds_lfht_iter *iter)
1566 {
1567 unsigned long size, hash;
1568 int ret;
1569
1570 size = rcu_dereference(ht->t.size);
1571 ret = _cds_lfht_del(ht, size, iter->node, 0);
1572 if (!ret) {
1573 hash = bit_reverse_ulong(iter->node->p.reverse_hash);
1574 ht_count_del(ht, size, hash);
1575 }
1576 return ret;
1577 }
1578
1579 static
1580 int cds_lfht_delete_dummy(struct cds_lfht *ht)
1581 {
1582 struct cds_lfht_node *node;
1583 struct _cds_lfht_node *lookup;
1584 unsigned long order, i, size;
1585
1586 /* Check that the table is empty */
1587 lookup = &ht->t.tbl[0]->nodes[0];
1588 node = (struct cds_lfht_node *) lookup;
1589 do {
1590 node = clear_flag(node)->p.next;
1591 if (!is_dummy(node))
1592 return -EPERM;
1593 assert(!is_removed(node));
1594 } while (!is_end(node));
1595 /*
1596 * size accessed without rcu_dereference because hash table is
1597 * being destroyed.
1598 */
1599 size = ht->t.size;
1600 /* Internal sanity check: all nodes left should be dummy */
1601 for (order = 0; order < get_count_order_ulong(size) + 1; order++) {
1602 unsigned long len;
1603
1604 len = !order ? 1 : 1UL << (order - 1);
1605 for (i = 0; i < len; i++) {
1606 dbg_printf("delete order %lu i %lu hash %lu\n",
1607 order, i,
1608 bit_reverse_ulong(ht->t.tbl[order]->nodes[i].reverse_hash));
1609 assert(is_dummy(ht->t.tbl[order]->nodes[i].next));
1610 }
1611
1612 if (order == ht->min_alloc_order)
1613 poison_free(ht->t.tbl[0]);
1614 else if (order > ht->min_alloc_order)
1615 poison_free(ht->t.tbl[order]);
1616 /* Nothing to delete for order < ht->min_alloc_order */
1617 }
1618 return 0;
1619 }
1620
1621 /*
1622 * Should only be called when no more concurrent readers nor writers can
1623 * possibly access the table.
1624 */
1625 int cds_lfht_destroy(struct cds_lfht *ht, pthread_attr_t **attr)
1626 {
1627 int ret;
1628
1629 /* Wait for in-flight resize operations to complete */
1630 _CMM_STORE_SHARED(ht->in_progress_destroy, 1);
1631 cmm_smp_mb(); /* Store destroy before load resize */
1632 while (uatomic_read(&ht->in_progress_resize))
1633 poll(NULL, 0, 100); /* wait for 100ms */
1634 ret = cds_lfht_delete_dummy(ht);
1635 if (ret)
1636 return ret;
1637 free_split_items_count(ht);
1638 if (attr)
1639 *attr = ht->resize_attr;
1640 poison_free(ht);
1641 return ret;
1642 }
1643
1644 void cds_lfht_count_nodes(struct cds_lfht *ht,
1645 long *approx_before,
1646 unsigned long *count,
1647 unsigned long *removed,
1648 long *approx_after)
1649 {
1650 struct cds_lfht_node *node, *next;
1651 struct _cds_lfht_node *lookup;
1652 unsigned long nr_dummy = 0;
1653
1654 *approx_before = 0;
1655 if (ht->split_count) {
1656 int i;
1657
1658 for (i = 0; i < split_count_mask + 1; i++) {
1659 *approx_before += uatomic_read(&ht->split_count[i].add);
1660 *approx_before -= uatomic_read(&ht->split_count[i].del);
1661 }
1662 }
1663
1664 *count = 0;
1665 *removed = 0;
1666
1667 /* Count non-dummy nodes in the table */
1668 lookup = &ht->t.tbl[0]->nodes[0];
1669 node = (struct cds_lfht_node *) lookup;
1670 do {
1671 next = rcu_dereference(node->p.next);
1672 if (is_removed(next)) {
1673 if (!is_dummy(next))
1674 (*removed)++;
1675 else
1676 (nr_dummy)++;
1677 } else if (!is_dummy(next))
1678 (*count)++;
1679 else
1680 (nr_dummy)++;
1681 node = clear_flag(next);
1682 } while (!is_end(node));
1683 dbg_printf("number of dummy nodes: %lu\n", nr_dummy);
1684 *approx_after = 0;
1685 if (ht->split_count) {
1686 int i;
1687
1688 for (i = 0; i < split_count_mask + 1; i++) {
1689 *approx_after += uatomic_read(&ht->split_count[i].add);
1690 *approx_after -= uatomic_read(&ht->split_count[i].del);
1691 }
1692 }
1693 }
1694
1695 /* called with resize mutex held */
1696 static
1697 void _do_cds_lfht_grow(struct cds_lfht *ht,
1698 unsigned long old_size, unsigned long new_size)
1699 {
1700 unsigned long old_order, new_order;
1701
1702 old_order = get_count_order_ulong(old_size);
1703 new_order = get_count_order_ulong(new_size);
1704 dbg_printf("resize from %lu (order %lu) to %lu (order %lu) buckets\n",
1705 old_size, old_order, new_size, new_order);
1706 assert(new_size > old_size);
1707 init_table(ht, old_order + 1, new_order);
1708 }
1709
1710 /* called with resize mutex held */
1711 static
1712 void _do_cds_lfht_shrink(struct cds_lfht *ht,
1713 unsigned long old_size, unsigned long new_size)
1714 {
1715 unsigned long old_order, new_order;
1716
1717 new_size = max(new_size, ht->min_alloc_size);
1718 old_order = get_count_order_ulong(old_size);
1719 new_order = get_count_order_ulong(new_size);
1720 dbg_printf("resize from %lu (order %lu) to %lu (order %lu) buckets\n",
1721 old_size, old_order, new_size, new_order);
1722 assert(new_size < old_size);
1723
1724 /* Remove and unlink all dummy nodes to remove. */
1725 fini_table(ht, new_order + 1, old_order);
1726 }
1727
1728
1729 /* called with resize mutex held */
1730 static
1731 void _do_cds_lfht_resize(struct cds_lfht *ht)
1732 {
1733 unsigned long new_size, old_size;
1734
1735 /*
1736 * Resize table, re-do if the target size has changed under us.
1737 */
1738 do {
1739 assert(uatomic_read(&ht->in_progress_resize));
1740 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
1741 break;
1742 ht->t.resize_initiated = 1;
1743 old_size = ht->t.size;
1744 new_size = CMM_LOAD_SHARED(ht->t.resize_target);
1745 if (old_size < new_size)
1746 _do_cds_lfht_grow(ht, old_size, new_size);
1747 else if (old_size > new_size)
1748 _do_cds_lfht_shrink(ht, old_size, new_size);
1749 ht->t.resize_initiated = 0;
1750 /* write resize_initiated before read resize_target */
1751 cmm_smp_mb();
1752 } while (ht->t.size != CMM_LOAD_SHARED(ht->t.resize_target));
1753 }
1754
1755 static
1756 unsigned long resize_target_update(struct cds_lfht *ht, unsigned long size,
1757 int growth_order)
1758 {
1759 return _uatomic_max(&ht->t.resize_target,
1760 size << growth_order);
1761 }
1762
1763 static
1764 void resize_target_update_count(struct cds_lfht *ht,
1765 unsigned long count)
1766 {
1767 count = max(count, ht->min_alloc_size);
1768 uatomic_set(&ht->t.resize_target, count);
1769 }
1770
1771 void cds_lfht_resize(struct cds_lfht *ht, unsigned long new_size)
1772 {
1773 resize_target_update_count(ht, new_size);
1774 CMM_STORE_SHARED(ht->t.resize_initiated, 1);
1775 ht->cds_lfht_rcu_thread_offline();
1776 pthread_mutex_lock(&ht->resize_mutex);
1777 _do_cds_lfht_resize(ht);
1778 pthread_mutex_unlock(&ht->resize_mutex);
1779 ht->cds_lfht_rcu_thread_online();
1780 }
1781
1782 static
1783 void do_resize_cb(struct rcu_head *head)
1784 {
1785 struct rcu_resize_work *work =
1786 caa_container_of(head, struct rcu_resize_work, head);
1787 struct cds_lfht *ht = work->ht;
1788
1789 ht->cds_lfht_rcu_thread_offline();
1790 pthread_mutex_lock(&ht->resize_mutex);
1791 _do_cds_lfht_resize(ht);
1792 pthread_mutex_unlock(&ht->resize_mutex);
1793 ht->cds_lfht_rcu_thread_online();
1794 poison_free(work);
1795 cmm_smp_mb(); /* finish resize before decrement */
1796 uatomic_dec(&ht->in_progress_resize);
1797 }
1798
1799 static
1800 void cds_lfht_resize_lazy(struct cds_lfht *ht, unsigned long size, int growth)
1801 {
1802 struct rcu_resize_work *work;
1803 unsigned long target_size;
1804
1805 target_size = resize_target_update(ht, size, growth);
1806 /* Store resize_target before read resize_initiated */
1807 cmm_smp_mb();
1808 if (!CMM_LOAD_SHARED(ht->t.resize_initiated) && size < target_size) {
1809 uatomic_inc(&ht->in_progress_resize);
1810 cmm_smp_mb(); /* increment resize count before load destroy */
1811 if (CMM_LOAD_SHARED(ht->in_progress_destroy)) {
1812 uatomic_dec(&ht->in_progress_resize);
1813 return;
1814 }
1815 work = malloc(sizeof(*work));
1816 work->ht = ht;
1817 ht->cds_lfht_call_rcu(&work->head, do_resize_cb);
1818 CMM_STORE_SHARED(ht->t.resize_initiated, 1);
1819 }
1820 }
1821
1822 static
1823 void cds_lfht_resize_lazy_count(struct cds_lfht *ht, unsigned long size,
1824 unsigned long count)
1825 {
1826 struct rcu_resize_work *work;
1827
1828 if (!(ht->flags & CDS_LFHT_AUTO_RESIZE))
1829 return;
1830 resize_target_update_count(ht, count);
1831 /* Store resize_target before read resize_initiated */
1832 cmm_smp_mb();
1833 if (!CMM_LOAD_SHARED(ht->t.resize_initiated)) {
1834 uatomic_inc(&ht->in_progress_resize);
1835 cmm_smp_mb(); /* increment resize count before load destroy */
1836 if (CMM_LOAD_SHARED(ht->in_progress_destroy)) {
1837 uatomic_dec(&ht->in_progress_resize);
1838 return;
1839 }
1840 work = malloc(sizeof(*work));
1841 work->ht = ht;
1842 ht->cds_lfht_call_rcu(&work->head, do_resize_cb);
1843 CMM_STORE_SHARED(ht->t.resize_initiated, 1);
1844 }
1845 }
This page took 0.107632 seconds and 5 git commands to generate.