2 * Written by Josh Dybnis and released to the public domain, as explained at
3 * http://creativecommons.org/licenses/publicdomain
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/
9 * See also Kir Fraser's dissertation "Practical Lock Freedom".
10 * www.cl.cam.ac.uk/techreports/UCAM-CL-TR-579.pdf
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.
26 // Setting MAX_LEVEL to 0 essentially makes this data structure the Harris-Michael lock-free list
41 static int random_level (void) {
42 unsigned r = nbd_rand();
46 r |= 1 << (MAX_LEVEL+1);
48 int n = __builtin_ctz(r)-1;
49 assert(n <= MAX_LEVEL);
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);
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);
63 item->top_level = level;
67 static void node_free (node_t *item) {
68 if (!IS_TAGGED(item->key)) {
74 static void node_defer_free (node_t *item) {
75 if (!IS_TAGGED(item->key)) {
76 nbd_defer_free(item->key);
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 *));
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;
91 TRACE("s3", "find_preds: searching for key %p in sl (head is %p)", key_data, pred);
93 int start_level = MAX_LEVEL;
95 // Optimization for small lists. No need to traverse empty higher levels.
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;
104 if (EXPECT_FALSE(start_level < n)) {
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("s3", "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
117 while (item != NULL) {
118 node_t *next = item->next[level];
119 TRACE("s3", "find_preds: visiting item %p (next %p)", item, next);
120 TRACE("s3", "find_preds: key %p", STRIP_TAG(item->key), item->val);
122 // A tag means an item is logically removed but not physically unlinked yet.
123 while (EXPECT_FALSE(IS_TAGGED(next))) {
125 // Skip over logically removed items.
127 item = (node_t *)STRIP_TAG(item->next);
128 if (EXPECT_FALSE(item == NULL))
130 next = item->next[level];
134 // Unlink logically removed items.
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))
140 next = item->next[level];
141 TRACE("s3", "find_preds: unlinked item %p from pred %p", item, pred);
142 TRACE("s3", "find_preds: now item is %p next is %p", item, next);
144 // The thread that completes the unlink should free the memory.
145 if (level == 0) { node_defer_free(other); }
147 TRACE("s3", "find_preds: lost race to unlink from pred %p; its link changed to %p", pred, other);
148 if (IS_TAGGED(other))
149 return find_preds(preds, succs, n, sl, key_data, key_len, help_remove); // retry
151 if (EXPECT_FALSE(item == NULL))
153 next = item->next[level];
157 if (EXPECT_FALSE(item == NULL))
160 // If we reached the key (or passed where it should be), we found a pred. Save it and continue down.
161 x = (IS_TAGGED(item->key))
162 ? (STRIP_TAG(item->key) - (uint64_t)key_data)
163 : ns_cmp_raw(item->key, key_data, key_len);
165 TRACE("s3", "find_preds: found pred %p item %p", pred, item);
173 // The cast to unsigned is for the case when n is -1.
174 if ((unsigned)level <= (unsigned)n) {
183 if (n == -1 && item != NULL) {
184 for (int level = start_level + 1; level <= item->top_level; ++level) {
185 preds[level] = sl->head;
188 return x == 0 ? item : NULL;
191 // Fast find that does not help unlink partially removed nodes and does not return the node's predecessors.
192 uint64_t sl_lookup (skiplist_t *sl, const void *key_data, uint32_t key_len) {
193 TRACE("s3", "sl_lookup: searching for key %p in skiplist %p", key, sl);
194 node_t *item = find_preds(NULL, NULL, 0, sl, key_data, key_len, FALSE);
196 // If we found an <item> matching the <key> return its value.
197 return item != NULL ? item->val : DOES_NOT_EXIST;
200 // Insert the <key> if it doesn't already exist in <sl>
201 uint64_t sl_add (skiplist_t *sl, const void *key_data, uint32_t key_len, uint64_t val) {
202 TRACE("s3", "sl_add: inserting key %p val %p", key_data, val);
203 node_t *preds[MAX_LEVEL+1];
204 node_t *nexts[MAX_LEVEL+1];
205 node_t *new_item = NULL;
206 int n = random_level();
208 node_t *old_item = find_preds(preds, nexts, n, sl, key_data, key_len, TRUE);
210 // If a node matching <key> already exists in <sl>, return its value.
211 if (old_item != NULL) {
212 TRACE("s3", "sl_add: there is already an item %p (value %p) with the same key", nexts[0], nexts[0]->val);
213 return nexts[0]->val;
216 // First insert <new_item> into the bottom level.
217 TRACE("s3", "sl_add: attempting to insert item between %p and %p", preds[0], nexts[0]);
218 new_item = node_alloc(n, key_data, key_len, val);
219 node_t *pred = preds[0];
220 node_t *next = new_item->next[0] = nexts[0];
221 for (int level = 1; level <= new_item->top_level; ++level) {
222 new_item->next[level] = nexts[level];
224 node_t *other = SYNC_CAS(&pred->next[0], next, new_item);
226 TRACE("s3", "sl_add: successfully inserted item %p at level 0", new_item, 0);
229 TRACE("s3", "sl_add: failed to change pred's link: expected %p found %p", next, other);
234 // Insert <new_item> into <sl> from the bottom level up.
235 for (int level = 1; level <= new_item->top_level; ++level) {
236 node_t *pred = preds[level];
237 node_t *next = nexts[level];
239 TRACE("s3", "sl_add: attempting to insert item between %p and %p", pred, next);
240 node_t *other = SYNC_CAS(&pred->next[level], next, new_item);
242 TRACE("s3", "sl_add: successfully inserted item %p at level %llu", new_item, level);
245 TRACE("s3", "sl_add: failed to change pred's link: expected %p found %p", next, other);
246 find_preds(preds, nexts, new_item->top_level, sl, key_data, key_len, TRUE);
250 // Update <new_item>'s next pointer
252 // There in no need to continue linking in the item if another thread removed it.
253 node_t *old_next = ((volatile node_t *)new_item)->next[level];
254 if (IS_TAGGED(old_next))
257 // Use a CAS so we do not inadvertantly stomp on a mark another thread placed on the item.
258 if (old_next == next || SYNC_CAS(&new_item->next[level], old_next, next) == old_next)
266 uint64_t sl_remove (skiplist_t *sl, const void *key_data, uint32_t key_len) {
267 TRACE("s3", "sl_remove: removing item with key %p from skiplist %p", key_data, sl);
268 node_t *preds[MAX_LEVEL+1];
269 node_t *item = find_preds(preds, NULL, -1, sl, key_data, key_len, TRUE);
271 TRACE("s3", "sl_remove: remove failed, an item with a matching key does not exist in the skiplist", 0, 0);
272 return DOES_NOT_EXIST;
275 // Mark <item> removed at each level of <sl> from the top down. This must be atomic. If multiple threads
276 // try to remove the same item only one of them should succeed. Marking the bottom level establishes which of
278 for (int level = item->top_level; level >= 0; --level) {
279 if (EXPECT_FALSE(IS_TAGGED(item->next[level]))) {
280 TRACE("s3", "sl_remove: %p is already marked for removal by another thread", item, 0);
282 return DOES_NOT_EXIST;
285 node_t *next = SYNC_FETCH_AND_OR(&item->next[level], TAG);
286 if (EXPECT_FALSE(IS_TAGGED(next))) {
287 TRACE("s3", "sl_remove: lost race -- %p is already marked for removal by another thread", item, 0);
289 return DOES_NOT_EXIST;
294 uint64_t val = item->val;
296 // Unlink <item> from <ll>. If we lose a race to another thread just back off. It is safe to leave the
297 // item partially unlinked for a later call (or some other thread) to physically unlink. By marking the
298 // item earlier, we logically removed it.
299 int level = item->top_level;
301 node_t *pred = preds[level];
302 node_t *next = item->next[level];
303 TRACE("s3", "sl_remove: link item's pred %p to it's successor %p", pred, STRIP_TAG(next));
304 node_t *other = NULL;
305 if ((other = SYNC_CAS(&pred->next[level], item, STRIP_TAG(next))) != item) {
306 TRACE("s3", "sl_remove: unlink failed; pred's link changed from %p to %p", item, other);
312 // The thread that completes the unlink should free the memory.
313 node_defer_free(item);
317 void sl_print (skiplist_t *sl) {
318 for (int level = MAX_LEVEL; level >= 0; --level) {
319 node_t *item = sl->head;
320 if (item->next[level] == NULL)
322 printf("(%d) ", level);
324 node_t *next = item->next[level];
325 printf("%s%p ", IS_TAGGED(next) ? "*" : "", item);
326 item = (node_t *)STRIP_TAG(next);
333 node_t *item = sl->head;
335 int is_marked = IS_TAGGED(item->next[0]);
337 if (IS_TAGGED(item->key)) {
338 printf("%s%p:%llx ", is_marked ? "*" : "", item, STRIP_TAG(item->key));
340 printf("%s%p:%s ", is_marked ? "*" : "", item, (char *)ns_data(item->key));
342 if (item != sl->head) {
343 printf("[%d]", item->top_level);
347 for (int level = 1; level <= item->top_level; ++level) {
348 node_t *next = (node_t *)STRIP_TAG(item->next[level]);
349 is_marked = IS_TAGGED(item->next[0]);
350 printf(" %p%s", next, is_marked ? "*" : "");
351 if (item == sl->head && item->next[level] == NULL)
356 item = (node_t *)STRIP_TAG(item->next[0]);