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