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