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