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