]> pd.if.org Git - nbds/blob - map/skiplist.c
70cb6e50ceb657d984b8df61d831af087131fcdf
[nbds] / map / skiplist.c
1 /* 
2  * Written by Josh Dybnis and released to the public domain, as explained at
3  * http://creativecommons.org/licenses/publicdomain
4  *
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/
8  *
9  * See also Kir Fraser's dissertation "Practical Lock Freedom".
10  * www.cl.cam.ac.uk/techreports/UCAM-CL-TR-579.pdf
11  *
12  * I've generalized the data structure to support update operations like set() and CAS() in addition to 
13  * the normal add() and remove() operations.
14  *
15  * Warning: This code is written for the x86 memory-model. The algorithim depends on certain stores 
16  * and loads being ordered. This code won't work correctly on platforms with weaker memory models if
17  * you don't add memory barriers in the right places.
18  */
19
20 #include <stdio.h>
21 #include <string.h>
22
23 #include "common.h"
24 #include "skiplist.h"
25 #include "runtime.h"
26 #include "mem.h"
27 #include "rcu.h"
28
29 // Setting MAX_LEVEL to 0 essentially makes this data structure the Harris-Michael lock-free list (in list.c).
30 #define MAX_LEVEL 31
31
32 typedef struct node {
33     map_key_t key;
34     map_val_t val;
35     int top_level;
36     markable_t next[1];
37 } node_t;
38
39 struct sl_iter {
40     node_t *next;
41 };
42
43 struct sl {
44     node_t *head;
45     const datatype_t *key_type;
46     int high_water; // max level of any item in the list
47 };
48
49 // Marking the <next> field of a node logically removes it from the list
50 #if 0
51 static inline markable_t  MARK_NODE(node_t * x) { return TAG_VALUE((markable_t)x, 0x1); }
52 static inline int        HAS_MARK(markable_t x) { return (IS_TAGGED(x, 0x1) == 0x1); }
53 static inline node_t *   GET_NODE(markable_t x) { assert(!HAS_MARK(x)); return (node_t *)x; }
54 static inline node_t * STRIP_MARK(markable_t x) { return ((node_t *)STRIP_TAG(x, 0x1)); }
55 #else
56 #define  MARK_NODE(x) TAG_VALUE((markable_t)(x), 0x1)
57 #define   HAS_MARK(x) (IS_TAGGED((x), 0x1) == 0x1)
58 #define   GET_NODE(x) ((node_t *)(x))
59 #define STRIP_MARK(x) ((node_t *)STRIP_TAG((x), 0x1))
60 #endif
61
62 static int random_level (void) {
63     unsigned r = nbd_rand();
64     int n = __builtin_ctz(r) / 2;
65     if (n > MAX_LEVEL) { n = MAX_LEVEL; }
66     return n;
67 }
68
69 static node_t *node_alloc (int level, map_key_t key, map_val_t val) {
70     assert(level >= 0 && level <= MAX_LEVEL);
71     size_t sz = sizeof(node_t) + level * sizeof(node_t *);
72     node_t *item = (node_t *)nbd_malloc(sz);
73     memset(item, 0, sz);
74     item->key = key;
75     item->val = val;
76     item->top_level = level;
77     TRACE("s2", "node_alloc: new node %p (%llu levels)", item, level);
78     return item;
79 }
80
81 skiplist_t *sl_alloc (const datatype_t *key_type) {
82     skiplist_t *sl = (skiplist_t *)nbd_malloc(sizeof(skiplist_t));
83     sl->key_type = key_type;
84     sl->high_water = 0;
85     sl->head = node_alloc(MAX_LEVEL, 0, 0);
86     memset(sl->head->next, 0, (MAX_LEVEL+1) * sizeof(skiplist_t *));
87     return sl;
88 }
89
90 void sl_free (skiplist_t *sl) {
91     node_t *item = GET_NODE(sl->head->next[0]);
92     while (item) {
93         node_t *next = STRIP_MARK(item->next[0]);
94         if (sl->key_type != NULL) {
95             nbd_free((void *)item->key);
96         }
97         nbd_free(item);
98         item = next;
99     }
100 }
101
102 size_t sl_count (skiplist_t *sl) {
103     size_t count = 0;
104     node_t *item = GET_NODE(sl->head->next[0]);
105     while (item) {
106         if (!HAS_MARK(item->next[0])) {
107             count++;
108         }
109         item = STRIP_MARK(item->next[0]);
110     }
111     return count;
112 }
113
114 static node_t *find_preds (node_t **preds, node_t **succs, int n, skiplist_t *sl, map_key_t key, int help_remove) {
115     node_t *pred = sl->head;
116     node_t *item = NULL;
117     TRACE("s2", "find_preds: searching for key %p in skiplist (head is %p)", key, pred);
118     int d = 0;
119     int start_level = sl->high_water;
120     if (EXPECT_FALSE(start_level < n)) {
121         start_level = n;
122     }
123
124     // Traverse the levels of <sl> from the top level to the bottom
125     for (int level = start_level; level >= 0; --level) {
126         markable_t next = pred->next[level];
127         if (next == DOES_NOT_EXIST && level > n)
128             continue;
129         TRACE("s3", "find_preds: traversing level %p starting at %p", level, pred);
130         if (EXPECT_FALSE(HAS_MARK(next))) {
131             TRACE("s2", "find_preds: pred %p is marked for removal (next %p); retry", pred, next);
132             ASSERT(level == pred->top_level || HAS_MARK(pred->next[level+1]));
133             return find_preds(preds, succs, n, sl, key, help_remove); // retry
134         }
135         item = GET_NODE(next);
136         while (item != NULL) {
137             next = item->next[level];
138
139             // A tag means an item is logically removed but not physically unlinked yet.
140             while (EXPECT_FALSE(HAS_MARK(next))) {
141                 TRACE("s3", "find_preds: found marked item %p (next is %p)", item, next);
142                 if (!help_remove) {
143
144                     // Skip over logically removed items.
145                     item = STRIP_MARK(next);
146                     if (EXPECT_FALSE(item == NULL))
147                         break;
148                     next = item->next[level];
149                 } else {
150
151                     // Unlink logically removed items.
152                     markable_t other = SYNC_CAS(&pred->next[level], item, STRIP_MARK(next));
153                     if (other == (markable_t)item) {
154                         TRACE("s3", "find_preds: unlinked item from pred %p", pred, 0);
155                         item = STRIP_MARK(next);
156                     } else {
157                         TRACE("s3", "find_preds: lost race to unlink item pred %p's link changed to %p", pred, other);
158                         if (HAS_MARK(other))
159                             return find_preds(preds, succs, n, sl, key, help_remove); // retry
160                         item = GET_NODE(other);
161                     }
162                     next = (item != NULL) ? item->next[level] : DOES_NOT_EXIST;
163                 }
164             }
165
166             if (EXPECT_FALSE(item == NULL)) {
167                 TRACE("s3", "find_preds: past the last item in the skiplist", 0, 0);
168                 break;
169             }
170
171             TRACE("s4", "find_preds: visiting item %p (next is %p)", item, next);
172             TRACE("s4", "find_preds: key %p val %p", STRIP_MARK(item->key), item->val);
173
174             if (EXPECT_TRUE(sl->key_type == NULL)) {
175                 d = item->key - key;
176             } else {
177                 d = sl->key_type->cmp((void *)item->key, (void *)key);
178             }
179
180             if (d >= 0)
181                 break;
182
183             pred = item;
184             item = GET_NODE(next);
185         }
186
187         TRACE("s3", "find_preds: found pred %p next %p", pred, item);
188
189         // The cast to unsigned is for the case when n is -1.
190         if ((unsigned)level <= (unsigned)n) { 
191             if (preds != NULL) {
192                 preds[level] = pred;
193             }
194             if (succs != NULL) {
195                 succs[level] = item;
196             }
197         }
198     }
199
200     // fill in empty levels
201     if (n == -1 && item != NULL && preds != NULL) {
202         assert(item->top_level <= MAX_LEVEL);
203         for (int level = start_level + 1; level <= item->top_level; ++level) {
204             preds[level] = sl->head;
205         }
206     }
207
208     if (d == 0) {
209         TRACE("s2", "find_preds: found matching item %p in skiplist, pred is %p", item, pred);
210         return item;
211     }
212     TRACE("s2", "find_preds: found proper place for key %p in skiplist, pred is %p. returning null", key, pred);
213     return NULL;
214 }
215
216 static void sl_unlink (skiplist_t *sl, map_key_t key) {
217     node_t *pred = sl->head;
218     node_t *item = NULL;
219     TRACE("s2", "sl_unlink: unlinking marked item with key %p", key, 0);
220     int d = 0;
221
222     // Traverse the levels of <sl> from the top level to the bottom
223     for (int level = sl->high_water; level >= 0; --level) {
224         markable_t next = pred->next[level];
225         if (next == DOES_NOT_EXIST)
226             continue;
227         TRACE("s3", "sl_unlink: traversing level %p starting at %p", level, pred);
228         if (EXPECT_FALSE(HAS_MARK(next))) {
229             TRACE("s2", "sl_unlink: lost a race; pred %p is marked for removal (next %p); retry", pred, next);
230             ASSERT(level == pred->top_level || HAS_MARK(pred->next[level+1]));
231             return sl_unlink(sl, key); // retry
232         }
233         item = GET_NODE(next);
234         while (item != NULL) {
235             next = item->next[level];
236
237             while (HAS_MARK(next)) {
238                 TRACE("s3", "sl_unlink: found marked item %p (next is %p)", item, next);
239
240                 markable_t other = SYNC_CAS(&pred->next[level], item, STRIP_MARK(next));
241                 if (other == (markable_t)item) {
242                     TRACE("s3", "sl_unlink: unlinked item from pred %p", pred, 0);
243                     item = STRIP_MARK(next);
244                 } else {
245                     TRACE("s3", "sl_unlink: lost race to unlink item, pred %p's link changed to %p", pred, other);
246                     if (HAS_MARK(other))
247                         return sl_unlink(sl, key); // retry
248                     item = GET_NODE(other);
249                 }
250                 next = (item != NULL) ? item->next[level] : DOES_NOT_EXIST;
251             }
252
253             if (EXPECT_FALSE(item == NULL)) {
254                 TRACE("s3", "sl_unlink: past the last item in the skiplist", 0, 0);
255                 break;
256             }
257
258             TRACE("s4", "sl_unlink: visiting item %p (next is %p)", item, next);
259             TRACE("s4", "sl_unlink: key %p val %p", STRIP_MARK(item->key), item->val);
260
261             if (EXPECT_TRUE(sl->key_type == NULL)) {
262                 d = item->key - key;
263             } else {
264                 d = sl->key_type->cmp((void *)item->key, (void *)key);
265             }
266
267             if (d > 0)
268                 break;
269
270             pred = item;
271             item = GET_NODE(next);
272         }
273
274         TRACE("s3", "sl_unlink: at pred %p next %p", pred, item);
275     }
276 }
277
278 // Fast find that does not help unlink partially removed nodes and does not return the node's predecessors.
279 map_val_t sl_lookup (skiplist_t *sl, map_key_t key) {
280     TRACE("s1", "sl_lookup: searching for key %p in skiplist %p", key, sl);
281     node_t *item = find_preds(NULL, NULL, 0, sl, key, FALSE);
282
283     // If we found an <item> matching the <key> return its value.
284     if (item != NULL) {
285         map_val_t val = item->val;
286         if (val != DOES_NOT_EXIST) {
287             TRACE("s1", "sl_lookup: found item %p. val %p. returning item", item, item->val);
288             return val;
289         }
290     }
291
292     TRACE("l1", "sl_lookup: no item in the skiplist matched the key", 0, 0);
293     return DOES_NOT_EXIST;
294 }
295
296 map_key_t sl_min_key (skiplist_t *sl) {
297     node_t *item = GET_NODE(sl->head->next[0]);
298     while (item != NULL) {
299         markable_t next = item->next[0];
300         if (!HAS_MARK(next))
301             return item->key;
302         item = STRIP_MARK(next);
303     }
304     return DOES_NOT_EXIST;
305 }
306
307 static map_val_t update_item (node_t *item, map_val_t expectation, map_val_t new_val) {
308     map_val_t old_val = item->val;
309
310     // If the item's value is DOES_NOT_EXIST it means another thread removed the node out from under us.
311     if (EXPECT_FALSE(old_val == DOES_NOT_EXIST)) {
312         TRACE("s2", "update_item: lost a race to another thread removing the item. retry", 0, 0);
313         return DOES_NOT_EXIST; // retry
314     }
315
316     if (EXPECT_FALSE(expectation == CAS_EXPECT_DOES_NOT_EXIST)) {
317         TRACE("s1", "update_item: found an item %p in the skiplist that matched the key. the expectation was "
318                 "not met, the skiplist was not changed", item, old_val);
319         return old_val; // failure
320     }
321
322     // Use a CAS and not a SWAP. If the CAS fails it means another thread removed the node or updated its
323     // value. If another thread removed the node but it is not unlinked yet and we used a SWAP, we could
324     // replace DOES_NOT_EXIST with our value. Then another thread that is updating the value could think it
325     // succeeded and return our value even though it should return DOES_NOT_EXIST. 
326     if (old_val == SYNC_CAS(&item->val, old_val, new_val)) {
327         TRACE("s1", "update_item: the CAS succeeded. updated the value of the item", 0, 0);
328         return old_val; // success
329     }
330     TRACE("s2", "update_item: lost a race. the CAS failed. another thread changed the item's value", 0, 0);
331
332     // retry
333     return update_item(item, expectation, new_val); // tail call
334 }
335
336 map_val_t sl_cas (skiplist_t *sl, map_key_t key, map_val_t expectation, map_val_t new_val) {
337     TRACE("s1", "sl_cas: key %p skiplist %p", key, sl);
338     TRACE("s1", "sl_cas: expectation %p new value %p", expectation, new_val);
339     ASSERT((int64_t)new_val > 0);
340
341     node_t *preds[MAX_LEVEL+1];
342     node_t *nexts[MAX_LEVEL+1];
343     node_t *new_item = NULL;
344     int n = random_level();
345     node_t *old_item = find_preds(preds, nexts, n, sl, key, TRUE);
346
347     // If there is already an item in the skiplist that matches the key just update its value.
348     if (old_item != NULL) {
349         map_val_t ret_val = update_item(old_item, expectation, new_val);
350         if (ret_val != DOES_NOT_EXIST)
351             return ret_val;
352
353         // If we lose a race with a thread removing the item we tried to update then we have to retry.
354         return sl_cas(sl, key, expectation, new_val); // tail call 
355     }
356
357     if (EXPECT_FALSE(expectation != CAS_EXPECT_DOES_NOT_EXIST && expectation != CAS_EXPECT_WHATEVER)) {
358         TRACE("l1", "sl_cas: the expectation was not met, the skiplist was not changed", 0, 0);
359         return DOES_NOT_EXIST; // failure, the caller expected an item for the <key> to already exist 
360     }
361
362     // Create a new node and insert it into the skiplist.
363     TRACE("s3", "sl_cas: attempting to insert a new item between %p and %p", preds[0], nexts[0]);
364     map_key_t new_key = sl->key_type == NULL ? key : (map_key_t)sl->key_type->clone((void *)key);
365     if (n > sl->high_water) {
366         n = sl->high_water + 1;
367         int x = SYNC_ADD(&sl->high_water, 1);
368         x = x;
369         TRACE("s2", "sl_cas: incremented high water mark to %p", x, 0);
370     }
371     new_item = node_alloc(n, new_key, new_val);
372
373     // Set <new_item>'s next pointers to their proper values
374     markable_t next = new_item->next[0] = (markable_t)nexts[0];
375     for (int level = 1; level <= new_item->top_level; ++level) {
376         new_item->next[level] = (markable_t)nexts[level];
377     }
378
379     // Link <new_item> into <sl> from the bottom level up. After <new_item> is inserted into the bottom level
380     // it is officially part of the skiplist.
381     node_t *pred = preds[0];
382     markable_t other = SYNC_CAS(&pred->next[0], next, new_item);
383     if (other != next) {
384         TRACE("s3", "sl_cas: failed to change pred's link: expected %p found %p", next, other);
385
386         // Lost a race to another thread modifying the skiplist. Free the new item we allocated and retry.
387         if (sl->key_type != NULL) {
388             nbd_free((void *)new_key);
389         }
390         nbd_free(new_item); 
391         return sl_cas(sl, key, expectation, new_val); // tail call
392     }
393
394     TRACE("s3", "sl_cas: successfully inserted a new item %p at the bottom level", new_item, 0);
395
396     for (int level = 1; level <= new_item->top_level; ++level) {
397         TRACE("s3", "sl_cas: inserting the new item %p at level %p", new_item, level);
398         do {
399             node_t *   pred = preds[level];
400             ASSERT(new_item->next[level]==(markable_t)nexts[level] || new_item->next[level]==MARK_NODE(nexts[level]));
401             TRACE("s3", "sl_cas: attempting to to insert the new item between %p and %p", pred, nexts[level]);
402
403             markable_t other = SYNC_CAS(&pred->next[level], nexts[level], (markable_t)new_item);
404             if (other == (markable_t)nexts[level])
405                 break; // successfully linked <new_item> into the skiplist at the current <level>
406             TRACE("s3", "sl_cas: lost a race. failed to change pred's link. expected %p found %p", nexts[level], other);
407
408             // Find <new_item>'s new preds and nexts.
409             find_preds(preds, nexts, new_item->top_level, sl, key, TRUE);
410
411             for (int i = level; i <= new_item->top_level; ++i) {
412                 markable_t old_next = new_item->next[i];
413                 if ((markable_t)nexts[i] == old_next)
414                     continue;
415
416                 // Update <new_item>'s inconsistent next pointer before trying again. Use a CAS so if another thread
417                 // is trying to remove the new item concurrently we do not stomp on the mark it places on the item.
418                 TRACE("s3", "sl_cas: attempting to update the new item's link from %p to %p", old_next, nexts[i]);
419                 other = SYNC_CAS(&new_item->next[i], old_next, nexts[i]);
420                 ASSERT(other == old_next || other == MARK_NODE(old_next));
421                 
422                 // If another thread is removing this item we can stop linking it into to skiplist
423                 if (HAS_MARK(other)) {
424                     sl_unlink(sl, key); // see comment below
425                     return DOES_NOT_EXIST;
426                 }
427             }
428         } while (1);
429     }
430
431     // In case another thread was in the process of removing the <new_item> while we were added it, we have to
432     // make sure it is completely unlinked before we return. We might have lost a race and inserted the new item
433     // at some level after the other thread thought it was fully removed. That is a problem because once a thread
434     // thinks it completely unlinks a node it queues it to be freed
435     if (HAS_MARK(new_item->next[new_item->top_level])) {
436         sl_unlink(sl, key);
437     }
438
439     return DOES_NOT_EXIST; // success, inserted a new item
440 }
441
442 map_val_t sl_remove (skiplist_t *sl, map_key_t key) {
443     TRACE("s1", "sl_remove: removing item with key %p from skiplist %p", key, sl);
444     node_t *preds[MAX_LEVEL+1];
445     node_t *item = find_preds(preds, NULL, -1, sl, key, TRUE);
446     if (item == NULL) {
447         TRACE("s3", "sl_remove: remove failed, an item with a matching key does not exist in the skiplist", 0, 0);
448         return DOES_NOT_EXIST;
449     }
450
451     // Mark <item> at each level of <sl> from the top down. If multiple threads try to concurrently remove
452     // the same item only one of them should succeed. Marking the bottom level establishes which of them succeeds.
453     markable_t old_next = 0;
454     for (int level = item->top_level; level >= 0; --level) {
455         markable_t next;
456         old_next = item->next[level];
457         do {
458             TRACE("s3", "sl_remove: marking item at level %p (next %p)", level, old_next);
459             next = old_next;
460             old_next = SYNC_CAS(&item->next[level], next, MARK_NODE((node_t *)next));
461             if (HAS_MARK(old_next)) {
462                 TRACE("s2", "sl_remove: %p is already marked for removal by another thread (next %p)", item, old_next);
463                 if (level == 0) 
464                     return DOES_NOT_EXIST;
465                 break;
466             }
467         } while (next != old_next);
468     }
469
470     // Atomically swap out the item's value in case another thread is updating the item while we are 
471     // removing it. This establishes which operation occurs first logically, the update or the remove. 
472     map_val_t val = SYNC_SWAP(&item->val, DOES_NOT_EXIST); 
473     TRACE("s2", "sl_remove: replaced item %p's value with DOES_NOT_EXIT", item, 0);
474
475     // unlink the item
476     sl_unlink(sl, key);
477
478     // free the node
479     if (sl->key_type != NULL) {
480         rcu_defer_free((void *)item->key);
481     }
482     rcu_defer_free(item);
483
484     return val;
485 }
486
487 void sl_print (skiplist_t *sl) {
488
489     printf("high water: %d levels\n", sl->high_water);
490     for (int level = MAX_LEVEL; level >= 0; --level) {
491         node_t *item = sl->head;
492         if (item->next[level] == DOES_NOT_EXIST)
493             continue;
494         printf("(%d) ", level);
495         int i = 0;
496         while (item) {
497             markable_t next = item->next[level];
498             printf("%s%p ", HAS_MARK(next) ? "*" : "", item);
499             item = STRIP_MARK(next);
500             if (i++ > 30) {
501                 printf("...");
502                 break;
503             }
504         }
505         printf("\n");
506         fflush(stdout);
507     }
508     node_t *item = sl->head;
509     int i = 0;
510     while (item) {
511         int is_marked = HAS_MARK(item->next[0]);
512         printf("%s%p:0x%llx ", is_marked ? "*" : "", item, (uint64_t)item->key);
513         if (item != sl->head) {
514             printf("[%d]", item->top_level);
515         } else {
516             printf("[HEAD]");
517         }
518         for (int level = 1; level <= item->top_level; ++level) {
519             node_t *next = STRIP_MARK(item->next[level]);
520             is_marked = HAS_MARK(item->next[0]);
521             printf(" %p%s", next, is_marked ? "*" : "");
522             if (item == sl->head && item->next[level] == DOES_NOT_EXIST)
523                 break;
524         }
525         printf("\n");
526         fflush(stdout);
527         item = STRIP_MARK(item->next[0]);
528         if (i++ > 30) {
529             printf("...\n");
530             break;
531         }
532     }
533 }
534
535 sl_iter_t *sl_iter_begin (skiplist_t *sl, map_key_t key) {
536     sl_iter_t *iter = (sl_iter_t *)nbd_malloc(sizeof(sl_iter_t));
537     if (key != DOES_NOT_EXIST) {
538         find_preds(NULL, &iter->next, 0, sl, key, FALSE);
539     } else {
540         iter->next = GET_NODE(sl->head->next[0]);
541     }
542     return iter;
543 }
544
545 map_val_t sl_iter_next (sl_iter_t *iter, map_key_t *key_ptr) {
546     assert(iter);
547     node_t *item = iter->next;
548     while (item != NULL && HAS_MARK(item->next[0])) {
549         item = STRIP_MARK(item->next[0]);
550     }
551     if (item == NULL) {
552         iter->next = NULL;
553         return DOES_NOT_EXIST;
554     }
555     iter->next = STRIP_MARK(item->next[0]);
556     if (key_ptr != NULL) {
557         *key_ptr = item->key;
558     }
559     return item->val;
560 }
561
562 void sl_iter_free (sl_iter_t *iter) {
563     nbd_free(iter);
564 }