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