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