Fix: rculfhash worker needs to unblock to SIGRCU
[urcu.git] / src / rculfhash.c
CommitLineData
5e28c532 1/*
abc490a1
MD
2 * rculfhash.c
3 *
1475579c 4 * Userspace RCU library - Lock-Free Resizable RCU Hash Table
abc490a1
MD
5 *
6 * Copyright 2010-2011 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
0dcf4847 7 * Copyright 2011 - Lai Jiangshan <laijs@cn.fujitsu.com>
abc490a1
MD
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
5e28c532
MD
22 */
23
e753ff5a
MD
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 *
1475579c 33 * Some specificities of this Lock-Free Resizable RCU Hash Table
e753ff5a
MD
34 * implementation:
35 *
36 * - RCU read-side critical section allows readers to perform hash
1f67ba50
MD
37 * table lookups, as well as traversals, and use the returned objects
38 * safely by allowing memory reclaim to take place only after a grace
39 * period.
e753ff5a
MD
40 * - Add and remove operations are lock-free, and do not need to
41 * allocate memory. They need to be executed within RCU read-side
42 * critical section to ensure the objects they read are valid and to
43 * deal with the cmpxchg ABA problem.
44 * - add and add_unique operations are supported. add_unique checks if
1f67ba50
MD
45 * the node key already exists in the hash table. It ensures not to
46 * populate a duplicate key if the node key already exists in the hash
47 * table.
48 * - The resize operation executes concurrently with
49 * add/add_unique/add_replace/remove/lookup/traversal.
e753ff5a
MD
50 * - Hash table nodes are contained within a split-ordered list. This
51 * list is ordered by incrementing reversed-bits-hash value.
1ee8f000 52 * - An index of bucket nodes is kept. These bucket nodes are the hash
1f67ba50
MD
53 * table "buckets". These buckets are internal nodes that allow to
54 * perform a fast hash lookup, similarly to a skip list. These
55 * buckets are chained together in the split-ordered list, which
56 * allows recursive expansion by inserting new buckets between the
57 * existing buckets. The split-ordered list allows adding new buckets
58 * between existing buckets as the table needs to grow.
59 * - The resize operation for small tables only allows expanding the
60 * hash table. It is triggered automatically by detecting long chains
61 * in the add operation.
1475579c
MD
62 * - The resize operation for larger tables (and available through an
63 * API) allows both expanding and shrinking the hash table.
4c42f1b8 64 * - Split-counters are used to keep track of the number of
1475579c 65 * nodes within the hash table for automatic resize triggering.
e753ff5a 66 * - Resize operation initiated by long chain detection is executed by a
d0ec0ed2 67 * worker thread, which keeps lock-freedom of add and remove.
e753ff5a
MD
68 * - Resize operations are protected by a mutex.
69 * - The removal operation is split in two parts: first, a "removed"
70 * flag is set in the next pointer within the node to remove. Then,
71 * a "garbage collection" is performed in the bucket containing the
72 * removed node (from the start of the bucket up to the removed node).
73 * All encountered nodes with "removed" flag set in their next
74 * pointers are removed from the linked-list. If the cmpxchg used for
75 * removal fails (due to concurrent garbage-collection or concurrent
76 * add), we retry from the beginning of the bucket. This ensures that
77 * the node with "removed" flag set is removed from the hash table
78 * (not visible to lookups anymore) before the RCU read-side critical
79 * section held across removal ends. Furthermore, this ensures that
80 * the node with "removed" flag set is removed from the linked-list
5c4ca589
MD
81 * before its memory is reclaimed. After setting the "removal" flag,
82 * only the thread which removal is the first to set the "removal
83 * owner" flag (with an xchg) into a node's next pointer is considered
84 * to have succeeded its removal (and thus owns the node to reclaim).
85 * Because we garbage-collect starting from an invariant node (the
86 * start-of-bucket bucket node) up to the "removed" node (or find a
87 * reverse-hash that is higher), we are sure that a successful
88 * traversal of the chain leads to a chain that is present in the
1f67ba50 89 * linked-list (the start node is never removed) and that it does not
5c4ca589
MD
90 * contain the "removed" node anymore, even if concurrent delete/add
91 * operations are changing the structure of the list concurrently.
1f67ba50
MD
92 * - The add operations perform garbage collection of buckets if they
93 * encounter nodes with removed flag set in the bucket where they want
94 * to add their new node. This ensures lock-freedom of add operation by
29e669f6
MD
95 * helping the remover unlink nodes from the list rather than to wait
96 * for it do to so.
1f67ba50
MD
97 * - There are three memory backends for the hash table buckets: the
98 * "order table", the "chunks", and the "mmap".
99 * - These bucket containers contain a compact version of the hash table
100 * nodes.
101 * - The RCU "order table":
102 * - has a first level table indexed by log2(hash index) which is
103 * copied and expanded by the resize operation. This order table
104 * allows finding the "bucket node" tables.
105 * - There is one bucket node table per hash index order. The size of
106 * each bucket node table is half the number of hashes contained in
107 * this order (except for order 0).
108 * - The RCU "chunks" is best suited for close interaction with a page
109 * allocator. It uses a linear array as index to "chunks" containing
110 * each the same number of buckets.
111 * - The RCU "mmap" memory backend uses a single memory map to hold
112 * all buckets.
5f177b1c 113 * - synchronize_rcu is used to garbage-collect the old bucket node table.
93d46c39 114 *
7f949215 115 * Ordering Guarantees:
0f5543cb 116 *
7f949215
MD
117 * To discuss these guarantees, we first define "read" operation as any
118 * of the the basic cds_lfht_lookup, cds_lfht_next_duplicate,
119 * cds_lfht_first, cds_lfht_next operation, as well as
67ecffc0 120 * cds_lfht_add_unique (failure).
7f949215
MD
121 *
122 * We define "read traversal" operation as any of the following
123 * group of operations
0f5543cb 124 * - cds_lfht_lookup followed by iteration with cds_lfht_next_duplicate
7f949215
MD
125 * (and/or cds_lfht_next, although less common).
126 * - cds_lfht_add_unique (failure) followed by iteration with
127 * cds_lfht_next_duplicate (and/or cds_lfht_next, although less
128 * common).
129 * - cds_lfht_first followed iteration with cds_lfht_next (and/or
130 * cds_lfht_next_duplicate, although less common).
0f5543cb 131 *
bf09adc7 132 * We define "write" operations as any of cds_lfht_add, cds_lfht_replace,
7f949215
MD
133 * cds_lfht_add_unique (success), cds_lfht_add_replace, cds_lfht_del.
134 *
135 * When cds_lfht_add_unique succeeds (returns the node passed as
136 * parameter), it acts as a "write" operation. When cds_lfht_add_unique
137 * fails (returns a node different from the one passed as parameter), it
138 * acts as a "read" operation. A cds_lfht_add_unique failure is a
139 * cds_lfht_lookup "read" operation, therefore, any ordering guarantee
140 * referring to "lookup" imply any of "lookup" or cds_lfht_add_unique
141 * (failure).
142 *
143 * We define "prior" and "later" node as nodes observable by reads and
144 * read traversals respectively before and after a write or sequence of
145 * write operations.
146 *
147 * Hash-table operations are often cascaded, for example, the pointer
148 * returned by a cds_lfht_lookup() might be passed to a cds_lfht_next(),
149 * whose return value might in turn be passed to another hash-table
150 * operation. This entire cascaded series of operations must be enclosed
151 * by a pair of matching rcu_read_lock() and rcu_read_unlock()
152 * operations.
153 *
154 * The following ordering guarantees are offered by this hash table:
155 *
156 * A.1) "read" after "write": if there is ordering between a write and a
157 * later read, then the read is guaranteed to see the write or some
158 * later write.
159 * A.2) "read traversal" after "write": given that there is dependency
160 * ordering between reads in a "read traversal", if there is
161 * ordering between a write and the first read of the traversal,
162 * then the "read traversal" is guaranteed to see the write or
163 * some later write.
164 * B.1) "write" after "read": if there is ordering between a read and a
165 * later write, then the read will never see the write.
166 * B.2) "write" after "read traversal": given that there is dependency
167 * ordering between reads in a "read traversal", if there is
168 * ordering between the last read of the traversal and a later
169 * write, then the "read traversal" will never see the write.
170 * C) "write" while "read traversal": if a write occurs during a "read
171 * traversal", the traversal may, or may not, see the write.
172 * D.1) "write" after "write": if there is ordering between a write and
173 * a later write, then the later write is guaranteed to see the
174 * effects of the first write.
175 * D.2) Concurrent "write" pairs: The system will assign an arbitrary
176 * order to any pair of concurrent conflicting writes.
177 * Non-conflicting writes (for example, to different keys) are
178 * unordered.
179 * E) If a grace period separates a "del" or "replace" operation
180 * and a subsequent operation, then that subsequent operation is
181 * guaranteed not to see the removed item.
182 * F) Uniqueness guarantee: given a hash table that does not contain
183 * duplicate items for a given key, there will only be one item in
184 * the hash table after an arbitrary sequence of add_unique and/or
185 * add_replace operations. Note, however, that a pair of
186 * concurrent read operations might well access two different items
187 * with that key.
188 * G.1) If a pair of lookups for a given key are ordered (e.g. by a
189 * memory barrier), then the second lookup will return the same
190 * node as the previous lookup, or some later node.
191 * G.2) A "read traversal" that starts after the end of a prior "read
192 * traversal" (ordered by memory barriers) is guaranteed to see the
193 * same nodes as the previous traversal, or some later nodes.
194 * G.3) Concurrent "read" pairs: concurrent reads are unordered. For
195 * example, if a pair of reads to the same key run concurrently
196 * with an insertion of that same key, the reads remain unordered
197 * regardless of their return values. In other words, you cannot
198 * rely on the values returned by the reads to deduce ordering.
199 *
200 * Progress guarantees:
201 *
202 * * Reads are wait-free. These operations always move forward in the
203 * hash table linked list, and this list has no loop.
204 * * Writes are lock-free. Any retry loop performed by a write operation
205 * is triggered by progress made within another update operation.
0f5543cb 206 *
1ee8f000 207 * Bucket node tables:
93d46c39 208 *
1ee8f000
LJ
209 * hash table hash table the last all bucket node tables
210 * order size bucket node 0 1 2 3 4 5 6(index)
93d46c39
LJ
211 * table size
212 * 0 1 1 1
213 * 1 2 1 1 1
214 * 2 4 2 1 1 2
215 * 3 8 4 1 1 2 4
216 * 4 16 8 1 1 2 4 8
217 * 5 32 16 1 1 2 4 8 16
218 * 6 64 32 1 1 2 4 8 16 32
219 *
1ee8f000 220 * When growing/shrinking, we only focus on the last bucket node table
93d46c39
LJ
221 * which size is (!order ? 1 : (1 << (order -1))).
222 *
223 * Example for growing/shrinking:
1ee8f000
LJ
224 * grow hash table from order 5 to 6: init the index=6 bucket node table
225 * shrink hash table from order 6 to 5: fini the index=6 bucket node table
93d46c39 226 *
1475579c 227 * A bit of ascii art explanation:
67ecffc0 228 *
1f67ba50
MD
229 * The order index is the off-by-one compared to the actual power of 2
230 * because we use index 0 to deal with the 0 special-case.
67ecffc0 231 *
1475579c 232 * This shows the nodes for a small table ordered by reversed bits:
67ecffc0 233 *
1475579c
MD
234 * bits reverse
235 * 0 000 000
236 * 4 100 001
237 * 2 010 010
238 * 6 110 011
239 * 1 001 100
240 * 5 101 101
241 * 3 011 110
242 * 7 111 111
67ecffc0
MD
243 *
244 * This shows the nodes in order of non-reversed bits, linked by
1475579c 245 * reversed-bit order.
67ecffc0 246 *
1475579c
MD
247 * order bits reverse
248 * 0 0 000 000
0adc36a8
LJ
249 * 1 | 1 001 100 <-
250 * 2 | | 2 010 010 <- |
f6fdd688 251 * | | | 3 011 110 | <- |
1475579c
MD
252 * 3 -> | | | 4 100 001 | |
253 * -> | | 5 101 101 |
254 * -> | 6 110 011
255 * -> 7 111 111
e753ff5a
MD
256 */
257
2ed95849
MD
258#define _LGPL_SOURCE
259#include <stdlib.h>
e0ba718a
MD
260#include <errno.h>
261#include <assert.h>
262#include <stdio.h>
abc490a1 263#include <stdint.h>
f000907d 264#include <string.h>
125f41db 265#include <sched.h>
95747f9e 266#include <unistd.h>
e0ba718a 267
a47dd11c 268#include "compat-getcpu.h"
95747f9e 269#include <urcu-pointer.h>
abc490a1 270#include <urcu-call-rcu.h>
7b17c13e 271#include <urcu-flavor.h>
a42cc659
MD
272#include <urcu/arch.h>
273#include <urcu/uatomic.h>
a42cc659 274#include <urcu/compiler.h>
abc490a1 275#include <urcu/rculfhash.h>
22e3a77f 276#include <urcu/static/urcu-signal-nr.h>
0b6aa001 277#include <rculfhash-internal.h>
5e28c532 278#include <stdio.h>
464a1ec9 279#include <pthread.h>
d0ec0ed2
MD
280#include <signal.h>
281#include "workqueue.h"
282#include "urcu-die.h"
44395fb7 283
f8994aee 284/*
4c42f1b8 285 * Split-counters lazily update the global counter each 1024
f8994aee
MD
286 * addition/removal. It automatically keeps track of resize required.
287 * We use the bucket length as indicator for need to expand for small
ffa11a18 288 * tables and machines lacking per-cpu data support.
f8994aee
MD
289 */
290#define COUNT_COMMIT_ORDER 10
4ddbb355 291#define DEFAULT_SPLIT_COUNT_MASK 0xFUL
6ea6bc67
MD
292#define CHAIN_LEN_TARGET 1
293#define CHAIN_LEN_RESIZE_THRESHOLD 3
2ed95849 294
cd95516d 295/*
76a73da8 296 * Define the minimum table size.
cd95516d 297 */
d0d8f9aa
LJ
298#define MIN_TABLE_ORDER 0
299#define MIN_TABLE_SIZE (1UL << MIN_TABLE_ORDER)
cd95516d 300
b7d619b0 301/*
1ee8f000 302 * Minimum number of bucket nodes to touch per thread to parallelize grow/shrink.
b7d619b0 303 */
6083a889
MD
304#define MIN_PARTITION_PER_THREAD_ORDER 12
305#define MIN_PARTITION_PER_THREAD (1UL << MIN_PARTITION_PER_THREAD_ORDER)
b7d619b0 306
d95bd160
MD
307/*
308 * The removed flag needs to be updated atomically with the pointer.
48ed1c18 309 * It indicates that no node must attach to the node scheduled for
b198f0fd 310 * removal, and that node garbage collection must be performed.
1ee8f000 311 * The bucket flag does not require to be updated atomically with the
d95bd160 312 * pointer, but it is added as a pointer low bit flag to save space.
1f67ba50
MD
313 * The "removal owner" flag is used to detect which of the "del"
314 * operation that has set the "removed flag" gets to return the removed
315 * node to its caller. Note that the replace operation does not need to
316 * iteract with the "removal owner" flag, because it validates that
317 * the "removed" flag is not set before performing its cmpxchg.
d95bd160 318 */
d37166c6 319#define REMOVED_FLAG (1UL << 0)
1ee8f000 320#define BUCKET_FLAG (1UL << 1)
db00ccc3
MD
321#define REMOVAL_OWNER_FLAG (1UL << 2)
322#define FLAGS_MASK ((1UL << 3) - 1)
d37166c6 323
bb7b2f26 324/* Value of the end pointer. Should not interact with flags. */
f9c80341 325#define END_VALUE NULL
bb7b2f26 326
7f52427b
MD
327/*
328 * ht_items_count: Split-counters counting the number of node addition
329 * and removal in the table. Only used if the CDS_LFHT_ACCOUNTING flag
330 * is set at hash table creation.
331 *
332 * These are free-running counters, never reset to zero. They count the
333 * number of add/remove, and trigger every (1 << COUNT_COMMIT_ORDER)
334 * operations to update the global counter. We choose a power-of-2 value
335 * for the trigger to deal with 32 or 64-bit overflow of the counter.
336 */
df44348d 337struct ht_items_count {
860d07e8 338 unsigned long add, del;
df44348d
MD
339} __attribute__((aligned(CAA_CACHE_LINE_SIZE)));
340
7f52427b 341/*
d0ec0ed2 342 * resize_work: Contains arguments passed to worker thread
7f52427b
MD
343 * responsible for performing lazy resize.
344 */
d0ec0ed2
MD
345struct resize_work {
346 struct urcu_work work;
14044b37 347 struct cds_lfht *ht;
abc490a1 348};
2ed95849 349
7f52427b
MD
350/*
351 * partition_resize_work: Contains arguments passed to worker threads
352 * executing the hash table resize on partitions of the hash table
353 * assigned to each processor's worker thread.
354 */
b7d619b0 355struct partition_resize_work {
1af6e26e 356 pthread_t thread_id;
b7d619b0
MD
357 struct cds_lfht *ht;
358 unsigned long i, start, len;
359 void (*fct)(struct cds_lfht *ht, unsigned long i,
360 unsigned long start, unsigned long len);
361};
362
d0ec0ed2
MD
363static struct urcu_workqueue *cds_lfht_workqueue;
364static unsigned long cds_lfht_workqueue_user_count;
365
366/*
367 * Mutex ensuring mutual exclusion between workqueue initialization and
368 * fork handlers. cds_lfht_fork_mutex nests inside call_rcu_mutex.
369 */
370static pthread_mutex_t cds_lfht_fork_mutex = PTHREAD_MUTEX_INITIALIZER;
371
372static struct urcu_atfork cds_lfht_atfork;
373
374/*
375 * atfork handler nesting counters. Handle being registered to many urcu
376 * flavors, thus being possibly invoked more than once in the
377 * pthread_atfork list of callbacks.
378 */
379static int cds_lfht_workqueue_atfork_nesting;
380
381static void cds_lfht_init_worker(const struct rcu_flavor_struct *flavor);
382static void cds_lfht_fini_worker(const struct rcu_flavor_struct *flavor);
383
abc490a1
MD
384/*
385 * Algorithm to reverse bits in a word by lookup table, extended to
386 * 64-bit words.
f9830efd 387 * Source:
abc490a1 388 * http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
f9830efd 389 * Originally from Public Domain.
abc490a1
MD
390 */
391
67ecffc0 392static const uint8_t BitReverseTable256[256] =
2ed95849 393{
abc490a1
MD
394#define R2(n) (n), (n) + 2*64, (n) + 1*64, (n) + 3*64
395#define R4(n) R2(n), R2((n) + 2*16), R2((n) + 1*16), R2((n) + 3*16)
396#define R6(n) R4(n), R4((n) + 2*4 ), R4((n) + 1*4 ), R4((n) + 3*4 )
397 R6(0), R6(2), R6(1), R6(3)
398};
399#undef R2
400#undef R4
401#undef R6
2ed95849 402
abc490a1
MD
403static
404uint8_t bit_reverse_u8(uint8_t v)
405{
406 return BitReverseTable256[v];
407}
ab7d5fc6 408
95bc7fb9
MD
409#if (CAA_BITS_PER_LONG == 32)
410static
abc490a1
MD
411uint32_t bit_reverse_u32(uint32_t v)
412{
67ecffc0
MD
413 return ((uint32_t) bit_reverse_u8(v) << 24) |
414 ((uint32_t) bit_reverse_u8(v >> 8) << 16) |
415 ((uint32_t) bit_reverse_u8(v >> 16) << 8) |
abc490a1 416 ((uint32_t) bit_reverse_u8(v >> 24));
2ed95849 417}
95bc7fb9
MD
418#else
419static
abc490a1 420uint64_t bit_reverse_u64(uint64_t v)
2ed95849 421{
67ecffc0
MD
422 return ((uint64_t) bit_reverse_u8(v) << 56) |
423 ((uint64_t) bit_reverse_u8(v >> 8) << 48) |
abc490a1
MD
424 ((uint64_t) bit_reverse_u8(v >> 16) << 40) |
425 ((uint64_t) bit_reverse_u8(v >> 24) << 32) |
67ecffc0
MD
426 ((uint64_t) bit_reverse_u8(v >> 32) << 24) |
427 ((uint64_t) bit_reverse_u8(v >> 40) << 16) |
abc490a1
MD
428 ((uint64_t) bit_reverse_u8(v >> 48) << 8) |
429 ((uint64_t) bit_reverse_u8(v >> 56));
430}
95bc7fb9 431#endif
abc490a1
MD
432
433static
434unsigned long bit_reverse_ulong(unsigned long v)
435{
436#if (CAA_BITS_PER_LONG == 32)
437 return bit_reverse_u32(v);
438#else
439 return bit_reverse_u64(v);
440#endif
441}
442
f9830efd 443/*
24365af7
MD
444 * fls: returns the position of the most significant bit.
445 * Returns 0 if no bit is set, else returns the position of the most
446 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
f9830efd 447 */
24365af7
MD
448#if defined(__i386) || defined(__x86_64)
449static inline
450unsigned int fls_u32(uint32_t x)
f9830efd 451{
24365af7
MD
452 int r;
453
e1789ce2 454 __asm__ ("bsrl %1,%0\n\t"
24365af7
MD
455 "jnz 1f\n\t"
456 "movl $-1,%0\n\t"
457 "1:\n\t"
458 : "=r" (r) : "rm" (x));
459 return r + 1;
460}
461#define HAS_FLS_U32
462#endif
463
464#if defined(__x86_64)
465static inline
466unsigned int fls_u64(uint64_t x)
467{
468 long r;
469
e1789ce2 470 __asm__ ("bsrq %1,%0\n\t"
24365af7
MD
471 "jnz 1f\n\t"
472 "movq $-1,%0\n\t"
473 "1:\n\t"
474 : "=r" (r) : "rm" (x));
475 return r + 1;
476}
477#define HAS_FLS_U64
478#endif
479
480#ifndef HAS_FLS_U64
481static __attribute__((unused))
482unsigned int fls_u64(uint64_t x)
483{
484 unsigned int r = 64;
485
486 if (!x)
487 return 0;
488
489 if (!(x & 0xFFFFFFFF00000000ULL)) {
490 x <<= 32;
491 r -= 32;
492 }
493 if (!(x & 0xFFFF000000000000ULL)) {
494 x <<= 16;
495 r -= 16;
496 }
497 if (!(x & 0xFF00000000000000ULL)) {
498 x <<= 8;
499 r -= 8;
500 }
501 if (!(x & 0xF000000000000000ULL)) {
502 x <<= 4;
503 r -= 4;
504 }
505 if (!(x & 0xC000000000000000ULL)) {
506 x <<= 2;
507 r -= 2;
508 }
509 if (!(x & 0x8000000000000000ULL)) {
510 x <<= 1;
511 r -= 1;
512 }
513 return r;
514}
515#endif
516
517#ifndef HAS_FLS_U32
518static __attribute__((unused))
519unsigned int fls_u32(uint32_t x)
520{
521 unsigned int r = 32;
f9830efd 522
24365af7
MD
523 if (!x)
524 return 0;
525 if (!(x & 0xFFFF0000U)) {
526 x <<= 16;
527 r -= 16;
528 }
529 if (!(x & 0xFF000000U)) {
530 x <<= 8;
531 r -= 8;
532 }
533 if (!(x & 0xF0000000U)) {
534 x <<= 4;
535 r -= 4;
536 }
537 if (!(x & 0xC0000000U)) {
538 x <<= 2;
539 r -= 2;
540 }
541 if (!(x & 0x80000000U)) {
542 x <<= 1;
543 r -= 1;
544 }
545 return r;
546}
547#endif
548
5bc6b66f 549unsigned int cds_lfht_fls_ulong(unsigned long x)
f9830efd 550{
6887cc5e 551#if (CAA_BITS_PER_LONG == 32)
24365af7
MD
552 return fls_u32(x);
553#else
554 return fls_u64(x);
555#endif
556}
f9830efd 557
920f8ef6
LJ
558/*
559 * Return the minimum order for which x <= (1UL << order).
560 * Return -1 if x is 0.
561 */
5bc6b66f 562int cds_lfht_get_count_order_u32(uint32_t x)
24365af7 563{
920f8ef6
LJ
564 if (!x)
565 return -1;
24365af7 566
920f8ef6 567 return fls_u32(x - 1);
24365af7
MD
568}
569
920f8ef6
LJ
570/*
571 * Return the minimum order for which x <= (1UL << order).
572 * Return -1 if x is 0.
573 */
5bc6b66f 574int cds_lfht_get_count_order_ulong(unsigned long x)
24365af7 575{
920f8ef6
LJ
576 if (!x)
577 return -1;
24365af7 578
5bc6b66f 579 return cds_lfht_fls_ulong(x - 1);
f9830efd
MD
580}
581
582static
ab65b890 583void cds_lfht_resize_lazy_grow(struct cds_lfht *ht, unsigned long size, int growth);
f9830efd 584
f8994aee 585static
4105056a 586void cds_lfht_resize_lazy_count(struct cds_lfht *ht, unsigned long size,
f8994aee
MD
587 unsigned long count);
588
5ffcaeef
MD
589static void mutex_lock(pthread_mutex_t *mutex)
590{
591 int ret;
592
593#ifndef DISTRUST_SIGNALS_EXTREME
594 ret = pthread_mutex_lock(mutex);
595 if (ret)
596 urcu_die(ret);
597#else /* #ifndef DISTRUST_SIGNALS_EXTREME */
598 while ((ret = pthread_mutex_trylock(mutex)) != 0) {
599 if (ret != EBUSY && ret != EINTR)
600 urcu_die(ret);
601 if (CMM_LOAD_SHARED(URCU_TLS(rcu_reader).need_mb)) {
602 cmm_smp_mb();
603 _CMM_STORE_SHARED(URCU_TLS(rcu_reader).need_mb, 0);
604 cmm_smp_mb();
605 }
606 (void) poll(NULL, 0, 10);
607 }
608#endif /* #else #ifndef DISTRUST_SIGNALS_EXTREME */
609}
610
611static void mutex_unlock(pthread_mutex_t *mutex)
612{
613 int ret;
614
615 ret = pthread_mutex_unlock(mutex);
616 if (ret)
617 urcu_die(ret);
618}
619
df44348d 620static long nr_cpus_mask = -1;
4c42f1b8 621static long split_count_mask = -1;
e53ab1eb 622static int split_count_order = -1;
4c42f1b8 623
4ddbb355 624#if defined(HAVE_SYSCONF)
4c42f1b8
LJ
625static void ht_init_nr_cpus_mask(void)
626{
627 long maxcpus;
628
629 maxcpus = sysconf(_SC_NPROCESSORS_CONF);
630 if (maxcpus <= 0) {
631 nr_cpus_mask = -2;
632 return;
633 }
634 /*
635 * round up number of CPUs to next power of two, so we
636 * can use & for modulo.
637 */
5bc6b66f 638 maxcpus = 1UL << cds_lfht_get_count_order_ulong(maxcpus);
4c42f1b8
LJ
639 nr_cpus_mask = maxcpus - 1;
640}
4ddbb355
LJ
641#else /* #if defined(HAVE_SYSCONF) */
642static void ht_init_nr_cpus_mask(void)
643{
644 nr_cpus_mask = -2;
645}
646#endif /* #else #if defined(HAVE_SYSCONF) */
df44348d
MD
647
648static
5afadd12 649void alloc_split_items_count(struct cds_lfht *ht)
df44348d 650{
4c42f1b8
LJ
651 if (nr_cpus_mask == -1) {
652 ht_init_nr_cpus_mask();
4ddbb355
LJ
653 if (nr_cpus_mask < 0)
654 split_count_mask = DEFAULT_SPLIT_COUNT_MASK;
655 else
656 split_count_mask = nr_cpus_mask;
e53ab1eb
MD
657 split_count_order =
658 cds_lfht_get_count_order_ulong(split_count_mask + 1);
df44348d 659 }
4c42f1b8 660
4ddbb355 661 assert(split_count_mask >= 0);
5afadd12
LJ
662
663 if (ht->flags & CDS_LFHT_ACCOUNTING) {
95bc7fb9
MD
664 ht->split_count = calloc(split_count_mask + 1,
665 sizeof(struct ht_items_count));
5afadd12
LJ
666 assert(ht->split_count);
667 } else {
668 ht->split_count = NULL;
669 }
df44348d
MD
670}
671
672static
5afadd12 673void free_split_items_count(struct cds_lfht *ht)
df44348d 674{
5afadd12 675 poison_free(ht->split_count);
df44348d
MD
676}
677
678static
14360f1c 679int ht_get_split_count_index(unsigned long hash)
df44348d
MD
680{
681 int cpu;
682
4c42f1b8 683 assert(split_count_mask >= 0);
a47dd11c 684 cpu = urcu_sched_getcpu();
8ed51e04 685 if (caa_unlikely(cpu < 0))
14360f1c 686 return hash & split_count_mask;
df44348d 687 else
4c42f1b8 688 return cpu & split_count_mask;
df44348d
MD
689}
690
691static
14360f1c 692void ht_count_add(struct cds_lfht *ht, unsigned long size, unsigned long hash)
df44348d 693{
4c42f1b8
LJ
694 unsigned long split_count;
695 int index;
314558bf 696 long count;
df44348d 697
8ed51e04 698 if (caa_unlikely(!ht->split_count))
3171717f 699 return;
14360f1c 700 index = ht_get_split_count_index(hash);
4c42f1b8 701 split_count = uatomic_add_return(&ht->split_count[index].add, 1);
314558bf
MD
702 if (caa_likely(split_count & ((1UL << COUNT_COMMIT_ORDER) - 1)))
703 return;
704 /* Only if number of add multiple of 1UL << COUNT_COMMIT_ORDER */
705
706 dbg_printf("add split count %lu\n", split_count);
707 count = uatomic_add_return(&ht->count,
708 1UL << COUNT_COMMIT_ORDER);
4c299dcb 709 if (caa_likely(count & (count - 1)))
314558bf
MD
710 return;
711 /* Only if global count is power of 2 */
712
713 if ((count >> CHAIN_LEN_RESIZE_THRESHOLD) < size)
714 return;
715 dbg_printf("add set global %ld\n", count);
716 cds_lfht_resize_lazy_count(ht, size,
717 count >> (CHAIN_LEN_TARGET - 1));
df44348d
MD
718}
719
720static
14360f1c 721void ht_count_del(struct cds_lfht *ht, unsigned long size, unsigned long hash)
df44348d 722{
4c42f1b8
LJ
723 unsigned long split_count;
724 int index;
314558bf 725 long count;
df44348d 726
8ed51e04 727 if (caa_unlikely(!ht->split_count))
3171717f 728 return;
14360f1c 729 index = ht_get_split_count_index(hash);
4c42f1b8 730 split_count = uatomic_add_return(&ht->split_count[index].del, 1);
314558bf
MD
731 if (caa_likely(split_count & ((1UL << COUNT_COMMIT_ORDER) - 1)))
732 return;
733 /* Only if number of deletes multiple of 1UL << COUNT_COMMIT_ORDER */
734
735 dbg_printf("del split count %lu\n", split_count);
736 count = uatomic_add_return(&ht->count,
737 -(1UL << COUNT_COMMIT_ORDER));
4c299dcb 738 if (caa_likely(count & (count - 1)))
314558bf
MD
739 return;
740 /* Only if global count is power of 2 */
741
742 if ((count >> CHAIN_LEN_RESIZE_THRESHOLD) >= size)
743 return;
744 dbg_printf("del set global %ld\n", count);
745 /*
746 * Don't shrink table if the number of nodes is below a
747 * certain threshold.
748 */
749 if (count < (1UL << COUNT_COMMIT_ORDER) * (split_count_mask + 1))
750 return;
751 cds_lfht_resize_lazy_count(ht, size,
752 count >> (CHAIN_LEN_TARGET - 1));
df44348d
MD
753}
754
f9830efd 755static
4105056a 756void check_resize(struct cds_lfht *ht, unsigned long size, uint32_t chain_len)
f9830efd 757{
f8994aee
MD
758 unsigned long count;
759
b8af5011
MD
760 if (!(ht->flags & CDS_LFHT_AUTO_RESIZE))
761 return;
f8994aee
MD
762 count = uatomic_read(&ht->count);
763 /*
764 * Use bucket-local length for small table expand and for
765 * environments lacking per-cpu data support.
766 */
e53ab1eb 767 if (count >= (1UL << (COUNT_COMMIT_ORDER + split_count_order)))
f8994aee 768 return;
24365af7 769 if (chain_len > 100)
f0c29ed7 770 dbg_printf("WARNING: large chain length: %u.\n",
24365af7 771 chain_len);
e53ab1eb
MD
772 if (chain_len >= CHAIN_LEN_RESIZE_THRESHOLD) {
773 int growth;
774
775 /*
776 * Ideal growth calculated based on chain length.
777 */
778 growth = cds_lfht_get_count_order_u32(chain_len
779 - (CHAIN_LEN_TARGET - 1));
780 if ((ht->flags & CDS_LFHT_ACCOUNTING)
781 && (size << growth)
782 >= (1UL << (COUNT_COMMIT_ORDER
783 + split_count_order))) {
784 /*
785 * If ideal growth expands the hash table size
786 * beyond the "small hash table" sizes, use the
787 * maximum small hash table size to attempt
788 * expanding the hash table. This only applies
789 * when node accounting is available, otherwise
790 * the chain length is used to expand the hash
791 * table in every case.
792 */
793 growth = COUNT_COMMIT_ORDER + split_count_order
794 - cds_lfht_get_count_order_ulong(size);
795 if (growth <= 0)
796 return;
797 }
798 cds_lfht_resize_lazy_grow(ht, size, growth);
799 }
f9830efd
MD
800}
801
abc490a1 802static
14044b37 803struct cds_lfht_node *clear_flag(struct cds_lfht_node *node)
abc490a1 804{
14044b37 805 return (struct cds_lfht_node *) (((unsigned long) node) & ~FLAGS_MASK);
abc490a1
MD
806}
807
808static
14044b37 809int is_removed(struct cds_lfht_node *node)
abc490a1 810{
d37166c6 811 return ((unsigned long) node) & REMOVED_FLAG;
abc490a1
MD
812}
813
f5596c94 814static
1ee8f000 815int is_bucket(struct cds_lfht_node *node)
f5596c94 816{
1ee8f000 817 return ((unsigned long) node) & BUCKET_FLAG;
f5596c94
MD
818}
819
820static
1ee8f000 821struct cds_lfht_node *flag_bucket(struct cds_lfht_node *node)
f5596c94 822{
1ee8f000 823 return (struct cds_lfht_node *) (((unsigned long) node) | BUCKET_FLAG);
f5596c94 824}
bb7b2f26 825
db00ccc3
MD
826static
827int is_removal_owner(struct cds_lfht_node *node)
828{
829 return ((unsigned long) node) & REMOVAL_OWNER_FLAG;
830}
831
832static
833struct cds_lfht_node *flag_removal_owner(struct cds_lfht_node *node)
834{
835 return (struct cds_lfht_node *) (((unsigned long) node) | REMOVAL_OWNER_FLAG);
836}
837
71bb3aca
MD
838static
839struct cds_lfht_node *flag_removed_or_removal_owner(struct cds_lfht_node *node)
840{
841 return (struct cds_lfht_node *) (((unsigned long) node) | REMOVED_FLAG | REMOVAL_OWNER_FLAG);
842}
843
bb7b2f26
MD
844static
845struct cds_lfht_node *get_end(void)
846{
847 return (struct cds_lfht_node *) END_VALUE;
848}
849
850static
851int is_end(struct cds_lfht_node *node)
852{
853 return clear_flag(node) == (struct cds_lfht_node *) END_VALUE;
854}
855
abc490a1 856static
ab65b890
LJ
857unsigned long _uatomic_xchg_monotonic_increase(unsigned long *ptr,
858 unsigned long v)
abc490a1
MD
859{
860 unsigned long old1, old2;
861
862 old1 = uatomic_read(ptr);
863 do {
864 old2 = old1;
865 if (old2 >= v)
f9830efd 866 return old2;
abc490a1 867 } while ((old1 = uatomic_cmpxchg(ptr, old2, v)) != old2);
ab65b890 868 return old2;
abc490a1
MD
869}
870
48f1b16d
LJ
871static
872void cds_lfht_alloc_bucket_table(struct cds_lfht *ht, unsigned long order)
873{
0b6aa001 874 return ht->mm->alloc_bucket_table(ht, order);
48f1b16d
LJ
875}
876
877/*
878 * cds_lfht_free_bucket_table() should be called with decreasing order.
879 * When cds_lfht_free_bucket_table(0) is called, it means the whole
880 * lfht is destroyed.
881 */
882static
883void cds_lfht_free_bucket_table(struct cds_lfht *ht, unsigned long order)
884{
0b6aa001 885 return ht->mm->free_bucket_table(ht, order);
48f1b16d
LJ
886}
887
9d72a73f
LJ
888static inline
889struct cds_lfht_node *bucket_at(struct cds_lfht *ht, unsigned long index)
f4a9cc0b 890{
0b6aa001 891 return ht->bucket_at(ht, index);
f4a9cc0b
LJ
892}
893
9d72a73f
LJ
894static inline
895struct cds_lfht_node *lookup_bucket(struct cds_lfht *ht, unsigned long size,
896 unsigned long hash)
897{
898 assert(size > 0);
899 return bucket_at(ht, hash & (size - 1));
900}
901
273399de
MD
902/*
903 * Remove all logically deleted nodes from a bucket up to a certain node key.
904 */
905static
1ee8f000 906void _cds_lfht_gc_bucket(struct cds_lfht_node *bucket, struct cds_lfht_node *node)
273399de 907{
14044b37 908 struct cds_lfht_node *iter_prev, *iter, *next, *new_next;
273399de 909
1ee8f000
LJ
910 assert(!is_bucket(bucket));
911 assert(!is_removed(bucket));
2f943cd7 912 assert(!is_removal_owner(bucket));
1ee8f000 913 assert(!is_bucket(node));
c90201ac 914 assert(!is_removed(node));
2f943cd7 915 assert(!is_removal_owner(node));
273399de 916 for (;;) {
1ee8f000
LJ
917 iter_prev = bucket;
918 /* We can always skip the bucket node initially */
04db56f8 919 iter = rcu_dereference(iter_prev->next);
b4cb483f 920 assert(!is_removed(iter));
2f943cd7 921 assert(!is_removal_owner(iter));
04db56f8 922 assert(iter_prev->reverse_hash <= node->reverse_hash);
bd4db153 923 /*
1ee8f000 924 * We should never be called with bucket (start of chain)
bd4db153
MD
925 * and logically removed node (end of path compression
926 * marker) being the actual same node. This would be a
927 * bug in the algorithm implementation.
928 */
1ee8f000 929 assert(bucket != node);
273399de 930 for (;;) {
8ed51e04 931 if (caa_unlikely(is_end(iter)))
f9c80341 932 return;
04db56f8 933 if (caa_likely(clear_flag(iter)->reverse_hash > node->reverse_hash))
f9c80341 934 return;
04db56f8 935 next = rcu_dereference(clear_flag(iter)->next);
8ed51e04 936 if (caa_likely(is_removed(next)))
273399de 937 break;
b453eae1 938 iter_prev = clear_flag(iter);
273399de
MD
939 iter = next;
940 }
b198f0fd 941 assert(!is_removed(iter));
2f943cd7 942 assert(!is_removal_owner(iter));
1ee8f000
LJ
943 if (is_bucket(iter))
944 new_next = flag_bucket(clear_flag(next));
f5596c94
MD
945 else
946 new_next = clear_flag(next);
04db56f8 947 (void) uatomic_cmpxchg(&iter_prev->next, iter, new_next);
273399de
MD
948 }
949}
950
9357c415
MD
951static
952int _cds_lfht_replace(struct cds_lfht *ht, unsigned long size,
953 struct cds_lfht_node *old_node,
3fb86f26 954 struct cds_lfht_node *old_next,
9357c415
MD
955 struct cds_lfht_node *new_node)
956{
04db56f8 957 struct cds_lfht_node *bucket, *ret_next;
9357c415
MD
958
959 if (!old_node) /* Return -ENOENT if asked to replace NULL node */
7801dadd 960 return -ENOENT;
9357c415
MD
961
962 assert(!is_removed(old_node));
2f943cd7 963 assert(!is_removal_owner(old_node));
1ee8f000 964 assert(!is_bucket(old_node));
9357c415 965 assert(!is_removed(new_node));
2f943cd7 966 assert(!is_removal_owner(new_node));
1ee8f000 967 assert(!is_bucket(new_node));
9357c415 968 assert(new_node != old_node);
3fb86f26 969 for (;;) {
9357c415 970 /* Insert after node to be replaced */
9357c415
MD
971 if (is_removed(old_next)) {
972 /*
973 * Too late, the old node has been removed under us
974 * between lookup and replace. Fail.
975 */
7801dadd 976 return -ENOENT;
9357c415 977 }
feda2722
LJ
978 assert(old_next == clear_flag(old_next));
979 assert(new_node != old_next);
71bb3aca
MD
980 /*
981 * REMOVAL_OWNER flag is _NEVER_ set before the REMOVED
982 * flag. It is either set atomically at the same time
983 * (replace) or after (del).
984 */
985 assert(!is_removal_owner(old_next));
feda2722 986 new_node->next = old_next;
9357c415
MD
987 /*
988 * Here is the whole trick for lock-free replace: we add
989 * the replacement node _after_ the node we want to
990 * replace by atomically setting its next pointer at the
991 * same time we set its removal flag. Given that
992 * the lookups/get next use an iterator aware of the
993 * next pointer, they will either skip the old node due
994 * to the removal flag and see the new node, or use
995 * the old node, but will not see the new one.
db00ccc3
MD
996 * This is a replacement of a node with another node
997 * that has the same value: we are therefore not
71bb3aca
MD
998 * removing a value from the hash table. We set both the
999 * REMOVED and REMOVAL_OWNER flags atomically so we own
1000 * the node after successful cmpxchg.
9357c415 1001 */
04db56f8 1002 ret_next = uatomic_cmpxchg(&old_node->next,
71bb3aca 1003 old_next, flag_removed_or_removal_owner(new_node));
3fb86f26 1004 if (ret_next == old_next)
7801dadd 1005 break; /* We performed the replacement. */
3fb86f26
LJ
1006 old_next = ret_next;
1007 }
9357c415 1008
9357c415
MD
1009 /*
1010 * Ensure that the old node is not visible to readers anymore:
1011 * lookup for the node, and remove it (along with any other
1012 * logically removed node) if found.
1013 */
04db56f8
LJ
1014 bucket = lookup_bucket(ht, size, bit_reverse_ulong(old_node->reverse_hash));
1015 _cds_lfht_gc_bucket(bucket, new_node);
7801dadd 1016
a85eff52 1017 assert(is_removed(CMM_LOAD_SHARED(old_node->next)));
7801dadd 1018 return 0;
9357c415
MD
1019}
1020
83beee94
MD
1021/*
1022 * A non-NULL unique_ret pointer uses the "add unique" (or uniquify) add
1023 * mode. A NULL unique_ret allows creation of duplicate keys.
1024 */
abc490a1 1025static
83beee94 1026void _cds_lfht_add(struct cds_lfht *ht,
91a75cc5 1027 unsigned long hash,
0422d92c 1028 cds_lfht_match_fct match,
996ff57c 1029 const void *key,
83beee94
MD
1030 unsigned long size,
1031 struct cds_lfht_node *node,
1032 struct cds_lfht_iter *unique_ret,
1ee8f000 1033 int bucket_flag)
abc490a1 1034{
14044b37 1035 struct cds_lfht_node *iter_prev, *iter, *next, *new_node, *new_next,
960c9e4f 1036 *return_node;
04db56f8 1037 struct cds_lfht_node *bucket;
abc490a1 1038
1ee8f000 1039 assert(!is_bucket(node));
c90201ac 1040 assert(!is_removed(node));
2f943cd7 1041 assert(!is_removal_owner(node));
91a75cc5 1042 bucket = lookup_bucket(ht, size, hash);
abc490a1 1043 for (;;) {
adc0de68 1044 uint32_t chain_len = 0;
abc490a1 1045
11519af6
MD
1046 /*
1047 * iter_prev points to the non-removed node prior to the
1048 * insert location.
11519af6 1049 */
04db56f8 1050 iter_prev = bucket;
1ee8f000 1051 /* We can always skip the bucket node initially */
04db56f8
LJ
1052 iter = rcu_dereference(iter_prev->next);
1053 assert(iter_prev->reverse_hash <= node->reverse_hash);
abc490a1 1054 for (;;) {
8ed51e04 1055 if (caa_unlikely(is_end(iter)))
273399de 1056 goto insert;
04db56f8 1057 if (caa_likely(clear_flag(iter)->reverse_hash > node->reverse_hash))
273399de 1058 goto insert;
238cc06e 1059
1ee8f000
LJ
1060 /* bucket node is the first node of the identical-hash-value chain */
1061 if (bucket_flag && clear_flag(iter)->reverse_hash == node->reverse_hash)
194fdbd1 1062 goto insert;
238cc06e 1063
04db56f8 1064 next = rcu_dereference(clear_flag(iter)->next);
8ed51e04 1065 if (caa_unlikely(is_removed(next)))
9dba85be 1066 goto gc_node;
238cc06e
LJ
1067
1068 /* uniquely add */
83beee94 1069 if (unique_ret
1ee8f000 1070 && !is_bucket(next)
04db56f8 1071 && clear_flag(iter)->reverse_hash == node->reverse_hash) {
238cc06e
LJ
1072 struct cds_lfht_iter d_iter = { .node = node, .next = iter, };
1073
1074 /*
1075 * uniquely adding inserts the node as the first
1076 * node of the identical-hash-value node chain.
1077 *
1078 * This semantic ensures no duplicated keys
1079 * should ever be observable in the table
1f67ba50
MD
1080 * (including traversing the table node by
1081 * node by forward iterations)
238cc06e 1082 */
04db56f8 1083 cds_lfht_next_duplicate(ht, match, key, &d_iter);
238cc06e
LJ
1084 if (!d_iter.node)
1085 goto insert;
1086
1087 *unique_ret = d_iter;
83beee94 1088 return;
48ed1c18 1089 }
238cc06e 1090
11519af6 1091 /* Only account for identical reverse hash once */
04db56f8 1092 if (iter_prev->reverse_hash != clear_flag(iter)->reverse_hash
1ee8f000 1093 && !is_bucket(next))
4105056a 1094 check_resize(ht, size, ++chain_len);
11519af6 1095 iter_prev = clear_flag(iter);
273399de 1096 iter = next;
abc490a1 1097 }
48ed1c18 1098
273399de 1099 insert:
7ec59d3b 1100 assert(node != clear_flag(iter));
11519af6 1101 assert(!is_removed(iter_prev));
2f943cd7 1102 assert(!is_removal_owner(iter_prev));
c90201ac 1103 assert(!is_removed(iter));
2f943cd7 1104 assert(!is_removal_owner(iter));
f000907d 1105 assert(iter_prev != node);
1ee8f000 1106 if (!bucket_flag)
04db56f8 1107 node->next = clear_flag(iter);
f9c80341 1108 else
1ee8f000
LJ
1109 node->next = flag_bucket(clear_flag(iter));
1110 if (is_bucket(iter))
1111 new_node = flag_bucket(node);
f5596c94
MD
1112 else
1113 new_node = node;
04db56f8 1114 if (uatomic_cmpxchg(&iter_prev->next, iter,
48ed1c18 1115 new_node) != iter) {
273399de 1116 continue; /* retry */
48ed1c18 1117 } else {
83beee94 1118 return_node = node;
960c9e4f 1119 goto end;
48ed1c18
MD
1120 }
1121
9dba85be
MD
1122 gc_node:
1123 assert(!is_removed(iter));
2f943cd7 1124 assert(!is_removal_owner(iter));
1ee8f000
LJ
1125 if (is_bucket(iter))
1126 new_next = flag_bucket(clear_flag(next));
f5596c94
MD
1127 else
1128 new_next = clear_flag(next);
04db56f8 1129 (void) uatomic_cmpxchg(&iter_prev->next, iter, new_next);
273399de 1130 /* retry */
464a1ec9 1131 }
9357c415 1132end:
83beee94
MD
1133 if (unique_ret) {
1134 unique_ret->node = return_node;
1135 /* unique_ret->next left unset, never used. */
1136 }
abc490a1 1137}
464a1ec9 1138
abc490a1 1139static
860d07e8 1140int _cds_lfht_del(struct cds_lfht *ht, unsigned long size,
b65ec430 1141 struct cds_lfht_node *node)
abc490a1 1142{
db00ccc3 1143 struct cds_lfht_node *bucket, *next;
5e28c532 1144
9357c415 1145 if (!node) /* Return -ENOENT if asked to delete NULL node */
743f9143 1146 return -ENOENT;
9357c415 1147
7ec59d3b 1148 /* logically delete the node */
1ee8f000 1149 assert(!is_bucket(node));
c90201ac 1150 assert(!is_removed(node));
db00ccc3 1151 assert(!is_removal_owner(node));
48ed1c18 1152
db00ccc3
MD
1153 /*
1154 * We are first checking if the node had previously been
1155 * logically removed (this check is not atomic with setting the
1156 * logical removal flag). Return -ENOENT if the node had
1157 * previously been removed.
1158 */
a85eff52 1159 next = CMM_LOAD_SHARED(node->next); /* next is not dereferenced */
db00ccc3
MD
1160 if (caa_unlikely(is_removed(next)))
1161 return -ENOENT;
b65ec430 1162 assert(!is_bucket(next));
196f4fab
MD
1163 /*
1164 * The del operation semantic guarantees a full memory barrier
1165 * before the uatomic_or atomic commit of the deletion flag.
1166 */
1167 cmm_smp_mb__before_uatomic_or();
db00ccc3
MD
1168 /*
1169 * We set the REMOVED_FLAG unconditionally. Note that there may
1170 * be more than one concurrent thread setting this flag.
1171 * Knowing which wins the race will be known after the garbage
1172 * collection phase, stay tuned!
1173 */
1174 uatomic_or(&node->next, REMOVED_FLAG);
7ec59d3b 1175 /* We performed the (logical) deletion. */
7ec59d3b
MD
1176
1177 /*
1178 * Ensure that the node is not visible to readers anymore: lookup for
273399de
MD
1179 * the node, and remove it (along with any other logically removed node)
1180 * if found.
11519af6 1181 */
04db56f8
LJ
1182 bucket = lookup_bucket(ht, size, bit_reverse_ulong(node->reverse_hash));
1183 _cds_lfht_gc_bucket(bucket, node);
743f9143 1184
a85eff52 1185 assert(is_removed(CMM_LOAD_SHARED(node->next)));
db00ccc3
MD
1186 /*
1187 * Last phase: atomically exchange node->next with a version
1188 * having "REMOVAL_OWNER_FLAG" set. If the returned node->next
1189 * pointer did _not_ have "REMOVAL_OWNER_FLAG" set, we now own
1190 * the node and win the removal race.
1191 * It is interesting to note that all "add" paths are forbidden
1192 * to change the next pointer starting from the point where the
1193 * REMOVED_FLAG is set, so here using a read, followed by a
1194 * xchg() suffice to guarantee that the xchg() will ever only
1195 * set the "REMOVAL_OWNER_FLAG" (or change nothing if the flag
1196 * was already set).
1197 */
1198 if (!is_removal_owner(uatomic_xchg(&node->next,
1199 flag_removal_owner(node->next))))
1200 return 0;
1201 else
1202 return -ENOENT;
abc490a1 1203}
2ed95849 1204
b7d619b0
MD
1205static
1206void *partition_resize_thread(void *arg)
1207{
1208 struct partition_resize_work *work = arg;
1209
7b17c13e 1210 work->ht->flavor->register_thread();
b7d619b0 1211 work->fct(work->ht, work->i, work->start, work->len);
7b17c13e 1212 work->ht->flavor->unregister_thread();
b7d619b0
MD
1213 return NULL;
1214}
1215
1216static
1217void partition_resize_helper(struct cds_lfht *ht, unsigned long i,
1218 unsigned long len,
1219 void (*fct)(struct cds_lfht *ht, unsigned long i,
1220 unsigned long start, unsigned long len))
1221{
e54ec2f5 1222 unsigned long partition_len, start = 0;
b7d619b0 1223 struct partition_resize_work *work;
6083a889
MD
1224 int thread, ret;
1225 unsigned long nr_threads;
b7d619b0 1226
d7f3ba4c
EW
1227 assert(nr_cpus_mask != -1);
1228 if (nr_cpus_mask < 0 || len < 2 * MIN_PARTITION_PER_THREAD)
1229 goto fallback;
1230
6083a889
MD
1231 /*
1232 * Note: nr_cpus_mask + 1 is always power of 2.
1233 * We spawn just the number of threads we need to satisfy the minimum
1234 * partition size, up to the number of CPUs in the system.
1235 */
91452a6a
MD
1236 if (nr_cpus_mask > 0) {
1237 nr_threads = min(nr_cpus_mask + 1,
1238 len >> MIN_PARTITION_PER_THREAD_ORDER);
1239 } else {
1240 nr_threads = 1;
1241 }
5bc6b66f 1242 partition_len = len >> cds_lfht_get_count_order_ulong(nr_threads);
6083a889 1243 work = calloc(nr_threads, sizeof(*work));
7c75d498
EW
1244 if (!work) {
1245 dbg_printf("error allocating for resize, single-threading\n");
1246 goto fallback;
1247 }
6083a889
MD
1248 for (thread = 0; thread < nr_threads; thread++) {
1249 work[thread].ht = ht;
1250 work[thread].i = i;
1251 work[thread].len = partition_len;
1252 work[thread].start = thread * partition_len;
1253 work[thread].fct = fct;
1af6e26e 1254 ret = pthread_create(&(work[thread].thread_id), ht->resize_attr,
6083a889 1255 partition_resize_thread, &work[thread]);
e54ec2f5
EW
1256 if (ret == EAGAIN) {
1257 /*
1258 * Out of resources: wait and join the threads
1259 * we've created, then handle leftovers.
1260 */
1261 dbg_printf("error spawning for resize, single-threading\n");
1262 start = work[thread].start;
1263 len -= start;
1264 nr_threads = thread;
1265 break;
1266 }
b7d619b0
MD
1267 assert(!ret);
1268 }
6083a889 1269 for (thread = 0; thread < nr_threads; thread++) {
1af6e26e 1270 ret = pthread_join(work[thread].thread_id, NULL);
b7d619b0
MD
1271 assert(!ret);
1272 }
1273 free(work);
e54ec2f5
EW
1274
1275 /*
1276 * A pthread_create failure above will either lead in us having
1277 * no threads to join or starting at a non-zero offset,
1278 * fallback to single thread processing of leftovers.
1279 */
1280 if (start == 0 && nr_threads > 0)
1281 return;
7c75d498 1282fallback:
e54ec2f5 1283 fct(ht, i, start, len);
b7d619b0
MD
1284}
1285
e8de508e
MD
1286/*
1287 * Holding RCU read lock to protect _cds_lfht_add against memory
d0ec0ed2 1288 * reclaim that could be performed by other worker threads (ABA
e8de508e 1289 * problem).
9ee0fc9a 1290 *
b7d619b0 1291 * When we reach a certain length, we can split this population phase over
9ee0fc9a
MD
1292 * many worker threads, based on the number of CPUs available in the system.
1293 * This should therefore take care of not having the expand lagging behind too
1294 * many concurrent insertion threads by using the scheduler's ability to
1ee8f000 1295 * schedule bucket node population fairly with insertions.
e8de508e 1296 */
4105056a 1297static
b7d619b0
MD
1298void init_table_populate_partition(struct cds_lfht *ht, unsigned long i,
1299 unsigned long start, unsigned long len)
4105056a 1300{
9d72a73f 1301 unsigned long j, size = 1UL << (i - 1);
4105056a 1302
d0d8f9aa 1303 assert(i > MIN_TABLE_ORDER);
7b17c13e 1304 ht->flavor->read_lock();
9d72a73f
LJ
1305 for (j = size + start; j < size + start + len; j++) {
1306 struct cds_lfht_node *new_node = bucket_at(ht, j);
1307
1308 assert(j >= size && j < (size << 1));
1309 dbg_printf("init populate: order %lu index %lu hash %lu\n",
1310 i, j, j);
1311 new_node->reverse_hash = bit_reverse_ulong(j);
91a75cc5 1312 _cds_lfht_add(ht, j, NULL, NULL, size, new_node, NULL, 1);
4105056a 1313 }
7b17c13e 1314 ht->flavor->read_unlock();
b7d619b0
MD
1315}
1316
1317static
1318void init_table_populate(struct cds_lfht *ht, unsigned long i,
1319 unsigned long len)
1320{
b7d619b0 1321 partition_resize_helper(ht, i, len, init_table_populate_partition);
4105056a
MD
1322}
1323
abc490a1 1324static
4105056a 1325void init_table(struct cds_lfht *ht,
93d46c39 1326 unsigned long first_order, unsigned long last_order)
24365af7 1327{
93d46c39 1328 unsigned long i;
24365af7 1329
93d46c39
LJ
1330 dbg_printf("init table: first_order %lu last_order %lu\n",
1331 first_order, last_order);
d0d8f9aa 1332 assert(first_order > MIN_TABLE_ORDER);
93d46c39 1333 for (i = first_order; i <= last_order; i++) {
4105056a 1334 unsigned long len;
24365af7 1335
4f6e90b7 1336 len = 1UL << (i - 1);
f0c29ed7 1337 dbg_printf("init order %lu len: %lu\n", i, len);
4d676753
MD
1338
1339 /* Stop expand if the resize target changes under us */
7b3893e4 1340 if (CMM_LOAD_SHARED(ht->resize_target) < (1UL << i))
4d676753
MD
1341 break;
1342
48f1b16d 1343 cds_lfht_alloc_bucket_table(ht, i);
4105056a 1344
4105056a 1345 /*
1ee8f000
LJ
1346 * Set all bucket nodes reverse hash values for a level and
1347 * link all bucket nodes into the table.
4105056a 1348 */
dc1da8f6 1349 init_table_populate(ht, i, len);
4105056a 1350
f9c80341
MD
1351 /*
1352 * Update table size.
1353 */
1354 cmm_smp_wmb(); /* populate data before RCU size */
7b3893e4 1355 CMM_STORE_SHARED(ht->size, 1UL << i);
f9c80341 1356
4f6e90b7 1357 dbg_printf("init new size: %lu\n", 1UL << i);
4105056a
MD
1358 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
1359 break;
1360 }
1361}
1362
e8de508e
MD
1363/*
1364 * Holding RCU read lock to protect _cds_lfht_remove against memory
d0ec0ed2 1365 * reclaim that could be performed by other worker threads (ABA
e8de508e
MD
1366 * problem).
1367 * For a single level, we logically remove and garbage collect each node.
1368 *
1369 * As a design choice, we perform logical removal and garbage collection on a
1370 * node-per-node basis to simplify this algorithm. We also assume keeping good
1371 * cache locality of the operation would overweight possible performance gain
1372 * that could be achieved by batching garbage collection for multiple levels.
1373 * However, this would have to be justified by benchmarks.
1374 *
1375 * Concurrent removal and add operations are helping us perform garbage
1376 * collection of logically removed nodes. We guarantee that all logically
d0ec0ed2
MD
1377 * removed nodes have been garbage-collected (unlinked) before work
1378 * enqueue is invoked to free a hole level of bucket nodes (after a
1379 * grace period).
e8de508e 1380 *
1f67ba50
MD
1381 * Logical removal and garbage collection can therefore be done in batch
1382 * or on a node-per-node basis, as long as the guarantee above holds.
9ee0fc9a 1383 *
b7d619b0
MD
1384 * When we reach a certain length, we can split this removal over many worker
1385 * threads, based on the number of CPUs available in the system. This should
1386 * take care of not letting resize process lag behind too many concurrent
9ee0fc9a 1387 * updater threads actively inserting into the hash table.
e8de508e 1388 */
4105056a 1389static
b7d619b0
MD
1390void remove_table_partition(struct cds_lfht *ht, unsigned long i,
1391 unsigned long start, unsigned long len)
4105056a 1392{
9d72a73f 1393 unsigned long j, size = 1UL << (i - 1);
4105056a 1394
d0d8f9aa 1395 assert(i > MIN_TABLE_ORDER);
7b17c13e 1396 ht->flavor->read_lock();
9d72a73f 1397 for (j = size + start; j < size + start + len; j++) {
2e2ce1e9
LJ
1398 struct cds_lfht_node *fini_bucket = bucket_at(ht, j);
1399 struct cds_lfht_node *parent_bucket = bucket_at(ht, j - size);
9d72a73f
LJ
1400
1401 assert(j >= size && j < (size << 1));
1402 dbg_printf("remove entry: order %lu index %lu hash %lu\n",
1403 i, j, j);
2e2ce1e9
LJ
1404 /* Set the REMOVED_FLAG to freeze the ->next for gc */
1405 uatomic_or(&fini_bucket->next, REMOVED_FLAG);
1406 _cds_lfht_gc_bucket(parent_bucket, fini_bucket);
abc490a1 1407 }
7b17c13e 1408 ht->flavor->read_unlock();
b7d619b0
MD
1409}
1410
1411static
1412void remove_table(struct cds_lfht *ht, unsigned long i, unsigned long len)
1413{
b7d619b0 1414 partition_resize_helper(ht, i, len, remove_table_partition);
2ed95849
MD
1415}
1416
61adb337
MD
1417/*
1418 * fini_table() is never called for first_order == 0, which is why
1419 * free_by_rcu_order == 0 can be used as criterion to know if free must
1420 * be called.
1421 */
1475579c 1422static
4105056a 1423void fini_table(struct cds_lfht *ht,
93d46c39 1424 unsigned long first_order, unsigned long last_order)
1475579c 1425{
93d46c39 1426 long i;
48f1b16d 1427 unsigned long free_by_rcu_order = 0;
1475579c 1428
93d46c39
LJ
1429 dbg_printf("fini table: first_order %lu last_order %lu\n",
1430 first_order, last_order);
d0d8f9aa 1431 assert(first_order > MIN_TABLE_ORDER);
93d46c39 1432 for (i = last_order; i >= first_order; i--) {
4105056a 1433 unsigned long len;
1475579c 1434
4f6e90b7 1435 len = 1UL << (i - 1);
e15df1cc 1436 dbg_printf("fini order %ld len: %lu\n", i, len);
4105056a 1437
4d676753 1438 /* Stop shrink if the resize target changes under us */
7b3893e4 1439 if (CMM_LOAD_SHARED(ht->resize_target) > (1UL << (i - 1)))
4d676753
MD
1440 break;
1441
1442 cmm_smp_wmb(); /* populate data before RCU size */
7b3893e4 1443 CMM_STORE_SHARED(ht->size, 1UL << (i - 1));
4d676753
MD
1444
1445 /*
1446 * We need to wait for all add operations to reach Q.S. (and
1447 * thus use the new table for lookups) before we can start
1ee8f000 1448 * releasing the old bucket nodes. Otherwise their lookup will
4d676753
MD
1449 * return a logically removed node as insert position.
1450 */
7b17c13e 1451 ht->flavor->update_synchronize_rcu();
48f1b16d
LJ
1452 if (free_by_rcu_order)
1453 cds_lfht_free_bucket_table(ht, free_by_rcu_order);
4d676753 1454
21263e21 1455 /*
1ee8f000
LJ
1456 * Set "removed" flag in bucket nodes about to be removed.
1457 * Unlink all now-logically-removed bucket node pointers.
4105056a
MD
1458 * Concurrent add/remove operation are helping us doing
1459 * the gc.
21263e21 1460 */
4105056a
MD
1461 remove_table(ht, i, len);
1462
48f1b16d 1463 free_by_rcu_order = i;
4105056a
MD
1464
1465 dbg_printf("fini new size: %lu\n", 1UL << i);
1475579c
MD
1466 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
1467 break;
1468 }
0d14ceb2 1469
48f1b16d 1470 if (free_by_rcu_order) {
7b17c13e 1471 ht->flavor->update_synchronize_rcu();
48f1b16d 1472 cds_lfht_free_bucket_table(ht, free_by_rcu_order);
0d14ceb2 1473 }
1475579c
MD
1474}
1475
ff0d69de 1476static
1ee8f000 1477void cds_lfht_create_bucket(struct cds_lfht *ht, unsigned long size)
ff0d69de 1478{
04db56f8 1479 struct cds_lfht_node *prev, *node;
9d72a73f 1480 unsigned long order, len, i;
ff0d69de 1481
48f1b16d 1482 cds_lfht_alloc_bucket_table(ht, 0);
ff0d69de 1483
9d72a73f
LJ
1484 dbg_printf("create bucket: order 0 index 0 hash 0\n");
1485 node = bucket_at(ht, 0);
1486 node->next = flag_bucket(get_end());
1487 node->reverse_hash = 0;
ff0d69de 1488
5bc6b66f 1489 for (order = 1; order < cds_lfht_get_count_order_ulong(size) + 1; order++) {
ff0d69de 1490 len = 1UL << (order - 1);
48f1b16d 1491 cds_lfht_alloc_bucket_table(ht, order);
ff0d69de 1492
9d72a73f
LJ
1493 for (i = 0; i < len; i++) {
1494 /*
1495 * Now, we are trying to init the node with the
1496 * hash=(len+i) (which is also a bucket with the
1497 * index=(len+i)) and insert it into the hash table,
1498 * so this node has to be inserted after the bucket
1499 * with the index=(len+i)&(len-1)=i. And because there
1500 * is no other non-bucket node nor bucket node with
1501 * larger index/hash inserted, so the bucket node
1502 * being inserted should be inserted directly linked
1503 * after the bucket node with index=i.
1504 */
1505 prev = bucket_at(ht, i);
1506 node = bucket_at(ht, len + i);
ff0d69de 1507
1ee8f000 1508 dbg_printf("create bucket: order %lu index %lu hash %lu\n",
9d72a73f
LJ
1509 order, len + i, len + i);
1510 node->reverse_hash = bit_reverse_ulong(len + i);
1511
1512 /* insert after prev */
1513 assert(is_bucket(prev->next));
ff0d69de 1514 node->next = prev->next;
1ee8f000 1515 prev->next = flag_bucket(node);
ff0d69de
LJ
1516 }
1517 }
1518}
1519
0422d92c 1520struct cds_lfht *_cds_lfht_new(unsigned long init_size,
0722081a 1521 unsigned long min_nr_alloc_buckets,
747d725c 1522 unsigned long max_nr_buckets,
b8af5011 1523 int flags,
0b6aa001 1524 const struct cds_lfht_mm_type *mm,
7b17c13e 1525 const struct rcu_flavor_struct *flavor,
b7d619b0 1526 pthread_attr_t *attr)
abc490a1 1527{
14044b37 1528 struct cds_lfht *ht;
24365af7 1529 unsigned long order;
abc490a1 1530
0722081a
LJ
1531 /* min_nr_alloc_buckets must be power of two */
1532 if (!min_nr_alloc_buckets || (min_nr_alloc_buckets & (min_nr_alloc_buckets - 1)))
5488222b 1533 return NULL;
747d725c 1534
8129be4e 1535 /* init_size must be power of two */
5488222b 1536 if (!init_size || (init_size & (init_size - 1)))
8129be4e 1537 return NULL;
747d725c 1538
c1888f3a
MD
1539 /*
1540 * Memory management plugin default.
1541 */
1542 if (!mm) {
5a2141a7
MD
1543 if (CAA_BITS_PER_LONG > 32
1544 && max_nr_buckets
c1888f3a
MD
1545 && max_nr_buckets <= (1ULL << 32)) {
1546 /*
1547 * For 64-bit architectures, with max number of
1548 * buckets small enough not to use the entire
1549 * 64-bit memory mapping space (and allowing a
1550 * fair number of hash table instances), use the
1551 * mmap allocator, which is faster than the
1552 * order allocator.
1553 */
1554 mm = &cds_lfht_mm_mmap;
1555 } else {
1556 /*
1557 * The fallback is to use the order allocator.
1558 */
1559 mm = &cds_lfht_mm_order;
1560 }
1561 }
1562
0b6aa001
LJ
1563 /* max_nr_buckets == 0 for order based mm means infinite */
1564 if (mm == &cds_lfht_mm_order && !max_nr_buckets)
747d725c
LJ
1565 max_nr_buckets = 1UL << (MAX_TABLE_ORDER - 1);
1566
1567 /* max_nr_buckets must be power of two */
1568 if (!max_nr_buckets || (max_nr_buckets & (max_nr_buckets - 1)))
1569 return NULL;
1570
d0ec0ed2
MD
1571 if (flags & CDS_LFHT_AUTO_RESIZE)
1572 cds_lfht_init_worker(flavor);
1573
0722081a 1574 min_nr_alloc_buckets = max(min_nr_alloc_buckets, MIN_TABLE_SIZE);
d0d8f9aa 1575 init_size = max(init_size, MIN_TABLE_SIZE);
747d725c
LJ
1576 max_nr_buckets = max(max_nr_buckets, min_nr_alloc_buckets);
1577 init_size = min(init_size, max_nr_buckets);
0b6aa001
LJ
1578
1579 ht = mm->alloc_cds_lfht(min_nr_alloc_buckets, max_nr_buckets);
b7d619b0 1580 assert(ht);
0b6aa001
LJ
1581 assert(ht->mm == mm);
1582 assert(ht->bucket_at == mm->bucket_at);
1583
b5d6b20f 1584 ht->flags = flags;
7b17c13e 1585 ht->flavor = flavor;
b7d619b0 1586 ht->resize_attr = attr;
5afadd12 1587 alloc_split_items_count(ht);
abc490a1
MD
1588 /* this mutex should not nest in read-side C.S. */
1589 pthread_mutex_init(&ht->resize_mutex, NULL);
5bc6b66f 1590 order = cds_lfht_get_count_order_ulong(init_size);
7b3893e4 1591 ht->resize_target = 1UL << order;
1ee8f000 1592 cds_lfht_create_bucket(ht, 1UL << order);
7b3893e4 1593 ht->size = 1UL << order;
abc490a1
MD
1594 return ht;
1595}
1596
6f554439 1597void cds_lfht_lookup(struct cds_lfht *ht, unsigned long hash,
996ff57c 1598 cds_lfht_match_fct match, const void *key,
6f554439 1599 struct cds_lfht_iter *iter)
2ed95849 1600{
04db56f8 1601 struct cds_lfht_node *node, *next, *bucket;
0422d92c 1602 unsigned long reverse_hash, size;
2ed95849 1603
abc490a1 1604 reverse_hash = bit_reverse_ulong(hash);
464a1ec9 1605
7b3893e4 1606 size = rcu_dereference(ht->size);
04db56f8 1607 bucket = lookup_bucket(ht, size, hash);
1ee8f000 1608 /* We can always skip the bucket node initially */
04db56f8 1609 node = rcu_dereference(bucket->next);
bb7b2f26 1610 node = clear_flag(node);
2ed95849 1611 for (;;) {
8ed51e04 1612 if (caa_unlikely(is_end(node))) {
96ad1112 1613 node = next = NULL;
abc490a1 1614 break;
bb7b2f26 1615 }
04db56f8 1616 if (caa_unlikely(node->reverse_hash > reverse_hash)) {
96ad1112 1617 node = next = NULL;
abc490a1 1618 break;
2ed95849 1619 }
04db56f8 1620 next = rcu_dereference(node->next);
7f52427b 1621 assert(node == clear_flag(node));
8ed51e04 1622 if (caa_likely(!is_removed(next))
1ee8f000 1623 && !is_bucket(next)
04db56f8 1624 && node->reverse_hash == reverse_hash
0422d92c 1625 && caa_likely(match(node, key))) {
273399de 1626 break;
2ed95849 1627 }
1b81fe1a 1628 node = clear_flag(next);
2ed95849 1629 }
a85eff52 1630 assert(!node || !is_bucket(CMM_LOAD_SHARED(node->next)));
adc0de68
MD
1631 iter->node = node;
1632 iter->next = next;
abc490a1 1633}
e0ba718a 1634
0422d92c 1635void cds_lfht_next_duplicate(struct cds_lfht *ht, cds_lfht_match_fct match,
996ff57c 1636 const void *key, struct cds_lfht_iter *iter)
a481e5ff 1637{
adc0de68 1638 struct cds_lfht_node *node, *next;
a481e5ff 1639 unsigned long reverse_hash;
a481e5ff 1640
adc0de68 1641 node = iter->node;
04db56f8 1642 reverse_hash = node->reverse_hash;
adc0de68 1643 next = iter->next;
a481e5ff
MD
1644 node = clear_flag(next);
1645
1646 for (;;) {
8ed51e04 1647 if (caa_unlikely(is_end(node))) {
96ad1112 1648 node = next = NULL;
a481e5ff 1649 break;
bb7b2f26 1650 }
04db56f8 1651 if (caa_unlikely(node->reverse_hash > reverse_hash)) {
96ad1112 1652 node = next = NULL;
a481e5ff
MD
1653 break;
1654 }
04db56f8 1655 next = rcu_dereference(node->next);
8ed51e04 1656 if (caa_likely(!is_removed(next))
1ee8f000 1657 && !is_bucket(next)
04db56f8 1658 && caa_likely(match(node, key))) {
a481e5ff
MD
1659 break;
1660 }
1661 node = clear_flag(next);
1662 }
a85eff52 1663 assert(!node || !is_bucket(CMM_LOAD_SHARED(node->next)));
adc0de68
MD
1664 iter->node = node;
1665 iter->next = next;
a481e5ff
MD
1666}
1667
4e9b9fbf
MD
1668void cds_lfht_next(struct cds_lfht *ht, struct cds_lfht_iter *iter)
1669{
1670 struct cds_lfht_node *node, *next;
1671
853395e1 1672 node = clear_flag(iter->next);
4e9b9fbf 1673 for (;;) {
8ed51e04 1674 if (caa_unlikely(is_end(node))) {
4e9b9fbf
MD
1675 node = next = NULL;
1676 break;
1677 }
04db56f8 1678 next = rcu_dereference(node->next);
8ed51e04 1679 if (caa_likely(!is_removed(next))
1ee8f000 1680 && !is_bucket(next)) {
4e9b9fbf
MD
1681 break;
1682 }
1683 node = clear_flag(next);
1684 }
a85eff52 1685 assert(!node || !is_bucket(CMM_LOAD_SHARED(node->next)));
4e9b9fbf
MD
1686 iter->node = node;
1687 iter->next = next;
1688}
1689
1690void cds_lfht_first(struct cds_lfht *ht, struct cds_lfht_iter *iter)
1691{
4e9b9fbf 1692 /*
1ee8f000 1693 * Get next after first bucket node. The first bucket node is the
4e9b9fbf
MD
1694 * first node of the linked list.
1695 */
9d72a73f 1696 iter->next = bucket_at(ht, 0)->next;
4e9b9fbf
MD
1697 cds_lfht_next(ht, iter);
1698}
1699
0422d92c
MD
1700void cds_lfht_add(struct cds_lfht *ht, unsigned long hash,
1701 struct cds_lfht_node *node)
abc490a1 1702{
0422d92c 1703 unsigned long size;
ab7d5fc6 1704
709bacf9 1705 node->reverse_hash = bit_reverse_ulong(hash);
7b3893e4 1706 size = rcu_dereference(ht->size);
91a75cc5 1707 _cds_lfht_add(ht, hash, NULL, NULL, size, node, NULL, 0);
14360f1c 1708 ht_count_add(ht, size, hash);
3eca1b8c
MD
1709}
1710
14044b37 1711struct cds_lfht_node *cds_lfht_add_unique(struct cds_lfht *ht,
6f554439 1712 unsigned long hash,
0422d92c 1713 cds_lfht_match_fct match,
996ff57c 1714 const void *key,
48ed1c18 1715 struct cds_lfht_node *node)
3eca1b8c 1716{
0422d92c 1717 unsigned long size;
83beee94 1718 struct cds_lfht_iter iter;
3eca1b8c 1719
709bacf9 1720 node->reverse_hash = bit_reverse_ulong(hash);
7b3893e4 1721 size = rcu_dereference(ht->size);
91a75cc5 1722 _cds_lfht_add(ht, hash, match, key, size, node, &iter, 0);
83beee94 1723 if (iter.node == node)
14360f1c 1724 ht_count_add(ht, size, hash);
83beee94 1725 return iter.node;
2ed95849
MD
1726}
1727
9357c415 1728struct cds_lfht_node *cds_lfht_add_replace(struct cds_lfht *ht,
6f554439 1729 unsigned long hash,
0422d92c 1730 cds_lfht_match_fct match,
996ff57c 1731 const void *key,
48ed1c18
MD
1732 struct cds_lfht_node *node)
1733{
0422d92c 1734 unsigned long size;
83beee94 1735 struct cds_lfht_iter iter;
48ed1c18 1736
709bacf9 1737 node->reverse_hash = bit_reverse_ulong(hash);
7b3893e4 1738 size = rcu_dereference(ht->size);
83beee94 1739 for (;;) {
91a75cc5 1740 _cds_lfht_add(ht, hash, match, key, size, node, &iter, 0);
83beee94 1741 if (iter.node == node) {
14360f1c 1742 ht_count_add(ht, size, hash);
83beee94
MD
1743 return NULL;
1744 }
1745
1746 if (!_cds_lfht_replace(ht, size, iter.node, iter.next, node))
1747 return iter.node;
1748 }
48ed1c18
MD
1749}
1750
2e79c445
MD
1751int cds_lfht_replace(struct cds_lfht *ht,
1752 struct cds_lfht_iter *old_iter,
1753 unsigned long hash,
1754 cds_lfht_match_fct match,
1755 const void *key,
9357c415
MD
1756 struct cds_lfht_node *new_node)
1757{
1758 unsigned long size;
1759
709bacf9 1760 new_node->reverse_hash = bit_reverse_ulong(hash);
2e79c445
MD
1761 if (!old_iter->node)
1762 return -ENOENT;
1763 if (caa_unlikely(old_iter->node->reverse_hash != new_node->reverse_hash))
1764 return -EINVAL;
1765 if (caa_unlikely(!match(old_iter->node, key)))
1766 return -EINVAL;
7b3893e4 1767 size = rcu_dereference(ht->size);
9357c415
MD
1768 return _cds_lfht_replace(ht, size, old_iter->node, old_iter->next,
1769 new_node);
1770}
1771
bc8c3c74 1772int cds_lfht_del(struct cds_lfht *ht, struct cds_lfht_node *node)
2ed95849 1773{
95bc7fb9 1774 unsigned long size;
df44348d 1775 int ret;
abc490a1 1776
7b3893e4 1777 size = rcu_dereference(ht->size);
bc8c3c74 1778 ret = _cds_lfht_del(ht, size, node);
14360f1c 1779 if (!ret) {
95bc7fb9
MD
1780 unsigned long hash;
1781
bc8c3c74 1782 hash = bit_reverse_ulong(node->reverse_hash);
14360f1c
LJ
1783 ht_count_del(ht, size, hash);
1784 }
df44348d 1785 return ret;
2ed95849 1786}
ab7d5fc6 1787
df55172a
MD
1788int cds_lfht_is_node_deleted(struct cds_lfht_node *node)
1789{
a85eff52 1790 return is_removed(CMM_LOAD_SHARED(node->next));
df55172a
MD
1791}
1792
abc490a1 1793static
1ee8f000 1794int cds_lfht_delete_bucket(struct cds_lfht *ht)
674f7a69 1795{
14044b37 1796 struct cds_lfht_node *node;
4105056a 1797 unsigned long order, i, size;
674f7a69 1798
abc490a1 1799 /* Check that the table is empty */
9d72a73f 1800 node = bucket_at(ht, 0);
abc490a1 1801 do {
04db56f8 1802 node = clear_flag(node)->next;
1ee8f000 1803 if (!is_bucket(node))
abc490a1 1804 return -EPERM;
273399de 1805 assert(!is_removed(node));
2f943cd7 1806 assert(!is_removal_owner(node));
bb7b2f26 1807 } while (!is_end(node));
4105056a
MD
1808 /*
1809 * size accessed without rcu_dereference because hash table is
1810 * being destroyed.
1811 */
7b3893e4 1812 size = ht->size;
1f67ba50 1813 /* Internal sanity check: all nodes left should be buckets */
48f1b16d
LJ
1814 for (i = 0; i < size; i++) {
1815 node = bucket_at(ht, i);
1816 dbg_printf("delete bucket: index %lu expected hash %lu hash %lu\n",
1817 i, i, bit_reverse_ulong(node->reverse_hash));
1818 assert(is_bucket(node->next));
1819 }
24365af7 1820
5bc6b66f 1821 for (order = cds_lfht_get_count_order_ulong(size); (long)order >= 0; order--)
48f1b16d 1822 cds_lfht_free_bucket_table(ht, order);
5488222b 1823
abc490a1 1824 return 0;
674f7a69
MD
1825}
1826
1827/*
1828 * Should only be called when no more concurrent readers nor writers can
1829 * possibly access the table.
1830 */
b7d619b0 1831int cds_lfht_destroy(struct cds_lfht *ht, pthread_attr_t **attr)
674f7a69 1832{
d0ec0ed2
MD
1833 int ret;
1834
1835 if (ht->flags & CDS_LFHT_AUTO_RESIZE) {
1836 /* Cancel ongoing resize operations. */
1837 _CMM_STORE_SHARED(ht->in_progress_destroy, 1);
1838 /* Wait for in-flight resize operations to complete */
1839 urcu_workqueue_flush_queued_work(cds_lfht_workqueue);
10e68472 1840 }
1ee8f000 1841 ret = cds_lfht_delete_bucket(ht);
abc490a1
MD
1842 if (ret)
1843 return ret;
5afadd12 1844 free_split_items_count(ht);
b7d619b0
MD
1845 if (attr)
1846 *attr = ht->resize_attr;
59629f09
MD
1847 ret = pthread_mutex_destroy(&ht->resize_mutex);
1848 if (ret)
1849 ret = -EBUSY;
d0ec0ed2
MD
1850 if (ht->flags & CDS_LFHT_AUTO_RESIZE)
1851 cds_lfht_fini_worker(ht->flavor);
98808fb1 1852 poison_free(ht);
5e28c532 1853 return ret;
674f7a69
MD
1854}
1855
14044b37 1856void cds_lfht_count_nodes(struct cds_lfht *ht,
d933dd0e 1857 long *approx_before,
273399de 1858 unsigned long *count,
d933dd0e 1859 long *approx_after)
273399de 1860{
14044b37 1861 struct cds_lfht_node *node, *next;
caf3653d 1862 unsigned long nr_bucket = 0, nr_removed = 0;
273399de 1863
7ed7682f 1864 *approx_before = 0;
5afadd12 1865 if (ht->split_count) {
973e5e1b
MD
1866 int i;
1867
4c42f1b8
LJ
1868 for (i = 0; i < split_count_mask + 1; i++) {
1869 *approx_before += uatomic_read(&ht->split_count[i].add);
1870 *approx_before -= uatomic_read(&ht->split_count[i].del);
973e5e1b
MD
1871 }
1872 }
1873
273399de 1874 *count = 0;
273399de 1875
1ee8f000 1876 /* Count non-bucket nodes in the table */
9d72a73f 1877 node = bucket_at(ht, 0);
273399de 1878 do {
04db56f8 1879 next = rcu_dereference(node->next);
b198f0fd 1880 if (is_removed(next)) {
1ee8f000 1881 if (!is_bucket(next))
caf3653d 1882 (nr_removed)++;
973e5e1b 1883 else
1ee8f000
LJ
1884 (nr_bucket)++;
1885 } else if (!is_bucket(next))
273399de 1886 (*count)++;
24365af7 1887 else
1ee8f000 1888 (nr_bucket)++;
273399de 1889 node = clear_flag(next);
bb7b2f26 1890 } while (!is_end(node));
caf3653d 1891 dbg_printf("number of logically removed nodes: %lu\n", nr_removed);
1ee8f000 1892 dbg_printf("number of bucket nodes: %lu\n", nr_bucket);
7ed7682f 1893 *approx_after = 0;
5afadd12 1894 if (ht->split_count) {
973e5e1b
MD
1895 int i;
1896
4c42f1b8
LJ
1897 for (i = 0; i < split_count_mask + 1; i++) {
1898 *approx_after += uatomic_read(&ht->split_count[i].add);
1899 *approx_after -= uatomic_read(&ht->split_count[i].del);
973e5e1b
MD
1900 }
1901 }
273399de
MD
1902}
1903
1475579c 1904/* called with resize mutex held */
abc490a1 1905static
4105056a 1906void _do_cds_lfht_grow(struct cds_lfht *ht,
1475579c 1907 unsigned long old_size, unsigned long new_size)
abc490a1 1908{
1475579c 1909 unsigned long old_order, new_order;
1475579c 1910
5bc6b66f
MD
1911 old_order = cds_lfht_get_count_order_ulong(old_size);
1912 new_order = cds_lfht_get_count_order_ulong(new_size);
1a401918
LJ
1913 dbg_printf("resize from %lu (order %lu) to %lu (order %lu) buckets\n",
1914 old_size, old_order, new_size, new_order);
1475579c 1915 assert(new_size > old_size);
93d46c39 1916 init_table(ht, old_order + 1, new_order);
abc490a1
MD
1917}
1918
1919/* called with resize mutex held */
1920static
4105056a 1921void _do_cds_lfht_shrink(struct cds_lfht *ht,
1475579c 1922 unsigned long old_size, unsigned long new_size)
464a1ec9 1923{
1475579c 1924 unsigned long old_order, new_order;
464a1ec9 1925
d0d8f9aa 1926 new_size = max(new_size, MIN_TABLE_SIZE);
5bc6b66f
MD
1927 old_order = cds_lfht_get_count_order_ulong(old_size);
1928 new_order = cds_lfht_get_count_order_ulong(new_size);
1a401918
LJ
1929 dbg_printf("resize from %lu (order %lu) to %lu (order %lu) buckets\n",
1930 old_size, old_order, new_size, new_order);
1475579c 1931 assert(new_size < old_size);
1475579c 1932
1ee8f000 1933 /* Remove and unlink all bucket nodes to remove. */
93d46c39 1934 fini_table(ht, new_order + 1, old_order);
464a1ec9
MD
1935}
1936
1475579c
MD
1937
1938/* called with resize mutex held */
1939static
1940void _do_cds_lfht_resize(struct cds_lfht *ht)
1941{
1942 unsigned long new_size, old_size;
4105056a
MD
1943
1944 /*
1945 * Resize table, re-do if the target size has changed under us.
1946 */
1947 do {
d2be3620
MD
1948 if (CMM_LOAD_SHARED(ht->in_progress_destroy))
1949 break;
7b3893e4
LJ
1950 ht->resize_initiated = 1;
1951 old_size = ht->size;
1952 new_size = CMM_LOAD_SHARED(ht->resize_target);
4105056a
MD
1953 if (old_size < new_size)
1954 _do_cds_lfht_grow(ht, old_size, new_size);
1955 else if (old_size > new_size)
1956 _do_cds_lfht_shrink(ht, old_size, new_size);
7b3893e4 1957 ht->resize_initiated = 0;
4105056a
MD
1958 /* write resize_initiated before read resize_target */
1959 cmm_smp_mb();
7b3893e4 1960 } while (ht->size != CMM_LOAD_SHARED(ht->resize_target));
1475579c
MD
1961}
1962
abc490a1 1963static
ab65b890 1964unsigned long resize_target_grow(struct cds_lfht *ht, unsigned long new_size)
464a1ec9 1965{
7b3893e4 1966 return _uatomic_xchg_monotonic_increase(&ht->resize_target, new_size);
464a1ec9
MD
1967}
1968
1475579c 1969static
4105056a 1970void resize_target_update_count(struct cds_lfht *ht,
b8af5011 1971 unsigned long count)
1475579c 1972{
d0d8f9aa 1973 count = max(count, MIN_TABLE_SIZE);
747d725c 1974 count = min(count, ht->max_nr_buckets);
7b3893e4 1975 uatomic_set(&ht->resize_target, count);
1475579c
MD
1976}
1977
1978void cds_lfht_resize(struct cds_lfht *ht, unsigned long new_size)
464a1ec9 1979{
10e68472
MD
1980 resize_target_update_count(ht, new_size);
1981 CMM_STORE_SHARED(ht->resize_initiated, 1);
5ffcaeef 1982 mutex_lock(&ht->resize_mutex);
1475579c 1983 _do_cds_lfht_resize(ht);
5ffcaeef 1984 mutex_unlock(&ht->resize_mutex);
abc490a1 1985}
464a1ec9 1986
abc490a1 1987static
d0ec0ed2 1988void do_resize_cb(struct urcu_work *work)
abc490a1 1989{
d0ec0ed2
MD
1990 struct resize_work *resize_work =
1991 caa_container_of(work, struct resize_work, work);
1992 struct cds_lfht *ht = resize_work->ht;
abc490a1 1993
d0ec0ed2 1994 ht->flavor->register_thread();
5ffcaeef 1995 mutex_lock(&ht->resize_mutex);
14044b37 1996 _do_cds_lfht_resize(ht);
5ffcaeef 1997 mutex_unlock(&ht->resize_mutex);
d0ec0ed2 1998 ht->flavor->unregister_thread();
98808fb1 1999 poison_free(work);
464a1ec9
MD
2000}
2001
abc490a1 2002static
f1f119ee 2003void __cds_lfht_resize_lazy_launch(struct cds_lfht *ht)
ab7d5fc6 2004{
d0ec0ed2 2005 struct resize_work *work;
abc490a1 2006
4105056a
MD
2007 /* Store resize_target before read resize_initiated */
2008 cmm_smp_mb();
7b3893e4 2009 if (!CMM_LOAD_SHARED(ht->resize_initiated)) {
ed35e6d8 2010 if (CMM_LOAD_SHARED(ht->in_progress_destroy)) {
59290e9d 2011 return;
ed35e6d8 2012 }
f9830efd 2013 work = malloc(sizeof(*work));
741f378e
MD
2014 if (work == NULL) {
2015 dbg_printf("error allocating resize work, bailing out\n");
741f378e
MD
2016 return;
2017 }
f9830efd 2018 work->ht = ht;
d0ec0ed2
MD
2019 urcu_workqueue_queue_work(cds_lfht_workqueue,
2020 &work->work, do_resize_cb);
7b3893e4 2021 CMM_STORE_SHARED(ht->resize_initiated, 1);
f9830efd 2022 }
ab7d5fc6 2023}
3171717f 2024
f1f119ee
LJ
2025static
2026void cds_lfht_resize_lazy_grow(struct cds_lfht *ht, unsigned long size, int growth)
2027{
2028 unsigned long target_size = size << growth;
2029
747d725c 2030 target_size = min(target_size, ht->max_nr_buckets);
f1f119ee
LJ
2031 if (resize_target_grow(ht, target_size) >= target_size)
2032 return;
2033
2034 __cds_lfht_resize_lazy_launch(ht);
2035}
2036
89bb121d
LJ
2037/*
2038 * We favor grow operations over shrink. A shrink operation never occurs
2039 * if a grow operation is queued for lazy execution. A grow operation
2040 * cancels any pending shrink lazy execution.
2041 */
3171717f 2042static
4105056a 2043void cds_lfht_resize_lazy_count(struct cds_lfht *ht, unsigned long size,
3171717f
MD
2044 unsigned long count)
2045{
b8af5011
MD
2046 if (!(ht->flags & CDS_LFHT_AUTO_RESIZE))
2047 return;
d0d8f9aa 2048 count = max(count, MIN_TABLE_SIZE);
747d725c 2049 count = min(count, ht->max_nr_buckets);
89bb121d
LJ
2050 if (count == size)
2051 return; /* Already the right size, no resize needed */
2052 if (count > size) { /* lazy grow */
2053 if (resize_target_grow(ht, count) >= count)
2054 return;
2055 } else { /* lazy shrink */
2056 for (;;) {
2057 unsigned long s;
2058
7b3893e4 2059 s = uatomic_cmpxchg(&ht->resize_target, size, count);
89bb121d
LJ
2060 if (s == size)
2061 break; /* no resize needed */
2062 if (s > size)
2063 return; /* growing is/(was just) in progress */
2064 if (s <= count)
2065 return; /* some other thread do shrink */
2066 size = s;
2067 }
2068 }
f1f119ee 2069 __cds_lfht_resize_lazy_launch(ht);
3171717f 2070}
d0ec0ed2 2071
d0ec0ed2
MD
2072static void cds_lfht_before_fork(void *priv)
2073{
2074 if (cds_lfht_workqueue_atfork_nesting++)
2075 return;
2076 mutex_lock(&cds_lfht_fork_mutex);
2077 if (!cds_lfht_workqueue)
2078 return;
2079 urcu_workqueue_pause_worker(cds_lfht_workqueue);
2080}
2081
2082static void cds_lfht_after_fork_parent(void *priv)
2083{
2084 if (--cds_lfht_workqueue_atfork_nesting)
2085 return;
2086 if (!cds_lfht_workqueue)
2087 goto end;
2088 urcu_workqueue_resume_worker(cds_lfht_workqueue);
2089end:
2090 mutex_unlock(&cds_lfht_fork_mutex);
2091}
2092
2093static void cds_lfht_after_fork_child(void *priv)
2094{
2095 if (--cds_lfht_workqueue_atfork_nesting)
2096 return;
2097 if (!cds_lfht_workqueue)
2098 goto end;
2099 urcu_workqueue_create_worker(cds_lfht_workqueue);
2100end:
2101 mutex_unlock(&cds_lfht_fork_mutex);
2102}
2103
2104static struct urcu_atfork cds_lfht_atfork = {
2105 .before_fork = cds_lfht_before_fork,
2106 .after_fork_parent = cds_lfht_after_fork_parent,
2107 .after_fork_child = cds_lfht_after_fork_child,
2108};
2109
22e3a77f 2110/*
2111 * Block all signals for the workqueue worker thread to ensure we don't
2112 * disturb the application. The SIGRCU signal needs to be unblocked for
2113 * the urcu-signal flavor.
2114 */
d0ec0ed2
MD
2115static void cds_lfht_worker_init(struct urcu_workqueue *workqueue,
2116 void *priv)
2117{
2118 int ret;
2119 sigset_t mask;
2120
d0ec0ed2
MD
2121 ret = sigfillset(&mask);
2122 if (ret)
2123 urcu_die(errno);
22e3a77f 2124 ret = sigdelset(&mask, SIGRCU);
2125 if (ret)
2126 urcu_die(ret);
2127 ret = pthread_sigmask(SIG_SETMASK, &mask, NULL);
d0ec0ed2
MD
2128 if (ret)
2129 urcu_die(ret);
2130}
2131
2132static void cds_lfht_init_worker(const struct rcu_flavor_struct *flavor)
2133{
2134 flavor->register_rculfhash_atfork(&cds_lfht_atfork);
2135
2136 mutex_lock(&cds_lfht_fork_mutex);
2137 if (cds_lfht_workqueue_user_count++)
2138 goto end;
2139 cds_lfht_workqueue = urcu_workqueue_create(0, -1, NULL,
2140 NULL, cds_lfht_worker_init, NULL, NULL, NULL, NULL, NULL);
2141end:
2142 mutex_unlock(&cds_lfht_fork_mutex);
2143}
2144
2145static void cds_lfht_fini_worker(const struct rcu_flavor_struct *flavor)
2146{
2147 mutex_lock(&cds_lfht_fork_mutex);
2148 if (--cds_lfht_workqueue_user_count)
2149 goto end;
2150 urcu_workqueue_destroy(cds_lfht_workqueue);
2151 cds_lfht_workqueue = NULL;
2152end:
2153 mutex_unlock(&cds_lfht_fork_mutex);
2154
2155 flavor->unregister_rculfhash_atfork(&cds_lfht_atfork);
2156}
This page took 0.171624 seconds and 4 git commands to generate.