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