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