source: mainline/kernel/generic/src/adt/cht.c@ dbcaa2d

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since dbcaa2d was 09ab0a9a, checked in by Jiri Svoboda <jiri@…>, 7 years ago

Fix vertical spacing with new Ccheck revision.

  • Property mode set to 100644
File size: 89.3 KB
Line 
1/*
2 * Copyright (c) 2012 Adam Hraska
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup genericadt
30 * @{
31 */
32
33/**
34 * @file
35 * @brief Scalable resizable concurrent lock-free hash table.
36 *
37 * CHT is a concurrent hash table that is scalable resizable and lock-free.
38 * resizable = the number of buckets of the table increases or decreases
39 * depending on the average number of elements per bucket (ie load)
40 * scalable = accessing the table from more cpus increases performance
41 * almost linearly
42 * lock-free = common operations never block; even if any of the operations
43 * is preempted or interrupted at any time, other operations will still
44 * make forward progress
45 *
46 * CHT is designed for read mostly scenarios. Performance degrades as the
47 * fraction of updates (insert/remove) increases. Other data structures
48 * significantly outperform CHT if the fraction of updates exceeds ~40%.
49 *
50 * CHT tolerates hardware exceptions and may be accessed from exception
51 * handlers as long as the underlying RCU implementation is exception safe.
52 *
53 * @par Caveats
54 *
55 * 0) Never assume an item is still in the table.
56 * The table may be accessed concurrently; therefore, other threads may
57 * insert or remove an item at any time. Do not assume an item is still
58 * in the table if cht_find() just returned it to you. Similarly, an
59 * item may have already been inserted by the time cht_find() returns NULL.
60 *
61 * 1) Always use RCU read locks when searching the table.
62 * Holding an RCU lock guarantees that an item found in the table remains
63 * valid (eg is not freed) even if the item was removed from the table
64 * in the meantime by another thread.
65 *
66 * 2) Never update values in place.
67 * Do not update items in the table in place, ie directly. The changes
68 * will not propagate to other readers (on other cpus) immediately or even
69 * correctly. Some readers may then encounter items that have only some
70 * of their fields changed or are completely inconsistent.
71 *
72 * Instead consider inserting an updated/changed copy of the item and
73 * removing the original item. Or contact the maintainer to provide
74 * you with a function that atomically replaces an item with a copy.
75 *
76 * 3) Use cht_insert_unique() instead of checking for duplicates with cht_find()
77 * The following code is prone to race conditions:
78 * @code
79 * if (NULL == cht_find(&h, key)) {
80 * // If another thread inserts and item here, we'll insert a duplicate.
81 * cht_insert(&h, item);
82 * }
83 * @endcode
84 * See cht_insert_unique() on how to correctly fix this.
85 *
86 *
87 * @par Semantics
88 *
89 * Lazy readers = cht_find_lazy(), cht_find_next_lazy()
90 * Readers = lazy readers, cht_find(), cht_find_next()
91 * Updates = cht_insert(), cht_insert_unique(), cht_remove_key(),
92 * cht_remove_item()
93 *
94 * Readers (but not lazy readers) are guaranteed to see the effects
95 * of @e completed updates. In other words, if cht_find() is invoked
96 * after a cht_insert() @e returned eg on another cpu, cht_find() is
97 * guaranteed to see the inserted item.
98 *
99 * Similarly, updates see the effects of @e completed updates. For example,
100 * issuing cht_remove() after a cht_insert() for that key returned (even
101 * on another cpu) is guaranteed to remove the inserted item.
102 *
103 * Reading or updating the table concurrently with other updates
104 * always returns consistent data and never corrupts the table.
105 * However the effects of concurrent updates may or may not be
106 * visible to all other concurrent readers or updaters. Eg, not
107 * all readers may see that an item has already been inserted
108 * if cht_insert() has not yet returned.
109 *
110 * Lazy readers are guaranteed to eventually see updates but it
111 * may take some time (possibly milliseconds) after the update
112 * completes for the change to propagate to lazy readers on all
113 * cpus.
114 *
115 * @par Implementation
116 *
117 * Collisions in CHT are resolved with chaining. The number of buckets
118 * is always a power of 2. Each bucket is represented with a single linked
119 * lock-free list [1]. Items in buckets are sorted by their mixed hashes
120 * in ascending order. All buckets are terminated with a single global
121 * sentinel node whose mixed hash value is the greatest possible.
122 *
123 * CHT with 2^k buckets uses the k most significant bits of a hash value
124 * to determine the bucket number where an item is to be stored. To
125 * avoid storing all items in a single bucket if the user supplied
126 * hash function does not produce uniform hashes, hash values are
127 * mixed first so that the top bits of a mixed hash change even if hash
128 * values differ only in the least significant bits. The mixed hash
129 * values are cached in cht_link.hash (which is overwritten once the
130 * item is scheduled for removal via rcu_call).
131 *
132 * A new item is inserted before all other existing items in the bucket
133 * with the same hash value as the newly inserted item (a la the original
134 * lock-free list [2]). Placing new items at the start of a same-hash
135 * sequence of items (eg duplicates) allows us to easily check for duplicates
136 * in cht_insert_unique(). The function can first check that there are
137 * no duplicates of the newly inserted item amongst the items with the
138 * same hash as the new item. If there were no duplicates the new item
139 * is linked before the same-hash items. Inserting a duplicate while
140 * the function is checking for duplicates is detected as a change of
141 * the link to the first checked same-hash item (and the search for
142 * duplicates can be restarted).
143 *
144 * @par Table resize algorithm
145 *
146 * Table resize is based on [3] and [5]. First, a new bucket head array
147 * is allocated and initialized. Second, old bucket heads are moved
148 * to the new bucket head array with the protocol mentioned in [5].
149 * At this point updaters start using the new bucket heads. Third,
150 * buckets are split (or joined) so that the table can make use of
151 * the extra bucket head slots in the new array (or stop wasting space
152 * with the unnecessary extra slots in the old array). Splitting
153 * or joining buckets employs a custom protocol. Last, the new array
154 * replaces the original bucket array.
155 *
156 * A single background work item (of the system work queue) guides
157 * resizing of the table. If an updater detects that the bucket it
158 * is about to access is undergoing a resize (ie its head is moving
159 * or it needs to be split/joined), it helps out and completes the
160 * head move or the bucket split/join.
161 *
162 * The table always grows or shrinks by a factor of 2. Because items
163 * are assigned a bucket based on the top k bits of their mixed hash
164 * values, when growing the table each bucket is split into two buckets
165 * and all items of the two new buckets come from the single bucket in the
166 * original table. Ie items from separate buckets in the original table
167 * never intermix in the new buckets. Moreover
168 * since the buckets are sorted by their mixed hash values the items
169 * at the beginning of the old bucket will end up in the first new
170 * bucket while all the remaining items of the old bucket will end up
171 * in the second new bucket. Therefore, there is a single point where
172 * to split the linked list of the old bucket into two correctly sorted
173 * linked lists of the new buckets:
174 * .- bucket split
175 * |
176 * <-- first --> v <-- second -->
177 * [old] --> [00b] -> [01b] -> [10b] -> [11b] -> sentinel
178 * ^ ^
179 * [new0] -- -+ |
180 * [new1] -- -- -- -- -- -- -- -+
181 *
182 * Resize in greater detail:
183 *
184 * a) First, a resizer (a single background system work queue item
185 * in charge of resizing the table) allocates and initializes a new
186 * bucket head array. New bucket heads are pointed to the sentinel
187 * and marked Invalid (in the lower order bits of the pointer to the
188 * next item, ie the sentinel in this case):
189 *
190 * [old, N] --> [00b] -> [01b] -> [10b] -> [11b] -> sentinel
191 * ^ ^
192 * [new0, Inv] -------------------------------------+ |
193 * [new1, Inv] ---------------------------------------+
194 *
195 *
196 * b) Second, the resizer starts moving old bucket heads with the following
197 * lock-free protocol (from [5]) where cas(variable, expected_val, new_val)
198 * is short for compare-and-swap:
199 *
200 * old head new0 head transition to next state
201 * -------- --------- ------------------------
202 * addr, N sentinel, Inv cas(old, (addr, N), (addr, Const))
203 * .. mark the old head as immutable, so that
204 * updaters do not relink it to other nodes
205 * until the head move is done.
206 * addr, Const sentinel, Inv cas(new0, (sentinel, Inv), (addr, N))
207 * .. move the address to the new head and mark
208 * the new head normal so updaters can start
209 * using it.
210 * addr, Const addr, N cas(old, (addr, Const), (addr, Inv))
211 * .. mark the old head Invalid to signify
212 * the head move is done.
213 * addr, Inv addr, N
214 *
215 * Notice that concurrent updaters may step in at any point and correctly
216 * complete the head move without disrupting the resizer. At worst, the
217 * resizer or other concurrent updaters will attempt a number of CAS() that
218 * will correctly fail.
219 *
220 * [old, Inv] -> [00b] -> [01b] -> [10b] -> [11b] -> sentinel
221 * ^ ^
222 * [new0, N] ----+ |
223 * [new1, Inv] --------------------------------------+
224 *
225 *
226 * c) Third, buckets are split if the table is growing; or joined if
227 * shrinking (by the resizer or updaters depending on whoever accesses
228 * the bucket first). See split_bucket() and join_buckets() for details.
229 *
230 * 1) Mark the last item of new0 with JOIN_FOLLOWS:
231 * [old, Inv] -> [00b] -> [01b, JF] -> [10b] -> [11b] -> sentinel
232 * ^ ^
233 * [new0, N] ----+ |
234 * [new1, Inv] ------------------------------------------+
235 *
236 * 2) Mark the first item of new1 with JOIN_NODE:
237 * [old, Inv] -> [00b] -> [01b, JF] -> [10b, JN] -> [11b] -> sentinel
238 * ^ ^
239 * [new0, N] ----+ |
240 * [new1, Inv] ----------------------------------------------+
241 *
242 * 3) Point new1 to the join-node and mark new1 NORMAL.
243 * [old, Inv] -> [00b] -> [01b, JF] -> [10b, JN] -> [11b] -> sentinel
244 * ^ ^
245 * [new0, N] ----+ |
246 * [new1, N] --------------------------+
247 *
248 *
249 * d) Fourth, the resizer cleans up extra marks added during bucket
250 * splits/joins but only when it is sure all updaters are accessing
251 * the table via the new bucket heads only (ie it is certain there
252 * are no delayed updaters unaware of the resize and accessing the
253 * table via the old bucket head).
254 *
255 * [old, Inv] ---+
256 * v
257 * [new0, N] --> [00b] -> [01b, N] ---+
258 * v
259 * [new1, N] --> [10b, N] -> [11b] -> sentinel
260 *
261 *
262 * e) Last, the resizer publishes the new bucket head array for everyone
263 * to see and use. This signals the end of the resize and the old bucket
264 * array is freed.
265 *
266 *
267 * To understand details of how the table is resized, read [1, 3, 5]
268 * and comments in join_buckets(), split_bucket().
269 *
270 *
271 * [1] High performance dynamic lock-free hash tables and list-based sets,
272 * Michael, 2002
273 * http://www.research.ibm.com/people/m/michael/spaa-2002.pdf
274 * [2] Lock-free linked lists using compare-and-swap,
275 * Valois, 1995
276 * http://people.csail.mit.edu/bushl2/rpi/portfolio/lockfree-grape/documents/lock-free-linked-lists.pdf
277 * [3] Resizable, scalable, concurrent hash tables via relativistic programming,
278 * Triplett, 2011
279 * http://www.usenix.org/event/atc11/tech/final_files/Triplett.pdf
280 * [4] Split-ordered Lists: Lock-free Extensible Hash Tables,
281 * Shavit, 2006
282 * http://www.cs.ucf.edu/~dcm/Teaching/COT4810-Spring2011/Literature/SplitOrderedLists.pdf
283 * [5] Towards a Scalable Non-blocking Coding Style,
284 * Click, 2008
285 * http://www.azulsystems.com/events/javaone_2008/2008_CodingNonBlock.pdf
286 */
287
288#include <adt/cht.h>
289#include <adt/hash.h>
290#include <assert.h>
291#include <mm/slab.h>
292#include <barrier.h>
293#include <barrier.h>
294#include <atomic.h>
295#include <synch/rcu.h>
296
297/* Logarithm of the min bucket count. Must be at least 3. 2^6 == 64 buckets. */
298#define CHT_MIN_ORDER 6
299/* Logarithm of the max bucket count. */
300#define CHT_MAX_ORDER (8 * sizeof(size_t))
301/* Minimum number of hash table buckets. */
302#define CHT_MIN_BUCKET_CNT (1 << CHT_MIN_ORDER)
303/* Does not have to be a power of 2. */
304#define CHT_MAX_LOAD 2
305
306typedef cht_ptr_t marked_ptr_t;
307typedef bool (*equal_pred_t)(void *arg, const cht_link_t *item);
308
309/** The following mark items and bucket heads.
310 *
311 * They are stored in the two low order bits of the next item pointers.
312 * Some marks may be combined. Some marks share the same binary value and
313 * are distinguished only by context (eg bucket head vs an ordinary item),
314 * in particular by walk_mode_t.
315 */
316typedef enum mark {
317 /** Normal non-deleted item or a valid bucket head. */
318 N_NORMAL = 0,
319 /** Logically deleted item that might have already been unlinked.
320 *
321 * May be combined with N_JOIN and N_JOIN_FOLLOWS. Applicable only
322 * to items; never to bucket heads.
323 *
324 * Once marked deleted an item remains marked deleted.
325 */
326 N_DELETED = 1,
327 /** Immutable bucket head.
328 *
329 * The bucket is being moved or joined with another and its (old) head
330 * must not be modified.
331 *
332 * May be combined with N_INVALID. Applicable only to old bucket heads,
333 * ie cht_t.b and not cht_t.new_b.
334 */
335 N_CONST = 1,
336 /** Invalid bucket head. The bucket head must not be modified.
337 *
338 * Old bucket heads (ie cht_t.b) are marked invalid if they have
339 * already been moved to cht_t.new_b or if the bucket had already
340 * been merged with another when shrinking the table. New bucket
341 * heads (ie cht_t.new_b) are marked invalid if the old bucket had
342 * not yet been moved or if an old bucket had not yet been split
343 * when growing the table.
344 */
345 N_INVALID = 3,
346 /** The item is a join node, ie joining two buckets
347 *
348 * A join node is either the first node of the second part of
349 * a bucket to be split; or it is the first node of the bucket
350 * to be merged into/appended to/joined with another bucket.
351 *
352 * May be combined with N_DELETED. Applicable only to items, never
353 * to bucket heads.
354 *
355 * Join nodes are referred to from two different buckets and may,
356 * therefore, not be safely/atomically unlinked from both buckets.
357 * As a result join nodes are not unlinked but rather just marked
358 * deleted. Once resize completes join nodes marked deleted are
359 * garbage collected.
360 */
361 N_JOIN = 2,
362 /** The next node is a join node and will soon be marked so.
363 *
364 * A join-follows node is the last node of the first part of bucket
365 * that is to be split, ie it is the last node that will remain
366 * in the same bucket after splitting it.
367 *
368 * May be combined with N_DELETED. Applicable to items as well
369 * as to bucket heads of the bucket to be split (but only in cht_t.new_b).
370 */
371 N_JOIN_FOLLOWS = 2,
372 /** Bit mask to filter out the address to the next item from the next ptr. */
373 N_MARK_MASK = 3
374} mark_t;
375
376/** Determines */
377typedef enum walk_mode {
378 /** The table is not resizing. */
379 WM_NORMAL = 4,
380 /** The table is undergoing a resize. Join nodes may be encountered. */
381 WM_LEAVE_JOIN,
382 /** The table is growing. A join-follows node may be encountered. */
383 WM_MOVE_JOIN_FOLLOWS
384} walk_mode_t;
385
386/** Bucket position window. */
387typedef struct wnd {
388 /** Pointer to cur's predecessor. */
389 marked_ptr_t *ppred;
390 /** Current item. */
391 cht_link_t *cur;
392 /** Last encountered item. Deleted or not. */
393 cht_link_t *last;
394} wnd_t;
395
396/* Sentinel node used by all buckets. Stores the greatest possible hash value.*/
397static const cht_link_t sentinel = {
398 /* NULL and N_NORMAL */
399 .link = 0 | N_NORMAL,
400 .hash = -1
401};
402
403static size_t size_to_order(size_t bucket_cnt, size_t min_order);
404static cht_buckets_t *alloc_buckets(size_t order, bool set_invalid,
405 bool can_block);
406static inline cht_link_t *find_lazy(cht_t *h, void *key);
407static cht_link_t *search_bucket(cht_t *h, marked_ptr_t head, void *key,
408 size_t search_hash);
409static cht_link_t *find_resizing(cht_t *h, void *key, size_t hash,
410 marked_ptr_t old_head, size_t old_idx);
411static bool insert_impl(cht_t *h, cht_link_t *item, cht_link_t **dup_item);
412static bool insert_at(cht_link_t *item, const wnd_t *wnd, walk_mode_t walk_mode,
413 bool *resizing);
414static bool has_duplicate(cht_t *h, const cht_link_t *item, size_t hash,
415 cht_link_t *cur, cht_link_t **dup_item);
416static cht_link_t *find_duplicate(cht_t *h, const cht_link_t *item, size_t hash,
417 cht_link_t *start);
418static bool remove_pred(cht_t *h, size_t hash, equal_pred_t pred, void *pred_arg);
419static bool delete_at(cht_t *h, wnd_t *wnd, walk_mode_t walk_mode,
420 bool *deleted_but_gc, bool *resizing);
421static bool mark_deleted(cht_link_t *cur, walk_mode_t walk_mode, bool *resizing);
422static bool unlink_from_pred(wnd_t *wnd, walk_mode_t walk_mode, bool *resizing);
423static bool find_wnd_and_gc_pred(cht_t *h, size_t hash, walk_mode_t walk_mode,
424 equal_pred_t pred, void *pred_arg, wnd_t *wnd, bool *resizing);
425static bool find_wnd_and_gc(cht_t *h, size_t hash, walk_mode_t walk_mode,
426 wnd_t *wnd, bool *resizing);
427static bool gc_deleted_node(cht_t *h, walk_mode_t walk_mode, wnd_t *wnd,
428 bool *resizing);
429static bool join_completed(cht_t *h, const wnd_t *wnd);
430static void upd_resizing_head(cht_t *h, size_t hash, marked_ptr_t **phead,
431 bool *join_finishing, walk_mode_t *walk_mode);
432static void item_removed(cht_t *h);
433static void item_inserted(cht_t *h);
434static void free_later(cht_t *h, cht_link_t *item);
435static void help_head_move(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head);
436static void start_head_move(marked_ptr_t *psrc_head);
437static void mark_const(marked_ptr_t *psrc_head);
438static void complete_head_move(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head);
439static void split_bucket(cht_t *h, marked_ptr_t *psrc_head,
440 marked_ptr_t *pdest_head, size_t split_hash);
441static void mark_join_follows(cht_t *h, marked_ptr_t *psrc_head,
442 size_t split_hash, wnd_t *wnd);
443static void mark_join_node(cht_link_t *join_node);
444static void join_buckets(cht_t *h, marked_ptr_t *psrc_head,
445 marked_ptr_t *pdest_head, size_t split_hash);
446static void link_to_join_node(cht_t *h, marked_ptr_t *pdest_head,
447 cht_link_t *join_node, size_t split_hash);
448static void resize_table(work_t *arg);
449static void grow_table(cht_t *h);
450static void shrink_table(cht_t *h);
451static void cleanup_join_node(cht_t *h, marked_ptr_t *new_head);
452static void clear_join_and_gc(cht_t *h, cht_link_t *join_node,
453 marked_ptr_t *new_head);
454static void cleanup_join_follows(cht_t *h, marked_ptr_t *new_head);
455static marked_ptr_t make_link(const cht_link_t *next, mark_t mark);
456static cht_link_t *get_next(marked_ptr_t link);
457static mark_t get_mark(marked_ptr_t link);
458static void next_wnd(wnd_t *wnd);
459static bool same_node_pred(void *node, const cht_link_t *item2);
460static size_t calc_key_hash(cht_t *h, void *key);
461static size_t node_hash(cht_t *h, const cht_link_t *item);
462static size_t calc_node_hash(cht_t *h, const cht_link_t *item);
463static void memoize_node_hash(cht_t *h, cht_link_t *item);
464static size_t calc_split_hash(size_t split_idx, size_t order);
465static size_t calc_bucket_idx(size_t hash, size_t order);
466static size_t grow_to_split_idx(size_t old_idx);
467static size_t grow_idx(size_t idx);
468static size_t shrink_idx(size_t idx);
469static marked_ptr_t cas_link(marked_ptr_t *link, const cht_link_t *cur_next,
470 mark_t cur_mark, const cht_link_t *new_next, mark_t new_mark);
471static marked_ptr_t _cas_link(marked_ptr_t *link, marked_ptr_t cur,
472 marked_ptr_t new);
473static void cas_order_barrier(void);
474
475static void dummy_remove_callback(cht_link_t *item)
476{
477 /* empty */
478}
479
480/** Creates a concurrent hash table.
481 *
482 * @param h Valid pointer to a cht_t instance.
483 * @param op Item specific operations. All operations are compulsory.
484 * @return True if successfully created the table. False otherwise.
485 */
486bool cht_create_simple(cht_t *h, cht_ops_t *op)
487{
488 return cht_create(h, 0, 0, 0, false, op);
489}
490
491/** Creates a concurrent hash table.
492 *
493 * @param h Valid pointer to a cht_t instance.
494 * @param init_size The initial number of buckets the table should contain.
495 * The table may be shrunk below this value if deemed necessary.
496 * Uses the default value if 0.
497 * @param min_size Minimum number of buckets that the table should contain.
498 * The number of buckets never drops below this value,
499 * although it may be rounded up internally as appropriate.
500 * Uses the default value if 0.
501 * @param max_load Maximum average number of items per bucket that allowed
502 * before the table grows.
503 * @param can_block If true creating the table blocks until enough memory
504 * is available (possibly indefinitely). Otherwise,
505 * table creation does not block and returns immediately
506 * even if not enough memory is available.
507 * @param op Item specific operations. All operations are compulsory.
508 * @return True if successfully created the table. False otherwise.
509 */
510bool cht_create(cht_t *h, size_t init_size, size_t min_size, size_t max_load,
511 bool can_block, cht_ops_t *op)
512{
513 assert(h);
514 assert(op && op->hash && op->key_hash && op->equal && op->key_equal);
515 /* Memoized hashes are stored in the rcu_link.func function pointer. */
516 static_assert(sizeof(size_t) == sizeof(rcu_func_t), "");
517 assert(sentinel.hash == (uintptr_t)sentinel.rcu_link.func);
518
519 /* All operations are compulsory. */
520 if (!op || !op->hash || !op->key_hash || !op->equal || !op->key_equal)
521 return false;
522
523 size_t min_order = size_to_order(min_size, CHT_MIN_ORDER);
524 size_t order = size_to_order(init_size, min_order);
525
526 h->b = alloc_buckets(order, false, can_block);
527
528 if (!h->b)
529 return false;
530
531 h->max_load = (max_load == 0) ? CHT_MAX_LOAD : max_load;
532 h->min_order = min_order;
533 h->new_b = NULL;
534 h->op = op;
535 atomic_store(&h->item_cnt, 0);
536 atomic_store(&h->resize_reqs, 0);
537
538 if (NULL == op->remove_callback) {
539 h->op->remove_callback = dummy_remove_callback;
540 }
541
542 /*
543 * Cached item hashes are stored in item->rcu_link.func. Once the item
544 * is deleted rcu_link.func will contain the value of invalid_hash.
545 */
546 h->invalid_hash = (uintptr_t)h->op->remove_callback;
547
548 /* Ensure the initialization takes place before we start using the table. */
549 write_barrier();
550
551 return true;
552}
553
554/** Allocates and initializes 2^order buckets.
555 *
556 * All bucket heads are initialized to point to the sentinel node.
557 *
558 * @param order The number of buckets to allocate is 2^order.
559 * @param set_invalid Bucket heads are marked invalid if true; otherwise
560 * they are marked N_NORMAL.
561 * @param can_block If true memory allocation blocks until enough memory
562 * is available (possibly indefinitely). Otherwise,
563 * memory allocation does not block.
564 * @return Newly allocated and initialized buckets or NULL if not enough memory.
565 */
566static cht_buckets_t *alloc_buckets(size_t order, bool set_invalid, bool can_block)
567{
568 size_t bucket_cnt = (1 << order);
569 size_t bytes =
570 sizeof(cht_buckets_t) + (bucket_cnt - 1) * sizeof(marked_ptr_t);
571 cht_buckets_t *b = can_block ? nfmalloc(bytes) : malloc(bytes);
572
573 if (!b)
574 return NULL;
575
576 b->order = order;
577
578 marked_ptr_t head_link = set_invalid ?
579 make_link(&sentinel, N_INVALID) :
580 make_link(&sentinel, N_NORMAL);
581
582 for (size_t i = 0; i < bucket_cnt; ++i) {
583 b->head[i] = head_link;
584 }
585
586 return b;
587}
588
589/** Returns the smallest k such that bucket_cnt <= 2^k and min_order <= k.*/
590static size_t size_to_order(size_t bucket_cnt, size_t min_order)
591{
592 size_t order = min_order;
593
594 /* Find a power of two such that bucket_cnt <= 2^order */
595 do {
596 if (bucket_cnt <= ((size_t)1 << order))
597 return order;
598
599 ++order;
600 } while (order < CHT_MAX_ORDER);
601
602 return order;
603}
604
605/** Destroys a CHT successfully created via cht_create().
606 *
607 * Waits for all outstanding concurrent operations to complete and
608 * frees internal allocated resources. The table is however not cleared
609 * and items already present in the table (if any) are leaked.
610 */
611void cht_destroy(cht_t *h)
612{
613 cht_destroy_unsafe(h);
614
615 /* You must clear the table of items. Otherwise cht_destroy will leak. */
616 assert(atomic_load(&h->item_cnt) == 0);
617}
618
619/** Destroys a successfully created CHT but does no error checking. */
620void cht_destroy_unsafe(cht_t *h)
621{
622 /* Wait for resize to complete. */
623 while (0 < atomic_load(&h->resize_reqs)) {
624 rcu_barrier();
625 }
626
627 /* Wait for all remove_callback()s to complete. */
628 rcu_barrier();
629
630 free(h->b);
631 h->b = NULL;
632}
633
634/** Returns the first item equal to the search key or NULL if not found.
635 *
636 * The call must be enclosed in a rcu_read_lock() unlock() pair. The
637 * returned item is guaranteed to be allocated until rcu_read_unlock()
638 * although the item may be concurrently removed from the table by another
639 * cpu.
640 *
641 * Further items matching the key may be retrieved via cht_find_next().
642 *
643 * cht_find() sees the effects of any completed cht_remove(), cht_insert().
644 * If a concurrent remove or insert had not yet completed cht_find() may
645 * or may not see the effects of it (eg it may find an item being removed).
646 *
647 * @param h CHT to operate on.
648 * @param key Search key as defined by cht_ops_t.key_equal() and .key_hash().
649 * @return First item equal to the key or NULL if such an item does not exist.
650 */
651cht_link_t *cht_find(cht_t *h, void *key)
652{
653 /* Make the most recent changes to the table visible. */
654 read_barrier();
655 return cht_find_lazy(h, key);
656}
657
658/** Returns the first item equal to the search key or NULL if not found.
659 *
660 * Unlike cht_find(), cht_find_lazy() may not see the effects of
661 * cht_remove() or cht_insert() even though they have already completed.
662 * It may take a couple of milliseconds for those changes to propagate
663 * and become visible to cht_find_lazy(). On the other hand, cht_find_lazy()
664 * operates a bit faster than cht_find().
665 *
666 * See cht_find() for more details.
667 */
668cht_link_t *cht_find_lazy(cht_t *h, void *key)
669{
670 return find_lazy(h, key);
671}
672
673/** Finds the first item equal to the search key. */
674static inline cht_link_t *find_lazy(cht_t *h, void *key)
675{
676 assert(h);
677 /* See docs to cht_find() and cht_find_lazy(). */
678 assert(rcu_read_locked());
679
680 size_t hash = calc_key_hash(h, key);
681
682 cht_buckets_t *b = rcu_access(h->b);
683 size_t idx = calc_bucket_idx(hash, b->order);
684 /*
685 * No need for access_once. b->head[idx] will point to an allocated node
686 * even if marked invalid until we exit rcu read section.
687 */
688 marked_ptr_t head = b->head[idx];
689
690 /* Undergoing a resize - take the slow path. */
691 if (N_INVALID == get_mark(head))
692 return find_resizing(h, key, hash, head, idx);
693
694 return search_bucket(h, head, key, hash);
695}
696
697/** Returns the next item matching \a item.
698 *
699 * Must be enclosed in a rcu_read_lock()/unlock() pair. Effects of
700 * completed cht_remove(), cht_insert() are guaranteed to be visible
701 * to cht_find_next().
702 *
703 * See cht_find() for more details.
704 */
705cht_link_t *cht_find_next(cht_t *h, const cht_link_t *item)
706{
707 /* Make the most recent changes to the table visible. */
708 read_barrier();
709 return cht_find_next_lazy(h, item);
710}
711
712/** Returns the next item matching \a item.
713 *
714 * Must be enclosed in a rcu_read_lock()/unlock() pair. Effects of
715 * completed cht_remove(), cht_insert() may or may not be visible
716 * to cht_find_next_lazy().
717 *
718 * See cht_find_lazy() for more details.
719 */
720cht_link_t *cht_find_next_lazy(cht_t *h, const cht_link_t *item)
721{
722 assert(h);
723 assert(rcu_read_locked());
724 assert(item);
725
726 return find_duplicate(h, item, calc_node_hash(h, item), get_next(item->link));
727}
728
729/** Searches the bucket at head for key using search_hash. */
730static inline cht_link_t *search_bucket(cht_t *h, marked_ptr_t head, void *key,
731 size_t search_hash)
732{
733 /*
734 * It is safe to access nodes even outside of this bucket (eg when
735 * splitting the bucket). The resizer makes sure that any node we
736 * may find by following the next pointers is allocated.
737 */
738
739 cht_link_t *cur = NULL;
740 marked_ptr_t prev = head;
741
742try_again:
743 /* Filter out items with different hashes. */
744 do {
745 cur = get_next(prev);
746 assert(cur);
747 prev = cur->link;
748 } while (node_hash(h, cur) < search_hash);
749
750 /*
751 * Only search for an item with an equal key if cur is not the sentinel
752 * node or a node with a different hash.
753 */
754 while (node_hash(h, cur) == search_hash) {
755 if (h->op->key_equal(key, cur)) {
756 if (!(N_DELETED & get_mark(cur->link)))
757 return cur;
758 }
759
760 cur = get_next(cur->link);
761 assert(cur);
762 }
763
764 /*
765 * In the unlikely case that we have encountered a node whose cached
766 * hash has been overwritten due to a pending rcu_call for it, skip
767 * the node and try again.
768 */
769 if (node_hash(h, cur) == h->invalid_hash) {
770 prev = cur->link;
771 goto try_again;
772 }
773
774 return NULL;
775}
776
777/** Searches for the key while the table is undergoing a resize. */
778static cht_link_t *find_resizing(cht_t *h, void *key, size_t hash,
779 marked_ptr_t old_head, size_t old_idx)
780{
781 assert(N_INVALID == get_mark(old_head));
782 assert(h->new_b);
783
784 size_t new_idx = calc_bucket_idx(hash, h->new_b->order);
785 marked_ptr_t new_head = h->new_b->head[new_idx];
786 marked_ptr_t search_head = new_head;
787
788 /* Growing. */
789 if (h->b->order < h->new_b->order) {
790 /*
791 * Old bucket head is invalid, so it must have been already
792 * moved. Make the new head visible if still not visible, ie
793 * invalid.
794 */
795 if (N_INVALID == get_mark(new_head)) {
796 /*
797 * We should be searching a newly added bucket but the old
798 * moved bucket has not yet been split (its marked invalid)
799 * or we have not yet seen the split.
800 */
801 if (grow_idx(old_idx) != new_idx) {
802 /*
803 * Search the moved bucket. It is guaranteed to contain
804 * items of the newly added bucket that were present
805 * before the moved bucket was split.
806 */
807 new_head = h->new_b->head[grow_idx(old_idx)];
808 }
809
810 /* new_head is now the moved bucket, either valid or invalid. */
811
812 /*
813 * The old bucket was definitely moved to new_head but the
814 * change of new_head had not yet propagated to this cpu.
815 */
816 if (N_INVALID == get_mark(new_head)) {
817 /*
818 * We could issue a read_barrier() and make the now valid
819 * moved bucket head new_head visible, but instead fall back
820 * on using the old bucket. Although the old bucket head is
821 * invalid, it points to a node that is allocated and in the
822 * right bucket. Before the node can be freed, it must be
823 * unlinked from the head (or another item after that item
824 * modified the new_head) and a grace period must elapse.
825 * As a result had the node been already freed the grace
826 * period preceeding the free() would make the unlink and
827 * any changes to new_head visible. Therefore, it is safe
828 * to use the node pointed to from the old bucket head.
829 */
830
831 search_head = old_head;
832 } else {
833 search_head = new_head;
834 }
835 }
836
837 return search_bucket(h, search_head, key, hash);
838 } else if (h->b->order > h->new_b->order) {
839 /* Shrinking. */
840
841 /* Index of the bucket in the old table that was moved. */
842 size_t move_src_idx = grow_idx(new_idx);
843 marked_ptr_t moved_old_head = h->b->head[move_src_idx];
844
845 /*
846 * h->b->head[move_src_idx] had already been moved to new_head
847 * but the change to new_head had not yet propagated to us.
848 */
849 if (N_INVALID == get_mark(new_head)) {
850 /*
851 * new_head is definitely valid and we could make it visible
852 * to this cpu with a read_barrier(). Instead, use the bucket
853 * in the old table that was moved even though it is now marked
854 * as invalid. The node it points to must be allocated because
855 * a grace period would have to elapse before it could be freed;
856 * and the grace period would make the now valid new_head
857 * visible to all cpus.
858 *
859 * Note that move_src_idx may not be the same as old_idx.
860 * If move_src_idx != old_idx then old_idx is the bucket
861 * in the old table that is not moved but instead it is
862 * appended to the moved bucket, ie it is added at the tail
863 * of new_head. In that case an invalid old_head notes that
864 * it had already been merged into (the moved) new_head.
865 * We will try to search that bucket first because it
866 * may contain some newly added nodes after the bucket
867 * join. Moreover, the bucket joining link may already be
868 * visible even if new_head is not. Therefore, if we're
869 * lucky we'll find the item via moved_old_head. In any
870 * case, we'll retry in proper old_head if not found.
871 */
872 search_head = moved_old_head;
873 }
874
875 cht_link_t *ret = search_bucket(h, search_head, key, hash);
876
877 if (ret)
878 return ret;
879 /*
880 * Bucket old_head was already joined with moved_old_head
881 * in the new table but we have not yet seen change of the
882 * joining link (or the item is not in the table).
883 */
884 if (move_src_idx != old_idx && get_next(old_head) != &sentinel) {
885 /*
886 * Note that old_head (the bucket to be merged into new_head)
887 * points to an allocated join node (if non-null) even if marked
888 * invalid. Before the resizer lets join nodes to be unlinked
889 * (and freed) it sets old_head to NULL and waits for a grace period.
890 * So either the invalid old_head points to join node; or old_head
891 * is null and we would have seen a completed bucket join while
892 * traversing search_head.
893 */
894 assert(N_JOIN & get_mark(get_next(old_head)->link));
895 return search_bucket(h, old_head, key, hash);
896 }
897
898 return NULL;
899 } else {
900 /*
901 * Resize is almost done. The resizer is waiting to make
902 * sure all cpus see that the new table replaced the old one.
903 */
904 assert(h->b->order == h->new_b->order);
905 /*
906 * The resizer must ensure all new bucket heads are visible before
907 * replacing the old table.
908 */
909 assert(N_NORMAL == get_mark(new_head));
910 return search_bucket(h, new_head, key, hash);
911 }
912}
913
914/** Inserts an item. Succeeds even if an equal item is already present. */
915void cht_insert(cht_t *h, cht_link_t *item)
916{
917 insert_impl(h, item, NULL);
918}
919
920/** Inserts a unique item. Returns false if an equal item was already present.
921 *
922 * Use this function to atomically check if an equal/duplicate item had
923 * not yet been inserted into the table and to insert this item into the
924 * table.
925 *
926 * The following is @e NOT thread-safe, so do not use:
927 * @code
928 * if (!cht_find(h, key)) {
929 * // A concurrent insert here may go unnoticed by cht_find() above.
930 * item = malloc(..);
931 * cht_insert(h, item);
932 * // Now we may have two items with equal search keys.
933 * }
934 * @endcode
935 *
936 * Replace such code with:
937 * @code
938 * item = malloc(..);
939 * if (!cht_insert_unique(h, item, &dup_item)) {
940 * // Whoops, someone beat us to it - an equal item 'dup_item'
941 * // had already been inserted.
942 * free(item);
943 * } else {
944 * // Successfully inserted the item and we are guaranteed that
945 * // there are no other equal items.
946 * }
947 * @endcode
948 *
949 */
950bool cht_insert_unique(cht_t *h, cht_link_t *item, cht_link_t **dup_item)
951{
952 assert(rcu_read_locked());
953 assert(dup_item);
954 return insert_impl(h, item, dup_item);
955}
956
957/** Inserts the item into the table and checks for duplicates if dup_item. */
958static bool insert_impl(cht_t *h, cht_link_t *item, cht_link_t **dup_item)
959{
960 rcu_read_lock();
961
962 cht_buckets_t *b = rcu_access(h->b);
963 memoize_node_hash(h, item);
964 size_t hash = node_hash(h, item);
965 size_t idx = calc_bucket_idx(hash, b->order);
966 marked_ptr_t *phead = &b->head[idx];
967
968 bool resizing = false;
969 bool inserted = false;
970
971 do {
972 walk_mode_t walk_mode = WM_NORMAL;
973 bool join_finishing;
974
975 resizing = resizing || (N_NORMAL != get_mark(*phead));
976
977 /* The table is resizing. Get the correct bucket head. */
978 if (resizing) {
979 upd_resizing_head(h, hash, &phead, &join_finishing, &walk_mode);
980 }
981
982 wnd_t wnd = {
983 .ppred = phead,
984 .cur = get_next(*phead),
985 .last = NULL
986 };
987
988 if (!find_wnd_and_gc(h, hash, walk_mode, &wnd, &resizing)) {
989 /* Could not GC a node; or detected an unexpected resize. */
990 continue;
991 }
992
993 if (dup_item && has_duplicate(h, item, hash, wnd.cur, dup_item)) {
994 rcu_read_unlock();
995 return false;
996 }
997
998 inserted = insert_at(item, &wnd, walk_mode, &resizing);
999 } while (!inserted);
1000
1001 rcu_read_unlock();
1002
1003 item_inserted(h);
1004 return true;
1005}
1006
1007/** Inserts item between wnd.ppred and wnd.cur.
1008 *
1009 * @param item Item to link to wnd.ppred and wnd.cur.
1010 * @param wnd The item will be inserted before wnd.cur. Wnd.ppred
1011 * must be N_NORMAL.
1012 * @param walk_mode
1013 * @param resizing Set to true only if the table is undergoing resize
1014 * and it was not expected (ie walk_mode == WM_NORMAL).
1015 * @return True if the item was successfully linked to wnd.ppred. False
1016 * if whole insert operation must be retried because the predecessor
1017 * of wnd.cur has changed.
1018 */
1019inline static bool insert_at(cht_link_t *item, const wnd_t *wnd,
1020 walk_mode_t walk_mode, bool *resizing)
1021{
1022 marked_ptr_t ret;
1023
1024 if (walk_mode == WM_NORMAL) {
1025 item->link = make_link(wnd->cur, N_NORMAL);
1026 /* Initialize the item before adding it to a bucket. */
1027 memory_barrier();
1028
1029 /* Link a clean/normal predecessor to the item. */
1030 ret = cas_link(wnd->ppred, wnd->cur, N_NORMAL, item, N_NORMAL);
1031
1032 if (ret == make_link(wnd->cur, N_NORMAL)) {
1033 return true;
1034 } else {
1035 /* This includes an invalid head but not a const head. */
1036 *resizing = ((N_JOIN_FOLLOWS | N_JOIN) & get_mark(ret));
1037 return false;
1038 }
1039 } else if (walk_mode == WM_MOVE_JOIN_FOLLOWS) {
1040 /* Move JOIN_FOLLOWS mark but filter out the DELETED mark. */
1041 mark_t jf_mark = get_mark(*wnd->ppred) & N_JOIN_FOLLOWS;
1042 item->link = make_link(wnd->cur, jf_mark);
1043 /* Initialize the item before adding it to a bucket. */
1044 memory_barrier();
1045
1046 /* Link the not-deleted predecessor to the item. Move its JF mark. */
1047 ret = cas_link(wnd->ppred, wnd->cur, jf_mark, item, N_NORMAL);
1048
1049 return ret == make_link(wnd->cur, jf_mark);
1050 } else {
1051 assert(walk_mode == WM_LEAVE_JOIN);
1052
1053 item->link = make_link(wnd->cur, N_NORMAL);
1054 /* Initialize the item before adding it to a bucket. */
1055 memory_barrier();
1056
1057 mark_t pred_mark = get_mark(*wnd->ppred);
1058 /* If the predecessor is a join node it may be marked deleted.*/
1059 mark_t exp_pred_mark = (N_JOIN & pred_mark) ? pred_mark : N_NORMAL;
1060
1061 ret = cas_link(wnd->ppred, wnd->cur, exp_pred_mark, item, exp_pred_mark);
1062 return ret == make_link(wnd->cur, exp_pred_mark);
1063 }
1064}
1065
1066/** Returns true if the chain starting at cur has an item equal to \a item.
1067 *
1068 * @param h CHT to operate on.
1069 * @param item Item whose duplicates the function looks for.
1070 * @param hash Hash of \a item.
1071 * @param[in] cur The first node with a hash greater to or equal to item's hash.
1072 * @param[out] dup_item The first duplicate item encountered.
1073 * @return True if a non-deleted item equal to \a item exists in the table.
1074 */
1075static inline bool has_duplicate(cht_t *h, const cht_link_t *item, size_t hash,
1076 cht_link_t *cur, cht_link_t **dup_item)
1077{
1078 assert(cur);
1079 assert(cur == &sentinel || hash <= node_hash(h, cur) ||
1080 node_hash(h, cur) == h->invalid_hash);
1081
1082 /* hash < node_hash(h, cur) */
1083 if (hash != node_hash(h, cur) && h->invalid_hash != node_hash(h, cur))
1084 return false;
1085
1086 /*
1087 * Load the most recent node marks. Otherwise we might pronounce a
1088 * logically deleted node for a duplicate of the item just because
1089 * the deleted node's DEL mark had not yet propagated to this cpu.
1090 */
1091 read_barrier();
1092
1093 *dup_item = find_duplicate(h, item, hash, cur);
1094 return NULL != *dup_item;
1095}
1096
1097/** Returns an item that is equal to \a item starting in a chain at \a start. */
1098static cht_link_t *find_duplicate(cht_t *h, const cht_link_t *item, size_t hash,
1099 cht_link_t *start)
1100{
1101 assert(hash <= node_hash(h, start) || h->invalid_hash == node_hash(h, start));
1102
1103 cht_link_t *cur = start;
1104
1105try_again:
1106 assert(cur);
1107
1108 while (node_hash(h, cur) == hash) {
1109 assert(cur != &sentinel);
1110
1111 bool deleted = (N_DELETED & get_mark(cur->link));
1112
1113 /* Skip logically deleted nodes. */
1114 if (!deleted && h->op->equal(item, cur))
1115 return cur;
1116
1117 cur = get_next(cur->link);
1118 assert(cur);
1119 }
1120
1121 /* Skip logically deleted nodes with rcu_call() in progress. */
1122 if (h->invalid_hash == node_hash(h, cur)) {
1123 cur = get_next(cur->link);
1124 goto try_again;
1125 }
1126
1127 return NULL;
1128}
1129
1130/** Removes all items matching the search key. Returns the number of items removed.*/
1131size_t cht_remove_key(cht_t *h, void *key)
1132{
1133 assert(h);
1134
1135 size_t hash = calc_key_hash(h, key);
1136 size_t removed = 0;
1137
1138 while (remove_pred(h, hash, h->op->key_equal, key))
1139 ++removed;
1140
1141 return removed;
1142}
1143
1144/** Removes a specific item from the table.
1145 *
1146 * The called must hold rcu read lock.
1147 *
1148 * @param item Item presumably present in the table and to be removed.
1149 * @return True if the item was removed successfully; or false if it had
1150 * already been deleted.
1151 */
1152bool cht_remove_item(cht_t *h, cht_link_t *item)
1153{
1154 assert(h);
1155 assert(item);
1156 /* Otherwise a concurrent cht_remove_key might free the item. */
1157 assert(rcu_read_locked());
1158
1159 /*
1160 * Even though we know the node we want to delete we must unlink it
1161 * from the correct bucket and from a clean/normal predecessor. Therefore,
1162 * we search for it again from the beginning of the correct bucket.
1163 */
1164 size_t hash = calc_node_hash(h, item);
1165 return remove_pred(h, hash, same_node_pred, item);
1166}
1167
1168/** Removes an item equal to pred_arg according to the predicate pred. */
1169static bool remove_pred(cht_t *h, size_t hash, equal_pred_t pred, void *pred_arg)
1170{
1171 rcu_read_lock();
1172
1173 bool resizing = false;
1174 bool deleted = false;
1175 bool deleted_but_gc = false;
1176
1177 cht_buckets_t *b = rcu_access(h->b);
1178 size_t idx = calc_bucket_idx(hash, b->order);
1179 marked_ptr_t *phead = &b->head[idx];
1180
1181 do {
1182 walk_mode_t walk_mode = WM_NORMAL;
1183 bool join_finishing = false;
1184
1185 resizing = resizing || (N_NORMAL != get_mark(*phead));
1186
1187 /* The table is resizing. Get the correct bucket head. */
1188 if (resizing) {
1189 upd_resizing_head(h, hash, &phead, &join_finishing, &walk_mode);
1190 }
1191
1192 wnd_t wnd = {
1193 .ppred = phead,
1194 .cur = get_next(*phead),
1195 .last = NULL
1196 };
1197
1198 if (!find_wnd_and_gc_pred(
1199 h, hash, walk_mode, pred, pred_arg, &wnd, &resizing)) {
1200 /* Could not GC a node; or detected an unexpected resize. */
1201 continue;
1202 }
1203
1204 /*
1205 * The item lookup is affected by a bucket join but effects of
1206 * the bucket join have not been seen while searching for the item.
1207 */
1208 if (join_finishing && !join_completed(h, &wnd)) {
1209 /*
1210 * Bucket was appended at the end of another but the next
1211 * ptr linking them together was not visible on this cpu.
1212 * join_completed() makes this appended bucket visible.
1213 */
1214 continue;
1215 }
1216
1217 /* Already deleted, but delete_at() requested one GC pass. */
1218 if (deleted_but_gc)
1219 break;
1220
1221 bool found = (wnd.cur != &sentinel && pred(pred_arg, wnd.cur));
1222
1223 if (!found) {
1224 rcu_read_unlock();
1225 return false;
1226 }
1227
1228 deleted = delete_at(h, &wnd, walk_mode, &deleted_but_gc, &resizing);
1229 } while (!deleted || deleted_but_gc);
1230
1231 rcu_read_unlock();
1232 return true;
1233}
1234
1235/** Unlinks wnd.cur from wnd.ppred and schedules a deferred free for the item.
1236 *
1237 * Ignores nodes marked N_JOIN if walk mode is WM_LEAVE_JOIN.
1238 *
1239 * @param h CHT to operate on.
1240 * @param wnd Points to the item to delete and its N_NORMAL predecessor.
1241 * @param walk_mode Bucket chaing walk mode.
1242 * @param deleted_but_gc Set to true if the item had been logically deleted,
1243 * but a garbage collecting walk of the bucket is in order for
1244 * it to be fully unlinked.
1245 * @param resizing Set to true if the table is undergoing an unexpected
1246 * resize (ie walk_mode == WM_NORMAL).
1247 * @return False if the wnd.ppred changed in the meantime and the whole
1248 * delete operation must be retried.
1249 */
1250static inline bool delete_at(cht_t *h, wnd_t *wnd, walk_mode_t walk_mode,
1251 bool *deleted_but_gc, bool *resizing)
1252{
1253 assert(wnd->cur && wnd->cur != &sentinel);
1254
1255 *deleted_but_gc = false;
1256
1257 if (!mark_deleted(wnd->cur, walk_mode, resizing)) {
1258 /* Already deleted, or unexpectedly marked as JOIN/JOIN_FOLLOWS. */
1259 return false;
1260 }
1261
1262 /* Marked deleted. Unlink from the bucket. */
1263
1264 /* Never unlink join nodes. */
1265 if (walk_mode == WM_LEAVE_JOIN && (N_JOIN & get_mark(wnd->cur->link)))
1266 return true;
1267
1268 cas_order_barrier();
1269
1270 if (unlink_from_pred(wnd, walk_mode, resizing)) {
1271 free_later(h, wnd->cur);
1272 } else {
1273 *deleted_but_gc = true;
1274 }
1275
1276 return true;
1277}
1278
1279/** Marks cur logically deleted. Returns false to request a retry. */
1280static inline bool mark_deleted(cht_link_t *cur, walk_mode_t walk_mode,
1281 bool *resizing)
1282{
1283 assert(cur && cur != &sentinel);
1284
1285 /*
1286 * Btw, we could loop here if the cas fails but let's not complicate
1287 * things and let's retry from the head of the bucket.
1288 */
1289
1290 cht_link_t *next = get_next(cur->link);
1291
1292 if (walk_mode == WM_NORMAL) {
1293 /* Only mark clean/normal nodes - JF/JN is used only during resize. */
1294 marked_ptr_t ret = cas_link(&cur->link, next, N_NORMAL, next, N_DELETED);
1295
1296 if (ret != make_link(next, N_NORMAL)) {
1297 *resizing = (N_JOIN | N_JOIN_FOLLOWS) & get_mark(ret);
1298 return false;
1299 }
1300 } else {
1301 static_assert(N_JOIN == N_JOIN_FOLLOWS, "");
1302
1303 /* Keep the N_JOIN/N_JOIN_FOLLOWS mark but strip N_DELETED. */
1304 mark_t cur_mark = get_mark(cur->link) & N_JOIN_FOLLOWS;
1305
1306 marked_ptr_t ret =
1307 cas_link(&cur->link, next, cur_mark, next, cur_mark | N_DELETED);
1308
1309 if (ret != make_link(next, cur_mark))
1310 return false;
1311 }
1312
1313 return true;
1314}
1315
1316/** Unlinks wnd.cur from wnd.ppred. Returns false if it should be retried. */
1317static inline bool unlink_from_pred(wnd_t *wnd, walk_mode_t walk_mode,
1318 bool *resizing)
1319{
1320 assert(wnd->cur != &sentinel);
1321 assert(wnd->cur && (N_DELETED & get_mark(wnd->cur->link)));
1322
1323 cht_link_t *next = get_next(wnd->cur->link);
1324
1325 if (walk_mode == WM_LEAVE_JOIN) {
1326 /* Never try to unlink join nodes. */
1327 assert(!(N_JOIN & get_mark(wnd->cur->link)));
1328
1329 mark_t pred_mark = get_mark(*wnd->ppred);
1330 /* Succeed only if the predecessor is clean/normal or a join node. */
1331 mark_t exp_pred_mark = (N_JOIN & pred_mark) ? pred_mark : N_NORMAL;
1332
1333 marked_ptr_t pred_link = make_link(wnd->cur, exp_pred_mark);
1334 marked_ptr_t next_link = make_link(next, exp_pred_mark);
1335
1336 if (pred_link != _cas_link(wnd->ppred, pred_link, next_link))
1337 return false;
1338 } else {
1339 assert(walk_mode == WM_MOVE_JOIN_FOLLOWS || walk_mode == WM_NORMAL);
1340 /* Move the JF mark if set. Clear DEL mark. */
1341 mark_t cur_mark = N_JOIN_FOLLOWS & get_mark(wnd->cur->link);
1342
1343 /* The predecessor must be clean/normal. */
1344 marked_ptr_t pred_link = make_link(wnd->cur, N_NORMAL);
1345 /* Link to cur's successor keeping/copying cur's JF mark. */
1346 marked_ptr_t next_link = make_link(next, cur_mark);
1347
1348 marked_ptr_t ret = _cas_link(wnd->ppred, pred_link, next_link);
1349
1350 if (pred_link != ret) {
1351 /* If we're not resizing the table there are no JF/JN nodes. */
1352 *resizing = (walk_mode == WM_NORMAL) &&
1353 (N_JOIN_FOLLOWS & get_mark(ret));
1354 return false;
1355 }
1356 }
1357
1358 return true;
1359}
1360
1361/** Finds the first non-deleted item equal to \a pred_arg according to \a pred.
1362 *
1363 * The function returns the candidate item in \a wnd. Logically deleted
1364 * nodes are garbage collected so the predecessor will most likely not
1365 * be marked as deleted.
1366 *
1367 * Unlike find_wnd_and_gc(), this function never returns a node that
1368 * is known to have already been marked N_DELETED.
1369 *
1370 * Any logically deleted nodes (ie those marked N_DELETED) are garbage
1371 * collected, ie free in the background via rcu_call (except for join-nodes
1372 * if walk_mode == WM_LEAVE_JOIN).
1373 *
1374 * @param h CHT to operate on.
1375 * @param hash Hash the search for.
1376 * @param walk_mode Bucket chain walk mode.
1377 * @param pred Predicate used to find an item equal to pred_arg.
1378 * @param pred_arg Argument to pass to the equality predicate \a pred.
1379 * @param[in,out] wnd The search starts with wnd.cur. If the desired
1380 * item is found wnd.cur will point to it.
1381 * @param resizing Set to true if the table is resizing but it was not
1382 * expected (ie walk_mode == WM_NORMAL).
1383 * @return False if the operation has to be retried. True otherwise
1384 * (even if an equal item had not been found).
1385 */
1386static bool find_wnd_and_gc_pred(cht_t *h, size_t hash, walk_mode_t walk_mode,
1387 equal_pred_t pred, void *pred_arg, wnd_t *wnd, bool *resizing)
1388{
1389 assert(wnd->cur);
1390
1391 if (wnd->cur == &sentinel)
1392 return true;
1393
1394 /*
1395 * A read barrier is not needed here to bring up the most recent
1396 * node marks (esp the N_DELETED). At worst we'll try to delete
1397 * an already deleted node; fail in delete_at(); and retry.
1398 */
1399
1400 size_t cur_hash;
1401
1402try_again:
1403 cur_hash = node_hash(h, wnd->cur);
1404
1405 while (cur_hash <= hash) {
1406 assert(wnd->cur && wnd->cur != &sentinel);
1407
1408 /* GC any deleted nodes on the way. */
1409 if (N_DELETED & get_mark(wnd->cur->link)) {
1410 if (!gc_deleted_node(h, walk_mode, wnd, resizing)) {
1411 /* Retry from the head of a bucket. */
1412 return false;
1413 }
1414 } else {
1415 /* Is this the node we were looking for? */
1416 if (cur_hash == hash && pred(pred_arg, wnd->cur))
1417 return true;
1418
1419 next_wnd(wnd);
1420 }
1421
1422 cur_hash = node_hash(h, wnd->cur);
1423 }
1424
1425 if (cur_hash == h->invalid_hash) {
1426 next_wnd(wnd);
1427 assert(wnd->cur);
1428 goto try_again;
1429 }
1430
1431 /* The searched for node is not in the current bucket. */
1432 return true;
1433}
1434
1435/** Find the first item (deleted or not) with a hash greater or equal to \a hash.
1436 *
1437 * The function returns the first item with a hash that is greater or
1438 * equal to \a hash in \a wnd. Moreover it garbage collects logically
1439 * deleted node that have not yet been unlinked and freed. Therefore,
1440 * the returned node's predecessor will most likely be N_NORMAL.
1441 *
1442 * Unlike find_wnd_and_gc_pred(), this function may return a node
1443 * that is known to had been marked N_DELETED.
1444 *
1445 * @param h CHT to operate on.
1446 * @param hash Hash of the item to find.
1447 * @param walk_mode Bucket chain walk mode.
1448 * @param[in,out] wnd wnd.cur denotes the first node of the chain. If the
1449 * the operation is successful, \a wnd points to the desired
1450 * item.
1451 * @param resizing Set to true if a table resize was detected but walk_mode
1452 * suggested the table was not undergoing a resize.
1453 * @return False indicates the operation must be retried. True otherwise
1454 * (even if an item with exactly the same has was not found).
1455 */
1456static bool find_wnd_and_gc(cht_t *h, size_t hash, walk_mode_t walk_mode,
1457 wnd_t *wnd, bool *resizing)
1458{
1459try_again:
1460 assert(wnd->cur);
1461
1462 while (node_hash(h, wnd->cur) < hash) {
1463 /* GC any deleted nodes along the way to our desired node. */
1464 if (N_DELETED & get_mark(wnd->cur->link)) {
1465 if (!gc_deleted_node(h, walk_mode, wnd, resizing)) {
1466 /* Failed to remove the garbage node. Retry. */
1467 return false;
1468 }
1469 } else {
1470 next_wnd(wnd);
1471 }
1472
1473 assert(wnd->cur);
1474 }
1475
1476 if (node_hash(h, wnd->cur) == h->invalid_hash) {
1477 next_wnd(wnd);
1478 goto try_again;
1479 }
1480
1481 /* wnd->cur may be NULL or even marked N_DELETED. */
1482 return true;
1483}
1484
1485/** Garbage collects the N_DELETED node at \a wnd skipping join nodes. */
1486static bool gc_deleted_node(cht_t *h, walk_mode_t walk_mode, wnd_t *wnd,
1487 bool *resizing)
1488{
1489 assert(N_DELETED & get_mark(wnd->cur->link));
1490
1491 /* Skip deleted JOIN nodes. */
1492 if (walk_mode == WM_LEAVE_JOIN && (N_JOIN & get_mark(wnd->cur->link))) {
1493 next_wnd(wnd);
1494 } else {
1495 /* Ordinary deleted node or a deleted JOIN_FOLLOWS. */
1496 assert(walk_mode != WM_LEAVE_JOIN ||
1497 !((N_JOIN | N_JOIN_FOLLOWS) & get_mark(wnd->cur->link)));
1498
1499 /* Unlink an ordinary deleted node, move JOIN_FOLLOWS mark. */
1500 if (!unlink_from_pred(wnd, walk_mode, resizing)) {
1501 /* Retry. The predecessor was deleted, invalid, const, join_follows. */
1502 return false;
1503 }
1504
1505 free_later(h, wnd->cur);
1506
1507 /* Leave ppred as is. */
1508 wnd->last = wnd->cur;
1509 wnd->cur = get_next(wnd->cur->link);
1510 }
1511
1512 return true;
1513}
1514
1515/** Returns true if a bucket join had already completed.
1516 *
1517 * May only be called if upd_resizing_head() indicates a bucket join
1518 * may be in progress.
1519 *
1520 * If it returns false, the search must be retried in order to guarantee
1521 * all item that should have been encountered have been seen.
1522 */
1523static bool join_completed(cht_t *h, const wnd_t *wnd)
1524{
1525 /*
1526 * The table is shrinking and the searched for item is in a bucket
1527 * appended to another. Check that the link joining these two buckets
1528 * is visible and if not, make it visible to this cpu.
1529 */
1530
1531 /*
1532 * Resizer ensures h->b->order stays the same for the duration of this
1533 * func. We got here because there was an alternative head to search.
1534 * The resizer waits for all preexisting readers to finish after
1535 * it
1536 */
1537 assert(h->b->order > h->new_b->order);
1538 assert(wnd->cur);
1539
1540 /* Either we did not need the joining link or we have already followed it.*/
1541 if (wnd->cur != &sentinel)
1542 return true;
1543
1544 /* We have reached the end of a bucket. */
1545
1546 if (wnd->last != &sentinel) {
1547 size_t last_seen_hash = node_hash(h, wnd->last);
1548
1549 if (last_seen_hash == h->invalid_hash) {
1550 last_seen_hash = calc_node_hash(h, wnd->last);
1551 }
1552
1553 size_t last_old_idx = calc_bucket_idx(last_seen_hash, h->b->order);
1554 size_t move_src_idx = grow_idx(shrink_idx(last_old_idx));
1555
1556 /*
1557 * Last node seen was in the joining bucket - if the searched
1558 * for node is there we will find it.
1559 */
1560 if (move_src_idx != last_old_idx)
1561 return true;
1562 }
1563
1564 /*
1565 * Reached the end of the bucket but no nodes from the joining bucket
1566 * were seen. There should have at least been a JOIN node so we have
1567 * definitely not seen (and followed) the joining link. Make the link
1568 * visible and retry.
1569 */
1570 read_barrier();
1571 return false;
1572}
1573
1574/** When resizing returns the bucket head to start the search with in \a phead.
1575 *
1576 * If a resize had been detected (eg cht_t.b.head[idx] is marked immutable).
1577 * upd_resizing_head() moves the bucket for \a hash from the old head
1578 * to the new head. Moreover, it splits or joins buckets as necessary.
1579 *
1580 * @param h CHT to operate on.
1581 * @param hash Hash of an item whose chain we would like to traverse.
1582 * @param[out] phead Head of the bucket to search for \a hash.
1583 * @param[out] join_finishing Set to true if a bucket join might be
1584 * in progress and the bucket may have to traversed again
1585 * as indicated by join_completed().
1586 * @param[out] walk_mode Specifies how to interpret node marks.
1587 */
1588static void upd_resizing_head(cht_t *h, size_t hash, marked_ptr_t **phead,
1589 bool *join_finishing, walk_mode_t *walk_mode)
1590{
1591 cht_buckets_t *b = rcu_access(h->b);
1592 size_t old_idx = calc_bucket_idx(hash, b->order);
1593 size_t new_idx = calc_bucket_idx(hash, h->new_b->order);
1594
1595 marked_ptr_t *pold_head = &b->head[old_idx];
1596 marked_ptr_t *pnew_head = &h->new_b->head[new_idx];
1597
1598 /* In any case, use the bucket in the new table. */
1599 *phead = pnew_head;
1600
1601 /* Growing the table. */
1602 if (b->order < h->new_b->order) {
1603 size_t move_dest_idx = grow_idx(old_idx);
1604 marked_ptr_t *pmoved_head = &h->new_b->head[move_dest_idx];
1605
1606 /* Complete moving the bucket from the old to the new table. */
1607 help_head_move(pold_head, pmoved_head);
1608
1609 /* The hash belongs to the moved bucket. */
1610 if (move_dest_idx == new_idx) {
1611 assert(pmoved_head == pnew_head);
1612 /*
1613 * move_head() makes the new head of the moved bucket visible.
1614 * The new head may be marked with a JOIN_FOLLOWS
1615 */
1616 assert(!(N_CONST & get_mark(*pmoved_head)));
1617 *walk_mode = WM_MOVE_JOIN_FOLLOWS;
1618 } else {
1619 assert(pmoved_head != pnew_head);
1620 /*
1621 * The hash belongs to the bucket that is the result of splitting
1622 * the old/moved bucket, ie the bucket that contains the second
1623 * half of the split/old/moved bucket.
1624 */
1625
1626 /* The moved bucket has not yet been split. */
1627 if (N_NORMAL != get_mark(*pnew_head)) {
1628 size_t split_hash = calc_split_hash(new_idx, h->new_b->order);
1629 split_bucket(h, pmoved_head, pnew_head, split_hash);
1630 /*
1631 * split_bucket() makes the new head visible. No
1632 * JOIN_FOLLOWS in this part of split bucket.
1633 */
1634 assert(N_NORMAL == get_mark(*pnew_head));
1635 }
1636
1637 *walk_mode = WM_LEAVE_JOIN;
1638 }
1639 } else if (h->new_b->order < b->order) {
1640 /* Shrinking the table. */
1641
1642 size_t move_src_idx = grow_idx(new_idx);
1643
1644 /*
1645 * Complete moving the bucket from the old to the new table.
1646 * Makes a valid pnew_head visible if already moved.
1647 */
1648 help_head_move(&b->head[move_src_idx], pnew_head);
1649
1650 /* Hash belongs to the bucket to be joined with the moved bucket. */
1651 if (move_src_idx != old_idx) {
1652 /* Bucket join not yet completed. */
1653 if (N_INVALID != get_mark(*pold_head)) {
1654 size_t split_hash = calc_split_hash(old_idx, b->order);
1655 join_buckets(h, pold_head, pnew_head, split_hash);
1656 }
1657
1658 /*
1659 * The resizer sets pold_head to &sentinel when all cpus are
1660 * guaranteed to see the bucket join.
1661 */
1662 *join_finishing = (&sentinel != get_next(*pold_head));
1663 }
1664
1665 /* move_head() or join_buckets() makes it so or makes the mark visible.*/
1666 assert(N_INVALID == get_mark(*pold_head));
1667 /* move_head() makes it visible. No JOIN_FOLLOWS used when shrinking. */
1668 assert(N_NORMAL == get_mark(*pnew_head));
1669
1670 *walk_mode = WM_LEAVE_JOIN;
1671 } else {
1672 /*
1673 * Final stage of resize. The resizer is waiting for all
1674 * readers to notice that the old table had been replaced.
1675 */
1676 assert(b == h->new_b);
1677 *walk_mode = WM_NORMAL;
1678 }
1679}
1680
1681#if 0
1682static void move_head(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head)
1683{
1684 start_head_move(psrc_head);
1685 cas_order_barrier();
1686 complete_head_move(psrc_head, pdest_head);
1687}
1688#endif
1689
1690/** Moves an immutable head \a psrc_head of cht_t.b to \a pdest_head of cht_t.new_b.
1691 *
1692 * The function guarantees the move will be visible on this cpu once
1693 * it completes. In particular, *pdest_head will not be N_INVALID.
1694 *
1695 * Unlike complete_head_move(), help_head_move() checks if the head had already
1696 * been moved and tries to avoid moving the bucket heads if possible.
1697 */
1698static inline void help_head_move(marked_ptr_t *psrc_head,
1699 marked_ptr_t *pdest_head)
1700{
1701 /* Head move has to in progress already when calling this func. */
1702 assert(N_CONST & get_mark(*psrc_head));
1703
1704 /* Head already moved. */
1705 if (N_INVALID == get_mark(*psrc_head)) {
1706 /* Effects of the head move have not yet propagated to this cpu. */
1707 if (N_INVALID == get_mark(*pdest_head)) {
1708 /* Make the move visible on this cpu. */
1709 read_barrier();
1710 }
1711 } else {
1712 complete_head_move(psrc_head, pdest_head);
1713 }
1714
1715 assert(!(N_CONST & get_mark(*pdest_head)));
1716}
1717
1718/** Initiates the move of the old head \a psrc_head.
1719 *
1720 * The move may be completed with help_head_move().
1721 */
1722static void start_head_move(marked_ptr_t *psrc_head)
1723{
1724 /* Mark src head immutable. */
1725 mark_const(psrc_head);
1726}
1727
1728/** Marks the head immutable. */
1729static void mark_const(marked_ptr_t *psrc_head)
1730{
1731 marked_ptr_t ret, src_link;
1732
1733 /* Mark src head immutable. */
1734 do {
1735 cht_link_t *next = get_next(*psrc_head);
1736 src_link = make_link(next, N_NORMAL);
1737
1738 /* Mark the normal/clean src link immutable/const. */
1739 ret = cas_link(psrc_head, next, N_NORMAL, next, N_CONST);
1740 } while (ret != src_link && !(N_CONST & get_mark(ret)));
1741}
1742
1743/** Completes moving head psrc_head to pdest_head (started by start_head_move()).*/
1744static void complete_head_move(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head)
1745{
1746 assert(N_JOIN_FOLLOWS != get_mark(*psrc_head));
1747 assert(N_CONST & get_mark(*psrc_head));
1748
1749 cht_link_t *next = get_next(*psrc_head);
1750
1751#ifdef CONFIG_DEBUG
1752 marked_ptr_t ret =
1753#endif
1754 cas_link(pdest_head, &sentinel, N_INVALID, next, N_NORMAL);
1755 assert(ret == make_link(&sentinel, N_INVALID) || (N_NORMAL == get_mark(ret)));
1756 cas_order_barrier();
1757
1758#ifdef CONFIG_DEBUG
1759 ret =
1760#endif
1761 cas_link(psrc_head, next, N_CONST, next, N_INVALID);
1762 assert(ret == make_link(next, N_CONST) || (N_INVALID == get_mark(ret)));
1763 cas_order_barrier();
1764}
1765
1766/** Splits the bucket at psrc_head and links to the remainder from pdest_head.
1767 *
1768 * Items with hashes greater or equal to \a split_hash are moved to bucket
1769 * with head at \a pdest_head.
1770 *
1771 * @param h CHT to operate on.
1772 * @param psrc_head Head of the bucket to split (in cht_t.new_b).
1773 * @param pdest_head Head of the bucket that points to the second part
1774 * of the split bucket in psrc_head. (in cht_t.new_b)
1775 * @param split_hash Hash of the first possible item in the remainder of
1776 * psrc_head, ie the smallest hash pdest_head is allowed
1777 * to point to..
1778 */
1779static void split_bucket(cht_t *h, marked_ptr_t *psrc_head,
1780 marked_ptr_t *pdest_head, size_t split_hash)
1781{
1782 /* Already split. */
1783 if (N_NORMAL == get_mark(*pdest_head))
1784 return;
1785
1786 /*
1787 * L == Last node of the first part of the split bucket. That part
1788 * remains in the original/src bucket.
1789 * F == First node of the second part of the split bucket. That part
1790 * will be referenced from the dest bucket head.
1791 *
1792 * We want to first mark a clean L as JF so that updaters unaware of
1793 * the split (or table resize):
1794 * - do not insert a new node between L and F
1795 * - do not unlink L (that is why it has to be clean/normal)
1796 * - do not unlink F
1797 *
1798 * Then we can safely mark F as JN even if it has been marked deleted.
1799 * Once F is marked as JN updaters aware of table resize will not
1800 * attempt to unlink it (JN will have two predecessors - we cannot
1801 * safely unlink from both at the same time). Updaters unaware of
1802 * ongoing resize can reach F only via L and that node is already
1803 * marked JF, so they won't unlink F.
1804 *
1805 * Last, link the new/dest head to F.
1806 *
1807 *
1808 * 0) ,-- split_hash, first hash of the dest bucket
1809 * v
1810 * [src_head | N] -> .. -> [L] -> [F]
1811 * [dest_head | Inv]
1812 *
1813 * 1) ,-- split_hash
1814 * v
1815 * [src_head | N] -> .. -> [JF] -> [F]
1816 * [dest_head | Inv]
1817 *
1818 * 2) ,-- split_hash
1819 * v
1820 * [src_head | N] -> .. -> [JF] -> [JN]
1821 * [dest_head | Inv]
1822 *
1823 * 3) ,-- split_hash
1824 * v
1825 * [src_head | N] -> .. -> [JF] -> [JN]
1826 * ^
1827 * [dest_head | N] -----------------'
1828 */
1829 wnd_t wnd;
1830
1831 rcu_read_lock();
1832
1833 /* Mark the last node of the first part of the split bucket as JF. */
1834 mark_join_follows(h, psrc_head, split_hash, &wnd);
1835 cas_order_barrier();
1836
1837 /* There are nodes in the dest bucket, ie the second part of the split. */
1838 if (wnd.cur != &sentinel) {
1839 /*
1840 * Mark the first node of the dest bucket as a join node so
1841 * updaters do not attempt to unlink it if it is deleted.
1842 */
1843 mark_join_node(wnd.cur);
1844 cas_order_barrier();
1845 } else {
1846 /*
1847 * Second part of the split bucket is empty. There are no nodes
1848 * to mark as JOIN nodes and there never will be.
1849 */
1850 }
1851
1852 /* Link the dest head to the second part of the split. */
1853#ifdef CONFIG_DEBUG
1854 marked_ptr_t ret =
1855#endif
1856 cas_link(pdest_head, &sentinel, N_INVALID, wnd.cur, N_NORMAL);
1857 assert(ret == make_link(&sentinel, N_INVALID) || (N_NORMAL == get_mark(ret)));
1858 cas_order_barrier();
1859
1860 rcu_read_unlock();
1861}
1862
1863/** Finds and marks the last node of psrc_head w/ hash less than split_hash.
1864 *
1865 * Finds a node in psrc_head with the greatest hash that is strictly less
1866 * than split_hash and marks it with N_JOIN_FOLLOWS.
1867 *
1868 * Returns a window pointing to that node.
1869 *
1870 * Any logically deleted nodes along the way are
1871 * garbage collected; therefore, the predecessor node (if any) will most
1872 * likely not be marked N_DELETED.
1873 *
1874 * @param h CHT to operate on.
1875 * @param psrc_head Bucket head.
1876 * @param split_hash The smallest hash a join node (ie the node following
1877 * the desired join-follows node) may have.
1878 * @param[out] wnd Points to the node marked with N_JOIN_FOLLOWS.
1879 */
1880static void mark_join_follows(cht_t *h, marked_ptr_t *psrc_head,
1881 size_t split_hash, wnd_t *wnd)
1882{
1883 /* See comment in split_bucket(). */
1884
1885 bool done = false;
1886
1887 do {
1888 bool resizing = false;
1889 wnd->ppred = psrc_head;
1890 wnd->cur = get_next(*psrc_head);
1891
1892 /*
1893 * Find the split window, ie the last node of the first part of
1894 * the split bucket and the its successor - the first node of
1895 * the second part of the split bucket. Retry if GC failed.
1896 */
1897 if (!find_wnd_and_gc(h, split_hash, WM_MOVE_JOIN_FOLLOWS, wnd, &resizing))
1898 continue;
1899
1900 /* Must not report that the table is resizing if WM_MOVE_JOIN_FOLLOWS.*/
1901 assert(!resizing);
1902 /*
1903 * Mark the last node of the first half of the split bucket
1904 * that a join node follows. It must be clean/normal.
1905 */
1906 marked_ptr_t ret =
1907 cas_link(wnd->ppred, wnd->cur, N_NORMAL, wnd->cur, N_JOIN_FOLLOWS);
1908
1909 /*
1910 * Successfully marked as a JF node or already marked that way (even
1911 * if also marked deleted - unlinking the node will move the JF mark).
1912 */
1913 done = (ret == make_link(wnd->cur, N_NORMAL)) ||
1914 (N_JOIN_FOLLOWS & get_mark(ret));
1915 } while (!done);
1916}
1917
1918/** Marks join_node with N_JOIN. */
1919static void mark_join_node(cht_link_t *join_node)
1920{
1921 /* See comment in split_bucket(). */
1922
1923 bool done;
1924 do {
1925 cht_link_t *next = get_next(join_node->link);
1926 mark_t mark = get_mark(join_node->link);
1927
1928 /*
1929 * May already be marked as deleted, but it won't be unlinked
1930 * because its predecessor is marked with JOIN_FOLLOWS or CONST.
1931 */
1932 marked_ptr_t ret =
1933 cas_link(&join_node->link, next, mark, next, mark | N_JOIN);
1934
1935 /* Successfully marked or already marked as a join node. */
1936 done = (ret == make_link(next, mark)) ||
1937 (N_JOIN & get_mark(ret));
1938 } while (!done);
1939}
1940
1941/** Appends the bucket at psrc_head to the bucket at pdest_head.
1942 *
1943 * @param h CHT to operate on.
1944 * @param psrc_head Bucket to merge with pdest_head.
1945 * @param pdest_head Bucket to be joined by psrc_head.
1946 * @param split_hash The smallest hash psrc_head may contain.
1947 */
1948static void join_buckets(cht_t *h, marked_ptr_t *psrc_head,
1949 marked_ptr_t *pdest_head, size_t split_hash)
1950{
1951 /* Buckets already joined. */
1952 if (N_INVALID == get_mark(*psrc_head))
1953 return;
1954 /*
1955 * F == First node of psrc_head, ie the bucket we want to append
1956 * to (ie join with) the bucket starting at pdest_head.
1957 * L == Last node of pdest_head, ie the bucket that psrc_head will
1958 * be appended to.
1959 *
1960 * (1) We first mark psrc_head immutable to signal that a join is
1961 * in progress and so that updaters unaware of the join (or table
1962 * resize):
1963 * - do not insert new nodes between the head psrc_head and F
1964 * - do not unlink F (it may already be marked deleted)
1965 *
1966 * (2) Next, F is marked as a join node. Updaters aware of table resize
1967 * will not attempt to unlink it. We cannot safely/atomically unlink
1968 * the join node because it will be pointed to from two different
1969 * buckets. Updaters unaware of resize will fail to unlink the join
1970 * node due to the head being marked immutable.
1971 *
1972 * (3) Then the tail of the bucket at pdest_head is linked to the join
1973 * node. From now on, nodes in both buckets can be found via pdest_head.
1974 *
1975 * (4) Last, mark immutable psrc_head as invalid. It signals updaters
1976 * that the join is complete and they can insert new nodes (originally
1977 * destined for psrc_head) into pdest_head.
1978 *
1979 * Note that pdest_head keeps pointing at the join node. This allows
1980 * lookups and updaters to determine if they should see a link between
1981 * the tail L and F when searching for nodes originally in psrc_head
1982 * via pdest_head. If they reach the tail of pdest_head without
1983 * encountering any nodes of psrc_head, either there were no nodes
1984 * in psrc_head to begin with or the link between L and F did not
1985 * yet propagate to their cpus. If psrc_head was empty, it remains
1986 * NULL. Otherwise psrc_head points to a join node (it will not be
1987 * unlinked until table resize completes) and updaters/lookups
1988 * should issue a read_barrier() to make the link [L]->[JN] visible.
1989 *
1990 * 0) ,-- split_hash, first hash of the src bucket
1991 * v
1992 * [dest_head | N]-> .. -> [L]
1993 * [src_head | N]--> [F] -> ..
1994 * ^
1995 * ` split_hash, first hash of the src bucket
1996 *
1997 * 1) ,-- split_hash
1998 * v
1999 * [dest_head | N]-> .. -> [L]
2000 * [src_head | C]--> [F] -> ..
2001 *
2002 * 2) ,-- split_hash
2003 * v
2004 * [dest_head | N]-> .. -> [L]
2005 * [src_head | C]--> [JN] -> ..
2006 *
2007 * 3) ,-- split_hash
2008 * v
2009 * [dest_head | N]-> .. -> [L] --+
2010 * v
2011 * [src_head | C]-------------> [JN] -> ..
2012 *
2013 * 4) ,-- split_hash
2014 * v
2015 * [dest_head | N]-> .. -> [L] --+
2016 * v
2017 * [src_head | Inv]-----------> [JN] -> ..
2018 */
2019
2020 rcu_read_lock();
2021
2022 /* Mark src_head immutable - signals updaters that bucket join started. */
2023 mark_const(psrc_head);
2024 cas_order_barrier();
2025
2026 cht_link_t *join_node = get_next(*psrc_head);
2027
2028 if (join_node != &sentinel) {
2029 mark_join_node(join_node);
2030 cas_order_barrier();
2031
2032 link_to_join_node(h, pdest_head, join_node, split_hash);
2033 cas_order_barrier();
2034 }
2035
2036#ifdef CONFIG_DEBUG
2037 marked_ptr_t ret =
2038#endif
2039 cas_link(psrc_head, join_node, N_CONST, join_node, N_INVALID);
2040 assert(ret == make_link(join_node, N_CONST) || (N_INVALID == get_mark(ret)));
2041 cas_order_barrier();
2042
2043 rcu_read_unlock();
2044}
2045
2046/** Links the tail of pdest_head to join_node.
2047 *
2048 * @param h CHT to operate on.
2049 * @param pdest_head Head of the bucket whose tail is to be linked to join_node.
2050 * @param join_node A node marked N_JOIN with a hash greater or equal to
2051 * split_hash.
2052 * @param split_hash The least hash that is greater than the hash of any items
2053 * (originally) in pdest_head.
2054 */
2055static void link_to_join_node(cht_t *h, marked_ptr_t *pdest_head,
2056 cht_link_t *join_node, size_t split_hash)
2057{
2058 bool done = false;
2059
2060 do {
2061 wnd_t wnd = {
2062 .ppred = pdest_head,
2063 .cur = get_next(*pdest_head)
2064 };
2065
2066 bool resizing = false;
2067
2068 if (!find_wnd_and_gc(h, split_hash, WM_LEAVE_JOIN, &wnd, &resizing))
2069 continue;
2070
2071 assert(!resizing);
2072
2073 if (wnd.cur != &sentinel) {
2074 /* Must be from the new appended bucket. */
2075 assert(split_hash <= node_hash(h, wnd.cur) ||
2076 h->invalid_hash == node_hash(h, wnd.cur));
2077 return;
2078 }
2079
2080 /* Reached the tail of pdest_head - link it to the join node. */
2081 marked_ptr_t ret =
2082 cas_link(wnd.ppred, &sentinel, N_NORMAL, join_node, N_NORMAL);
2083
2084 done = (ret == make_link(&sentinel, N_NORMAL));
2085 } while (!done);
2086}
2087
2088/** Instructs RCU to free the item once all preexisting references are dropped.
2089 *
2090 * The item is freed via op->remove_callback().
2091 */
2092static void free_later(cht_t *h, cht_link_t *item)
2093{
2094 assert(item != &sentinel);
2095
2096 /*
2097 * remove_callback only works as rcu_func_t because rcu_link is the first
2098 * field in cht_link_t.
2099 */
2100 rcu_call(&item->rcu_link, (rcu_func_t)h->op->remove_callback);
2101
2102 item_removed(h);
2103}
2104
2105/** Notes that an item had been unlinked from the table and shrinks it if needed.
2106 *
2107 * If the number of items in the table drops below 1/4 of the maximum
2108 * allowed load the table is shrunk in the background.
2109 */
2110static inline void item_removed(cht_t *h)
2111{
2112 size_t items = (size_t) atomic_predec(&h->item_cnt);
2113 size_t bucket_cnt = (1 << h->b->order);
2114
2115 bool need_shrink = (items == h->max_load * bucket_cnt / 4);
2116 bool missed_shrink = (items == h->max_load * bucket_cnt / 8);
2117
2118 if ((need_shrink || missed_shrink) && h->b->order > h->min_order) {
2119 size_t resize_reqs = atomic_preinc(&h->resize_reqs);
2120 /* The first resize request. Start the resizer. */
2121 if (1 == resize_reqs) {
2122 workq_global_enqueue_noblock(&h->resize_work, resize_table);
2123 }
2124 }
2125}
2126
2127/** Notes an item had been inserted and grows the table if needed.
2128 *
2129 * The table is resized in the background.
2130 */
2131static inline void item_inserted(cht_t *h)
2132{
2133 size_t items = (size_t) atomic_preinc(&h->item_cnt);
2134 size_t bucket_cnt = (1 << h->b->order);
2135
2136 bool need_grow = (items == h->max_load * bucket_cnt);
2137 bool missed_grow = (items == 2 * h->max_load * bucket_cnt);
2138
2139 if ((need_grow || missed_grow) && h->b->order < CHT_MAX_ORDER) {
2140 size_t resize_reqs = atomic_preinc(&h->resize_reqs);
2141 /* The first resize request. Start the resizer. */
2142 if (1 == resize_reqs) {
2143 workq_global_enqueue_noblock(&h->resize_work, resize_table);
2144 }
2145 }
2146}
2147
2148/** Resize request handler. Invoked on the system work queue. */
2149static void resize_table(work_t *arg)
2150{
2151 cht_t *h = member_to_inst(arg, cht_t, resize_work);
2152
2153#ifdef CONFIG_DEBUG
2154 assert(h->b);
2155 /* Make resize_reqs visible. */
2156 read_barrier();
2157 assert(0 < atomic_load(&h->resize_reqs));
2158#endif
2159
2160 bool done = false;
2161
2162 do {
2163 /* Load the most recent h->item_cnt. */
2164 read_barrier();
2165 size_t cur_items = (size_t) atomic_load(&h->item_cnt);
2166 size_t bucket_cnt = (1 << h->b->order);
2167 size_t max_items = h->max_load * bucket_cnt;
2168
2169 if (cur_items >= max_items && h->b->order < CHT_MAX_ORDER) {
2170 grow_table(h);
2171 } else if (cur_items <= max_items / 4 && h->b->order > h->min_order) {
2172 shrink_table(h);
2173 } else {
2174 /* Table is just the right size. */
2175 size_t reqs = atomic_predec(&h->resize_reqs);
2176 done = (reqs == 0);
2177 }
2178 } while (!done);
2179}
2180
2181/** Increases the number of buckets two-fold. Blocks until done. */
2182static void grow_table(cht_t *h)
2183{
2184 if (h->b->order >= CHT_MAX_ORDER)
2185 return;
2186
2187 h->new_b = alloc_buckets(h->b->order + 1, true, false);
2188
2189 /* Failed to alloc a new table - try next time the resizer is run. */
2190 if (!h->new_b)
2191 return;
2192
2193 /* Wait for all readers and updaters to see the initialized new table. */
2194 rcu_synchronize();
2195 size_t old_bucket_cnt = (1 << h->b->order);
2196
2197 /*
2198 * Give updaters a chance to help out with the resize. Do the minimum
2199 * work needed to announce a resize is in progress, ie start moving heads.
2200 */
2201 for (size_t idx = 0; idx < old_bucket_cnt; ++idx) {
2202 start_head_move(&h->b->head[idx]);
2203 }
2204
2205 /* Order start_head_move() wrt complete_head_move(). */
2206 cas_order_barrier();
2207
2208 /* Complete moving heads and split any buckets not yet split by updaters. */
2209 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2210 marked_ptr_t *move_dest_head = &h->new_b->head[grow_idx(old_idx)];
2211 marked_ptr_t *move_src_head = &h->b->head[old_idx];
2212
2213 /* Head move not yet completed. */
2214 if (N_INVALID != get_mark(*move_src_head)) {
2215 complete_head_move(move_src_head, move_dest_head);
2216 }
2217
2218 size_t split_idx = grow_to_split_idx(old_idx);
2219 size_t split_hash = calc_split_hash(split_idx, h->new_b->order);
2220 marked_ptr_t *split_dest_head = &h->new_b->head[split_idx];
2221
2222 split_bucket(h, move_dest_head, split_dest_head, split_hash);
2223 }
2224
2225 /*
2226 * Wait for all updaters to notice the new heads. Once everyone sees
2227 * the invalid old bucket heads they will know a resize is in progress
2228 * and updaters will modify the correct new buckets.
2229 */
2230 rcu_synchronize();
2231
2232 /* Clear the JOIN_FOLLOWS mark and remove the link between the split buckets.*/
2233 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2234 size_t new_idx = grow_idx(old_idx);
2235
2236 cleanup_join_follows(h, &h->new_b->head[new_idx]);
2237 }
2238
2239 /*
2240 * Wait for everyone to notice that buckets were split, ie link connecting
2241 * the join follows and join node has been cut.
2242 */
2243 rcu_synchronize();
2244
2245 /* Clear the JOIN mark and GC any deleted join nodes. */
2246 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2247 size_t new_idx = grow_to_split_idx(old_idx);
2248
2249 cleanup_join_node(h, &h->new_b->head[new_idx]);
2250 }
2251
2252 /* Wait for everyone to see that the table is clear of any resize marks. */
2253 rcu_synchronize();
2254
2255 cht_buckets_t *old_b = h->b;
2256 rcu_assign(h->b, h->new_b);
2257
2258 /* Wait for everyone to start using the new table. */
2259 rcu_synchronize();
2260
2261 free(old_b);
2262
2263 /* Not needed; just for increased readability. */
2264 h->new_b = NULL;
2265}
2266
2267/** Halfs the number of buckets. Blocks until done. */
2268static void shrink_table(cht_t *h)
2269{
2270 if (h->b->order <= h->min_order)
2271 return;
2272
2273 h->new_b = alloc_buckets(h->b->order - 1, true, false);
2274
2275 /* Failed to alloc a new table - try next time the resizer is run. */
2276 if (!h->new_b)
2277 return;
2278
2279 /* Wait for all readers and updaters to see the initialized new table. */
2280 rcu_synchronize();
2281
2282 size_t old_bucket_cnt = (1 << h->b->order);
2283
2284 /*
2285 * Give updaters a chance to help out with the resize. Do the minimum
2286 * work needed to announce a resize is in progress, ie start moving heads.
2287 */
2288 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2289 size_t new_idx = shrink_idx(old_idx);
2290
2291 /* This bucket should be moved. */
2292 if (grow_idx(new_idx) == old_idx) {
2293 start_head_move(&h->b->head[old_idx]);
2294 } else {
2295 /* This bucket should join the moved bucket once the move is done.*/
2296 }
2297 }
2298
2299 /* Order start_head_move() wrt to complete_head_move(). */
2300 cas_order_barrier();
2301
2302 /* Complete moving heads and join buckets with the moved buckets. */
2303 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2304 size_t new_idx = shrink_idx(old_idx);
2305 size_t move_src_idx = grow_idx(new_idx);
2306
2307 /* This bucket should be moved. */
2308 if (move_src_idx == old_idx) {
2309 /* Head move not yet completed. */
2310 if (N_INVALID != get_mark(h->b->head[old_idx])) {
2311 complete_head_move(&h->b->head[old_idx], &h->new_b->head[new_idx]);
2312 }
2313 } else {
2314 /* This bucket should join the moved bucket. */
2315 size_t split_hash = calc_split_hash(old_idx, h->b->order);
2316 join_buckets(h, &h->b->head[old_idx], &h->new_b->head[new_idx],
2317 split_hash);
2318 }
2319 }
2320
2321 /*
2322 * Wait for all updaters to notice the new heads. Once everyone sees
2323 * the invalid old bucket heads they will know a resize is in progress
2324 * and updaters will modify the correct new buckets.
2325 */
2326 rcu_synchronize();
2327
2328 /* Let everyone know joins are complete and fully visible. */
2329 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2330 size_t move_src_idx = grow_idx(shrink_idx(old_idx));
2331
2332 /* Set the invalid joinee head to NULL. */
2333 if (old_idx != move_src_idx) {
2334 assert(N_INVALID == get_mark(h->b->head[old_idx]));
2335
2336 if (&sentinel != get_next(h->b->head[old_idx]))
2337 h->b->head[old_idx] = make_link(&sentinel, N_INVALID);
2338 }
2339 }
2340
2341 /* todo comment join node vs reset joinee head*/
2342 rcu_synchronize();
2343
2344 size_t new_bucket_cnt = (1 << h->new_b->order);
2345
2346 /* Clear the JOIN mark and GC any deleted join nodes. */
2347 for (size_t new_idx = 0; new_idx < new_bucket_cnt; ++new_idx) {
2348 cleanup_join_node(h, &h->new_b->head[new_idx]);
2349 }
2350
2351 /* Wait for everyone to see that the table is clear of any resize marks. */
2352 rcu_synchronize();
2353
2354 cht_buckets_t *old_b = h->b;
2355 rcu_assign(h->b, h->new_b);
2356
2357 /* Wait for everyone to start using the new table. */
2358 rcu_synchronize();
2359
2360 free(old_b);
2361
2362 /* Not needed; just for increased readability. */
2363 h->new_b = NULL;
2364}
2365
2366/** Finds and clears the N_JOIN mark from a node in new_head (if present). */
2367static void cleanup_join_node(cht_t *h, marked_ptr_t *new_head)
2368{
2369 rcu_read_lock();
2370
2371 cht_link_t *cur = get_next(*new_head);
2372
2373 while (cur != &sentinel) {
2374 /* Clear the join node's JN mark - even if it is marked as deleted. */
2375 if (N_JOIN & get_mark(cur->link)) {
2376 clear_join_and_gc(h, cur, new_head);
2377 break;
2378 }
2379
2380 cur = get_next(cur->link);
2381 }
2382
2383 rcu_read_unlock();
2384}
2385
2386/** Clears the join_node's N_JOIN mark frees it if marked N_DELETED as well. */
2387static void clear_join_and_gc(cht_t *h, cht_link_t *join_node,
2388 marked_ptr_t *new_head)
2389{
2390 assert(join_node != &sentinel);
2391 assert(join_node && (N_JOIN & get_mark(join_node->link)));
2392
2393 bool done;
2394
2395 /* Clear the JN mark. */
2396 do {
2397 marked_ptr_t jn_link = join_node->link;
2398 cht_link_t *next = get_next(jn_link);
2399 /* Clear the JOIN mark but keep the DEL mark if present. */
2400 mark_t cleared_mark = get_mark(jn_link) & N_DELETED;
2401
2402 marked_ptr_t ret =
2403 _cas_link(&join_node->link, jn_link, make_link(next, cleared_mark));
2404
2405 /* Done if the mark was cleared. Retry if a new node was inserted. */
2406 done = (ret == jn_link);
2407 assert(ret == jn_link || (get_mark(ret) & N_JOIN));
2408 } while (!done);
2409
2410 if (!(N_DELETED & get_mark(join_node->link)))
2411 return;
2412
2413 /* The join node had been marked as deleted - GC it. */
2414
2415 /* Clear the JOIN mark before trying to unlink the deleted join node.*/
2416 cas_order_barrier();
2417
2418 size_t jn_hash = node_hash(h, join_node);
2419 do {
2420 bool resizing = false;
2421
2422 wnd_t wnd = {
2423 .ppred = new_head,
2424 .cur = get_next(*new_head)
2425 };
2426
2427 done = find_wnd_and_gc_pred(h, jn_hash, WM_NORMAL, same_node_pred,
2428 join_node, &wnd, &resizing);
2429
2430 assert(!resizing);
2431 } while (!done);
2432}
2433
2434/** Finds a non-deleted node with N_JOIN_FOLLOWS and clears the mark. */
2435static void cleanup_join_follows(cht_t *h, marked_ptr_t *new_head)
2436{
2437 assert(new_head);
2438
2439 rcu_read_lock();
2440
2441 wnd_t wnd = {
2442 .ppred = NULL,
2443 .cur = NULL
2444 };
2445 marked_ptr_t *cur_link = new_head;
2446
2447 /*
2448 * Find the non-deleted node with a JF mark and clear the JF mark.
2449 * The JF node may be deleted and/or the mark moved to its neighbors
2450 * at any time. Therefore, we GC deleted nodes until we find the JF
2451 * node in order to remove stale/deleted JF nodes left behind eg by
2452 * delayed threads that did not yet get a chance to unlink the deleted
2453 * JF node and move its mark.
2454 *
2455 * Note that the head may be marked JF (but never DELETED).
2456 */
2457 while (true) {
2458 bool is_jf_node = N_JOIN_FOLLOWS & get_mark(*cur_link);
2459
2460 /* GC any deleted nodes on the way - even deleted JOIN_FOLLOWS. */
2461 if (N_DELETED & get_mark(*cur_link)) {
2462 assert(cur_link != new_head);
2463 assert(wnd.ppred && wnd.cur && wnd.cur != &sentinel);
2464 assert(cur_link == &wnd.cur->link);
2465
2466 bool dummy;
2467 bool deleted = gc_deleted_node(h, WM_MOVE_JOIN_FOLLOWS, &wnd, &dummy);
2468
2469 /* Failed to GC or collected a deleted JOIN_FOLLOWS. */
2470 if (!deleted || is_jf_node) {
2471 /* Retry from the head of the bucket. */
2472 cur_link = new_head;
2473 continue;
2474 }
2475 } else {
2476 /* Found a non-deleted JF. Clear its JF mark. */
2477 if (is_jf_node) {
2478 cht_link_t *next = get_next(*cur_link);
2479 marked_ptr_t ret =
2480 cas_link(cur_link, next, N_JOIN_FOLLOWS, &sentinel, N_NORMAL);
2481
2482 assert(next == &sentinel ||
2483 ((N_JOIN | N_JOIN_FOLLOWS) & get_mark(ret)));
2484
2485 /* Successfully cleared the JF mark of a non-deleted node. */
2486 if (ret == make_link(next, N_JOIN_FOLLOWS)) {
2487 break;
2488 } else {
2489 /*
2490 * The JF node had been deleted or a new node inserted
2491 * right after it. Retry from the head.
2492 */
2493 cur_link = new_head;
2494 continue;
2495 }
2496 } else {
2497 wnd.ppred = cur_link;
2498 wnd.cur = get_next(*cur_link);
2499 }
2500 }
2501
2502 /* We must encounter a JF node before we reach the end of the bucket. */
2503 assert(wnd.cur && wnd.cur != &sentinel);
2504 cur_link = &wnd.cur->link;
2505 }
2506
2507 rcu_read_unlock();
2508}
2509
2510/** Returns the first possible hash following a bucket split point.
2511 *
2512 * In other words the returned hash is the smallest possible hash
2513 * the remainder of the split bucket may contain.
2514 */
2515static inline size_t calc_split_hash(size_t split_idx, size_t order)
2516{
2517 assert(1 <= order && order <= 8 * sizeof(size_t));
2518 return split_idx << (8 * sizeof(size_t) - order);
2519}
2520
2521/** Returns the bucket head index given the table size order and item hash. */
2522static inline size_t calc_bucket_idx(size_t hash, size_t order)
2523{
2524 assert(1 <= order && order <= 8 * sizeof(size_t));
2525 return hash >> (8 * sizeof(size_t) - order);
2526}
2527
2528/** Returns the bucket index of destination*/
2529static inline size_t grow_to_split_idx(size_t old_idx)
2530{
2531 return grow_idx(old_idx) | 1;
2532}
2533
2534/** Returns the destination index of a bucket head when the table is growing. */
2535static inline size_t grow_idx(size_t idx)
2536{
2537 return idx << 1;
2538}
2539
2540/** Returns the destination index of a bucket head when the table is shrinking.*/
2541static inline size_t shrink_idx(size_t idx)
2542{
2543 return idx >> 1;
2544}
2545
2546/** Returns a mixed hash of the search key.*/
2547static inline size_t calc_key_hash(cht_t *h, void *key)
2548{
2549 /* Mimic calc_node_hash. */
2550 return hash_mix(h->op->key_hash(key)) & ~(size_t)1;
2551}
2552
2553/** Returns a memoized mixed hash of the item. */
2554static inline size_t node_hash(cht_t *h, const cht_link_t *item)
2555{
2556 assert(item->hash == h->invalid_hash ||
2557 item->hash == sentinel.hash ||
2558 item->hash == calc_node_hash(h, item));
2559
2560 return item->hash;
2561}
2562
2563/** Calculates and mixed the hash of the item. */
2564static inline size_t calc_node_hash(cht_t *h, const cht_link_t *item)
2565{
2566 assert(item != &sentinel);
2567 /*
2568 * Clear the lowest order bit in order for sentinel's node hash
2569 * to be the greatest possible.
2570 */
2571 return hash_mix(h->op->hash(item)) & ~(size_t)1;
2572}
2573
2574/** Computes and memoizes the hash of the item. */
2575static inline void memoize_node_hash(cht_t *h, cht_link_t *item)
2576{
2577 item->hash = calc_node_hash(h, item);
2578}
2579
2580/** Packs the next pointer address and the mark into a single pointer. */
2581static inline marked_ptr_t make_link(const cht_link_t *next, mark_t mark)
2582{
2583 marked_ptr_t ptr = (marked_ptr_t) next;
2584
2585 assert(!(ptr & N_MARK_MASK));
2586 assert(!((unsigned)mark & ~N_MARK_MASK));
2587
2588 return ptr | mark;
2589}
2590
2591/** Strips any marks from the next item link and returns the next item's address.*/
2592static inline cht_link_t *get_next(marked_ptr_t link)
2593{
2594 return (cht_link_t *)(link & ~N_MARK_MASK);
2595}
2596
2597/** Returns the current node's mark stored in the next item link. */
2598static inline mark_t get_mark(marked_ptr_t link)
2599{
2600 return (mark_t)(link & N_MARK_MASK);
2601}
2602
2603/** Moves the window by one item so that is points to the next item. */
2604static inline void next_wnd(wnd_t *wnd)
2605{
2606 assert(wnd);
2607 assert(wnd->cur);
2608
2609 wnd->last = wnd->cur;
2610 wnd->ppred = &wnd->cur->link;
2611 wnd->cur = get_next(wnd->cur->link);
2612}
2613
2614/** Predicate that matches only exactly the same node. */
2615static bool same_node_pred(void *node, const cht_link_t *item2)
2616{
2617 const cht_link_t *item1 = (const cht_link_t *) node;
2618 return item1 == item2;
2619}
2620
2621/** Compare-and-swaps a next item link. */
2622static inline marked_ptr_t cas_link(marked_ptr_t *link, const cht_link_t *cur_next,
2623 mark_t cur_mark, const cht_link_t *new_next, mark_t new_mark)
2624{
2625 return _cas_link(link, make_link(cur_next, cur_mark),
2626 make_link(new_next, new_mark));
2627}
2628
2629/** Compare-and-swaps a next item link. */
2630static inline marked_ptr_t _cas_link(marked_ptr_t *link, marked_ptr_t cur,
2631 marked_ptr_t new)
2632{
2633 assert(link != &sentinel.link);
2634 /*
2635 * cas(x) on the same location x on one cpu must be ordered, but do not
2636 * have to be ordered wrt to other cas(y) to a different location y
2637 * on the same cpu.
2638 *
2639 * cas(x) must act as a write barrier on x, ie if cas(x) succeeds
2640 * and is observed by another cpu, then all cpus must be able to
2641 * make the effects of cas(x) visible just by issuing a load barrier.
2642 * For example:
2643 * cpu1 cpu2 cpu3
2644 * cas(x, 0 -> 1), succeeds
2645 * cas(x, 0 -> 1), fails
2646 * MB, to order load of x in cas and store to y
2647 * y = 7
2648 * sees y == 7
2649 * loadMB must be enough to make cas(x) on cpu3 visible to cpu1, ie x == 1.
2650 *
2651 * If cas() did not work this way:
2652 * a) our head move protocol would not be correct.
2653 * b) freeing an item linked to a moved head after another item was
2654 * inserted in front of it, would require more than one grace period.
2655 *
2656 * Ad (a): In the following example, cpu1 starts moving old_head
2657 * to new_head, cpu2 completes the move and cpu3 notices cpu2
2658 * completed the move before cpu1 gets a chance to notice cpu2
2659 * had already completed the move. Our requirements for cas()
2660 * assume cpu3 will see a valid and mutable value in new_head
2661 * after issuing a load memory barrier once it has determined
2662 * the old_head's value had been successfully moved to new_head
2663 * (because it sees old_head marked invalid).
2664 *
2665 * cpu1 cpu2 cpu3
2666 * cas(old_head, <addr, N>, <addr, Const>), succeeds
2667 * cas-order-barrier
2668 * // Move from old_head to new_head started, now the interesting stuff:
2669 * cas(new_head, <0, Inv>, <addr, N>), succeeds
2670 *
2671 * cas(new_head, <0, Inv>, <addr, N>), but fails
2672 * cas-order-barrier
2673 * cas(old_head, <addr, Const>, <addr, Inv>), succeeds
2674 *
2675 * Sees old_head marked Inv (by cpu2)
2676 * load-MB
2677 * assert(new_head == <addr, N>)
2678 *
2679 * cas-order-barrier
2680 *
2681 * Even though cpu1 did not yet issue a cas-order-barrier, cpu1's store
2682 * to new_head (successful cas()) must be made visible to cpu3 with
2683 * a load memory barrier if cpu1's store to new_head is visible
2684 * on another cpu (cpu2) and that cpu's (cpu2's) store to old_head
2685 * is already visible to cpu3. *
2686 */
2687 void *expected = (void *)cur;
2688
2689 /*
2690 * Use the acquire-release model, although we could probably
2691 * get away even with the relaxed memory model due to our use
2692 * of explicit memory barriers.
2693 */
2694 __atomic_compare_exchange_n((void **)link, &expected, (void *)new, false,
2695 __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE);
2696
2697 return (marked_ptr_t) expected;
2698}
2699
2700/** Orders compare-and-swaps to different memory locations. */
2701static inline void cas_order_barrier(void)
2702{
2703 /* Make sure CAS to different memory locations are ordered. */
2704 write_barrier();
2705}
2706
2707/** @}
2708 */
Note: See TracBrowser for help on using the repository browser.