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