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