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