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