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