]> pd.if.org Git - nbds/blob - map/skiplist.c
6e02e12600673267a80291b2005ae1e90662d4b3
[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[];
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 };
47
48 // Marking the <next> field of a node logically removes it from the list
49 #if 0
50 static inline markable_t  MARK_NODE(node_t * x) { return TAG_VALUE((markable_t)x, 0x1); }
51 static inline int        HAS_MARK(markable_t x) { return (IS_TAGGED(x, 0x1) == 0x1); }
52 static inline node_t *   GET_NODE(markable_t x) { assert(!HAS_MARK(x)); return (node_t *)x; }
53 static inline node_t * STRIP_MARK(markable_t x) { return ((node_t *)STRIP_TAG(x, 0x1)); }
54 #else
55 #define  MARK_NODE(x) TAG_VALUE((markable_t)(x), 0x1)
56 #define   HAS_MARK(x) (IS_TAGGED((x), 0x1) == 0x1)
57 #define   GET_NODE(x) ((node_t *)(x))
58 #define STRIP_MARK(x) ((node_t *)STRIP_TAG((x), 0x1))
59 #endif
60
61 static int random_level (void) {
62     unsigned r = nbd_rand();
63     if (r & 1)
64         return 0;
65 #if MAX_LEVEL < 31
66     r |= 1 << (MAX_LEVEL+1);
67 #endif
68     int n = __builtin_ctz(r)-1;
69     assert(n <= MAX_LEVEL);
70     return n;
71 }
72
73 static node_t *node_alloc (int level, map_key_t key, map_val_t val) {
74     assert(level >= 0 && level <= MAX_LEVEL);
75     size_t sz = sizeof(node_t) + (level + 1) * sizeof(node_t *);
76     node_t *item = (node_t *)nbd_malloc(sz);
77     memset(item, 0, sz);
78     item->key = key;
79     item->val = val;
80     item->top_level = level;
81     return item;
82 }
83
84 skiplist_t *sl_alloc (const datatype_t *key_type) {
85     skiplist_t *sl = (skiplist_t *)nbd_malloc(sizeof(skiplist_t));
86     sl->key_type = key_type;
87     sl->head = node_alloc(MAX_LEVEL, 0, 0);
88     memset(sl->head->next, 0, (MAX_LEVEL+1) * sizeof(skiplist_t *));
89     return sl;
90 }
91
92 void sl_free (skiplist_t *sl) {
93     node_t *item = GET_NODE(sl->head->next[0]);
94     while (item) {
95         node_t *next = STRIP_MARK(item->next[0]);
96         if (sl->key_type != NULL) {
97             nbd_free((void *)item->key);
98         }
99         nbd_free(item);
100         item = next;
101     }
102 }
103
104 size_t sl_count (skiplist_t *sl) {
105     size_t count = 0;
106     node_t *item = GET_NODE(sl->head->next[0]);
107     while (item) {
108         if (!HAS_MARK(item->next[0])) {
109             count++;
110         }
111         item = STRIP_MARK(item->next[0]);
112     }
113     return count;
114 }
115
116 static node_t *find_preds (node_t **preds, node_t **succs, int n, skiplist_t *sl, map_key_t key, int help_remove) {
117     node_t *pred = sl->head;
118     node_t *item = NULL;
119     TRACE("s2", "find_preds: searching for key %p in skiplist (head is %p)", key, pred);
120     int d = 0;
121     int start_level = MAX_LEVEL;
122 #if MAX_LEVEL > 2
123     // Optimization for small lists. No need to traverse empty higher levels.
124     start_level = 2;
125     while (pred->next[start_level+1] != DOES_NOT_EXIST) {
126         start_level += start_level - 1;
127         if (EXPECT_FALSE(start_level >= MAX_LEVEL)) {
128             start_level = MAX_LEVEL;
129             break;
130         }
131     }
132     if (EXPECT_FALSE(start_level < n)) {
133         start_level = n;
134     }
135 #endif
136
137     // Traverse the levels of <sl> from the top level to the bottom
138     for (int level = start_level; level >= 0; --level) {
139         TRACE("s3", "find_preds: level %llu", level, 0);
140         markable_t next = pred->next[level];
141         if (EXPECT_FALSE(HAS_MARK(next))) {
142             TRACE("s2", "find_preds: pred %p is marked for removal (next %p); retry", pred, next);
143             return find_preds(preds, succs, n, sl, key, help_remove); // retry
144         }
145         item = GET_NODE(next);
146         while (item != NULL) {
147             next = item->next[level];
148
149             // A tag means an item is logically removed but not physically unlinked yet.
150             while (EXPECT_FALSE(HAS_MARK(next))) {
151
152                 // Skip over logically removed items.
153                 if (!help_remove) {
154                     item = STRIP_MARK(next);
155                     if (EXPECT_FALSE(item == NULL))
156                         break;
157                     next = item->next[level];
158                     TRACE("s3", "find_preds: skipping marked item %p (next is 0x%llx)", item, next);
159                     continue;
160                 }
161
162                 // Unlink logically removed items.
163                 TRACE("s3", "find_preds: unlinking marked item %p; next is 0x%llx", item, next);
164                 markable_t other = SYNC_CAS(&pred->next[level], item, STRIP_MARK(next));
165                 if (other == (markable_t)item) {
166                     item = STRIP_MARK(next);
167                     next = (item != NULL) ? item->next[level] : DOES_NOT_EXIST;
168                     TRACE("s3", "find_preds: now the current item is %p next is 0x%llx", item, next);
169
170                     // The thread that completes the unlink should free the memory.
171                     if (level == 0) {
172                         node_t *unlinked = GET_NODE(other);
173                         if (sl->key_type != NULL) {
174                             rcu_defer_free((void *)unlinked->key);
175                         }
176                         rcu_defer_free(unlinked);
177                     }
178                 } else {
179                     TRACE("s3", "find_preds: lost race to unlink item %p from pred %p", item, pred);
180                     TRACE("s3", "find_preds: pred's link changed to %p", other, 0);
181                     if (HAS_MARK(other))
182                         return find_preds(preds, succs, n, sl, key, help_remove); // retry
183                     item = GET_NODE(other);
184                     next = (item != NULL) ? item->next[level] : DOES_NOT_EXIST;
185                 }
186             }
187
188             if (EXPECT_FALSE(item == NULL))
189                 break;
190
191             TRACE("s4", "find_preds: visiting item %p (next is %p)", item, next);
192             TRACE("s4", "find_preds: key %p val %p", STRIP_MARK(item->key), item->val);
193
194             if (EXPECT_TRUE(sl->key_type == NULL)) {
195                 d = item->key - key;
196             } else {
197                 d = sl->key_type->cmp((void *)item->key, (void *)key);
198             }
199
200             if (d >= 0) {
201                 TRACE("s4", "find_preds: found pred %p item %p", pred, item);
202                 break;
203             }
204
205             pred = item;
206             item = GET_NODE(next);
207         }
208
209         // The cast to unsigned is for the case when n is -1.
210         if ((unsigned)level <= (unsigned)n) { 
211             if (preds != NULL) {
212                 preds[level] = pred;
213             }
214             if (succs != NULL) {
215                 succs[level] = item;
216             }
217         }
218     }
219
220      // fill in empty levels
221      if (n == -1 && item != NULL) {
222          assert(item->top_level <= MAX_LEVEL);
223          for (int level = start_level + 1; level <= item->top_level; ++level) {
224              preds[level] = sl->head;
225          }
226      }
227     
228     if (d == 0) {
229         TRACE("s2", "find_preds: found matching item %p in skiplist, pred is %p", item, pred);
230         return item;
231     }
232     TRACE("s2", "find_preds: found proper place for key %p in skiplist, pred is %p. returning null", key, pred);
233     return NULL;
234 }
235
236 // Fast find that does not help unlink partially removed nodes and does not return the node's predecessors.
237 map_val_t sl_lookup (skiplist_t *sl, map_key_t key) {
238     TRACE("s1", "sl_lookup: searching for key %p in skiplist %p", key, sl);
239     node_t *item = find_preds(NULL, NULL, 0, sl, key, FALSE);
240
241     // If we found an <item> matching the <key> return its value.
242     if (item != NULL) {
243         map_val_t val = item->val;
244         if (val != DOES_NOT_EXIST) {
245             TRACE("s1", "sl_lookup: found item %p. val %p. returning item", item, item->val);
246             return val;
247         }
248     }
249
250     TRACE("l1", "sl_lookup: no item in the skiplist matched the key", 0, 0);
251     return DOES_NOT_EXIST;
252 }
253
254 map_key_t sl_min_key (skiplist_t *sl) {
255     node_t *item = GET_NODE(sl->head->next[0]);
256     while (item != NULL) {
257         markable_t next = item->next[0];
258         if (!HAS_MARK(next))
259             return item->key;
260         item = STRIP_MARK(next);
261     }
262     return DOES_NOT_EXIST;
263 }
264
265 map_val_t sl_cas (skiplist_t *sl, map_key_t key, map_val_t expectation, map_val_t new_val) {
266     TRACE("s1", "sl_cas: key %p skiplist %p", key, sl);
267     TRACE("s1", "sl_cas: expectation %p new value %p", expectation, new_val);
268     ASSERT((int64_t)new_val > 0);
269
270     node_t *preds[MAX_LEVEL+1];
271     node_t *nexts[MAX_LEVEL+1];
272     node_t *new_item = NULL;
273     int n = random_level();
274     do {
275         node_t *old_item = find_preds(preds, nexts, n, sl, key, TRUE);
276         if (old_item == NULL) {
277
278             // There was not an item in the skiplist that matches the key. 
279             if (EXPECT_FALSE(expectation != CAS_EXPECT_DOES_NOT_EXIST && expectation != CAS_EXPECT_WHATEVER)) {
280                 TRACE("l1", "sl_cas: the expectation was not met, the skiplist was not changed", 0, 0);
281                 return DOES_NOT_EXIST; // failure
282             }
283
284             // First insert <new_item> into the bottom level.
285             TRACE("s3", "sl_cas: attempting to insert item between %p and %p", preds[0], nexts[0]);
286             map_key_t new_key = sl->key_type == NULL ? key : (map_key_t)sl->key_type->clone((void *)key);
287             new_item = node_alloc(n, new_key, new_val);
288             node_t *pred = preds[0];
289             markable_t next = new_item->next[0] = (markable_t)nexts[0];
290             for (int level = 1; level <= new_item->top_level; ++level) {
291                 new_item->next[level] = (markable_t)nexts[level];
292             }
293             markable_t other = SYNC_CAS(&pred->next[0], next, new_item);
294             if (other == next) {
295                 TRACE("s3", "sl_cas: successfully inserted item %p at level 0", new_item, 0);
296                 break; // success
297             }
298             TRACE("s3", "sl_cas: failed to change pred's link: expected %p found %p", next, other);
299             if (sl->key_type != NULL) {
300                 nbd_free((void *)new_key);
301             }
302             nbd_free(new_item);
303             continue;
304         }
305
306         // Found an item in the skiplist that matches the key.
307         map_val_t old_item_val = old_item->val;
308         do {
309             // If the item's value is DOES_NOT_EXIST it means another thread removed the node out from under us.
310             if (EXPECT_FALSE(old_item_val == DOES_NOT_EXIST)) {
311                 TRACE("s2", "sl_cas: lost a race, found an item but another thread removed it. retry", 0, 0);
312                 break; // retry
313             }
314
315             if (EXPECT_FALSE(expectation == CAS_EXPECT_DOES_NOT_EXIST)) {
316                 TRACE("s1", "sl_cas: found an item %p in the skiplist that matched the key. the expectation was "
317                         "not met, the skiplist was not changed", old_item, old_item_val);
318                 return old_item_val; // failure
319             }
320
321             // Use a CAS and not a SWAP. If the node is in the process of being removed and we used a SWAP, we could
322             // replace DOES_NOT_EXIST with our value. Then another thread that is updating the value could think it
323             // succeeded and return our value even though we indicated that the node has been removed. If the CAS 
324             // fails it means another thread either removed the node or updated its value.
325             map_val_t ret_val = SYNC_CAS(&old_item->val, old_item_val, new_val);
326             if (ret_val == old_item_val) {
327                 TRACE("s1", "sl_cas: the CAS succeeded. updated the value of the item", 0, 0);
328                 return ret_val; // success
329             }
330             TRACE("s2", "sl_cas: lost a race. the CAS failed. another thread changed the item's value", 0, 0);
331
332             old_item_val = ret_val;
333         } while (1);
334     } while (1);
335
336     // Link <new_item> into <sl> from the bottom up.
337     for (int level = 1; level <= new_item->top_level; ++level) {
338         node_t *pred = preds[level];
339         markable_t next = (markable_t)nexts[level];
340         do {
341             TRACE("s3", "sl_cas: attempting to insert item between %p and %p", pred, next);
342             markable_t other = SYNC_CAS(&pred->next[level], next, (markable_t)new_item);
343             if (other == next) {
344                 TRACE("s3", "sl_cas: successfully inserted item %p at level %llu", new_item, level);
345                 break; // success
346             }
347             TRACE("s3", "sl_cas: failed to change pred's link: expected %p found %p", next, other);
348             find_preds(preds, nexts, new_item->top_level, sl, key, TRUE);
349             pred = preds[level];
350             next = (markable_t)nexts[level];
351
352             // Update <new_item>'s next pointer
353             do {
354                 // There in no need to continue linking in the item if another thread removed it.
355                 markable_t old_next = ((volatile node_t *)new_item)->next[level];
356                 if (HAS_MARK(old_next))
357                     return DOES_NOT_EXIST; // success
358
359                 // Use a CAS so we do not inadvertantly stomp on a mark another thread placed on the item.
360                 if (old_next == next || SYNC_CAS(&new_item->next[level], old_next, next) == old_next)
361                     break;
362             } while (1);
363         } while (1);
364     }
365     return DOES_NOT_EXIST; // success
366 }
367
368 map_val_t sl_remove (skiplist_t *sl, map_key_t key) {
369     TRACE("s1", "sl_remove: removing item with key %p from skiplist %p", key, sl);
370     node_t *preds[MAX_LEVEL+1];
371     node_t *item = find_preds(preds, NULL, -1, sl, key, TRUE);
372     if (item == NULL) {
373         TRACE("s3", "sl_remove: remove failed, an item with a matching key does not exist in the skiplist", 0, 0);
374         return DOES_NOT_EXIST;
375     }
376
377     // Mark and unlink <item> at each level of <sl> from the top down. If multiple threads try to concurrently remove
378     // the same item only one of them should succeed. Marking the bottom level establishes which of them succeeds.
379     for (int level = item->top_level; level > 0; --level) {
380         markable_t next;
381         markable_t old_next = item->next[level];
382         do {
383             next = old_next;
384             old_next = SYNC_CAS(&item->next[level], next, MARK_NODE((node_t *)next));
385             if (HAS_MARK(old_next)) {
386                 TRACE("s2", "sl_remove: %p is already marked for removal by another thread at level %llu", item, level);
387                 break;
388             }
389         } while (next != old_next);
390
391         node_t *pred = preds[level];
392         TRACE("s2", "sl_remove: linking the item's pred %p to the item's successor %p", pred, STRIP_MARK(next));
393         markable_t other = SYNC_CAS(&pred->next[level], item, STRIP_MARK(next));
394         if (other != (markable_t)item) {
395             TRACE("s1", "sl_remove: unlink failed; pred's link changed from %p to %p", item, other);
396             // If our former predecessor now points past us we know another thread unlinked us. Otherwise, we need
397             // to search for a new set of preds.
398             if (other == DOES_NOT_EXIST)
399                 continue; // <pred> points past <item> to the end of the list; go on to the next level.
400
401             int d = -1;
402             if (!HAS_MARK(other)) {
403                 map_key_t other_key = GET_NODE(other)->key;
404                 if (EXPECT_TRUE(sl->key_type == NULL)) {
405                     d = item->key - other_key;
406                 } else {
407                     d = sl->key_type->cmp((void *)item->key, (void *)other_key);
408                 }
409             }
410             if (d > 0) {
411                 node_t *temp = find_preds(preds, NULL, level, sl, key, TRUE);
412                 if (temp != item)
413                     return DOES_NOT_EXIST; // Another thread removed the item we were targeting.
414                 level++; // Redo this level.
415             }
416         }
417     }
418
419     markable_t next;
420     markable_t old_next = item->next[0];
421     do {
422         next = old_next;
423         old_next = SYNC_CAS(&item->next[0], next, MARK_NODE((node_t *)next));
424         if (HAS_MARK(old_next)) {
425             TRACE("s2", "sl_remove: %p is already marked for removal by another thread at level 0", item, 0);
426             return DOES_NOT_EXIST;
427         }
428     } while (next != old_next);
429     TRACE("s1", "sl_remove: marked item %p removed at level 0", item, 0);
430
431     // Atomically swap out the item's value in case another thread is updating the item while we are 
432     // removing it. This establishes which operation occurs first logically, the update or the remove. 
433     map_val_t val = SYNC_SWAP(&item->val, DOES_NOT_EXIST); 
434     TRACE("s2", "sl_remove: replaced item %p's value with DOES_NOT_EXIT", item, 0);
435
436     node_t *pred = preds[0];
437     TRACE("s2", "sl_remove: linking the item's pred %p to the item's successor %p", pred, STRIP_MARK(next));
438     if (SYNC_CAS(&pred->next[0], item, STRIP_MARK(next))) {
439         TRACE("s2", "sl_remove: unlinked item %p from the skiplist at level 0", item, 0);
440         // The thread that completes the unlink should free the memory.
441         if (sl->key_type != NULL) {
442             rcu_defer_free((void *)item->key);
443         }
444         rcu_defer_free(item);
445     }
446     return val;
447 }
448
449 void sl_print (skiplist_t *sl) {
450     for (int level = MAX_LEVEL; level >= 0; --level) {
451         node_t *item = sl->head;
452         if (item->next[level] == DOES_NOT_EXIST)
453             continue;
454         printf("(%d) ", level);
455         int i = 0;
456         while (item) {
457             markable_t next = item->next[level];
458             printf("%s%p ", HAS_MARK(next) ? "*" : "", item);
459             item = STRIP_MARK(next);
460             if (i++ > 30) {
461                 printf("...");
462                 break;
463             }
464         }
465         printf("\n");
466         fflush(stdout);
467     }
468     node_t *item = sl->head;
469     int i = 0;
470     while (item) {
471         int is_marked = HAS_MARK(item->next[0]);
472         printf("%s%p:0x%llx ", is_marked ? "*" : "", item, (uint64_t)item->key);
473         if (item != sl->head) {
474             printf("[%d]", item->top_level);
475         } else {
476             printf("[HEAD]");
477         }
478         for (int level = 1; level <= item->top_level; ++level) {
479             node_t *next = STRIP_MARK(item->next[level]);
480             is_marked = HAS_MARK(item->next[0]);
481             printf(" %p%s", next, is_marked ? "*" : "");
482             if (item == sl->head && item->next[level] == DOES_NOT_EXIST)
483                 break;
484         }
485         printf("\n");
486         fflush(stdout);
487         item = STRIP_MARK(item->next[0]);
488         if (i++ > 30) {
489             printf("...\n");
490             break;
491         }
492     }
493 }
494
495 sl_iter_t *sl_iter_begin (skiplist_t *sl, map_key_t key) {
496     sl_iter_t *iter = (sl_iter_t *)nbd_malloc(sizeof(sl_iter_t));
497     if (key != DOES_NOT_EXIST) {
498         find_preds(NULL, &iter->next, 0, sl, key, FALSE);
499     } else {
500         iter->next = GET_NODE(sl->head->next[0]);
501     }
502     return iter;
503 }
504
505 map_val_t sl_iter_next (sl_iter_t *iter, map_key_t *key_ptr) {
506     assert(iter);
507     node_t *item = iter->next;
508     while (item != NULL && HAS_MARK(item->next[0])) {
509         item = STRIP_MARK(item->next[0]);
510     }
511     if (item == NULL) {
512         iter->next = NULL;
513         return DOES_NOT_EXIST;
514     }
515     iter->next = STRIP_MARK(item->next[0]);
516     if (key_ptr != NULL) {
517         *key_ptr = item->key;
518     }
519     return item->val;
520 }
521
522 void sl_iter_free (sl_iter_t *iter) {
523     nbd_free(iter);
524 }