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