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