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