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