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