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