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