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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since c28413a9 was c28413a9, checked in by Adam Hraska <adam.hraska+hos@…>, 13 years ago

cht: Added cht_create_simple(). cht_create() can now block until memory is available.

  • Property mode set to 100644
File size: 89.7 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
30/** @addtogroup genericadt
31 * @{
32 */
33
34/**
35 * @file
36 * @brief Scalable resizable concurrent lock-free hash table.
37 *
38 * CHT is a concurrent hash table that is scalable resizable and lock-free.
39 * resizable = the number of buckets of the table increases or decreases
40 * depending on the average number of elements per bucket (ie load)
41 * scalable = accessing the table from more cpus increases performance
42 * almost linearly
43 * lock-free = common operations never block; even if any of the operations
44 * is preempted or interrupted at any time, other operations will still
45 * make forward progress
46 *
47 * CHT is designed for read mostly scenarios. Performance degrades as the
48 * fraction of updates (insert/remove) increases. Other data structures
49 * significantly outperform CHT if the fraction of updates exceeds ~40%.
50 *
51 * CHT tolerates hardware exceptions and may be accessed from exception
52 * handlers as long as the underlying RCU implementation is exception safe.
53 *
54 * @par Caveats
55 *
56 * 0) Never assume an item is still in the table.
57 * The table may be accessed concurrently; therefore, other threads may
58 * insert or remove an item at any time. Do not assume an item is still
59 * in the table if cht_find() just returned it to you. Similarly, an
60 * item may have already been inserted by the time cht_find() returns NULL.
61 *
62 * 1) Always use RCU read locks when searching the table.
63 * Holding an RCU lock guarantees that an item found in the table remains
64 * valid (eg is not freed) even if the item was removed from the table
65 * in the meantime by another thread.
66 *
67 * 2) Never update values in place.
68 * Do not update items in the table in place, ie directly. The changes
69 * will not propagate to other readers (on other cpus) immediately or even
70 * correctly. Some readers may then encounter items that have only some
71 * of their fields changed or are completely inconsistent.
72 *
73 * Instead consider inserting an updated/changed copy of the item and
74 * removing the original item. Or contact the maintainer to provide
75 * you with a function that atomically replaces an item with a copy.
76 *
77 * 3) Use cht_insert_unique() instead of checking for duplicates with cht_find()
78 * The following code is prone to race conditions:
79 * @code
80 * if (NULL == cht_find(&h, key)) {
81 * // If another thread inserts and item here, we'll insert a duplicate.
82 * cht_insert(&h, item);
83 * }
84 * @endcode
85 * See cht_insert_unique() on how to correctly fix this.
86 *
87 *
88 * @par Semantics
89 *
90 * Lazy readers = cht_find_lazy(), cht_find_next_lazy()
91 * Readers = lazy readers, cht_find(), cht_find_next()
92 * Updates = cht_insert(), cht_insert_unique(), cht_remove_key(),
93 * cht_remove_item()
94 *
95 * Readers (but not lazy readers) are guaranteed to see the effects
96 * of @e completed updates. In other words, if cht_find() is invoked
97 * after a cht_insert() @e returned eg on another cpu, cht_find() is
98 * guaranteed to see the inserted item.
99 *
100 * Similarly, updates see the effects of @e completed updates. For example,
101 * issuing cht_remove() after a cht_insert() for that key returned (even
102 * on another cpu) is guaranteed to remove the inserted item.
103 *
104 * Reading or updating the table concurrently with other updates
105 * always returns consistent data and never corrupts the table.
106 * However the effects of concurrent updates may or may not be
107 * visible to all other concurrent readers or updaters. Eg, not
108 * all readers may see that an item has already been inserted
109 * if cht_insert() has not yet returned.
110 *
111 * Lazy readers are guaranteed to eventually see updates but it
112 * may take some time (possibly milliseconds) after the update
113 * completes for the change to propagate to lazy readers on all
114 * cpus.
115 *
116 * @par Implementation
117 *
118 * Collisions in CHT are resolved with chaining. The number of buckets
119 * is always a power of 2. Each bucket is represented with a single linked
120 * lock-free list [1]. Items in buckets are sorted by their mixed hashes
121 * in ascending order. All buckets are terminated with a single global
122 * sentinel node whose mixed hash value is the greatest possible.
123 *
124 * CHT with 2^k buckets uses the k most significant bits of a hash value
125 * to determine the bucket number where an item is to be stored. To
126 * avoid storing all items in a single bucket if the user supplied
127 * hash function does not produce uniform hashes, hash values are
128 * mixed first so that the top bits of a mixed hash change even if hash
129 * values differ only in the least significant bits. The mixed hash
130 * values are cached in cht_link.hash (which is overwritten once the
131 * item is scheduled for removal via rcu_call).
132 *
133 * A new item is inserted before all other existing items in the bucket
134 * with the same hash value as the newly inserted item (a la the original
135 * lock-free list [2]). Placing new items at the start of a same-hash
136 * sequence of items (eg duplicates) allows us to easily check for duplicates
137 * in cht_insert_unique(). The function can first check that there are
138 * no duplicates of the newly inserted item amongst the items with the
139 * same hash as the new item. If there were no duplicates the new item
140 * is linked before the same-hash items. Inserting a duplicate while
141 * the function is checking for duplicates is detected as a change of
142 * the link to the first checked same-hash item (and the search for
143 * duplicates can be restarted).
144 *
145 * @par Table resize algorithm
146 *
147 * Table resize is based on [3] and [5]. First, a new bucket head array
148 * is allocated and initialized. Second, old bucket heads are moved
149 * to the new bucket head array with the protocol mentioned in [5].
150 * At this point updaters start using the new bucket heads. Third,
151 * buckets are split (or joined) so that the table can make use of
152 * the extra bucket head slots in the new array (or stop wasting space
153 * with the unnecessary extra slots in the old array). Splitting
154 * or joining buckets employs a custom protocol. Last, the new array
155 * replaces the original bucket array.
156 *
157 * A single background work item (of the system work queue) guides
158 * resizing of the table. If an updater detects that the bucket it
159 * is about to access is undergoing a resize (ie its head is moving
160 * or it needs to be split/joined), it helps out and completes the
161 * head move or the bucket split/join.
162 *
163 * The table always grows or shrinks by a factor of 2. Because items
164 * are assigned a bucket based on the top k bits of their mixed hash
165 * values, when growing the table each bucket is split into two buckets
166 * and all items of the two new buckets come from the single bucket in the
167 * original table. Ie items from separate buckets in the original table
168 * never intermix in the new buckets. Moreover
169 * since the buckets are sorted by their mixed hash values the items
170 * at the beginning of the old bucket will end up in the first new
171 * bucket while all the remaining items of the old bucket will end up
172 * in the second new bucket. Therefore, there is a single point where
173 * to split the linked list of the old bucket into two correctly sorted
174 * linked lists of the new buckets:
175 * .- bucket split
176 * |
177 * <-- first --> v <-- second -->
178 * [old] --> [00b] -> [01b] -> [10b] -> [11b] -> sentinel
179 * ^ ^
180 * [new0] -- -+ |
181 * [new1] -- -- -- -- -- -- -- -+
182 *
183 * Resize in greater detail:
184 *
185 * a) First, a resizer (a single background system work queue item
186 * in charge of resizing the table) allocates and initializes a new
187 * bucket head array. New bucket heads are pointed to the sentinel
188 * and marked Invalid (in the lower order bits of the pointer to the
189 * next item, ie the sentinel in this case):
190 *
191 * [old, N] --> [00b] -> [01b] -> [10b] -> [11b] -> sentinel
192 * ^ ^
193 * [new0, Inv] -------------------------------------+ |
194 * [new1, Inv] ---------------------------------------+
195 *
196 *
197 * b) Second, the resizer starts moving old bucket heads with the following
198 * lock-free protocol (from [5]) where cas(variable, expected_val, new_val)
199 * is short for compare-and-swap:
200 *
201 * old head new0 head transition to next state
202 * -------- --------- ------------------------
203 * addr, N sentinel, Inv cas(old, (addr, N), (addr, Const))
204 * .. mark the old head as immutable, so that
205 * updaters do not relink it to other nodes
206 * until the head move is done.
207 * addr, Const sentinel, Inv cas(new0, (sentinel, Inv), (addr, N))
208 * .. move the address to the new head and mark
209 * the new head normal so updaters can start
210 * using it.
211 * addr, Const addr, N cas(old, (addr, Const), (addr, Inv))
212 * .. mark the old head Invalid to signify
213 * the head move is done.
214 * addr, Inv addr, N
215 *
216 * Notice that concurrent updaters may step in at any point and correctly
217 * complete the head move without disrupting the resizer. At worst, the
218 * resizer or other concurrent updaters will attempt a number of CAS() that
219 * will correctly fail.
220 *
221 * [old, Inv] -> [00b] -> [01b] -> [10b] -> [11b] -> sentinel
222 * ^ ^
223 * [new0, N] ----+ |
224 * [new1, Inv] --------------------------------------+
225 *
226 *
227 * c) Third, buckets are split if the table is growing; or joined if
228 * shrinking (by the resizer or updaters depending on whoever accesses
229 * the bucket first). See split_bucket() and join_buckets() for details.
230 *
231 * 1) Mark the last item of new0 with JOIN_FOLLOWS:
232 * [old, Inv] -> [00b] -> [01b, JF] -> [10b] -> [11b] -> sentinel
233 * ^ ^
234 * [new0, N] ----+ |
235 * [new1, Inv] ------------------------------------------+
236 *
237 * 2) Mark the first item of new1 with JOIN_NODE:
238 * [old, Inv] -> [00b] -> [01b, JF] -> [10b, JN] -> [11b] -> sentinel
239 * ^ ^
240 * [new0, N] ----+ |
241 * [new1, Inv] ----------------------------------------------+
242 *
243 * 3) Point new1 to the join-node and mark new1 NORMAL.
244 * [old, Inv] -> [00b] -> [01b, JF] -> [10b, JN] -> [11b] -> sentinel
245 * ^ ^
246 * [new0, N] ----+ |
247 * [new1, N] --------------------------+
248 *
249 *
250 * d) Fourth, the resizer cleans up extra marks added during bucket
251 * splits/joins but only when it is sure all updaters are accessing
252 * the table via the new bucket heads only (ie it is certain there
253 * are no delayed updaters unaware of the resize and accessing the
254 * table via the old bucket head).
255 *
256 * [old, Inv] ---+
257 * v
258 * [new0, N] --> [00b] -> [01b, N] ---+
259 * v
260 * [new1, N] --> [10b, N] -> [11b] -> sentinel
261 *
262 *
263 * e) Last, the resizer publishes the new bucket head array for everyone
264 * to see and use. This signals the end of the resize and the old bucket
265 * array is freed.
266 *
267 *
268 * To understand details of how the table is resized, read [1, 3, 5]
269 * and comments in join_buckets(), split_bucket().
270 *
271 *
272 * [1] High performance dynamic lock-free hash tables and list-based sets,
273 * Michael, 2002
274 * http://www.research.ibm.com/people/m/michael/spaa-2002.pdf
275 * [2] Lock-free linked lists using compare-and-swap,
276 * Valois, 1995
277 * http://people.csail.mit.edu/bushl2/rpi/portfolio/lockfree-grape/documents/lock-free-linked-lists.pdf
278 * [3] Resizable, scalable, concurrent hash tables via relativistic programming,
279 * Triplett, 2011
280 * http://www.usenix.org/event/atc11/tech/final_files/Triplett.pdf
281 * [4] Split-ordered Lists: Lock-free Extensible Hash Tables,
282 * Shavit, 2006
283 * http://www.cs.ucf.edu/~dcm/Teaching/COT4810-Spring2011/Literature/SplitOrderedLists.pdf
284 * [5] Towards a Scalable Non-blocking Coding Style,
285 * Click, 2008
286 * http://www.azulsystems.com/events/javaone_2008/2008_CodingNonBlock.pdf
287 */
288
289
290#include <adt/cht.h>
291#include <adt/hash.h>
292#include <debug.h>
293#include <memstr.h>
294#include <mm/slab.h>
295#include <arch/barrier.h>
296#include <compiler/barrier.h>
297#include <atomic.h>
298#include <synch/rcu.h>
299
300
301/* Logarithm of the min bucket count. Must be at least 3. 2^6 == 64 buckets. */
302#define CHT_MIN_ORDER 6
303/* Logarithm of the max bucket count. */
304#define CHT_MAX_ORDER (8 * sizeof(size_t))
305/* Minimum number of hash table buckets. */
306#define CHT_MIN_BUCKET_CNT (1 << CHT_MIN_ORDER)
307/* Does not have to be a power of 2. */
308#define CHT_MAX_LOAD 2
309
310typedef cht_ptr_t marked_ptr_t;
311typedef bool (*equal_pred_t)(void *arg, const cht_link_t *item);
312
313/** The following mark items and bucket heads.
314 *
315 * They are stored in the two low order bits of the next item pointers.
316 * Some marks may be combined. Some marks share the same binary value and
317 * are distinguished only by context (eg bucket head vs an ordinary item),
318 * in particular by walk_mode_t.
319 */
320typedef enum mark {
321 /** Normal non-deleted item or a valid bucket head. */
322 N_NORMAL = 0,
323 /** Logically deleted item that might have already been unlinked.
324 *
325 * May be combined with N_JOIN and N_JOIN_FOLLOWS. Applicable only
326 * to items; never to bucket heads.
327 *
328 * Once marked deleted an item remains marked deleted.
329 */
330 N_DELETED = 1,
331 /** Immutable bucket head.
332 *
333 * The bucket is being moved or joined with another and its (old) head
334 * must not be modified.
335 *
336 * May be combined with N_INVALID. Applicable only to old bucket heads,
337 * ie cht_t.b and not cht_t.new_b.
338 */
339 N_CONST = 1,
340 /** Invalid bucket head. The bucket head must not be modified.
341 *
342 * Old bucket heads (ie cht_t.b) are marked invalid if they have
343 * already been moved to cht_t.new_b or if the bucket had already
344 * been merged with another when shrinking the table. New bucket
345 * heads (ie cht_t.new_b) are marked invalid if the old bucket had
346 * not yet been moved or if an old bucket had not yet been split
347 * when growing the table.
348 */
349 N_INVALID = 3,
350 /** The item is a join node, ie joining two buckets
351 *
352 * A join node is either the first node of the second part of
353 * a bucket to be split; or it is the first node of the bucket
354 * to be merged into/appended to/joined with another bucket.
355 *
356 * May be combined with N_DELETED. Applicable only to items, never
357 * to bucket heads.
358 *
359 * Join nodes are referred to from two different buckets and may,
360 * therefore, not be safely/atomically unlinked from both buckets.
361 * As a result join nodes are not unlinked but rather just marked
362 * deleted. Once resize completes join nodes marked deleted are
363 * garbage collected.
364 */
365 N_JOIN = 2,
366 /** The next node is a join node and will soon be marked so.
367 *
368 * A join-follows node is the last node of the first part of bucket
369 * that is to be split, ie it is the last node that will remain
370 * in the same bucket after splitting it.
371 *
372 * May be combined with N_DELETED. Applicable to items as well
373 * as to bucket heads of the bucket to be split (but only in cht_t.new_b).
374 */
375 N_JOIN_FOLLOWS = 2,
376 /** Bit mask to filter out the address to the next item from the next ptr. */
377 N_MARK_MASK = 3
378} mark_t;
379
380/** Determines */
381typedef enum walk_mode {
382 /** The table is not resizing. */
383 WM_NORMAL = 4,
384 /** The table is undergoing a resize. Join nodes may be encountered. */
385 WM_LEAVE_JOIN,
386 /** The table is growing. A join-follows node may be encountered. */
387 WM_MOVE_JOIN_FOLLOWS
388} walk_mode_t;
389
390/** Bucket position window. */
391typedef struct wnd {
392 /** Pointer to cur's predecessor. */
393 marked_ptr_t *ppred;
394 /** Current item. */
395 cht_link_t *cur;
396 /** Last encountered item. Deleted or not. */
397 cht_link_t *last;
398} wnd_t;
399
400
401/* Sentinel node used by all buckets. Stores the greatest possible hash value.*/
402static const cht_link_t sentinel = {
403 /* NULL and N_NORMAL */
404 .link = 0 | N_NORMAL,
405 .hash = -1
406};
407
408
409static size_t size_to_order(size_t bucket_cnt, size_t min_order);
410static cht_buckets_t *alloc_buckets(size_t order, bool set_invalid,
411 bool can_block);
412static inline cht_link_t *find_lazy(cht_t *h, void *key);
413static cht_link_t *search_bucket(cht_t *h, marked_ptr_t head, void *key,
414 size_t search_hash);
415static cht_link_t *find_resizing(cht_t *h, void *key, size_t hash,
416 marked_ptr_t old_head, size_t old_idx);
417static bool insert_impl(cht_t *h, cht_link_t *item, cht_link_t **dup_item);
418static bool insert_at(cht_link_t *item, const wnd_t *wnd, walk_mode_t walk_mode,
419 bool *resizing);
420static bool has_duplicate(cht_t *h, const cht_link_t *item, size_t hash,
421 cht_link_t *cur, cht_link_t **dup_item);
422static cht_link_t *find_duplicate(cht_t *h, const cht_link_t *item, size_t hash,
423 cht_link_t *start);
424static bool remove_pred(cht_t *h, size_t hash, equal_pred_t pred, void *pred_arg);
425static bool delete_at(cht_t *h, wnd_t *wnd, walk_mode_t walk_mode,
426 bool *deleted_but_gc, bool *resizing);
427static bool mark_deleted(cht_link_t *cur, walk_mode_t walk_mode, bool *resizing);
428static bool unlink_from_pred(wnd_t *wnd, walk_mode_t walk_mode, bool *resizing);
429static bool find_wnd_and_gc_pred(cht_t *h, size_t hash, walk_mode_t walk_mode,
430 equal_pred_t pred, void *pred_arg, wnd_t *wnd, bool *resizing);
431static bool find_wnd_and_gc(cht_t *h, size_t hash, walk_mode_t walk_mode,
432 wnd_t *wnd, bool *resizing);
433static bool gc_deleted_node(cht_t *h, walk_mode_t walk_mode, wnd_t *wnd,
434 bool *resizing);
435static bool join_completed(cht_t *h, const wnd_t *wnd);
436static void upd_resizing_head(cht_t *h, size_t hash, marked_ptr_t **phead,
437 bool *join_finishing, walk_mode_t *walk_mode);
438static void item_removed(cht_t *h);
439static void item_inserted(cht_t *h);
440static void free_later(cht_t *h, cht_link_t *item);
441static void help_head_move(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head);
442static void start_head_move(marked_ptr_t *psrc_head);
443static void mark_const(marked_ptr_t *psrc_head);
444static void complete_head_move(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head);
445static void split_bucket(cht_t *h, marked_ptr_t *psrc_head,
446 marked_ptr_t *pdest_head, size_t split_hash);
447static void mark_join_follows(cht_t *h, marked_ptr_t *psrc_head,
448 size_t split_hash, wnd_t *wnd);
449static void mark_join_node(cht_link_t *join_node);
450static void join_buckets(cht_t *h, marked_ptr_t *psrc_head,
451 marked_ptr_t *pdest_head, size_t split_hash);
452static void link_to_join_node(cht_t *h, marked_ptr_t *pdest_head,
453 cht_link_t *join_node, size_t split_hash);
454static void resize_table(work_t *arg);
455static void grow_table(cht_t *h);
456static void shrink_table(cht_t *h);
457static void cleanup_join_node(cht_t *h, marked_ptr_t *new_head);
458static void clear_join_and_gc(cht_t *h, cht_link_t *join_node,
459 marked_ptr_t *new_head);
460static void cleanup_join_follows(cht_t *h, marked_ptr_t *new_head);
461static marked_ptr_t make_link(const cht_link_t *next, mark_t mark);
462static cht_link_t * get_next(marked_ptr_t link);
463static mark_t get_mark(marked_ptr_t link);
464static void next_wnd(wnd_t *wnd);
465static bool same_node_pred(void *node, const cht_link_t *item2);
466static size_t calc_key_hash(cht_t *h, void *key);
467static size_t node_hash(cht_t *h, const cht_link_t *item);
468static size_t calc_node_hash(cht_t *h, const cht_link_t *item);
469static void memoize_node_hash(cht_t *h, cht_link_t *item);
470static size_t calc_split_hash(size_t split_idx, size_t order);
471static size_t calc_bucket_idx(size_t hash, size_t order);
472static size_t grow_to_split_idx(size_t old_idx);
473static size_t grow_idx(size_t idx);
474static size_t shrink_idx(size_t idx);
475static marked_ptr_t cas_link(marked_ptr_t *link, const cht_link_t *cur_next,
476 mark_t cur_mark, const cht_link_t *new_next, mark_t new_mark);
477static marked_ptr_t _cas_link(marked_ptr_t *link, marked_ptr_t cur,
478 marked_ptr_t new);
479static void cas_order_barrier(void);
480
481static void dummy_remove_callback(cht_link_t *item)
482{
483 /* empty */
484}
485
486/** Creates a concurrent hash table.
487 *
488 * @param h Valid pointer to a cht_t instance.
489 * @param op Item specific operations. All operations are compulsory.
490 * @return True if successfully created the table. False otherwise.
491 */
492bool cht_create_simple(cht_t *h, cht_ops_t *op)
493{
494 return cht_create(h, 0, 0, 0, false, op);
495}
496
497/** Creates a concurrent hash table.
498 *
499 * @param h Valid pointer to a cht_t instance.
500 * @param init_size The initial number of buckets the table should contain.
501 * The table may be shrunk below this value if deemed necessary.
502 * Uses the default value if 0.
503 * @param min_size Minimum number of buckets that the table should contain.
504 * The number of buckets never drops below this value,
505 * although it may be rounded up internally as appropriate.
506 * Uses the default value if 0.
507 * @param max_load Maximum average number of items per bucket that allowed
508 * before the table grows.
509 * @param can_block If true creating the table blocks until enough memory
510 * is available (possibly indefinitely). Otherwise,
511 * table creation does not block and returns immediately
512 * even if not enough memory is available.
513 * @param op Item specific operations. All operations are compulsory.
514 * @return True if successfully created the table. False otherwise.
515 */
516bool cht_create(cht_t *h, size_t init_size, size_t min_size, size_t max_load,
517 bool can_block, cht_ops_t *op)
518{
519 ASSERT(h);
520 ASSERT(op && op->hash && op->key_hash && op->equal && op->key_equal);
521 /* Memoized hashes are stored in the rcu_link.func function pointer. */
522 ASSERT(sizeof(size_t) == sizeof(rcu_func_t));
523 ASSERT(sentinel.hash == (uintptr_t)sentinel.rcu_link.func);
524
525 /* All operations are compulsory. */
526 if (!op || !op->hash || !op->key_hash || !op->equal || !op->key_equal)
527 return false;
528
529 size_t min_order = size_to_order(min_size, CHT_MIN_ORDER);
530 size_t order = size_to_order(init_size, min_order);
531
532 h->b = alloc_buckets(order, false, can_block);
533
534 if (!h->b)
535 return false;
536
537 h->max_load = (max_load == 0) ? CHT_MAX_LOAD : max_load;
538 h->min_order = min_order;
539 h->new_b = NULL;
540 h->op = op;
541 atomic_set(&h->item_cnt, 0);
542 atomic_set(&h->resize_reqs, 0);
543
544 if (NULL == op->remove_callback) {
545 h->op->remove_callback = dummy_remove_callback;
546 }
547
548 /*
549 * Cached item hashes are stored in item->rcu_link.func. Once the item
550 * is deleted rcu_link.func will contain the value of invalid_hash.
551 */
552 h->invalid_hash = (uintptr_t)h->op->remove_callback;
553
554 /* Ensure the initialization takes place before we start using the table. */
555 write_barrier();
556
557 return true;
558}
559
560/** Allocates and initializes 2^order buckets.
561 *
562 * All bucket heads are initialized to point to the sentinel node.
563 *
564 * @param order The number of buckets to allocate is 2^order.
565 * @param set_invalid Bucket heads are marked invalid if true; otherwise
566 * they are marked N_NORMAL.
567 * @param can_block If true memory allocation blocks until enough memory
568 * is available (possibly indefinitely). Otherwise,
569 * memory allocation does not block.
570 * @return Newly allocated and initialized buckets or NULL if not enough memory.
571 */
572static cht_buckets_t *alloc_buckets(size_t order, bool set_invalid, bool can_block)
573{
574 size_t bucket_cnt = (1 << order);
575 size_t bytes =
576 sizeof(cht_buckets_t) + (bucket_cnt - 1) * sizeof(marked_ptr_t);
577 cht_buckets_t *b = malloc(bytes, can_block ? 0 : FRAME_ATOMIC);
578
579 if (!b)
580 return NULL;
581
582 b->order = order;
583
584 marked_ptr_t head_link = set_invalid
585 ? make_link(&sentinel, N_INVALID)
586 : make_link(&sentinel, N_NORMAL);
587
588 for (size_t i = 0; i < bucket_cnt; ++i) {
589 b->head[i] = head_link;
590 }
591
592 return b;
593}
594
595/** Returns the smallest k such that bucket_cnt <= 2^k and min_order <= k.*/
596static size_t size_to_order(size_t bucket_cnt, size_t min_order)
597{
598 size_t order = min_order;
599
600 /* Find a power of two such that bucket_cnt <= 2^order */
601 do {
602 if (bucket_cnt <= ((size_t)1 << order))
603 return order;
604
605 ++order;
606 } while (order < CHT_MAX_ORDER);
607
608 return order;
609}
610
611/** Destroys a CHT successfully created via cht_create().
612 *
613 * Waits for all outstanding concurrent operations to complete and
614 * frees internal allocated resources. The table is however not cleared
615 * and items already present in the table (if any) are leaked.
616 */
617void cht_destroy(cht_t *h)
618{
619 /* Wait for resize to complete. */
620 while (0 < atomic_get(&h->resize_reqs)) {
621 rcu_barrier();
622 }
623
624 /* Wait for all remove_callback()s to complete. */
625 rcu_barrier();
626
627 free(h->b);
628 h->b = NULL;
629
630 /* You must clear the table of items. Otherwise cht_destroy will leak. */
631 ASSERT(atomic_get(&h->item_cnt) == 0);
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 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
1682#if 0
1683static void move_head(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head)
1684{
1685 start_head_move(psrc_head);
1686 cas_order_barrier();
1687 complete_head_move(psrc_head, pdest_head);
1688}
1689#endif
1690
1691/** Moves an immutable head \a psrc_head of cht_t.b to \a pdest_head of cht_t.new_b.
1692 *
1693 * The function guarantees the move will be visible on this cpu once
1694 * it completes. In particular, *pdest_head will not be N_INVALID.
1695 *
1696 * Unlike complete_head_move(), help_head_move() checks if the head had already
1697 * been moved and tries to avoid moving the bucket heads if possible.
1698 */
1699static inline void help_head_move(marked_ptr_t *psrc_head,
1700 marked_ptr_t *pdest_head)
1701{
1702 /* Head move has to in progress already when calling this func. */
1703 ASSERT(N_CONST & get_mark(*psrc_head));
1704
1705 /* Head already moved. */
1706 if (N_INVALID == get_mark(*psrc_head)) {
1707 /* Effects of the head move have not yet propagated to this cpu. */
1708 if (N_INVALID == get_mark(*pdest_head)) {
1709 /* Make the move visible on this cpu. */
1710 read_barrier();
1711 }
1712 } else {
1713 complete_head_move(psrc_head, pdest_head);
1714 }
1715
1716 ASSERT(!(N_CONST & get_mark(*pdest_head)));
1717}
1718
1719/** Initiates the move of the old head \a psrc_head.
1720 *
1721 * The move may be completed with help_head_move().
1722 */
1723static void start_head_move(marked_ptr_t *psrc_head)
1724{
1725 /* Mark src head immutable. */
1726 mark_const(psrc_head);
1727}
1728
1729/** Marks the head immutable. */
1730static void mark_const(marked_ptr_t *psrc_head)
1731{
1732 marked_ptr_t ret, src_link;
1733
1734 /* Mark src head immutable. */
1735 do {
1736 cht_link_t *next = get_next(*psrc_head);
1737 src_link = make_link(next, N_NORMAL);
1738
1739 /* Mark the normal/clean src link immutable/const. */
1740 ret = cas_link(psrc_head, next, N_NORMAL, next, N_CONST);
1741 } while(ret != src_link && !(N_CONST & get_mark(ret)));
1742}
1743
1744/** Completes moving head psrc_head to pdest_head (started by start_head_move()).*/
1745static void complete_head_move(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head)
1746{
1747 ASSERT(N_JOIN_FOLLOWS != get_mark(*psrc_head));
1748 ASSERT(N_CONST & get_mark(*psrc_head));
1749
1750 cht_link_t *next = get_next(*psrc_head);
1751 marked_ptr_t ret;
1752
1753 ret = cas_link(pdest_head, &sentinel, N_INVALID, next, N_NORMAL);
1754 ASSERT(ret == make_link(&sentinel, N_INVALID) || (N_NORMAL == get_mark(ret)));
1755 cas_order_barrier();
1756
1757 ret = cas_link(psrc_head, next, N_CONST, next, N_INVALID);
1758 ASSERT(ret == make_link(next, N_CONST) || (N_INVALID == get_mark(ret)));
1759 cas_order_barrier();
1760}
1761
1762/** Splits the bucket at psrc_head and links to the remainder from pdest_head.
1763 *
1764 * Items with hashes greater or equal to \a split_hash are moved to bucket
1765 * with head at \a pdest_head.
1766 *
1767 * @param h CHT to operate on.
1768 * @param psrc_head Head of the bucket to split (in cht_t.new_b).
1769 * @param pdest_head Head of the bucket that points to the second part
1770 * of the split bucket in psrc_head. (in cht_t.new_b)
1771 * @param split_hash Hash of the first possible item in the remainder of
1772 * psrc_head, ie the smallest hash pdest_head is allowed
1773 * to point to..
1774 */
1775static void split_bucket(cht_t *h, marked_ptr_t *psrc_head,
1776 marked_ptr_t *pdest_head, size_t split_hash)
1777{
1778 /* Already split. */
1779 if (N_NORMAL == get_mark(*pdest_head))
1780 return;
1781
1782 /*
1783 * L == Last node of the first part of the split bucket. That part
1784 * remains in the original/src bucket.
1785 * F == First node of the second part of the split bucket. That part
1786 * will be referenced from the dest bucket head.
1787 *
1788 * We want to first mark a clean L as JF so that updaters unaware of
1789 * the split (or table resize):
1790 * - do not insert a new node between L and F
1791 * - do not unlink L (that is why it has to be clean/normal)
1792 * - do not unlink F
1793 *
1794 * Then we can safely mark F as JN even if it has been marked deleted.
1795 * Once F is marked as JN updaters aware of table resize will not
1796 * attempt to unlink it (JN will have two predecessors - we cannot
1797 * safely unlink from both at the same time). Updaters unaware of
1798 * ongoing resize can reach F only via L and that node is already
1799 * marked JF, so they won't unlink F.
1800 *
1801 * Last, link the new/dest head to F.
1802 *
1803 *
1804 * 0) ,-- split_hash, first hash of the dest bucket
1805 * v
1806 * [src_head | N] -> .. -> [L] -> [F]
1807 * [dest_head | Inv]
1808 *
1809 * 1) ,-- split_hash
1810 * v
1811 * [src_head | N] -> .. -> [JF] -> [F]
1812 * [dest_head | Inv]
1813 *
1814 * 2) ,-- split_hash
1815 * v
1816 * [src_head | N] -> .. -> [JF] -> [JN]
1817 * [dest_head | Inv]
1818 *
1819 * 3) ,-- split_hash
1820 * v
1821 * [src_head | N] -> .. -> [JF] -> [JN]
1822 * ^
1823 * [dest_head | N] -----------------'
1824 */
1825 wnd_t wnd;
1826
1827 rcu_read_lock();
1828
1829 /* Mark the last node of the first part of the split bucket as JF. */
1830 mark_join_follows(h, psrc_head, split_hash, &wnd);
1831 cas_order_barrier();
1832
1833 /* There are nodes in the dest bucket, ie the second part of the split. */
1834 if (wnd.cur != &sentinel) {
1835 /*
1836 * Mark the first node of the dest bucket as a join node so
1837 * updaters do not attempt to unlink it if it is deleted.
1838 */
1839 mark_join_node(wnd.cur);
1840 cas_order_barrier();
1841 } else {
1842 /*
1843 * Second part of the split bucket is empty. There are no nodes
1844 * to mark as JOIN nodes and there never will be.
1845 */
1846 }
1847
1848 /* Link the dest head to the second part of the split. */
1849 marked_ptr_t ret =
1850 cas_link(pdest_head, &sentinel, N_INVALID, wnd.cur, N_NORMAL);
1851 ASSERT(ret == make_link(&sentinel, N_INVALID) || (N_NORMAL == get_mark(ret)));
1852 cas_order_barrier();
1853
1854 rcu_read_unlock();
1855}
1856
1857/** Finds and marks the last node of psrc_head w/ hash less than split_hash.
1858 *
1859 * Finds a node in psrc_head with the greatest hash that is strictly less
1860 * than split_hash and marks it with N_JOIN_FOLLOWS.
1861 *
1862 * Returns a window pointing to that node.
1863 *
1864 * Any logically deleted nodes along the way are
1865 * garbage collected; therefore, the predecessor node (if any) will most
1866 * likely not be marked N_DELETED.
1867 *
1868 * @param h CHT to operate on.
1869 * @param psrc_head Bucket head.
1870 * @param split_hash The smallest hash a join node (ie the node following
1871 * the desired join-follows node) may have.
1872 * @param[out] wnd Points to the node marked with N_JOIN_FOLLOWS.
1873 */
1874static void mark_join_follows(cht_t *h, marked_ptr_t *psrc_head,
1875 size_t split_hash, wnd_t *wnd)
1876{
1877 /* See comment in split_bucket(). */
1878
1879 bool done;
1880 do {
1881 bool resizing = false;
1882 wnd->ppred = psrc_head;
1883 wnd->cur = get_next(*psrc_head);
1884
1885 /*
1886 * Find the split window, ie the last node of the first part of
1887 * the split bucket and the its successor - the first node of
1888 * the second part of the split bucket. Retry if GC failed.
1889 */
1890 if (!find_wnd_and_gc(h, split_hash, WM_MOVE_JOIN_FOLLOWS, wnd, &resizing))
1891 continue;
1892
1893 /* Must not report that the table is resizing if WM_MOVE_JOIN_FOLLOWS.*/
1894 ASSERT(!resizing);
1895 /*
1896 * Mark the last node of the first half of the split bucket
1897 * that a join node follows. It must be clean/normal.
1898 */
1899 marked_ptr_t ret
1900 = cas_link(wnd->ppred, wnd->cur, N_NORMAL, wnd->cur, N_JOIN_FOLLOWS);
1901
1902 /*
1903 * Successfully marked as a JF node or already marked that way (even
1904 * if also marked deleted - unlinking the node will move the JF mark).
1905 */
1906 done = (ret == make_link(wnd->cur, N_NORMAL))
1907 || (N_JOIN_FOLLOWS & get_mark(ret));
1908 } while (!done);
1909}
1910
1911/** Marks join_node with N_JOIN. */
1912static void mark_join_node(cht_link_t *join_node)
1913{
1914 /* See comment in split_bucket(). */
1915
1916 bool done;
1917 do {
1918 cht_link_t *next = get_next(join_node->link);
1919 mark_t mark = get_mark(join_node->link);
1920
1921 /*
1922 * May already be marked as deleted, but it won't be unlinked
1923 * because its predecessor is marked with JOIN_FOLLOWS or CONST.
1924 */
1925 marked_ptr_t ret
1926 = cas_link(&join_node->link, next, mark, next, mark | N_JOIN);
1927
1928 /* Successfully marked or already marked as a join node. */
1929 done = (ret == make_link(next, mark))
1930 || (N_JOIN & get_mark(ret));
1931 } while(!done);
1932}
1933
1934/** Appends the bucket at psrc_head to the bucket at pdest_head.
1935 *
1936 * @param h CHT to operate on.
1937 * @param psrc_head Bucket to merge with pdest_head.
1938 * @param pdest_head Bucket to be joined by psrc_head.
1939 * @param split_hash The smallest hash psrc_head may contain.
1940 */
1941static void join_buckets(cht_t *h, marked_ptr_t *psrc_head,
1942 marked_ptr_t *pdest_head, size_t split_hash)
1943{
1944 /* Buckets already joined. */
1945 if (N_INVALID == get_mark(*psrc_head))
1946 return;
1947 /*
1948 * F == First node of psrc_head, ie the bucket we want to append
1949 * to (ie join with) the bucket starting at pdest_head.
1950 * L == Last node of pdest_head, ie the bucket that psrc_head will
1951 * be appended to.
1952 *
1953 * (1) We first mark psrc_head immutable to signal that a join is
1954 * in progress and so that updaters unaware of the join (or table
1955 * resize):
1956 * - do not insert new nodes between the head psrc_head and F
1957 * - do not unlink F (it may already be marked deleted)
1958 *
1959 * (2) Next, F is marked as a join node. Updaters aware of table resize
1960 * will not attempt to unlink it. We cannot safely/atomically unlink
1961 * the join node because it will be pointed to from two different
1962 * buckets. Updaters unaware of resize will fail to unlink the join
1963 * node due to the head being marked immutable.
1964 *
1965 * (3) Then the tail of the bucket at pdest_head is linked to the join
1966 * node. From now on, nodes in both buckets can be found via pdest_head.
1967 *
1968 * (4) Last, mark immutable psrc_head as invalid. It signals updaters
1969 * that the join is complete and they can insert new nodes (originally
1970 * destined for psrc_head) into pdest_head.
1971 *
1972 * Note that pdest_head keeps pointing at the join node. This allows
1973 * lookups and updaters to determine if they should see a link between
1974 * the tail L and F when searching for nodes originally in psrc_head
1975 * via pdest_head. If they reach the tail of pdest_head without
1976 * encountering any nodes of psrc_head, either there were no nodes
1977 * in psrc_head to begin with or the link between L and F did not
1978 * yet propagate to their cpus. If psrc_head was empty, it remains
1979 * NULL. Otherwise psrc_head points to a join node (it will not be
1980 * unlinked until table resize completes) and updaters/lookups
1981 * should issue a read_barrier() to make the link [L]->[JN] visible.
1982 *
1983 * 0) ,-- split_hash, first hash of the src bucket
1984 * v
1985 * [dest_head | N]-> .. -> [L]
1986 * [src_head | N]--> [F] -> ..
1987 * ^
1988 * ` split_hash, first hash of the src bucket
1989 *
1990 * 1) ,-- split_hash
1991 * v
1992 * [dest_head | N]-> .. -> [L]
1993 * [src_head | C]--> [F] -> ..
1994 *
1995 * 2) ,-- split_hash
1996 * v
1997 * [dest_head | N]-> .. -> [L]
1998 * [src_head | C]--> [JN] -> ..
1999 *
2000 * 3) ,-- split_hash
2001 * v
2002 * [dest_head | N]-> .. -> [L] --+
2003 * v
2004 * [src_head | C]-------------> [JN] -> ..
2005 *
2006 * 4) ,-- split_hash
2007 * v
2008 * [dest_head | N]-> .. -> [L] --+
2009 * v
2010 * [src_head | Inv]-----------> [JN] -> ..
2011 */
2012
2013 rcu_read_lock();
2014
2015 /* Mark src_head immutable - signals updaters that bucket join started. */
2016 mark_const(psrc_head);
2017 cas_order_barrier();
2018
2019 cht_link_t *join_node = get_next(*psrc_head);
2020
2021 if (join_node != &sentinel) {
2022 mark_join_node(join_node);
2023 cas_order_barrier();
2024
2025 link_to_join_node(h, pdest_head, join_node, split_hash);
2026 cas_order_barrier();
2027 }
2028
2029 marked_ptr_t ret =
2030 cas_link(psrc_head, join_node, N_CONST, join_node, N_INVALID);
2031 ASSERT(ret == make_link(join_node, N_CONST) || (N_INVALID == get_mark(ret)));
2032 cas_order_barrier();
2033
2034 rcu_read_unlock();
2035}
2036
2037/** Links the tail of pdest_head to join_node.
2038 *
2039 * @param h CHT to operate on.
2040 * @param pdest_head Head of the bucket whose tail is to be linked to join_node.
2041 * @param join_node A node marked N_JOIN with a hash greater or equal to
2042 * split_hash.
2043 * @param split_hash The least hash that is greater than the hash of any items
2044 * (originally) in pdest_head.
2045 */
2046static void link_to_join_node(cht_t *h, marked_ptr_t *pdest_head,
2047 cht_link_t *join_node, size_t split_hash)
2048{
2049 bool done;
2050 do {
2051 wnd_t wnd = {
2052 .ppred = pdest_head,
2053 .cur = get_next(*pdest_head)
2054 };
2055
2056 bool resizing = false;
2057
2058 if (!find_wnd_and_gc(h, split_hash, WM_LEAVE_JOIN, &wnd, &resizing))
2059 continue;
2060
2061 ASSERT(!resizing);
2062
2063 if (wnd.cur != &sentinel) {
2064 /* Must be from the new appended bucket. */
2065 ASSERT(split_hash <= node_hash(h, wnd.cur)
2066 || h->invalid_hash == node_hash(h, wnd.cur));
2067 return;
2068 }
2069
2070 /* Reached the tail of pdest_head - link it to the join node. */
2071 marked_ptr_t ret =
2072 cas_link(wnd.ppred, &sentinel, N_NORMAL, join_node, N_NORMAL);
2073
2074 done = (ret == make_link(&sentinel, N_NORMAL));
2075 } while (!done);
2076}
2077
2078/** Instructs RCU to free the item once all preexisting references are dropped.
2079 *
2080 * The item is freed via op->remove_callback().
2081 */
2082static void free_later(cht_t *h, cht_link_t *item)
2083{
2084 ASSERT(item != &sentinel);
2085
2086 /*
2087 * remove_callback only works as rcu_func_t because rcu_link is the first
2088 * field in cht_link_t.
2089 */
2090 rcu_call(&item->rcu_link, (rcu_func_t)h->op->remove_callback);
2091
2092 item_removed(h);
2093}
2094
2095/** Notes that an item had been unlinked from the table and shrinks it if needed.
2096 *
2097 * If the number of items in the table drops below 1/4 of the maximum
2098 * allowed load the table is shrunk in the background.
2099 */
2100static inline void item_removed(cht_t *h)
2101{
2102 size_t items = (size_t) atomic_predec(&h->item_cnt);
2103 size_t bucket_cnt = (1 << h->b->order);
2104
2105 bool need_shrink = (items == h->max_load * bucket_cnt / 4);
2106 bool missed_shrink = (items == h->max_load * bucket_cnt / 8);
2107
2108 if ((need_shrink || missed_shrink) && h->b->order > h->min_order) {
2109 atomic_count_t resize_reqs = atomic_preinc(&h->resize_reqs);
2110 /* The first resize request. Start the resizer. */
2111 if (1 == resize_reqs) {
2112 workq_global_enqueue_noblock(&h->resize_work, resize_table);
2113 }
2114 }
2115}
2116
2117/** Notes an item had been inserted and grows the table if needed.
2118 *
2119 * The table is resized in the background.
2120 */
2121static inline void item_inserted(cht_t *h)
2122{
2123 size_t items = (size_t) atomic_preinc(&h->item_cnt);
2124 size_t bucket_cnt = (1 << h->b->order);
2125
2126 bool need_grow = (items == h->max_load * bucket_cnt);
2127 bool missed_grow = (items == 2 * h->max_load * bucket_cnt);
2128
2129 if ((need_grow || missed_grow) && h->b->order < CHT_MAX_ORDER) {
2130 atomic_count_t resize_reqs = atomic_preinc(&h->resize_reqs);
2131 /* The first resize request. Start the resizer. */
2132 if (1 == resize_reqs) {
2133 workq_global_enqueue_noblock(&h->resize_work, resize_table);
2134 }
2135 }
2136}
2137
2138/** Resize request handler. Invoked on the system work queue. */
2139static void resize_table(work_t *arg)
2140{
2141 cht_t *h = member_to_inst(arg, cht_t, resize_work);
2142
2143#ifdef CONFIG_DEBUG
2144 ASSERT(h->b);
2145 /* Make resize_reqs visible. */
2146 read_barrier();
2147 ASSERT(0 < atomic_get(&h->resize_reqs));
2148#endif
2149
2150 bool done;
2151 do {
2152 /* Load the most recent h->item_cnt. */
2153 read_barrier();
2154 size_t cur_items = (size_t) atomic_get(&h->item_cnt);
2155 size_t bucket_cnt = (1 << h->b->order);
2156 size_t max_items = h->max_load * bucket_cnt;
2157
2158 if (cur_items >= max_items && h->b->order < CHT_MAX_ORDER) {
2159 grow_table(h);
2160 } else if (cur_items <= max_items / 4 && h->b->order > h->min_order) {
2161 shrink_table(h);
2162 } else {
2163 /* Table is just the right size. */
2164 atomic_count_t reqs = atomic_predec(&h->resize_reqs);
2165 done = (reqs == 0);
2166 }
2167 } while (!done);
2168}
2169
2170/** Increases the number of buckets two-fold. Blocks until done. */
2171static void grow_table(cht_t *h)
2172{
2173 if (h->b->order >= CHT_MAX_ORDER)
2174 return;
2175
2176 h->new_b = alloc_buckets(h->b->order + 1, true, false);
2177
2178 /* Failed to alloc a new table - try next time the resizer is run. */
2179 if (!h->new_b)
2180 return;
2181
2182 /* Wait for all readers and updaters to see the initialized new table. */
2183 rcu_synchronize();
2184 size_t old_bucket_cnt = (1 << h->b->order);
2185
2186 /*
2187 * Give updaters a chance to help out with the resize. Do the minimum
2188 * work needed to announce a resize is in progress, ie start moving heads.
2189 */
2190 for (size_t idx = 0; idx < old_bucket_cnt; ++idx) {
2191 start_head_move(&h->b->head[idx]);
2192 }
2193
2194 /* Order start_head_move() wrt complete_head_move(). */
2195 cas_order_barrier();
2196
2197 /* Complete moving heads and split any buckets not yet split by updaters. */
2198 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2199 marked_ptr_t *move_dest_head = &h->new_b->head[grow_idx(old_idx)];
2200 marked_ptr_t *move_src_head = &h->b->head[old_idx];
2201
2202 /* Head move not yet completed. */
2203 if (N_INVALID != get_mark(*move_src_head)) {
2204 complete_head_move(move_src_head, move_dest_head);
2205 }
2206
2207 size_t split_idx = grow_to_split_idx(old_idx);
2208 size_t split_hash = calc_split_hash(split_idx, h->new_b->order);
2209 marked_ptr_t *split_dest_head = &h->new_b->head[split_idx];
2210
2211 split_bucket(h, move_dest_head, split_dest_head, split_hash);
2212 }
2213
2214 /*
2215 * Wait for all updaters to notice the new heads. Once everyone sees
2216 * the invalid old bucket heads they will know a resize is in progress
2217 * and updaters will modify the correct new buckets.
2218 */
2219 rcu_synchronize();
2220
2221 /* Clear the JOIN_FOLLOWS mark and remove the link between the split buckets.*/
2222 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2223 size_t new_idx = grow_idx(old_idx);
2224
2225 cleanup_join_follows(h, &h->new_b->head[new_idx]);
2226 }
2227
2228 /*
2229 * Wait for everyone to notice that buckets were split, ie link connecting
2230 * the join follows and join node has been cut.
2231 */
2232 rcu_synchronize();
2233
2234 /* Clear the JOIN mark and GC any deleted join nodes. */
2235 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2236 size_t new_idx = grow_to_split_idx(old_idx);
2237
2238 cleanup_join_node(h, &h->new_b->head[new_idx]);
2239 }
2240
2241 /* Wait for everyone to see that the table is clear of any resize marks. */
2242 rcu_synchronize();
2243
2244 cht_buckets_t *old_b = h->b;
2245 rcu_assign(h->b, h->new_b);
2246
2247 /* Wait for everyone to start using the new table. */
2248 rcu_synchronize();
2249
2250 free(old_b);
2251
2252 /* Not needed; just for increased readability. */
2253 h->new_b = NULL;
2254}
2255
2256/** Halfs the number of buckets. Blocks until done. */
2257static void shrink_table(cht_t *h)
2258{
2259 if (h->b->order <= h->min_order)
2260 return;
2261
2262 h->new_b = alloc_buckets(h->b->order - 1, true, false);
2263
2264 /* Failed to alloc a new table - try next time the resizer is run. */
2265 if (!h->new_b)
2266 return;
2267
2268 /* Wait for all readers and updaters to see the initialized new table. */
2269 rcu_synchronize();
2270
2271 size_t old_bucket_cnt = (1 << h->b->order);
2272
2273 /*
2274 * Give updaters a chance to help out with the resize. Do the minimum
2275 * work needed to announce a resize is in progress, ie start moving heads.
2276 */
2277 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2278 size_t new_idx = shrink_idx(old_idx);
2279
2280 /* This bucket should be moved. */
2281 if (grow_idx(new_idx) == old_idx) {
2282 start_head_move(&h->b->head[old_idx]);
2283 } else {
2284 /* This bucket should join the moved bucket once the move is done.*/
2285 }
2286 }
2287
2288 /* Order start_head_move() wrt to complete_head_move(). */
2289 cas_order_barrier();
2290
2291 /* Complete moving heads and join buckets with the moved buckets. */
2292 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2293 size_t new_idx = shrink_idx(old_idx);
2294 size_t move_src_idx = grow_idx(new_idx);
2295
2296 /* This bucket should be moved. */
2297 if (move_src_idx == old_idx) {
2298 /* Head move not yet completed. */
2299 if (N_INVALID != get_mark(h->b->head[old_idx])) {
2300 complete_head_move(&h->b->head[old_idx], &h->new_b->head[new_idx]);
2301 }
2302 } else {
2303 /* This bucket should join the moved bucket. */
2304 size_t split_hash = calc_split_hash(old_idx, h->b->order);
2305 join_buckets(h, &h->b->head[old_idx], &h->new_b->head[new_idx],
2306 split_hash);
2307 }
2308 }
2309
2310 /*
2311 * Wait for all updaters to notice the new heads. Once everyone sees
2312 * the invalid old bucket heads they will know a resize is in progress
2313 * and updaters will modify the correct new buckets.
2314 */
2315 rcu_synchronize();
2316
2317 /* Let everyone know joins are complete and fully visible. */
2318 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2319 size_t move_src_idx = grow_idx(shrink_idx(old_idx));
2320
2321 /* Set the invalid joinee head to NULL. */
2322 if (old_idx != move_src_idx) {
2323 ASSERT(N_INVALID == get_mark(h->b->head[old_idx]));
2324
2325 if (&sentinel != get_next(h->b->head[old_idx]))
2326 h->b->head[old_idx] = make_link(&sentinel, N_INVALID);
2327 }
2328 }
2329
2330 /* todo comment join node vs reset joinee head*/
2331 rcu_synchronize();
2332
2333 size_t new_bucket_cnt = (1 << h->new_b->order);
2334
2335 /* Clear the JOIN mark and GC any deleted join nodes. */
2336 for (size_t new_idx = 0; new_idx < new_bucket_cnt; ++new_idx) {
2337 cleanup_join_node(h, &h->new_b->head[new_idx]);
2338 }
2339
2340 /* Wait for everyone to see that the table is clear of any resize marks. */
2341 rcu_synchronize();
2342
2343 cht_buckets_t *old_b = h->b;
2344 rcu_assign(h->b, h->new_b);
2345
2346 /* Wait for everyone to start using the new table. */
2347 rcu_synchronize();
2348
2349 free(old_b);
2350
2351 /* Not needed; just for increased readability. */
2352 h->new_b = NULL;
2353}
2354
2355/** Finds and clears the N_JOIN mark from a node in new_head (if present). */
2356static void cleanup_join_node(cht_t *h, marked_ptr_t *new_head)
2357{
2358 rcu_read_lock();
2359
2360 cht_link_t *cur = get_next(*new_head);
2361
2362 while (cur != &sentinel) {
2363 /* Clear the join node's JN mark - even if it is marked as deleted. */
2364 if (N_JOIN & get_mark(cur->link)) {
2365 clear_join_and_gc(h, cur, new_head);
2366 break;
2367 }
2368
2369 cur = get_next(cur->link);
2370 }
2371
2372 rcu_read_unlock();
2373}
2374
2375/** Clears the join_node's N_JOIN mark frees it if marked N_DELETED as well. */
2376static void clear_join_and_gc(cht_t *h, cht_link_t *join_node,
2377 marked_ptr_t *new_head)
2378{
2379 ASSERT(join_node != &sentinel);
2380 ASSERT(join_node && (N_JOIN & get_mark(join_node->link)));
2381
2382 bool done;
2383
2384 /* Clear the JN mark. */
2385 do {
2386 marked_ptr_t jn_link = join_node->link;
2387 cht_link_t *next = get_next(jn_link);
2388 /* Clear the JOIN mark but keep the DEL mark if present. */
2389 mark_t cleared_mark = get_mark(jn_link) & N_DELETED;
2390
2391 marked_ptr_t ret =
2392 _cas_link(&join_node->link, jn_link, make_link(next, cleared_mark));
2393
2394 /* Done if the mark was cleared. Retry if a new node was inserted. */
2395 done = (ret == jn_link);
2396 ASSERT(ret == jn_link || (get_mark(ret) & N_JOIN));
2397 } while (!done);
2398
2399 if (!(N_DELETED & get_mark(join_node->link)))
2400 return;
2401
2402 /* The join node had been marked as deleted - GC it. */
2403
2404 /* Clear the JOIN mark before trying to unlink the deleted join node.*/
2405 cas_order_barrier();
2406
2407 size_t jn_hash = node_hash(h, join_node);
2408 do {
2409 bool resizing = false;
2410
2411 wnd_t wnd = {
2412 .ppred = new_head,
2413 .cur = get_next(*new_head)
2414 };
2415
2416 done = find_wnd_and_gc_pred(h, jn_hash, WM_NORMAL, same_node_pred,
2417 join_node, &wnd, &resizing);
2418
2419 ASSERT(!resizing);
2420 } while (!done);
2421}
2422
2423/** Finds a non-deleted node with N_JOIN_FOLLOWS and clears the mark. */
2424static void cleanup_join_follows(cht_t *h, marked_ptr_t *new_head)
2425{
2426 ASSERT(new_head);
2427
2428 rcu_read_lock();
2429
2430 wnd_t wnd = {
2431 .ppred = NULL,
2432 .cur = NULL
2433 };
2434 marked_ptr_t *cur_link = new_head;
2435
2436 /*
2437 * Find the non-deleted node with a JF mark and clear the JF mark.
2438 * The JF node may be deleted and/or the mark moved to its neighbors
2439 * at any time. Therefore, we GC deleted nodes until we find the JF
2440 * node in order to remove stale/deleted JF nodes left behind eg by
2441 * delayed threads that did not yet get a chance to unlink the deleted
2442 * JF node and move its mark.
2443 *
2444 * Note that the head may be marked JF (but never DELETED).
2445 */
2446 while (true) {
2447 bool is_jf_node = N_JOIN_FOLLOWS & get_mark(*cur_link);
2448
2449 /* GC any deleted nodes on the way - even deleted JOIN_FOLLOWS. */
2450 if (N_DELETED & get_mark(*cur_link)) {
2451 ASSERT(cur_link != new_head);
2452 ASSERT(wnd.ppred && wnd.cur && wnd.cur != &sentinel);
2453 ASSERT(cur_link == &wnd.cur->link);
2454
2455 bool dummy;
2456 bool deleted = gc_deleted_node(h, WM_MOVE_JOIN_FOLLOWS, &wnd, &dummy);
2457
2458 /* Failed to GC or collected a deleted JOIN_FOLLOWS. */
2459 if (!deleted || is_jf_node) {
2460 /* Retry from the head of the bucket. */
2461 cur_link = new_head;
2462 continue;
2463 }
2464 } else {
2465 /* Found a non-deleted JF. Clear its JF mark. */
2466 if (is_jf_node) {
2467 cht_link_t *next = get_next(*cur_link);
2468 marked_ptr_t ret =
2469 cas_link(cur_link, next, N_JOIN_FOLLOWS, &sentinel, N_NORMAL);
2470
2471 ASSERT(next == &sentinel
2472 || ((N_JOIN | N_JOIN_FOLLOWS) & get_mark(ret)));
2473
2474 /* Successfully cleared the JF mark of a non-deleted node. */
2475 if (ret == make_link(next, N_JOIN_FOLLOWS)) {
2476 break;
2477 } else {
2478 /*
2479 * The JF node had been deleted or a new node inserted
2480 * right after it. Retry from the head.
2481 */
2482 cur_link = new_head;
2483 continue;
2484 }
2485 } else {
2486 wnd.ppred = cur_link;
2487 wnd.cur = get_next(*cur_link);
2488 }
2489 }
2490
2491 /* We must encounter a JF node before we reach the end of the bucket. */
2492 ASSERT(wnd.cur && wnd.cur != &sentinel);
2493 cur_link = &wnd.cur->link;
2494 }
2495
2496 rcu_read_unlock();
2497}
2498
2499/** Returns the first possible hash following a bucket split point.
2500 *
2501 * In other words the returned hash is the smallest possible hash
2502 * the remainder of the split bucket may contain.
2503 */
2504static inline size_t calc_split_hash(size_t split_idx, size_t order)
2505{
2506 ASSERT(1 <= order && order <= 8 * sizeof(size_t));
2507 return split_idx << (8 * sizeof(size_t) - order);
2508}
2509
2510/** Returns the bucket head index given the table size order and item hash. */
2511static inline size_t calc_bucket_idx(size_t hash, size_t order)
2512{
2513 ASSERT(1 <= order && order <= 8 * sizeof(size_t));
2514 return hash >> (8 * sizeof(size_t) - order);
2515}
2516
2517/** Returns the bucket index of destination*/
2518static inline size_t grow_to_split_idx(size_t old_idx)
2519{
2520 return grow_idx(old_idx) | 1;
2521}
2522
2523/** Returns the destination index of a bucket head when the table is growing. */
2524static inline size_t grow_idx(size_t idx)
2525{
2526 return idx << 1;
2527}
2528
2529/** Returns the destination index of a bucket head when the table is shrinking.*/
2530static inline size_t shrink_idx(size_t idx)
2531{
2532 return idx >> 1;
2533}
2534
2535/** Returns a mixed hash of the search key.*/
2536static inline size_t calc_key_hash(cht_t *h, void *key)
2537{
2538 /* Mimic calc_node_hash. */
2539 return hash_mix(h->op->key_hash(key)) & ~(size_t)1;
2540}
2541
2542/** Returns a memoized mixed hash of the item. */
2543static inline size_t node_hash(cht_t *h, const cht_link_t *item)
2544{
2545 ASSERT(item->hash == h->invalid_hash
2546 || item->hash == sentinel.hash
2547 || item->hash == calc_node_hash(h, item));
2548
2549 return item->hash;
2550}
2551
2552/** Calculates and mixed the hash of the item. */
2553static inline size_t calc_node_hash(cht_t *h, const cht_link_t *item)
2554{
2555 ASSERT(item != &sentinel);
2556 /*
2557 * Clear the lowest order bit in order for sentinel's node hash
2558 * to be the greatest possible.
2559 */
2560 return hash_mix(h->op->hash(item)) & ~(size_t)1;
2561}
2562
2563/** Computes and memoizes the hash of the item. */
2564static inline void memoize_node_hash(cht_t *h, cht_link_t *item)
2565{
2566 item->hash = calc_node_hash(h, item);
2567}
2568
2569/** Packs the next pointer address and the mark into a single pointer. */
2570static inline marked_ptr_t make_link(const cht_link_t *next, mark_t mark)
2571{
2572 marked_ptr_t ptr = (marked_ptr_t) next;
2573
2574 ASSERT(!(ptr & N_MARK_MASK));
2575 ASSERT(!((unsigned)mark & ~N_MARK_MASK));
2576
2577 return ptr | mark;
2578}
2579
2580/** Strips any marks from the next item link and returns the next item's address.*/
2581static inline cht_link_t * get_next(marked_ptr_t link)
2582{
2583 return (cht_link_t*)(link & ~N_MARK_MASK);
2584}
2585
2586/** Returns the current node's mark stored in the next item link. */
2587static inline mark_t get_mark(marked_ptr_t link)
2588{
2589 return (mark_t)(link & N_MARK_MASK);
2590}
2591
2592/** Moves the window by one item so that is points to the next item. */
2593static inline void next_wnd(wnd_t *wnd)
2594{
2595 ASSERT(wnd);
2596 ASSERT(wnd->cur);
2597
2598 wnd->last = wnd->cur;
2599 wnd->ppred = &wnd->cur->link;
2600 wnd->cur = get_next(wnd->cur->link);
2601}
2602
2603/** Predicate that matches only exactly the same node. */
2604static bool same_node_pred(void *node, const cht_link_t *item2)
2605{
2606 const cht_link_t *item1 = (const cht_link_t*) node;
2607 return item1 == item2;
2608}
2609
2610/** Compare-and-swaps a next item link. */
2611static inline marked_ptr_t cas_link(marked_ptr_t *link, const cht_link_t *cur_next,
2612 mark_t cur_mark, const cht_link_t *new_next, mark_t new_mark)
2613{
2614 return _cas_link(link, make_link(cur_next, cur_mark),
2615 make_link(new_next, new_mark));
2616}
2617
2618/** Compare-and-swaps a next item link. */
2619static inline marked_ptr_t _cas_link(marked_ptr_t *link, marked_ptr_t cur,
2620 marked_ptr_t new)
2621{
2622 ASSERT(link != &sentinel.link);
2623 /*
2624 * cas(x) on the same location x on one cpu must be ordered, but do not
2625 * have to be ordered wrt to other cas(y) to a different location y
2626 * on the same cpu.
2627 *
2628 * cas(x) must act as a write barrier on x, ie if cas(x) succeeds
2629 * and is observed by another cpu, then all cpus must be able to
2630 * make the effects of cas(x) visible just by issuing a load barrier.
2631 * For example:
2632 * cpu1 cpu2 cpu3
2633 * cas(x, 0 -> 1), succeeds
2634 * cas(x, 0 -> 1), fails
2635 * MB, to order load of x in cas and store to y
2636 * y = 7
2637 * sees y == 7
2638 * loadMB must be enough to make cas(x) on cpu3 visible to cpu1, ie x == 1.
2639 *
2640 * If cas() did not work this way:
2641 * a) our head move protocol would not be correct.
2642 * b) freeing an item linked to a moved head after another item was
2643 * inserted in front of it, would require more than one grace period.
2644 *
2645 * Ad (a): In the following example, cpu1 starts moving old_head
2646 * to new_head, cpu2 completes the move and cpu3 notices cpu2
2647 * completed the move before cpu1 gets a chance to notice cpu2
2648 * had already completed the move. Our requirements for cas()
2649 * assume cpu3 will see a valid and mutable value in new_head
2650 * after issuing a load memory barrier once it has determined
2651 * the old_head's value had been successfully moved to new_head
2652 * (because it sees old_head marked invalid).
2653 *
2654 * cpu1 cpu2 cpu3
2655 * cas(old_head, <addr, N>, <addr, Const>), succeeds
2656 * cas-order-barrier
2657 * // Move from old_head to new_head started, now the interesting stuff:
2658 * cas(new_head, <0, Inv>, <addr, N>), succeeds
2659 *
2660 * cas(new_head, <0, Inv>, <addr, N>), but fails
2661 * cas-order-barrier
2662 * cas(old_head, <addr, Const>, <addr, Inv>), succeeds
2663 *
2664 * Sees old_head marked Inv (by cpu2)
2665 * load-MB
2666 * assert(new_head == <addr, N>)
2667 *
2668 * cas-order-barrier
2669 *
2670 * Even though cpu1 did not yet issue a cas-order-barrier, cpu1's store
2671 * to new_head (successful cas()) must be made visible to cpu3 with
2672 * a load memory barrier if cpu1's store to new_head is visible
2673 * on another cpu (cpu2) and that cpu's (cpu2's) store to old_head
2674 * is already visible to cpu3. *
2675 */
2676 void *expected = (void*)cur;
2677
2678 /*
2679 * Use the acquire-release model, although we could probably
2680 * get away even with the relaxed memory model due to our use
2681 * of explicit memory barriers.
2682 */
2683 __atomic_compare_exchange_n((void**)link, &expected, (void *)new, false,
2684 __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE);
2685
2686 return (marked_ptr_t) expected;
2687}
2688
2689/** Orders compare-and-swaps to different memory locations. */
2690static inline void cas_order_barrier(void)
2691{
2692 /* Make sure CAS to different memory locations are ordered. */
2693 write_barrier();
2694}
2695
2696
2697/** @}
2698 */
Note: See TracBrowser for help on using the repository browser.