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