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