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