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