]> pd.if.org Git - nbds/blob - struct/skiplist.c
e8060ddb3e6e820282e79d8a2032d3ebba444a2d
[nbds] / struct / 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  * This code is written for the x86 memory-model. The algorithim depends on certain stores and
13  * loads being ordered. Be careful, this code probably won't work correctly on platforms with
14  * weaker memory models if you don't add memory barriers in the right places.
15  */
16 #include <stdio.h>
17 #include <string.h>
18
19 #include "common.h"
20 #include "runtime.h"
21 #include "struct.h"
22 #include "nstring.h"
23 #include "mem.h"
24 #include "tls.h"
25
26 // Setting MAX_LEVEL to 0 essentially makes this data structure the Harris-Michael lock-free list
27 // (in list.c).
28 #define MAX_LEVEL 31
29
30 typedef struct node {
31     nstring_t *key;
32     uint64_t val;
33     int top_level;
34     struct node *next[];
35 } node_t;
36
37 struct sl {
38     node_t *head;
39 };
40
41 static int random_level (void) {
42     unsigned r = nbd_rand();
43     if (r & 1)
44         return 0;
45 #if MAX_LEVEL < 31
46     r |= 1 << (MAX_LEVEL+1);
47 #endif
48     int n = __builtin_ctz(r)-1;
49     assert(n <= MAX_LEVEL);
50     return n;
51 }
52
53 node_t *node_alloc (int level, const void *key_data, uint32_t key_len, uint64_t val) {
54     assert(level >= 0 && level <= MAX_LEVEL);
55     size_t sz = sizeof(node_t) + (level + 1) * sizeof(node_t *);
56     node_t *item = (node_t *)nbd_malloc(sz);
57     memset(item, 0, sz);
58     // If <key_len> is -1 it indicates <key_data> is an integer and not a pointer
59     item->key = (key_len == (unsigned)-1) 
60               ? (void *)TAG_VALUE(key_data) 
61               : ns_alloc(key_data, key_len); 
62     item->val = val;
63     item->top_level = level;
64     return item;
65 }
66
67 static void node_free (node_t *item) {
68     if (!IS_TAGGED(item->key)) {
69         nbd_free(item->key);
70     }
71     nbd_free(item);
72 }
73
74 static void node_defer_free (node_t *item) {
75     if (!IS_TAGGED(item->key)) {
76         nbd_defer_free(item->key);
77     }
78     nbd_defer_free(item);
79 }
80
81 skiplist_t *sl_alloc (void) {
82     skiplist_t *sl = (skiplist_t *)nbd_malloc(sizeof(skiplist_t));
83     sl->head = node_alloc(MAX_LEVEL, " ", 0, 0);
84     memset(sl->head->next, 0, (MAX_LEVEL+1) * sizeof(skiplist_t *));
85     return sl;
86 }
87
88 static node_t *find_preds (node_t **preds, node_t **succs, int n, skiplist_t *sl, const void *key_data, uint32_t key_len, int help_remove) {
89     node_t *pred = sl->head;
90     node_t *item = NULL;
91     TRACE("s2", "find_preds: searching for key %p in sl (head is %p)", key_data, pred);
92     int d;
93     int start_level = MAX_LEVEL;
94 #if MAX_LEVEL > 2
95     // Optimization for small lists. No need to traverse empty higher levels.
96     start_level = 2;
97     while (pred->next[start_level+1] != NULL) {
98         start_level += start_level - 1;
99         if (EXPECT_FALSE(start_level >= MAX_LEVEL)) {
100             start_level = MAX_LEVEL;
101             break;
102         }
103     }
104     if (EXPECT_FALSE(start_level < n)) {
105         start_level = n;
106     }
107 #endif
108
109     // Traverse the levels of <sl> from the top level to the bottom
110     for (int level = start_level; level >= 0; --level) {
111         TRACE("s3", "find_preds: level %llu", level, 0);
112         item = pred->next[level];
113         if (EXPECT_FALSE(IS_TAGGED(item))) {
114             TRACE("s2", "find_preds: pred %p is marked for removal (item %p); retry", pred, item);
115             return find_preds(preds, succs, n, sl, key_data, key_len, help_remove); // retry
116         }
117         while (item != NULL) {
118             node_t *next = item->next[level];
119
120             // A tag means an item is logically removed but not physically unlinked yet.
121             while (EXPECT_FALSE(IS_TAGGED(next))) {
122
123                 // Skip over logically removed items.
124                 if (!help_remove) {
125                     item = (node_t *)STRIP_TAG(item->next);
126                     if (EXPECT_FALSE(item == NULL))
127                         break;
128                     TRACE("s3", "find_preds: skipping marked item %p (next is %p)", item, next);
129                     next = item->next[level];
130                     continue;
131                 }
132
133                 // Unlink logically removed items.
134                 node_t *other;
135                 TRACE("s3", "find_preds: unlinking marked item %p; next is %p", item, next);
136                 if ((other = SYNC_CAS(&pred->next[level], item, STRIP_TAG(next))) == item) {
137                     item = (node_t *)STRIP_TAG(next);
138                     if (EXPECT_FALSE(item == NULL))
139                         break;
140                     next = item->next[level];
141                     TRACE("s3", "find_preds: now the current item is %p next is %p", item, next);
142
143                     // The thread that completes the unlink should free the memory.
144                     if (level == 0) { node_defer_free(other); }
145                 } else {
146                     TRACE("s2", "find_preds: lost race to unlink item %p from pred %p", item, pred);
147                     TRACE("s2", "find_preds: pred's link changed to %p", other, 0);
148                     if (IS_TAGGED(other))
149                         return find_preds(preds, succs, n, sl, key_data, key_len, help_remove); // retry
150                     item = other;
151                     if (EXPECT_FALSE(item == NULL))
152                         break;
153                     next = item->next[level];
154                 }
155             }
156
157             if (EXPECT_FALSE(item == NULL))
158                 break;
159
160             TRACE("s3", "find_preds: visiting item %p (next is %p)", item, next);
161             TRACE("s4", "find_preds: key %p val %p", STRIP_TAG(item->key), item->val);
162
163             // A tagged key is an integer, otherwise it is a pointer to a string
164             if (IS_TAGGED(item->key)) {
165                 d = (STRIP_TAG(item->key) - (uint64_t)key_data);
166             } else {
167                 int item_key_len = item->key->len;
168                 int len = (key_len < item_key_len) ? key_len : item_key_len;
169                 d = memcmp(item->key->data, key_data, len);
170                 if (d == 0) { d = item_key_len - key_len; }
171             }
172
173             if (d >= 0) {
174                 TRACE("s2", "find_preds: found pred %p item %p", pred, item);
175                 break;
176             }
177
178             pred = item;
179             item = next;
180         }
181
182         // The cast to unsigned is for the case when n is -1.
183         if ((unsigned)level <= (unsigned)n) { 
184             if (preds != NULL) {
185                 preds[level] = pred;
186             }
187             if (succs != NULL) {
188                 succs[level] = item;
189             }
190         }
191     }
192
193     // fill in empty levels
194     if (n == -1 && item != NULL) {
195         for (int level = start_level + 1; level <= item->top_level; ++level) {
196             preds[level] = sl->head;
197         }
198     }
199
200     if (d == 0) {
201         TRACE("s2", "find_preds: found matching item %p in skiplist, pred is %p", item, pred);
202         return item;
203     }
204     TRACE("s2", "find_preds: found proper place for key %p in skiplist, pred is %p. returning null", key_data, pred);
205     return NULL;
206 }
207
208 // Fast find that does not help unlink partially removed nodes and does not return the node's predecessors.
209 uint64_t sl_lookup (skiplist_t *sl, const void *key_data, uint32_t key_len) {
210     TRACE("s1", "sl_lookup: searching for key %p in skiplist %p", key_data, sl);
211     node_t *item = find_preds(NULL, NULL, 0, sl, key_data, key_len, FALSE);
212
213     // If we found an <item> matching the <key> return its value.
214     if (item != NULL) {
215         uint64_t val = item->val;
216         if (val != DOES_NOT_EXIST) {
217             TRACE("s1", "sl_lookup: found item %p. val %p. returning item", item, item->val);
218             return val;
219         }
220     }
221
222     TRACE("l1", "sl_lookup: no item in the skiplist matched the key", 0, 0);
223     return DOES_NOT_EXIST;
224 }
225
226 uint64_t sl_cas (skiplist_t *sl, const void *key_data, uint32_t key_len, uint64_t expectation, uint64_t new_val) {
227     TRACE("s1", "sl_cas: key %p skiplist %p", key_data, sl);
228     TRACE("s1", "sl_cas: expectation %p new value %p", expectation, new_val);
229     ASSERT((int64_t)new_val > 0);
230
231     node_t *preds[MAX_LEVEL+1];
232     node_t *nexts[MAX_LEVEL+1];
233     node_t *new_item = NULL;
234     int n = random_level();
235     do {
236         node_t *old_item = find_preds(preds, nexts, n, sl, key_data, key_len, TRUE);
237         if (old_item == NULL) {
238
239             // There was not an item in the skiplist that matches the key. 
240             if (EXPECT_FALSE((int64_t)expectation > 0 || expectation == EXPECT_EXISTS)) {
241                 TRACE("l1", "sl_cas: the expectation was not met, the skiplist was not changed", 0, 0);
242                 return DOES_NOT_EXIST; // failure
243             }
244
245             ASSERT(expectation == EXPECT_DOES_NOT_EXIST || expectation == EXPECT_WHATEVER);
246
247             // First insert <new_item> into the bottom level.
248             TRACE("s3", "sl_cas: attempting to insert item between %p and %p", preds[0], nexts[0]);
249             new_item = node_alloc(n, key_data, key_len, new_val);
250             node_t *pred = preds[0];
251             node_t *next = new_item->next[0] = nexts[0];
252             for (int level = 1; level <= new_item->top_level; ++level) {
253                 new_item->next[level] = nexts[level];
254             }
255             node_t *other = SYNC_CAS(&pred->next[0], next, new_item);
256             if (other == next) {
257                 TRACE("s3", "sl_cas: successfully inserted item %p at level 0", new_item, 0);
258                 break; // success
259             }
260             TRACE("s3", "sl_cas: failed to change pred's link: expected %p found %p", next, other);
261             node_free(new_item);
262             continue;
263         }
264
265         // Found an item in the skiplist that matches the key.
266         uint64_t old_item_val = old_item->val;
267         do {
268             // If the item's value is DOES_NOT_EXIST it means another thread removed the node out from under us.
269             if (EXPECT_FALSE(old_item_val == DOES_NOT_EXIST)) {
270                 TRACE("s2", "sl_cas: lost a race, found an item but another thread removed it. retry", 0, 0);
271                 break; // retry
272             }
273
274             if (EXPECT_FALSE(expectation == EXPECT_DOES_NOT_EXIST)) {
275                 TRACE("s1", "sl_cas: found an item %p in the skiplist that matched the key. the expectation was "
276                         "not met, the skiplist was not changed", old_item, old_item_val);
277                 return old_item_val; // failure
278             }
279
280             // Use a CAS and not a SWAP. If the node is in the process of being removed and we used a SWAP, we could
281             // replace DOES_NOT_EXIST with our value. Then another thread that is updating the value could think it
282             // succeeded and return our value even though we indicated that the node has been removed. If the CAS 
283             // fails it means another thread either removed the node or updated its value.
284             uint64_t ret_val = SYNC_CAS(&old_item->val, old_item_val, new_val);
285             if (ret_val == old_item_val) {
286                 TRACE("s1", "sl_cas: the CAS succeeded. updated the value of the item", 0, 0);
287                 return ret_val; // success
288             }
289             TRACE("s2", "sl_cas: lost a race. the CAS failed. another thread changed the item's value", 0, 0);
290
291             old_item_val = ret_val;
292         } while (1);
293     } while (1);
294
295     // Link <new_item> into <sl> from the bottom up.
296     for (int level = 1; level <= new_item->top_level; ++level) {
297         node_t *pred = preds[level];
298         node_t *next = nexts[level];
299         do {
300             TRACE("s3", "sl_cas: attempting to insert item between %p and %p", pred, next);
301             node_t *other = SYNC_CAS(&pred->next[level], next, new_item);
302             if (other == next) {
303                 TRACE("s3", "sl_cas: successfully inserted item %p at level %llu", new_item, level);
304                 break; // success
305             }
306             TRACE("s3", "sl_cas: failed to change pred's link: expected %p found %p", next, other);
307             find_preds(preds, nexts, new_item->top_level, sl, key_data, key_len, TRUE);
308             pred = preds[level];
309             next = nexts[level];
310
311             // Update <new_item>'s next pointer
312             do {
313                 // There in no need to continue linking in the item if another thread removed it.
314                 node_t *old_next = ((volatile node_t *)new_item)->next[level];
315                 if (IS_TAGGED(old_next))
316                     return new_val;
317
318                 // Use a CAS so we do not inadvertantly stomp on a mark another thread placed on the item.
319                 if (old_next == next || SYNC_CAS(&new_item->next[level], old_next, next) == old_next)
320                     break;
321             } while (1);
322         } while (1);
323     }
324     return new_val;
325 }
326
327 uint64_t sl_remove (skiplist_t *sl, const void *key_data, uint32_t key_len) {
328     TRACE("s1", "sl_remove: removing item with key %p from skiplist %p", key_data, sl);
329     node_t *preds[MAX_LEVEL+1];
330     node_t *item = find_preds(preds, NULL, -1, sl, key_data, key_len, TRUE);
331     if (item == NULL) {
332         TRACE("s3", "sl_remove: remove failed, an item with a matching key does not exist in the skiplist", 0, 0);
333         return DOES_NOT_EXIST;
334     }
335
336     // Mark <item> removed at each level of <sl> from the top down. This must be atomic. If multiple threads
337     // try to remove the same item only one of them should succeed. Marking the bottom level establishes which of 
338     // them succeeds.
339     for (int level = item->top_level; level >= 0; --level) {
340         if (EXPECT_FALSE(IS_TAGGED(item->next[level]))) {
341             TRACE("s3", "sl_remove: %p is already marked for removal by another thread", item, 0);
342             if (level == 0)
343                 return DOES_NOT_EXIST;
344             continue;
345         }
346         node_t *next;
347         node_t *old_next = item->next[level];
348         do {
349             next = old_next;
350             old_next = SYNC_CAS(&item->next[level], next, TAG_VALUE(next));
351             if (IS_TAGGED(old_next)) {
352                 TRACE("s2", "sl_remove: lost race -- %p is already marked for removal by another thread", item, 0);
353                 if (level == 0)
354                     return DOES_NOT_EXIST;
355             }
356         } while (!IS_TAGGED(old_next) || next != old_next);
357     }
358
359     // This has to be an atomic swap in case another thread is updating the item while we are removing it. 
360     uint64_t val = SYNC_SWAP(&item->val, DOES_NOT_EXIST); 
361     TRACE("s2", "sl_remove: replaced item's val %p with DOES_NOT_EXIT", val, 0);
362
363     // Unlink <item> from <sl>. If we lose a race to another thread just back off. It is safe to leave the
364     // item partially unlinked for a later call (or some other thread) to physically unlink. By marking the
365     // item earlier, we logically removed it. 
366     int level = item->top_level;
367     while (level >= 0) {
368         node_t *pred = preds[level];
369         node_t *next = item->next[level];
370         TRACE("s2", "sl_remove: unlink the item by linking its pred %p to it's successor %p", pred, STRIP_TAG(next));
371         node_t *other = NULL;
372         if ((other = SYNC_CAS(&pred->next[level], item, STRIP_TAG(next))) != item) {
373             TRACE("s1", "sl_remove: unlink failed; pred's link changed from %p to %p", item, other);
374             return val;
375         }
376         --level; 
377     }
378
379     // The thread that completes the unlink should free the memory.
380     TRACE("s1", "sl_remove: successfully unlinked item %p from the skiplist", item, 0);
381     node_defer_free(item); 
382     return val;
383 }
384
385 void sl_print (skiplist_t *sl) {
386     for (int level = MAX_LEVEL; level >= 0; --level) {
387         node_t *item = sl->head;
388         if (item->next[level] == NULL)
389             continue;
390         printf("(%d) ", level);
391         while (item) {
392             node_t *next = item->next[level];
393             printf("%s%p ", IS_TAGGED(next) ? "*" : "", item);
394             item = (node_t *)STRIP_TAG(next);
395         }
396         printf("\n");
397         fflush(stdout);
398     }
399
400     printf("\n");
401     node_t *item = sl->head;
402     while (item) {
403         int is_marked = IS_TAGGED(item->next[0]);
404
405         if (IS_TAGGED(item->key)) {
406             printf("%s%p:%llx ", is_marked ? "*" : "", item, STRIP_TAG(item->key));
407         } else {
408             printf("%s%p:%s ", is_marked ? "*" : "", item, (char *)item->key->data);
409         }
410         if (item != sl->head) {
411             printf("[%d]", item->top_level);
412         } else {
413             printf("[*]");
414         }
415         for (int level = 1; level <= item->top_level; ++level) {
416             node_t *next = (node_t *)STRIP_TAG(item->next[level]);
417             is_marked = IS_TAGGED(item->next[0]);
418             printf(" %p%s", next, is_marked ? "*" : "");
419             if (item == sl->head && item->next[level] == NULL)
420                 break;
421         }
422         printf("\n");
423         fflush(stdout);
424         item = (node_t *)STRIP_TAG(item->next[0]);
425     }
426 }