]> pd.if.org Git - nbds/blob - struct/skiplist.c
9a26720001474f2858b53a46530b30b3e3c20de2
[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  * C implementation of the lock-free skiplist data-structure created by Maurice Herlihy, 
6  * Yossi Lev, and Nir Shavit. See "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 depends on certain stores and loads being ordered. Be careful on non-x86 platforms
13  * with weaker memory-models. This code probably won't work without adding some memory barriers.
14  */
15 #include <stdio.h>
16 #include <string.h>
17
18 #include "common.h"
19 #include "struct.h"
20 #include "mem.h"
21
22 #define MAX_LEVEL 31
23
24 typedef struct node {
25     uint64_t key;
26     uint64_t value;
27     int top_level;
28     struct node *next[];
29 } node_t;
30
31 typedef struct skiplist {
32     node_t *head;
33     node_t *last;
34     int top_level;
35 } skiplist_t;
36
37 static int random_level (int r) {
38     if (r&1)
39         return 0;
40     int n = __builtin_ctz(r);
41     if (n < MAX_LEVEL)
42         return n;
43     return MAX_LEVEL;
44 }
45
46 node_t *node_alloc (int top_level, uint64_t key, uint64_t value) {
47     assert(top_level >= 0 && top_level <= MAX_LEVEL);
48     size_t sz = sizeof(node_t) + (top_level + 1) * sizeof(node_t *);
49     node_t *item = (node_t *)nbd_malloc(sz);
50     memset(item, 0, sz);
51     item->key   = key;
52     item->value = value;
53     item->top_level = top_level;
54     return item;
55 }
56
57 skiplist_t *sl_alloc (void) {
58     skiplist_t *skiplist = (skiplist_t *)nbd_malloc(sizeof(skiplist_t));
59     skiplist->head = node_alloc(MAX_LEVEL, 0, 0);
60     skiplist->last = node_alloc(MAX_LEVEL, (uint64_t)-1, 0);
61     for (int level = 0; level <= MAX_LEVEL; ++level) {
62         skiplist->head->next[level] = skiplist->last;
63     }
64     return skiplist;
65 }
66
67 static node_t *find_preds (node_t **preds, skiplist_t *skiplist, uint64_t key, int help_remove) {
68     node_t *pred = skiplist->head;
69     node_t *item = NULL;
70     TRACE("s3", "find_preds: searching for key %p in skiplist (head is %p)", key, pred);
71 #ifndef NDEBUG
72     int count = 0;
73 #endif
74
75     // Traverse the levels of the skiplist from the top level to the bottom
76     for (int level = MAX_LEVEL; level >= 0; --level) {
77         TRACE("s3", "find_preds: level %llu", level, 0);
78         item = pred->next[level];
79         if (IS_TAGGED(item)) {
80             TRACE("s3", "find_preds: pred %p is marked for removal (item %p); retry", pred, item);
81             return find_preds(preds, skiplist, key, help_remove); // retry
82         }
83         do {
84             node_t *next = item->next[level];
85             TRACE("s3", "find_preds: visiting item %p (next %p)", item, next);
86             TRACE("s3", "find_preds: key %p", item->key, 0);
87
88             // Marked items are logically removed, but not fully unlinked yet.
89             while (EXPECT_FALSE(IS_TAGGED(next))) {
90
91                 // Skip over partially removed items.
92                 if (!help_remove) {
93                     item = (node_t *)STRIP_TAG(item->next);
94                     next = item->next[level];
95                     continue;
96                 }
97
98                 // Unlink partially removed items.
99                 node_t *other;
100                 if ((other = SYNC_CAS(&pred->next[level], item, STRIP_TAG(next))) == item) {
101                     item = (node_t *)STRIP_TAG(next);
102                     next = item->next[level];
103                     TRACE("s3", "find_preds: unlinked item %p from pred %p", item, pred);
104                     TRACE("s3", "find_preds: now item is %p next is %p", item, next);
105
106                     // The thread that completes the unlink should free the memory.
107                     if (level == 0) { nbd_defer_free(other); }
108                 } else {
109                     TRACE("s3", "find_preds: lost race to unlink item from pred %p; its link changed to %p",pred,other);
110                     if (IS_TAGGED(other))
111                         return find_preds(preds, skiplist, key, help_remove); // retry
112                     item = other;
113                     next = item->next[level];
114                 }
115             }
116
117             // If we reached the key (or passed where it should be), we found a pred. Save it and continue down.
118             if (item->key >= key) {
119                 TRACE("s3", "find_preds: found pred %p item %p", pred, item);
120                 if (preds != NULL) {
121                     preds[level] = pred;
122                 }
123                 break;
124             }
125
126             assert(count++ < 18);
127             pred = item;
128             item = next;
129
130         } while (1);
131     }
132     return item;
133 }
134
135 // Fast find that does not help unlink partially removed nodes and does not return the node's predecessors.
136 uint64_t sl_lookup (skiplist_t *skiplist, uint64_t key) {
137     TRACE("s3", "sl_lookup: searching for key %p in skiplist %p", key, skiplist);
138     node_t *item = find_preds(NULL, skiplist, key, FALSE);
139
140     // If we found an <item> matching the <key> return its value.
141     return (item->key == key) ? item->value : DOES_NOT_EXIST;
142 }
143
144 // Insert the <key> if it doesn't already exist in the <skiplist>
145 uint64_t sl_add_r (int r, skiplist_t *skiplist, uint64_t key, uint64_t value) {
146     TRACE("s3", "sl_add: inserting key %p value %p", key, value);
147     node_t *preds[MAX_LEVEL+1];
148     node_t *item = NULL;
149     do {
150         node_t *next = find_preds(preds, skiplist, key, TRUE);
151
152         // If a node matching <key> already exists in the skiplist, return its value.
153         if (next->key == key) {
154             TRACE("s3", "sl_add: there is already an item %p (value %p) with the same key", next, next->value);
155             if (EXPECT_FALSE(item != NULL)) { nbd_free(item); }
156             return next->value;
157         }
158
159         // First insert <item> into the bottom level.
160         if (EXPECT_TRUE(item == NULL)) { item = node_alloc(random_level(r), key, value); }
161         TRACE("s3", "sl_add: attempting to insert item between %p and %p", preds[0], next);
162         item->next[0] = next;
163         for (int level = 1; level <= item->top_level; ++level) {
164             item->next[level] = preds[level]->next[level];
165         }
166         node_t *other = SYNC_CAS(&preds[0]->next[0], next, item);
167         if (other == next) {
168             TRACE("s3", "sl_add: successfully inserted item %p at level 0", item, 0);
169             break; // success
170         }
171         TRACE("s3", "sl_add: failed to change pred's link: expected %p found %p", next, other);
172
173     } while (1);
174
175     // Insert <item> into the skiplist from the bottom level up.
176     for (int level = 1; level <= item->top_level; ++level) {
177         do {
178             node_t *pred = preds[level];
179             node_t *next = pred->next[level];
180             while (EXPECT_FALSE(IS_TAGGED(next) || next->key < key)) {
181                 find_preds(preds, skiplist, key, TRUE);
182                 pred = preds[level];
183                 next = pred->next[level];
184             }
185
186             do {
187                 // There in no need to continue linking in the item if another thread removed it.
188                 node_t *old_next = ((volatile node_t *)item)->next[level];
189                 if (IS_TAGGED(old_next))
190                     return DOES_NOT_EXIST; // success
191
192                 // Use a CAS so we to not inadvertantly remove a mark another thread placed on the item.
193                 if (next == old_next || SYNC_CAS(&item->next[level], old_next, next) == old_next)
194                     break;
195             } while (1);
196
197             TRACE("s3", "sl_add: attempting to insert item between %p and %p", pred, next);
198             node_t *other = SYNC_CAS(&pred->next[level], next, item);
199             if (other == next) {
200                 TRACE("s3", "sl_add: successfully inserted item %p at level %llu", item, level);
201                 break; // success
202             }
203             TRACE("s3", "sl_add: failed to change pred's link: expected %p found %p", next, other);
204
205         } while (1);
206     }
207     return value;
208 }
209
210 uint64_t sl_remove (skiplist_t *skiplist, uint64_t key) {
211     TRACE("s3", "sl_remove: removing item with key %p from skiplist %p", key, skiplist);
212     node_t *preds[MAX_LEVEL+1];
213     node_t *item = find_preds(preds, skiplist, key, TRUE);
214     if (item->key != key) {
215         TRACE("s3", "sl_remove: remove failed, an item with a matching key does not exist in the skiplist", 0, 0);
216         return DOES_NOT_EXIST;
217     }
218
219     // Mark <item> removed at each level of the skiplist from the top down. This must be atomic. If multiple threads
220     // try to remove the same item only one of them should succeed. Marking the bottom level establishes which of 
221     // them succeeds.
222     for (int level = item->top_level; level >= 0; --level) {
223         if (EXPECT_FALSE(IS_TAGGED(item->next[level]))) {
224             TRACE("s3", "sl_remove: %p is already marked for removal by another thread", item, 0);
225             if (level == 0)
226                 return DOES_NOT_EXIST;
227             continue;
228         }
229         node_t *next = SYNC_FETCH_AND_OR(&item->next[level], TAG);
230         if (EXPECT_FALSE(IS_TAGGED(next))) {
231             TRACE("s3", "sl_remove: lost race -- %p is already marked for removal by another thread", item, 0);
232             if (level == 0)
233                 return DOES_NOT_EXIST;
234             continue;
235         }
236     }
237
238     uint64_t value = item->value;
239
240     // Unlink <item> from the top down.
241     int level = item->top_level;
242     while (level >= 0) {
243         node_t *pred = preds[level];
244         node_t *next = item->next[level];
245         TRACE("s3", "sl_remove: link item's pred %p to it's successor %p", pred, STRIP_TAG(next));
246         node_t *other = NULL;
247         if ((other = SYNC_CAS(&pred->next[level], item, STRIP_TAG(next))) != item) {
248             TRACE("s3", "sl_remove: unlink failed; pred's link changed from %p to %p", item, other);
249             // By marking the item earlier, we logically removed it. It is safe to leave the item partially
250             // unlinked. Another thread will finish physically removing it from the skiplist.
251             return value;
252         }
253         --level; 
254     }
255
256     // The thread that completes the unlink should free the memory.
257     nbd_defer_free(item); 
258     return value;
259 }
260
261 void sl_print (skiplist_t *skiplist) {
262     for (int level = MAX_LEVEL; level >= 0; --level) {
263         node_t *item = skiplist->head;
264         if (item->next[level] == skiplist->last)
265             continue;
266         printf("(%d) ", level);
267         while (item) {
268             node_t *next = item->next[level];
269             printf("%s%p:0x%llx ", IS_TAGGED(next) ? "*" : "", item, item->key);
270             item = (node_t *)STRIP_TAG(next);
271         }
272         printf("\n");
273         fflush(stdout);
274     }
275
276     printf("\n");
277     node_t *item = skiplist->head;
278     while (item) {
279         assert(item->top_level <= MAX_LEVEL);
280         int is_marked = IS_TAGGED(item->next[0]);
281         printf("%s%p:0x%llx (%d", is_marked ? "*" : "", item, item->key, item->top_level);
282         for (int level = 1; level <= item->top_level; ++level) {
283             node_t *next = (node_t *)STRIP_TAG(item->next[level]);
284             printf(" %p:0x%llx", item->next[level], next ? next->key : 0);
285             if (item == skiplist->head && item->next[level] == skiplist->last)
286                 break;
287             if (item == skiplist->last && item->next[level] == NULL)
288                 break;
289         }
290         printf(")\n");
291         fflush(stdout);
292         item = (node_t *)STRIP_TAG(item->next[0]);
293     }
294 }
295
296 #ifdef MAKE_skiplist_test
297 #include <errno.h>
298 #include <pthread.h>
299 #include <sys/time.h>
300
301 #include "runtime.h"
302
303 #define NUM_ITERATIONS 10000000
304
305 static volatile int wait_;
306 static long num_threads_;
307 static skiplist_t *sl_;
308
309 void *worker (void *arg) {
310     int id = (int)(size_t)arg;
311
312     unsigned int rand_seed = id+1;//rdtsc_l();
313
314     // Wait for all the worker threads to be ready.
315     SYNC_ADD(&wait_, -1);
316     do {} while (wait_); 
317
318     for (int i = 0; i < NUM_ITERATIONS/num_threads_; ++i) {
319         int n = rand_r(&rand_seed);
320         int key = (n & 0xF) + 1;
321         if (n & (1 << 8)) {
322             sl_add_r(n, sl_, key, 1);
323         } else {
324             sl_remove(sl_, key);
325         }
326
327         rcu_update();
328     }
329
330     return NULL;
331 }
332
333 int main (int argc, char **argv) {
334     nbd_init();
335     lwt_set_trace_level("s3");
336
337     char* program_name = argv[0];
338     pthread_t thread[MAX_NUM_THREADS];
339
340     if (argc > 2) {
341         fprintf(stderr, "Usage: %s num_threads\n", program_name);
342         return -1;
343     }
344
345     num_threads_ = 2;
346     if (argc == 2)
347     {
348         errno = 0;
349         num_threads_ = strtol(argv[1], NULL, 10);
350         if (errno) {
351             fprintf(stderr, "%s: Invalid argument for number of threads\n", program_name);
352             return -1;
353         }
354         if (num_threads_ <= 0) {
355             fprintf(stderr, "%s: Number of threads must be at least 1\n", program_name);
356             return -1;
357         }
358         if (num_threads_ > MAX_NUM_THREADS) {
359             fprintf(stderr, "%s: Number of threads cannot be more than %d\n", program_name, MAX_NUM_THREADS);
360             return -1;
361         }
362     }
363
364     sl_ = sl_alloc();
365
366     struct timeval tv1, tv2;
367     gettimeofday(&tv1, NULL);
368
369     wait_ = num_threads_;
370
371     for (int i = 0; i < num_threads_; ++i) {
372         int rc = nbd_thread_create(thread + i, i, worker, (void*)(size_t)i);
373         if (rc != 0) { perror("pthread_create"); return rc; }
374     }
375
376     for (int i = 0; i < num_threads_; ++i) {
377         pthread_join(thread[i], NULL);
378     }
379
380     gettimeofday(&tv2, NULL);
381     int ms = (int)(1000000*(tv2.tv_sec - tv1.tv_sec) + tv2.tv_usec - tv1.tv_usec) / 1000;
382     printf("Th:%ld Time:%dms\n", num_threads_, ms);
383     sl_print(sl_);
384     lwt_dump("lwt.out");
385
386     return 0;
387 }
388 #endif//skiplist_test