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