[project @ 2006-01-09 14:35:53 by simonmar]
[ghc-hetmet.git] / ghc / rts / STM.c
1 /* -----------------------------------------------------------------------------
2  * (c) The GHC Team 1998-2005
3  * 
4  * STM implementation.
5  *
6  * Overview
7  * --------
8  *
9  * See the PPoPP 2005 paper "Composable memory transactions".  In summary, 
10  * each transcation has a TRec (transaction record) holding entries for each of the
11  * TVars (transactional variables) that it has accessed.  Each entry records
12  * (a) the TVar, (b) the expected value seen in the TVar, (c) the new value that
13  * the transaction wants to write to the TVar, (d) during commit, the identity of
14  * the TRec that wrote the expected value.  
15  *
16  * Separate TRecs are used for each level in a nest of transactions.  This allows
17  * a nested transaction to be aborted without condemning its enclosing transactions.
18  * This is needed in the implementation of catchRetry.  Note that the "expected value"
19  * in a nested transaction's TRec is the value expected to be *held in memory* if
20  * the transaction commits -- not the "new value" stored in one of the enclosing
21  * transactions.  This means that validation can be done without searching through
22  * a nest of TRecs.
23  *
24  * Concurrency control
25  * -------------------
26  *
27  * Three different concurrency control schemes can be built according to the settings
28  * in STM.h:
29  * 
30  * STM_UNIPROC assumes that the caller serialises invocations on the STM interface.
31  * In the Haskell RTS this means it is suitable only for non-SMP builds.
32  *
33  * STM_CG_LOCK uses coarse-grained locking -- a single 'stm lock' is acquired during
34  * an invocation on the STM interface.  Note that this does not mean that 
35  * transactions are simply serialized -- the lock is only held *within* the 
36  * implementation of stmCommitTransaction, stmWait etc.
37  *
38  * STM_FG_LOCKS uses fine-grained locking -- locking is done on a per-TVar basis
39  * and, when committing a transaction, no locks are acquired for TVars that have
40  * been read but not updated.
41  *
42  * Concurrency control is implemented in the functions:
43  *
44  *    lock_stm
45  *    unlock_stm
46  *    lock_tvar / cond_lock_tvar
47  *    unlock_tvar
48  *
49  * The choice between STM_UNIPROC / STM_CG_LOCK / STM_FG_LOCKS affects the 
50  * implementation of these functions.  
51  *
52  * lock_stm & unlock_stm are straightforward : they acquire a simple spin-lock
53  * using STM_CG_LOCK, and otherwise they are no-ops.
54  *
55  * lock_tvar / cond_lock_tvar and unlock_tvar are more complex because they 
56  * have other effects (present in STM_UNIPROC and STM_CG_LOCK builds) as well
57  * as the actual business of maniupultaing a lock (present only in STM_FG_LOCKS
58  * builds).  This is because locking a TVar is implemented by writing the lock
59  * holder's TRec into the TVar's current_value field:
60  *
61  *   lock_tvar - lock a specified TVar (STM_FG_LOCKS only), returning the value 
62  *               it contained.
63  *
64  *   cond_lock_tvar - lock a specified TVar (STM_FG_LOCKS only) if it 
65  *               contains a specified value.  Return TRUE if this succeeds,
66  *               FALSE otherwise.
67  *
68  *   unlock_tvar - release the lock on a specified TVar (STM_FG_LOCKS only),
69  *               storing a specified value in place of the lock entry.
70  *
71  * Using these operations, the typcial pattern of a commit/validate/wait operation
72  * is to (a) lock the STM, (b) lock all the TVars being updated, (c) check that 
73  * the TVars that were only read from still contain their expected values, 
74  * (d) release the locks on the TVars, writing updates to them in the case of a 
75  * commit, (e) unlock the STM.
76  *
77  * Queues of waiting threads hang off the first_wait_queue_entry field of each
78  * TVar.  This may only be manipulated when holding that TVar's lock.  In
79  * particular, when a thread is putting itself to sleep, it mustn't release
80  * the TVar's lock until it has added itself to the wait queue and marked its
81  * TSO as BlockedOnSTM -- this makes sure that other threads will know to wake it.
82  *
83  * ---------------------------------------------------------------------------*/
84
85 #include "PosixSource.h"
86 #include "Rts.h"
87 #include "RtsFlags.h"
88 #include "RtsUtils.h"
89 #include "Schedule.h"
90 #include "SMP.h"
91 #include "STM.h"
92 #include "Storage.h"
93
94 #include <stdlib.h>
95 #include <stdio.h>
96
97 #define TRUE 1
98 #define FALSE 0
99
100 // ACQ_ASSERT is used for assertions which are only required for SMP builds with
101 // fine-grained locking. 
102
103 #if defined(STM_FG_LOCKS)
104 #define ACQ_ASSERT(_X) ASSERT(_X)
105 #define NACQ_ASSERT(_X) /*Nothing*/
106 #else
107 #define ACQ_ASSERT(_X) /*Nothing*/
108 #define NACQ_ASSERT(_X) ASSERT(_X)
109 #endif
110
111 /*......................................................................*/
112
113 // If SHAKE is defined then validation will sometime spuriously fail.  They helps test
114 // unusualy code paths if genuine contention is rare
115
116 #if defined(DEBUG)
117 #define SHAKE
118 #if defined(THREADED_RTS)
119 #define TRACE(_x...) IF_DEBUG(stm, debugBelch("STM  (task %p): ", (void *)(unsigned long)(unsigned int)osThreadId()); debugBelch ( _x ))
120 #else
121 #define TRACE(_x...) IF_DEBUG(stm, debugBelch ( _x ))
122 #endif
123 #else
124 #define TRACE(_x...) /*Nothing*/
125 #endif
126
127 #ifdef SHAKE
128 static const int do_shake = TRUE;
129 #else
130 static const int do_shake = FALSE;
131 #endif
132 static int shake_ctr = 0;
133 static int shake_lim = 1;
134
135 static int shake(void) {
136   if (do_shake) {
137     if (((shake_ctr++) % shake_lim) == 0) {
138       shake_ctr = 1;
139       shake_lim ++;
140       return TRUE;
141     } 
142     return FALSE;
143   } else {
144     return FALSE;
145   }
146 }
147
148 /*......................................................................*/
149
150 // Helper macros for iterating over entries within a transaction
151 // record
152
153 #define FOR_EACH_ENTRY(_t,_x,CODE) do {                                         \
154   StgTRecHeader *__t = (_t);                                                    \
155   StgTRecChunk *__c = __t -> current_chunk;                                     \
156   StgWord __limit = __c -> next_entry_idx;                                      \
157   TRACE("%p : FOR_EACH_ENTRY, current_chunk=%p limit=%ld\n", __t, __c, __limit); \
158   while (__c != END_STM_CHUNK_LIST) {                                           \
159     StgWord __i;                                                                \
160     for (__i = 0; __i < __limit; __i ++) {                                      \
161       TRecEntry *_x = &(__c -> entries[__i]);                                   \
162       do { CODE } while (0);                                                    \
163     }                                                                           \
164     __c = __c -> prev_chunk;                                                    \
165     __limit = TREC_CHUNK_NUM_ENTRIES;                                           \
166   }                                                                             \
167  exit_for_each:                                                                 \
168   if (FALSE) goto exit_for_each;                                                \
169 } while (0)
170
171 #define BREAK_FOR_EACH goto exit_for_each
172      
173 /*......................................................................*/
174
175 // if REUSE_MEMORY is defined then attempt to re-use descriptors, log chunks,
176 // and wait queue entries without GC
177
178 #define REUSE_MEMORY
179
180 /*......................................................................*/
181
182 #define IF_STM_UNIPROC(__X)  do { } while (0)
183 #define IF_STM_CG_LOCK(__X)  do { } while (0)
184 #define IF_STM_FG_LOCKS(__X) do { } while (0)
185
186 #if defined(STM_UNIPROC)
187 #undef IF_STM_UNIPROC
188 #define IF_STM_UNIPROC(__X)  do { __X } while (0)
189 static const StgBool use_read_phase = FALSE;
190
191 static void lock_stm(StgTRecHeader *trec STG_UNUSED) {
192   TRACE("%p : lock_stm()\n", trec);
193 }
194
195 static void unlock_stm(StgTRecHeader *trec STG_UNUSED) {
196   TRACE("%p : unlock_stm()\n", trec);
197 }
198
199 static StgClosure *lock_tvar(StgTRecHeader *trec STG_UNUSED, 
200                              StgTVar *s STG_UNUSED) {
201   StgClosure *result;
202   TRACE("%p : lock_tvar(%p)\n", trec, s);
203   result = s -> current_value;
204   return result;
205 }
206
207 static void unlock_tvar(StgTRecHeader *trec STG_UNUSED,
208                         StgTVar *s STG_UNUSED,
209                         StgClosure *c,
210                         StgBool force_update) {
211   TRACE("%p : unlock_tvar(%p)\n", trec, s);
212   if (force_update) {
213     s -> current_value = c;
214   }
215 }
216
217 static StgBool cond_lock_tvar(StgTRecHeader *trec STG_UNUSED, 
218                               StgTVar *s STG_UNUSED,
219                               StgClosure *expected) {
220   StgClosure *result;
221   TRACE("%p : cond_lock_tvar(%p, %p)\n", trec, s, expected);
222   result = s -> current_value;
223   TRACE("%p : %s\n", trec, (result == expected) ? "success" : "failure");
224   return (result == expected);
225 }
226 #endif
227
228 #if defined(STM_CG_LOCK) /*........................................*/
229
230 #undef IF_STM_CG_LOCK
231 #define IF_STM_CG_LOCK(__X)  do { __X } while (0)
232 static const StgBool use_read_phase = FALSE;
233 static volatile StgTRecHeader *smp_locked = NULL;
234
235 static void lock_stm(StgTRecHeader *trec) {
236   while (cas(&smp_locked, NULL, trec) != NULL) { }
237   TRACE("%p : lock_stm()\n", trec);
238 }
239
240 static void unlock_stm(StgTRecHeader *trec STG_UNUSED) {
241   TRACE("%p : unlock_stm()\n", trec);
242   ASSERT (smp_locked == trec);
243   smp_locked = 0;
244 }
245
246 static StgClosure *lock_tvar(StgTRecHeader *trec STG_UNUSED, 
247                              StgTVar *s STG_UNUSED) {
248   StgClosure *result;
249   TRACE("%p : lock_tvar(%p)\n", trec, s);
250   ASSERT (smp_locked == trec);
251   result = s -> current_value;
252   return result;
253 }
254
255 static void *unlock_tvar(StgTRecHeader *trec STG_UNUSED,
256                          StgTVar *s STG_UNUSED,
257                          StgClosure *c,
258                          StgBool force_update) {
259   TRACE("%p : unlock_tvar(%p, %p)\n", trec, s, c);
260   ASSERT (smp_locked == trec);
261   if (force_update) {
262     s -> current_value = c;
263   }
264 }
265
266 static StgBool cond_lock_tvar(StgTRecHeader *trec STG_UNUSED, 
267                                StgTVar *s STG_UNUSED,
268                                StgClosure *expected) {
269   StgClosure *result;
270   TRACE("%p : cond_lock_tvar(%p, %p)\n", trec, s, expected);
271   ASSERT (smp_locked == trec);
272   result = s -> current_value;
273   TRACE("%p : %d\n", result ? "success" : "failure");
274   return (result == expected);
275 }
276 #endif
277
278 #if defined(STM_FG_LOCKS) /*...................................*/
279
280 #undef IF_STM_FG_LOCKS
281 #define IF_STM_FG_LOCKS(__X) do { __X } while (0)
282 static const StgBool use_read_phase = TRUE;
283
284 static void lock_stm(StgTRecHeader *trec STG_UNUSED) {
285   TRACE("%p : lock_stm()\n", trec);
286 }
287
288 static void unlock_stm(StgTRecHeader *trec STG_UNUSED) {
289   TRACE("%p : unlock_stm()\n", trec);
290 }
291
292 static StgClosure *lock_tvar(StgTRecHeader *trec, 
293                              StgTVar *s STG_UNUSED) {
294   StgClosure *result;
295   TRACE("%p : lock_tvar(%p)\n", trec, s);
296   do {
297     do {
298       result = s -> current_value;
299     } while (GET_INFO(result) == &stg_TREC_HEADER_info);
300   } while (cas(&(s -> current_value), result, trec) != result);
301   return result;
302 }
303
304 static void unlock_tvar(StgTRecHeader *trec STG_UNUSED,
305                         StgTVar *s,
306                         StgClosure *c,
307                         StgBool force_update STG_UNUSED) {
308   TRACE("%p : unlock_tvar(%p, %p)\n", trec, s, c);
309   ASSERT(s -> current_value == trec);
310   s -> current_value = c;
311 }
312
313 static StgBool cond_lock_tvar(StgTRecHeader *trec, 
314                               StgTVar *s,
315                               StgClosure *expected) {
316   StgClosure *result;
317   TRACE("%p : cond_lock_tvar(%p, %p)\n", trec, s, expected);
318   result = cas(&(s -> current_value), expected, trec);
319   TRACE("%p : %s\n", trec, result ? "success" : "failure");
320   return (result == expected);
321 }
322 #endif
323
324 /*......................................................................*/
325
326 // Helper functions for thread blocking and unblocking
327
328 static void park_tso(StgTSO *tso) {
329   ASSERT(tso -> why_blocked == NotBlocked);
330   tso -> why_blocked = BlockedOnSTM;
331   tso -> block_info.closure = (StgClosure *) END_TSO_QUEUE;
332   TRACE("park_tso on tso=%p\n", tso);
333 }
334
335 static void unpark_tso(Capability *cap, StgTSO *tso) {
336   // We will continue unparking threads while they remain on one of the wait
337   // queues: it's up to the thread itself to remove it from the wait queues
338   // if it decides to do so when it is scheduled.
339   if (tso -> why_blocked == BlockedOnSTM) {
340     TRACE("unpark_tso on tso=%p\n", tso);
341     unblockOne(cap,tso);
342   } else {
343     TRACE("spurious unpark_tso on tso=%p\n", tso);
344   }
345 }
346
347 static void unpark_waiters_on(Capability *cap, StgTVar *s) {
348   StgTVarWaitQueue *q;
349   TRACE("unpark_waiters_on tvar=%p\n", s);
350   for (q = s -> first_wait_queue_entry; 
351        q != END_STM_WAIT_QUEUE; 
352        q = q -> next_queue_entry) {
353     unpark_tso(cap, q -> waiting_tso);
354   }
355 }
356
357 /*......................................................................*/
358
359 // Helper functions for downstream allocation and initialization
360
361 static StgTVarWaitQueue *new_stg_tvar_wait_queue(Capability *cap,
362                                                  StgTSO *waiting_tso) {
363   StgTVarWaitQueue *result;
364   result = (StgTVarWaitQueue *)allocateLocal(cap, sizeofW(StgTVarWaitQueue));
365   SET_HDR (result, &stg_TVAR_WAIT_QUEUE_info, CCS_SYSTEM);
366   result -> waiting_tso = waiting_tso;
367   return result;
368 }
369
370 static StgTRecChunk *new_stg_trec_chunk(Capability *cap) {
371   StgTRecChunk *result;
372   result = (StgTRecChunk *)allocateLocal(cap, sizeofW(StgTRecChunk));
373   SET_HDR (result, &stg_TREC_CHUNK_info, CCS_SYSTEM);
374   result -> prev_chunk = END_STM_CHUNK_LIST;
375   result -> next_entry_idx = 0;
376   return result;
377 }
378
379 static StgTRecHeader *new_stg_trec_header(Capability *cap,
380                                           StgTRecHeader *enclosing_trec) {
381   StgTRecHeader *result;
382   result = (StgTRecHeader *) allocateLocal(cap, sizeofW(StgTRecHeader));
383   SET_HDR (result, &stg_TREC_HEADER_info, CCS_SYSTEM);
384
385   result -> enclosing_trec = enclosing_trec;
386   result -> current_chunk = new_stg_trec_chunk(cap);
387
388   if (enclosing_trec == NO_TREC) {
389     result -> state = TREC_ACTIVE;
390   } else {
391     ASSERT(enclosing_trec -> state == TREC_ACTIVE ||
392            enclosing_trec -> state == TREC_CONDEMNED);
393     result -> state = enclosing_trec -> state;
394   }
395
396   return result;  
397 }
398
399 /*......................................................................*/
400
401 // Allocation / deallocation functions that retain per-capability lists
402 // of closures that can be re-used
403
404 static StgTVarWaitQueue *alloc_stg_tvar_wait_queue(Capability *cap,
405                                                    StgTSO *waiting_tso) {
406   StgTVarWaitQueue *result = NULL;
407   if (cap -> free_tvar_wait_queues == END_STM_WAIT_QUEUE) {
408     result = new_stg_tvar_wait_queue(cap, waiting_tso);
409   } else {
410     result = cap -> free_tvar_wait_queues;
411     result -> waiting_tso = waiting_tso;
412     cap -> free_tvar_wait_queues = result -> next_queue_entry;
413   }
414   return result;
415 }
416
417 static void free_stg_tvar_wait_queue(Capability *cap,
418                                      StgTVarWaitQueue *wq) {
419 #if defined(REUSE_MEMORY)
420   wq -> next_queue_entry = cap -> free_tvar_wait_queues;
421   cap -> free_tvar_wait_queues = wq;
422 #endif
423 }
424
425 static StgTRecChunk *alloc_stg_trec_chunk(Capability *cap) {
426   StgTRecChunk *result = NULL;
427   if (cap -> free_trec_chunks == END_STM_CHUNK_LIST) {
428     result = new_stg_trec_chunk(cap);
429   } else {
430     result = cap -> free_trec_chunks;
431     cap -> free_trec_chunks = result -> prev_chunk;
432     result -> prev_chunk = END_STM_CHUNK_LIST;
433     result -> next_entry_idx = 0;
434   }
435   return result;
436 }
437
438 static void free_stg_trec_chunk(Capability *cap, 
439                                 StgTRecChunk *c) {
440 #if defined(REUSE_MEMORY)
441   c -> prev_chunk = cap -> free_trec_chunks;
442   cap -> free_trec_chunks = c;
443 #endif
444 }
445
446 static StgTRecHeader *alloc_stg_trec_header(Capability *cap,
447                                             StgTRecHeader *enclosing_trec) {
448   StgTRecHeader *result = NULL;
449   if (cap -> free_trec_headers == NO_TREC) {
450     result = new_stg_trec_header(cap, enclosing_trec);
451   } else {
452     result = cap -> free_trec_headers;
453     cap -> free_trec_headers = result -> enclosing_trec;
454     result -> enclosing_trec = enclosing_trec;
455     result -> current_chunk -> next_entry_idx = 0;
456     if (enclosing_trec == NO_TREC) {
457       result -> state = TREC_ACTIVE;
458     } else {
459       ASSERT(enclosing_trec -> state == TREC_ACTIVE ||
460              enclosing_trec -> state == TREC_CONDEMNED);
461       result -> state = enclosing_trec -> state;
462     }
463   }
464   return result;
465 }
466
467 static void free_stg_trec_header(Capability *cap,
468                                  StgTRecHeader *trec) {
469 #if defined(REUSE_MEMORY)
470   StgTRecChunk *chunk = trec -> current_chunk -> prev_chunk;
471   while (chunk != END_STM_CHUNK_LIST) {
472     StgTRecChunk *prev_chunk = chunk -> prev_chunk;
473     free_stg_trec_chunk(cap, chunk);
474     chunk = prev_chunk;
475   } 
476   trec -> current_chunk -> prev_chunk = END_STM_CHUNK_LIST;
477   trec -> enclosing_trec = cap -> free_trec_headers;
478   cap -> free_trec_headers = trec;
479 #endif
480 }
481
482 /*......................................................................*/
483
484 // Helper functions for managing waiting lists
485
486 static void build_wait_queue_entries_for_trec(Capability *cap,
487                                       StgTSO *tso, 
488                                       StgTRecHeader *trec) {
489   ASSERT(trec != NO_TREC);
490   ASSERT(trec -> enclosing_trec == NO_TREC);
491   ASSERT(trec -> state == TREC_ACTIVE);
492
493   TRACE("%p : build_wait_queue_entries_for_trec()\n", trec);
494
495   FOR_EACH_ENTRY(trec, e, {
496     StgTVar *s;
497     StgTVarWaitQueue *q;
498     StgTVarWaitQueue *fq;
499     s = e -> tvar;
500     TRACE("%p : adding tso=%p to wait queue for tvar=%p\n", trec, tso, s);
501     ACQ_ASSERT(s -> current_value == trec);
502     NACQ_ASSERT(s -> current_value == e -> expected_value);
503     fq = s -> first_wait_queue_entry;
504     q = alloc_stg_tvar_wait_queue(cap, tso);
505     q -> next_queue_entry = fq;
506     q -> prev_queue_entry = END_STM_WAIT_QUEUE;
507     if (fq != END_STM_WAIT_QUEUE) {
508       fq -> prev_queue_entry = q;
509     }
510     s -> first_wait_queue_entry = q;
511     e -> new_value = (StgClosure *) q;
512   });
513 }
514
515 static void remove_wait_queue_entries_for_trec(Capability *cap,
516                                                StgTRecHeader *trec) {
517   ASSERT(trec != NO_TREC);
518   ASSERT(trec -> enclosing_trec == NO_TREC);
519   ASSERT(trec -> state == TREC_WAITING ||
520          trec -> state == TREC_CONDEMNED);
521
522   TRACE("%p : remove_wait_queue_entries_for_trec()\n", trec);
523
524   FOR_EACH_ENTRY(trec, e, {
525     StgTVar *s;
526     StgTVarWaitQueue *pq;
527     StgTVarWaitQueue *nq;
528     StgTVarWaitQueue *q;
529     s = e -> tvar;
530     StgClosure *saw = lock_tvar(trec, s);
531     q = (StgTVarWaitQueue *) (e -> new_value);
532     TRACE("%p : removing tso=%p from wait queue for tvar=%p\n", trec, q -> waiting_tso, s);
533     ACQ_ASSERT(s -> current_value == trec);
534     nq = q -> next_queue_entry;
535     pq = q -> prev_queue_entry;
536     if (nq != END_STM_WAIT_QUEUE) {
537       nq -> prev_queue_entry = pq;
538     }
539     if (pq != END_STM_WAIT_QUEUE) {
540       pq -> next_queue_entry = nq;
541     } else {
542       ASSERT (s -> first_wait_queue_entry == q);
543       s -> first_wait_queue_entry = nq;
544     }
545     free_stg_tvar_wait_queue(cap, q);
546     unlock_tvar(trec, s, saw, FALSE);
547   });
548 }
549  
550 /*......................................................................*/
551  
552 static TRecEntry *get_new_entry(Capability *cap,
553                                 StgTRecHeader *t) {
554   TRecEntry *result;
555   StgTRecChunk *c;
556   int i;
557
558   c = t -> current_chunk;
559   i = c -> next_entry_idx;
560   ASSERT(c != END_STM_CHUNK_LIST);
561
562   if (i < TREC_CHUNK_NUM_ENTRIES) {
563     // Continue to use current chunk
564     result = &(c -> entries[i]);
565     c -> next_entry_idx ++;
566   } else {
567     // Current chunk is full: allocate a fresh one
568     StgTRecChunk *nc;
569     nc = alloc_stg_trec_chunk(cap);
570     nc -> prev_chunk = c;
571     nc -> next_entry_idx = 1;
572     t -> current_chunk = nc;
573     result = &(nc -> entries[0]);
574   }
575
576   return result;
577 }
578
579 /*......................................................................*/
580
581 static void merge_update_into(Capability *cap,
582                               StgTRecHeader *t,
583                               StgTVar *tvar,
584                               StgClosure *expected_value,
585                               StgClosure *new_value) {
586   int found;
587   
588   // Look for an entry in this trec
589   found = FALSE;
590   FOR_EACH_ENTRY(t, e, {
591     StgTVar *s;
592     s = e -> tvar;
593     if (s == tvar) {
594       found = TRUE;
595       if (e -> expected_value != expected_value) {
596         // Must abort if the two entries start from different values
597         TRACE("%p : entries inconsistent at %p (%p vs %p)\n", 
598               t, tvar, e -> expected_value, expected_value);
599         t -> state = TREC_CONDEMNED;
600       } 
601       e -> new_value = new_value;
602       BREAK_FOR_EACH;
603     }
604   });
605
606   if (!found) {
607     // No entry so far in this trec
608     TRecEntry *ne;
609     ne = get_new_entry(cap, t);
610     ne -> tvar = tvar;
611     ne -> expected_value = expected_value;
612     ne -> new_value = new_value;
613   }
614 }
615
616 /*......................................................................*/
617
618 static StgBool entry_is_update(TRecEntry *e) {
619   StgBool result;
620   result = (e -> expected_value != e -> new_value);
621   return result;
622
623
624 static StgBool entry_is_read_only(TRecEntry *e) {
625   StgBool result;
626   result = (e -> expected_value == e -> new_value);
627   return result;
628
629
630 static StgBool tvar_is_locked(StgTVar *s, StgTRecHeader *h) {
631   StgClosure *c;
632   StgBool result;
633   c = s -> current_value;
634   result = (c == (StgClosure *) h);
635   return result;  
636 }
637
638 // revert_ownership : release a lock on a TVar, storing back
639 // the value that it held when the lock was acquired.  "revert_all"
640 // is set in stmWait and stmReWait when we acquired locks on all of 
641 // the TVars involved.  "revert_all" is not set in commit operations
642 // where we don't lock TVars that have been read from but not updated.
643
644 static void revert_ownership(StgTRecHeader *trec STG_UNUSED,
645                              StgBool revert_all STG_UNUSED) {
646 #if defined(STM_FG_LOCKS) 
647   FOR_EACH_ENTRY(trec, e, {
648     if (revert_all || entry_is_update(e)) {
649       StgTVar *s;
650       s = e -> tvar;
651       if (tvar_is_locked(s, trec)) {
652         unlock_tvar(trec, s, e -> expected_value, TRUE);
653       }
654     }
655   });
656 #endif
657 }
658
659 /*......................................................................*/
660
661 // validate_and_acquire_ownership : this performs the twin functions
662 // of checking that the TVars referred to by entries in trec hold the
663 // expected values and:
664 // 
665 //   - locking the TVar (on updated TVars during commit, or all TVars
666 //     during wait)
667 //
668 //   - recording the identity of the TRec who wrote the value seen in the
669 //     TVar (on non-updated TVars during commit).  These values are 
670 //     stashed in the TRec entries and are then checked in check_read_only
671 //     to ensure that an atomic snapshot of all of these locations has been
672 //     seen.
673
674 static StgBool validate_and_acquire_ownership (StgTRecHeader *trec, 
675                                                int acquire_all,
676                                                int retain_ownership) {
677   StgBool result;
678
679   if (shake()) {
680     TRACE("%p : shake, pretending trec is invalid when it may not be\n", trec);
681     return FALSE;
682   }
683
684   ASSERT ((trec -> state == TREC_ACTIVE) || 
685           (trec -> state == TREC_WAITING) ||
686           (trec -> state == TREC_CONDEMNED));
687   result = !((trec -> state) == TREC_CONDEMNED);
688   if (result) {
689     FOR_EACH_ENTRY(trec, e, {
690       StgTVar *s;
691       s = e -> tvar;
692       if (acquire_all || entry_is_update(e)) {
693         TRACE("%p : trying to acquire %p\n", trec, s);
694         if (!cond_lock_tvar(trec, s, e -> expected_value)) {
695           TRACE("%p : failed to acquire %p\n", trec, s);
696           result = FALSE;
697           BREAK_FOR_EACH;
698         }
699       } else {
700         ASSERT(use_read_phase);
701         IF_STM_FG_LOCKS({
702           TRACE("%p : will need to check %p\n", trec, s);
703           if (s -> current_value != e -> expected_value) {
704             TRACE("%p : doesn't match\n", trec);
705             result = FALSE;
706             BREAK_FOR_EACH;
707           }
708           e -> num_updates = s -> num_updates;
709           if (s -> current_value != e -> expected_value) {
710             TRACE("%p : doesn't match (race)\n", trec);
711             result = FALSE;
712             BREAK_FOR_EACH;
713           } else {
714             TRACE("%p : need to check version %d\n", trec, e -> num_updates);
715           }
716         });
717       }
718     });
719   }
720
721   if ((!result) || (!retain_ownership)) {
722     revert_ownership(trec, acquire_all);
723   }
724   
725   return result;
726 }
727
728 // check_read_only : check that we've seen an atomic snapshot of the
729 // non-updated TVars accessed by a trec.  This checks that the last TRec to
730 // commit an update to the TVar is unchanged since the value was stashed in
731 // validate_and_acquire_ownership.  If no udpate is seen to any TVar than
732 // all of them contained their expected values at the start of the call to
733 // check_read_only.
734 //
735 // The paper "Concurrent programming without locks" (under submission), or
736 // Keir Fraser's PhD dissertation "Practical lock-free programming" discuss
737 // this kind of algorithm.
738
739 static StgBool check_read_only(StgTRecHeader *trec STG_UNUSED) {
740   StgBool result = TRUE;
741
742   ASSERT (use_read_phase);
743   IF_STM_FG_LOCKS({
744     FOR_EACH_ENTRY(trec, e, {
745       StgTVar *s;
746       s = e -> tvar;
747       if (entry_is_read_only(e)) {
748         TRACE("%p : check_read_only for TVar %p, saw %d\n", trec, s, e -> num_updates);
749         if (s -> num_updates != e -> num_updates) {
750           // ||s -> current_value != e -> expected_value) {
751           TRACE("%p : mismatch\n", trec);
752           result = FALSE;
753           BREAK_FOR_EACH;
754         }
755       }
756     });
757   });
758
759   return result;
760 }
761
762
763 /************************************************************************/
764
765 void stmPreGCHook() {
766   nat i;
767
768   lock_stm(NO_TREC);
769   TRACE("stmPreGCHook\n");
770   for (i = 0; i < n_capabilities; i ++) {
771     Capability *cap = &capabilities[i];
772     cap -> free_tvar_wait_queues = END_STM_WAIT_QUEUE;
773     cap -> free_trec_chunks = END_STM_CHUNK_LIST;
774     cap -> free_trec_headers = NO_TREC;
775   }
776   unlock_stm(NO_TREC);
777 }
778
779 /************************************************************************/
780
781 // check_read_only relies on version numbers held in TVars' "num_updates" 
782 // fields not wrapping around while a transaction is committed.  The version
783 // number is incremented each time an update is committed to the TVar
784 // This is unlikely to wrap around when 32-bit integers are used for the counts, 
785 // but to ensure correctness we maintain a shared count on the maximum
786 // number of commit operations that may occur and check that this has 
787 // not increased by more than 2^32 during a commit.
788
789 #define TOKEN_BATCH_SIZE 1024
790
791 static volatile StgInt64 max_commits = 0;
792
793 static volatile StgBool token_locked = FALSE;
794
795 #if defined(SMP)
796 static void getTokenBatch(Capability *cap) {
797   while (cas(&token_locked, FALSE, TRUE) == TRUE) { /* nothing */ }
798   max_commits += TOKEN_BATCH_SIZE;
799   cap -> transaction_tokens = TOKEN_BATCH_SIZE;
800   token_locked = FALSE;
801 }
802
803 static void getToken(Capability *cap) {
804   if (cap -> transaction_tokens == 0) {
805     getTokenBatch(cap);
806   }
807   cap -> transaction_tokens --;
808 }
809 #else
810 static void getToken(Capability *cap STG_UNUSED) {
811   // Nothing
812 }
813 #endif
814
815 /*......................................................................*/
816
817 StgTRecHeader *stmStartTransaction(Capability *cap,
818                                    StgTRecHeader *outer) {
819   StgTRecHeader *t;
820   TRACE("%p : stmStartTransaction with %d tokens\n", 
821         outer, 
822         cap -> transaction_tokens);
823
824   getToken(cap);
825
826   t = alloc_stg_trec_header(cap, outer);
827   TRACE("%p : stmStartTransaction()=%p\n", outer, t);
828   return t;
829 }
830
831 /*......................................................................*/
832
833 void stmAbortTransaction(Capability *cap,
834                          StgTRecHeader *trec) {
835   TRACE("%p : stmAbortTransaction\n", trec);
836   ASSERT (trec != NO_TREC);
837   ASSERT ((trec -> state == TREC_ACTIVE) || 
838           (trec -> state == TREC_WAITING) ||
839           (trec -> state == TREC_CONDEMNED));
840
841   lock_stm(trec);
842   if (trec -> state == TREC_WAITING) {
843     ASSERT (trec -> enclosing_trec == NO_TREC);
844     TRACE("%p : stmAbortTransaction aborting waiting transaction\n", trec);
845     remove_wait_queue_entries_for_trec(cap, trec);
846   } 
847   trec -> state = TREC_ABORTED;
848   unlock_stm(trec);
849
850   free_stg_trec_header(cap, trec);
851
852   TRACE("%p : stmAbortTransaction done\n", trec);
853 }
854
855 /*......................................................................*/
856
857 void stmCondemnTransaction(Capability *cap,
858                            StgTRecHeader *trec) {
859   TRACE("%p : stmCondemnTransaction\n", trec);
860   ASSERT (trec != NO_TREC);
861   ASSERT ((trec -> state == TREC_ACTIVE) || 
862           (trec -> state == TREC_WAITING) ||
863           (trec -> state == TREC_CONDEMNED));
864
865   lock_stm(trec);
866   if (trec -> state == TREC_WAITING) {
867     ASSERT (trec -> enclosing_trec == NO_TREC);
868     TRACE("%p : stmCondemnTransaction condemning waiting transaction\n", trec);
869     remove_wait_queue_entries_for_trec(cap, trec);
870   } 
871   trec -> state = TREC_CONDEMNED;
872   unlock_stm(trec);
873
874   TRACE("%p : stmCondemnTransaction done\n", trec);
875 }
876
877 /*......................................................................*/
878
879 StgTRecHeader *stmGetEnclosingTRec(StgTRecHeader *trec) {
880   StgTRecHeader *outer;
881   TRACE("%p : stmGetEnclosingTRec\n", trec);
882   outer = trec -> enclosing_trec;
883   TRACE("%p : stmGetEnclosingTRec()=%p\n", trec, outer);
884   return outer;
885 }
886
887 /*......................................................................*/
888
889 StgBool stmValidateNestOfTransactions(StgTRecHeader *trec) {
890   StgTRecHeader *t;
891   StgBool result;
892
893   TRACE("%p : stmValidateNestOfTransactions\n", trec);
894   ASSERT(trec != NO_TREC);
895   ASSERT((trec -> state == TREC_ACTIVE) || 
896          (trec -> state == TREC_WAITING) ||
897          (trec -> state == TREC_CONDEMNED));
898
899   lock_stm(trec);
900
901   t = trec;
902   result = TRUE;
903   while (t != NO_TREC) {
904     result &= validate_and_acquire_ownership(t, TRUE, FALSE);
905     t = t -> enclosing_trec;
906   }
907
908   if (!result && trec -> state != TREC_WAITING) {
909     trec -> state = TREC_CONDEMNED; 
910   }
911
912   unlock_stm(trec);
913
914   TRACE("%p : stmValidateNestOfTransactions()=%d\n", trec, result);
915   return result;
916 }
917
918 /*......................................................................*/
919
920 StgBool stmCommitTransaction(Capability *cap, StgTRecHeader *trec) {
921   int result;
922   StgInt64 max_commits_at_start = max_commits;
923
924   TRACE("%p : stmCommitTransaction()\n", trec);
925   ASSERT (trec != NO_TREC);
926
927   lock_stm(trec);
928
929   ASSERT (trec -> enclosing_trec == NO_TREC);
930   ASSERT ((trec -> state == TREC_ACTIVE) || 
931           (trec -> state == TREC_CONDEMNED));
932
933   result = validate_and_acquire_ownership(trec, (!use_read_phase), TRUE);
934   if (result) {
935     // We now know that all the updated locations hold their expected values.
936     ASSERT (trec -> state == TREC_ACTIVE);
937
938     if (use_read_phase) {
939       TRACE("%p : doing read check\n", trec);
940       result = check_read_only(trec);
941       TRACE("%p : read-check %s\n", trec, result ? "succeeded" : "failed");
942
943       StgInt64 max_commits_at_end = max_commits;
944       StgInt64 max_concurrent_commits;
945       max_concurrent_commits = ((max_commits_at_end - max_commits_at_start) +
946                                 (n_capabilities * TOKEN_BATCH_SIZE));
947       if (((max_concurrent_commits >> 32) > 0) || shake()) {
948         result = FALSE;
949       }
950     }
951     
952     if (result) {
953       // We now know that all of the read-only locations held their exepcted values
954       // at the end of the call to validate_and_acquire_ownership.  This forms the
955       // linearization point of the commit.
956       
957       FOR_EACH_ENTRY(trec, e, {
958         StgTVar *s;
959         s = e -> tvar;
960         if (e -> new_value != e -> expected_value) {
961           // Entry is an update: write the value back to the TVar, unlocking it if
962           // necessary.
963
964           ACQ_ASSERT(tvar_is_locked(s, trec));
965           TRACE("%p : writing %p to %p, waking waiters\n", trec, e -> new_value, s);
966           unpark_waiters_on(cap,s);
967           IF_STM_FG_LOCKS({
968             s -> num_updates ++;
969           });
970           unlock_tvar(trec, s, e -> new_value, TRUE);
971         } 
972         ACQ_ASSERT(!tvar_is_locked(s, trec));
973       });
974     } else {
975       revert_ownership(trec, FALSE);
976     }
977   } 
978
979   unlock_stm(trec);
980
981   free_stg_trec_header(cap, trec);
982
983   TRACE("%p : stmCommitTransaction()=%d\n", trec, result);
984
985   return result;
986 }
987
988 /*......................................................................*/
989
990 StgBool stmCommitNestedTransaction(Capability *cap, StgTRecHeader *trec) {
991   StgTRecHeader *et;
992   int result;
993   ASSERT (trec != NO_TREC && trec -> enclosing_trec != NO_TREC);
994   TRACE("%p : stmCommitNestedTransaction() into %p\n", trec, trec -> enclosing_trec);
995   ASSERT ((trec -> state == TREC_ACTIVE) || (trec -> state == TREC_CONDEMNED));
996
997   lock_stm(trec);
998
999   et = trec -> enclosing_trec;
1000   result = validate_and_acquire_ownership(trec, FALSE, TRUE);
1001   if (result) {
1002     // We now know that all the updated locations hold their expected values.
1003
1004     if (use_read_phase) {
1005       TRACE("%p : doing read check\n", trec);
1006       result = check_read_only(trec);
1007     }
1008     if (result) {
1009       // We now know that all of the read-only locations held their exepcted values
1010       // at the end of the call to validate_and_acquire_ownership.  This forms the
1011       // linearization point of the commit.
1012
1013       if (result) {
1014         TRACE("%p : read-check succeeded\n", trec);
1015         FOR_EACH_ENTRY(trec, e, {
1016           // Merge each entry into the enclosing transaction record, release all
1017           // locks.
1018
1019           StgTVar *s;
1020           s = e -> tvar;
1021           if (entry_is_update(e)) {
1022             unlock_tvar(trec, s, e -> expected_value, FALSE);
1023           }
1024           merge_update_into(cap, et, s, e -> expected_value, e -> new_value);
1025           ACQ_ASSERT(s -> current_value != trec);
1026         });
1027       } else {
1028         revert_ownership(trec, FALSE);
1029       }
1030     }
1031   } 
1032
1033   unlock_stm(trec);
1034
1035   free_stg_trec_header(cap, trec);
1036
1037   TRACE("%p : stmCommitNestedTransaction()=%d\n", trec, result);
1038
1039   return result;
1040 }
1041
1042 /*......................................................................*/
1043
1044 StgBool stmWait(Capability *cap, StgTSO *tso, StgTRecHeader *trec) {
1045   int result;
1046   TRACE("%p : stmWait(%p)\n", trec, tso);
1047   ASSERT (trec != NO_TREC);
1048   ASSERT (trec -> enclosing_trec == NO_TREC);
1049   ASSERT ((trec -> state == TREC_ACTIVE) || 
1050           (trec -> state == TREC_CONDEMNED));
1051
1052   lock_stm(trec);
1053   result = validate_and_acquire_ownership(trec, TRUE, TRUE);
1054   if (result) {
1055     // The transaction is valid so far so we can actually start waiting.
1056     // (Otherwise the transaction was not valid and the thread will have to
1057     // retry it).
1058
1059     // Put ourselves to sleep.  We retain locks on all the TVars involved
1060     // until we are sound asleep : (a) on the wait queues, (b) BlockedOnSTM
1061     // in the TSO, (c) TREC_WAITING in the Trec.  
1062     build_wait_queue_entries_for_trec(cap, tso, trec);
1063     park_tso(tso);
1064     trec -> state = TREC_WAITING;
1065
1066     // We haven't released ownership of the transaction yet.  The TSO
1067     // has been put on the wait queue for the TVars it is waiting for,
1068     // but we haven't yet tidied up the TSO's stack and made it safe
1069     // to wake up the TSO.  Therefore, we must wait until the TSO is
1070     // safe to wake up before we release ownership - when all is well,
1071     // the runtime will call stmWaitUnlock() below, with the same
1072     // TRec.
1073
1074   } else {
1075     unlock_stm(trec);
1076     free_stg_trec_header(cap, trec);
1077   }
1078
1079   TRACE("%p : stmWait(%p)=%d\n", trec, tso, result);
1080   return result;
1081 }
1082
1083
1084 void
1085 stmWaitUnlock(Capability *cap STG_UNUSED, StgTRecHeader *trec) {
1086     revert_ownership(trec, TRUE);
1087     unlock_stm(trec);
1088 }
1089
1090 /*......................................................................*/
1091
1092 StgBool stmReWait(Capability *cap, StgTSO *tso) {
1093   int result;
1094   StgTRecHeader *trec = tso->trec;
1095
1096   TRACE("%p : stmReWait\n", trec);
1097   ASSERT (trec != NO_TREC);
1098   ASSERT (trec -> enclosing_trec == NO_TREC);
1099   ASSERT ((trec -> state == TREC_WAITING) || 
1100           (trec -> state == TREC_CONDEMNED));
1101
1102   lock_stm(trec);
1103   result = validate_and_acquire_ownership(trec, TRUE, TRUE);
1104   TRACE("%p : validation %s\n", trec, result ? "succeeded" : "failed");
1105   if (result) {
1106     // The transaction remains valid -- do nothing because it is already on
1107     // the wait queues
1108     ASSERT (trec -> state == TREC_WAITING);
1109     park_tso(tso);
1110     revert_ownership(trec, TRUE);
1111   } else {
1112     // The transcation has become invalid.  We can now remove it from the wait
1113     // queues.
1114     if (trec -> state != TREC_CONDEMNED) {
1115       remove_wait_queue_entries_for_trec (cap, trec);
1116     }
1117     free_stg_trec_header(cap, trec);
1118   }
1119   unlock_stm(trec);
1120
1121   TRACE("%p : stmReWait()=%d\n", trec, result);
1122   return result;
1123 }
1124
1125 /*......................................................................*/
1126
1127 static TRecEntry *get_entry_for(StgTRecHeader *trec, StgTVar *tvar, StgTRecHeader **in) {
1128   TRecEntry *result = NULL;
1129
1130   TRACE("%p : get_entry_for TVar %p\n", trec, tvar);
1131   ASSERT(trec != NO_TREC);
1132
1133   do {
1134     FOR_EACH_ENTRY(trec, e, {
1135       if (e -> tvar == tvar) {
1136         result = e;
1137         if (in != NULL) {
1138           *in = trec;
1139         }
1140         BREAK_FOR_EACH;
1141       }
1142     });
1143     trec = trec -> enclosing_trec;
1144   } while (result == NULL && trec != NO_TREC);
1145
1146   return result;    
1147 }
1148
1149 static StgClosure *read_current_value(StgTRecHeader *trec STG_UNUSED, StgTVar *tvar) {
1150   StgClosure *result;
1151   result = tvar -> current_value;
1152
1153 #if defined(STM_FG_LOCKS)
1154   while (GET_INFO(result) == &stg_TREC_HEADER_info) {
1155     TRACE("%p : read_current_value(%p) saw %p\n", trec, tvar, result);
1156     result = tvar -> current_value;
1157   }
1158 #endif
1159
1160   TRACE("%p : read_current_value(%p)=%p\n", trec, tvar, result);
1161   return result;
1162 }
1163
1164 /*......................................................................*/
1165
1166 StgClosure *stmReadTVar(Capability *cap,
1167                         StgTRecHeader *trec, 
1168                         StgTVar *tvar) {
1169   StgTRecHeader *entry_in;
1170   StgClosure *result = NULL;
1171   TRecEntry *entry = NULL;
1172   TRACE("%p : stmReadTVar(%p)\n", trec, tvar);
1173   ASSERT (trec != NO_TREC);
1174   ASSERT (trec -> state == TREC_ACTIVE || 
1175           trec -> state == TREC_CONDEMNED);
1176
1177   entry = get_entry_for(trec, tvar, &entry_in);
1178
1179   if (entry != NULL) {
1180     if (entry_in == trec) {
1181       // Entry found in our trec
1182       result = entry -> new_value;
1183     } else {
1184       // Entry found in another trec
1185       TRecEntry *new_entry = get_new_entry(cap, trec);
1186       new_entry -> tvar = tvar;
1187       new_entry -> expected_value = entry -> expected_value;
1188       new_entry -> new_value = entry -> new_value;
1189       result = new_entry -> new_value;
1190     } 
1191   } else {
1192     // No entry found
1193     StgClosure *current_value = read_current_value(trec, tvar);
1194     TRecEntry *new_entry = get_new_entry(cap, trec);
1195     new_entry -> tvar = tvar;
1196     new_entry -> expected_value = current_value;
1197     new_entry -> new_value = current_value;
1198     result = current_value;
1199   }
1200
1201   TRACE("%p : stmReadTVar(%p)=%p\n", trec, tvar, result);
1202   return result;
1203 }
1204
1205 /*......................................................................*/
1206
1207 void stmWriteTVar(Capability *cap,
1208                   StgTRecHeader *trec,
1209                   StgTVar *tvar, 
1210                   StgClosure *new_value) {
1211
1212   StgTRecHeader *entry_in;
1213   TRecEntry *entry = NULL;
1214   TRACE("%p : stmWriteTVar(%p, %p)\n", trec, tvar, new_value);
1215   ASSERT (trec != NO_TREC);
1216   ASSERT (trec -> state == TREC_ACTIVE || 
1217           trec -> state == TREC_CONDEMNED);
1218
1219   entry = get_entry_for(trec, tvar, &entry_in);
1220
1221   if (entry != NULL) {
1222     if (entry_in == trec) {
1223       // Entry found in our trec
1224       entry -> new_value = new_value;
1225     } else {
1226       // Entry found in another trec
1227       TRecEntry *new_entry = get_new_entry(cap, trec);
1228       new_entry -> tvar = tvar;
1229       new_entry -> expected_value = entry -> expected_value;
1230       new_entry -> new_value = new_value;
1231     } 
1232   } else {
1233     // No entry found
1234     StgClosure *current_value = read_current_value(trec, tvar);
1235     TRecEntry *new_entry = get_new_entry(cap, trec);
1236     new_entry -> tvar = tvar;
1237     new_entry -> expected_value = current_value;
1238     new_entry -> new_value = new_value;
1239   }
1240
1241   TRACE("%p : stmWriteTVar done\n", trec);
1242 }
1243
1244 /*......................................................................*/
1245
1246 StgTVar *stmNewTVar(Capability *cap,
1247                     StgClosure *new_value) {
1248   StgTVar *result;
1249   result = (StgTVar *)allocateLocal(cap, sizeofW(StgTVar));
1250   SET_HDR (result, &stg_TVAR_info, CCS_SYSTEM);
1251   result -> current_value = new_value;
1252   result -> first_wait_queue_entry = END_STM_WAIT_QUEUE;
1253 #if defined(SMP)
1254   result -> num_updates = 0;
1255 #endif
1256   return result;
1257 }
1258
1259 /*......................................................................*/