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