2 * Written by Josh Dybnis and released to the public domain, as explained at
3 * http://creativecommons.org/licenses/publicdomain
5 * Implementation of the lock-free skiplist data-structure created by Maurice Herlihy, Yossi Lev,
6 * and Nir Shavit. See Herlihy's and Shivit's book "The Art of Multiprocessor Programming".
7 * http://www.amazon.com/Art-Multiprocessor-Programming-Maurice-Herlihy/dp/0123705916/
9 * See also Kir Fraser's dissertation "Practical Lock Freedom".
10 * www.cl.cam.ac.uk/techreports/UCAM-CL-TR-579.pdf
12 * This code is written for the x86 memory-model. The algorithim depends on certain stores and
13 * loads being ordered. Be careful, this code probably won't work correctly on platforms with
14 * weaker memory models if you don't add memory barriers in the right places.
26 // Setting MAX_LEVEL to 0 essentially makes this data structure the Harris-Michael lock-free list
41 static int random_level (void) {
42 unsigned r = nbd_rand();
45 int n = __builtin_ctz(r)-1;
50 assert(n <= MAX_LEVEL);
54 node_t *node_alloc (int level, const void *key_data, uint32_t key_len, uint64_t value) {
55 assert(level >= 0 && level <= MAX_LEVEL);
56 size_t sz = sizeof(node_t) + (level + 1) * sizeof(node_t *);
57 node_t *item = (node_t *)nbd_malloc(sz);
59 item->key = ns_alloc(key_data, key_len);
61 item->top_level = level;
65 skiplist_t *sl_alloc (void) {
66 skiplist_t *sl = (skiplist_t *)nbd_malloc(sizeof(skiplist_t));
67 sl->head = node_alloc(MAX_LEVEL, " ", 0, 0);
68 memset(sl->head->next, 0, (MAX_LEVEL+1) * sizeof(skiplist_t *));
72 static node_t *find_preds (int *found, node_t *preds[MAX_LEVEL+1], int n, skiplist_t *sl, const void *key_data, uint32_t key_len, int help_remove) {
73 node_t *pred = sl->head;
75 TRACE("s3", "find_preds: searching for key %p in sl (head is %p)", key_data, pred);
78 int start_level = MAX_LEVEL;
80 // Optimization for small lists. No need to traverse empty higher levels.
82 while (pred->next[start_level+1] != NULL) {
83 start_level += start_level - 1;
84 if (EXPECT_FALSE(start_level >= MAX_LEVEL)) {
85 start_level = MAX_LEVEL;
89 if (EXPECT_FALSE(start_level < n)) {
94 // Traverse the levels of <sl> from the top level to the bottom
95 for (int level = start_level; level >= 0; --level) {
96 TRACE("s3", "find_preds: level %llu", level, 0);
97 item = pred->next[level];
98 if (EXPECT_FALSE(IS_TAGGED(item))) {
99 TRACE("s3", "find_preds: pred %p is marked for removal (item %p); retry", pred, item);
100 return find_preds(found, preds, n, sl, key_data, key_len, help_remove); // retry
102 while (item != NULL) {
103 node_t *next = item->next[level];
104 TRACE("s3", "find_preds: visiting item %p (next %p)", item, next);
105 TRACE("s3", "find_preds: key %p", item->key, 0);
107 // A tag means an item is logically removed but not physically unlinked yet.
108 while (EXPECT_FALSE(IS_TAGGED(next))) {
110 // Skip over logically removed items.
112 item = (node_t *)STRIP_TAG(item->next);
113 if (EXPECT_FALSE(item == NULL))
115 next = item->next[level];
119 // Unlink logically removed items.
121 if ((other = SYNC_CAS(&pred->next[level], item, STRIP_TAG(next))) == item) {
122 item = (node_t *)STRIP_TAG(next);
123 if (EXPECT_FALSE(item == NULL))
125 next = item->next[level];
126 TRACE("s3", "find_preds: unlinked item %p from pred %p", item, pred);
127 TRACE("s3", "find_preds: now item is %p next is %p", item, next);
129 // The thread that completes the unlink should free the memory.
130 if (level == 0) { nbd_defer_free(other); }
132 TRACE("s3", "find_preds: lost race to unlink from pred %p; its link changed to %p", pred, other);
133 if (IS_TAGGED(other))
134 return find_preds(found, preds, n, sl, key_data, key_len, help_remove); // retry
136 if (EXPECT_FALSE(item == NULL))
138 next = item->next[level];
142 if (EXPECT_FALSE(item == NULL))
145 // If we reached the key (or passed where it should be), we found a pred. Save it and continue down.
146 int x = ns_cmp_raw(item->key, key_data, key_len);
148 if (level == 0 && x == 0) {
151 TRACE("s3", "find_preds: found pred %p item %p", pred, item);
162 if (n == -1 && item != NULL) {
163 assert(preds != NULL);
164 for (int level = start_level + 1; level <= item->top_level; ++level) {
165 preds[level] = sl->head;
171 // Fast find that does not help unlink partially removed nodes and does not return the node's predecessors.
172 uint64_t sl_lookup (skiplist_t *sl, const void *key_data, uint32_t key_len) {
173 TRACE("s3", "sl_lookup: searching for key %p in sl %p", key, sl);
175 node_t *item = find_preds(&found, NULL, 0, sl, key_data, key_len, FALSE);
177 // If we found an <item> matching the <key> return its value.
178 return found ? item->value : DOES_NOT_EXIST;
181 // Insert the <key> if it doesn't already exist in <sl>
182 uint64_t sl_add (skiplist_t *sl, const void *key_data, uint32_t key_len, uint64_t value) {
183 TRACE("s3", "sl_add: inserting key %p value %p", key, value);
184 node_t *preds[MAX_LEVEL+1];
186 int n = random_level();
189 node_t *next = find_preds(&found, preds, n, sl, key_data, key_len, TRUE);
191 // If a node matching <key> already exists in <sl>, return its value.
193 TRACE("s3", "sl_add: there is already an item %p (value %p) with the same key", next, next->value);
194 if (EXPECT_FALSE(item != NULL)) { nbd_free(item); }
198 // First insert <item> into the bottom level.
199 if (EXPECT_TRUE(item == NULL)) { item = node_alloc(n, key_data, key_len, value); }
200 TRACE("s3", "sl_add: attempting to insert item between %p and %p", preds[0], next);
201 item->next[0] = next;
202 for (int level = 1; level <= item->top_level; ++level) {
203 node_t *pred = preds[level];
204 item->next[level] = pred->next[level];
206 node_t *pred = preds[0];
207 node_t *other = SYNC_CAS(&pred->next[0], next, item);
209 TRACE("s3", "sl_add: successfully inserted item %p at level 0", item, 0);
212 TRACE("s3", "sl_add: failed to change pred's link: expected %p found %p", next, other);
216 // Insert <item> into <sl> from the bottom level up.
217 for (int level = 1; level <= item->top_level; ++level) {
223 next = pred->next[level];
224 if (next == NULL) // item goes at the end of the list
226 if (!IS_TAGGED(next) && ns_cmp_raw(next->key, key_data, key_len) > 0) // pred's link changed
229 find_preds(&found, preds, item->top_level, sl, key_data, key_len, TRUE);
233 // There in no need to continue linking in the item if another thread removed it.
234 node_t *old_next = ((volatile node_t *)item)->next[level];
235 if (IS_TAGGED(old_next))
236 return DOES_NOT_EXIST; // success
238 // Use a CAS so we to not inadvertantly remove a mark another thread placed on the item.
239 if (next == old_next || SYNC_CAS(&item->next[level], old_next, next) == old_next)
243 TRACE("s3", "sl_add: attempting to insert item between %p and %p", pred, next);
244 node_t *other = SYNC_CAS(&pred->next[level], next, item);
246 TRACE("s3", "sl_add: successfully inserted item %p at level %llu", item, level);
249 TRACE("s3", "sl_add: failed to change pred's link: expected %p found %p", next, other);
256 uint64_t sl_remove (skiplist_t *sl, const void *key_data, uint32_t key_len) {
257 TRACE("s3", "sl_remove: removing item with key %p from sl %p", key_data, sl);
259 node_t *preds[MAX_LEVEL+1];
260 node_t *item = find_preds(&found, preds, -1, sl, key_data, key_len, TRUE);
262 TRACE("s3", "sl_remove: remove failed, an item with a matching key does not exist in the sl", 0, 0);
263 return DOES_NOT_EXIST;
266 // Mark <item> removed at each level of <sl> from the top down. This must be atomic. If multiple threads
267 // try to remove the same item only one of them should succeed. Marking the bottom level establishes which of
269 for (int level = item->top_level; level >= 0; --level) {
270 if (EXPECT_FALSE(IS_TAGGED(item->next[level]))) {
271 TRACE("s3", "sl_remove: %p is already marked for removal by another thread", item, 0);
273 return DOES_NOT_EXIST;
276 node_t *next = SYNC_FETCH_AND_OR(&item->next[level], TAG);
277 if (EXPECT_FALSE(IS_TAGGED(next))) {
278 TRACE("s3", "sl_remove: lost race -- %p is already marked for removal by another thread", item, 0);
280 return DOES_NOT_EXIST;
285 uint64_t value = item->value;
287 // Unlink <item> from the top down.
288 int level = item->top_level;
290 node_t *pred = preds[level];
291 node_t *next = item->next[level];
292 TRACE("s3", "sl_remove: link item's pred %p to it's successor %p", pred, STRIP_TAG(next));
293 node_t *other = NULL;
294 if ((other = SYNC_CAS(&pred->next[level], item, STRIP_TAG(next))) != item) {
295 TRACE("s3", "sl_remove: unlink failed; pred's link changed from %p to %p", item, other);
296 // By marking the item earlier, we logically removed it. It is safe to leave the item partially
297 // unlinked. Another thread will finish physically removing it from <sl>.
303 // The thread that completes the unlink should free the memory.
304 nbd_defer_free(item);
308 void sl_print (skiplist_t *sl) {
309 for (int level = MAX_LEVEL; level >= 0; --level) {
310 node_t *item = sl->head;
311 if (item->next[level] == NULL)
313 printf("(%d) ", level);
315 node_t *next = item->next[level];
316 printf("%s%p ", IS_TAGGED(next) ? "*" : "", item);
317 item = (node_t *)STRIP_TAG(next);
324 node_t *item = sl->head;
326 int is_marked = IS_TAGGED(item->next[0]);
327 printf("%s%p:%s ", is_marked ? "*" : "", item, (char *)ns_data(item->key));
328 if (item != sl->head) {
329 printf("[%d]", item->top_level);
333 for (int level = 1; level <= item->top_level; ++level) {
334 node_t *next = (node_t *)STRIP_TAG(item->next[level]);
335 is_marked = IS_TAGGED(item->next[0]);
336 printf(" %p%s", next, is_marked ? "*" : "");
337 if (item == sl->head && item->next[level] == NULL)
342 item = (node_t *)STRIP_TAG(item->next[0]);