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