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