]> pd.if.org Git - nbds/blob - map/list.c
all structures now support arbitrary type keys with a fast path for integers
[nbds] / map / list.c
1 /* 
2  * Written by Josh Dybnis and released to the public domain, as explained at
3  * http://creativecommons.org/licenses/publicdomain
4  *
5  * Harris-Michael lock-free list-based set
6  * http://www.research.ibm.com/people/m/michael/spaa-2002.pdf
7  */
8
9 #include <stdio.h>
10 #include <string.h>
11
12 #include "common.h"
13 #include "mlocal.h"
14 #include "mem.h"
15
16 typedef struct node {
17     void *key;
18     uint64_t val;
19     struct node *next;
20 } node_t;
21
22 struct ll {
23     node_t *head;
24     cmp_fun_t cmp_fun;
25     clone_fun_t clone_fun;
26 };
27
28 static const map_impl_t ll_map_impl = { 
29     (map_alloc_t)ll_alloc, (map_cas_t)ll_cas, (map_get_t)ll_lookup, (map_remove_t)ll_remove, 
30     (map_count_t)ll_count, (map_print_t)ll_print, (map_free_t)ll_free
31 };
32
33 const map_impl_t *MAP_TYPE_LIST = &ll_map_impl;
34
35 static node_t *node_alloc (void *key, uint64_t val) {
36     node_t *item = (node_t *)nbd_malloc(sizeof(node_t));
37     item->key = key;
38     item->val = val;
39     return item;
40 }
41
42 list_t *ll_alloc (cmp_fun_t cmp_fun, hash_fun_t hash_fun, clone_fun_t clone_fun) {
43     list_t *ll = (list_t *)nbd_malloc(sizeof(list_t));
44     ll->cmp_fun = cmp_fun;
45     ll->clone_fun = clone_fun;
46     ll->head = node_alloc(NULL, 0);
47     ll->head->next = NULL;
48     return ll;
49 }
50
51 void ll_free (list_t *ll) {
52     node_t *item = ll->head->next;
53     while (item) {
54         node_t *next = (node_t *)STRIP_TAG(item->next);
55         nbd_free(item);
56         item = next;
57     }
58 }
59
60 uint64_t ll_count (list_t *ll) {
61     uint64_t count = 0;
62     node_t *item = ll->head->next;
63     while (item) {
64         count++;
65         item = (node_t *)STRIP_TAG(item->next);
66     }
67     return count;
68 }
69
70 static int find_pred (node_t **pred_ptr, node_t **item_ptr, list_t *ll, void *key, int help_remove) {
71     node_t *pred = ll->head;
72     node_t *item = pred->next;
73     TRACE("l2", "find_pred: searching for key %p in list (head is %p)", key, pred);
74
75     while (item != NULL) {
76         node_t *next = item->next;
77
78         // A tag means an item is logically removed but not physically unlinked yet.
79         while (EXPECT_FALSE(IS_TAGGED(next))) {
80
81             // Skip over logically removed items.
82             if (!help_remove) {
83                 item = (node_t *)STRIP_TAG(item->next);
84                 if (EXPECT_FALSE(item == NULL))
85                     break;
86                 TRACE("l3", "find_pred: skipping marked item %p (next is %p)", item, next);
87                 next = item->next;
88                 continue;
89             }
90
91             // Unlink logically removed items.
92             node_t *other;
93             TRACE("l3", "find_pred: unlinking marked item %p next is %p", item, next);
94             if ((other = SYNC_CAS(&pred->next, item, STRIP_TAG(next))) == item) {
95                 TRACE("l2", "find_pred: unlinked item %p from pred %p", item, pred);
96                 item = (node_t *)STRIP_TAG(next);
97                 if (EXPECT_FALSE(item == NULL))
98                     break;
99                 next = item->next;
100                 TRACE("l3", "find_pred: now current item is %p next is %p", item, next);
101
102                 // The thread that completes the unlink should free the memory.
103                 if (ll->clone_fun != NULL) {
104                     nbd_defer_free((void*)other->key);
105                 }
106                 nbd_defer_free(other);
107             } else {
108                 TRACE("l2", "find_pred: lost a race to unlink item %p from pred %p", item, pred);
109                 TRACE("l2", "find_pred: pred's link changed to %p", other, 0);
110                 if (IS_TAGGED(other))
111                     return find_pred(pred_ptr, item_ptr, ll, key, help_remove); // retry
112                 item = other;
113                 if (EXPECT_FALSE(item == NULL))
114                     break;
115                 next = item->next;
116             }
117         }
118
119         if (EXPECT_FALSE(item == NULL))
120             break;
121
122         TRACE("l3", "find_pred: visiting item %p (next is %p)", item, next);
123         TRACE("l4", "find_pred: key %p val %p", item->key, item->val);
124
125         int d;
126         if (EXPECT_TRUE(ll->cmp_fun == NULL)) {
127             d = (uint64_t)item->key - (uint64_t)key;
128         } else {
129             d = ll->cmp_fun(item->key, key);
130         }
131
132         // If we reached the key (or passed where it should be), we found the right predesssor
133         if (d >= 0) {
134             if (pred_ptr != NULL) {
135                 *pred_ptr = pred;
136             }
137             *item_ptr = item;
138             if (d == 0) {
139                 TRACE("l2", "find_pred: found matching item %p in list, pred is %p", item, pred);
140                 return TRUE;
141             } 
142             TRACE("l2", "find_pred: found proper place for key %p in list, pred is %p", key, pred);
143             return FALSE;
144         }
145
146         pred = item;
147         item = next;
148     }
149
150     // <key> is not in <ll>.
151     if (pred_ptr != NULL) {
152         *pred_ptr = pred;
153     }
154     *item_ptr = NULL;
155     TRACE("l2", "find_pred: reached end of list. last item is %p", pred, 0);
156     return FALSE;
157 }
158
159 // Fast find. Do not help unlink partially removed nodes and do not return the found item's predecessor.
160 uint64_t ll_lookup (list_t *ll, void *key) {
161     TRACE("l1", "ll_lookup: searching for key %p in list %p", key, ll);
162     node_t *item;
163     int found = find_pred(NULL, &item, ll, key, FALSE);
164
165     // If we found an <item> matching the key return its value.
166     if (found) {
167         uint64_t val = item->val;
168         if (val != DOES_NOT_EXIST) {
169             TRACE("l1", "ll_lookup: found item %p. val %p. returning item", item, item->val);
170             return val;
171         }
172     }
173
174     TRACE("l1", "ll_lookup: no item in the list matched the key", 0, 0);
175     return DOES_NOT_EXIST;
176 }
177
178 uint64_t ll_cas (list_t *ll, void *key, uint64_t expectation, uint64_t new_val) {
179     TRACE("l1", "ll_cas: key %p list %p", key, ll);
180     TRACE("l1", "ll_cas: expectation %p new value %p", expectation, new_val);
181     ASSERT((int64_t)new_val > 0);
182
183     do {
184         node_t *pred, *old_item;
185         int found = find_pred(&pred, &old_item, ll, key, TRUE);
186         if (!found) {
187
188             // There was not an item in the list that matches the key. 
189             if (EXPECT_FALSE((int64_t)expectation > 0 || expectation == CAS_EXPECT_EXISTS)) {
190                 TRACE("l1", "ll_cas: the expectation was not met, the list was not changed", 0, 0);
191                 return DOES_NOT_EXIST; // failure
192             }
193
194             ASSERT(expectation == CAS_EXPECT_DOES_NOT_EXIST || expectation == CAS_EXPECT_WHATEVER);
195
196             // Create a new item and insert it into the list.
197             TRACE("l2", "ll_cas: attempting to insert item between %p and %p", pred, pred->next);
198             void *new_key  = (ll->clone_fun == NULL) ? key : ll->clone_fun(key);
199             node_t *new_item = node_alloc(new_key, new_val);
200             node_t *next = new_item->next = old_item;
201             node_t *other = SYNC_CAS(&pred->next, next, new_item);
202             if (other == next) {
203                 TRACE("l1", "ll_cas: successfully inserted new item %p", new_item, 0);
204                 return DOES_NOT_EXIST; // success
205             }
206
207             // Lost a race. Failed to insert the new item into the list.
208             TRACE("l1", "ll_cas: lost a race. CAS failed. expected pred's link to be %p but found %p", next, other);
209             if (ll->clone_fun != NULL) {
210                 nbd_free(new_key);
211             }
212             nbd_free(new_item);
213             continue; // retry
214         }
215
216         // Found an item in the list that matches the key.
217         uint64_t old_item_val = old_item->val;
218         do {
219             // If the item's value is DOES_NOT_EXIST it means another thread removed the node out from under us.
220             if (EXPECT_FALSE(old_item_val == DOES_NOT_EXIST)) {
221                 TRACE("l2", "ll_cas: lost a race, found an item but another thread removed it. retry", 0, 0);
222                 break; // retry
223             }
224
225             if (EXPECT_FALSE(expectation == CAS_EXPECT_DOES_NOT_EXIST)) {
226                 TRACE("l1", "ll_cas: found an item %p in the list that matched the key. the expectation was "
227                         "not met, the list was not changed", old_item, old_item_val);
228                 return old_item_val; // failure
229             }
230
231             // Use a CAS and not a SWAP. If the node is in the process of being removed and we used a SWAP, we could
232             // replace DOES_NOT_EXIST with our value. Then another thread that is updating the value could think it
233             // succeeded and return our value even though we indicated that the node has been removed. If the CAS 
234             // fails it means another thread either removed the node or updated its value.
235             uint64_t ret_val = SYNC_CAS(&old_item->val, old_item_val, new_val);
236             if (ret_val == old_item_val) {
237                 TRACE("l1", "ll_cas: the CAS succeeded. updated the value of the item", 0, 0);
238                 return ret_val; // success
239             }
240             TRACE("l2", "ll_cas: lost a race. the CAS failed. another thread changed the item's value", 0, 0);
241
242             old_item_val = ret_val;
243         } while (1);
244     } while (1);
245 }
246
247 uint64_t ll_remove (list_t *ll, void *key) {
248     TRACE("l1", "ll_remove: removing item with key %p from list %p", key, ll);
249     node_t *pred;
250     node_t *item;
251     int found = find_pred(&pred, &item, ll, key, TRUE);
252     if (!found) {
253         TRACE("l1", "ll_remove: remove failed, an item with a matching key does not exist in the list", 0, 0);
254         return DOES_NOT_EXIST;
255     }
256
257     // Mark <item> removed. This must be atomic. If multiple threads try to remove the same item
258     // only one of them should succeed.
259     node_t *next;
260     node_t *old_next = item->next;
261     do {
262         next = old_next;
263         old_next = SYNC_CAS(&item->next, next, TAG_VALUE(next));
264         if (IS_TAGGED(old_next)) {
265             TRACE("l1", "ll_remove: lost a race -- %p is already marked for removal by another thread", item, 0);
266             return DOES_NOT_EXIST;
267         }
268     } while (next != old_next);
269     TRACE("l2", "ll_remove: logically removed item %p", item, 0);
270     ASSERT(IS_TAGGED(item->next));
271
272     // This has to be an atomic swap in case another thread is updating the item while we are removing it. 
273     uint64_t val = SYNC_SWAP(&item->val, DOES_NOT_EXIST); 
274     TRACE("l2", "ll_remove: replaced item's val %p with DOES_NOT_EXIT", val, 0);
275
276     // Unlink <item> from <ll>. If we lose a race to another thread just back off. It is safe to leave the
277     // item logically removed for a later call (or some other thread) to physically unlink. By marking the
278     // item earlier, we logically removed it. 
279     TRACE("l2", "ll_remove: unlink the item by linking its pred %p to its successor %p", pred, next);
280     node_t *other;
281     if ((other = SYNC_CAS(&pred->next, item, next)) != item) {
282         TRACE("l1", "ll_remove: unlink failed; pred's link changed from %p to %p", item, other);
283         return val;
284     } 
285
286     // The thread that completes the unlink should free the memory.
287     if (ll->clone_fun != NULL) {
288         nbd_defer_free(item->key);
289     }
290     nbd_defer_free(item);
291     TRACE("l1", "ll_remove: successfully unlinked item %p from the list", item, 0);
292     return val;
293 }
294
295 void ll_print (list_t *ll) {
296     node_t *item;
297     item = ll->head->next;
298     int i = 0;
299     while (item) {
300         node_t *next = item->next;
301         if (IS_TAGGED(item)) {
302             printf("*");
303         }
304         printf("%p:%p ", item, item->key);
305         fflush(stdout);
306         item = (node_t *)STRIP_TAG(next);
307         if (i++ > 30) {
308             printf("...");
309             break;
310         }
311     }
312     printf("\n");
313 }