]> pd.if.org Git - nbds/blob - txn/txn.c
a932f66a3d9f79b05121a3da9f776c55397c4ea4
[nbds] / txn / txn.c
1 /*
2  * Written by Josh Dybnis and released to the public domain, as explained at
3  * http://creativecommons.org/licenses/publicdomain
4  */
5 #include "common.h"
6 #include "txn.h"
7 #include "mem.h"
8 #include "rcu.h"
9 #include "lwt.h"
10 #include "skiplist.h"
11
12 #define UNDETERMINED_VERSION 0
13 #define ABORTED_VERSION      TAG_VALUE(0, TAG1)
14 #define INITIAL_WRITES_SIZE  4
15 #define PTR_TO_VAL(x) ((size_t)(x) >> 2)
16 #define VAL_TO_PTR(x) ((update_t *)((x) << 2))
17
18 typedef struct update_rec update_t;
19 typedef map_key_t version_t;
20
21 struct update_rec {
22     version_t version; // tagged versions are txn_t pointers, untagged are actual version numbers
23     map_val_t value;
24     map_val_t next; // an earlier update
25 };
26
27 typedef struct write_rec {
28     map_key_t key;
29     update_t *rec;
30 } write_rec_t;
31
32 struct txn {
33     version_t rv;
34     version_t wv;
35     map_t *map;
36     write_rec_t *writes;
37     size_t writes_size;
38     size_t writes_count;
39     size_t writes_scan;
40     txn_state_e state;
41 };
42
43 static txn_state_e txn_validate (txn_t *txn);
44
45 static version_t version_ = 1;
46
47 static skiplist_t *active_ = NULL;
48
49 __attribute__ ((constructor)) void txn_init (void) {
50     active_ = sl_alloc(NULL);
51 }
52
53 // Validate the updates for <key>. Validation fails if there is a write-write conflict. That is if after our
54 // read version another transaction committed a change to an entry we are also trying to change.
55 //
56 // If we encounter a potential conflict with a transaction that is in the process of validating, we help it
57 // complete validating. It must be finished before we can decide to rollback or commit.
58 //
59 static txn_state_e validate_key (txn_t *txn, map_key_t key) {
60     assert(txn->state != TXN_RUNNING);
61
62     map_val_t val = map_get(txn->map, key);
63     update_t *update = NULL;
64     for (; val != DOES_NOT_EXIST; val = update->next) {
65
66         // If the update or its version is not tagged it means the update is committed.
67         //
68         // We can stop at the first committed record we find that is at least as old as our read version. All
69         // the other committed records following it will be older. And all the uncommitted records following it
70         // will eventually conflict with it and abort.
71         if (!IS_TAGGED(val, TAG2))
72             return TXN_VALIDATED;
73         update = VAL_TO_PTR(val);
74         if (!IS_TAGGED(update->version, TAG1))
75             return (update->version <= txn->rv) ? TXN_VALIDATED : TXN_ABORTED;
76
77         // If the update's version is tagged then either the update was aborted or the the version number is
78         // actually a pointer to a running transaction's txn_t.
79
80         // Skip aborted transactions.
81         if (EXPECT_FALSE(update->version == ABORTED_VERSION))
82             continue;
83
84         // The update's transaction is still in progress. Access its txn_t.
85         txn_t *writer = (txn_t *)VAL_TO_PTR(update->version);
86         if (writer == txn)
87             continue; // Skip our own updates.
88         txn_state_e writer_state = writer->state;
89
90         // Any running transaction will only be able to acquire a wv greater than ours. A transaction changes its
91         // state to validating before aquiring a wv. We can ignore an unvalidated transaction if its version is
92         // greater than ours. See the next comment below for the explination why.
93         if (writer_state == TXN_RUNNING)
94             continue;
95
96         // If <writer> has a later version than us we can safely ignore its updates. It will not commit until
97         // we have completed validation (in order to remain non-blocking it will help us validate if necessary).
98         // This protocol ensures a deterministic resolution to every conflict and avoids infinite ping-ponging
99         // between validating two conflicting transactions.
100         if (writer_state == TXN_VALIDATING) {
101             if (writer->wv > txn->wv)
102                 continue;
103             // Help <writer> commit. We need to know if <writer> aborts or commits before we can decide what to
104             // do. But we don't want to block, so we assist.
105             writer_state = txn_validate(writer);
106         }
107
108         // Skip updates from aborted transactions.
109         if (writer_state == TXN_ABORTED)
110             continue;
111
112         assert(writer_state == TXN_VALIDATED);
113         return (writer->wv <= txn->rv) ? TXN_VALIDATED : TXN_ABORTED;
114     }
115
116     return TXN_VALIDATED;
117 }
118
119 static txn_state_e txn_validate (txn_t *txn) {
120     assert(txn->state != TXN_RUNNING);
121     int i;
122     switch (txn->state) {
123
124         case TXN_VALIDATING:
125             if (txn->wv == UNDETERMINED_VERSION) {
126                 version_t wv = SYNC_ADD(&version_, 1);
127                 SYNC_CAS(&txn->wv, UNDETERMINED_VERSION, wv);
128             }
129
130             for (i = 0; i < txn->writes_count; ++i) {
131                 txn_state_e s = validate_key(txn, txn->writes[i].key);
132                 if (s == TXN_ABORTED) {
133                     txn->state = TXN_ABORTED;
134                     break;
135                 }
136                 assert(s == TXN_VALIDATED);
137             }
138             if (txn->state == TXN_VALIDATING) {
139                 txn->state =  TXN_VALIDATED;
140             }
141             break;
142
143         case TXN_VALIDATED:
144         case TXN_ABORTED:
145             break;
146
147         default:
148             assert(FALSE);
149     }
150
151     return txn->state;
152 }
153
154 static update_t *alloc_update_rec (version_t ver, map_val_t val) {
155     update_t *u = (update_t *)nbd_malloc(sizeof(update_t));
156     u->version = ver;
157     u->value = val;
158     u->next = DOES_NOT_EXIST;
159     return u;
160 }
161
162 txn_t *txn_begin (map_t *map) {
163     TRACE("x1", "txn_begin: map %p", map, 0);
164     txn_t *txn = (txn_t *)nbd_malloc(sizeof(txn_t));
165     memset(txn, 0, sizeof(txn_t));
166     txn->wv = UNDETERMINED_VERSION;
167     txn->state = TXN_RUNNING;
168     txn->map = map;
169     txn->writes = nbd_malloc(sizeof(*txn->writes) * INITIAL_WRITES_SIZE);
170     txn->writes_size = INITIAL_WRITES_SIZE;
171
172     // acquire the read version for txn. must be careful to avoid a race
173     do {
174         txn->rv = version_;
175
176         unsigned old_count;
177         unsigned temp = 0;
178         do {
179             old_count = temp;
180             temp = sl_cas(active_, txn->rv, old_count, old_count + 1);
181         } while (temp != old_count);
182
183         if (txn->rv == version_)
184             break;
185
186         temp = 1;
187         do {
188             old_count = temp;
189             temp = sl_cas(active_, (map_key_t)txn->rv, old_count, old_count - 1);
190         } while (temp != old_count);
191     } while (1);
192
193     TRACE("x1", "txn_begin: returning new transaction %p (read version %p)", txn, txn->rv);
194     return txn;
195 }
196
197 void txn_abort (txn_t *txn) {
198     if (txn->state != TXN_RUNNING)
199         return;
200
201     int i;
202     for (i = 0; i < txn->writes_count; ++i) {
203         update_t *update = (update_t *)txn->writes[i].rec;
204         update->version = ABORTED_VERSION;
205     }
206
207     rcu_defer_free(txn->writes);
208     rcu_defer_free(txn);
209 }
210
211 txn_state_e txn_commit (txn_t *txn) {
212     if (txn->state != TXN_RUNNING)
213         return txn->state;
214
215     assert(txn->state == TXN_RUNNING);
216     txn->state = TXN_VALIDATING;
217     txn_state_e state = txn_validate(txn);
218
219     // Detach <txn> from its updates.
220     version_t wv = (txn->state == TXN_ABORTED) ? ABORTED_VERSION : txn->wv;
221     int i;
222     for (i = 0; i < txn->writes_count; ++i) {
223         update_t *update = txn->writes[i].rec;
224         update->version = wv;
225     }
226
227     // Lower the reference count for <txn>'s read version
228     unsigned temp = 2;
229     unsigned old_count;
230     do {
231         old_count = temp;
232         temp = sl_cas(active_, (map_key_t)txn->rv, old_count, old_count - 1);
233         if (temp == 1 && txn->rv != version_) {
234             sl_remove(active_, (map_key_t)txn->rv);
235             break;
236         }
237     } while (old_count != temp);
238
239     rcu_defer_free(txn->writes);
240     rcu_defer_free(txn);
241
242     return state;
243 }
244
245 // Get most recent committed version prior to our read version.
246 map_val_t txn_map_get (txn_t *txn, map_key_t key) {
247     TRACE("x1", "txn_map_get: txn %p map %p", txn, txn->map);
248     TRACE("x1", "txn_map_get: key %p", key, 0);
249
250     if (txn->state != TXN_RUNNING) {
251         TRACE("x1", "txn_map_get: error txn not running (state %p)", txn->state, 0);
252         return ERROR_TXN_NOT_RUNNING;
253     }
254
255     // Iterate through the update records to find the latest committed version prior to our read version.
256     map_val_t newest_val = map_get(txn->map, key);
257     map_val_t val = newest_val;
258     update_t *update;
259     for ( ; (update = VAL_TO_PTR(val)) != NULL ; val = update->next) {
260
261         // If TAG2 is set in <val> it indicates that <val> is an update record. Otherwise all the following are
262         // true: <val> is a literal value, it is older than any currently active transaction, and it is the most
263         // recently set value for its key. Therefore it is visible to <txn>.
264         if (!IS_TAGGED(val, TAG2)) {
265             TRACE("x1", "txn_map_get: found untagged value; returning %p", val, 0);
266             return val;
267         }
268
269         // If the update's version is not tagged it means the update is committed.
270         if (!IS_TAGGED(update->version, TAG1)) {
271             if (update->version <= txn->rv) {
272                 TRACE("x2", "txn_map_get: found committed update %p (version %p)", update, update->version);
273                 break; // success
274             }
275             TRACE("x2", "txn_map_get: skipping update %p (version %p)", update, update->version);
276             continue;
277         }
278
279         // If the update's version is tagged then either the update was aborted or the the version number is
280         // actually a pointer to a running transaction's txn_t.
281
282         // Skip updates from aborted transactions.
283         if (EXPECT_FALSE(update->version == ABORTED_VERSION)) {
284             TRACE("x2", "txn_map_get: skipping aborted update %p", update, 0);
285             continue;
286         }
287
288         // The update's transaction is still in progress. Access its txn_t.
289         txn_t *writer = (txn_t *)VAL_TO_PTR(update->version);
290         if (writer == txn) { 
291             TRACE("x2", "txn_map_get: found txn's own update %p", update, 0);
292             break; // success
293         }
294
295         txn_state_e writer_state = writer->state;
296         if (writer_state == TXN_RUNNING) {
297             TRACE("x2", "txn_map_get: skipping update %p of in-progress transaction %p", update, writer);
298             continue;
299         }
300
301         if (writer_state == TXN_VALIDATING) {
302             TRACE("x2", "txn_map_get: update %p transaction %p validating", update, writer);
303             if (writer->wv > txn->rv)
304                 continue;
305             writer_state = txn_validate(writer);
306         }
307
308         // Skip updates from aborted transactions.
309         if (writer_state == TXN_ABORTED) {
310             TRACE("x2", "txn_map_get: skipping aborted update %p", update, 0);
311             continue;
312         }
313
314         assert(writer_state == TXN_VALIDATED);
315         if (writer->wv > txn->rv) {
316             TRACE("x2", "txn_map_get: skipping update %p (version %p)", update, update->version);
317             continue;
318         }
319         break; // success
320     }
321
322     if (update == NULL) {
323         TRACE("x1", "txn_map_get: key does not exist in map", key, 0);
324         return DOES_NOT_EXIST;
325     }
326
327     map_val_t value = update->value;
328     TRACE("x1", "txn_map_get: key found returning value %p", value, 0);
329
330     return value;
331     // collect some garbage
332     version_t min_active_version = UNDETERMINED_VERSION;
333     update_t *next_update = NULL;
334     if (IS_TAGGED(update->next, TAG2)) {
335         next_update = VAL_TO_PTR(update->next);
336
337         // If <next_update> (and all update records following it [execpt if it is aborted]) is old enough
338         // that it is not visible to any active transaction we can safely free it.
339         min_active_version = (version_t)sl_min_key(active_);
340         if (next_update->version < min_active_version) {
341
342             // If the <next_update> is aborted, skip over it to look for more recent ones that may follow
343             update_t *temp = next_update;
344             while (temp->version == ABORTED_VERSION) {
345                 assert(!IS_TAGGED(temp->version, TAG1));
346                 map_val_t next = temp->next;
347                 if (!IS_TAGGED(next, TAG2))
348                     break;
349
350                 // Bail out of garbage collection if we find a record that might still be accessed by an
351                 // ongoing transaction.
352                 if (VAL_TO_PTR(next)->version >= min_active_version)
353                     return value;
354
355                 temp = VAL_TO_PTR(next);
356             }
357
358             // free the next update record and all the ones following it
359             temp = next_update;
360             map_val_t next;
361             do {
362                 next = SYNC_SWAP(&temp->next, DOES_NOT_EXIST);
363
364                 // if we find ourself in a race just back off and let the other thread take care of it
365                 if (next == DOES_NOT_EXIST)
366                     return value;
367
368                 nbd_free(temp);
369
370                 temp = VAL_TO_PTR(next);
371
372             } while (IS_TAGGED(next, TAG2));
373         }
374     }
375
376     // If there is one item left and it is visible by all active transactions we can merge it into the map itself.
377     // There is no need for an update record.
378     if (next_update == NULL && val == newest_val) {
379         if (min_active_version == UNDETERMINED_VERSION) {
380             min_active_version = (version_t)sl_min_key(active_);
381         }
382         if (update->version <= min_active_version) {
383             if (map_cas(txn->map, key, TAG_VALUE(val, TAG2), value) == TAG_VALUE(val, TAG2)) {
384                 rcu_defer_free(update);
385             }
386         }
387     }
388
389     return value;
390 }
391
392 void txn_map_set (txn_t *txn, map_key_t key, map_val_t value) {
393     TRACE("x1", "txn_map_set: txn %p map %p", txn, txn->map);
394     TRACE("x1", "txn_map_set: key %p value %p", key, value);
395     assert(!IS_TAGGED(value, TAG1) && !IS_TAGGED(value, TAG2));
396
397     if (txn->state != TXN_RUNNING) {
398         TRACE("x1", "txn_map_set: error txn not running (state %p)", txn->state, 0);
399         return;
400     }
401
402     // create a new update record
403     version_t ver = TAG_VALUE(PTR_TO_VAL(txn), TAG1); // tagged versions are txn_t pointers
404     update_t *update = alloc_update_rec(ver, value);
405
406     // push the new update record onto <key>'s update list
407     map_val_t old_update = map_get(txn->map, key);
408     TRACE("x2", "txn_map_set: old update %p new update record %p", old_update, update);
409     do {
410         update->next = old_update;
411         map_val_t temp = map_cas(txn->map, key, old_update, TAG_VALUE(PTR_TO_VAL(update), TAG2));
412         if (temp == old_update) 
413             break;
414
415         TRACE("x1", "txn_map_set: cas failed; found %p expected %p", temp, old_update);
416         old_update = temp;
417     } while (1);
418
419     // add <key> to the write set for commit-time validation
420     if (txn->writes_count == txn->writes_size) {
421         write_rec_t *w = nbd_malloc(sizeof(write_rec_t) * txn->writes_size * 2);
422         memcpy(w, txn->writes, txn->writes_size * sizeof(write_rec_t));
423         txn->writes_size *= 2;
424         nbd_free(txn->writes);
425         txn->writes = w;
426     }
427     int i = txn->writes_count++;
428     txn->writes[i].key = key;
429     txn->writes[i].rec = update;
430 }