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