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

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

cht: Expanded cht_insert_unique() to return a duplicate if found.

  • Property mode set to 100644
File size: 88.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);
411static inline cht_link_t *find_lazy(cht_t *h, void *key);
412static cht_link_t *search_bucket(cht_t *h, marked_ptr_t head, void *key,
413 size_t search_hash);
414static cht_link_t *find_resizing(cht_t *h, void *key, size_t hash,
415 marked_ptr_t old_head, size_t old_idx);
416static bool insert_impl(cht_t *h, cht_link_t *item, cht_link_t **dup_item);
417static bool insert_at(cht_link_t *item, const wnd_t *wnd, walk_mode_t walk_mode,
418 bool *resizing);
419static bool has_duplicate(cht_t *h, const cht_link_t *item, size_t hash,
420 cht_link_t *cur, cht_link_t **dup_item);
421static cht_link_t *find_duplicate(cht_t *h, const cht_link_t *item, size_t hash,
422 cht_link_t *start);
423static bool remove_pred(cht_t *h, size_t hash, equal_pred_t pred, void *pred_arg);
424static bool delete_at(cht_t *h, wnd_t *wnd, walk_mode_t walk_mode,
425 bool *deleted_but_gc, bool *resizing);
426static bool mark_deleted(cht_link_t *cur, walk_mode_t walk_mode, bool *resizing);
427static bool unlink_from_pred(wnd_t *wnd, walk_mode_t walk_mode, bool *resizing);
428static bool find_wnd_and_gc_pred(cht_t *h, size_t hash, walk_mode_t walk_mode,
429 equal_pred_t pred, void *pred_arg, wnd_t *wnd, bool *resizing);
430static bool find_wnd_and_gc(cht_t *h, size_t hash, walk_mode_t walk_mode,
431 wnd_t *wnd, bool *resizing);
432static bool gc_deleted_node(cht_t *h, walk_mode_t walk_mode, wnd_t *wnd,
433 bool *resizing);
434static bool join_completed(cht_t *h, const wnd_t *wnd);
435static void upd_resizing_head(cht_t *h, size_t hash, marked_ptr_t **phead,
436 bool *join_finishing, walk_mode_t *walk_mode);
437static void item_removed(cht_t *h);
438static void item_inserted(cht_t *h);
439static void free_later(cht_t *h, cht_link_t *item);
440static void help_head_move(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head);
441static void start_head_move(marked_ptr_t *psrc_head);
442static void mark_const(marked_ptr_t *psrc_head);
443static void complete_head_move(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head);
444static void split_bucket(cht_t *h, marked_ptr_t *psrc_head,
445 marked_ptr_t *pdest_head, size_t split_hash);
446static void mark_join_follows(cht_t *h, marked_ptr_t *psrc_head,
447 size_t split_hash, wnd_t *wnd);
448static void mark_join_node(cht_link_t *join_node);
449static void join_buckets(cht_t *h, marked_ptr_t *psrc_head,
450 marked_ptr_t *pdest_head, size_t split_hash);
451static void link_to_join_node(cht_t *h, marked_ptr_t *pdest_head,
452 cht_link_t *join_node, size_t split_hash);
453static void resize_table(work_t *arg);
454static void grow_table(cht_t *h);
455static void shrink_table(cht_t *h);
456static void cleanup_join_node(cht_t *h, marked_ptr_t *new_head);
457static void clear_join_and_gc(cht_t *h, cht_link_t *join_node,
458 marked_ptr_t *new_head);
459static void cleanup_join_follows(cht_t *h, marked_ptr_t *new_head);
460static marked_ptr_t make_link(const cht_link_t *next, mark_t mark);
461static cht_link_t * get_next(marked_ptr_t link);
462static mark_t get_mark(marked_ptr_t link);
463static void next_wnd(wnd_t *wnd);
464static bool same_node_pred(void *node, const cht_link_t *item2);
465static size_t calc_key_hash(cht_t *h, void *key);
466static size_t node_hash(cht_t *h, const cht_link_t *item);
467static size_t calc_node_hash(cht_t *h, const cht_link_t *item);
468static void memoize_node_hash(cht_t *h, cht_link_t *item);
469static size_t calc_split_hash(size_t split_idx, size_t order);
470static size_t calc_bucket_idx(size_t hash, size_t order);
471static size_t grow_to_split_idx(size_t old_idx);
472static size_t grow_idx(size_t idx);
473static size_t shrink_idx(size_t idx);
474static marked_ptr_t cas_link(marked_ptr_t *link, const cht_link_t *cur_next,
475 mark_t cur_mark, const cht_link_t *new_next, mark_t new_mark);
476static marked_ptr_t _cas_link(marked_ptr_t *link, marked_ptr_t cur,
477 marked_ptr_t new);
478static void cas_order_barrier(void);
479
480/** Creates a concurrent hash table.
481 *
482 * @param h Valid pointer to a cht_t instance.
483 * @param init_size The initial number of buckets the table should contain.
484 * The table may be shrunk below this value if deemed necessary.
485 * Uses the default value if 0.
486 * @param min_size Minimum number of buckets that the table should contain.
487 * The number of buckets never drops below this value,
488 * although it may be rounded up internally as appropriate.
489 * Uses the default value if 0.
490 * @param max_load Maximum average number of items per bucket that allowed
491 * before the table grows.
492 * @param op Item specific operations. All operations are compulsory.
493 * @return True if successfully created the table. False otherwise.
494 */
495bool cht_create(cht_t *h, size_t init_size, size_t min_size, size_t max_load,
496 cht_ops_t *op)
497{
498 ASSERT(h);
499 ASSERT(op && op->hash && op->key_hash && op->equal && op->key_equal);
500 /* Memoized hashes are stored in the rcu_link.func function pointer. */
501 ASSERT(sizeof(size_t) == sizeof(rcu_func_t));
502 ASSERT(sentinel.hash == (uintptr_t)sentinel.rcu_link.func);
503
504 /* All operations are compulsory. */
505 if (!op || !op->hash || !op->key_hash || !op->equal || !op->key_equal)
506 return false;
507
508 size_t min_order = size_to_order(min_size, CHT_MIN_ORDER);
509 size_t order = size_to_order(init_size, min_order);
510
511 h->b = alloc_buckets(order, false);
512
513 if (!h->b)
514 return false;
515
516 h->max_load = (max_load == 0) ? CHT_MAX_LOAD : max_load;
517 h->min_order = min_order;
518 h->new_b = NULL;
519 h->op = op;
520 atomic_set(&h->item_cnt, 0);
521 atomic_set(&h->resize_reqs, 0);
522 /*
523 * Cached item hashes are stored in item->rcu_link.func. Once the item
524 * is deleted rcu_link.func will contain the value of invalid_hash.
525 */
526 h->invalid_hash = (uintptr_t)h->op->remove_callback;
527
528 /* Ensure the initialization takes place before we start using the table. */
529 write_barrier();
530
531 return true;
532}
533
534/** Allocates and initializes 2^order buckets.
535 *
536 * All bucket heads are initialized to point to the sentinel node.
537 *
538 * @param order The number of buckets to allocate is 2^order.
539 * @param set_invalid Bucket heads are marked invalid if true; otherwise
540 * they are marked N_NORMAL.
541 * @return Newly allocated and initialized buckets or NULL if not enough memory.
542 */
543static cht_buckets_t *alloc_buckets(size_t order, bool set_invalid)
544{
545 size_t bucket_cnt = (1 << order);
546 size_t bytes =
547 sizeof(cht_buckets_t) + (bucket_cnt - 1) * sizeof(marked_ptr_t);
548 cht_buckets_t *b = malloc(bytes, FRAME_ATOMIC);
549
550 if (!b)
551 return NULL;
552
553 b->order = order;
554
555 marked_ptr_t head_link = set_invalid
556 ? make_link(&sentinel, N_INVALID)
557 : make_link(&sentinel, N_NORMAL);
558
559 for (size_t i = 0; i < bucket_cnt; ++i) {
560 b->head[i] = head_link;
561 }
562
563 return b;
564}
565
566/** Returns the smallest k such that bucket_cnt <= 2^k and min_order <= k.*/
567static size_t size_to_order(size_t bucket_cnt, size_t min_order)
568{
569 size_t order = min_order;
570
571 /* Find a power of two such that bucket_cnt <= 2^order */
572 do {
573 if (bucket_cnt <= ((size_t)1 << order))
574 return order;
575
576 ++order;
577 } while (order < CHT_MAX_ORDER);
578
579 return order;
580}
581
582/** Destroys a CHT successfully created via cht_create().
583 *
584 * Waits for all outstanding concurrent operations to complete and
585 * frees internal allocated resources. The table is however not cleared
586 * and items already present in the table (if any) are leaked.
587 */
588void cht_destroy(cht_t *h)
589{
590 /* Wait for resize to complete. */
591 while (0 < atomic_get(&h->resize_reqs)) {
592 rcu_barrier();
593 }
594
595 /* Wait for all remove_callback()s to complete. */
596 rcu_barrier();
597
598 free(h->b);
599 h->b = NULL;
600
601 /* You must clear the table of items. Otherwise cht_destroy will leak. */
602 ASSERT(atomic_get(&h->item_cnt) == 0);
603}
604
605/** Returns the first item equal to the search key or NULL if not found.
606 *
607 * The call must be enclosed in a rcu_read_lock() unlock() pair. The
608 * returned item is guaranteed to be allocated until rcu_read_unlock()
609 * although the item may be concurrently removed from the table by another
610 * cpu.
611 *
612 * Further items matching the key may be retrieved via cht_find_next().
613 *
614 * cht_find() sees the effects of any completed cht_remove(), cht_insert().
615 * If a concurrent remove or insert had not yet completed cht_find() may
616 * or may not see the effects of it (eg it may find an item being removed).
617 *
618 * @param h CHT to operate on.
619 * @param key Search key as defined by cht_ops_t.key_equal() and .key_hash().
620 * @return First item equal to the key or NULL if such an item does not exist.
621 */
622cht_link_t *cht_find(cht_t *h, void *key)
623{
624 /* Make the most recent changes to the table visible. */
625 read_barrier();
626 return cht_find_lazy(h, key);
627}
628
629/** Returns the first item equal to the search key or NULL if not found.
630 *
631 * Unlike cht_find(), cht_find_lazy() may not see the effects of
632 * cht_remove() or cht_insert() even though they have already completed.
633 * It may take a couple of milliseconds for those changes to propagate
634 * and become visible to cht_find_lazy(). On the other hand, cht_find_lazy()
635 * operates a bit faster than cht_find().
636 *
637 * See cht_find() for more details.
638 */
639cht_link_t *cht_find_lazy(cht_t *h, void *key)
640{
641 return find_lazy(h, key);
642}
643
644/** Finds the first item equal to the search key. */
645static inline cht_link_t *find_lazy(cht_t *h, void *key)
646{
647 ASSERT(h);
648 /* See docs to cht_find() and cht_find_lazy(). */
649 ASSERT(rcu_read_locked());
650
651 size_t hash = calc_key_hash(h, key);
652
653 cht_buckets_t *b = rcu_access(h->b);
654 size_t idx = calc_bucket_idx(hash, b->order);
655 /*
656 * No need for access_once. b->head[idx] will point to an allocated node
657 * even if marked invalid until we exit rcu read section.
658 */
659 marked_ptr_t head = b->head[idx];
660
661 /* Undergoing a resize - take the slow path. */
662 if (N_INVALID == get_mark(head))
663 return find_resizing(h, key, hash, head, idx);
664
665 return search_bucket(h, head, key, hash);
666}
667
668/** Returns the next item matching \a item.
669 *
670 * Must be enclosed in a rcu_read_lock()/unlock() pair. Effects of
671 * completed cht_remove(), cht_insert() are guaranteed to be visible
672 * to cht_find_next().
673 *
674 * See cht_find() for more details.
675 */
676cht_link_t *cht_find_next(cht_t *h, const cht_link_t *item)
677{
678 /* Make the most recent changes to the table visible. */
679 read_barrier();
680 return cht_find_next_lazy(h, item);
681}
682
683/** Returns the next item matching \a item.
684 *
685 * Must be enclosed in a rcu_read_lock()/unlock() pair. Effects of
686 * completed cht_remove(), cht_insert() may or may not be visible
687 * to cht_find_next_lazy().
688 *
689 * See cht_find_lazy() for more details.
690 */
691cht_link_t *cht_find_next_lazy(cht_t *h, const cht_link_t *item)
692{
693 ASSERT(h);
694 ASSERT(rcu_read_locked());
695 ASSERT(item);
696
697 return find_duplicate(h, item, calc_node_hash(h, item), get_next(item->link));
698}
699
700/** Searches the bucket at head for key using search_hash. */
701static inline cht_link_t *search_bucket(cht_t *h, marked_ptr_t head, void *key,
702 size_t search_hash)
703{
704 /*
705 * It is safe to access nodes even outside of this bucket (eg when
706 * splitting the bucket). The resizer makes sure that any node we
707 * may find by following the next pointers is allocated.
708 */
709
710 cht_link_t *cur = NULL;
711 marked_ptr_t prev = head;
712
713try_again:
714 /* Filter out items with different hashes. */
715 do {
716 cur = get_next(prev);
717 ASSERT(cur);
718 prev = cur->link;
719 } while (node_hash(h, cur) < search_hash);
720
721 /*
722 * Only search for an item with an equal key if cur is not the sentinel
723 * node or a node with a different hash.
724 */
725 while (node_hash(h, cur) == search_hash) {
726 if (h->op->key_equal(key, cur)) {
727 if (!(N_DELETED & get_mark(cur->link)))
728 return cur;
729 }
730
731 cur = get_next(cur->link);
732 ASSERT(cur);
733 }
734
735 /*
736 * In the unlikely case that we have encountered a node whose cached
737 * hash has been overwritten due to a pending rcu_call for it, skip
738 * the node and try again.
739 */
740 if (node_hash(h, cur) == h->invalid_hash) {
741 prev = cur->link;
742 goto try_again;
743 }
744
745 return NULL;
746}
747
748/** Searches for the key while the table is undergoing a resize. */
749static cht_link_t *find_resizing(cht_t *h, void *key, size_t hash,
750 marked_ptr_t old_head, size_t old_idx)
751{
752 ASSERT(N_INVALID == get_mark(old_head));
753 ASSERT(h->new_b);
754
755 size_t new_idx = calc_bucket_idx(hash, h->new_b->order);
756 marked_ptr_t new_head = h->new_b->head[new_idx];
757 marked_ptr_t search_head = new_head;
758
759 /* Growing. */
760 if (h->b->order < h->new_b->order) {
761 /*
762 * Old bucket head is invalid, so it must have been already
763 * moved. Make the new head visible if still not visible, ie
764 * invalid.
765 */
766 if (N_INVALID == get_mark(new_head)) {
767 /*
768 * We should be searching a newly added bucket but the old
769 * moved bucket has not yet been split (its marked invalid)
770 * or we have not yet seen the split.
771 */
772 if (grow_idx(old_idx) != new_idx) {
773 /*
774 * Search the moved bucket. It is guaranteed to contain
775 * items of the newly added bucket that were present
776 * before the moved bucket was split.
777 */
778 new_head = h->new_b->head[grow_idx(old_idx)];
779 }
780
781 /* new_head is now the moved bucket, either valid or invalid. */
782
783 /*
784 * The old bucket was definitely moved to new_head but the
785 * change of new_head had not yet propagated to this cpu.
786 */
787 if (N_INVALID == get_mark(new_head)) {
788 /*
789 * We could issue a read_barrier() and make the now valid
790 * moved bucket head new_head visible, but instead fall back
791 * on using the old bucket. Although the old bucket head is
792 * invalid, it points to a node that is allocated and in the
793 * right bucket. Before the node can be freed, it must be
794 * unlinked from the head (or another item after that item
795 * modified the new_head) and a grace period must elapse.
796 * As a result had the node been already freed the grace
797 * period preceeding the free() would make the unlink and
798 * any changes to new_head visible. Therefore, it is safe
799 * to use the node pointed to from the old bucket head.
800 */
801
802 search_head = old_head;
803 } else {
804 search_head = new_head;
805 }
806 }
807
808 return search_bucket(h, search_head, key, hash);
809 } else if (h->b->order > h->new_b->order) {
810 /* Shrinking. */
811
812 /* Index of the bucket in the old table that was moved. */
813 size_t move_src_idx = grow_idx(new_idx);
814 marked_ptr_t moved_old_head = h->b->head[move_src_idx];
815
816 /*
817 * h->b->head[move_src_idx] had already been moved to new_head
818 * but the change to new_head had not yet propagated to us.
819 */
820 if (N_INVALID == get_mark(new_head)) {
821 /*
822 * new_head is definitely valid and we could make it visible
823 * to this cpu with a read_barrier(). Instead, use the bucket
824 * in the old table that was moved even though it is now marked
825 * as invalid. The node it points to must be allocated because
826 * a grace period would have to elapse before it could be freed;
827 * and the grace period would make the now valid new_head
828 * visible to all cpus.
829 *
830 * Note that move_src_idx may not be the same as old_idx.
831 * If move_src_idx != old_idx then old_idx is the bucket
832 * in the old table that is not moved but instead it is
833 * appended to the moved bucket, ie it is added at the tail
834 * of new_head. In that case an invalid old_head notes that
835 * it had already been merged into (the moved) new_head.
836 * We will try to search that bucket first because it
837 * may contain some newly added nodes after the bucket
838 * join. Moreover, the bucket joining link may already be
839 * visible even if new_head is not. Therefore, if we're
840 * lucky we'll find the item via moved_old_head. In any
841 * case, we'll retry in proper old_head if not found.
842 */
843 search_head = moved_old_head;
844 }
845
846 cht_link_t *ret = search_bucket(h, search_head, key, hash);
847
848 if (ret)
849 return ret;
850 /*
851 * Bucket old_head was already joined with moved_old_head
852 * in the new table but we have not yet seen change of the
853 * joining link (or the item is not in the table).
854 */
855 if (move_src_idx != old_idx && get_next(old_head) != &sentinel) {
856 /*
857 * Note that old_head (the bucket to be merged into new_head)
858 * points to an allocated join node (if non-null) even if marked
859 * invalid. Before the resizer lets join nodes to be unlinked
860 * (and freed) it sets old_head to NULL and waits for a grace period.
861 * So either the invalid old_head points to join node; or old_head
862 * is null and we would have seen a completed bucket join while
863 * traversing search_head.
864 */
865 ASSERT(N_JOIN & get_mark(get_next(old_head)->link));
866 return search_bucket(h, old_head, key, hash);
867 }
868
869 return NULL;
870 } else {
871 /*
872 * Resize is almost done. The resizer is waiting to make
873 * sure all cpus see that the new table replaced the old one.
874 */
875 ASSERT(h->b->order == h->new_b->order);
876 /*
877 * The resizer must ensure all new bucket heads are visible before
878 * replacing the old table.
879 */
880 ASSERT(N_NORMAL == get_mark(new_head));
881 return search_bucket(h, new_head, key, hash);
882 }
883}
884
885/** Inserts an item. Succeeds even if an equal item is already present. */
886void cht_insert(cht_t *h, cht_link_t *item)
887{
888 insert_impl(h, item, NULL);
889}
890
891/** Inserts a unique item. Returns false if an equal item was already present.
892 *
893 * Use this function to atomically check if an equal/duplicate item had
894 * not yet been inserted into the table and to insert this item into the
895 * table.
896 *
897 * The following is @e NOT thread-safe, so do not use:
898 * @code
899 * if (!cht_find(h, key)) {
900 * // A concurrent insert here may go unnoticed by cht_find() above.
901 * item = malloc(..);
902 * cht_insert(h, item);
903 * // Now we may have two items with equal search keys.
904 * }
905 * @endcode
906 *
907 * Replace such code with:
908 * @code
909 * item = malloc(..);
910 * if (!cht_insert_unique(h, item, &dup_item)) {
911 * // Whoops, someone beat us to it - an equal item 'dup_item'
912 * // had already been inserted.
913 * free(item);
914 * } else {
915 * // Successfully inserted the item and we are guaranteed that
916 * // there are no other equal items.
917 * }
918 * @endcode
919 *
920 */
921bool cht_insert_unique(cht_t *h, cht_link_t *item, cht_link_t **dup_item)
922{
923 ASSERT(rcu_read_locked());
924 ASSERT(dup_item);
925 return insert_impl(h, item, dup_item);
926}
927
928/** Inserts the item into the table and checks for duplicates if dup_item. */
929static bool insert_impl(cht_t *h, cht_link_t *item, cht_link_t **dup_item)
930{
931 rcu_read_lock();
932
933 cht_buckets_t *b = rcu_access(h->b);
934 memoize_node_hash(h, item);
935 size_t hash = node_hash(h, item);
936 size_t idx = calc_bucket_idx(hash, b->order);
937 marked_ptr_t *phead = &b->head[idx];
938
939 bool resizing = false;
940 bool inserted = false;
941
942 do {
943 walk_mode_t walk_mode = WM_NORMAL;
944 bool join_finishing;
945
946 resizing = resizing || (N_NORMAL != get_mark(*phead));
947
948 /* The table is resizing. Get the correct bucket head. */
949 if (resizing) {
950 upd_resizing_head(h, hash, &phead, &join_finishing, &walk_mode);
951 }
952
953 wnd_t wnd = {
954 .ppred = phead,
955 .cur = get_next(*phead),
956 .last = NULL
957 };
958
959 if (!find_wnd_and_gc(h, hash, walk_mode, &wnd, &resizing)) {
960 /* Could not GC a node; or detected an unexpected resize. */
961 continue;
962 }
963
964 if (dup_item && has_duplicate(h, item, hash, wnd.cur, dup_item)) {
965 rcu_read_unlock();
966 return false;
967 }
968
969 inserted = insert_at(item, &wnd, walk_mode, &resizing);
970 } while (!inserted);
971
972 rcu_read_unlock();
973
974 item_inserted(h);
975 return true;
976}
977
978/** Inserts item between wnd.ppred and wnd.cur.
979 *
980 * @param item Item to link to wnd.ppred and wnd.cur.
981 * @param wnd The item will be inserted before wnd.cur. Wnd.ppred
982 * must be N_NORMAL.
983 * @param walk_mode
984 * @param resizing Set to true only if the table is undergoing resize
985 * and it was not expected (ie walk_mode == WM_NORMAL).
986 * @return True if the item was successfully linked to wnd.ppred. False
987 * if whole insert operation must be retried because the predecessor
988 * of wnd.cur has changed.
989 */
990inline static bool insert_at(cht_link_t *item, const wnd_t *wnd,
991 walk_mode_t walk_mode, bool *resizing)
992{
993 marked_ptr_t ret;
994
995 if (walk_mode == WM_NORMAL) {
996 item->link = make_link(wnd->cur, N_NORMAL);
997 /* Initialize the item before adding it to a bucket. */
998 memory_barrier();
999
1000 /* Link a clean/normal predecessor to the item. */
1001 ret = cas_link(wnd->ppred, wnd->cur, N_NORMAL, item, N_NORMAL);
1002
1003 if (ret == make_link(wnd->cur, N_NORMAL)) {
1004 return true;
1005 } else {
1006 /* This includes an invalid head but not a const head. */
1007 *resizing = ((N_JOIN_FOLLOWS | N_JOIN) & get_mark(ret));
1008 return false;
1009 }
1010 } else if (walk_mode == WM_MOVE_JOIN_FOLLOWS) {
1011 /* Move JOIN_FOLLOWS mark but filter out the DELETED mark. */
1012 mark_t jf_mark = get_mark(*wnd->ppred) & N_JOIN_FOLLOWS;
1013 item->link = make_link(wnd->cur, jf_mark);
1014 /* Initialize the item before adding it to a bucket. */
1015 memory_barrier();
1016
1017 /* Link the not-deleted predecessor to the item. Move its JF mark. */
1018 ret = cas_link(wnd->ppred, wnd->cur, jf_mark, item, N_NORMAL);
1019
1020 return ret == make_link(wnd->cur, jf_mark);
1021 } else {
1022 ASSERT(walk_mode == WM_LEAVE_JOIN);
1023
1024 item->link = make_link(wnd->cur, N_NORMAL);
1025 /* Initialize the item before adding it to a bucket. */
1026 memory_barrier();
1027
1028 mark_t pred_mark = get_mark(*wnd->ppred);
1029 /* If the predecessor is a join node it may be marked deleted.*/
1030 mark_t exp_pred_mark = (N_JOIN & pred_mark) ? pred_mark : N_NORMAL;
1031
1032 ret = cas_link(wnd->ppred, wnd->cur, exp_pred_mark, item, exp_pred_mark);
1033 return ret == make_link(wnd->cur, exp_pred_mark);
1034 }
1035}
1036
1037/** Returns true if the chain starting at cur has an item equal to \a item.
1038 *
1039 * @param h CHT to operate on.
1040 * @param item Item whose duplicates the function looks for.
1041 * @param hash Hash of \a item.
1042 * @param[in] cur The first node with a hash greater to or equal to item's hash.
1043 * @param[out] dup_item The first duplicate item encountered.
1044 * @return True if a non-deleted item equal to \a item exists in the table.
1045 */
1046static inline bool has_duplicate(cht_t *h, const cht_link_t *item, size_t hash,
1047 cht_link_t *cur, cht_link_t **dup_item)
1048{
1049 ASSERT(cur);
1050 ASSERT(cur == &sentinel || hash <= node_hash(h, cur)
1051 || node_hash(h, cur) == h->invalid_hash);
1052
1053 /* hash < node_hash(h, cur) */
1054 if (hash != node_hash(h, cur) && h->invalid_hash != node_hash(h, cur))
1055 return false;
1056
1057 /*
1058 * Load the most recent node marks. Otherwise we might pronounce a
1059 * logically deleted node for a duplicate of the item just because
1060 * the deleted node's DEL mark had not yet propagated to this cpu.
1061 */
1062 read_barrier();
1063
1064 *dup_item = find_duplicate(h, item, hash, cur);
1065 return NULL != *dup_item;
1066}
1067
1068/** Returns an item that is equal to \a item starting in a chain at \a start. */
1069static cht_link_t *find_duplicate(cht_t *h, const cht_link_t *item, size_t hash,
1070 cht_link_t *start)
1071{
1072 ASSERT(hash <= node_hash(h, start) || h->invalid_hash == node_hash(h, start));
1073
1074 cht_link_t *cur = start;
1075
1076try_again:
1077 ASSERT(cur);
1078
1079 while (node_hash(h, cur) == hash) {
1080 ASSERT(cur != &sentinel);
1081
1082 bool deleted = (N_DELETED & get_mark(cur->link));
1083
1084 /* Skip logically deleted nodes. */
1085 if (!deleted && h->op->equal(item, cur))
1086 return cur;
1087
1088 cur = get_next(cur->link);
1089 ASSERT(cur);
1090 }
1091
1092 /* Skip logically deleted nodes with rcu_call() in progress. */
1093 if (h->invalid_hash == node_hash(h, cur)) {
1094 cur = get_next(cur->link);
1095 goto try_again;
1096 }
1097
1098 return NULL;
1099}
1100
1101/** Removes all items matching the search key. Returns the number of items removed.*/
1102size_t cht_remove_key(cht_t *h, void *key)
1103{
1104 ASSERT(h);
1105
1106 size_t hash = calc_key_hash(h, key);
1107 size_t removed = 0;
1108
1109 while (remove_pred(h, hash, h->op->key_equal, key))
1110 ++removed;
1111
1112 return removed;
1113}
1114
1115/** Removes a specific item from the table.
1116 *
1117 * The called must hold rcu read lock.
1118 *
1119 * @param item Item presumably present in the table and to be removed.
1120 * @return True if the item was removed successfully; or false if it had
1121 * already been deleted.
1122 */
1123bool cht_remove_item(cht_t *h, cht_link_t *item)
1124{
1125 ASSERT(h);
1126 ASSERT(item);
1127 /* Otherwise a concurrent cht_remove_key might free the item. */
1128 ASSERT(rcu_read_locked());
1129
1130 /*
1131 * Even though we know the node we want to delete we must unlink it
1132 * from the correct bucket and from a clean/normal predecessor. Therefore,
1133 * we search for it again from the beginning of the correct bucket.
1134 */
1135 size_t hash = calc_node_hash(h, item);
1136 return remove_pred(h, hash, same_node_pred, item);
1137}
1138
1139/** Removes an item equal to pred_arg according to the predicate pred. */
1140static bool remove_pred(cht_t *h, size_t hash, equal_pred_t pred, void *pred_arg)
1141{
1142 rcu_read_lock();
1143
1144 bool resizing = false;
1145 bool deleted = false;
1146 bool deleted_but_gc = false;
1147
1148 cht_buckets_t *b = rcu_access(h->b);
1149 size_t idx = calc_bucket_idx(hash, b->order);
1150 marked_ptr_t *phead = &b->head[idx];
1151
1152 do {
1153 walk_mode_t walk_mode = WM_NORMAL;
1154 bool join_finishing = false;
1155
1156 resizing = resizing || (N_NORMAL != get_mark(*phead));
1157
1158 /* The table is resizing. Get the correct bucket head. */
1159 if (resizing) {
1160 upd_resizing_head(h, hash, &phead, &join_finishing, &walk_mode);
1161 }
1162
1163 wnd_t wnd = {
1164 .ppred = phead,
1165 .cur = get_next(*phead),
1166 .last = NULL
1167 };
1168
1169 if (!find_wnd_and_gc_pred(
1170 h, hash, walk_mode, pred, pred_arg, &wnd, &resizing)) {
1171 /* Could not GC a node; or detected an unexpected resize. */
1172 continue;
1173 }
1174
1175 /*
1176 * The item lookup is affected by a bucket join but effects of
1177 * the bucket join have not been seen while searching for the item.
1178 */
1179 if (join_finishing && !join_completed(h, &wnd)) {
1180 /*
1181 * Bucket was appended at the end of another but the next
1182 * ptr linking them together was not visible on this cpu.
1183 * join_completed() makes this appended bucket visible.
1184 */
1185 continue;
1186 }
1187
1188 /* Already deleted, but delete_at() requested one GC pass. */
1189 if (deleted_but_gc)
1190 break;
1191
1192 bool found = (wnd.cur != &sentinel && pred(pred_arg, wnd.cur));
1193
1194 if (!found) {
1195 rcu_read_unlock();
1196 return false;
1197 }
1198
1199 deleted = delete_at(h, &wnd, walk_mode, &deleted_but_gc, &resizing);
1200 } while (!deleted || deleted_but_gc);
1201
1202 rcu_read_unlock();
1203 return true;
1204}
1205
1206/** Unlinks wnd.cur from wnd.ppred and schedules a deferred free for the item.
1207 *
1208 * Ignores nodes marked N_JOIN if walk mode is WM_LEAVE_JOIN.
1209 *
1210 * @param h CHT to operate on.
1211 * @param wnd Points to the item to delete and its N_NORMAL predecessor.
1212 * @param walk_mode Bucket chaing walk mode.
1213 * @param deleted_but_gc Set to true if the item had been logically deleted,
1214 * but a garbage collecting walk of the bucket is in order for
1215 * it to be fully unlinked.
1216 * @param resizing Set to true if the table is undergoing an unexpected
1217 * resize (ie walk_mode == WM_NORMAL).
1218 * @return False if the wnd.ppred changed in the meantime and the whole
1219 * delete operation must be retried.
1220 */
1221static inline bool delete_at(cht_t *h, wnd_t *wnd, walk_mode_t walk_mode,
1222 bool *deleted_but_gc, bool *resizing)
1223{
1224 ASSERT(wnd->cur && wnd->cur != &sentinel);
1225
1226 *deleted_but_gc = false;
1227
1228 if (!mark_deleted(wnd->cur, walk_mode, resizing)) {
1229 /* Already deleted, or unexpectedly marked as JOIN/JOIN_FOLLOWS. */
1230 return false;
1231 }
1232
1233 /* Marked deleted. Unlink from the bucket. */
1234
1235 /* Never unlink join nodes. */
1236 if (walk_mode == WM_LEAVE_JOIN && (N_JOIN & get_mark(wnd->cur->link)))
1237 return true;
1238
1239 cas_order_barrier();
1240
1241 if (unlink_from_pred(wnd, walk_mode, resizing)) {
1242 free_later(h, wnd->cur);
1243 } else {
1244 *deleted_but_gc = true;
1245 }
1246
1247 return true;
1248}
1249
1250/** Marks cur logically deleted. Returns false to request a retry. */
1251static inline bool mark_deleted(cht_link_t *cur, walk_mode_t walk_mode,
1252 bool *resizing)
1253{
1254 ASSERT(cur && cur != &sentinel);
1255
1256 /*
1257 * Btw, we could loop here if the cas fails but let's not complicate
1258 * things and let's retry from the head of the bucket.
1259 */
1260
1261 cht_link_t *next = get_next(cur->link);
1262
1263 if (walk_mode == WM_NORMAL) {
1264 /* Only mark clean/normal nodes - JF/JN is used only during resize. */
1265 marked_ptr_t ret = cas_link(&cur->link, next, N_NORMAL, next, N_DELETED);
1266
1267 if (ret != make_link(next, N_NORMAL)) {
1268 *resizing = (N_JOIN | N_JOIN_FOLLOWS) & get_mark(ret);
1269 return false;
1270 }
1271 } else {
1272 ASSERT(N_JOIN == N_JOIN_FOLLOWS);
1273
1274 /* Keep the N_JOIN/N_JOIN_FOLLOWS mark but strip N_DELETED. */
1275 mark_t cur_mark = get_mark(cur->link) & N_JOIN_FOLLOWS;
1276
1277 marked_ptr_t ret =
1278 cas_link(&cur->link, next, cur_mark, next, cur_mark | N_DELETED);
1279
1280 if (ret != make_link(next, cur_mark))
1281 return false;
1282 }
1283
1284 return true;
1285}
1286
1287/** Unlinks wnd.cur from wnd.ppred. Returns false if it should be retried. */
1288static inline bool unlink_from_pred(wnd_t *wnd, walk_mode_t walk_mode,
1289 bool *resizing)
1290{
1291 ASSERT(wnd->cur != &sentinel);
1292 ASSERT(wnd->cur && (N_DELETED & get_mark(wnd->cur->link)));
1293
1294 cht_link_t *next = get_next(wnd->cur->link);
1295
1296 if (walk_mode == WM_LEAVE_JOIN) {
1297 /* Never try to unlink join nodes. */
1298 ASSERT(!(N_JOIN & get_mark(wnd->cur->link)));
1299
1300 mark_t pred_mark = get_mark(*wnd->ppred);
1301 /* Succeed only if the predecessor is clean/normal or a join node. */
1302 mark_t exp_pred_mark = (N_JOIN & pred_mark) ? pred_mark : N_NORMAL;
1303
1304 marked_ptr_t pred_link = make_link(wnd->cur, exp_pred_mark);
1305 marked_ptr_t next_link = make_link(next, exp_pred_mark);
1306
1307 if (pred_link != _cas_link(wnd->ppred, pred_link, next_link))
1308 return false;
1309 } else {
1310 ASSERT(walk_mode == WM_MOVE_JOIN_FOLLOWS || walk_mode == WM_NORMAL);
1311 /* Move the JF mark if set. Clear DEL mark. */
1312 mark_t cur_mark = N_JOIN_FOLLOWS & get_mark(wnd->cur->link);
1313
1314 /* The predecessor must be clean/normal. */
1315 marked_ptr_t pred_link = make_link(wnd->cur, N_NORMAL);
1316 /* Link to cur's successor keeping/copying cur's JF mark. */
1317 marked_ptr_t next_link = make_link(next, cur_mark);
1318
1319 marked_ptr_t ret = _cas_link(wnd->ppred, pred_link, next_link);
1320
1321 if (pred_link != ret) {
1322 /* If we're not resizing the table there are no JF/JN nodes. */
1323 *resizing = (walk_mode == WM_NORMAL)
1324 && (N_JOIN_FOLLOWS & get_mark(ret));
1325 return false;
1326 }
1327 }
1328
1329 return true;
1330}
1331
1332/** Finds the first non-deleted item equal to \a pred_arg according to \a pred.
1333 *
1334 * The function returns the candidate item in \a wnd. Logically deleted
1335 * nodes are garbage collected so the predecessor will most likely not
1336 * be marked as deleted.
1337 *
1338 * Unlike find_wnd_and_gc(), this function never returns a node that
1339 * is known to have already been marked N_DELETED.
1340 *
1341 * Any logically deleted nodes (ie those marked N_DELETED) are garbage
1342 * collected, ie free in the background via rcu_call (except for join-nodes
1343 * if walk_mode == WM_LEAVE_JOIN).
1344 *
1345 * @param h CHT to operate on.
1346 * @param hash Hash the search for.
1347 * @param walk_mode Bucket chain walk mode.
1348 * @param pred Predicate used to find an item equal to pred_arg.
1349 * @param pred_arg Argument to pass to the equality predicate \a pred.
1350 * @param[in,out] wnd The search starts with wnd.cur. If the desired
1351 * item is found wnd.cur will point to it.
1352 * @param resizing Set to true if the table is resizing but it was not
1353 * expected (ie walk_mode == WM_NORMAL).
1354 * @return False if the operation has to be retried. True otherwise
1355 * (even if an equal item had not been found).
1356 */
1357static bool find_wnd_and_gc_pred(cht_t *h, size_t hash, walk_mode_t walk_mode,
1358 equal_pred_t pred, void *pred_arg, wnd_t *wnd, bool *resizing)
1359{
1360 ASSERT(wnd->cur);
1361
1362 if (wnd->cur == &sentinel)
1363 return true;
1364
1365 /*
1366 * A read barrier is not needed here to bring up the most recent
1367 * node marks (esp the N_DELETED). At worst we'll try to delete
1368 * an already deleted node; fail in delete_at(); and retry.
1369 */
1370
1371 size_t cur_hash;
1372
1373try_again:
1374 cur_hash = node_hash(h, wnd->cur);
1375
1376 while (cur_hash <= hash) {
1377 ASSERT(wnd->cur && wnd->cur != &sentinel);
1378
1379 /* GC any deleted nodes on the way. */
1380 if (N_DELETED & get_mark(wnd->cur->link)) {
1381 if (!gc_deleted_node(h, walk_mode, wnd, resizing)) {
1382 /* Retry from the head of a bucket. */
1383 return false;
1384 }
1385 } else {
1386 /* Is this the node we were looking for? */
1387 if (cur_hash == hash && pred(pred_arg, wnd->cur))
1388 return true;
1389
1390 next_wnd(wnd);
1391 }
1392
1393 cur_hash = node_hash(h, wnd->cur);
1394 }
1395
1396 if (cur_hash == h->invalid_hash) {
1397 next_wnd(wnd);
1398 ASSERT(wnd->cur);
1399 goto try_again;
1400 }
1401
1402 /* The searched for node is not in the current bucket. */
1403 return true;
1404}
1405
1406/** Find the first item (deleted or not) with a hash greater or equal to \a hash.
1407 *
1408 * The function returns the first item with a hash that is greater or
1409 * equal to \a hash in \a wnd. Moreover it garbage collects logically
1410 * deleted node that have not yet been unlinked and freed. Therefore,
1411 * the returned node's predecessor will most likely be N_NORMAL.
1412 *
1413 * Unlike find_wnd_and_gc_pred(), this function may return a node
1414 * that is known to had been marked N_DELETED.
1415 *
1416 * @param h CHT to operate on.
1417 * @param hash Hash of the item to find.
1418 * @param walk_mode Bucket chain walk mode.
1419 * @param[in,out] wnd wnd.cur denotes the first node of the chain. If the
1420 * the operation is successful, \a wnd points to the desired
1421 * item.
1422 * @param resizing Set to true if a table resize was detected but walk_mode
1423 * suggested the table was not undergoing a resize.
1424 * @return False indicates the operation must be retried. True otherwise
1425 * (even if an item with exactly the same has was not found).
1426 */
1427static bool find_wnd_and_gc(cht_t *h, size_t hash, walk_mode_t walk_mode,
1428 wnd_t *wnd, bool *resizing)
1429{
1430try_again:
1431 ASSERT(wnd->cur);
1432
1433 while (node_hash(h, wnd->cur) < hash) {
1434 /* GC any deleted nodes along the way to our desired node. */
1435 if (N_DELETED & get_mark(wnd->cur->link)) {
1436 if (!gc_deleted_node(h, walk_mode, wnd, resizing)) {
1437 /* Failed to remove the garbage node. Retry. */
1438 return false;
1439 }
1440 } else {
1441 next_wnd(wnd);
1442 }
1443
1444 ASSERT(wnd->cur);
1445 }
1446
1447 if (node_hash(h, wnd->cur) == h->invalid_hash) {
1448 next_wnd(wnd);
1449 goto try_again;
1450 }
1451
1452 /* wnd->cur may be NULL or even marked N_DELETED. */
1453 return true;
1454}
1455
1456/** Garbage collects the N_DELETED node at \a wnd skipping join nodes. */
1457static bool gc_deleted_node(cht_t *h, walk_mode_t walk_mode, wnd_t *wnd,
1458 bool *resizing)
1459{
1460 ASSERT(N_DELETED & get_mark(wnd->cur->link));
1461
1462 /* Skip deleted JOIN nodes. */
1463 if (walk_mode == WM_LEAVE_JOIN && (N_JOIN & get_mark(wnd->cur->link))) {
1464 next_wnd(wnd);
1465 } else {
1466 /* Ordinary deleted node or a deleted JOIN_FOLLOWS. */
1467 ASSERT(walk_mode != WM_LEAVE_JOIN
1468 || !((N_JOIN | N_JOIN_FOLLOWS) & get_mark(wnd->cur->link)));
1469
1470 /* Unlink an ordinary deleted node, move JOIN_FOLLOWS mark. */
1471 if (!unlink_from_pred(wnd, walk_mode, resizing)) {
1472 /* Retry. The predecessor was deleted, invalid, const, join_follows. */
1473 return false;
1474 }
1475
1476 free_later(h, wnd->cur);
1477
1478 /* Leave ppred as is. */
1479 wnd->last = wnd->cur;
1480 wnd->cur = get_next(wnd->cur->link);
1481 }
1482
1483 return true;
1484}
1485
1486/** Returns true if a bucket join had already completed.
1487 *
1488 * May only be called if upd_resizing_head() indicates a bucket join
1489 * may be in progress.
1490 *
1491 * If it returns false, the search must be retried in order to guarantee
1492 * all item that should have been encountered have been seen.
1493 */
1494static bool join_completed(cht_t *h, const wnd_t *wnd)
1495{
1496 /*
1497 * The table is shrinking and the searched for item is in a bucket
1498 * appended to another. Check that the link joining these two buckets
1499 * is visible and if not, make it visible to this cpu.
1500 */
1501
1502 /*
1503 * Resizer ensures h->b->order stays the same for the duration of this
1504 * func. We got here because there was an alternative head to search.
1505 * The resizer waits for all preexisting readers to finish after
1506 * it
1507 */
1508 ASSERT(h->b->order > h->new_b->order);
1509 ASSERT(wnd->cur);
1510
1511 /* Either we did not need the joining link or we have already followed it.*/
1512 if (wnd->cur != &sentinel)
1513 return true;
1514
1515 /* We have reached the end of a bucket. */
1516
1517 if (wnd->last != &sentinel) {
1518 size_t last_seen_hash = node_hash(h, wnd->last);
1519
1520 if (last_seen_hash == h->invalid_hash) {
1521 last_seen_hash = calc_node_hash(h, wnd->last);
1522 }
1523
1524 size_t last_old_idx = calc_bucket_idx(last_seen_hash, h->b->order);
1525 size_t move_src_idx = grow_idx(shrink_idx(last_old_idx));
1526
1527 /*
1528 * Last node seen was in the joining bucket - if the searched
1529 * for node is there we will find it.
1530 */
1531 if (move_src_idx != last_old_idx)
1532 return true;
1533 }
1534
1535 /*
1536 * Reached the end of the bucket but no nodes from the joining bucket
1537 * were seen. There should have at least been a JOIN node so we have
1538 * definitely not seen (and followed) the joining link. Make the link
1539 * visible and retry.
1540 */
1541 read_barrier();
1542 return false;
1543}
1544
1545/** When resizing returns the bucket head to start the search with in \a phead.
1546 *
1547 * If a resize had been detected (eg cht_t.b.head[idx] is marked immutable).
1548 * upd_resizing_head() moves the bucket for \a hash from the old head
1549 * to the new head. Moreover, it splits or joins buckets as necessary.
1550 *
1551 * @param h CHT to operate on.
1552 * @param hash Hash of an item whose chain we would like to traverse.
1553 * @param[out] phead Head of the bucket to search for \a hash.
1554 * @param[out] join_finishing Set to true if a bucket join might be
1555 * in progress and the bucket may have to traversed again
1556 * as indicated by join_completed().
1557 * @param[out] walk_mode Specifies how to interpret node marks.
1558 */
1559static void upd_resizing_head(cht_t *h, size_t hash, marked_ptr_t **phead,
1560 bool *join_finishing, walk_mode_t *walk_mode)
1561{
1562 cht_buckets_t *b = rcu_access(h->b);
1563 size_t old_idx = calc_bucket_idx(hash, b->order);
1564 size_t new_idx = calc_bucket_idx(hash, h->new_b->order);
1565
1566 marked_ptr_t *pold_head = &b->head[old_idx];
1567 marked_ptr_t *pnew_head = &h->new_b->head[new_idx];
1568
1569 /* In any case, use the bucket in the new table. */
1570 *phead = pnew_head;
1571
1572 /* Growing the table. */
1573 if (b->order < h->new_b->order) {
1574 size_t move_dest_idx = grow_idx(old_idx);
1575 marked_ptr_t *pmoved_head = &h->new_b->head[move_dest_idx];
1576
1577 /* Complete moving the bucket from the old to the new table. */
1578 help_head_move(pold_head, pmoved_head);
1579
1580 /* The hash belongs to the moved bucket. */
1581 if (move_dest_idx == new_idx) {
1582 ASSERT(pmoved_head == pnew_head);
1583 /*
1584 * move_head() makes the new head of the moved bucket visible.
1585 * The new head may be marked with a JOIN_FOLLOWS
1586 */
1587 ASSERT(!(N_CONST & get_mark(*pmoved_head)));
1588 *walk_mode = WM_MOVE_JOIN_FOLLOWS;
1589 } else {
1590 ASSERT(pmoved_head != pnew_head);
1591 /*
1592 * The hash belongs to the bucket that is the result of splitting
1593 * the old/moved bucket, ie the bucket that contains the second
1594 * half of the split/old/moved bucket.
1595 */
1596
1597 /* The moved bucket has not yet been split. */
1598 if (N_NORMAL != get_mark(*pnew_head)) {
1599 size_t split_hash = calc_split_hash(new_idx, h->new_b->order);
1600 split_bucket(h, pmoved_head, pnew_head, split_hash);
1601 /*
1602 * split_bucket() makes the new head visible. No
1603 * JOIN_FOLLOWS in this part of split bucket.
1604 */
1605 ASSERT(N_NORMAL == get_mark(*pnew_head));
1606 }
1607
1608 *walk_mode = WM_LEAVE_JOIN;
1609 }
1610 } else if (h->new_b->order < b->order ) {
1611 /* Shrinking the table. */
1612
1613 size_t move_src_idx = grow_idx(new_idx);
1614
1615 /*
1616 * Complete moving the bucket from the old to the new table.
1617 * Makes a valid pnew_head visible if already moved.
1618 */
1619 help_head_move(&b->head[move_src_idx], pnew_head);
1620
1621 /* Hash belongs to the bucket to be joined with the moved bucket. */
1622 if (move_src_idx != old_idx) {
1623 /* Bucket join not yet completed. */
1624 if (N_INVALID != get_mark(*pold_head)) {
1625 size_t split_hash = calc_split_hash(old_idx, b->order);
1626 join_buckets(h, pold_head, pnew_head, split_hash);
1627 }
1628
1629 /*
1630 * The resizer sets pold_head to &sentinel when all cpus are
1631 * guaranteed to see the bucket join.
1632 */
1633 *join_finishing = (&sentinel != get_next(*pold_head));
1634 }
1635
1636 /* move_head() or join_buckets() makes it so or makes the mark visible.*/
1637 ASSERT(N_INVALID == get_mark(*pold_head));
1638 /* move_head() makes it visible. No JOIN_FOLLOWS used when shrinking. */
1639 ASSERT(N_NORMAL == get_mark(*pnew_head));
1640
1641 *walk_mode = WM_LEAVE_JOIN;
1642 } else {
1643 /*
1644 * Final stage of resize. The resizer is waiting for all
1645 * readers to notice that the old table had been replaced.
1646 */
1647 ASSERT(b == h->new_b);
1648 *walk_mode = WM_NORMAL;
1649 }
1650}
1651
1652
1653#if 0
1654static void move_head(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head)
1655{
1656 start_head_move(psrc_head);
1657 cas_order_barrier();
1658 complete_head_move(psrc_head, pdest_head);
1659}
1660#endif
1661
1662/** Moves an immutable head \a psrc_head of cht_t.b to \a pdest_head of cht_t.new_b.
1663 *
1664 * The function guarantees the move will be visible on this cpu once
1665 * it completes. In particular, *pdest_head will not be N_INVALID.
1666 *
1667 * Unlike complete_head_move(), help_head_move() checks if the head had already
1668 * been moved and tries to avoid moving the bucket heads if possible.
1669 */
1670static inline void help_head_move(marked_ptr_t *psrc_head,
1671 marked_ptr_t *pdest_head)
1672{
1673 /* Head move has to in progress already when calling this func. */
1674 ASSERT(N_CONST & get_mark(*psrc_head));
1675
1676 /* Head already moved. */
1677 if (N_INVALID == get_mark(*psrc_head)) {
1678 /* Effects of the head move have not yet propagated to this cpu. */
1679 if (N_INVALID == get_mark(*pdest_head)) {
1680 /* Make the move visible on this cpu. */
1681 read_barrier();
1682 }
1683 } else {
1684 complete_head_move(psrc_head, pdest_head);
1685 }
1686
1687 ASSERT(!(N_CONST & get_mark(*pdest_head)));
1688}
1689
1690/** Initiates the move of the old head \a psrc_head.
1691 *
1692 * The move may be completed with help_head_move().
1693 */
1694static void start_head_move(marked_ptr_t *psrc_head)
1695{
1696 /* Mark src head immutable. */
1697 mark_const(psrc_head);
1698}
1699
1700/** Marks the head immutable. */
1701static void mark_const(marked_ptr_t *psrc_head)
1702{
1703 marked_ptr_t ret, src_link;
1704
1705 /* Mark src head immutable. */
1706 do {
1707 cht_link_t *next = get_next(*psrc_head);
1708 src_link = make_link(next, N_NORMAL);
1709
1710 /* Mark the normal/clean src link immutable/const. */
1711 ret = cas_link(psrc_head, next, N_NORMAL, next, N_CONST);
1712 } while(ret != src_link && !(N_CONST & get_mark(ret)));
1713}
1714
1715/** Completes moving head psrc_head to pdest_head (started by start_head_move()).*/
1716static void complete_head_move(marked_ptr_t *psrc_head, marked_ptr_t *pdest_head)
1717{
1718 ASSERT(N_JOIN_FOLLOWS != get_mark(*psrc_head));
1719 ASSERT(N_CONST & get_mark(*psrc_head));
1720
1721 cht_link_t *next = get_next(*psrc_head);
1722 marked_ptr_t ret;
1723
1724 ret = cas_link(pdest_head, &sentinel, N_INVALID, next, N_NORMAL);
1725 ASSERT(ret == make_link(&sentinel, N_INVALID) || (N_NORMAL == get_mark(ret)));
1726 cas_order_barrier();
1727
1728 ret = cas_link(psrc_head, next, N_CONST, next, N_INVALID);
1729 ASSERT(ret == make_link(next, N_CONST) || (N_INVALID == get_mark(ret)));
1730 cas_order_barrier();
1731}
1732
1733/** Splits the bucket at psrc_head and links to the remainder from pdest_head.
1734 *
1735 * Items with hashes greater or equal to \a split_hash are moved to bucket
1736 * with head at \a pdest_head.
1737 *
1738 * @param h CHT to operate on.
1739 * @param psrc_head Head of the bucket to split (in cht_t.new_b).
1740 * @param pdest_head Head of the bucket that points to the second part
1741 * of the split bucket in psrc_head. (in cht_t.new_b)
1742 * @param split_hash Hash of the first possible item in the remainder of
1743 * psrc_head, ie the smallest hash pdest_head is allowed
1744 * to point to..
1745 */
1746static void split_bucket(cht_t *h, marked_ptr_t *psrc_head,
1747 marked_ptr_t *pdest_head, size_t split_hash)
1748{
1749 /* Already split. */
1750 if (N_NORMAL == get_mark(*pdest_head))
1751 return;
1752
1753 /*
1754 * L == Last node of the first part of the split bucket. That part
1755 * remains in the original/src bucket.
1756 * F == First node of the second part of the split bucket. That part
1757 * will be referenced from the dest bucket head.
1758 *
1759 * We want to first mark a clean L as JF so that updaters unaware of
1760 * the split (or table resize):
1761 * - do not insert a new node between L and F
1762 * - do not unlink L (that is why it has to be clean/normal)
1763 * - do not unlink F
1764 *
1765 * Then we can safely mark F as JN even if it has been marked deleted.
1766 * Once F is marked as JN updaters aware of table resize will not
1767 * attempt to unlink it (JN will have two predecessors - we cannot
1768 * safely unlink from both at the same time). Updaters unaware of
1769 * ongoing resize can reach F only via L and that node is already
1770 * marked JF, so they won't unlink F.
1771 *
1772 * Last, link the new/dest head to F.
1773 *
1774 *
1775 * 0) ,-- split_hash, first hash of the dest bucket
1776 * v
1777 * [src_head | N] -> .. -> [L] -> [F]
1778 * [dest_head | Inv]
1779 *
1780 * 1) ,-- split_hash
1781 * v
1782 * [src_head | N] -> .. -> [JF] -> [F]
1783 * [dest_head | Inv]
1784 *
1785 * 2) ,-- split_hash
1786 * v
1787 * [src_head | N] -> .. -> [JF] -> [JN]
1788 * [dest_head | Inv]
1789 *
1790 * 3) ,-- split_hash
1791 * v
1792 * [src_head | N] -> .. -> [JF] -> [JN]
1793 * ^
1794 * [dest_head | N] -----------------'
1795 */
1796 wnd_t wnd;
1797
1798 rcu_read_lock();
1799
1800 /* Mark the last node of the first part of the split bucket as JF. */
1801 mark_join_follows(h, psrc_head, split_hash, &wnd);
1802 cas_order_barrier();
1803
1804 /* There are nodes in the dest bucket, ie the second part of the split. */
1805 if (wnd.cur != &sentinel) {
1806 /*
1807 * Mark the first node of the dest bucket as a join node so
1808 * updaters do not attempt to unlink it if it is deleted.
1809 */
1810 mark_join_node(wnd.cur);
1811 cas_order_barrier();
1812 } else {
1813 /*
1814 * Second part of the split bucket is empty. There are no nodes
1815 * to mark as JOIN nodes and there never will be.
1816 */
1817 }
1818
1819 /* Link the dest head to the second part of the split. */
1820 marked_ptr_t ret =
1821 cas_link(pdest_head, &sentinel, N_INVALID, wnd.cur, N_NORMAL);
1822 ASSERT(ret == make_link(&sentinel, N_INVALID) || (N_NORMAL == get_mark(ret)));
1823 cas_order_barrier();
1824
1825 rcu_read_unlock();
1826}
1827
1828/** Finds and marks the last node of psrc_head w/ hash less than split_hash.
1829 *
1830 * Finds a node in psrc_head with the greatest hash that is strictly less
1831 * than split_hash and marks it with N_JOIN_FOLLOWS.
1832 *
1833 * Returns a window pointing to that node.
1834 *
1835 * Any logically deleted nodes along the way are
1836 * garbage collected; therefore, the predecessor node (if any) will most
1837 * likely not be marked N_DELETED.
1838 *
1839 * @param h CHT to operate on.
1840 * @param psrc_head Bucket head.
1841 * @param split_hash The smallest hash a join node (ie the node following
1842 * the desired join-follows node) may have.
1843 * @param[out] wnd Points to the node marked with N_JOIN_FOLLOWS.
1844 */
1845static void mark_join_follows(cht_t *h, marked_ptr_t *psrc_head,
1846 size_t split_hash, wnd_t *wnd)
1847{
1848 /* See comment in split_bucket(). */
1849
1850 bool done;
1851 do {
1852 bool resizing = false;
1853 wnd->ppred = psrc_head;
1854 wnd->cur = get_next(*psrc_head);
1855
1856 /*
1857 * Find the split window, ie the last node of the first part of
1858 * the split bucket and the its successor - the first node of
1859 * the second part of the split bucket. Retry if GC failed.
1860 */
1861 if (!find_wnd_and_gc(h, split_hash, WM_MOVE_JOIN_FOLLOWS, wnd, &resizing))
1862 continue;
1863
1864 /* Must not report that the table is resizing if WM_MOVE_JOIN_FOLLOWS.*/
1865 ASSERT(!resizing);
1866 /*
1867 * Mark the last node of the first half of the split bucket
1868 * that a join node follows. It must be clean/normal.
1869 */
1870 marked_ptr_t ret
1871 = cas_link(wnd->ppred, wnd->cur, N_NORMAL, wnd->cur, N_JOIN_FOLLOWS);
1872
1873 /*
1874 * Successfully marked as a JF node or already marked that way (even
1875 * if also marked deleted - unlinking the node will move the JF mark).
1876 */
1877 done = (ret == make_link(wnd->cur, N_NORMAL))
1878 || (N_JOIN_FOLLOWS & get_mark(ret));
1879 } while (!done);
1880}
1881
1882/** Marks join_node with N_JOIN. */
1883static void mark_join_node(cht_link_t *join_node)
1884{
1885 /* See comment in split_bucket(). */
1886
1887 bool done;
1888 do {
1889 cht_link_t *next = get_next(join_node->link);
1890 mark_t mark = get_mark(join_node->link);
1891
1892 /*
1893 * May already be marked as deleted, but it won't be unlinked
1894 * because its predecessor is marked with JOIN_FOLLOWS or CONST.
1895 */
1896 marked_ptr_t ret
1897 = cas_link(&join_node->link, next, mark, next, mark | N_JOIN);
1898
1899 /* Successfully marked or already marked as a join node. */
1900 done = (ret == make_link(next, mark))
1901 || (N_JOIN & get_mark(ret));
1902 } while(!done);
1903}
1904
1905/** Appends the bucket at psrc_head to the bucket at pdest_head.
1906 *
1907 * @param h CHT to operate on.
1908 * @param psrc_head Bucket to merge with pdest_head.
1909 * @param pdest_head Bucket to be joined by psrc_head.
1910 * @param split_hash The smallest hash psrc_head may contain.
1911 */
1912static void join_buckets(cht_t *h, marked_ptr_t *psrc_head,
1913 marked_ptr_t *pdest_head, size_t split_hash)
1914{
1915 /* Buckets already joined. */
1916 if (N_INVALID == get_mark(*psrc_head))
1917 return;
1918 /*
1919 * F == First node of psrc_head, ie the bucket we want to append
1920 * to (ie join with) the bucket starting at pdest_head.
1921 * L == Last node of pdest_head, ie the bucket that psrc_head will
1922 * be appended to.
1923 *
1924 * (1) We first mark psrc_head immutable to signal that a join is
1925 * in progress and so that updaters unaware of the join (or table
1926 * resize):
1927 * - do not insert new nodes between the head psrc_head and F
1928 * - do not unlink F (it may already be marked deleted)
1929 *
1930 * (2) Next, F is marked as a join node. Updaters aware of table resize
1931 * will not attempt to unlink it. We cannot safely/atomically unlink
1932 * the join node because it will be pointed to from two different
1933 * buckets. Updaters unaware of resize will fail to unlink the join
1934 * node due to the head being marked immutable.
1935 *
1936 * (3) Then the tail of the bucket at pdest_head is linked to the join
1937 * node. From now on, nodes in both buckets can be found via pdest_head.
1938 *
1939 * (4) Last, mark immutable psrc_head as invalid. It signals updaters
1940 * that the join is complete and they can insert new nodes (originally
1941 * destined for psrc_head) into pdest_head.
1942 *
1943 * Note that pdest_head keeps pointing at the join node. This allows
1944 * lookups and updaters to determine if they should see a link between
1945 * the tail L and F when searching for nodes originally in psrc_head
1946 * via pdest_head. If they reach the tail of pdest_head without
1947 * encountering any nodes of psrc_head, either there were no nodes
1948 * in psrc_head to begin with or the link between L and F did not
1949 * yet propagate to their cpus. If psrc_head was empty, it remains
1950 * NULL. Otherwise psrc_head points to a join node (it will not be
1951 * unlinked until table resize completes) and updaters/lookups
1952 * should issue a read_barrier() to make the link [L]->[JN] visible.
1953 *
1954 * 0) ,-- split_hash, first hash of the src bucket
1955 * v
1956 * [dest_head | N]-> .. -> [L]
1957 * [src_head | N]--> [F] -> ..
1958 * ^
1959 * ` split_hash, first hash of the src bucket
1960 *
1961 * 1) ,-- split_hash
1962 * v
1963 * [dest_head | N]-> .. -> [L]
1964 * [src_head | C]--> [F] -> ..
1965 *
1966 * 2) ,-- split_hash
1967 * v
1968 * [dest_head | N]-> .. -> [L]
1969 * [src_head | C]--> [JN] -> ..
1970 *
1971 * 3) ,-- split_hash
1972 * v
1973 * [dest_head | N]-> .. -> [L] --+
1974 * v
1975 * [src_head | C]-------------> [JN] -> ..
1976 *
1977 * 4) ,-- split_hash
1978 * v
1979 * [dest_head | N]-> .. -> [L] --+
1980 * v
1981 * [src_head | Inv]-----------> [JN] -> ..
1982 */
1983
1984 rcu_read_lock();
1985
1986 /* Mark src_head immutable - signals updaters that bucket join started. */
1987 mark_const(psrc_head);
1988 cas_order_barrier();
1989
1990 cht_link_t *join_node = get_next(*psrc_head);
1991
1992 if (join_node != &sentinel) {
1993 mark_join_node(join_node);
1994 cas_order_barrier();
1995
1996 link_to_join_node(h, pdest_head, join_node, split_hash);
1997 cas_order_barrier();
1998 }
1999
2000 marked_ptr_t ret =
2001 cas_link(psrc_head, join_node, N_CONST, join_node, N_INVALID);
2002 ASSERT(ret == make_link(join_node, N_CONST) || (N_INVALID == get_mark(ret)));
2003 cas_order_barrier();
2004
2005 rcu_read_unlock();
2006}
2007
2008/** Links the tail of pdest_head to join_node.
2009 *
2010 * @param h CHT to operate on.
2011 * @param pdest_head Head of the bucket whose tail is to be linked to join_node.
2012 * @param join_node A node marked N_JOIN with a hash greater or equal to
2013 * split_hash.
2014 * @param split_hash The least hash that is greater than the hash of any items
2015 * (originally) in pdest_head.
2016 */
2017static void link_to_join_node(cht_t *h, marked_ptr_t *pdest_head,
2018 cht_link_t *join_node, size_t split_hash)
2019{
2020 bool done;
2021 do {
2022 wnd_t wnd = {
2023 .ppred = pdest_head,
2024 .cur = get_next(*pdest_head)
2025 };
2026
2027 bool resizing = false;
2028
2029 if (!find_wnd_and_gc(h, split_hash, WM_LEAVE_JOIN, &wnd, &resizing))
2030 continue;
2031
2032 ASSERT(!resizing);
2033
2034 if (wnd.cur != &sentinel) {
2035 /* Must be from the new appended bucket. */
2036 ASSERT(split_hash <= node_hash(h, wnd.cur)
2037 || h->invalid_hash == node_hash(h, wnd.cur));
2038 return;
2039 }
2040
2041 /* Reached the tail of pdest_head - link it to the join node. */
2042 marked_ptr_t ret =
2043 cas_link(wnd.ppred, &sentinel, N_NORMAL, join_node, N_NORMAL);
2044
2045 done = (ret == make_link(&sentinel, N_NORMAL));
2046 } while (!done);
2047}
2048
2049/** Instructs RCU to free the item once all preexisting references are dropped.
2050 *
2051 * The item is freed via op->remove_callback().
2052 */
2053static void free_later(cht_t *h, cht_link_t *item)
2054{
2055 ASSERT(item != &sentinel);
2056
2057 /*
2058 * remove_callback only works as rcu_func_t because rcu_link is the first
2059 * field in cht_link_t.
2060 */
2061 rcu_call(&item->rcu_link, (rcu_func_t)h->op->remove_callback);
2062
2063 item_removed(h);
2064}
2065
2066/** Notes that an item had been unlinked from the table and shrinks it if needed.
2067 *
2068 * If the number of items in the table drops below 1/4 of the maximum
2069 * allowed load the table is shrunk in the background.
2070 */
2071static inline void item_removed(cht_t *h)
2072{
2073 size_t items = (size_t) atomic_predec(&h->item_cnt);
2074 size_t bucket_cnt = (1 << h->b->order);
2075
2076 bool need_shrink = (items == h->max_load * bucket_cnt / 4);
2077 bool missed_shrink = (items == h->max_load * bucket_cnt / 8);
2078
2079 if ((need_shrink || missed_shrink) && h->b->order > h->min_order) {
2080 atomic_count_t resize_reqs = atomic_preinc(&h->resize_reqs);
2081 /* The first resize request. Start the resizer. */
2082 if (1 == resize_reqs) {
2083 workq_global_enqueue_noblock(&h->resize_work, resize_table);
2084 }
2085 }
2086}
2087
2088/** Notes an item had been inserted and grows the table if needed.
2089 *
2090 * The table is resized in the background.
2091 */
2092static inline void item_inserted(cht_t *h)
2093{
2094 size_t items = (size_t) atomic_preinc(&h->item_cnt);
2095 size_t bucket_cnt = (1 << h->b->order);
2096
2097 bool need_grow = (items == h->max_load * bucket_cnt);
2098 bool missed_grow = (items == 2 * h->max_load * bucket_cnt);
2099
2100 if ((need_grow || missed_grow) && h->b->order < CHT_MAX_ORDER) {
2101 atomic_count_t resize_reqs = atomic_preinc(&h->resize_reqs);
2102 /* The first resize request. Start the resizer. */
2103 if (1 == resize_reqs) {
2104 workq_global_enqueue_noblock(&h->resize_work, resize_table);
2105 }
2106 }
2107}
2108
2109/** Resize request handler. Invoked on the system work queue. */
2110static void resize_table(work_t *arg)
2111{
2112 cht_t *h = member_to_inst(arg, cht_t, resize_work);
2113
2114#ifdef CONFIG_DEBUG
2115 ASSERT(h->b);
2116 /* Make resize_reqs visible. */
2117 read_barrier();
2118 ASSERT(0 < atomic_get(&h->resize_reqs));
2119#endif
2120
2121 bool done;
2122 do {
2123 /* Load the most recent h->item_cnt. */
2124 read_barrier();
2125 size_t cur_items = (size_t) atomic_get(&h->item_cnt);
2126 size_t bucket_cnt = (1 << h->b->order);
2127 size_t max_items = h->max_load * bucket_cnt;
2128
2129 if (cur_items >= max_items && h->b->order < CHT_MAX_ORDER) {
2130 grow_table(h);
2131 } else if (cur_items <= max_items / 4 && h->b->order > h->min_order) {
2132 shrink_table(h);
2133 } else {
2134 /* Table is just the right size. */
2135 atomic_count_t reqs = atomic_predec(&h->resize_reqs);
2136 done = (reqs == 0);
2137 }
2138 } while (!done);
2139}
2140
2141/** Increases the number of buckets two-fold. Blocks until done. */
2142static void grow_table(cht_t *h)
2143{
2144 if (h->b->order >= CHT_MAX_ORDER)
2145 return;
2146
2147 h->new_b = alloc_buckets(h->b->order + 1, true);
2148
2149 /* Failed to alloc a new table - try next time the resizer is run. */
2150 if (!h->new_b)
2151 return;
2152
2153 /* Wait for all readers and updaters to see the initialized new table. */
2154 rcu_synchronize();
2155 size_t old_bucket_cnt = (1 << h->b->order);
2156
2157 /*
2158 * Give updaters a chance to help out with the resize. Do the minimum
2159 * work needed to announce a resize is in progress, ie start moving heads.
2160 */
2161 for (size_t idx = 0; idx < old_bucket_cnt; ++idx) {
2162 start_head_move(&h->b->head[idx]);
2163 }
2164
2165 /* Order start_head_move() wrt complete_head_move(). */
2166 cas_order_barrier();
2167
2168 /* Complete moving heads and split any buckets not yet split by updaters. */
2169 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2170 marked_ptr_t *move_dest_head = &h->new_b->head[grow_idx(old_idx)];
2171 marked_ptr_t *move_src_head = &h->b->head[old_idx];
2172
2173 /* Head move not yet completed. */
2174 if (N_INVALID != get_mark(*move_src_head)) {
2175 complete_head_move(move_src_head, move_dest_head);
2176 }
2177
2178 size_t split_idx = grow_to_split_idx(old_idx);
2179 size_t split_hash = calc_split_hash(split_idx, h->new_b->order);
2180 marked_ptr_t *split_dest_head = &h->new_b->head[split_idx];
2181
2182 split_bucket(h, move_dest_head, split_dest_head, split_hash);
2183 }
2184
2185 /*
2186 * Wait for all updaters to notice the new heads. Once everyone sees
2187 * the invalid old bucket heads they will know a resize is in progress
2188 * and updaters will modify the correct new buckets.
2189 */
2190 rcu_synchronize();
2191
2192 /* Clear the JOIN_FOLLOWS mark and remove the link between the split buckets.*/
2193 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2194 size_t new_idx = grow_idx(old_idx);
2195
2196 cleanup_join_follows(h, &h->new_b->head[new_idx]);
2197 }
2198
2199 /*
2200 * Wait for everyone to notice that buckets were split, ie link connecting
2201 * the join follows and join node has been cut.
2202 */
2203 rcu_synchronize();
2204
2205 /* Clear the JOIN mark and GC any deleted join nodes. */
2206 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2207 size_t new_idx = grow_to_split_idx(old_idx);
2208
2209 cleanup_join_node(h, &h->new_b->head[new_idx]);
2210 }
2211
2212 /* Wait for everyone to see that the table is clear of any resize marks. */
2213 rcu_synchronize();
2214
2215 cht_buckets_t *old_b = h->b;
2216 rcu_assign(h->b, h->new_b);
2217
2218 /* Wait for everyone to start using the new table. */
2219 rcu_synchronize();
2220
2221 free(old_b);
2222
2223 /* Not needed; just for increased readability. */
2224 h->new_b = NULL;
2225}
2226
2227/** Halfs the number of buckets. Blocks until done. */
2228static void shrink_table(cht_t *h)
2229{
2230 if (h->b->order <= h->min_order)
2231 return;
2232
2233 h->new_b = alloc_buckets(h->b->order - 1, true);
2234
2235 /* Failed to alloc a new table - try next time the resizer is run. */
2236 if (!h->new_b)
2237 return;
2238
2239 /* Wait for all readers and updaters to see the initialized new table. */
2240 rcu_synchronize();
2241
2242 size_t old_bucket_cnt = (1 << h->b->order);
2243
2244 /*
2245 * Give updaters a chance to help out with the resize. Do the minimum
2246 * work needed to announce a resize is in progress, ie start moving heads.
2247 */
2248 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2249 size_t new_idx = shrink_idx(old_idx);
2250
2251 /* This bucket should be moved. */
2252 if (grow_idx(new_idx) == old_idx) {
2253 start_head_move(&h->b->head[old_idx]);
2254 } else {
2255 /* This bucket should join the moved bucket once the move is done.*/
2256 }
2257 }
2258
2259 /* Order start_head_move() wrt to complete_head_move(). */
2260 cas_order_barrier();
2261
2262 /* Complete moving heads and join buckets with the moved buckets. */
2263 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2264 size_t new_idx = shrink_idx(old_idx);
2265 size_t move_src_idx = grow_idx(new_idx);
2266
2267 /* This bucket should be moved. */
2268 if (move_src_idx == old_idx) {
2269 /* Head move not yet completed. */
2270 if (N_INVALID != get_mark(h->b->head[old_idx])) {
2271 complete_head_move(&h->b->head[old_idx], &h->new_b->head[new_idx]);
2272 }
2273 } else {
2274 /* This bucket should join the moved bucket. */
2275 size_t split_hash = calc_split_hash(old_idx, h->b->order);
2276 join_buckets(h, &h->b->head[old_idx], &h->new_b->head[new_idx],
2277 split_hash);
2278 }
2279 }
2280
2281 /*
2282 * Wait for all updaters to notice the new heads. Once everyone sees
2283 * the invalid old bucket heads they will know a resize is in progress
2284 * and updaters will modify the correct new buckets.
2285 */
2286 rcu_synchronize();
2287
2288 /* Let everyone know joins are complete and fully visible. */
2289 for (size_t old_idx = 0; old_idx < old_bucket_cnt; ++old_idx) {
2290 size_t move_src_idx = grow_idx(shrink_idx(old_idx));
2291
2292 /* Set the invalid joinee head to NULL. */
2293 if (old_idx != move_src_idx) {
2294 ASSERT(N_INVALID == get_mark(h->b->head[old_idx]));
2295
2296 if (&sentinel != get_next(h->b->head[old_idx]))
2297 h->b->head[old_idx] = make_link(&sentinel, N_INVALID);
2298 }
2299 }
2300
2301 /* todo comment join node vs reset joinee head*/
2302 rcu_synchronize();
2303
2304 size_t new_bucket_cnt = (1 << h->new_b->order);
2305
2306 /* Clear the JOIN mark and GC any deleted join nodes. */
2307 for (size_t new_idx = 0; new_idx < new_bucket_cnt; ++new_idx) {
2308 cleanup_join_node(h, &h->new_b->head[new_idx]);
2309 }
2310
2311 /* Wait for everyone to see that the table is clear of any resize marks. */
2312 rcu_synchronize();
2313
2314 cht_buckets_t *old_b = h->b;
2315 rcu_assign(h->b, h->new_b);
2316
2317 /* Wait for everyone to start using the new table. */
2318 rcu_synchronize();
2319
2320 free(old_b);
2321
2322 /* Not needed; just for increased readability. */
2323 h->new_b = NULL;
2324}
2325
2326/** Finds and clears the N_JOIN mark from a node in new_head (if present). */
2327static void cleanup_join_node(cht_t *h, marked_ptr_t *new_head)
2328{
2329 rcu_read_lock();
2330
2331 cht_link_t *cur = get_next(*new_head);
2332
2333 while (cur != &sentinel) {
2334 /* Clear the join node's JN mark - even if it is marked as deleted. */
2335 if (N_JOIN & get_mark(cur->link)) {
2336 clear_join_and_gc(h, cur, new_head);
2337 break;
2338 }
2339
2340 cur = get_next(cur->link);
2341 }
2342
2343 rcu_read_unlock();
2344}
2345
2346/** Clears the join_node's N_JOIN mark frees it if marked N_DELETED as well. */
2347static void clear_join_and_gc(cht_t *h, cht_link_t *join_node,
2348 marked_ptr_t *new_head)
2349{
2350 ASSERT(join_node != &sentinel);
2351 ASSERT(join_node && (N_JOIN & get_mark(join_node->link)));
2352
2353 bool done;
2354
2355 /* Clear the JN mark. */
2356 do {
2357 marked_ptr_t jn_link = join_node->link;
2358 cht_link_t *next = get_next(jn_link);
2359 /* Clear the JOIN mark but keep the DEL mark if present. */
2360 mark_t cleared_mark = get_mark(jn_link) & N_DELETED;
2361
2362 marked_ptr_t ret =
2363 _cas_link(&join_node->link, jn_link, make_link(next, cleared_mark));
2364
2365 /* Done if the mark was cleared. Retry if a new node was inserted. */
2366 done = (ret == jn_link);
2367 ASSERT(ret == jn_link || (get_mark(ret) & N_JOIN));
2368 } while (!done);
2369
2370 if (!(N_DELETED & get_mark(join_node->link)))
2371 return;
2372
2373 /* The join node had been marked as deleted - GC it. */
2374
2375 /* Clear the JOIN mark before trying to unlink the deleted join node.*/
2376 cas_order_barrier();
2377
2378 size_t jn_hash = node_hash(h, join_node);
2379 do {
2380 bool resizing = false;
2381
2382 wnd_t wnd = {
2383 .ppred = new_head,
2384 .cur = get_next(*new_head)
2385 };
2386
2387 done = find_wnd_and_gc_pred(h, jn_hash, WM_NORMAL, same_node_pred,
2388 join_node, &wnd, &resizing);
2389
2390 ASSERT(!resizing);
2391 } while (!done);
2392}
2393
2394/** Finds a non-deleted node with N_JOIN_FOLLOWS and clears the mark. */
2395static void cleanup_join_follows(cht_t *h, marked_ptr_t *new_head)
2396{
2397 ASSERT(new_head);
2398
2399 rcu_read_lock();
2400
2401 wnd_t wnd = {
2402 .ppred = NULL,
2403 .cur = NULL
2404 };
2405 marked_ptr_t *cur_link = new_head;
2406
2407 /*
2408 * Find the non-deleted node with a JF mark and clear the JF mark.
2409 * The JF node may be deleted and/or the mark moved to its neighbors
2410 * at any time. Therefore, we GC deleted nodes until we find the JF
2411 * node in order to remove stale/deleted JF nodes left behind eg by
2412 * delayed threads that did not yet get a chance to unlink the deleted
2413 * JF node and move its mark.
2414 *
2415 * Note that the head may be marked JF (but never DELETED).
2416 */
2417 while (true) {
2418 bool is_jf_node = N_JOIN_FOLLOWS & get_mark(*cur_link);
2419
2420 /* GC any deleted nodes on the way - even deleted JOIN_FOLLOWS. */
2421 if (N_DELETED & get_mark(*cur_link)) {
2422 ASSERT(cur_link != new_head);
2423 ASSERT(wnd.ppred && wnd.cur && wnd.cur != &sentinel);
2424 ASSERT(cur_link == &wnd.cur->link);
2425
2426 bool dummy;
2427 bool deleted = gc_deleted_node(h, WM_MOVE_JOIN_FOLLOWS, &wnd, &dummy);
2428
2429 /* Failed to GC or collected a deleted JOIN_FOLLOWS. */
2430 if (!deleted || is_jf_node) {
2431 /* Retry from the head of the bucket. */
2432 cur_link = new_head;
2433 continue;
2434 }
2435 } else {
2436 /* Found a non-deleted JF. Clear its JF mark. */
2437 if (is_jf_node) {
2438 cht_link_t *next = get_next(*cur_link);
2439 marked_ptr_t ret =
2440 cas_link(cur_link, next, N_JOIN_FOLLOWS, &sentinel, N_NORMAL);
2441
2442 ASSERT(next == &sentinel
2443 || ((N_JOIN | N_JOIN_FOLLOWS) & get_mark(ret)));
2444
2445 /* Successfully cleared the JF mark of a non-deleted node. */
2446 if (ret == make_link(next, N_JOIN_FOLLOWS)) {
2447 break;
2448 } else {
2449 /*
2450 * The JF node had been deleted or a new node inserted
2451 * right after it. Retry from the head.
2452 */
2453 cur_link = new_head;
2454 continue;
2455 }
2456 } else {
2457 wnd.ppred = cur_link;
2458 wnd.cur = get_next(*cur_link);
2459 }
2460 }
2461
2462 /* We must encounter a JF node before we reach the end of the bucket. */
2463 ASSERT(wnd.cur && wnd.cur != &sentinel);
2464 cur_link = &wnd.cur->link;
2465 }
2466
2467 rcu_read_unlock();
2468}
2469
2470/** Returns the first possible hash following a bucket split point.
2471 *
2472 * In other words the returned hash is the smallest possible hash
2473 * the remainder of the split bucket may contain.
2474 */
2475static inline size_t calc_split_hash(size_t split_idx, size_t order)
2476{
2477 ASSERT(1 <= order && order <= 8 * sizeof(size_t));
2478 return split_idx << (8 * sizeof(size_t) - order);
2479}
2480
2481/** Returns the bucket head index given the table size order and item hash. */
2482static inline size_t calc_bucket_idx(size_t hash, size_t order)
2483{
2484 ASSERT(1 <= order && order <= 8 * sizeof(size_t));
2485 return hash >> (8 * sizeof(size_t) - order);
2486}
2487
2488/** Returns the bucket index of destination*/
2489static inline size_t grow_to_split_idx(size_t old_idx)
2490{
2491 return grow_idx(old_idx) | 1;
2492}
2493
2494/** Returns the destination index of a bucket head when the table is growing. */
2495static inline size_t grow_idx(size_t idx)
2496{
2497 return idx << 1;
2498}
2499
2500/** Returns the destination index of a bucket head when the table is shrinking.*/
2501static inline size_t shrink_idx(size_t idx)
2502{
2503 return idx >> 1;
2504}
2505
2506/** Returns a mixed hash of the search key.*/
2507static inline size_t calc_key_hash(cht_t *h, void *key)
2508{
2509 /* Mimic calc_node_hash. */
2510 return hash_mix(h->op->key_hash(key)) & ~(size_t)1;
2511}
2512
2513/** Returns a memoized mixed hash of the item. */
2514static inline size_t node_hash(cht_t *h, const cht_link_t *item)
2515{
2516 ASSERT(item->hash == h->invalid_hash
2517 || item->hash == sentinel.hash
2518 || item->hash == calc_node_hash(h, item));
2519
2520 return item->hash;
2521}
2522
2523/** Calculates and mixed the hash of the item. */
2524static inline size_t calc_node_hash(cht_t *h, const cht_link_t *item)
2525{
2526 ASSERT(item != &sentinel);
2527 /*
2528 * Clear the lowest order bit in order for sentinel's node hash
2529 * to be the greatest possible.
2530 */
2531 return hash_mix(h->op->hash(item)) & ~(size_t)1;
2532}
2533
2534/** Computes and memoizes the hash of the item. */
2535static inline void memoize_node_hash(cht_t *h, cht_link_t *item)
2536{
2537 item->hash = calc_node_hash(h, item);
2538}
2539
2540/** Packs the next pointer address and the mark into a single pointer. */
2541static inline marked_ptr_t make_link(const cht_link_t *next, mark_t mark)
2542{
2543 marked_ptr_t ptr = (marked_ptr_t) next;
2544
2545 ASSERT(!(ptr & N_MARK_MASK));
2546 ASSERT(!((unsigned)mark & ~N_MARK_MASK));
2547
2548 return ptr | mark;
2549}
2550
2551/** Strips any marks from the next item link and returns the next item's address.*/
2552static inline cht_link_t * get_next(marked_ptr_t link)
2553{
2554 return (cht_link_t*)(link & ~N_MARK_MASK);
2555}
2556
2557/** Returns the current node's mark stored in the next item link. */
2558static inline mark_t get_mark(marked_ptr_t link)
2559{
2560 return (mark_t)(link & N_MARK_MASK);
2561}
2562
2563/** Moves the window by one item so that is points to the next item. */
2564static inline void next_wnd(wnd_t *wnd)
2565{
2566 ASSERT(wnd);
2567 ASSERT(wnd->cur);
2568
2569 wnd->last = wnd->cur;
2570 wnd->ppred = &wnd->cur->link;
2571 wnd->cur = get_next(wnd->cur->link);
2572}
2573
2574/** Predicate that matches only exactly the same node. */
2575static bool same_node_pred(void *node, const cht_link_t *item2)
2576{
2577 const cht_link_t *item1 = (const cht_link_t*) node;
2578 return item1 == item2;
2579}
2580
2581/** Compare-and-swaps a next item link. */
2582static inline marked_ptr_t cas_link(marked_ptr_t *link, const cht_link_t *cur_next,
2583 mark_t cur_mark, const cht_link_t *new_next, mark_t new_mark)
2584{
2585 return _cas_link(link, make_link(cur_next, cur_mark),
2586 make_link(new_next, new_mark));
2587}
2588
2589/** Compare-and-swaps a next item link. */
2590static inline marked_ptr_t _cas_link(marked_ptr_t *link, marked_ptr_t cur,
2591 marked_ptr_t new)
2592{
2593 ASSERT(link != &sentinel.link);
2594 /*
2595 * cas(x) on the same location x on one cpu must be ordered, but do not
2596 * have to be ordered wrt to other cas(y) to a different location y
2597 * on the same cpu.
2598 *
2599 * cas(x) must act as a write barrier on x, ie if cas(x) succeeds
2600 * and is observed by another cpu, then all cpus must be able to
2601 * make the effects of cas(x) visible just by issuing a load barrier.
2602 * For example:
2603 * cpu1 cpu2 cpu3
2604 * cas(x, 0 -> 1), succeeds
2605 * cas(x, 0 -> 1), fails
2606 * MB, to order load of x in cas and store to y
2607 * y = 7
2608 * sees y == 7
2609 * loadMB must be enough to make cas(x) on cpu3 visible to cpu1, ie x == 1.
2610 *
2611 * If cas() did not work this way:
2612 * a) our head move protocol would not be correct.
2613 * b) freeing an item linked to a moved head after another item was
2614 * inserted in front of it, would require more than one grace period.
2615 *
2616 * Ad (a): In the following example, cpu1 starts moving old_head
2617 * to new_head, cpu2 completes the move and cpu3 notices cpu2
2618 * completed the move before cpu1 gets a chance to notice cpu2
2619 * had already completed the move. Our requirements for cas()
2620 * assume cpu3 will see a valid and mutable value in new_head
2621 * after issuing a load memory barrier once it has determined
2622 * the old_head's value had been successfully moved to new_head
2623 * (because it sees old_head marked invalid).
2624 *
2625 * cpu1 cpu2 cpu3
2626 * cas(old_head, <addr, N>, <addr, Const>), succeeds
2627 * cas-order-barrier
2628 * // Move from old_head to new_head started, now the interesting stuff:
2629 * cas(new_head, <0, Inv>, <addr, N>), succeeds
2630 *
2631 * cas(new_head, <0, Inv>, <addr, N>), but fails
2632 * cas-order-barrier
2633 * cas(old_head, <addr, Const>, <addr, Inv>), succeeds
2634 *
2635 * Sees old_head marked Inv (by cpu2)
2636 * load-MB
2637 * assert(new_head == <addr, N>)
2638 *
2639 * cas-order-barrier
2640 *
2641 * Even though cpu1 did not yet issue a cas-order-barrier, cpu1's store
2642 * to new_head (successful cas()) must be made visible to cpu3 with
2643 * a load memory barrier if cpu1's store to new_head is visible
2644 * on another cpu (cpu2) and that cpu's (cpu2's) store to old_head
2645 * is already visible to cpu3. *
2646 */
2647 void *expected = (void*)cur;
2648
2649 /*
2650 * Use the acquire-release model, although we could probably
2651 * get away even with the relaxed memory model due to our use
2652 * of explicit memory barriers.
2653 */
2654 __atomic_compare_exchange_n((void**)link, &expected, (void *)new, false,
2655 __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE);
2656
2657 return (marked_ptr_t) expected;
2658}
2659
2660/** Orders compare-and-swaps to different memory locations. */
2661static inline void cas_order_barrier(void)
2662{
2663 /* Make sure CAS to different memory locations are ordered. */
2664 write_barrier();
2665}
2666
2667
2668/** @}
2669 */
Note: See TracBrowser for help on using the repository browser.