check for ThreadRelocated in checkBlackHoles()
[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                         newSpark(&(free_caps[i]->r), spark);
885                     }
886                 }
887             }
888         }
889 #endif /* SPARK_PUSHING */
890
891         // release the capabilities
892         for (i = 0; i < n_free_caps; i++) {
893             task->cap = free_caps[i];
894             releaseAndWakeupCapability(free_caps[i]);
895         }
896     }
897     task->cap = cap; // reset to point to our Capability.
898
899 #endif /* THREADED_RTS */
900
901 }
902
903 /* ----------------------------------------------------------------------------
904  * Start any pending signal handlers
905  * ------------------------------------------------------------------------- */
906
907 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
908 static void
909 scheduleStartSignalHandlers(Capability *cap)
910 {
911     if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
912         // safe outside the lock
913         startSignalHandlers(cap);
914     }
915 }
916 #else
917 static void
918 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
919 {
920 }
921 #endif
922
923 /* ----------------------------------------------------------------------------
924  * Check for blocked threads that can be woken up.
925  * ------------------------------------------------------------------------- */
926
927 static void
928 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
929 {
930 #if !defined(THREADED_RTS)
931     //
932     // Check whether any waiting threads need to be woken up.  If the
933     // run queue is empty, and there are no other tasks running, we
934     // can wait indefinitely for something to happen.
935     //
936     if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
937     {
938         awaitEvent( emptyRunQueue(cap) && !blackholes_need_checking );
939     }
940 #endif
941 }
942
943
944 /* ----------------------------------------------------------------------------
945  * Check for threads woken up by other Capabilities
946  * ------------------------------------------------------------------------- */
947
948 static void
949 scheduleCheckWakeupThreads(Capability *cap USED_IF_THREADS)
950 {
951 #if defined(THREADED_RTS)
952     // Any threads that were woken up by other Capabilities get
953     // appended to our run queue.
954     if (!emptyWakeupQueue(cap)) {
955         ACQUIRE_LOCK(&cap->lock);
956         if (emptyRunQueue(cap)) {
957             cap->run_queue_hd = cap->wakeup_queue_hd;
958             cap->run_queue_tl = cap->wakeup_queue_tl;
959         } else {
960             setTSOLink(cap, cap->run_queue_tl, cap->wakeup_queue_hd);
961             cap->run_queue_tl = cap->wakeup_queue_tl;
962         }
963         cap->wakeup_queue_hd = cap->wakeup_queue_tl = END_TSO_QUEUE;
964         RELEASE_LOCK(&cap->lock);
965     }
966 #endif
967 }
968
969 /* ----------------------------------------------------------------------------
970  * Check for threads blocked on BLACKHOLEs that can be woken up
971  * ------------------------------------------------------------------------- */
972 static void
973 scheduleCheckBlackHoles (Capability *cap)
974 {
975     if ( blackholes_need_checking ) // check without the lock first
976     {
977         ACQUIRE_LOCK(&sched_mutex);
978         if ( blackholes_need_checking ) {
979             blackholes_need_checking = rtsFalse;
980             // important that we reset the flag *before* checking the
981             // blackhole queue, otherwise we could get deadlock.  This
982             // happens as follows: we wake up a thread that
983             // immediately runs on another Capability, blocks on a
984             // blackhole, and then we reset the blackholes_need_checking flag.
985             checkBlackHoles(cap);
986         }
987         RELEASE_LOCK(&sched_mutex);
988     }
989 }
990
991 /* ----------------------------------------------------------------------------
992  * Detect deadlock conditions and attempt to resolve them.
993  * ------------------------------------------------------------------------- */
994
995 static void
996 scheduleDetectDeadlock (Capability *cap, Task *task)
997 {
998
999 #if defined(PARALLEL_HASKELL)
1000     // ToDo: add deadlock detection in GUM (similar to THREADED_RTS) -- HWL
1001     return;
1002 #endif
1003
1004     /* 
1005      * Detect deadlock: when we have no threads to run, there are no
1006      * threads blocked, waiting for I/O, or sleeping, and all the
1007      * other tasks are waiting for work, we must have a deadlock of
1008      * some description.
1009      */
1010     if ( emptyThreadQueues(cap) )
1011     {
1012 #if defined(THREADED_RTS)
1013         /* 
1014          * In the threaded RTS, we only check for deadlock if there
1015          * has been no activity in a complete timeslice.  This means
1016          * we won't eagerly start a full GC just because we don't have
1017          * any threads to run currently.
1018          */
1019         if (recent_activity != ACTIVITY_INACTIVE) return;
1020 #endif
1021
1022         debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
1023
1024         // Garbage collection can release some new threads due to
1025         // either (a) finalizers or (b) threads resurrected because
1026         // they are unreachable and will therefore be sent an
1027         // exception.  Any threads thus released will be immediately
1028         // runnable.
1029         cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
1030         // when force_major == rtsTrue. scheduleDoGC sets
1031         // recent_activity to ACTIVITY_DONE_GC and turns off the timer
1032         // signal.
1033
1034         if ( !emptyRunQueue(cap) ) return;
1035
1036 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
1037         /* If we have user-installed signal handlers, then wait
1038          * for signals to arrive rather then bombing out with a
1039          * deadlock.
1040          */
1041         if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
1042             debugTrace(DEBUG_sched,
1043                        "still deadlocked, waiting for signals...");
1044
1045             awaitUserSignals();
1046
1047             if (signals_pending()) {
1048                 startSignalHandlers(cap);
1049             }
1050
1051             // either we have threads to run, or we were interrupted:
1052             ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
1053
1054             return;
1055         }
1056 #endif
1057
1058 #if !defined(THREADED_RTS)
1059         /* Probably a real deadlock.  Send the current main thread the
1060          * Deadlock exception.
1061          */
1062         if (task->tso) {
1063             switch (task->tso->why_blocked) {
1064             case BlockedOnSTM:
1065             case BlockedOnBlackHole:
1066             case BlockedOnException:
1067             case BlockedOnMVar:
1068                 throwToSingleThreaded(cap, task->tso, 
1069                                       (StgClosure *)nonTermination_closure);
1070                 return;
1071             default:
1072                 barf("deadlock: main thread blocked in a strange way");
1073             }
1074         }
1075         return;
1076 #endif
1077     }
1078 }
1079
1080
1081 /* ----------------------------------------------------------------------------
1082  * Send pending messages (PARALLEL_HASKELL only)
1083  * ------------------------------------------------------------------------- */
1084
1085 #if defined(PARALLEL_HASKELL)
1086 static void
1087 scheduleSendPendingMessages(void)
1088 {
1089
1090 # if defined(PAR) // global Mem.Mgmt., omit for now
1091     if (PendingFetches != END_BF_QUEUE) {
1092         processFetches();
1093     }
1094 # endif
1095     
1096     if (RtsFlags.ParFlags.BufferTime) {
1097         // if we use message buffering, we must send away all message
1098         // packets which have become too old...
1099         sendOldBuffers(); 
1100     }
1101 }
1102 #endif
1103
1104 /* ----------------------------------------------------------------------------
1105  * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
1106  * ------------------------------------------------------------------------- */
1107
1108 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
1109 static void
1110 scheduleActivateSpark(Capability *cap)
1111 {
1112     if (anySparks())
1113     {
1114         createSparkThread(cap);
1115         debugTrace(DEBUG_sched, "creating a spark thread");
1116     }
1117 }
1118 #endif // PARALLEL_HASKELL || THREADED_RTS
1119
1120 /* ----------------------------------------------------------------------------
1121  * Get work from a remote node (PARALLEL_HASKELL only)
1122  * ------------------------------------------------------------------------- */
1123     
1124 #if defined(PARALLEL_HASKELL)
1125 static rtsBool /* return value used in PARALLEL_HASKELL only */
1126 scheduleGetRemoteWork (Capability *cap STG_UNUSED)
1127 {
1128 #if defined(PARALLEL_HASKELL)
1129   rtsBool receivedFinish = rtsFalse;
1130
1131   // idle() , i.e. send all buffers, wait for work
1132   if (RtsFlags.ParFlags.BufferTime) {
1133         IF_PAR_DEBUG(verbose, 
1134                 debugBelch("...send all pending data,"));
1135         {
1136           nat i;
1137           for (i=1; i<=nPEs; i++)
1138             sendImmediately(i); // send all messages away immediately
1139         }
1140   }
1141
1142   /* this would be the place for fishing in GUM... 
1143
1144      if (no-earlier-fish-around) 
1145           sendFish(choosePe());
1146    */
1147
1148   // Eden:just look for incoming messages (blocking receive)
1149   IF_PAR_DEBUG(verbose, 
1150                debugBelch("...wait for incoming messages...\n"));
1151   processMessages(cap, &receivedFinish); // blocking receive...
1152
1153
1154   return receivedFinish;
1155   // reenter scheduling look after having received something
1156
1157 #else /* !PARALLEL_HASKELL, i.e. THREADED_RTS */
1158
1159   return rtsFalse; /* return value unused in THREADED_RTS */
1160
1161 #endif /* PARALLEL_HASKELL */
1162 }
1163 #endif // PARALLEL_HASKELL || THREADED_RTS
1164
1165 /* ----------------------------------------------------------------------------
1166  * After running a thread...
1167  * ------------------------------------------------------------------------- */
1168
1169 static void
1170 schedulePostRunThread (Capability *cap, StgTSO *t)
1171 {
1172     // We have to be able to catch transactions that are in an
1173     // infinite loop as a result of seeing an inconsistent view of
1174     // memory, e.g. 
1175     //
1176     //   atomically $ do
1177     //       [a,b] <- mapM readTVar [ta,tb]
1178     //       when (a == b) loop
1179     //
1180     // and a is never equal to b given a consistent view of memory.
1181     //
1182     if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1183         if (!stmValidateNestOfTransactions (t -> trec)) {
1184             debugTrace(DEBUG_sched | DEBUG_stm,
1185                        "trec %p found wasting its time", t);
1186             
1187             // strip the stack back to the
1188             // ATOMICALLY_FRAME, aborting the (nested)
1189             // transaction, and saving the stack of any
1190             // partially-evaluated thunks on the heap.
1191             throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1192             
1193             ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1194         }
1195     }
1196
1197   /* some statistics gathering in the parallel case */
1198 }
1199
1200 /* -----------------------------------------------------------------------------
1201  * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1202  * -------------------------------------------------------------------------- */
1203
1204 static rtsBool
1205 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1206 {
1207     // did the task ask for a large block?
1208     if (cap->r.rHpAlloc > BLOCK_SIZE) {
1209         // if so, get one and push it on the front of the nursery.
1210         bdescr *bd;
1211         lnat blocks;
1212         
1213         blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1214         
1215         debugTrace(DEBUG_sched,
1216                    "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n", 
1217                    (long)t->id, whatNext_strs[t->what_next], blocks);
1218     
1219         // don't do this if the nursery is (nearly) full, we'll GC first.
1220         if (cap->r.rCurrentNursery->link != NULL ||
1221             cap->r.rNursery->n_blocks == 1) {  // paranoia to prevent infinite loop
1222                                                // if the nursery has only one block.
1223             
1224             ACQUIRE_SM_LOCK
1225             bd = allocGroup( blocks );
1226             RELEASE_SM_LOCK
1227             cap->r.rNursery->n_blocks += blocks;
1228             
1229             // link the new group into the list
1230             bd->link = cap->r.rCurrentNursery;
1231             bd->u.back = cap->r.rCurrentNursery->u.back;
1232             if (cap->r.rCurrentNursery->u.back != NULL) {
1233                 cap->r.rCurrentNursery->u.back->link = bd;
1234             } else {
1235 #if !defined(THREADED_RTS)
1236                 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1237                        g0s0 == cap->r.rNursery);
1238 #endif
1239                 cap->r.rNursery->blocks = bd;
1240             }             
1241             cap->r.rCurrentNursery->u.back = bd;
1242             
1243             // initialise it as a nursery block.  We initialise the
1244             // step, gen_no, and flags field of *every* sub-block in
1245             // this large block, because this is easier than making
1246             // sure that we always find the block head of a large
1247             // block whenever we call Bdescr() (eg. evacuate() and
1248             // isAlive() in the GC would both have to do this, at
1249             // least).
1250             { 
1251                 bdescr *x;
1252                 for (x = bd; x < bd + blocks; x++) {
1253                     x->step = cap->r.rNursery;
1254                     x->gen_no = 0;
1255                     x->flags = 0;
1256                 }
1257             }
1258             
1259             // This assert can be a killer if the app is doing lots
1260             // of large block allocations.
1261             IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1262             
1263             // now update the nursery to point to the new block
1264             cap->r.rCurrentNursery = bd;
1265             
1266             // we might be unlucky and have another thread get on the
1267             // run queue before us and steal the large block, but in that
1268             // case the thread will just end up requesting another large
1269             // block.
1270             pushOnRunQueue(cap,t);
1271             return rtsFalse;  /* not actually GC'ing */
1272         }
1273     }
1274     
1275     debugTrace(DEBUG_sched,
1276                "--<< thread %ld (%s) stopped: HeapOverflow",
1277                (long)t->id, whatNext_strs[t->what_next]);
1278
1279     if (cap->r.rHpLim == NULL || cap->context_switch) {
1280         // Sometimes we miss a context switch, e.g. when calling
1281         // primitives in a tight loop, MAYBE_GC() doesn't check the
1282         // context switch flag, and we end up waiting for a GC.
1283         // See #1984, and concurrent/should_run/1984
1284         cap->context_switch = 0;
1285         addToRunQueue(cap,t);
1286     } else {
1287         pushOnRunQueue(cap,t);
1288     }
1289     return rtsTrue;
1290     /* actual GC is done at the end of the while loop in schedule() */
1291 }
1292
1293 /* -----------------------------------------------------------------------------
1294  * Handle a thread that returned to the scheduler with ThreadStackOverflow
1295  * -------------------------------------------------------------------------- */
1296
1297 static void
1298 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1299 {
1300     debugTrace (DEBUG_sched,
1301                 "--<< thread %ld (%s) stopped, StackOverflow", 
1302                 (long)t->id, whatNext_strs[t->what_next]);
1303
1304     /* just adjust the stack for this thread, then pop it back
1305      * on the run queue.
1306      */
1307     { 
1308         /* enlarge the stack */
1309         StgTSO *new_t = threadStackOverflow(cap, t);
1310         
1311         /* The TSO attached to this Task may have moved, so update the
1312          * pointer to it.
1313          */
1314         if (task->tso == t) {
1315             task->tso = new_t;
1316         }
1317         pushOnRunQueue(cap,new_t);
1318     }
1319 }
1320
1321 /* -----------------------------------------------------------------------------
1322  * Handle a thread that returned to the scheduler with ThreadYielding
1323  * -------------------------------------------------------------------------- */
1324
1325 static rtsBool
1326 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1327 {
1328     // Reset the context switch flag.  We don't do this just before
1329     // running the thread, because that would mean we would lose ticks
1330     // during GC, which can lead to unfair scheduling (a thread hogs
1331     // the CPU because the tick always arrives during GC).  This way
1332     // penalises threads that do a lot of allocation, but that seems
1333     // better than the alternative.
1334     cap->context_switch = 0;
1335     
1336     /* put the thread back on the run queue.  Then, if we're ready to
1337      * GC, check whether this is the last task to stop.  If so, wake
1338      * up the GC thread.  getThread will block during a GC until the
1339      * GC is finished.
1340      */
1341 #ifdef DEBUG
1342     if (t->what_next != prev_what_next) {
1343         debugTrace(DEBUG_sched,
1344                    "--<< thread %ld (%s) stopped to switch evaluators", 
1345                    (long)t->id, whatNext_strs[t->what_next]);
1346     } else {
1347         debugTrace(DEBUG_sched,
1348                    "--<< thread %ld (%s) stopped, yielding",
1349                    (long)t->id, whatNext_strs[t->what_next]);
1350     }
1351 #endif
1352     
1353     IF_DEBUG(sanity,
1354              //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1355              checkTSO(t));
1356     ASSERT(t->_link == END_TSO_QUEUE);
1357     
1358     // Shortcut if we're just switching evaluators: don't bother
1359     // doing stack squeezing (which can be expensive), just run the
1360     // thread.
1361     if (t->what_next != prev_what_next) {
1362         return rtsTrue;
1363     }
1364
1365     addToRunQueue(cap,t);
1366
1367     return rtsFalse;
1368 }
1369
1370 /* -----------------------------------------------------------------------------
1371  * Handle a thread that returned to the scheduler with ThreadBlocked
1372  * -------------------------------------------------------------------------- */
1373
1374 static void
1375 scheduleHandleThreadBlocked( StgTSO *t
1376 #if !defined(GRAN) && !defined(DEBUG)
1377     STG_UNUSED
1378 #endif
1379     )
1380 {
1381
1382       // We don't need to do anything.  The thread is blocked, and it
1383       // has tidied up its stack and placed itself on whatever queue
1384       // it needs to be on.
1385
1386     // ASSERT(t->why_blocked != NotBlocked);
1387     // Not true: for example,
1388     //    - in THREADED_RTS, the thread may already have been woken
1389     //      up by another Capability.  This actually happens: try
1390     //      conc023 +RTS -N2.
1391     //    - the thread may have woken itself up already, because
1392     //      threadPaused() might have raised a blocked throwTo
1393     //      exception, see maybePerformBlockedException().
1394
1395 #ifdef DEBUG
1396     if (traceClass(DEBUG_sched)) {
1397         debugTraceBegin("--<< thread %lu (%s) stopped: ", 
1398                         (unsigned long)t->id, whatNext_strs[t->what_next]);
1399         printThreadBlockage(t);
1400         debugTraceEnd();
1401     }
1402 #endif
1403 }
1404
1405 /* -----------------------------------------------------------------------------
1406  * Handle a thread that returned to the scheduler with ThreadFinished
1407  * -------------------------------------------------------------------------- */
1408
1409 static rtsBool
1410 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1411 {
1412     /* Need to check whether this was a main thread, and if so,
1413      * return with the return value.
1414      *
1415      * We also end up here if the thread kills itself with an
1416      * uncaught exception, see Exception.cmm.
1417      */
1418     debugTrace(DEBUG_sched, "--++ thread %lu (%s) finished", 
1419                (unsigned long)t->id, whatNext_strs[t->what_next]);
1420
1421     // blocked exceptions can now complete, even if the thread was in
1422     // blocked mode (see #2910).  This unconditionally calls
1423     // lockTSO(), which ensures that we don't miss any threads that
1424     // are engaged in throwTo() with this thread as a target.
1425     awakenBlockedExceptionQueue (cap, t);
1426
1427       //
1428       // Check whether the thread that just completed was a bound
1429       // thread, and if so return with the result.  
1430       //
1431       // There is an assumption here that all thread completion goes
1432       // through this point; we need to make sure that if a thread
1433       // ends up in the ThreadKilled state, that it stays on the run
1434       // queue so it can be dealt with here.
1435       //
1436
1437       if (t->bound) {
1438
1439           if (t->bound != task) {
1440 #if !defined(THREADED_RTS)
1441               // Must be a bound thread that is not the topmost one.  Leave
1442               // it on the run queue until the stack has unwound to the
1443               // point where we can deal with this.  Leaving it on the run
1444               // queue also ensures that the garbage collector knows about
1445               // this thread and its return value (it gets dropped from the
1446               // step->threads list so there's no other way to find it).
1447               appendToRunQueue(cap,t);
1448               return rtsFalse;
1449 #else
1450               // this cannot happen in the threaded RTS, because a
1451               // bound thread can only be run by the appropriate Task.
1452               barf("finished bound thread that isn't mine");
1453 #endif
1454           }
1455
1456           ASSERT(task->tso == t);
1457
1458           if (t->what_next == ThreadComplete) {
1459               if (task->ret) {
1460                   // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1461                   *(task->ret) = (StgClosure *)task->tso->sp[1]; 
1462               }
1463               task->stat = Success;
1464           } else {
1465               if (task->ret) {
1466                   *(task->ret) = NULL;
1467               }
1468               if (sched_state >= SCHED_INTERRUPTING) {
1469                   if (heap_overflow) {
1470                       task->stat = HeapExhausted;
1471                   } else {
1472                       task->stat = Interrupted;
1473                   }
1474               } else {
1475                   task->stat = Killed;
1476               }
1477           }
1478 #ifdef DEBUG
1479           removeThreadLabel((StgWord)task->tso->id);
1480 #endif
1481           return rtsTrue; // tells schedule() to return
1482       }
1483
1484       return rtsFalse;
1485 }
1486
1487 /* -----------------------------------------------------------------------------
1488  * Perform a heap census
1489  * -------------------------------------------------------------------------- */
1490
1491 static rtsBool
1492 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1493 {
1494     // When we have +RTS -i0 and we're heap profiling, do a census at
1495     // every GC.  This lets us get repeatable runs for debugging.
1496     if (performHeapProfile ||
1497         (RtsFlags.ProfFlags.profileInterval==0 &&
1498          RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1499         return rtsTrue;
1500     } else {
1501         return rtsFalse;
1502     }
1503 }
1504
1505 /* -----------------------------------------------------------------------------
1506  * Perform a garbage collection if necessary
1507  * -------------------------------------------------------------------------- */
1508
1509 static Capability *
1510 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1511 {
1512     rtsBool heap_census;
1513 #ifdef THREADED_RTS
1514     /* extern static volatile StgWord waiting_for_gc; 
1515        lives inside capability.c */
1516     rtsBool gc_type, prev_pending_gc;
1517     nat i;
1518 #endif
1519
1520     if (sched_state == SCHED_SHUTTING_DOWN) {
1521         // The final GC has already been done, and the system is
1522         // shutting down.  We'll probably deadlock if we try to GC
1523         // now.
1524         return cap;
1525     }
1526
1527 #ifdef THREADED_RTS
1528     if (sched_state < SCHED_INTERRUPTING
1529         && RtsFlags.ParFlags.parGcEnabled
1530         && N >= RtsFlags.ParFlags.parGcGen
1531         && ! oldest_gen->steps[0].mark)
1532     {
1533         gc_type = PENDING_GC_PAR;
1534     } else {
1535         gc_type = PENDING_GC_SEQ;
1536     }
1537
1538     // In order to GC, there must be no threads running Haskell code.
1539     // Therefore, the GC thread needs to hold *all* the capabilities,
1540     // and release them after the GC has completed.  
1541     //
1542     // This seems to be the simplest way: previous attempts involved
1543     // making all the threads with capabilities give up their
1544     // capabilities and sleep except for the *last* one, which
1545     // actually did the GC.  But it's quite hard to arrange for all
1546     // the other tasks to sleep and stay asleep.
1547     //
1548
1549     /*  Other capabilities are prevented from running yet more Haskell
1550         threads if waiting_for_gc is set. Tested inside
1551         yieldCapability() and releaseCapability() in Capability.c */
1552
1553     prev_pending_gc = cas(&waiting_for_gc, 0, gc_type);
1554     if (prev_pending_gc) {
1555         do {
1556             debugTrace(DEBUG_sched, "someone else is trying to GC (%d)...", 
1557                        prev_pending_gc);
1558             ASSERT(cap);
1559             yieldCapability(&cap,task);
1560         } while (waiting_for_gc);
1561         return cap;  // NOTE: task->cap might have changed here
1562     }
1563
1564     setContextSwitches();
1565
1566     // The final shutdown GC is always single-threaded, because it's
1567     // possible that some of the Capabilities have no worker threads.
1568     
1569     if (gc_type == PENDING_GC_SEQ)
1570     {
1571         postEvent(cap, EVENT_REQUEST_SEQ_GC, 0, 0);
1572         // single-threaded GC: grab all the capabilities
1573         for (i=0; i < n_capabilities; i++) {
1574             debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1575             if (cap != &capabilities[i]) {
1576                 Capability *pcap = &capabilities[i];
1577                 // we better hope this task doesn't get migrated to
1578                 // another Capability while we're waiting for this one.
1579                 // It won't, because load balancing happens while we have
1580                 // all the Capabilities, but even so it's a slightly
1581                 // unsavoury invariant.
1582                 task->cap = pcap;
1583                 waitForReturnCapability(&pcap, task);
1584                 if (pcap != &capabilities[i]) {
1585                     barf("scheduleDoGC: got the wrong capability");
1586                 }
1587             }
1588         }
1589     }
1590     else
1591     {
1592         // multi-threaded GC: make sure all the Capabilities donate one
1593         // GC thread each.
1594         postEvent(cap, EVENT_REQUEST_PAR_GC, 0, 0);
1595         debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1596
1597         waitForGcThreads(cap);
1598     }
1599 #endif
1600
1601     // so this happens periodically:
1602     if (cap) scheduleCheckBlackHoles(cap);
1603     
1604     IF_DEBUG(scheduler, printAllThreads());
1605
1606 delete_threads_and_gc:
1607     /*
1608      * We now have all the capabilities; if we're in an interrupting
1609      * state, then we should take the opportunity to delete all the
1610      * threads in the system.
1611      */
1612     if (sched_state == SCHED_INTERRUPTING) {
1613         deleteAllThreads(cap);
1614         sched_state = SCHED_SHUTTING_DOWN;
1615     }
1616     
1617     heap_census = scheduleNeedHeapProfile(rtsTrue);
1618
1619 #if defined(THREADED_RTS)
1620     postEvent(cap, EVENT_GC_START, 0, 0);
1621     debugTrace(DEBUG_sched, "doing GC");
1622     // reset waiting_for_gc *before* GC, so that when the GC threads
1623     // emerge they don't immediately re-enter the GC.
1624     waiting_for_gc = 0;
1625     GarbageCollect(force_major || heap_census, gc_type, cap);
1626 #else
1627     GarbageCollect(force_major || heap_census, 0, cap);
1628 #endif
1629     postEvent(cap, EVENT_GC_END, 0, 0);
1630
1631     if (recent_activity == ACTIVITY_INACTIVE && force_major)
1632     {
1633         // We are doing a GC because the system has been idle for a
1634         // timeslice and we need to check for deadlock.  Record the
1635         // fact that we've done a GC and turn off the timer signal;
1636         // it will get re-enabled if we run any threads after the GC.
1637         recent_activity = ACTIVITY_DONE_GC;
1638         stopTimer();
1639     }
1640     else
1641     {
1642         // the GC might have taken long enough for the timer to set
1643         // recent_activity = ACTIVITY_INACTIVE, but we aren't
1644         // necessarily deadlocked:
1645         recent_activity = ACTIVITY_YES;
1646     }
1647
1648 #if defined(THREADED_RTS)
1649     if (gc_type == PENDING_GC_PAR)
1650     {
1651         releaseGCThreads(cap);
1652     }
1653 #endif
1654
1655     if (heap_census) {
1656         debugTrace(DEBUG_sched, "performing heap census");
1657         heapCensus();
1658         performHeapProfile = rtsFalse;
1659     }
1660
1661     if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1662         // GC set the heap_overflow flag, so we should proceed with
1663         // an orderly shutdown now.  Ultimately we want the main
1664         // thread to return to its caller with HeapExhausted, at which
1665         // point the caller should call hs_exit().  The first step is
1666         // to delete all the threads.
1667         //
1668         // Another way to do this would be to raise an exception in
1669         // the main thread, which we really should do because it gives
1670         // the program a chance to clean up.  But how do we find the
1671         // main thread?  It should presumably be the same one that
1672         // gets ^C exceptions, but that's all done on the Haskell side
1673         // (GHC.TopHandler).
1674         sched_state = SCHED_INTERRUPTING;
1675         goto delete_threads_and_gc;
1676     }
1677
1678 #ifdef SPARKBALANCE
1679     /* JB 
1680        Once we are all together... this would be the place to balance all
1681        spark pools. No concurrent stealing or adding of new sparks can
1682        occur. Should be defined in Sparks.c. */
1683     balanceSparkPoolsCaps(n_capabilities, capabilities);
1684 #endif
1685
1686 #if defined(THREADED_RTS)
1687     if (gc_type == PENDING_GC_SEQ) {
1688         // release our stash of capabilities.
1689         for (i = 0; i < n_capabilities; i++) {
1690             if (cap != &capabilities[i]) {
1691                 task->cap = &capabilities[i];
1692                 releaseCapability(&capabilities[i]);
1693             }
1694         }
1695     }
1696     if (cap) {
1697         task->cap = cap;
1698     } else {
1699         task->cap = NULL;
1700     }
1701 #endif
1702
1703     return cap;
1704 }
1705
1706 /* ---------------------------------------------------------------------------
1707  * Singleton fork(). Do not copy any running threads.
1708  * ------------------------------------------------------------------------- */
1709
1710 pid_t
1711 forkProcess(HsStablePtr *entry
1712 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1713             STG_UNUSED
1714 #endif
1715            )
1716 {
1717 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1718     Task *task;
1719     pid_t pid;
1720     StgTSO* t,*next;
1721     Capability *cap;
1722     nat s;
1723     
1724 #if defined(THREADED_RTS)
1725     if (RtsFlags.ParFlags.nNodes > 1) {
1726         errorBelch("forking not supported with +RTS -N<n> greater than 1");
1727         stg_exit(EXIT_FAILURE);
1728     }
1729 #endif
1730
1731     debugTrace(DEBUG_sched, "forking!");
1732     
1733     // ToDo: for SMP, we should probably acquire *all* the capabilities
1734     cap = rts_lock();
1735     
1736     // no funny business: hold locks while we fork, otherwise if some
1737     // other thread is holding a lock when the fork happens, the data
1738     // structure protected by the lock will forever be in an
1739     // inconsistent state in the child.  See also #1391.
1740     ACQUIRE_LOCK(&sched_mutex);
1741     ACQUIRE_LOCK(&cap->lock);
1742     ACQUIRE_LOCK(&cap->running_task->lock);
1743
1744     pid = fork();
1745     
1746     if (pid) { // parent
1747         
1748         RELEASE_LOCK(&sched_mutex);
1749         RELEASE_LOCK(&cap->lock);
1750         RELEASE_LOCK(&cap->running_task->lock);
1751
1752         // just return the pid
1753         rts_unlock(cap);
1754         return pid;
1755         
1756     } else { // child
1757         
1758 #if defined(THREADED_RTS)
1759         initMutex(&sched_mutex);
1760         initMutex(&cap->lock);
1761         initMutex(&cap->running_task->lock);
1762 #endif
1763
1764         // Now, all OS threads except the thread that forked are
1765         // stopped.  We need to stop all Haskell threads, including
1766         // those involved in foreign calls.  Also we need to delete
1767         // all Tasks, because they correspond to OS threads that are
1768         // now gone.
1769
1770         for (s = 0; s < total_steps; s++) {
1771           for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1772             if (t->what_next == ThreadRelocated) {
1773                 next = t->_link;
1774             } else {
1775                 next = t->global_link;
1776                 // don't allow threads to catch the ThreadKilled
1777                 // exception, but we do want to raiseAsync() because these
1778                 // threads may be evaluating thunks that we need later.
1779                 deleteThread_(cap,t);
1780             }
1781           }
1782         }
1783         
1784         // Empty the run queue.  It seems tempting to let all the
1785         // killed threads stay on the run queue as zombies to be
1786         // cleaned up later, but some of them correspond to bound
1787         // threads for which the corresponding Task does not exist.
1788         cap->run_queue_hd = END_TSO_QUEUE;
1789         cap->run_queue_tl = END_TSO_QUEUE;
1790
1791         // Any suspended C-calling Tasks are no more, their OS threads
1792         // don't exist now:
1793         cap->suspended_ccalling_tasks = NULL;
1794
1795         // Empty the threads lists.  Otherwise, the garbage
1796         // collector may attempt to resurrect some of these threads.
1797         for (s = 0; s < total_steps; s++) {
1798             all_steps[s].threads = END_TSO_QUEUE;
1799         }
1800
1801         // Wipe the task list, except the current Task.
1802         ACQUIRE_LOCK(&sched_mutex);
1803         for (task = all_tasks; task != NULL; task=task->all_link) {
1804             if (task != cap->running_task) {
1805 #if defined(THREADED_RTS)
1806                 initMutex(&task->lock); // see #1391
1807 #endif
1808                 discardTask(task);
1809             }
1810         }
1811         RELEASE_LOCK(&sched_mutex);
1812
1813 #if defined(THREADED_RTS)
1814         // Wipe our spare workers list, they no longer exist.  New
1815         // workers will be created if necessary.
1816         cap->spare_workers = NULL;
1817         cap->returning_tasks_hd = NULL;
1818         cap->returning_tasks_tl = NULL;
1819 #endif
1820
1821         // On Unix, all timers are reset in the child, so we need to start
1822         // the timer again.
1823         initTimer();
1824         startTimer();
1825
1826         cap = rts_evalStableIO(cap, entry, NULL);  // run the action
1827         rts_checkSchedStatus("forkProcess",cap);
1828         
1829         rts_unlock(cap);
1830         hs_exit();                      // clean up and exit
1831         stg_exit(EXIT_SUCCESS);
1832     }
1833 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1834     barf("forkProcess#: primop not supported on this platform, sorry!\n");
1835     return -1;
1836 #endif
1837 }
1838
1839 /* ---------------------------------------------------------------------------
1840  * Delete all the threads in the system
1841  * ------------------------------------------------------------------------- */
1842    
1843 static void
1844 deleteAllThreads ( Capability *cap )
1845 {
1846     // NOTE: only safe to call if we own all capabilities.
1847
1848     StgTSO* t, *next;
1849     nat s;
1850
1851     debugTrace(DEBUG_sched,"deleting all threads");
1852     for (s = 0; s < total_steps; s++) {
1853       for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1854         if (t->what_next == ThreadRelocated) {
1855             next = t->_link;
1856         } else {
1857             next = t->global_link;
1858             deleteThread(cap,t);
1859         }
1860       }
1861     }      
1862
1863     // The run queue now contains a bunch of ThreadKilled threads.  We
1864     // must not throw these away: the main thread(s) will be in there
1865     // somewhere, and the main scheduler loop has to deal with it.
1866     // Also, the run queue is the only thing keeping these threads from
1867     // being GC'd, and we don't want the "main thread has been GC'd" panic.
1868
1869 #if !defined(THREADED_RTS)
1870     ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1871     ASSERT(sleeping_queue == END_TSO_QUEUE);
1872 #endif
1873 }
1874
1875 /* -----------------------------------------------------------------------------
1876    Managing the suspended_ccalling_tasks list.
1877    Locks required: sched_mutex
1878    -------------------------------------------------------------------------- */
1879
1880 STATIC_INLINE void
1881 suspendTask (Capability *cap, Task *task)
1882 {
1883     ASSERT(task->next == NULL && task->prev == NULL);
1884     task->next = cap->suspended_ccalling_tasks;
1885     task->prev = NULL;
1886     if (cap->suspended_ccalling_tasks) {
1887         cap->suspended_ccalling_tasks->prev = task;
1888     }
1889     cap->suspended_ccalling_tasks = task;
1890 }
1891
1892 STATIC_INLINE void
1893 recoverSuspendedTask (Capability *cap, Task *task)
1894 {
1895     if (task->prev) {
1896         task->prev->next = task->next;
1897     } else {
1898         ASSERT(cap->suspended_ccalling_tasks == task);
1899         cap->suspended_ccalling_tasks = task->next;
1900     }
1901     if (task->next) {
1902         task->next->prev = task->prev;
1903     }
1904     task->next = task->prev = NULL;
1905 }
1906
1907 /* ---------------------------------------------------------------------------
1908  * Suspending & resuming Haskell threads.
1909  * 
1910  * When making a "safe" call to C (aka _ccall_GC), the task gives back
1911  * its capability before calling the C function.  This allows another
1912  * task to pick up the capability and carry on running Haskell
1913  * threads.  It also means that if the C call blocks, it won't lock
1914  * the whole system.
1915  *
1916  * The Haskell thread making the C call is put to sleep for the
1917  * duration of the call, on the susepended_ccalling_threads queue.  We
1918  * give out a token to the task, which it can use to resume the thread
1919  * on return from the C function.
1920  * ------------------------------------------------------------------------- */
1921    
1922 void *
1923 suspendThread (StgRegTable *reg)
1924 {
1925   Capability *cap;
1926   int saved_errno;
1927   StgTSO *tso;
1928   Task *task;
1929 #if mingw32_HOST_OS
1930   StgWord32 saved_winerror;
1931 #endif
1932
1933   saved_errno = errno;
1934 #if mingw32_HOST_OS
1935   saved_winerror = GetLastError();
1936 #endif
1937
1938   /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1939    */
1940   cap = regTableToCapability(reg);
1941
1942   task = cap->running_task;
1943   tso = cap->r.rCurrentTSO;
1944
1945   postEvent(cap, EVENT_STOP_THREAD, tso->id, THREAD_SUSPENDED_FOREIGN_CALL);
1946   debugTrace(DEBUG_sched, 
1947              "thread %lu did a safe foreign call", 
1948              (unsigned long)cap->r.rCurrentTSO->id);
1949
1950   // XXX this might not be necessary --SDM
1951   tso->what_next = ThreadRunGHC;
1952
1953   threadPaused(cap,tso);
1954
1955   if ((tso->flags & TSO_BLOCKEX) == 0)  {
1956       tso->why_blocked = BlockedOnCCall;
1957       tso->flags |= TSO_BLOCKEX;
1958       tso->flags &= ~TSO_INTERRUPTIBLE;
1959   } else {
1960       tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1961   }
1962
1963   // Hand back capability
1964   task->suspended_tso = tso;
1965
1966   ACQUIRE_LOCK(&cap->lock);
1967
1968   suspendTask(cap,task);
1969   cap->in_haskell = rtsFalse;
1970   releaseCapability_(cap,rtsFalse);
1971   
1972   RELEASE_LOCK(&cap->lock);
1973
1974 #if defined(THREADED_RTS)
1975   /* Preparing to leave the RTS, so ensure there's a native thread/task
1976      waiting to take over.
1977   */
1978   debugTrace(DEBUG_sched, "thread %lu: leaving RTS", (unsigned long)tso->id);
1979 #endif
1980
1981   errno = saved_errno;
1982 #if mingw32_HOST_OS
1983   SetLastError(saved_winerror);
1984 #endif
1985   return task;
1986 }
1987
1988 StgRegTable *
1989 resumeThread (void *task_)
1990 {
1991     StgTSO *tso;
1992     Capability *cap;
1993     Task *task = task_;
1994     int saved_errno;
1995 #if mingw32_HOST_OS
1996     StgWord32 saved_winerror;
1997 #endif
1998
1999     saved_errno = errno;
2000 #if mingw32_HOST_OS
2001     saved_winerror = GetLastError();
2002 #endif
2003
2004     cap = task->cap;
2005     // Wait for permission to re-enter the RTS with the result.
2006     waitForReturnCapability(&cap,task);
2007     // we might be on a different capability now... but if so, our
2008     // entry on the suspended_ccalling_tasks list will also have been
2009     // migrated.
2010
2011     // Remove the thread from the suspended list
2012     recoverSuspendedTask(cap,task);
2013
2014     tso = task->suspended_tso;
2015     task->suspended_tso = NULL;
2016     tso->_link = END_TSO_QUEUE; // no write barrier reqd
2017
2018     postEvent(cap, EVENT_RUN_THREAD, tso->id, 0);
2019     debugTrace(DEBUG_sched, "thread %lu: re-entering RTS", (unsigned long)tso->id);
2020     
2021     if (tso->why_blocked == BlockedOnCCall) {
2022         // avoid locking the TSO if we don't have to
2023         if (tso->blocked_exceptions != END_TSO_QUEUE) {
2024             awakenBlockedExceptionQueue(cap,tso);
2025         }
2026         tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
2027     }
2028     
2029     /* Reset blocking status */
2030     tso->why_blocked  = NotBlocked;
2031     
2032     cap->r.rCurrentTSO = tso;
2033     cap->in_haskell = rtsTrue;
2034     errno = saved_errno;
2035 #if mingw32_HOST_OS
2036     SetLastError(saved_winerror);
2037 #endif
2038
2039     /* We might have GC'd, mark the TSO dirty again */
2040     dirty_TSO(cap,tso);
2041
2042     IF_DEBUG(sanity, checkTSO(tso));
2043
2044     return &cap->r;
2045 }
2046
2047 /* ---------------------------------------------------------------------------
2048  * scheduleThread()
2049  *
2050  * scheduleThread puts a thread on the end  of the runnable queue.
2051  * This will usually be done immediately after a thread is created.
2052  * The caller of scheduleThread must create the thread using e.g.
2053  * createThread and push an appropriate closure
2054  * on this thread's stack before the scheduler is invoked.
2055  * ------------------------------------------------------------------------ */
2056
2057 void
2058 scheduleThread(Capability *cap, StgTSO *tso)
2059 {
2060     // The thread goes at the *end* of the run-queue, to avoid possible
2061     // starvation of any threads already on the queue.
2062     appendToRunQueue(cap,tso);
2063 }
2064
2065 void
2066 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
2067 {
2068 #if defined(THREADED_RTS)
2069     tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
2070                               // move this thread from now on.
2071     cpu %= RtsFlags.ParFlags.nNodes;
2072     if (cpu == cap->no) {
2073         appendToRunQueue(cap,tso);
2074     } else {
2075         postEvent (cap, EVENT_MIGRATE_THREAD, tso->id, capabilities[cpu].no);
2076         wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
2077     }
2078 #else
2079     appendToRunQueue(cap,tso);
2080 #endif
2081 }
2082
2083 Capability *
2084 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
2085 {
2086     Task *task;
2087
2088     // We already created/initialised the Task
2089     task = cap->running_task;
2090
2091     // This TSO is now a bound thread; make the Task and TSO
2092     // point to each other.
2093     tso->bound = task;
2094     tso->cap = cap;
2095
2096     task->tso = tso;
2097     task->ret = ret;
2098     task->stat = NoStatus;
2099
2100     appendToRunQueue(cap,tso);
2101
2102     debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)tso->id);
2103
2104     cap = schedule(cap,task);
2105
2106     ASSERT(task->stat != NoStatus);
2107     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
2108
2109     debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)task->tso->id);
2110     return cap;
2111 }
2112
2113 /* ----------------------------------------------------------------------------
2114  * Starting Tasks
2115  * ------------------------------------------------------------------------- */
2116
2117 #if defined(THREADED_RTS)
2118 void OSThreadProcAttr
2119 workerStart(Task *task)
2120 {
2121     Capability *cap;
2122
2123     // See startWorkerTask().
2124     ACQUIRE_LOCK(&task->lock);
2125     cap = task->cap;
2126     RELEASE_LOCK(&task->lock);
2127
2128     if (RtsFlags.ParFlags.setAffinity) {
2129         setThreadAffinity(cap->no, n_capabilities);
2130     }
2131
2132     // set the thread-local pointer to the Task:
2133     taskEnter(task);
2134
2135     // schedule() runs without a lock.
2136     cap = schedule(cap,task);
2137
2138     // On exit from schedule(), we have a Capability, but possibly not
2139     // the same one we started with.
2140
2141     // During shutdown, the requirement is that after all the
2142     // Capabilities are shut down, all workers that are shutting down
2143     // have finished workerTaskStop().  This is why we hold on to
2144     // cap->lock until we've finished workerTaskStop() below.
2145     //
2146     // There may be workers still involved in foreign calls; those
2147     // will just block in waitForReturnCapability() because the
2148     // Capability has been shut down.
2149     //
2150     ACQUIRE_LOCK(&cap->lock);
2151     releaseCapability_(cap,rtsFalse);
2152     workerTaskStop(task);
2153     RELEASE_LOCK(&cap->lock);
2154 }
2155 #endif
2156
2157 /* ---------------------------------------------------------------------------
2158  * initScheduler()
2159  *
2160  * Initialise the scheduler.  This resets all the queues - if the
2161  * queues contained any threads, they'll be garbage collected at the
2162  * next pass.
2163  *
2164  * ------------------------------------------------------------------------ */
2165
2166 void 
2167 initScheduler(void)
2168 {
2169 #if !defined(THREADED_RTS)
2170   blocked_queue_hd  = END_TSO_QUEUE;
2171   blocked_queue_tl  = END_TSO_QUEUE;
2172   sleeping_queue    = END_TSO_QUEUE;
2173 #endif
2174
2175   blackhole_queue   = END_TSO_QUEUE;
2176
2177   sched_state    = SCHED_RUNNING;
2178   recent_activity = ACTIVITY_YES;
2179
2180 #if defined(THREADED_RTS)
2181   /* Initialise the mutex and condition variables used by
2182    * the scheduler. */
2183   initMutex(&sched_mutex);
2184 #endif
2185   
2186   ACQUIRE_LOCK(&sched_mutex);
2187
2188   /* A capability holds the state a native thread needs in
2189    * order to execute STG code. At least one capability is
2190    * floating around (only THREADED_RTS builds have more than one).
2191    */
2192   initCapabilities();
2193
2194   initTaskManager();
2195
2196 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
2197   initSparkPools();
2198 #endif
2199
2200 #if defined(THREADED_RTS)
2201   /*
2202    * Eagerly start one worker to run each Capability, except for
2203    * Capability 0.  The idea is that we're probably going to start a
2204    * bound thread on Capability 0 pretty soon, so we don't want a
2205    * worker task hogging it.
2206    */
2207   { 
2208       nat i;
2209       Capability *cap;
2210       for (i = 1; i < n_capabilities; i++) {
2211           cap = &capabilities[i];
2212           ACQUIRE_LOCK(&cap->lock);
2213           startWorkerTask(cap, workerStart);
2214           RELEASE_LOCK(&cap->lock);
2215       }
2216   }
2217 #endif
2218
2219   RELEASE_LOCK(&sched_mutex);
2220 }
2221
2222 void
2223 exitScheduler(
2224     rtsBool wait_foreign
2225 #if !defined(THREADED_RTS)
2226                          __attribute__((unused))
2227 #endif
2228 )
2229                /* see Capability.c, shutdownCapability() */
2230 {
2231     Task *task = NULL;
2232
2233     ACQUIRE_LOCK(&sched_mutex);
2234     task = newBoundTask();
2235     RELEASE_LOCK(&sched_mutex);
2236
2237     // If we haven't killed all the threads yet, do it now.
2238     if (sched_state < SCHED_SHUTTING_DOWN) {
2239         sched_state = SCHED_INTERRUPTING;
2240         waitForReturnCapability(&task->cap,task);
2241         scheduleDoGC(task->cap,task,rtsFalse);    
2242         releaseCapability(task->cap);
2243     }
2244     sched_state = SCHED_SHUTTING_DOWN;
2245
2246 #if defined(THREADED_RTS)
2247     { 
2248         nat i;
2249         
2250         for (i = 0; i < n_capabilities; i++) {
2251             shutdownCapability(&capabilities[i], task, wait_foreign);
2252         }
2253         boundTaskExiting(task);
2254     }
2255 #endif
2256 }
2257
2258 void
2259 freeScheduler( void )
2260 {
2261     nat still_running;
2262
2263     ACQUIRE_LOCK(&sched_mutex);
2264     still_running = freeTaskManager();
2265     // We can only free the Capabilities if there are no Tasks still
2266     // running.  We might have a Task about to return from a foreign
2267     // call into waitForReturnCapability(), for example (actually,
2268     // this should be the *only* thing that a still-running Task can
2269     // do at this point, and it will block waiting for the
2270     // Capability).
2271     if (still_running == 0) {
2272         freeCapabilities();
2273         if (n_capabilities != 1) {
2274             stgFree(capabilities);
2275         }
2276     }
2277     RELEASE_LOCK(&sched_mutex);
2278 #if defined(THREADED_RTS)
2279     closeMutex(&sched_mutex);
2280 #endif
2281 }
2282
2283 /* -----------------------------------------------------------------------------
2284    performGC
2285
2286    This is the interface to the garbage collector from Haskell land.
2287    We provide this so that external C code can allocate and garbage
2288    collect when called from Haskell via _ccall_GC.
2289    -------------------------------------------------------------------------- */
2290
2291 static void
2292 performGC_(rtsBool force_major)
2293 {
2294     Task *task;
2295
2296     // We must grab a new Task here, because the existing Task may be
2297     // associated with a particular Capability, and chained onto the 
2298     // suspended_ccalling_tasks queue.
2299     ACQUIRE_LOCK(&sched_mutex);
2300     task = newBoundTask();
2301     RELEASE_LOCK(&sched_mutex);
2302
2303     waitForReturnCapability(&task->cap,task);
2304     scheduleDoGC(task->cap,task,force_major);
2305     releaseCapability(task->cap);
2306     boundTaskExiting(task);
2307 }
2308
2309 void
2310 performGC(void)
2311 {
2312     performGC_(rtsFalse);
2313 }
2314
2315 void
2316 performMajorGC(void)
2317 {
2318     performGC_(rtsTrue);
2319 }
2320
2321 /* -----------------------------------------------------------------------------
2322    Stack overflow
2323
2324    If the thread has reached its maximum stack size, then raise the
2325    StackOverflow exception in the offending thread.  Otherwise
2326    relocate the TSO into a larger chunk of memory and adjust its stack
2327    size appropriately.
2328    -------------------------------------------------------------------------- */
2329
2330 static StgTSO *
2331 threadStackOverflow(Capability *cap, StgTSO *tso)
2332 {
2333   nat new_stack_size, stack_words;
2334   lnat new_tso_size;
2335   StgPtr new_sp;
2336   StgTSO *dest;
2337
2338   IF_DEBUG(sanity,checkTSO(tso));
2339
2340   // don't allow throwTo() to modify the blocked_exceptions queue
2341   // while we are moving the TSO:
2342   lockClosure((StgClosure *)tso);
2343
2344   if (tso->stack_size >= tso->max_stack_size && !(tso->flags & TSO_BLOCKEX)) {
2345       // NB. never raise a StackOverflow exception if the thread is
2346       // inside Control.Exceptino.block.  It is impractical to protect
2347       // against stack overflow exceptions, since virtually anything
2348       // can raise one (even 'catch'), so this is the only sensible
2349       // thing to do here.  See bug #767.
2350
2351       debugTrace(DEBUG_gc,
2352                  "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2353                  (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2354       IF_DEBUG(gc,
2355                /* If we're debugging, just print out the top of the stack */
2356                printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size, 
2357                                                 tso->sp+64)));
2358
2359       // Send this thread the StackOverflow exception
2360       unlockTSO(tso);
2361       throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2362       return tso;
2363   }
2364
2365   /* Try to double the current stack size.  If that takes us over the
2366    * maximum stack size for this thread, then use the maximum instead
2367    * (that is, unless we're already at or over the max size and we
2368    * can't raise the StackOverflow exception (see above), in which
2369    * case just double the size). Finally round up so the TSO ends up as
2370    * a whole number of blocks.
2371    */
2372   if (tso->stack_size >= tso->max_stack_size) {
2373       new_stack_size = tso->stack_size * 2;
2374   } else { 
2375       new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2376   }
2377   new_tso_size   = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) + 
2378                                        TSO_STRUCT_SIZE)/sizeof(W_);
2379   new_tso_size = round_to_mblocks(new_tso_size);  /* Be MBLOCK-friendly */
2380   new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2381
2382   debugTrace(DEBUG_sched, 
2383              "increasing stack size from %ld words to %d.",
2384              (long)tso->stack_size, new_stack_size);
2385
2386   dest = (StgTSO *)allocateLocal(cap,new_tso_size);
2387   TICK_ALLOC_TSO(new_stack_size,0);
2388
2389   /* copy the TSO block and the old stack into the new area */
2390   memcpy(dest,tso,TSO_STRUCT_SIZE);
2391   stack_words = tso->stack + tso->stack_size - tso->sp;
2392   new_sp = (P_)dest + new_tso_size - stack_words;
2393   memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2394
2395   /* relocate the stack pointers... */
2396   dest->sp         = new_sp;
2397   dest->stack_size = new_stack_size;
2398         
2399   /* Mark the old TSO as relocated.  We have to check for relocated
2400    * TSOs in the garbage collector and any primops that deal with TSOs.
2401    *
2402    * It's important to set the sp value to just beyond the end
2403    * of the stack, so we don't attempt to scavenge any part of the
2404    * dead TSO's stack.
2405    */
2406   tso->what_next = ThreadRelocated;
2407   setTSOLink(cap,tso,dest);
2408   tso->sp = (P_)&(tso->stack[tso->stack_size]);
2409   tso->why_blocked = NotBlocked;
2410
2411   IF_PAR_DEBUG(verbose,
2412                debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2413                      tso->id, tso, tso->stack_size);
2414                /* If we're debugging, just print out the top of the stack */
2415                printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size, 
2416                                                 tso->sp+64)));
2417   
2418   unlockTSO(dest);
2419   unlockTSO(tso);
2420
2421   IF_DEBUG(sanity,checkTSO(dest));
2422 #if 0
2423   IF_DEBUG(scheduler,printTSO(dest));
2424 #endif
2425
2426   return dest;
2427 }
2428
2429 static StgTSO *
2430 threadStackUnderflow (Task *task STG_UNUSED, StgTSO *tso)
2431 {
2432     bdescr *bd, *new_bd;
2433     lnat free_w, tso_size_w;
2434     StgTSO *new_tso;
2435
2436     tso_size_w = tso_sizeW(tso);
2437
2438     if (tso_size_w < MBLOCK_SIZE_W || 
2439         (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4) 
2440     {
2441         return tso;
2442     }
2443
2444     // don't allow throwTo() to modify the blocked_exceptions queue
2445     // while we are moving the TSO:
2446     lockClosure((StgClosure *)tso);
2447
2448     // this is the number of words we'll free
2449     free_w = round_to_mblocks(tso_size_w/2);
2450
2451     bd = Bdescr((StgPtr)tso);
2452     new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2453     bd->free = bd->start + TSO_STRUCT_SIZEW;
2454
2455     new_tso = (StgTSO *)new_bd->start;
2456     memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2457     new_tso->stack_size = new_bd->free - new_tso->stack;
2458
2459     debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2460                (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2461
2462     tso->what_next = ThreadRelocated;
2463     tso->_link = new_tso; // no write barrier reqd: same generation
2464
2465     // The TSO attached to this Task may have moved, so update the
2466     // pointer to it.
2467     if (task->tso == tso) {
2468         task->tso = new_tso;
2469     }
2470
2471     unlockTSO(new_tso);
2472     unlockTSO(tso);
2473
2474     IF_DEBUG(sanity,checkTSO(new_tso));
2475
2476     return new_tso;
2477 }
2478
2479 /* ---------------------------------------------------------------------------
2480    Interrupt execution
2481    - usually called inside a signal handler so it mustn't do anything fancy.   
2482    ------------------------------------------------------------------------ */
2483
2484 void
2485 interruptStgRts(void)
2486 {
2487     sched_state = SCHED_INTERRUPTING;
2488     setContextSwitches();
2489     wakeUpRts();
2490 }
2491
2492 /* -----------------------------------------------------------------------------
2493    Wake up the RTS
2494    
2495    This function causes at least one OS thread to wake up and run the
2496    scheduler loop.  It is invoked when the RTS might be deadlocked, or
2497    an external event has arrived that may need servicing (eg. a
2498    keyboard interrupt).
2499
2500    In the single-threaded RTS we don't do anything here; we only have
2501    one thread anyway, and the event that caused us to want to wake up
2502    will have interrupted any blocking system call in progress anyway.
2503    -------------------------------------------------------------------------- */
2504
2505 void
2506 wakeUpRts(void)
2507 {
2508 #if defined(THREADED_RTS)
2509     // This forces the IO Manager thread to wakeup, which will
2510     // in turn ensure that some OS thread wakes up and runs the
2511     // scheduler loop, which will cause a GC and deadlock check.
2512     ioManagerWakeup();
2513 #endif
2514 }
2515
2516 /* -----------------------------------------------------------------------------
2517  * checkBlackHoles()
2518  *
2519  * Check the blackhole_queue for threads that can be woken up.  We do
2520  * this periodically: before every GC, and whenever the run queue is
2521  * empty.
2522  *
2523  * An elegant solution might be to just wake up all the blocked
2524  * threads with awakenBlockedQueue occasionally: they'll go back to
2525  * sleep again if the object is still a BLACKHOLE.  Unfortunately this
2526  * doesn't give us a way to tell whether we've actually managed to
2527  * wake up any threads, so we would be busy-waiting.
2528  *
2529  * -------------------------------------------------------------------------- */
2530
2531 static rtsBool
2532 checkBlackHoles (Capability *cap)
2533 {
2534     StgTSO **prev, *t;
2535     rtsBool any_woke_up = rtsFalse;
2536     StgHalfWord type;
2537
2538     // blackhole_queue is global:
2539     ASSERT_LOCK_HELD(&sched_mutex);
2540
2541     debugTrace(DEBUG_sched, "checking threads blocked on black holes");
2542
2543     // ASSUMES: sched_mutex
2544     prev = &blackhole_queue;
2545     t = blackhole_queue;
2546     while (t != END_TSO_QUEUE) {
2547         if (t->what_next == ThreadRelocated) {
2548             t = t->_link;
2549             continue;
2550         }
2551         ASSERT(t->why_blocked == BlockedOnBlackHole);
2552         type = get_itbl(UNTAG_CLOSURE(t->block_info.closure))->type;
2553         if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
2554             IF_DEBUG(sanity,checkTSO(t));
2555             t = unblockOne(cap, t);
2556             *prev = t;
2557             any_woke_up = rtsTrue;
2558         } else {
2559             prev = &t->_link;
2560             t = t->_link;
2561         }
2562     }
2563
2564     return any_woke_up;
2565 }
2566
2567 /* -----------------------------------------------------------------------------
2568    Deleting threads
2569
2570    This is used for interruption (^C) and forking, and corresponds to
2571    raising an exception but without letting the thread catch the
2572    exception.
2573    -------------------------------------------------------------------------- */
2574
2575 static void 
2576 deleteThread (Capability *cap, StgTSO *tso)
2577 {
2578     // NOTE: must only be called on a TSO that we have exclusive
2579     // access to, because we will call throwToSingleThreaded() below.
2580     // The TSO must be on the run queue of the Capability we own, or 
2581     // we must own all Capabilities.
2582
2583     if (tso->why_blocked != BlockedOnCCall &&
2584         tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2585         throwToSingleThreaded(cap,tso,NULL);
2586     }
2587 }
2588
2589 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2590 static void 
2591 deleteThread_(Capability *cap, StgTSO *tso)
2592 { // for forkProcess only:
2593   // like deleteThread(), but we delete threads in foreign calls, too.
2594
2595     if (tso->why_blocked == BlockedOnCCall ||
2596         tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2597         unblockOne(cap,tso);
2598         tso->what_next = ThreadKilled;
2599     } else {
2600         deleteThread(cap,tso);
2601     }
2602 }
2603 #endif
2604
2605 /* -----------------------------------------------------------------------------
2606    raiseExceptionHelper
2607    
2608    This function is called by the raise# primitve, just so that we can
2609    move some of the tricky bits of raising an exception from C-- into
2610    C.  Who knows, it might be a useful re-useable thing here too.
2611    -------------------------------------------------------------------------- */
2612
2613 StgWord
2614 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2615 {
2616     Capability *cap = regTableToCapability(reg);
2617     StgThunk *raise_closure = NULL;
2618     StgPtr p, next;
2619     StgRetInfoTable *info;
2620     //
2621     // This closure represents the expression 'raise# E' where E
2622     // is the exception raise.  It is used to overwrite all the
2623     // thunks which are currently under evaluataion.
2624     //
2625
2626     // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2627     // LDV profiling: stg_raise_info has THUNK as its closure
2628     // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2629     // payload, MIN_UPD_SIZE is more approprate than 1.  It seems that
2630     // 1 does not cause any problem unless profiling is performed.
2631     // However, when LDV profiling goes on, we need to linearly scan
2632     // small object pool, where raise_closure is stored, so we should
2633     // use MIN_UPD_SIZE.
2634     //
2635     // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2636     //                                 sizeofW(StgClosure)+1);
2637     //
2638
2639     //
2640     // Walk up the stack, looking for the catch frame.  On the way,
2641     // we update any closures pointed to from update frames with the
2642     // raise closure that we just built.
2643     //
2644     p = tso->sp;
2645     while(1) {
2646         info = get_ret_itbl((StgClosure *)p);
2647         next = p + stack_frame_sizeW((StgClosure *)p);
2648         switch (info->i.type) {
2649             
2650         case UPDATE_FRAME:
2651             // Only create raise_closure if we need to.
2652             if (raise_closure == NULL) {
2653                 raise_closure = 
2654                     (StgThunk *)allocateLocal(cap,sizeofW(StgThunk)+1);
2655                 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2656                 raise_closure->payload[0] = exception;
2657             }
2658             UPD_IND(((StgUpdateFrame *)p)->updatee,(StgClosure *)raise_closure);
2659             p = next;
2660             continue;
2661
2662         case ATOMICALLY_FRAME:
2663             debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2664             tso->sp = p;
2665             return ATOMICALLY_FRAME;
2666             
2667         case CATCH_FRAME:
2668             tso->sp = p;
2669             return CATCH_FRAME;
2670
2671         case CATCH_STM_FRAME:
2672             debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2673             tso->sp = p;
2674             return CATCH_STM_FRAME;
2675             
2676         case STOP_FRAME:
2677             tso->sp = p;
2678             return STOP_FRAME;
2679
2680         case CATCH_RETRY_FRAME:
2681         default:
2682             p = next; 
2683             continue;
2684         }
2685     }
2686 }
2687
2688
2689 /* -----------------------------------------------------------------------------
2690    findRetryFrameHelper
2691
2692    This function is called by the retry# primitive.  It traverses the stack
2693    leaving tso->sp referring to the frame which should handle the retry.  
2694
2695    This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#) 
2696    or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).  
2697
2698    We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2699    create) because retries are not considered to be exceptions, despite the
2700    similar implementation.
2701
2702    We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2703    not be created within memory transactions.
2704    -------------------------------------------------------------------------- */
2705
2706 StgWord
2707 findRetryFrameHelper (StgTSO *tso)
2708 {
2709   StgPtr           p, next;
2710   StgRetInfoTable *info;
2711
2712   p = tso -> sp;
2713   while (1) {
2714     info = get_ret_itbl((StgClosure *)p);
2715     next = p + stack_frame_sizeW((StgClosure *)p);
2716     switch (info->i.type) {
2717       
2718     case ATOMICALLY_FRAME:
2719         debugTrace(DEBUG_stm,
2720                    "found ATOMICALLY_FRAME at %p during retry", p);
2721         tso->sp = p;
2722         return ATOMICALLY_FRAME;
2723       
2724     case CATCH_RETRY_FRAME:
2725         debugTrace(DEBUG_stm,
2726                    "found CATCH_RETRY_FRAME at %p during retrry", p);
2727         tso->sp = p;
2728         return CATCH_RETRY_FRAME;
2729       
2730     case CATCH_STM_FRAME: {
2731         StgTRecHeader *trec = tso -> trec;
2732         StgTRecHeader *outer = stmGetEnclosingTRec(trec);
2733         debugTrace(DEBUG_stm,
2734                    "found CATCH_STM_FRAME at %p during retry", p);
2735         debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2736         stmAbortTransaction(tso -> cap, trec);
2737         stmFreeAbortedTRec(tso -> cap, trec);
2738         tso -> trec = outer;
2739         p = next; 
2740         continue;
2741     }
2742       
2743
2744     default:
2745       ASSERT(info->i.type != CATCH_FRAME);
2746       ASSERT(info->i.type != STOP_FRAME);
2747       p = next; 
2748       continue;
2749     }
2750   }
2751 }
2752
2753 /* -----------------------------------------------------------------------------
2754    resurrectThreads is called after garbage collection on the list of
2755    threads found to be garbage.  Each of these threads will be woken
2756    up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2757    on an MVar, or NonTermination if the thread was blocked on a Black
2758    Hole.
2759
2760    Locks: assumes we hold *all* the capabilities.
2761    -------------------------------------------------------------------------- */
2762
2763 void
2764 resurrectThreads (StgTSO *threads)
2765 {
2766     StgTSO *tso, *next;
2767     Capability *cap;
2768     step *step;
2769
2770     for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2771         next = tso->global_link;
2772
2773         step = Bdescr((P_)tso)->step;
2774         tso->global_link = step->threads;
2775         step->threads = tso;
2776
2777         debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2778         
2779         // Wake up the thread on the Capability it was last on
2780         cap = tso->cap;
2781         
2782         switch (tso->why_blocked) {
2783         case BlockedOnMVar:
2784         case BlockedOnException:
2785             /* Called by GC - sched_mutex lock is currently held. */
2786             throwToSingleThreaded(cap, tso,
2787                                   (StgClosure *)blockedOnDeadMVar_closure);
2788             break;
2789         case BlockedOnBlackHole:
2790             throwToSingleThreaded(cap, tso,
2791                                   (StgClosure *)nonTermination_closure);
2792             break;
2793         case BlockedOnSTM:
2794             throwToSingleThreaded(cap, tso,
2795                                   (StgClosure *)blockedIndefinitely_closure);
2796             break;
2797         case NotBlocked:
2798             /* This might happen if the thread was blocked on a black hole
2799              * belonging to a thread that we've just woken up (raiseAsync
2800              * can wake up threads, remember...).
2801              */
2802             continue;
2803         default:
2804             barf("resurrectThreads: thread blocked in a strange way");
2805         }
2806     }
2807 }
2808
2809 /* -----------------------------------------------------------------------------
2810    performPendingThrowTos is called after garbage collection, and
2811    passed a list of threads that were found to have pending throwTos
2812    (tso->blocked_exceptions was not empty), and were blocked.
2813    Normally this doesn't happen, because we would deliver the
2814    exception directly if the target thread is blocked, but there are
2815    small windows where it might occur on a multiprocessor (see
2816    throwTo()).
2817
2818    NB. we must be holding all the capabilities at this point, just
2819    like resurrectThreads().
2820    -------------------------------------------------------------------------- */
2821
2822 void
2823 performPendingThrowTos (StgTSO *threads)
2824 {
2825     StgTSO *tso, *next;
2826     Capability *cap;
2827     step *step;
2828
2829     for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2830         next = tso->global_link;
2831
2832         step = Bdescr((P_)tso)->step;
2833         tso->global_link = step->threads;
2834         step->threads = tso;
2835
2836         debugTrace(DEBUG_sched, "performing blocked throwTo to thread %lu", (unsigned long)tso->id);
2837         
2838         cap = tso->cap;
2839         maybePerformBlockedException(cap, tso);
2840     }
2841 }