Eventlog support for new event type: create spark.
[ghc-hetmet.git] / rts / Schedule.c
1 /* ---------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2006
4  *
5  * The scheduler and thread-related functionality
6  *
7  * --------------------------------------------------------------------------*/
8
9 #include "PosixSource.h"
10 #define KEEP_LOCKCLOSURE
11 #include "Rts.h"
12 #include "SchedAPI.h"
13 #include "RtsUtils.h"
14 #include "RtsFlags.h"
15 #include "OSThreads.h"
16 #include "Storage.h"
17 #include "StgRun.h"
18 #include "Hooks.h"
19 #include "Schedule.h"
20 #include "StgMiscClosures.h"
21 #include "Interpreter.h"
22 #include "Printer.h"
23 #include "RtsSignals.h"
24 #include "Sanity.h"
25 #include "Stats.h"
26 #include "STM.h"
27 #include "Timer.h"
28 #include "Prelude.h"
29 #include "ThreadLabels.h"
30 #include "LdvProfile.h"
31 #include "Updates.h"
32 #include "Proftimer.h"
33 #include "ProfHeap.h"
34 #include "GC.h"
35 #include "Weak.h"
36 #include "EventLog.h"
37
38 /* PARALLEL_HASKELL includes go here */
39
40 #include "Sparks.h"
41 #include "Capability.h"
42 #include "Task.h"
43 #include "AwaitEvent.h"
44 #if defined(mingw32_HOST_OS)
45 #include "win32/IOManager.h"
46 #endif
47 #include "Trace.h"
48 #include "RaiseAsync.h"
49 #include "Threads.h"
50 #include "ThrIOManager.h"
51
52 #ifdef HAVE_SYS_TYPES_H
53 #include <sys/types.h>
54 #endif
55 #ifdef HAVE_UNISTD_H
56 #include <unistd.h>
57 #endif
58
59 #include <string.h>
60 #include <stdlib.h>
61 #include <stdarg.h>
62
63 #ifdef HAVE_ERRNO_H
64 #include <errno.h>
65 #endif
66
67 // Turn off inlining when debugging - it obfuscates things
68 #ifdef DEBUG
69 # undef  STATIC_INLINE
70 # define STATIC_INLINE static
71 #endif
72
73 /* -----------------------------------------------------------------------------
74  * Global variables
75  * -------------------------------------------------------------------------- */
76
77 #if !defined(THREADED_RTS)
78 // Blocked/sleeping thrads
79 StgTSO *blocked_queue_hd = NULL;
80 StgTSO *blocked_queue_tl = NULL;
81 StgTSO *sleeping_queue = NULL;    // perhaps replace with a hash table?
82 #endif
83
84 /* Threads blocked on blackholes.
85  * LOCK: sched_mutex+capability, or all capabilities
86  */
87 StgTSO *blackhole_queue = NULL;
88
89 /* The blackhole_queue should be checked for threads to wake up.  See
90  * Schedule.h for more thorough comment.
91  * LOCK: none (doesn't matter if we miss an update)
92  */
93 rtsBool blackholes_need_checking = rtsFalse;
94
95 /* Set to true when the latest garbage collection failed to reclaim
96  * enough space, and the runtime should proceed to shut itself down in
97  * an orderly fashion (emitting profiling info etc.)
98  */
99 rtsBool heap_overflow = rtsFalse;
100
101 /* flag that tracks whether we have done any execution in this time slice.
102  * LOCK: currently none, perhaps we should lock (but needs to be
103  * updated in the fast path of the scheduler).
104  *
105  * NB. must be StgWord, we do xchg() on it.
106  */
107 volatile StgWord recent_activity = ACTIVITY_YES;
108
109 /* if this flag is set as well, give up execution
110  * LOCK: none (changes monotonically)
111  */
112 volatile StgWord sched_state = SCHED_RUNNING;
113
114 /*  This is used in `TSO.h' and gcc 2.96 insists that this variable actually 
115  *  exists - earlier gccs apparently didn't.
116  *  -= chak
117  */
118 StgTSO dummy_tso;
119
120 /*
121  * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
122  * in an MT setting, needed to signal that a worker thread shouldn't hang around
123  * in the scheduler when it is out of work.
124  */
125 rtsBool shutting_down_scheduler = rtsFalse;
126
127 /*
128  * This mutex protects most of the global scheduler data in
129  * the THREADED_RTS runtime.
130  */
131 #if defined(THREADED_RTS)
132 Mutex sched_mutex;
133 #endif
134
135 #if !defined(mingw32_HOST_OS)
136 #define FORKPROCESS_PRIMOP_SUPPORTED
137 #endif
138
139 /* -----------------------------------------------------------------------------
140  * static function prototypes
141  * -------------------------------------------------------------------------- */
142
143 static Capability *schedule (Capability *initialCapability, Task *task);
144
145 //
146 // These function all encapsulate parts of the scheduler loop, and are
147 // abstracted only to make the structure and control flow of the
148 // scheduler clearer.
149 //
150 static void schedulePreLoop (void);
151 static void scheduleFindWork (Capability *cap);
152 #if defined(THREADED_RTS)
153 static void scheduleYield (Capability **pcap, Task *task);
154 #endif
155 static void scheduleStartSignalHandlers (Capability *cap);
156 static void scheduleCheckBlockedThreads (Capability *cap);
157 static void scheduleCheckWakeupThreads(Capability *cap USED_IF_NOT_THREADS);
158 static void scheduleCheckBlackHoles (Capability *cap);
159 static void scheduleDetectDeadlock (Capability *cap, Task *task);
160 static void schedulePushWork(Capability *cap, Task *task);
161 #if defined(PARALLEL_HASKELL)
162 static rtsBool scheduleGetRemoteWork(Capability *cap);
163 static void scheduleSendPendingMessages(void);
164 #endif
165 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
166 static void scheduleActivateSpark(Capability *cap);
167 #endif
168 static void schedulePostRunThread(Capability *cap, StgTSO *t);
169 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
170 static void scheduleHandleStackOverflow( Capability *cap, Task *task, 
171                                          StgTSO *t);
172 static rtsBool scheduleHandleYield( Capability *cap, StgTSO *t, 
173                                     nat prev_what_next );
174 static void scheduleHandleThreadBlocked( StgTSO *t );
175 static rtsBool scheduleHandleThreadFinished( Capability *cap, Task *task,
176                                              StgTSO *t );
177 static rtsBool scheduleNeedHeapProfile(rtsBool ready_to_gc);
178 static Capability *scheduleDoGC(Capability *cap, Task *task,
179                                 rtsBool force_major);
180
181 static rtsBool checkBlackHoles(Capability *cap);
182
183 static StgTSO *threadStackOverflow(Capability *cap, StgTSO *tso);
184 static StgTSO *threadStackUnderflow(Task *task, StgTSO *tso);
185
186 static void deleteThread (Capability *cap, StgTSO *tso);
187 static void deleteAllThreads (Capability *cap);
188
189 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
190 static void deleteThread_(Capability *cap, StgTSO *tso);
191 #endif
192
193 #ifdef DEBUG
194 static char *whatNext_strs[] = {
195   "(unknown)",
196   "ThreadRunGHC",
197   "ThreadInterpret",
198   "ThreadKilled",
199   "ThreadRelocated",
200   "ThreadComplete"
201 };
202 #endif
203
204 /* -----------------------------------------------------------------------------
205  * Putting a thread on the run queue: different scheduling policies
206  * -------------------------------------------------------------------------- */
207
208 STATIC_INLINE void
209 addToRunQueue( Capability *cap, StgTSO *t )
210 {
211 #if defined(PARALLEL_HASKELL)
212     if (RtsFlags.ParFlags.doFairScheduling) { 
213         // this does round-robin scheduling; good for concurrency
214         appendToRunQueue(cap,t);
215     } else {
216         // this does unfair scheduling; good for parallelism
217         pushOnRunQueue(cap,t);
218     }
219 #else
220     // this does round-robin scheduling; good for concurrency
221     appendToRunQueue(cap,t);
222 #endif
223 }
224
225 /* ---------------------------------------------------------------------------
226    Main scheduling loop.
227
228    We use round-robin scheduling, each thread returning to the
229    scheduler loop when one of these conditions is detected:
230
231       * out of heap space
232       * timer expires (thread yields)
233       * thread blocks
234       * thread ends
235       * stack overflow
236
237    GRAN version:
238      In a GranSim setup this loop iterates over the global event queue.
239      This revolves around the global event queue, which determines what 
240      to do next. Therefore, it's more complicated than either the 
241      concurrent or the parallel (GUM) setup.
242   This version has been entirely removed (JB 2008/08).
243
244    GUM version:
245      GUM iterates over incoming messages.
246      It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
247      and sends out a fish whenever it has nothing to do; in-between
248      doing the actual reductions (shared code below) it processes the
249      incoming messages and deals with delayed operations 
250      (see PendingFetches).
251      This is not the ugliest code you could imagine, but it's bloody close.
252
253   (JB 2008/08) This version was formerly indicated by a PP-Flag PAR,
254   now by PP-flag PARALLEL_HASKELL. The Eden RTS (in GHC-6.x) uses it,
255   as well as future GUM versions. This file has been refurbished to
256   only contain valid code, which is however incomplete, refers to
257   invalid includes etc.
258
259    ------------------------------------------------------------------------ */
260
261 static Capability *
262 schedule (Capability *initialCapability, Task *task)
263 {
264   StgTSO *t;
265   Capability *cap;
266   StgThreadReturnCode ret;
267 #if defined(PARALLEL_HASKELL)
268   rtsBool receivedFinish = rtsFalse;
269 #endif
270   nat prev_what_next;
271   rtsBool ready_to_gc;
272 #if defined(THREADED_RTS)
273   rtsBool first = rtsTrue;
274 #endif
275   
276   cap = initialCapability;
277
278   // Pre-condition: this task owns initialCapability.
279   // The sched_mutex is *NOT* held
280   // NB. on return, we still hold a capability.
281
282   debugTrace (DEBUG_sched, 
283               "### NEW SCHEDULER LOOP (task: %p, cap: %p)",
284               task, initialCapability);
285
286   if (running_finalizers) {
287       errorBelch("error: a C finalizer called back into Haskell.\n"
288                  "   use Foreign.Concurrent.newForeignPtr for Haskell finalizers.");
289       stg_exit(EXIT_FAILURE);
290   }
291
292   schedulePreLoop();
293
294   // -----------------------------------------------------------
295   // Scheduler loop starts here:
296
297 #if defined(PARALLEL_HASKELL)
298 #define TERMINATION_CONDITION        (!receivedFinish)
299 #else
300 #define TERMINATION_CONDITION        rtsTrue
301 #endif
302
303   while (TERMINATION_CONDITION) {
304
305     // Check whether we have re-entered the RTS from Haskell without
306     // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
307     // call).
308     if (cap->in_haskell) {
309           errorBelch("schedule: re-entered unsafely.\n"
310                      "   Perhaps a 'foreign import unsafe' should be 'safe'?");
311           stg_exit(EXIT_FAILURE);
312     }
313
314     // The interruption / shutdown sequence.
315     // 
316     // In order to cleanly shut down the runtime, we want to:
317     //   * make sure that all main threads return to their callers
318     //     with the state 'Interrupted'.
319     //   * clean up all OS threads assocated with the runtime
320     //   * free all memory etc.
321     //
322     // So the sequence for ^C goes like this:
323     //
324     //   * ^C handler sets sched_state := SCHED_INTERRUPTING and
325     //     arranges for some Capability to wake up
326     //
327     //   * all threads in the system are halted, and the zombies are
328     //     placed on the run queue for cleaning up.  We acquire all
329     //     the capabilities in order to delete the threads, this is
330     //     done by scheduleDoGC() for convenience (because GC already
331     //     needs to acquire all the capabilities).  We can't kill
332     //     threads involved in foreign calls.
333     // 
334     //   * somebody calls shutdownHaskell(), which calls exitScheduler()
335     //
336     //   * sched_state := SCHED_SHUTTING_DOWN
337     //
338     //   * all workers exit when the run queue on their capability
339     //     drains.  All main threads will also exit when their TSO
340     //     reaches the head of the run queue and they can return.
341     //
342     //   * eventually all Capabilities will shut down, and the RTS can
343     //     exit.
344     //
345     //   * We might be left with threads blocked in foreign calls, 
346     //     we should really attempt to kill these somehow (TODO);
347     
348     switch (sched_state) {
349     case SCHED_RUNNING:
350         break;
351     case SCHED_INTERRUPTING:
352         debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
353 #if defined(THREADED_RTS)
354         discardSparksCap(cap);
355 #endif
356         /* scheduleDoGC() deletes all the threads */
357         cap = scheduleDoGC(cap,task,rtsFalse);
358
359         // after scheduleDoGC(), we must be shutting down.  Either some
360         // other Capability did the final GC, or we did it above,
361         // either way we can fall through to the SCHED_SHUTTING_DOWN
362         // case now.
363         ASSERT(sched_state == SCHED_SHUTTING_DOWN);
364         // fall through
365
366     case SCHED_SHUTTING_DOWN:
367         debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
368         // If we are a worker, just exit.  If we're a bound thread
369         // then we will exit below when we've removed our TSO from
370         // the run queue.
371         if (task->tso == NULL && emptyRunQueue(cap)) {
372             return cap;
373         }
374         break;
375     default:
376         barf("sched_state: %d", sched_state);
377     }
378
379     scheduleFindWork(cap);
380
381     /* work pushing, currently relevant only for THREADED_RTS:
382        (pushes threads, wakes up idle capabilities for stealing) */
383     schedulePushWork(cap,task);
384
385 #if defined(PARALLEL_HASKELL)
386     /* since we perform a blocking receive and continue otherwise,
387        either we never reach here or we definitely have work! */
388     // from here: non-empty run queue
389     ASSERT(!emptyRunQueue(cap));
390
391     if (PacketsWaiting()) {  /* now process incoming messages, if any
392                                 pending...  
393
394                                 CAUTION: scheduleGetRemoteWork called
395                                 above, waits for messages as well! */
396       processMessages(cap, &receivedFinish);
397     }
398 #endif // PARALLEL_HASKELL: non-empty run queue!
399
400     scheduleDetectDeadlock(cap,task);
401
402 #if defined(THREADED_RTS)
403     cap = task->cap;    // reload cap, it might have changed
404 #endif
405
406     // Normally, the only way we can get here with no threads to
407     // run is if a keyboard interrupt received during 
408     // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
409     // Additionally, it is not fatal for the
410     // threaded RTS to reach here with no threads to run.
411     //
412     // win32: might be here due to awaitEvent() being abandoned
413     // as a result of a console event having been delivered.
414     
415 #if defined(THREADED_RTS)
416     if (first) 
417     {
418     // XXX: ToDo
419     //     // don't yield the first time, we want a chance to run this
420     //     // thread for a bit, even if there are others banging at the
421     //     // door.
422     //     first = rtsFalse;
423     //     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
424     }
425
426   yield:
427     scheduleYield(&cap,task);
428     if (emptyRunQueue(cap)) continue; // look for work again
429 #endif
430
431 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
432     if ( emptyRunQueue(cap) ) {
433         ASSERT(sched_state >= SCHED_INTERRUPTING);
434     }
435 #endif
436
437     // 
438     // Get a thread to run
439     //
440     t = popRunQueue(cap);
441
442     // Sanity check the thread we're about to run.  This can be
443     // expensive if there is lots of thread switching going on...
444     IF_DEBUG(sanity,checkTSO(t));
445
446 #if defined(THREADED_RTS)
447     // Check whether we can run this thread in the current task.
448     // If not, we have to pass our capability to the right task.
449     {
450         Task *bound = t->bound;
451       
452         if (bound) {
453             if (bound == task) {
454                 debugTrace(DEBUG_sched,
455                            "### Running thread %lu in bound thread", (unsigned long)t->id);
456                 // yes, the Haskell thread is bound to the current native thread
457             } else {
458                 debugTrace(DEBUG_sched,
459                            "### thread %lu bound to another OS thread", (unsigned long)t->id);
460                 // no, bound to a different Haskell thread: pass to that thread
461                 pushOnRunQueue(cap,t);
462                 continue;
463             }
464         } else {
465             // The thread we want to run is unbound.
466             if (task->tso) { 
467                 debugTrace(DEBUG_sched,
468                            "### this OS thread cannot run thread %lu", (unsigned long)t->id);
469                 // no, the current native thread is bound to a different
470                 // Haskell thread, so pass it to any worker thread
471                 pushOnRunQueue(cap,t);
472                 continue; 
473             }
474         }
475     }
476 #endif
477
478     // If we're shutting down, and this thread has not yet been
479     // killed, kill it now.  This sometimes happens when a finalizer
480     // thread is created by the final GC, or a thread previously
481     // in a foreign call returns.
482     if (sched_state >= SCHED_INTERRUPTING &&
483         !(t->what_next == ThreadComplete || t->what_next == ThreadKilled)) {
484         deleteThread(cap,t);
485     }
486
487     /* context switches are initiated by the timer signal, unless
488      * the user specified "context switch as often as possible", with
489      * +RTS -C0
490      */
491     if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
492         && !emptyThreadQueues(cap)) {
493         cap->context_switch = 1;
494     }
495          
496 run_thread:
497
498     // CurrentTSO is the thread to run.  t might be different if we
499     // loop back to run_thread, so make sure to set CurrentTSO after
500     // that.
501     cap->r.rCurrentTSO = t;
502
503     debugTrace(DEBUG_sched, "-->> running thread %ld %s ...", 
504                               (long)t->id, whatNext_strs[t->what_next]);
505
506     startHeapProfTimer();
507
508     // Check for exceptions blocked on this thread
509     maybePerformBlockedException (cap, t);
510
511     // ----------------------------------------------------------------------
512     // Run the current thread 
513
514     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
515     ASSERT(t->cap == cap);
516     ASSERT(t->bound ? t->bound->cap == cap : 1);
517
518     prev_what_next = t->what_next;
519
520     errno = t->saved_errno;
521 #if mingw32_HOST_OS
522     SetLastError(t->saved_winerror);
523 #endif
524
525     cap->in_haskell = rtsTrue;
526
527     dirty_TSO(cap,t);
528
529 #if defined(THREADED_RTS)
530     if (recent_activity == ACTIVITY_DONE_GC) {
531         // ACTIVITY_DONE_GC means we turned off the timer signal to
532         // conserve power (see #1623).  Re-enable it here.
533         nat prev;
534         prev = xchg((P_)&recent_activity, ACTIVITY_YES);
535         if (prev == ACTIVITY_DONE_GC) {
536             startTimer();
537         }
538     } else {
539         recent_activity = ACTIVITY_YES;
540     }
541 #endif
542
543     postEvent(cap, EVENT_RUN_THREAD, t->id, 0);
544
545     switch (prev_what_next) {
546         
547     case ThreadKilled:
548     case ThreadComplete:
549         /* Thread already finished, return to scheduler. */
550         ret = ThreadFinished;
551         break;
552         
553     case ThreadRunGHC:
554     {
555         StgRegTable *r;
556         r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
557         cap = regTableToCapability(r);
558         ret = r->rRet;
559         break;
560     }
561     
562     case ThreadInterpret:
563         cap = interpretBCO(cap);
564         ret = cap->r.rRet;
565         break;
566         
567     default:
568         barf("schedule: invalid what_next field");
569     }
570
571     cap->in_haskell = rtsFalse;
572
573     // The TSO might have moved, eg. if it re-entered the RTS and a GC
574     // happened.  So find the new location:
575     t = cap->r.rCurrentTSO;
576
577     // We have run some Haskell code: there might be blackhole-blocked
578     // threads to wake up now.
579     // Lock-free test here should be ok, we're just setting a flag.
580     if ( blackhole_queue != END_TSO_QUEUE ) {
581         blackholes_need_checking = rtsTrue;
582     }
583     
584     // And save the current errno in this thread.
585     // XXX: possibly bogus for SMP because this thread might already
586     // be running again, see code below.
587     t->saved_errno = errno;
588 #if mingw32_HOST_OS
589     // Similarly for Windows error code
590     t->saved_winerror = GetLastError();
591 #endif
592
593     postEvent (cap, EVENT_STOP_THREAD, t->id, ret);
594
595 #if defined(THREADED_RTS)
596     // If ret is ThreadBlocked, and this Task is bound to the TSO that
597     // blocked, we are in limbo - the TSO is now owned by whatever it
598     // is blocked on, and may in fact already have been woken up,
599     // perhaps even on a different Capability.  It may be the case
600     // that task->cap != cap.  We better yield this Capability
601     // immediately and return to normaility.
602     if (ret == ThreadBlocked) {
603         debugTrace(DEBUG_sched,
604                    "--<< thread %lu (%s) stopped: blocked",
605                    (unsigned long)t->id, whatNext_strs[t->what_next]);
606         goto yield;
607     }
608 #endif
609
610     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
611     ASSERT(t->cap == cap);
612
613     // ----------------------------------------------------------------------
614     
615     // Costs for the scheduler are assigned to CCS_SYSTEM
616     stopHeapProfTimer();
617 #if defined(PROFILING)
618     CCCS = CCS_SYSTEM;
619 #endif
620     
621     schedulePostRunThread(cap,t);
622
623     t = threadStackUnderflow(task,t);
624
625     ready_to_gc = rtsFalse;
626
627     switch (ret) {
628     case HeapOverflow:
629         ready_to_gc = scheduleHandleHeapOverflow(cap,t);
630         break;
631
632     case StackOverflow:
633         scheduleHandleStackOverflow(cap,task,t);
634         break;
635
636     case ThreadYielding:
637         if (scheduleHandleYield(cap, t, prev_what_next)) {
638             // shortcut for switching between compiler/interpreter:
639             goto run_thread; 
640         }
641         break;
642
643     case ThreadBlocked:
644         scheduleHandleThreadBlocked(t);
645         break;
646
647     case ThreadFinished:
648         if (scheduleHandleThreadFinished(cap, task, t)) return cap;
649         ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
650         break;
651
652     default:
653       barf("schedule: invalid thread return code %d", (int)ret);
654     }
655
656     if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
657       cap = scheduleDoGC(cap,task,rtsFalse);
658     }
659   } /* end of while() */
660 }
661
662 /* ----------------------------------------------------------------------------
663  * Setting up the scheduler loop
664  * ------------------------------------------------------------------------- */
665
666 static void
667 schedulePreLoop(void)
668 {
669   // initialisation for scheduler - what cannot go into initScheduler()  
670 }
671
672 /* -----------------------------------------------------------------------------
673  * scheduleFindWork()
674  *
675  * Search for work to do, and handle messages from elsewhere.
676  * -------------------------------------------------------------------------- */
677
678 static void
679 scheduleFindWork (Capability *cap)
680 {
681     scheduleStartSignalHandlers(cap);
682
683     // Only check the black holes here if we've nothing else to do.
684     // During normal execution, the black hole list only gets checked
685     // at GC time, to avoid repeatedly traversing this possibly long
686     // list each time around the scheduler.
687     if (emptyRunQueue(cap)) { scheduleCheckBlackHoles(cap); }
688
689     scheduleCheckWakeupThreads(cap);
690
691     scheduleCheckBlockedThreads(cap);
692
693 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
694     if (emptyRunQueue(cap)) { scheduleActivateSpark(cap); }
695 #endif
696
697 #if defined(PARALLEL_HASKELL)
698     // if messages have been buffered...
699     scheduleSendPendingMessages();
700 #endif
701
702 #if defined(PARALLEL_HASKELL)
703     if (emptyRunQueue(cap)) {
704         receivedFinish = scheduleGetRemoteWork(cap);
705         continue; //  a new round, (hopefully) with new work
706         /* 
707            in GUM, this a) sends out a FISH and returns IF no fish is
708                            out already
709                         b) (blocking) awaits and receives messages
710            
711            in Eden, this is only the blocking receive, as b) in GUM.
712         */
713     }
714 #endif
715 }
716
717 #if defined(THREADED_RTS)
718 STATIC_INLINE rtsBool
719 shouldYieldCapability (Capability *cap, Task *task)
720 {
721     // we need to yield this capability to someone else if..
722     //   - another thread is initiating a GC
723     //   - another Task is returning from a foreign call
724     //   - the thread at the head of the run queue cannot be run
725     //     by this Task (it is bound to another Task, or it is unbound
726     //     and this task it bound).
727     return (waiting_for_gc || 
728             cap->returning_tasks_hd != NULL ||
729             (!emptyRunQueue(cap) && (task->tso == NULL
730                                      ? cap->run_queue_hd->bound != NULL
731                                      : cap->run_queue_hd->bound != task)));
732 }
733
734 // This is the single place where a Task goes to sleep.  There are
735 // two reasons it might need to sleep:
736 //    - there are no threads to run
737 //    - we need to yield this Capability to someone else 
738 //      (see shouldYieldCapability())
739 //
740 // Careful: the scheduler loop is quite delicate.  Make sure you run
741 // the tests in testsuite/concurrent (all ways) after modifying this,
742 // and also check the benchmarks in nofib/parallel for regressions.
743
744 static void
745 scheduleYield (Capability **pcap, Task *task)
746 {
747     Capability *cap = *pcap;
748
749     // if we have work, and we don't need to give up the Capability, continue.
750     if (!shouldYieldCapability(cap,task) && 
751         (!emptyRunQueue(cap) ||
752          !emptyWakeupQueue(cap) ||
753          blackholes_need_checking ||
754          sched_state >= SCHED_INTERRUPTING))
755         return;
756
757     // otherwise yield (sleep), and keep yielding if necessary.
758     do {
759         yieldCapability(&cap,task);
760     } 
761     while (shouldYieldCapability(cap,task));
762
763     // note there may still be no threads on the run queue at this
764     // point, the caller has to check.
765
766     *pcap = cap;
767     return;
768 }
769 #endif
770     
771 /* -----------------------------------------------------------------------------
772  * schedulePushWork()
773  *
774  * Push work to other Capabilities if we have some.
775  * -------------------------------------------------------------------------- */
776
777 static void
778 schedulePushWork(Capability *cap USED_IF_THREADS, 
779                  Task *task      USED_IF_THREADS)
780 {
781   /* following code not for PARALLEL_HASKELL. I kept the call general,
782      future GUM versions might use pushing in a distributed setup */
783 #if defined(THREADED_RTS)
784
785     Capability *free_caps[n_capabilities], *cap0;
786     nat i, n_free_caps;
787
788     // migration can be turned off with +RTS -qg
789     if (!RtsFlags.ParFlags.migrate) return;
790
791     // Check whether we have more threads on our run queue, or sparks
792     // in our pool, that we could hand to another Capability.
793     if (cap->run_queue_hd == END_TSO_QUEUE) {
794         if (sparkPoolSizeCap(cap) < 2) return;
795     } else {
796         if (cap->run_queue_hd->_link == END_TSO_QUEUE &&
797             sparkPoolSizeCap(cap) < 1) return;
798     }
799
800     // First grab as many free Capabilities as we can.
801     for (i=0, n_free_caps=0; i < n_capabilities; i++) {
802         cap0 = &capabilities[i];
803         if (cap != cap0 && tryGrabCapability(cap0,task)) {
804             if (!emptyRunQueue(cap0) || cap->returning_tasks_hd != NULL) {
805                 // it already has some work, we just grabbed it at 
806                 // the wrong moment.  Or maybe it's deadlocked!
807                 releaseCapability(cap0);
808             } else {
809                 free_caps[n_free_caps++] = cap0;
810             }
811         }
812     }
813
814     // we now have n_free_caps free capabilities stashed in
815     // free_caps[].  Share our run queue equally with them.  This is
816     // probably the simplest thing we could do; improvements we might
817     // want to do include:
818     //
819     //   - giving high priority to moving relatively new threads, on 
820     //     the gournds that they haven't had time to build up a
821     //     working set in the cache on this CPU/Capability.
822     //
823     //   - giving low priority to moving long-lived threads
824
825     if (n_free_caps > 0) {
826         StgTSO *prev, *t, *next;
827         rtsBool pushed_to_all;
828
829         debugTrace(DEBUG_sched, 
830                    "cap %d: %s and %d free capabilities, sharing...", 
831                    cap->no, 
832                    (!emptyRunQueue(cap) && cap->run_queue_hd->_link != END_TSO_QUEUE)?
833                    "excess threads on run queue":"sparks to share (>=2)",
834                    n_free_caps);
835
836         i = 0;
837         pushed_to_all = rtsFalse;
838
839         if (cap->run_queue_hd != END_TSO_QUEUE) {
840             prev = cap->run_queue_hd;
841             t = prev->_link;
842             prev->_link = END_TSO_QUEUE;
843             for (; t != END_TSO_QUEUE; t = next) {
844                 next = t->_link;
845                 t->_link = END_TSO_QUEUE;
846                 if (t->what_next == ThreadRelocated
847                     || t->bound == task // don't move my bound thread
848                     || tsoLocked(t)) {  // don't move a locked thread
849                     setTSOLink(cap, prev, t);
850                     prev = t;
851                 } else if (i == n_free_caps) {
852                     pushed_to_all = rtsTrue;
853                     i = 0;
854                     // keep one for us
855                     setTSOLink(cap, prev, t);
856                     prev = t;
857                 } else {
858                     debugTrace(DEBUG_sched, "pushing thread %lu to capability %d", (unsigned long)t->id, free_caps[i]->no);
859                     appendToRunQueue(free_caps[i],t);
860
861         postEvent (cap, EVENT_MIGRATE_THREAD, t->id, free_caps[i]->no);
862
863                     if (t->bound) { t->bound->cap = free_caps[i]; }
864                     t->cap = free_caps[i];
865                     i++;
866                 }
867             }
868             cap->run_queue_tl = prev;
869         }
870
871 #ifdef SPARK_PUSHING
872         /* JB I left this code in place, it would work but is not necessary */
873
874         // If there are some free capabilities that we didn't push any
875         // threads to, then try to push a spark to each one.
876         if (!pushed_to_all) {
877             StgClosure *spark;
878             // i is the next free capability to push to
879             for (; i < n_free_caps; i++) {
880                 if (emptySparkPoolCap(free_caps[i])) {
881                     spark = tryStealSpark(cap->sparks);
882                     if (spark != NULL) {
883                         debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
884
885       postEvent(free_caps[i], EVENT_STEAL_SPARK, t->id, cap->no);
886
887                         newSpark(&(free_caps[i]->r), spark);
888                     }
889                 }
890             }
891         }
892 #endif /* SPARK_PUSHING */
893
894         // release the capabilities
895         for (i = 0; i < n_free_caps; i++) {
896             task->cap = free_caps[i];
897             releaseAndWakeupCapability(free_caps[i]);
898         }
899     }
900     task->cap = cap; // reset to point to our Capability.
901
902 #endif /* THREADED_RTS */
903
904 }
905
906 /* ----------------------------------------------------------------------------
907  * Start any pending signal handlers
908  * ------------------------------------------------------------------------- */
909
910 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
911 static void
912 scheduleStartSignalHandlers(Capability *cap)
913 {
914     if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
915         // safe outside the lock
916         startSignalHandlers(cap);
917     }
918 }
919 #else
920 static void
921 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
922 {
923 }
924 #endif
925
926 /* ----------------------------------------------------------------------------
927  * Check for blocked threads that can be woken up.
928  * ------------------------------------------------------------------------- */
929
930 static void
931 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
932 {
933 #if !defined(THREADED_RTS)
934     //
935     // Check whether any waiting threads need to be woken up.  If the
936     // run queue is empty, and there are no other tasks running, we
937     // can wait indefinitely for something to happen.
938     //
939     if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
940     {
941         awaitEvent( emptyRunQueue(cap) && !blackholes_need_checking );
942     }
943 #endif
944 }
945
946
947 /* ----------------------------------------------------------------------------
948  * Check for threads woken up by other Capabilities
949  * ------------------------------------------------------------------------- */
950
951 static void
952 scheduleCheckWakeupThreads(Capability *cap USED_IF_THREADS)
953 {
954 #if defined(THREADED_RTS)
955     // Any threads that were woken up by other Capabilities get
956     // appended to our run queue.
957     if (!emptyWakeupQueue(cap)) {
958         ACQUIRE_LOCK(&cap->lock);
959         if (emptyRunQueue(cap)) {
960             cap->run_queue_hd = cap->wakeup_queue_hd;
961             cap->run_queue_tl = cap->wakeup_queue_tl;
962         } else {
963             setTSOLink(cap, cap->run_queue_tl, cap->wakeup_queue_hd);
964             cap->run_queue_tl = cap->wakeup_queue_tl;
965         }
966         cap->wakeup_queue_hd = cap->wakeup_queue_tl = END_TSO_QUEUE;
967         RELEASE_LOCK(&cap->lock);
968     }
969 #endif
970 }
971
972 /* ----------------------------------------------------------------------------
973  * Check for threads blocked on BLACKHOLEs that can be woken up
974  * ------------------------------------------------------------------------- */
975 static void
976 scheduleCheckBlackHoles (Capability *cap)
977 {
978     if ( blackholes_need_checking ) // check without the lock first
979     {
980         ACQUIRE_LOCK(&sched_mutex);
981         if ( blackholes_need_checking ) {
982             blackholes_need_checking = rtsFalse;
983             // important that we reset the flag *before* checking the
984             // blackhole queue, otherwise we could get deadlock.  This
985             // happens as follows: we wake up a thread that
986             // immediately runs on another Capability, blocks on a
987             // blackhole, and then we reset the blackholes_need_checking flag.
988             checkBlackHoles(cap);
989         }
990         RELEASE_LOCK(&sched_mutex);
991     }
992 }
993
994 /* ----------------------------------------------------------------------------
995  * Detect deadlock conditions and attempt to resolve them.
996  * ------------------------------------------------------------------------- */
997
998 static void
999 scheduleDetectDeadlock (Capability *cap, Task *task)
1000 {
1001
1002 #if defined(PARALLEL_HASKELL)
1003     // ToDo: add deadlock detection in GUM (similar to THREADED_RTS) -- HWL
1004     return;
1005 #endif
1006
1007     /* 
1008      * Detect deadlock: when we have no threads to run, there are no
1009      * threads blocked, waiting for I/O, or sleeping, and all the
1010      * other tasks are waiting for work, we must have a deadlock of
1011      * some description.
1012      */
1013     if ( emptyThreadQueues(cap) )
1014     {
1015 #if defined(THREADED_RTS)
1016         /* 
1017          * In the threaded RTS, we only check for deadlock if there
1018          * has been no activity in a complete timeslice.  This means
1019          * we won't eagerly start a full GC just because we don't have
1020          * any threads to run currently.
1021          */
1022         if (recent_activity != ACTIVITY_INACTIVE) return;
1023 #endif
1024
1025         debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
1026
1027         // Garbage collection can release some new threads due to
1028         // either (a) finalizers or (b) threads resurrected because
1029         // they are unreachable and will therefore be sent an
1030         // exception.  Any threads thus released will be immediately
1031         // runnable.
1032         cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
1033         // when force_major == rtsTrue. scheduleDoGC sets
1034         // recent_activity to ACTIVITY_DONE_GC and turns off the timer
1035         // signal.
1036
1037         if ( !emptyRunQueue(cap) ) return;
1038
1039 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
1040         /* If we have user-installed signal handlers, then wait
1041          * for signals to arrive rather then bombing out with a
1042          * deadlock.
1043          */
1044         if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
1045             debugTrace(DEBUG_sched,
1046                        "still deadlocked, waiting for signals...");
1047
1048             awaitUserSignals();
1049
1050             if (signals_pending()) {
1051                 startSignalHandlers(cap);
1052             }
1053
1054             // either we have threads to run, or we were interrupted:
1055             ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
1056
1057             return;
1058         }
1059 #endif
1060
1061 #if !defined(THREADED_RTS)
1062         /* Probably a real deadlock.  Send the current main thread the
1063          * Deadlock exception.
1064          */
1065         if (task->tso) {
1066             switch (task->tso->why_blocked) {
1067             case BlockedOnSTM:
1068             case BlockedOnBlackHole:
1069             case BlockedOnException:
1070             case BlockedOnMVar:
1071                 throwToSingleThreaded(cap, task->tso, 
1072                                       (StgClosure *)nonTermination_closure);
1073                 return;
1074             default:
1075                 barf("deadlock: main thread blocked in a strange way");
1076             }
1077         }
1078         return;
1079 #endif
1080     }
1081 }
1082
1083
1084 /* ----------------------------------------------------------------------------
1085  * Send pending messages (PARALLEL_HASKELL only)
1086  * ------------------------------------------------------------------------- */
1087
1088 #if defined(PARALLEL_HASKELL)
1089 static void
1090 scheduleSendPendingMessages(void)
1091 {
1092
1093 # if defined(PAR) // global Mem.Mgmt., omit for now
1094     if (PendingFetches != END_BF_QUEUE) {
1095         processFetches();
1096     }
1097 # endif
1098     
1099     if (RtsFlags.ParFlags.BufferTime) {
1100         // if we use message buffering, we must send away all message
1101         // packets which have become too old...
1102         sendOldBuffers(); 
1103     }
1104 }
1105 #endif
1106
1107 /* ----------------------------------------------------------------------------
1108  * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
1109  * ------------------------------------------------------------------------- */
1110
1111 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
1112 static void
1113 scheduleActivateSpark(Capability *cap)
1114 {
1115     if (anySparks())
1116     {
1117         createSparkThread(cap);
1118         debugTrace(DEBUG_sched, "creating a spark thread");
1119     }
1120 }
1121 #endif // PARALLEL_HASKELL || THREADED_RTS
1122
1123 /* ----------------------------------------------------------------------------
1124  * Get work from a remote node (PARALLEL_HASKELL only)
1125  * ------------------------------------------------------------------------- */
1126     
1127 #if defined(PARALLEL_HASKELL)
1128 static rtsBool /* return value used in PARALLEL_HASKELL only */
1129 scheduleGetRemoteWork (Capability *cap STG_UNUSED)
1130 {
1131 #if defined(PARALLEL_HASKELL)
1132   rtsBool receivedFinish = rtsFalse;
1133
1134   // idle() , i.e. send all buffers, wait for work
1135   if (RtsFlags.ParFlags.BufferTime) {
1136         IF_PAR_DEBUG(verbose, 
1137                 debugBelch("...send all pending data,"));
1138         {
1139           nat i;
1140           for (i=1; i<=nPEs; i++)
1141             sendImmediately(i); // send all messages away immediately
1142         }
1143   }
1144
1145   /* this would be the place for fishing in GUM... 
1146
1147      if (no-earlier-fish-around) 
1148           sendFish(choosePe());
1149    */
1150
1151   // Eden:just look for incoming messages (blocking receive)
1152   IF_PAR_DEBUG(verbose, 
1153                debugBelch("...wait for incoming messages...\n"));
1154   processMessages(cap, &receivedFinish); // blocking receive...
1155
1156
1157   return receivedFinish;
1158   // reenter scheduling look after having received something
1159
1160 #else /* !PARALLEL_HASKELL, i.e. THREADED_RTS */
1161
1162   return rtsFalse; /* return value unused in THREADED_RTS */
1163
1164 #endif /* PARALLEL_HASKELL */
1165 }
1166 #endif // PARALLEL_HASKELL || THREADED_RTS
1167
1168 /* ----------------------------------------------------------------------------
1169  * After running a thread...
1170  * ------------------------------------------------------------------------- */
1171
1172 static void
1173 schedulePostRunThread (Capability *cap, StgTSO *t)
1174 {
1175     // We have to be able to catch transactions that are in an
1176     // infinite loop as a result of seeing an inconsistent view of
1177     // memory, e.g. 
1178     //
1179     //   atomically $ do
1180     //       [a,b] <- mapM readTVar [ta,tb]
1181     //       when (a == b) loop
1182     //
1183     // and a is never equal to b given a consistent view of memory.
1184     //
1185     if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1186         if (!stmValidateNestOfTransactions (t -> trec)) {
1187             debugTrace(DEBUG_sched | DEBUG_stm,
1188                        "trec %p found wasting its time", t);
1189             
1190             // strip the stack back to the
1191             // ATOMICALLY_FRAME, aborting the (nested)
1192             // transaction, and saving the stack of any
1193             // partially-evaluated thunks on the heap.
1194             throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1195             
1196             ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1197         }
1198     }
1199
1200   /* some statistics gathering in the parallel case */
1201 }
1202
1203 /* -----------------------------------------------------------------------------
1204  * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1205  * -------------------------------------------------------------------------- */
1206
1207 static rtsBool
1208 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1209 {
1210     // did the task ask for a large block?
1211     if (cap->r.rHpAlloc > BLOCK_SIZE) {
1212         // if so, get one and push it on the front of the nursery.
1213         bdescr *bd;
1214         lnat blocks;
1215         
1216         blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1217         
1218         debugTrace(DEBUG_sched,
1219                    "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n", 
1220                    (long)t->id, whatNext_strs[t->what_next], blocks);
1221     
1222         // don't do this if the nursery is (nearly) full, we'll GC first.
1223         if (cap->r.rCurrentNursery->link != NULL ||
1224             cap->r.rNursery->n_blocks == 1) {  // paranoia to prevent infinite loop
1225                                                // if the nursery has only one block.
1226             
1227             ACQUIRE_SM_LOCK
1228             bd = allocGroup( blocks );
1229             RELEASE_SM_LOCK
1230             cap->r.rNursery->n_blocks += blocks;
1231             
1232             // link the new group into the list
1233             bd->link = cap->r.rCurrentNursery;
1234             bd->u.back = cap->r.rCurrentNursery->u.back;
1235             if (cap->r.rCurrentNursery->u.back != NULL) {
1236                 cap->r.rCurrentNursery->u.back->link = bd;
1237             } else {
1238 #if !defined(THREADED_RTS)
1239                 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1240                        g0s0 == cap->r.rNursery);
1241 #endif
1242                 cap->r.rNursery->blocks = bd;
1243             }             
1244             cap->r.rCurrentNursery->u.back = bd;
1245             
1246             // initialise it as a nursery block.  We initialise the
1247             // step, gen_no, and flags field of *every* sub-block in
1248             // this large block, because this is easier than making
1249             // sure that we always find the block head of a large
1250             // block whenever we call Bdescr() (eg. evacuate() and
1251             // isAlive() in the GC would both have to do this, at
1252             // least).
1253             { 
1254                 bdescr *x;
1255                 for (x = bd; x < bd + blocks; x++) {
1256                     x->step = cap->r.rNursery;
1257                     x->gen_no = 0;
1258                     x->flags = 0;
1259                 }
1260             }
1261             
1262             // This assert can be a killer if the app is doing lots
1263             // of large block allocations.
1264             IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1265             
1266             // now update the nursery to point to the new block
1267             cap->r.rCurrentNursery = bd;
1268             
1269             // we might be unlucky and have another thread get on the
1270             // run queue before us and steal the large block, but in that
1271             // case the thread will just end up requesting another large
1272             // block.
1273             pushOnRunQueue(cap,t);
1274             return rtsFalse;  /* not actually GC'ing */
1275         }
1276     }
1277     
1278     debugTrace(DEBUG_sched,
1279                "--<< thread %ld (%s) stopped: HeapOverflow",
1280                (long)t->id, whatNext_strs[t->what_next]);
1281
1282     if (cap->r.rHpLim == NULL || cap->context_switch) {
1283         // Sometimes we miss a context switch, e.g. when calling
1284         // primitives in a tight loop, MAYBE_GC() doesn't check the
1285         // context switch flag, and we end up waiting for a GC.
1286         // See #1984, and concurrent/should_run/1984
1287         cap->context_switch = 0;
1288         addToRunQueue(cap,t);
1289     } else {
1290         pushOnRunQueue(cap,t);
1291     }
1292     return rtsTrue;
1293     /* actual GC is done at the end of the while loop in schedule() */
1294 }
1295
1296 /* -----------------------------------------------------------------------------
1297  * Handle a thread that returned to the scheduler with ThreadStackOverflow
1298  * -------------------------------------------------------------------------- */
1299
1300 static void
1301 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1302 {
1303     debugTrace (DEBUG_sched,
1304                 "--<< thread %ld (%s) stopped, StackOverflow", 
1305                 (long)t->id, whatNext_strs[t->what_next]);
1306
1307     /* just adjust the stack for this thread, then pop it back
1308      * on the run queue.
1309      */
1310     { 
1311         /* enlarge the stack */
1312         StgTSO *new_t = threadStackOverflow(cap, t);
1313         
1314         /* The TSO attached to this Task may have moved, so update the
1315          * pointer to it.
1316          */
1317         if (task->tso == t) {
1318             task->tso = new_t;
1319         }
1320         pushOnRunQueue(cap,new_t);
1321     }
1322 }
1323
1324 /* -----------------------------------------------------------------------------
1325  * Handle a thread that returned to the scheduler with ThreadYielding
1326  * -------------------------------------------------------------------------- */
1327
1328 static rtsBool
1329 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1330 {
1331     // Reset the context switch flag.  We don't do this just before
1332     // running the thread, because that would mean we would lose ticks
1333     // during GC, which can lead to unfair scheduling (a thread hogs
1334     // the CPU because the tick always arrives during GC).  This way
1335     // penalises threads that do a lot of allocation, but that seems
1336     // better than the alternative.
1337     cap->context_switch = 0;
1338     
1339     /* put the thread back on the run queue.  Then, if we're ready to
1340      * GC, check whether this is the last task to stop.  If so, wake
1341      * up the GC thread.  getThread will block during a GC until the
1342      * GC is finished.
1343      */
1344 #ifdef DEBUG
1345     if (t->what_next != prev_what_next) {
1346         debugTrace(DEBUG_sched,
1347                    "--<< thread %ld (%s) stopped to switch evaluators", 
1348                    (long)t->id, whatNext_strs[t->what_next]);
1349     } else {
1350         debugTrace(DEBUG_sched,
1351                    "--<< thread %ld (%s) stopped, yielding",
1352                    (long)t->id, whatNext_strs[t->what_next]);
1353     }
1354 #endif
1355     
1356     IF_DEBUG(sanity,
1357              //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1358              checkTSO(t));
1359     ASSERT(t->_link == END_TSO_QUEUE);
1360     
1361     // Shortcut if we're just switching evaluators: don't bother
1362     // doing stack squeezing (which can be expensive), just run the
1363     // thread.
1364     if (t->what_next != prev_what_next) {
1365         return rtsTrue;
1366     }
1367
1368     addToRunQueue(cap,t);
1369
1370     return rtsFalse;
1371 }
1372
1373 /* -----------------------------------------------------------------------------
1374  * Handle a thread that returned to the scheduler with ThreadBlocked
1375  * -------------------------------------------------------------------------- */
1376
1377 static void
1378 scheduleHandleThreadBlocked( StgTSO *t
1379 #if !defined(GRAN) && !defined(DEBUG)
1380     STG_UNUSED
1381 #endif
1382     )
1383 {
1384
1385       // We don't need to do anything.  The thread is blocked, and it
1386       // has tidied up its stack and placed itself on whatever queue
1387       // it needs to be on.
1388
1389     // ASSERT(t->why_blocked != NotBlocked);
1390     // Not true: for example,
1391     //    - in THREADED_RTS, the thread may already have been woken
1392     //      up by another Capability.  This actually happens: try
1393     //      conc023 +RTS -N2.
1394     //    - the thread may have woken itself up already, because
1395     //      threadPaused() might have raised a blocked throwTo
1396     //      exception, see maybePerformBlockedException().
1397
1398 #ifdef DEBUG
1399     if (traceClass(DEBUG_sched)) {
1400         debugTraceBegin("--<< thread %lu (%s) stopped: ", 
1401                         (unsigned long)t->id, whatNext_strs[t->what_next]);
1402         printThreadBlockage(t);
1403         debugTraceEnd();
1404     }
1405 #endif
1406 }
1407
1408 /* -----------------------------------------------------------------------------
1409  * Handle a thread that returned to the scheduler with ThreadFinished
1410  * -------------------------------------------------------------------------- */
1411
1412 static rtsBool
1413 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1414 {
1415     /* Need to check whether this was a main thread, and if so,
1416      * return with the return value.
1417      *
1418      * We also end up here if the thread kills itself with an
1419      * uncaught exception, see Exception.cmm.
1420      */
1421     debugTrace(DEBUG_sched, "--++ thread %lu (%s) finished", 
1422                (unsigned long)t->id, whatNext_strs[t->what_next]);
1423
1424     // blocked exceptions can now complete, even if the thread was in
1425     // blocked mode (see #2910).  This unconditionally calls
1426     // lockTSO(), which ensures that we don't miss any threads that
1427     // are engaged in throwTo() with this thread as a target.
1428     awakenBlockedExceptionQueue (cap, t);
1429
1430       //
1431       // Check whether the thread that just completed was a bound
1432       // thread, and if so return with the result.  
1433       //
1434       // There is an assumption here that all thread completion goes
1435       // through this point; we need to make sure that if a thread
1436       // ends up in the ThreadKilled state, that it stays on the run
1437       // queue so it can be dealt with here.
1438       //
1439
1440       if (t->bound) {
1441
1442           if (t->bound != task) {
1443 #if !defined(THREADED_RTS)
1444               // Must be a bound thread that is not the topmost one.  Leave
1445               // it on the run queue until the stack has unwound to the
1446               // point where we can deal with this.  Leaving it on the run
1447               // queue also ensures that the garbage collector knows about
1448               // this thread and its return value (it gets dropped from the
1449               // step->threads list so there's no other way to find it).
1450               appendToRunQueue(cap,t);
1451               return rtsFalse;
1452 #else
1453               // this cannot happen in the threaded RTS, because a
1454               // bound thread can only be run by the appropriate Task.
1455               barf("finished bound thread that isn't mine");
1456 #endif
1457           }
1458
1459           ASSERT(task->tso == t);
1460
1461           if (t->what_next == ThreadComplete) {
1462               if (task->ret) {
1463                   // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1464                   *(task->ret) = (StgClosure *)task->tso->sp[1]; 
1465               }
1466               task->stat = Success;
1467           } else {
1468               if (task->ret) {
1469                   *(task->ret) = NULL;
1470               }
1471               if (sched_state >= SCHED_INTERRUPTING) {
1472                   if (heap_overflow) {
1473                       task->stat = HeapExhausted;
1474                   } else {
1475                       task->stat = Interrupted;
1476                   }
1477               } else {
1478                   task->stat = Killed;
1479               }
1480           }
1481 #ifdef DEBUG
1482           removeThreadLabel((StgWord)task->tso->id);
1483 #endif
1484           return rtsTrue; // tells schedule() to return
1485       }
1486
1487       return rtsFalse;
1488 }
1489
1490 /* -----------------------------------------------------------------------------
1491  * Perform a heap census
1492  * -------------------------------------------------------------------------- */
1493
1494 static rtsBool
1495 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1496 {
1497     // When we have +RTS -i0 and we're heap profiling, do a census at
1498     // every GC.  This lets us get repeatable runs for debugging.
1499     if (performHeapProfile ||
1500         (RtsFlags.ProfFlags.profileInterval==0 &&
1501          RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1502         return rtsTrue;
1503     } else {
1504         return rtsFalse;
1505     }
1506 }
1507
1508 /* -----------------------------------------------------------------------------
1509  * Perform a garbage collection if necessary
1510  * -------------------------------------------------------------------------- */
1511
1512 static Capability *
1513 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1514 {
1515     rtsBool heap_census;
1516 #ifdef THREADED_RTS
1517     /* extern static volatile StgWord waiting_for_gc; 
1518        lives inside capability.c */
1519     rtsBool gc_type, prev_pending_gc;
1520     nat i;
1521 #endif
1522
1523     if (sched_state == SCHED_SHUTTING_DOWN) {
1524         // The final GC has already been done, and the system is
1525         // shutting down.  We'll probably deadlock if we try to GC
1526         // now.
1527         return cap;
1528     }
1529
1530 #ifdef THREADED_RTS
1531     if (sched_state < SCHED_INTERRUPTING
1532         && RtsFlags.ParFlags.parGcEnabled
1533         && N >= RtsFlags.ParFlags.parGcGen
1534         && ! oldest_gen->steps[0].mark)
1535     {
1536         gc_type = PENDING_GC_PAR;
1537     } else {
1538         gc_type = PENDING_GC_SEQ;
1539     }
1540
1541     // In order to GC, there must be no threads running Haskell code.
1542     // Therefore, the GC thread needs to hold *all* the capabilities,
1543     // and release them after the GC has completed.  
1544     //
1545     // This seems to be the simplest way: previous attempts involved
1546     // making all the threads with capabilities give up their
1547     // capabilities and sleep except for the *last* one, which
1548     // actually did the GC.  But it's quite hard to arrange for all
1549     // the other tasks to sleep and stay asleep.
1550     //
1551
1552     /*  Other capabilities are prevented from running yet more Haskell
1553         threads if waiting_for_gc is set. Tested inside
1554         yieldCapability() and releaseCapability() in Capability.c */
1555
1556     prev_pending_gc = cas(&waiting_for_gc, 0, gc_type);
1557     if (prev_pending_gc) {
1558         do {
1559             debugTrace(DEBUG_sched, "someone else is trying to GC (%d)...", 
1560                        prev_pending_gc);
1561             ASSERT(cap);
1562             yieldCapability(&cap,task);
1563         } while (waiting_for_gc);
1564         return cap;  // NOTE: task->cap might have changed here
1565     }
1566
1567     setContextSwitches();
1568
1569     // The final shutdown GC is always single-threaded, because it's
1570     // possible that some of the Capabilities have no worker threads.
1571     
1572     if (gc_type == PENDING_GC_SEQ)
1573     {
1574         postEvent(cap, EVENT_REQUEST_SEQ_GC, 0, 0);
1575         // single-threaded GC: grab all the capabilities
1576         for (i=0; i < n_capabilities; i++) {
1577             debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1578             if (cap != &capabilities[i]) {
1579                 Capability *pcap = &capabilities[i];
1580                 // we better hope this task doesn't get migrated to
1581                 // another Capability while we're waiting for this one.
1582                 // It won't, because load balancing happens while we have
1583                 // all the Capabilities, but even so it's a slightly
1584                 // unsavoury invariant.
1585                 task->cap = pcap;
1586                 waitForReturnCapability(&pcap, task);
1587                 if (pcap != &capabilities[i]) {
1588                     barf("scheduleDoGC: got the wrong capability");
1589                 }
1590             }
1591         }
1592     }
1593     else
1594     {
1595         // multi-threaded GC: make sure all the Capabilities donate one
1596         // GC thread each.
1597         postEvent(cap, EVENT_REQUEST_PAR_GC, 0, 0);
1598         debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1599
1600         waitForGcThreads(cap);
1601     }
1602 #endif
1603
1604     // so this happens periodically:
1605     if (cap) scheduleCheckBlackHoles(cap);
1606     
1607     IF_DEBUG(scheduler, printAllThreads());
1608
1609 delete_threads_and_gc:
1610     /*
1611      * We now have all the capabilities; if we're in an interrupting
1612      * state, then we should take the opportunity to delete all the
1613      * threads in the system.
1614      */
1615     if (sched_state == SCHED_INTERRUPTING) {
1616         deleteAllThreads(cap);
1617         sched_state = SCHED_SHUTTING_DOWN;
1618     }
1619     
1620     heap_census = scheduleNeedHeapProfile(rtsTrue);
1621
1622 #if defined(THREADED_RTS)
1623     postEvent(cap, EVENT_GC_START, 0, 0);
1624     debugTrace(DEBUG_sched, "doing GC");
1625     // reset waiting_for_gc *before* GC, so that when the GC threads
1626     // emerge they don't immediately re-enter the GC.
1627     waiting_for_gc = 0;
1628     GarbageCollect(force_major || heap_census, gc_type, cap);
1629 #else
1630     GarbageCollect(force_major || heap_census, 0, cap);
1631 #endif
1632     postEvent(cap, EVENT_GC_END, 0, 0);
1633
1634     if (recent_activity == ACTIVITY_INACTIVE && force_major)
1635     {
1636         // We are doing a GC because the system has been idle for a
1637         // timeslice and we need to check for deadlock.  Record the
1638         // fact that we've done a GC and turn off the timer signal;
1639         // it will get re-enabled if we run any threads after the GC.
1640         recent_activity = ACTIVITY_DONE_GC;
1641         stopTimer();
1642     }
1643     else
1644     {
1645         // the GC might have taken long enough for the timer to set
1646         // recent_activity = ACTIVITY_INACTIVE, but we aren't
1647         // necessarily deadlocked:
1648         recent_activity = ACTIVITY_YES;
1649     }
1650
1651 #if defined(THREADED_RTS)
1652     if (gc_type == PENDING_GC_PAR)
1653     {
1654         releaseGCThreads(cap);
1655     }
1656 #endif
1657
1658     if (heap_census) {
1659         debugTrace(DEBUG_sched, "performing heap census");
1660         heapCensus();
1661         performHeapProfile = rtsFalse;
1662     }
1663
1664     if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1665         // GC set the heap_overflow flag, so we should proceed with
1666         // an orderly shutdown now.  Ultimately we want the main
1667         // thread to return to its caller with HeapExhausted, at which
1668         // point the caller should call hs_exit().  The first step is
1669         // to delete all the threads.
1670         //
1671         // Another way to do this would be to raise an exception in
1672         // the main thread, which we really should do because it gives
1673         // the program a chance to clean up.  But how do we find the
1674         // main thread?  It should presumably be the same one that
1675         // gets ^C exceptions, but that's all done on the Haskell side
1676         // (GHC.TopHandler).
1677         sched_state = SCHED_INTERRUPTING;
1678         goto delete_threads_and_gc;
1679     }
1680
1681 #ifdef SPARKBALANCE
1682     /* JB 
1683        Once we are all together... this would be the place to balance all
1684        spark pools. No concurrent stealing or adding of new sparks can
1685        occur. Should be defined in Sparks.c. */
1686     balanceSparkPoolsCaps(n_capabilities, capabilities);
1687 #endif
1688
1689 #if defined(THREADED_RTS)
1690     if (gc_type == PENDING_GC_SEQ) {
1691         // release our stash of capabilities.
1692         for (i = 0; i < n_capabilities; i++) {
1693             if (cap != &capabilities[i]) {
1694                 task->cap = &capabilities[i];
1695                 releaseCapability(&capabilities[i]);
1696             }
1697         }
1698     }
1699     if (cap) {
1700         task->cap = cap;
1701     } else {
1702         task->cap = NULL;
1703     }
1704 #endif
1705
1706     return cap;
1707 }
1708
1709 /* ---------------------------------------------------------------------------
1710  * Singleton fork(). Do not copy any running threads.
1711  * ------------------------------------------------------------------------- */
1712
1713 pid_t
1714 forkProcess(HsStablePtr *entry
1715 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1716             STG_UNUSED
1717 #endif
1718            )
1719 {
1720 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1721     Task *task;
1722     pid_t pid;
1723     StgTSO* t,*next;
1724     Capability *cap;
1725     nat s;
1726     
1727 #if defined(THREADED_RTS)
1728     if (RtsFlags.ParFlags.nNodes > 1) {
1729         errorBelch("forking not supported with +RTS -N<n> greater than 1");
1730         stg_exit(EXIT_FAILURE);
1731     }
1732 #endif
1733
1734     debugTrace(DEBUG_sched, "forking!");
1735     
1736     // ToDo: for SMP, we should probably acquire *all* the capabilities
1737     cap = rts_lock();
1738     
1739     // no funny business: hold locks while we fork, otherwise if some
1740     // other thread is holding a lock when the fork happens, the data
1741     // structure protected by the lock will forever be in an
1742     // inconsistent state in the child.  See also #1391.
1743     ACQUIRE_LOCK(&sched_mutex);
1744     ACQUIRE_LOCK(&cap->lock);
1745     ACQUIRE_LOCK(&cap->running_task->lock);
1746
1747     pid = fork();
1748     
1749     if (pid) { // parent
1750         
1751         RELEASE_LOCK(&sched_mutex);
1752         RELEASE_LOCK(&cap->lock);
1753         RELEASE_LOCK(&cap->running_task->lock);
1754
1755         // just return the pid
1756         rts_unlock(cap);
1757         return pid;
1758         
1759     } else { // child
1760         
1761 #if defined(THREADED_RTS)
1762         initMutex(&sched_mutex);
1763         initMutex(&cap->lock);
1764         initMutex(&cap->running_task->lock);
1765 #endif
1766
1767         // Now, all OS threads except the thread that forked are
1768         // stopped.  We need to stop all Haskell threads, including
1769         // those involved in foreign calls.  Also we need to delete
1770         // all Tasks, because they correspond to OS threads that are
1771         // now gone.
1772
1773         for (s = 0; s < total_steps; s++) {
1774           for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1775             if (t->what_next == ThreadRelocated) {
1776                 next = t->_link;
1777             } else {
1778                 next = t->global_link;
1779                 // don't allow threads to catch the ThreadKilled
1780                 // exception, but we do want to raiseAsync() because these
1781                 // threads may be evaluating thunks that we need later.
1782                 deleteThread_(cap,t);
1783             }
1784           }
1785         }
1786         
1787         // Empty the run queue.  It seems tempting to let all the
1788         // killed threads stay on the run queue as zombies to be
1789         // cleaned up later, but some of them correspond to bound
1790         // threads for which the corresponding Task does not exist.
1791         cap->run_queue_hd = END_TSO_QUEUE;
1792         cap->run_queue_tl = END_TSO_QUEUE;
1793
1794         // Any suspended C-calling Tasks are no more, their OS threads
1795         // don't exist now:
1796         cap->suspended_ccalling_tasks = NULL;
1797
1798         // Empty the threads lists.  Otherwise, the garbage
1799         // collector may attempt to resurrect some of these threads.
1800         for (s = 0; s < total_steps; s++) {
1801             all_steps[s].threads = END_TSO_QUEUE;
1802         }
1803
1804         // Wipe the task list, except the current Task.
1805         ACQUIRE_LOCK(&sched_mutex);
1806         for (task = all_tasks; task != NULL; task=task->all_link) {
1807             if (task != cap->running_task) {
1808 #if defined(THREADED_RTS)
1809                 initMutex(&task->lock); // see #1391
1810 #endif
1811                 discardTask(task);
1812             }
1813         }
1814         RELEASE_LOCK(&sched_mutex);
1815
1816 #if defined(THREADED_RTS)
1817         // Wipe our spare workers list, they no longer exist.  New
1818         // workers will be created if necessary.
1819         cap->spare_workers = NULL;
1820         cap->returning_tasks_hd = NULL;
1821         cap->returning_tasks_tl = NULL;
1822 #endif
1823
1824         // On Unix, all timers are reset in the child, so we need to start
1825         // the timer again.
1826         initTimer();
1827         startTimer();
1828
1829         cap = rts_evalStableIO(cap, entry, NULL);  // run the action
1830         rts_checkSchedStatus("forkProcess",cap);
1831         
1832         rts_unlock(cap);
1833         hs_exit();                      // clean up and exit
1834         stg_exit(EXIT_SUCCESS);
1835     }
1836 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1837     barf("forkProcess#: primop not supported on this platform, sorry!\n");
1838     return -1;
1839 #endif
1840 }
1841
1842 /* ---------------------------------------------------------------------------
1843  * Delete all the threads in the system
1844  * ------------------------------------------------------------------------- */
1845    
1846 static void
1847 deleteAllThreads ( Capability *cap )
1848 {
1849     // NOTE: only safe to call if we own all capabilities.
1850
1851     StgTSO* t, *next;
1852     nat s;
1853
1854     debugTrace(DEBUG_sched,"deleting all threads");
1855     for (s = 0; s < total_steps; s++) {
1856       for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1857         if (t->what_next == ThreadRelocated) {
1858             next = t->_link;
1859         } else {
1860             next = t->global_link;
1861             deleteThread(cap,t);
1862         }
1863       }
1864     }      
1865
1866     // The run queue now contains a bunch of ThreadKilled threads.  We
1867     // must not throw these away: the main thread(s) will be in there
1868     // somewhere, and the main scheduler loop has to deal with it.
1869     // Also, the run queue is the only thing keeping these threads from
1870     // being GC'd, and we don't want the "main thread has been GC'd" panic.
1871
1872 #if !defined(THREADED_RTS)
1873     ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1874     ASSERT(sleeping_queue == END_TSO_QUEUE);
1875 #endif
1876 }
1877
1878 /* -----------------------------------------------------------------------------
1879    Managing the suspended_ccalling_tasks list.
1880    Locks required: sched_mutex
1881    -------------------------------------------------------------------------- */
1882
1883 STATIC_INLINE void
1884 suspendTask (Capability *cap, Task *task)
1885 {
1886     ASSERT(task->next == NULL && task->prev == NULL);
1887     task->next = cap->suspended_ccalling_tasks;
1888     task->prev = NULL;
1889     if (cap->suspended_ccalling_tasks) {
1890         cap->suspended_ccalling_tasks->prev = task;
1891     }
1892     cap->suspended_ccalling_tasks = task;
1893 }
1894
1895 STATIC_INLINE void
1896 recoverSuspendedTask (Capability *cap, Task *task)
1897 {
1898     if (task->prev) {
1899         task->prev->next = task->next;
1900     } else {
1901         ASSERT(cap->suspended_ccalling_tasks == task);
1902         cap->suspended_ccalling_tasks = task->next;
1903     }
1904     if (task->next) {
1905         task->next->prev = task->prev;
1906     }
1907     task->next = task->prev = NULL;
1908 }
1909
1910 /* ---------------------------------------------------------------------------
1911  * Suspending & resuming Haskell threads.
1912  * 
1913  * When making a "safe" call to C (aka _ccall_GC), the task gives back
1914  * its capability before calling the C function.  This allows another
1915  * task to pick up the capability and carry on running Haskell
1916  * threads.  It also means that if the C call blocks, it won't lock
1917  * the whole system.
1918  *
1919  * The Haskell thread making the C call is put to sleep for the
1920  * duration of the call, on the susepended_ccalling_threads queue.  We
1921  * give out a token to the task, which it can use to resume the thread
1922  * on return from the C function.
1923  * ------------------------------------------------------------------------- */
1924    
1925 void *
1926 suspendThread (StgRegTable *reg)
1927 {
1928   Capability *cap;
1929   int saved_errno;
1930   StgTSO *tso;
1931   Task *task;
1932 #if mingw32_HOST_OS
1933   StgWord32 saved_winerror;
1934 #endif
1935
1936   saved_errno = errno;
1937 #if mingw32_HOST_OS
1938   saved_winerror = GetLastError();
1939 #endif
1940
1941   /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1942    */
1943   cap = regTableToCapability(reg);
1944
1945   task = cap->running_task;
1946   tso = cap->r.rCurrentTSO;
1947
1948   postEvent(cap, EVENT_STOP_THREAD, tso->id, THREAD_SUSPENDED_FOREIGN_CALL);
1949   debugTrace(DEBUG_sched, 
1950              "thread %lu did a safe foreign call", 
1951              (unsigned long)cap->r.rCurrentTSO->id);
1952
1953   // XXX this might not be necessary --SDM
1954   tso->what_next = ThreadRunGHC;
1955
1956   threadPaused(cap,tso);
1957
1958   if ((tso->flags & TSO_BLOCKEX) == 0)  {
1959       tso->why_blocked = BlockedOnCCall;
1960       tso->flags |= TSO_BLOCKEX;
1961       tso->flags &= ~TSO_INTERRUPTIBLE;
1962   } else {
1963       tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1964   }
1965
1966   // Hand back capability
1967   task->suspended_tso = tso;
1968
1969   ACQUIRE_LOCK(&cap->lock);
1970
1971   suspendTask(cap,task);
1972   cap->in_haskell = rtsFalse;
1973   releaseCapability_(cap,rtsFalse);
1974   
1975   RELEASE_LOCK(&cap->lock);
1976
1977 #if defined(THREADED_RTS)
1978   /* Preparing to leave the RTS, so ensure there's a native thread/task
1979      waiting to take over.
1980   */
1981   debugTrace(DEBUG_sched, "thread %lu: leaving RTS", (unsigned long)tso->id);
1982 #endif
1983
1984   errno = saved_errno;
1985 #if mingw32_HOST_OS
1986   SetLastError(saved_winerror);
1987 #endif
1988   return task;
1989 }
1990
1991 StgRegTable *
1992 resumeThread (void *task_)
1993 {
1994     StgTSO *tso;
1995     Capability *cap;
1996     Task *task = task_;
1997     int saved_errno;
1998 #if mingw32_HOST_OS
1999     StgWord32 saved_winerror;
2000 #endif
2001
2002     saved_errno = errno;
2003 #if mingw32_HOST_OS
2004     saved_winerror = GetLastError();
2005 #endif
2006
2007     cap = task->cap;
2008     // Wait for permission to re-enter the RTS with the result.
2009     waitForReturnCapability(&cap,task);
2010     // we might be on a different capability now... but if so, our
2011     // entry on the suspended_ccalling_tasks list will also have been
2012     // migrated.
2013
2014     // Remove the thread from the suspended list
2015     recoverSuspendedTask(cap,task);
2016
2017     tso = task->suspended_tso;
2018     task->suspended_tso = NULL;
2019     tso->_link = END_TSO_QUEUE; // no write barrier reqd
2020
2021     postEvent(cap, EVENT_RUN_THREAD, tso->id, 0);
2022     debugTrace(DEBUG_sched, "thread %lu: re-entering RTS", (unsigned long)tso->id);
2023     
2024     if (tso->why_blocked == BlockedOnCCall) {
2025         // avoid locking the TSO if we don't have to
2026         if (tso->blocked_exceptions != END_TSO_QUEUE) {
2027             awakenBlockedExceptionQueue(cap,tso);
2028         }
2029         tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
2030     }
2031     
2032     /* Reset blocking status */
2033     tso->why_blocked  = NotBlocked;
2034     
2035     cap->r.rCurrentTSO = tso;
2036     cap->in_haskell = rtsTrue;
2037     errno = saved_errno;
2038 #if mingw32_HOST_OS
2039     SetLastError(saved_winerror);
2040 #endif
2041
2042     /* We might have GC'd, mark the TSO dirty again */
2043     dirty_TSO(cap,tso);
2044
2045     IF_DEBUG(sanity, checkTSO(tso));
2046
2047     return &cap->r;
2048 }
2049
2050 /* ---------------------------------------------------------------------------
2051  * scheduleThread()
2052  *
2053  * scheduleThread puts a thread on the end  of the runnable queue.
2054  * This will usually be done immediately after a thread is created.
2055  * The caller of scheduleThread must create the thread using e.g.
2056  * createThread and push an appropriate closure
2057  * on this thread's stack before the scheduler is invoked.
2058  * ------------------------------------------------------------------------ */
2059
2060 void
2061 scheduleThread(Capability *cap, StgTSO *tso)
2062 {
2063     // The thread goes at the *end* of the run-queue, to avoid possible
2064     // starvation of any threads already on the queue.
2065     appendToRunQueue(cap,tso);
2066 }
2067
2068 void
2069 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
2070 {
2071 #if defined(THREADED_RTS)
2072     tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
2073                               // move this thread from now on.
2074     cpu %= RtsFlags.ParFlags.nNodes;
2075     if (cpu == cap->no) {
2076         appendToRunQueue(cap,tso);
2077     } else {
2078         postEvent (cap, EVENT_MIGRATE_THREAD, tso->id, capabilities[cpu].no);
2079         wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
2080     }
2081 #else
2082     appendToRunQueue(cap,tso);
2083 #endif
2084 }
2085
2086 Capability *
2087 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
2088 {
2089     Task *task;
2090
2091     // We already created/initialised the Task
2092     task = cap->running_task;
2093
2094     // This TSO is now a bound thread; make the Task and TSO
2095     // point to each other.
2096     tso->bound = task;
2097     tso->cap = cap;
2098
2099     task->tso = tso;
2100     task->ret = ret;
2101     task->stat = NoStatus;
2102
2103     appendToRunQueue(cap,tso);
2104
2105     debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)tso->id);
2106
2107     cap = schedule(cap,task);
2108
2109     ASSERT(task->stat != NoStatus);
2110     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
2111
2112     debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)task->tso->id);
2113     return cap;
2114 }
2115
2116 /* ----------------------------------------------------------------------------
2117  * Starting Tasks
2118  * ------------------------------------------------------------------------- */
2119
2120 #if defined(THREADED_RTS)
2121 void OSThreadProcAttr
2122 workerStart(Task *task)
2123 {
2124     Capability *cap;
2125
2126     // See startWorkerTask().
2127     ACQUIRE_LOCK(&task->lock);
2128     cap = task->cap;
2129     RELEASE_LOCK(&task->lock);
2130
2131     if (RtsFlags.ParFlags.setAffinity) {
2132         setThreadAffinity(cap->no, n_capabilities);
2133     }
2134
2135     // set the thread-local pointer to the Task:
2136     taskEnter(task);
2137
2138     // schedule() runs without a lock.
2139     cap = schedule(cap,task);
2140
2141     // On exit from schedule(), we have a Capability, but possibly not
2142     // the same one we started with.
2143
2144     // During shutdown, the requirement is that after all the
2145     // Capabilities are shut down, all workers that are shutting down
2146     // have finished workerTaskStop().  This is why we hold on to
2147     // cap->lock until we've finished workerTaskStop() below.
2148     //
2149     // There may be workers still involved in foreign calls; those
2150     // will just block in waitForReturnCapability() because the
2151     // Capability has been shut down.
2152     //
2153     ACQUIRE_LOCK(&cap->lock);
2154     releaseCapability_(cap,rtsFalse);
2155     workerTaskStop(task);
2156     RELEASE_LOCK(&cap->lock);
2157 }
2158 #endif
2159
2160 /* ---------------------------------------------------------------------------
2161  * initScheduler()
2162  *
2163  * Initialise the scheduler.  This resets all the queues - if the
2164  * queues contained any threads, they'll be garbage collected at the
2165  * next pass.
2166  *
2167  * ------------------------------------------------------------------------ */
2168
2169 void 
2170 initScheduler(void)
2171 {
2172 #if !defined(THREADED_RTS)
2173   blocked_queue_hd  = END_TSO_QUEUE;
2174   blocked_queue_tl  = END_TSO_QUEUE;
2175   sleeping_queue    = END_TSO_QUEUE;
2176 #endif
2177
2178   blackhole_queue   = END_TSO_QUEUE;
2179
2180   sched_state    = SCHED_RUNNING;
2181   recent_activity = ACTIVITY_YES;
2182
2183 #if defined(THREADED_RTS)
2184   /* Initialise the mutex and condition variables used by
2185    * the scheduler. */
2186   initMutex(&sched_mutex);
2187 #endif
2188   
2189   ACQUIRE_LOCK(&sched_mutex);
2190
2191   /* A capability holds the state a native thread needs in
2192    * order to execute STG code. At least one capability is
2193    * floating around (only THREADED_RTS builds have more than one).
2194    */
2195   initCapabilities();
2196
2197   initTaskManager();
2198
2199 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
2200   initSparkPools();
2201 #endif
2202
2203 #if defined(THREADED_RTS)
2204   /*
2205    * Eagerly start one worker to run each Capability, except for
2206    * Capability 0.  The idea is that we're probably going to start a
2207    * bound thread on Capability 0 pretty soon, so we don't want a
2208    * worker task hogging it.
2209    */
2210   { 
2211       nat i;
2212       Capability *cap;
2213       for (i = 1; i < n_capabilities; i++) {
2214           cap = &capabilities[i];
2215           ACQUIRE_LOCK(&cap->lock);
2216           startWorkerTask(cap, workerStart);
2217           RELEASE_LOCK(&cap->lock);
2218       }
2219   }
2220 #endif
2221
2222   RELEASE_LOCK(&sched_mutex);
2223 }
2224
2225 void
2226 exitScheduler(
2227     rtsBool wait_foreign
2228 #if !defined(THREADED_RTS)
2229                          __attribute__((unused))
2230 #endif
2231 )
2232                /* see Capability.c, shutdownCapability() */
2233 {
2234     Task *task = NULL;
2235
2236     ACQUIRE_LOCK(&sched_mutex);
2237     task = newBoundTask();
2238     RELEASE_LOCK(&sched_mutex);
2239
2240     // If we haven't killed all the threads yet, do it now.
2241     if (sched_state < SCHED_SHUTTING_DOWN) {
2242         sched_state = SCHED_INTERRUPTING;
2243         waitForReturnCapability(&task->cap,task);
2244         scheduleDoGC(task->cap,task,rtsFalse);    
2245         releaseCapability(task->cap);
2246     }
2247     sched_state = SCHED_SHUTTING_DOWN;
2248
2249 #if defined(THREADED_RTS)
2250     { 
2251         nat i;
2252         
2253         for (i = 0; i < n_capabilities; i++) {
2254             shutdownCapability(&capabilities[i], task, wait_foreign);
2255         }
2256         boundTaskExiting(task);
2257     }
2258 #endif
2259 }
2260
2261 void
2262 freeScheduler( void )
2263 {
2264     nat still_running;
2265
2266     ACQUIRE_LOCK(&sched_mutex);
2267     still_running = freeTaskManager();
2268     // We can only free the Capabilities if there are no Tasks still
2269     // running.  We might have a Task about to return from a foreign
2270     // call into waitForReturnCapability(), for example (actually,
2271     // this should be the *only* thing that a still-running Task can
2272     // do at this point, and it will block waiting for the
2273     // Capability).
2274     if (still_running == 0) {
2275         freeCapabilities();
2276         if (n_capabilities != 1) {
2277             stgFree(capabilities);
2278         }
2279     }
2280     RELEASE_LOCK(&sched_mutex);
2281 #if defined(THREADED_RTS)
2282     closeMutex(&sched_mutex);
2283 #endif
2284 }
2285
2286 /* -----------------------------------------------------------------------------
2287    performGC
2288
2289    This is the interface to the garbage collector from Haskell land.
2290    We provide this so that external C code can allocate and garbage
2291    collect when called from Haskell via _ccall_GC.
2292    -------------------------------------------------------------------------- */
2293
2294 static void
2295 performGC_(rtsBool force_major)
2296 {
2297     Task *task;
2298
2299     // We must grab a new Task here, because the existing Task may be
2300     // associated with a particular Capability, and chained onto the 
2301     // suspended_ccalling_tasks queue.
2302     ACQUIRE_LOCK(&sched_mutex);
2303     task = newBoundTask();
2304     RELEASE_LOCK(&sched_mutex);
2305
2306     waitForReturnCapability(&task->cap,task);
2307     scheduleDoGC(task->cap,task,force_major);
2308     releaseCapability(task->cap);
2309     boundTaskExiting(task);
2310 }
2311
2312 void
2313 performGC(void)
2314 {
2315     performGC_(rtsFalse);
2316 }
2317
2318 void
2319 performMajorGC(void)
2320 {
2321     performGC_(rtsTrue);
2322 }
2323
2324 /* -----------------------------------------------------------------------------
2325    Stack overflow
2326
2327    If the thread has reached its maximum stack size, then raise the
2328    StackOverflow exception in the offending thread.  Otherwise
2329    relocate the TSO into a larger chunk of memory and adjust its stack
2330    size appropriately.
2331    -------------------------------------------------------------------------- */
2332
2333 static StgTSO *
2334 threadStackOverflow(Capability *cap, StgTSO *tso)
2335 {
2336   nat new_stack_size, stack_words;
2337   lnat new_tso_size;
2338   StgPtr new_sp;
2339   StgTSO *dest;
2340
2341   IF_DEBUG(sanity,checkTSO(tso));
2342
2343   // don't allow throwTo() to modify the blocked_exceptions queue
2344   // while we are moving the TSO:
2345   lockClosure((StgClosure *)tso);
2346
2347   if (tso->stack_size >= tso->max_stack_size && !(tso->flags & TSO_BLOCKEX)) {
2348       // NB. never raise a StackOverflow exception if the thread is
2349       // inside Control.Exceptino.block.  It is impractical to protect
2350       // against stack overflow exceptions, since virtually anything
2351       // can raise one (even 'catch'), so this is the only sensible
2352       // thing to do here.  See bug #767.
2353
2354       debugTrace(DEBUG_gc,
2355                  "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2356                  (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2357       IF_DEBUG(gc,
2358                /* If we're debugging, just print out the top of the stack */
2359                printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size, 
2360                                                 tso->sp+64)));
2361
2362       // Send this thread the StackOverflow exception
2363       unlockTSO(tso);
2364       throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2365       return tso;
2366   }
2367
2368   /* Try to double the current stack size.  If that takes us over the
2369    * maximum stack size for this thread, then use the maximum instead
2370    * (that is, unless we're already at or over the max size and we
2371    * can't raise the StackOverflow exception (see above), in which
2372    * case just double the size). Finally round up so the TSO ends up as
2373    * a whole number of blocks.
2374    */
2375   if (tso->stack_size >= tso->max_stack_size) {
2376       new_stack_size = tso->stack_size * 2;
2377   } else { 
2378       new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2379   }
2380   new_tso_size   = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) + 
2381                                        TSO_STRUCT_SIZE)/sizeof(W_);
2382   new_tso_size = round_to_mblocks(new_tso_size);  /* Be MBLOCK-friendly */
2383   new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2384
2385   debugTrace(DEBUG_sched, 
2386              "increasing stack size from %ld words to %d.",
2387              (long)tso->stack_size, new_stack_size);
2388
2389   dest = (StgTSO *)allocateLocal(cap,new_tso_size);
2390   TICK_ALLOC_TSO(new_stack_size,0);
2391
2392   /* copy the TSO block and the old stack into the new area */
2393   memcpy(dest,tso,TSO_STRUCT_SIZE);
2394   stack_words = tso->stack + tso->stack_size - tso->sp;
2395   new_sp = (P_)dest + new_tso_size - stack_words;
2396   memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2397
2398   /* relocate the stack pointers... */
2399   dest->sp         = new_sp;
2400   dest->stack_size = new_stack_size;
2401         
2402   /* Mark the old TSO as relocated.  We have to check for relocated
2403    * TSOs in the garbage collector and any primops that deal with TSOs.
2404    *
2405    * It's important to set the sp value to just beyond the end
2406    * of the stack, so we don't attempt to scavenge any part of the
2407    * dead TSO's stack.
2408    */
2409   tso->what_next = ThreadRelocated;
2410   setTSOLink(cap,tso,dest);
2411   tso->sp = (P_)&(tso->stack[tso->stack_size]);
2412   tso->why_blocked = NotBlocked;
2413
2414   IF_PAR_DEBUG(verbose,
2415                debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2416                      tso->id, tso, tso->stack_size);
2417                /* If we're debugging, just print out the top of the stack */
2418                printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size, 
2419                                                 tso->sp+64)));
2420   
2421   unlockTSO(dest);
2422   unlockTSO(tso);
2423
2424   IF_DEBUG(sanity,checkTSO(dest));
2425 #if 0
2426   IF_DEBUG(scheduler,printTSO(dest));
2427 #endif
2428
2429   return dest;
2430 }
2431
2432 static StgTSO *
2433 threadStackUnderflow (Task *task STG_UNUSED, StgTSO *tso)
2434 {
2435     bdescr *bd, *new_bd;
2436     lnat free_w, tso_size_w;
2437     StgTSO *new_tso;
2438
2439     tso_size_w = tso_sizeW(tso);
2440
2441     if (tso_size_w < MBLOCK_SIZE_W || 
2442         (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4) 
2443     {
2444         return tso;
2445     }
2446
2447     // don't allow throwTo() to modify the blocked_exceptions queue
2448     // while we are moving the TSO:
2449     lockClosure((StgClosure *)tso);
2450
2451     // this is the number of words we'll free
2452     free_w = round_to_mblocks(tso_size_w/2);
2453
2454     bd = Bdescr((StgPtr)tso);
2455     new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2456     bd->free = bd->start + TSO_STRUCT_SIZEW;
2457
2458     new_tso = (StgTSO *)new_bd->start;
2459     memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2460     new_tso->stack_size = new_bd->free - new_tso->stack;
2461
2462     debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2463                (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2464
2465     tso->what_next = ThreadRelocated;
2466     tso->_link = new_tso; // no write barrier reqd: same generation
2467
2468     // The TSO attached to this Task may have moved, so update the
2469     // pointer to it.
2470     if (task->tso == tso) {
2471         task->tso = new_tso;
2472     }
2473
2474     unlockTSO(new_tso);
2475     unlockTSO(tso);
2476
2477     IF_DEBUG(sanity,checkTSO(new_tso));
2478
2479     return new_tso;
2480 }
2481
2482 /* ---------------------------------------------------------------------------
2483    Interrupt execution
2484    - usually called inside a signal handler so it mustn't do anything fancy.   
2485    ------------------------------------------------------------------------ */
2486
2487 void
2488 interruptStgRts(void)
2489 {
2490     sched_state = SCHED_INTERRUPTING;
2491     setContextSwitches();
2492     wakeUpRts();
2493 }
2494
2495 /* -----------------------------------------------------------------------------
2496    Wake up the RTS
2497    
2498    This function causes at least one OS thread to wake up and run the
2499    scheduler loop.  It is invoked when the RTS might be deadlocked, or
2500    an external event has arrived that may need servicing (eg. a
2501    keyboard interrupt).
2502
2503    In the single-threaded RTS we don't do anything here; we only have
2504    one thread anyway, and the event that caused us to want to wake up
2505    will have interrupted any blocking system call in progress anyway.
2506    -------------------------------------------------------------------------- */
2507
2508 void
2509 wakeUpRts(void)
2510 {
2511 #if defined(THREADED_RTS)
2512     // This forces the IO Manager thread to wakeup, which will
2513     // in turn ensure that some OS thread wakes up and runs the
2514     // scheduler loop, which will cause a GC and deadlock check.
2515     ioManagerWakeup();
2516 #endif
2517 }
2518
2519 /* -----------------------------------------------------------------------------
2520  * checkBlackHoles()
2521  *
2522  * Check the blackhole_queue for threads that can be woken up.  We do
2523  * this periodically: before every GC, and whenever the run queue is
2524  * empty.
2525  *
2526  * An elegant solution might be to just wake up all the blocked
2527  * threads with awakenBlockedQueue occasionally: they'll go back to
2528  * sleep again if the object is still a BLACKHOLE.  Unfortunately this
2529  * doesn't give us a way to tell whether we've actually managed to
2530  * wake up any threads, so we would be busy-waiting.
2531  *
2532  * -------------------------------------------------------------------------- */
2533
2534 static rtsBool
2535 checkBlackHoles (Capability *cap)
2536 {
2537     StgTSO **prev, *t;
2538     rtsBool any_woke_up = rtsFalse;
2539     StgHalfWord type;
2540
2541     // blackhole_queue is global:
2542     ASSERT_LOCK_HELD(&sched_mutex);
2543
2544     debugTrace(DEBUG_sched, "checking threads blocked on black holes");
2545
2546     // ASSUMES: sched_mutex
2547     prev = &blackhole_queue;
2548     t = blackhole_queue;
2549     while (t != END_TSO_QUEUE) {
2550         if (t->what_next == ThreadRelocated) {
2551             t = t->_link;
2552             continue;
2553         }
2554         ASSERT(t->why_blocked == BlockedOnBlackHole);
2555         type = get_itbl(UNTAG_CLOSURE(t->block_info.closure))->type;
2556         if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
2557             IF_DEBUG(sanity,checkTSO(t));
2558             t = unblockOne(cap, t);
2559             *prev = t;
2560             any_woke_up = rtsTrue;
2561         } else {
2562             prev = &t->_link;
2563             t = t->_link;
2564         }
2565     }
2566
2567     return any_woke_up;
2568 }
2569
2570 /* -----------------------------------------------------------------------------
2571    Deleting threads
2572
2573    This is used for interruption (^C) and forking, and corresponds to
2574    raising an exception but without letting the thread catch the
2575    exception.
2576    -------------------------------------------------------------------------- */
2577
2578 static void 
2579 deleteThread (Capability *cap, StgTSO *tso)
2580 {
2581     // NOTE: must only be called on a TSO that we have exclusive
2582     // access to, because we will call throwToSingleThreaded() below.
2583     // The TSO must be on the run queue of the Capability we own, or 
2584     // we must own all Capabilities.
2585
2586     if (tso->why_blocked != BlockedOnCCall &&
2587         tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2588         throwToSingleThreaded(cap,tso,NULL);
2589     }
2590 }
2591
2592 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2593 static void 
2594 deleteThread_(Capability *cap, StgTSO *tso)
2595 { // for forkProcess only:
2596   // like deleteThread(), but we delete threads in foreign calls, too.
2597
2598     if (tso->why_blocked == BlockedOnCCall ||
2599         tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2600         unblockOne(cap,tso);
2601         tso->what_next = ThreadKilled;
2602     } else {
2603         deleteThread(cap,tso);
2604     }
2605 }
2606 #endif
2607
2608 /* -----------------------------------------------------------------------------
2609    raiseExceptionHelper
2610    
2611    This function is called by the raise# primitve, just so that we can
2612    move some of the tricky bits of raising an exception from C-- into
2613    C.  Who knows, it might be a useful re-useable thing here too.
2614    -------------------------------------------------------------------------- */
2615
2616 StgWord
2617 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2618 {
2619     Capability *cap = regTableToCapability(reg);
2620     StgThunk *raise_closure = NULL;
2621     StgPtr p, next;
2622     StgRetInfoTable *info;
2623     //
2624     // This closure represents the expression 'raise# E' where E
2625     // is the exception raise.  It is used to overwrite all the
2626     // thunks which are currently under evaluataion.
2627     //
2628
2629     // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2630     // LDV profiling: stg_raise_info has THUNK as its closure
2631     // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2632     // payload, MIN_UPD_SIZE is more approprate than 1.  It seems that
2633     // 1 does not cause any problem unless profiling is performed.
2634     // However, when LDV profiling goes on, we need to linearly scan
2635     // small object pool, where raise_closure is stored, so we should
2636     // use MIN_UPD_SIZE.
2637     //
2638     // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2639     //                                 sizeofW(StgClosure)+1);
2640     //
2641
2642     //
2643     // Walk up the stack, looking for the catch frame.  On the way,
2644     // we update any closures pointed to from update frames with the
2645     // raise closure that we just built.
2646     //
2647     p = tso->sp;
2648     while(1) {
2649         info = get_ret_itbl((StgClosure *)p);
2650         next = p + stack_frame_sizeW((StgClosure *)p);
2651         switch (info->i.type) {
2652             
2653         case UPDATE_FRAME:
2654             // Only create raise_closure if we need to.
2655             if (raise_closure == NULL) {
2656                 raise_closure = 
2657                     (StgThunk *)allocateLocal(cap,sizeofW(StgThunk)+1);
2658                 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2659                 raise_closure->payload[0] = exception;
2660             }
2661             UPD_IND(((StgUpdateFrame *)p)->updatee,(StgClosure *)raise_closure);
2662             p = next;
2663             continue;
2664
2665         case ATOMICALLY_FRAME:
2666             debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2667             tso->sp = p;
2668             return ATOMICALLY_FRAME;
2669             
2670         case CATCH_FRAME:
2671             tso->sp = p;
2672             return CATCH_FRAME;
2673
2674         case CATCH_STM_FRAME:
2675             debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2676             tso->sp = p;
2677             return CATCH_STM_FRAME;
2678             
2679         case STOP_FRAME:
2680             tso->sp = p;
2681             return STOP_FRAME;
2682
2683         case CATCH_RETRY_FRAME:
2684         default:
2685             p = next; 
2686             continue;
2687         }
2688     }
2689 }
2690
2691
2692 /* -----------------------------------------------------------------------------
2693    findRetryFrameHelper
2694
2695    This function is called by the retry# primitive.  It traverses the stack
2696    leaving tso->sp referring to the frame which should handle the retry.  
2697
2698    This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#) 
2699    or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).  
2700
2701    We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2702    create) because retries are not considered to be exceptions, despite the
2703    similar implementation.
2704
2705    We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2706    not be created within memory transactions.
2707    -------------------------------------------------------------------------- */
2708
2709 StgWord
2710 findRetryFrameHelper (StgTSO *tso)
2711 {
2712   StgPtr           p, next;
2713   StgRetInfoTable *info;
2714
2715   p = tso -> sp;
2716   while (1) {
2717     info = get_ret_itbl((StgClosure *)p);
2718     next = p + stack_frame_sizeW((StgClosure *)p);
2719     switch (info->i.type) {
2720       
2721     case ATOMICALLY_FRAME:
2722         debugTrace(DEBUG_stm,
2723                    "found ATOMICALLY_FRAME at %p during retry", p);
2724         tso->sp = p;
2725         return ATOMICALLY_FRAME;
2726       
2727     case CATCH_RETRY_FRAME:
2728         debugTrace(DEBUG_stm,
2729                    "found CATCH_RETRY_FRAME at %p during retrry", p);
2730         tso->sp = p;
2731         return CATCH_RETRY_FRAME;
2732       
2733     case CATCH_STM_FRAME: {
2734         StgTRecHeader *trec = tso -> trec;
2735         StgTRecHeader *outer = stmGetEnclosingTRec(trec);
2736         debugTrace(DEBUG_stm,
2737                    "found CATCH_STM_FRAME at %p during retry", p);
2738         debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2739         stmAbortTransaction(tso -> cap, trec);
2740         stmFreeAbortedTRec(tso -> cap, trec);
2741         tso -> trec = outer;
2742         p = next; 
2743         continue;
2744     }
2745       
2746
2747     default:
2748       ASSERT(info->i.type != CATCH_FRAME);
2749       ASSERT(info->i.type != STOP_FRAME);
2750       p = next; 
2751       continue;
2752     }
2753   }
2754 }
2755
2756 /* -----------------------------------------------------------------------------
2757    resurrectThreads is called after garbage collection on the list of
2758    threads found to be garbage.  Each of these threads will be woken
2759    up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2760    on an MVar, or NonTermination if the thread was blocked on a Black
2761    Hole.
2762
2763    Locks: assumes we hold *all* the capabilities.
2764    -------------------------------------------------------------------------- */
2765
2766 void
2767 resurrectThreads (StgTSO *threads)
2768 {
2769     StgTSO *tso, *next;
2770     Capability *cap;
2771     step *step;
2772
2773     for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2774         next = tso->global_link;
2775
2776         step = Bdescr((P_)tso)->step;
2777         tso->global_link = step->threads;
2778         step->threads = tso;
2779
2780         debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2781         
2782         // Wake up the thread on the Capability it was last on
2783         cap = tso->cap;
2784         
2785         switch (tso->why_blocked) {
2786         case BlockedOnMVar:
2787         case BlockedOnException:
2788             /* Called by GC - sched_mutex lock is currently held. */
2789             throwToSingleThreaded(cap, tso,
2790                                   (StgClosure *)blockedOnDeadMVar_closure);
2791             break;
2792         case BlockedOnBlackHole:
2793             throwToSingleThreaded(cap, tso,
2794                                   (StgClosure *)nonTermination_closure);
2795             break;
2796         case BlockedOnSTM:
2797             throwToSingleThreaded(cap, tso,
2798                                   (StgClosure *)blockedIndefinitely_closure);
2799             break;
2800         case NotBlocked:
2801             /* This might happen if the thread was blocked on a black hole
2802              * belonging to a thread that we've just woken up (raiseAsync
2803              * can wake up threads, remember...).
2804              */
2805             continue;
2806         default:
2807             barf("resurrectThreads: thread blocked in a strange way");
2808         }
2809     }
2810 }
2811
2812 /* -----------------------------------------------------------------------------
2813    performPendingThrowTos is called after garbage collection, and
2814    passed a list of threads that were found to have pending throwTos
2815    (tso->blocked_exceptions was not empty), and were blocked.
2816    Normally this doesn't happen, because we would deliver the
2817    exception directly if the target thread is blocked, but there are
2818    small windows where it might occur on a multiprocessor (see
2819    throwTo()).
2820
2821    NB. we must be holding all the capabilities at this point, just
2822    like resurrectThreads().
2823    -------------------------------------------------------------------------- */
2824
2825 void
2826 performPendingThrowTos (StgTSO *threads)
2827 {
2828     StgTSO *tso, *next;
2829     Capability *cap;
2830     step *step;
2831
2832     for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2833         next = tso->global_link;
2834
2835         step = Bdescr((P_)tso)->step;
2836         tso->global_link = step->threads;
2837         step->threads = tso;
2838
2839         debugTrace(DEBUG_sched, "performing blocked throwTo to thread %lu", (unsigned long)tso->id);
2840         
2841         cap = tso->cap;
2842         maybePerformBlockedException(cap, tso);
2843     }
2844 }