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