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