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