1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2006
5 * The scheduler and thread-related functionality
7 * --------------------------------------------------------------------------*/
9 #include "PosixSource.h"
10 #define KEEP_LOCKCLOSURE
13 #include "sm/Storage.h"
17 #include "Interpreter.h"
19 #include "RtsSignals.h"
20 #include "sm/Sanity.h"
24 #include "ThreadLabels.h"
26 #include "Proftimer.h"
29 #include "sm/GC.h" // waitForGcThreads, releaseGCThreads, N
31 #include "Capability.h"
33 #include "AwaitEvent.h"
34 #if defined(mingw32_HOST_OS)
35 #include "win32/IOManager.h"
38 #include "RaiseAsync.h"
41 #include "ThreadPaused.h"
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
59 /* -----------------------------------------------------------------------------
61 * -------------------------------------------------------------------------- */
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?
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.)
74 rtsBool heap_overflow = rtsFalse;
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).
80 * NB. must be StgWord, we do xchg() on it.
82 volatile StgWord recent_activity = ACTIVITY_YES;
84 /* if this flag is set as well, give up execution
85 * LOCK: none (changes monotonically)
87 volatile StgWord sched_state = SCHED_RUNNING;
89 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
90 * exists - earlier gccs apparently didn't.
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.
100 rtsBool shutting_down_scheduler = rtsFalse;
103 * This mutex protects most of the global scheduler data in
104 * the THREADED_RTS runtime.
106 #if defined(THREADED_RTS)
110 #if !defined(mingw32_HOST_OS)
111 #define FORKPROCESS_PRIMOP_SUPPORTED
114 /* -----------------------------------------------------------------------------
115 * static function prototypes
116 * -------------------------------------------------------------------------- */
118 static Capability *schedule (Capability *initialCapability, Task *task);
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.
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);
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);
138 static void schedulePostRunThread(Capability *cap, StgTSO *t);
139 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
140 static void scheduleHandleStackOverflow( Capability *cap, Task *task,
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,
147 static rtsBool scheduleNeedHeapProfile(rtsBool ready_to_gc);
148 static Capability *scheduleDoGC(Capability *cap, Task *task,
149 rtsBool force_major);
151 static StgTSO *threadStackOverflow(Capability *cap, StgTSO *tso);
152 static StgTSO *threadStackUnderflow(Capability *cap, Task *task, StgTSO *tso);
154 static void deleteThread (Capability *cap, StgTSO *tso);
155 static void deleteAllThreads (Capability *cap);
157 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
158 static void deleteThread_(Capability *cap, StgTSO *tso);
161 /* -----------------------------------------------------------------------------
162 * Putting a thread on the run queue: different scheduling policies
163 * -------------------------------------------------------------------------- */
166 addToRunQueue( Capability *cap, StgTSO *t )
168 // this does round-robin scheduling; good for concurrency
169 appendToRunQueue(cap,t);
172 /* ---------------------------------------------------------------------------
173 Main scheduling loop.
175 We use round-robin scheduling, each thread returning to the
176 scheduler loop when one of these conditions is detected:
179 * timer expires (thread yields)
185 In a GranSim setup this loop iterates over the global event queue.
186 This revolves around the global event queue, which determines what
187 to do next. Therefore, it's more complicated than either the
188 concurrent or the parallel (GUM) setup.
189 This version has been entirely removed (JB 2008/08).
192 GUM iterates over incoming messages.
193 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
194 and sends out a fish whenever it has nothing to do; in-between
195 doing the actual reductions (shared code below) it processes the
196 incoming messages and deals with delayed operations
197 (see PendingFetches).
198 This is not the ugliest code you could imagine, but it's bloody close.
200 (JB 2008/08) This version was formerly indicated by a PP-Flag PAR,
201 now by PP-flag PARALLEL_HASKELL. The Eden RTS (in GHC-6.x) uses it,
202 as well as future GUM versions. This file has been refurbished to
203 only contain valid code, which is however incomplete, refers to
204 invalid includes etc.
206 ------------------------------------------------------------------------ */
209 schedule (Capability *initialCapability, Task *task)
213 StgThreadReturnCode ret;
216 #if defined(THREADED_RTS)
217 rtsBool first = rtsTrue;
218 rtsBool force_yield = rtsFalse;
221 cap = initialCapability;
223 // Pre-condition: this task owns initialCapability.
224 // The sched_mutex is *NOT* held
225 // NB. on return, we still hold a capability.
227 debugTrace (DEBUG_sched, "cap %d: schedule()", initialCapability->no);
231 // -----------------------------------------------------------
232 // Scheduler loop starts here:
236 // Check whether we have re-entered the RTS from Haskell without
237 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
239 if (cap->in_haskell) {
240 errorBelch("schedule: re-entered unsafely.\n"
241 " Perhaps a 'foreign import unsafe' should be 'safe'?");
242 stg_exit(EXIT_FAILURE);
245 // The interruption / shutdown sequence.
247 // In order to cleanly shut down the runtime, we want to:
248 // * make sure that all main threads return to their callers
249 // with the state 'Interrupted'.
250 // * clean up all OS threads assocated with the runtime
251 // * free all memory etc.
253 // So the sequence for ^C goes like this:
255 // * ^C handler sets sched_state := SCHED_INTERRUPTING and
256 // arranges for some Capability to wake up
258 // * all threads in the system are halted, and the zombies are
259 // placed on the run queue for cleaning up. We acquire all
260 // the capabilities in order to delete the threads, this is
261 // done by scheduleDoGC() for convenience (because GC already
262 // needs to acquire all the capabilities). We can't kill
263 // threads involved in foreign calls.
265 // * somebody calls shutdownHaskell(), which calls exitScheduler()
267 // * sched_state := SCHED_SHUTTING_DOWN
269 // * all workers exit when the run queue on their capability
270 // drains. All main threads will also exit when their TSO
271 // reaches the head of the run queue and they can return.
273 // * eventually all Capabilities will shut down, and the RTS can
276 // * We might be left with threads blocked in foreign calls,
277 // we should really attempt to kill these somehow (TODO);
279 switch (sched_state) {
282 case SCHED_INTERRUPTING:
283 debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
284 #if defined(THREADED_RTS)
285 discardSparksCap(cap);
287 /* scheduleDoGC() deletes all the threads */
288 cap = scheduleDoGC(cap,task,rtsFalse);
290 // after scheduleDoGC(), we must be shutting down. Either some
291 // other Capability did the final GC, or we did it above,
292 // either way we can fall through to the SCHED_SHUTTING_DOWN
294 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
297 case SCHED_SHUTTING_DOWN:
298 debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
299 // If we are a worker, just exit. If we're a bound thread
300 // then we will exit below when we've removed our TSO from
302 if (!isBoundTask(task) && emptyRunQueue(cap)) {
307 barf("sched_state: %d", sched_state);
310 scheduleFindWork(cap);
312 /* work pushing, currently relevant only for THREADED_RTS:
313 (pushes threads, wakes up idle capabilities for stealing) */
314 schedulePushWork(cap,task);
316 scheduleDetectDeadlock(cap,task);
318 #if defined(THREADED_RTS)
319 cap = task->cap; // reload cap, it might have changed
322 // Normally, the only way we can get here with no threads to
323 // run is if a keyboard interrupt received during
324 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
325 // Additionally, it is not fatal for the
326 // threaded RTS to reach here with no threads to run.
328 // win32: might be here due to awaitEvent() being abandoned
329 // as a result of a console event having been delivered.
331 #if defined(THREADED_RTS)
335 // // don't yield the first time, we want a chance to run this
336 // // thread for a bit, even if there are others banging at the
339 // ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
343 scheduleYield(&cap,task,force_yield);
344 force_yield = rtsFalse;
346 if (emptyRunQueue(cap)) continue; // look for work again
349 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
350 if ( emptyRunQueue(cap) ) {
351 ASSERT(sched_state >= SCHED_INTERRUPTING);
356 // Get a thread to run
358 t = popRunQueue(cap);
360 // Sanity check the thread we're about to run. This can be
361 // expensive if there is lots of thread switching going on...
362 IF_DEBUG(sanity,checkTSO(t));
364 #if defined(THREADED_RTS)
365 // Check whether we can run this thread in the current task.
366 // If not, we have to pass our capability to the right task.
368 InCall *bound = t->bound;
371 if (bound->task == task) {
372 // yes, the Haskell thread is bound to the current native thread
374 debugTrace(DEBUG_sched,
375 "thread %lu bound to another OS thread",
376 (unsigned long)t->id);
377 // no, bound to a different Haskell thread: pass to that thread
378 pushOnRunQueue(cap,t);
382 // The thread we want to run is unbound.
383 if (task->incall->tso) {
384 debugTrace(DEBUG_sched,
385 "this OS thread cannot run thread %lu",
386 (unsigned long)t->id);
387 // no, the current native thread is bound to a different
388 // Haskell thread, so pass it to any worker thread
389 pushOnRunQueue(cap,t);
396 // If we're shutting down, and this thread has not yet been
397 // killed, kill it now. This sometimes happens when a finalizer
398 // thread is created by the final GC, or a thread previously
399 // in a foreign call returns.
400 if (sched_state >= SCHED_INTERRUPTING &&
401 !(t->what_next == ThreadComplete || t->what_next == ThreadKilled)) {
405 /* context switches are initiated by the timer signal, unless
406 * the user specified "context switch as often as possible", with
409 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
410 && !emptyThreadQueues(cap)) {
411 cap->context_switch = 1;
416 // CurrentTSO is the thread to run. t might be different if we
417 // loop back to run_thread, so make sure to set CurrentTSO after
419 cap->r.rCurrentTSO = t;
421 startHeapProfTimer();
423 // ----------------------------------------------------------------------
424 // Run the current thread
426 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
427 ASSERT(t->cap == cap);
428 ASSERT(t->bound ? t->bound->task->cap == cap : 1);
430 prev_what_next = t->what_next;
432 errno = t->saved_errno;
434 SetLastError(t->saved_winerror);
437 cap->in_haskell = rtsTrue;
441 #if defined(THREADED_RTS)
442 if (recent_activity == ACTIVITY_DONE_GC) {
443 // ACTIVITY_DONE_GC means we turned off the timer signal to
444 // conserve power (see #1623). Re-enable it here.
446 prev = xchg((P_)&recent_activity, ACTIVITY_YES);
447 if (prev == ACTIVITY_DONE_GC) {
450 } else if (recent_activity != ACTIVITY_INACTIVE) {
451 // If we reached ACTIVITY_INACTIVE, then don't reset it until
452 // we've done the GC. The thread running here might just be
453 // the IO manager thread that handle_tick() woke up via
455 recent_activity = ACTIVITY_YES;
459 traceEventRunThread(cap, t);
461 switch (prev_what_next) {
465 /* Thread already finished, return to scheduler. */
466 ret = ThreadFinished;
472 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
473 cap = regTableToCapability(r);
478 case ThreadInterpret:
479 cap = interpretBCO(cap);
484 barf("schedule: invalid what_next field");
487 cap->in_haskell = rtsFalse;
489 // The TSO might have moved, eg. if it re-entered the RTS and a GC
490 // happened. So find the new location:
491 t = cap->r.rCurrentTSO;
493 // And save the current errno in this thread.
494 // XXX: possibly bogus for SMP because this thread might already
495 // be running again, see code below.
496 t->saved_errno = errno;
498 // Similarly for Windows error code
499 t->saved_winerror = GetLastError();
502 traceEventStopThread(cap, t, ret);
504 #if defined(THREADED_RTS)
505 // If ret is ThreadBlocked, and this Task is bound to the TSO that
506 // blocked, we are in limbo - the TSO is now owned by whatever it
507 // is blocked on, and may in fact already have been woken up,
508 // perhaps even on a different Capability. It may be the case
509 // that task->cap != cap. We better yield this Capability
510 // immediately and return to normaility.
511 if (ret == ThreadBlocked) {
512 force_yield = rtsTrue;
517 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
518 ASSERT(t->cap == cap);
520 // ----------------------------------------------------------------------
522 // Costs for the scheduler are assigned to CCS_SYSTEM
524 #if defined(PROFILING)
528 schedulePostRunThread(cap,t);
530 if (ret != StackOverflow) {
531 t = threadStackUnderflow(cap,task,t);
534 ready_to_gc = rtsFalse;
538 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
542 scheduleHandleStackOverflow(cap,task,t);
546 if (scheduleHandleYield(cap, t, prev_what_next)) {
547 // shortcut for switching between compiler/interpreter:
553 scheduleHandleThreadBlocked(t);
557 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
558 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
562 barf("schedule: invalid thread return code %d", (int)ret);
565 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
566 cap = scheduleDoGC(cap,task,rtsFalse);
568 } /* end of while() */
571 /* ----------------------------------------------------------------------------
572 * Setting up the scheduler loop
573 * ------------------------------------------------------------------------- */
576 schedulePreLoop(void)
578 // initialisation for scheduler - what cannot go into initScheduler()
581 /* -----------------------------------------------------------------------------
584 * Search for work to do, and handle messages from elsewhere.
585 * -------------------------------------------------------------------------- */
588 scheduleFindWork (Capability *cap)
590 scheduleStartSignalHandlers(cap);
592 scheduleProcessInbox(cap);
594 scheduleCheckBlockedThreads(cap);
596 #if defined(THREADED_RTS)
597 if (emptyRunQueue(cap)) { scheduleActivateSpark(cap); }
601 #if defined(THREADED_RTS)
602 STATIC_INLINE rtsBool
603 shouldYieldCapability (Capability *cap, Task *task)
605 // we need to yield this capability to someone else if..
606 // - another thread is initiating a GC
607 // - another Task is returning from a foreign call
608 // - the thread at the head of the run queue cannot be run
609 // by this Task (it is bound to another Task, or it is unbound
610 // and this task it bound).
611 return (waiting_for_gc ||
612 cap->returning_tasks_hd != NULL ||
613 (!emptyRunQueue(cap) && (task->incall->tso == NULL
614 ? cap->run_queue_hd->bound != NULL
615 : cap->run_queue_hd->bound != task->incall)));
618 // This is the single place where a Task goes to sleep. There are
619 // two reasons it might need to sleep:
620 // - there are no threads to run
621 // - we need to yield this Capability to someone else
622 // (see shouldYieldCapability())
624 // Careful: the scheduler loop is quite delicate. Make sure you run
625 // the tests in testsuite/concurrent (all ways) after modifying this,
626 // and also check the benchmarks in nofib/parallel for regressions.
629 scheduleYield (Capability **pcap, Task *task, rtsBool force_yield)
631 Capability *cap = *pcap;
633 // if we have work, and we don't need to give up the Capability, continue.
635 // The force_yield flag is used when a bound thread blocks. This
636 // is a particularly tricky situation: the current Task does not
637 // own the TSO any more, since it is on some queue somewhere, and
638 // might be woken up or manipulated by another thread at any time.
639 // The TSO and Task might be migrated to another Capability.
640 // Certain invariants might be in doubt, such as task->bound->cap
641 // == cap. We have to yield the current Capability immediately,
642 // no messing around.
645 !shouldYieldCapability(cap,task) &&
646 (!emptyRunQueue(cap) ||
648 sched_state >= SCHED_INTERRUPTING))
651 // otherwise yield (sleep), and keep yielding if necessary.
653 yieldCapability(&cap,task);
655 while (shouldYieldCapability(cap,task));
657 // note there may still be no threads on the run queue at this
658 // point, the caller has to check.
665 /* -----------------------------------------------------------------------------
668 * Push work to other Capabilities if we have some.
669 * -------------------------------------------------------------------------- */
672 schedulePushWork(Capability *cap USED_IF_THREADS,
673 Task *task USED_IF_THREADS)
675 /* following code not for PARALLEL_HASKELL. I kept the call general,
676 future GUM versions might use pushing in a distributed setup */
677 #if defined(THREADED_RTS)
679 Capability *free_caps[n_capabilities], *cap0;
682 // migration can be turned off with +RTS -qm
683 if (!RtsFlags.ParFlags.migrate) return;
685 // Check whether we have more threads on our run queue, or sparks
686 // in our pool, that we could hand to another Capability.
687 if (cap->run_queue_hd == END_TSO_QUEUE) {
688 if (sparkPoolSizeCap(cap) < 2) return;
690 if (cap->run_queue_hd->_link == END_TSO_QUEUE &&
691 sparkPoolSizeCap(cap) < 1) return;
694 // First grab as many free Capabilities as we can.
695 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
696 cap0 = &capabilities[i];
697 if (cap != cap0 && tryGrabCapability(cap0,task)) {
698 if (!emptyRunQueue(cap0)
699 || cap->returning_tasks_hd != NULL
700 || cap->inbox != (Message*)END_TSO_QUEUE) {
701 // it already has some work, we just grabbed it at
702 // the wrong moment. Or maybe it's deadlocked!
703 releaseCapability(cap0);
705 free_caps[n_free_caps++] = cap0;
710 // we now have n_free_caps free capabilities stashed in
711 // free_caps[]. Share our run queue equally with them. This is
712 // probably the simplest thing we could do; improvements we might
713 // want to do include:
715 // - giving high priority to moving relatively new threads, on
716 // the gournds that they haven't had time to build up a
717 // working set in the cache on this CPU/Capability.
719 // - giving low priority to moving long-lived threads
721 if (n_free_caps > 0) {
722 StgTSO *prev, *t, *next;
723 rtsBool pushed_to_all;
725 debugTrace(DEBUG_sched,
726 "cap %d: %s and %d free capabilities, sharing...",
728 (!emptyRunQueue(cap) && cap->run_queue_hd->_link != END_TSO_QUEUE)?
729 "excess threads on run queue":"sparks to share (>=2)",
733 pushed_to_all = rtsFalse;
735 if (cap->run_queue_hd != END_TSO_QUEUE) {
736 prev = cap->run_queue_hd;
738 prev->_link = END_TSO_QUEUE;
739 for (; t != END_TSO_QUEUE; t = next) {
741 t->_link = END_TSO_QUEUE;
742 if (t->what_next == ThreadRelocated
743 || t->bound == task->incall // don't move my bound thread
744 || tsoLocked(t)) { // don't move a locked thread
745 setTSOLink(cap, prev, t);
747 } else if (i == n_free_caps) {
748 pushed_to_all = rtsTrue;
751 setTSOLink(cap, prev, t);
754 appendToRunQueue(free_caps[i],t);
756 traceEventMigrateThread (cap, t, free_caps[i]->no);
758 if (t->bound) { t->bound->task->cap = free_caps[i]; }
759 t->cap = free_caps[i];
763 cap->run_queue_tl = prev;
767 /* JB I left this code in place, it would work but is not necessary */
769 // If there are some free capabilities that we didn't push any
770 // threads to, then try to push a spark to each one.
771 if (!pushed_to_all) {
773 // i is the next free capability to push to
774 for (; i < n_free_caps; i++) {
775 if (emptySparkPoolCap(free_caps[i])) {
776 spark = tryStealSpark(cap->sparks);
778 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
780 traceEventStealSpark(free_caps[i], t, cap->no);
782 newSpark(&(free_caps[i]->r), spark);
787 #endif /* SPARK_PUSHING */
789 // release the capabilities
790 for (i = 0; i < n_free_caps; i++) {
791 task->cap = free_caps[i];
792 releaseAndWakeupCapability(free_caps[i]);
795 task->cap = cap; // reset to point to our Capability.
797 #endif /* THREADED_RTS */
801 /* ----------------------------------------------------------------------------
802 * Start any pending signal handlers
803 * ------------------------------------------------------------------------- */
805 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
807 scheduleStartSignalHandlers(Capability *cap)
809 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
810 // safe outside the lock
811 startSignalHandlers(cap);
816 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
821 /* ----------------------------------------------------------------------------
822 * Check for blocked threads that can be woken up.
823 * ------------------------------------------------------------------------- */
826 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
828 #if !defined(THREADED_RTS)
830 // Check whether any waiting threads need to be woken up. If the
831 // run queue is empty, and there are no other tasks running, we
832 // can wait indefinitely for something to happen.
834 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
836 awaitEvent (emptyRunQueue(cap));
841 /* ----------------------------------------------------------------------------
842 * Detect deadlock conditions and attempt to resolve them.
843 * ------------------------------------------------------------------------- */
846 scheduleDetectDeadlock (Capability *cap, Task *task)
849 * Detect deadlock: when we have no threads to run, there are no
850 * threads blocked, waiting for I/O, or sleeping, and all the
851 * other tasks are waiting for work, we must have a deadlock of
854 if ( emptyThreadQueues(cap) )
856 #if defined(THREADED_RTS)
858 * In the threaded RTS, we only check for deadlock if there
859 * has been no activity in a complete timeslice. This means
860 * we won't eagerly start a full GC just because we don't have
861 * any threads to run currently.
863 if (recent_activity != ACTIVITY_INACTIVE) return;
866 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
868 // Garbage collection can release some new threads due to
869 // either (a) finalizers or (b) threads resurrected because
870 // they are unreachable and will therefore be sent an
871 // exception. Any threads thus released will be immediately
873 cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
874 // when force_major == rtsTrue. scheduleDoGC sets
875 // recent_activity to ACTIVITY_DONE_GC and turns off the timer
878 if ( !emptyRunQueue(cap) ) return;
880 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
881 /* If we have user-installed signal handlers, then wait
882 * for signals to arrive rather then bombing out with a
885 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
886 debugTrace(DEBUG_sched,
887 "still deadlocked, waiting for signals...");
891 if (signals_pending()) {
892 startSignalHandlers(cap);
895 // either we have threads to run, or we were interrupted:
896 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
902 #if !defined(THREADED_RTS)
903 /* Probably a real deadlock. Send the current main thread the
904 * Deadlock exception.
906 if (task->incall->tso) {
907 switch (task->incall->tso->why_blocked) {
909 case BlockedOnBlackHole:
910 case BlockedOnMsgThrowTo:
912 throwToSingleThreaded(cap, task->incall->tso,
913 (StgClosure *)nonTermination_closure);
916 barf("deadlock: main thread blocked in a strange way");
925 /* ----------------------------------------------------------------------------
926 * Send pending messages (PARALLEL_HASKELL only)
927 * ------------------------------------------------------------------------- */
929 #if defined(PARALLEL_HASKELL)
931 scheduleSendPendingMessages(void)
934 # if defined(PAR) // global Mem.Mgmt., omit for now
935 if (PendingFetches != END_BF_QUEUE) {
940 if (RtsFlags.ParFlags.BufferTime) {
941 // if we use message buffering, we must send away all message
942 // packets which have become too old...
948 /* ----------------------------------------------------------------------------
949 * Process message in the current Capability's inbox
950 * ------------------------------------------------------------------------- */
953 scheduleProcessInbox (Capability *cap USED_IF_THREADS)
955 #if defined(THREADED_RTS)
958 while (!emptyInbox(cap)) {
959 ACQUIRE_LOCK(&cap->lock);
961 cap->inbox = m->link;
962 RELEASE_LOCK(&cap->lock);
963 executeMessage(cap, (Message *)m);
968 /* ----------------------------------------------------------------------------
969 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
970 * ------------------------------------------------------------------------- */
972 #if defined(THREADED_RTS)
974 scheduleActivateSpark(Capability *cap)
978 createSparkThread(cap);
979 debugTrace(DEBUG_sched, "creating a spark thread");
982 #endif // PARALLEL_HASKELL || THREADED_RTS
984 /* ----------------------------------------------------------------------------
985 * After running a thread...
986 * ------------------------------------------------------------------------- */
989 schedulePostRunThread (Capability *cap, StgTSO *t)
991 // We have to be able to catch transactions that are in an
992 // infinite loop as a result of seeing an inconsistent view of
996 // [a,b] <- mapM readTVar [ta,tb]
997 // when (a == b) loop
999 // and a is never equal to b given a consistent view of memory.
1001 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1002 if (!stmValidateNestOfTransactions (t -> trec)) {
1003 debugTrace(DEBUG_sched | DEBUG_stm,
1004 "trec %p found wasting its time", t);
1006 // strip the stack back to the
1007 // ATOMICALLY_FRAME, aborting the (nested)
1008 // transaction, and saving the stack of any
1009 // partially-evaluated thunks on the heap.
1010 throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1012 // ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1016 /* some statistics gathering in the parallel case */
1019 /* -----------------------------------------------------------------------------
1020 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1021 * -------------------------------------------------------------------------- */
1024 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1026 // did the task ask for a large block?
1027 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1028 // if so, get one and push it on the front of the nursery.
1032 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1034 debugTrace(DEBUG_sched,
1035 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1036 (long)t->id, what_next_strs[t->what_next], blocks);
1038 // don't do this if the nursery is (nearly) full, we'll GC first.
1039 if (cap->r.rCurrentNursery->link != NULL ||
1040 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1041 // if the nursery has only one block.
1044 bd = allocGroup( blocks );
1046 cap->r.rNursery->n_blocks += blocks;
1048 // link the new group into the list
1049 bd->link = cap->r.rCurrentNursery;
1050 bd->u.back = cap->r.rCurrentNursery->u.back;
1051 if (cap->r.rCurrentNursery->u.back != NULL) {
1052 cap->r.rCurrentNursery->u.back->link = bd;
1054 cap->r.rNursery->blocks = bd;
1056 cap->r.rCurrentNursery->u.back = bd;
1058 // initialise it as a nursery block. We initialise the
1059 // step, gen_no, and flags field of *every* sub-block in
1060 // this large block, because this is easier than making
1061 // sure that we always find the block head of a large
1062 // block whenever we call Bdescr() (eg. evacuate() and
1063 // isAlive() in the GC would both have to do this, at
1067 for (x = bd; x < bd + blocks; x++) {
1068 initBdescr(x,g0,g0);
1074 // This assert can be a killer if the app is doing lots
1075 // of large block allocations.
1076 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1078 // now update the nursery to point to the new block
1079 cap->r.rCurrentNursery = bd;
1081 // we might be unlucky and have another thread get on the
1082 // run queue before us and steal the large block, but in that
1083 // case the thread will just end up requesting another large
1085 pushOnRunQueue(cap,t);
1086 return rtsFalse; /* not actually GC'ing */
1090 if (cap->r.rHpLim == NULL || cap->context_switch) {
1091 // Sometimes we miss a context switch, e.g. when calling
1092 // primitives in a tight loop, MAYBE_GC() doesn't check the
1093 // context switch flag, and we end up waiting for a GC.
1094 // See #1984, and concurrent/should_run/1984
1095 cap->context_switch = 0;
1096 addToRunQueue(cap,t);
1098 pushOnRunQueue(cap,t);
1101 /* actual GC is done at the end of the while loop in schedule() */
1104 /* -----------------------------------------------------------------------------
1105 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1106 * -------------------------------------------------------------------------- */
1109 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1111 /* just adjust the stack for this thread, then pop it back
1115 /* enlarge the stack */
1116 StgTSO *new_t = threadStackOverflow(cap, t);
1118 /* The TSO attached to this Task may have moved, so update the
1121 if (task->incall->tso == t) {
1122 task->incall->tso = new_t;
1124 pushOnRunQueue(cap,new_t);
1128 /* -----------------------------------------------------------------------------
1129 * Handle a thread that returned to the scheduler with ThreadYielding
1130 * -------------------------------------------------------------------------- */
1133 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1135 /* put the thread back on the run queue. Then, if we're ready to
1136 * GC, check whether this is the last task to stop. If so, wake
1137 * up the GC thread. getThread will block during a GC until the
1141 ASSERT(t->_link == END_TSO_QUEUE);
1143 // Shortcut if we're just switching evaluators: don't bother
1144 // doing stack squeezing (which can be expensive), just run the
1146 if (cap->context_switch == 0 && t->what_next != prev_what_next) {
1147 debugTrace(DEBUG_sched,
1148 "--<< thread %ld (%s) stopped to switch evaluators",
1149 (long)t->id, what_next_strs[t->what_next]);
1153 // Reset the context switch flag. We don't do this just before
1154 // running the thread, because that would mean we would lose ticks
1155 // during GC, which can lead to unfair scheduling (a thread hogs
1156 // the CPU because the tick always arrives during GC). This way
1157 // penalises threads that do a lot of allocation, but that seems
1158 // better than the alternative.
1159 cap->context_switch = 0;
1162 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1165 addToRunQueue(cap,t);
1170 /* -----------------------------------------------------------------------------
1171 * Handle a thread that returned to the scheduler with ThreadBlocked
1172 * -------------------------------------------------------------------------- */
1175 scheduleHandleThreadBlocked( StgTSO *t
1182 // We don't need to do anything. The thread is blocked, and it
1183 // has tidied up its stack and placed itself on whatever queue
1184 // it needs to be on.
1186 // ASSERT(t->why_blocked != NotBlocked);
1187 // Not true: for example,
1188 // - the thread may have woken itself up already, because
1189 // threadPaused() might have raised a blocked throwTo
1190 // exception, see maybePerformBlockedException().
1193 traceThreadStatus(DEBUG_sched, t);
1197 /* -----------------------------------------------------------------------------
1198 * Handle a thread that returned to the scheduler with ThreadFinished
1199 * -------------------------------------------------------------------------- */
1202 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1204 /* Need to check whether this was a main thread, and if so,
1205 * return with the return value.
1207 * We also end up here if the thread kills itself with an
1208 * uncaught exception, see Exception.cmm.
1211 // blocked exceptions can now complete, even if the thread was in
1212 // blocked mode (see #2910).
1213 awakenBlockedExceptionQueue (cap, t);
1216 // Check whether the thread that just completed was a bound
1217 // thread, and if so return with the result.
1219 // There is an assumption here that all thread completion goes
1220 // through this point; we need to make sure that if a thread
1221 // ends up in the ThreadKilled state, that it stays on the run
1222 // queue so it can be dealt with here.
1227 if (t->bound != task->incall) {
1228 #if !defined(THREADED_RTS)
1229 // Must be a bound thread that is not the topmost one. Leave
1230 // it on the run queue until the stack has unwound to the
1231 // point where we can deal with this. Leaving it on the run
1232 // queue also ensures that the garbage collector knows about
1233 // this thread and its return value (it gets dropped from the
1234 // step->threads list so there's no other way to find it).
1235 appendToRunQueue(cap,t);
1238 // this cannot happen in the threaded RTS, because a
1239 // bound thread can only be run by the appropriate Task.
1240 barf("finished bound thread that isn't mine");
1244 ASSERT(task->incall->tso == t);
1246 if (t->what_next == ThreadComplete) {
1248 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1249 *(task->ret) = (StgClosure *)task->incall->tso->sp[1];
1251 task->stat = Success;
1254 *(task->ret) = NULL;
1256 if (sched_state >= SCHED_INTERRUPTING) {
1257 if (heap_overflow) {
1258 task->stat = HeapExhausted;
1260 task->stat = Interrupted;
1263 task->stat = Killed;
1267 removeThreadLabel((StgWord)task->incall->tso->id);
1270 // We no longer consider this thread and task to be bound to
1271 // each other. The TSO lives on until it is GC'd, but the
1272 // task is about to be released by the caller, and we don't
1273 // want anyone following the pointer from the TSO to the
1274 // defunct task (which might have already been
1275 // re-used). This was a real bug: the GC updated
1276 // tso->bound->tso which lead to a deadlock.
1278 task->incall->tso = NULL;
1280 return rtsTrue; // tells schedule() to return
1286 /* -----------------------------------------------------------------------------
1287 * Perform a heap census
1288 * -------------------------------------------------------------------------- */
1291 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1293 // When we have +RTS -i0 and we're heap profiling, do a census at
1294 // every GC. This lets us get repeatable runs for debugging.
1295 if (performHeapProfile ||
1296 (RtsFlags.ProfFlags.profileInterval==0 &&
1297 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1304 /* -----------------------------------------------------------------------------
1305 * Perform a garbage collection if necessary
1306 * -------------------------------------------------------------------------- */
1309 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1311 rtsBool heap_census;
1313 /* extern static volatile StgWord waiting_for_gc;
1314 lives inside capability.c */
1315 rtsBool gc_type, prev_pending_gc;
1319 if (sched_state == SCHED_SHUTTING_DOWN) {
1320 // The final GC has already been done, and the system is
1321 // shutting down. We'll probably deadlock if we try to GC
1327 if (sched_state < SCHED_INTERRUPTING
1328 && RtsFlags.ParFlags.parGcEnabled
1329 && N >= RtsFlags.ParFlags.parGcGen
1330 && ! oldest_gen->mark)
1332 gc_type = PENDING_GC_PAR;
1334 gc_type = PENDING_GC_SEQ;
1337 // In order to GC, there must be no threads running Haskell code.
1338 // Therefore, the GC thread needs to hold *all* the capabilities,
1339 // and release them after the GC has completed.
1341 // This seems to be the simplest way: previous attempts involved
1342 // making all the threads with capabilities give up their
1343 // capabilities and sleep except for the *last* one, which
1344 // actually did the GC. But it's quite hard to arrange for all
1345 // the other tasks to sleep and stay asleep.
1348 /* Other capabilities are prevented from running yet more Haskell
1349 threads if waiting_for_gc is set. Tested inside
1350 yieldCapability() and releaseCapability() in Capability.c */
1352 prev_pending_gc = cas(&waiting_for_gc, 0, gc_type);
1353 if (prev_pending_gc) {
1355 debugTrace(DEBUG_sched, "someone else is trying to GC (%d)...",
1358 yieldCapability(&cap,task);
1359 } while (waiting_for_gc);
1360 return cap; // NOTE: task->cap might have changed here
1363 setContextSwitches();
1365 // The final shutdown GC is always single-threaded, because it's
1366 // possible that some of the Capabilities have no worker threads.
1368 if (gc_type == PENDING_GC_SEQ)
1370 traceEventRequestSeqGc(cap);
1374 traceEventRequestParGc(cap);
1375 debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1378 if (gc_type == PENDING_GC_SEQ)
1380 // single-threaded GC: grab all the capabilities
1381 for (i=0; i < n_capabilities; i++) {
1382 debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1383 if (cap != &capabilities[i]) {
1384 Capability *pcap = &capabilities[i];
1385 // we better hope this task doesn't get migrated to
1386 // another Capability while we're waiting for this one.
1387 // It won't, because load balancing happens while we have
1388 // all the Capabilities, but even so it's a slightly
1389 // unsavoury invariant.
1391 waitForReturnCapability(&pcap, task);
1392 if (pcap != &capabilities[i]) {
1393 barf("scheduleDoGC: got the wrong capability");
1400 // multi-threaded GC: make sure all the Capabilities donate one
1402 waitForGcThreads(cap);
1407 IF_DEBUG(scheduler, printAllThreads());
1409 delete_threads_and_gc:
1411 * We now have all the capabilities; if we're in an interrupting
1412 * state, then we should take the opportunity to delete all the
1413 * threads in the system.
1415 if (sched_state == SCHED_INTERRUPTING) {
1416 deleteAllThreads(cap);
1417 sched_state = SCHED_SHUTTING_DOWN;
1420 heap_census = scheduleNeedHeapProfile(rtsTrue);
1422 traceEventGcStart(cap);
1423 #if defined(THREADED_RTS)
1424 // reset waiting_for_gc *before* GC, so that when the GC threads
1425 // emerge they don't immediately re-enter the GC.
1427 GarbageCollect(force_major || heap_census, gc_type, cap);
1429 GarbageCollect(force_major || heap_census, 0, cap);
1431 traceEventGcEnd(cap);
1433 if (recent_activity == ACTIVITY_INACTIVE && force_major)
1435 // We are doing a GC because the system has been idle for a
1436 // timeslice and we need to check for deadlock. Record the
1437 // fact that we've done a GC and turn off the timer signal;
1438 // it will get re-enabled if we run any threads after the GC.
1439 recent_activity = ACTIVITY_DONE_GC;
1444 // the GC might have taken long enough for the timer to set
1445 // recent_activity = ACTIVITY_INACTIVE, but we aren't
1446 // necessarily deadlocked:
1447 recent_activity = ACTIVITY_YES;
1450 #if defined(THREADED_RTS)
1451 if (gc_type == PENDING_GC_PAR)
1453 releaseGCThreads(cap);
1458 debugTrace(DEBUG_sched, "performing heap census");
1460 performHeapProfile = rtsFalse;
1463 if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1464 // GC set the heap_overflow flag, so we should proceed with
1465 // an orderly shutdown now. Ultimately we want the main
1466 // thread to return to its caller with HeapExhausted, at which
1467 // point the caller should call hs_exit(). The first step is
1468 // to delete all the threads.
1470 // Another way to do this would be to raise an exception in
1471 // the main thread, which we really should do because it gives
1472 // the program a chance to clean up. But how do we find the
1473 // main thread? It should presumably be the same one that
1474 // gets ^C exceptions, but that's all done on the Haskell side
1475 // (GHC.TopHandler).
1476 sched_state = SCHED_INTERRUPTING;
1477 goto delete_threads_and_gc;
1482 Once we are all together... this would be the place to balance all
1483 spark pools. No concurrent stealing or adding of new sparks can
1484 occur. Should be defined in Sparks.c. */
1485 balanceSparkPoolsCaps(n_capabilities, capabilities);
1488 #if defined(THREADED_RTS)
1489 if (gc_type == PENDING_GC_SEQ) {
1490 // release our stash of capabilities.
1491 for (i = 0; i < n_capabilities; i++) {
1492 if (cap != &capabilities[i]) {
1493 task->cap = &capabilities[i];
1494 releaseCapability(&capabilities[i]);
1508 /* ---------------------------------------------------------------------------
1509 * Singleton fork(). Do not copy any running threads.
1510 * ------------------------------------------------------------------------- */
1513 forkProcess(HsStablePtr *entry
1514 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1519 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1525 #if defined(THREADED_RTS)
1526 if (RtsFlags.ParFlags.nNodes > 1) {
1527 errorBelch("forking not supported with +RTS -N<n> greater than 1");
1528 stg_exit(EXIT_FAILURE);
1532 debugTrace(DEBUG_sched, "forking!");
1534 // ToDo: for SMP, we should probably acquire *all* the capabilities
1537 // no funny business: hold locks while we fork, otherwise if some
1538 // other thread is holding a lock when the fork happens, the data
1539 // structure protected by the lock will forever be in an
1540 // inconsistent state in the child. See also #1391.
1541 ACQUIRE_LOCK(&sched_mutex);
1542 ACQUIRE_LOCK(&cap->lock);
1543 ACQUIRE_LOCK(&cap->running_task->lock);
1547 if (pid) { // parent
1549 RELEASE_LOCK(&sched_mutex);
1550 RELEASE_LOCK(&cap->lock);
1551 RELEASE_LOCK(&cap->running_task->lock);
1553 // just return the pid
1559 #if defined(THREADED_RTS)
1560 initMutex(&sched_mutex);
1561 initMutex(&cap->lock);
1562 initMutex(&cap->running_task->lock);
1565 // Now, all OS threads except the thread that forked are
1566 // stopped. We need to stop all Haskell threads, including
1567 // those involved in foreign calls. Also we need to delete
1568 // all Tasks, because they correspond to OS threads that are
1571 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1572 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1573 if (t->what_next == ThreadRelocated) {
1576 next = t->global_link;
1577 // don't allow threads to catch the ThreadKilled
1578 // exception, but we do want to raiseAsync() because these
1579 // threads may be evaluating thunks that we need later.
1580 deleteThread_(cap,t);
1582 // stop the GC from updating the InCall to point to
1583 // the TSO. This is only necessary because the
1584 // OSThread bound to the TSO has been killed, and
1585 // won't get a chance to exit in the usual way (see
1586 // also scheduleHandleThreadFinished).
1592 // Empty the run queue. It seems tempting to let all the
1593 // killed threads stay on the run queue as zombies to be
1594 // cleaned up later, but some of them correspond to bound
1595 // threads for which the corresponding Task does not exist.
1596 cap->run_queue_hd = END_TSO_QUEUE;
1597 cap->run_queue_tl = END_TSO_QUEUE;
1599 // Any suspended C-calling Tasks are no more, their OS threads
1601 cap->suspended_ccalls = NULL;
1603 // Empty the threads lists. Otherwise, the garbage
1604 // collector may attempt to resurrect some of these threads.
1605 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1606 generations[g].threads = END_TSO_QUEUE;
1609 discardTasksExcept(cap->running_task);
1611 #if defined(THREADED_RTS)
1612 // Wipe our spare workers list, they no longer exist. New
1613 // workers will be created if necessary.
1614 cap->spare_workers = NULL;
1615 cap->returning_tasks_hd = NULL;
1616 cap->returning_tasks_tl = NULL;
1619 // On Unix, all timers are reset in the child, so we need to start
1624 #if defined(THREADED_RTS)
1625 cap = ioManagerStartCap(cap);
1628 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1629 rts_checkSchedStatus("forkProcess",cap);
1632 hs_exit(); // clean up and exit
1633 stg_exit(EXIT_SUCCESS);
1635 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1636 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1640 /* ---------------------------------------------------------------------------
1641 * Delete all the threads in the system
1642 * ------------------------------------------------------------------------- */
1645 deleteAllThreads ( Capability *cap )
1647 // NOTE: only safe to call if we own all capabilities.
1652 debugTrace(DEBUG_sched,"deleting all threads");
1653 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1654 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1655 if (t->what_next == ThreadRelocated) {
1658 next = t->global_link;
1659 deleteThread(cap,t);
1664 // The run queue now contains a bunch of ThreadKilled threads. We
1665 // must not throw these away: the main thread(s) will be in there
1666 // somewhere, and the main scheduler loop has to deal with it.
1667 // Also, the run queue is the only thing keeping these threads from
1668 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1670 #if !defined(THREADED_RTS)
1671 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1672 ASSERT(sleeping_queue == END_TSO_QUEUE);
1676 /* -----------------------------------------------------------------------------
1677 Managing the suspended_ccalls list.
1678 Locks required: sched_mutex
1679 -------------------------------------------------------------------------- */
1682 suspendTask (Capability *cap, Task *task)
1686 incall = task->incall;
1687 ASSERT(incall->next == NULL && incall->prev == NULL);
1688 incall->next = cap->suspended_ccalls;
1689 incall->prev = NULL;
1690 if (cap->suspended_ccalls) {
1691 cap->suspended_ccalls->prev = incall;
1693 cap->suspended_ccalls = incall;
1697 recoverSuspendedTask (Capability *cap, Task *task)
1701 incall = task->incall;
1703 incall->prev->next = incall->next;
1705 ASSERT(cap->suspended_ccalls == incall);
1706 cap->suspended_ccalls = incall->next;
1709 incall->next->prev = incall->prev;
1711 incall->next = incall->prev = NULL;
1714 /* ---------------------------------------------------------------------------
1715 * Suspending & resuming Haskell threads.
1717 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1718 * its capability before calling the C function. This allows another
1719 * task to pick up the capability and carry on running Haskell
1720 * threads. It also means that if the C call blocks, it won't lock
1723 * The Haskell thread making the C call is put to sleep for the
1724 * duration of the call, on the susepended_ccalling_threads queue. We
1725 * give out a token to the task, which it can use to resume the thread
1726 * on return from the C function.
1727 * ------------------------------------------------------------------------- */
1730 suspendThread (StgRegTable *reg)
1737 StgWord32 saved_winerror;
1740 saved_errno = errno;
1742 saved_winerror = GetLastError();
1745 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1747 cap = regTableToCapability(reg);
1749 task = cap->running_task;
1750 tso = cap->r.rCurrentTSO;
1752 traceEventStopThread(cap, tso, THREAD_SUSPENDED_FOREIGN_CALL);
1754 // XXX this might not be necessary --SDM
1755 tso->what_next = ThreadRunGHC;
1757 threadPaused(cap,tso);
1759 if ((tso->flags & TSO_BLOCKEX) == 0) {
1760 tso->why_blocked = BlockedOnCCall;
1761 tso->flags |= TSO_BLOCKEX;
1762 tso->flags &= ~TSO_INTERRUPTIBLE;
1764 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1767 // Hand back capability
1768 task->incall->suspended_tso = tso;
1769 task->incall->suspended_cap = cap;
1771 ACQUIRE_LOCK(&cap->lock);
1773 suspendTask(cap,task);
1774 cap->in_haskell = rtsFalse;
1775 releaseCapability_(cap,rtsFalse);
1777 RELEASE_LOCK(&cap->lock);
1779 errno = saved_errno;
1781 SetLastError(saved_winerror);
1787 resumeThread (void *task_)
1795 StgWord32 saved_winerror;
1798 saved_errno = errno;
1800 saved_winerror = GetLastError();
1803 incall = task->incall;
1804 cap = incall->suspended_cap;
1807 // Wait for permission to re-enter the RTS with the result.
1808 waitForReturnCapability(&cap,task);
1809 // we might be on a different capability now... but if so, our
1810 // entry on the suspended_ccalls list will also have been
1813 // Remove the thread from the suspended list
1814 recoverSuspendedTask(cap,task);
1816 tso = incall->suspended_tso;
1817 incall->suspended_tso = NULL;
1818 incall->suspended_cap = NULL;
1819 tso->_link = END_TSO_QUEUE; // no write barrier reqd
1821 traceEventRunThread(cap, tso);
1823 if (tso->why_blocked == BlockedOnCCall) {
1824 // avoid locking the TSO if we don't have to
1825 if (tso->blocked_exceptions != END_BLOCKED_EXCEPTIONS_QUEUE) {
1826 awakenBlockedExceptionQueue(cap,tso);
1828 tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
1831 /* Reset blocking status */
1832 tso->why_blocked = NotBlocked;
1834 cap->r.rCurrentTSO = tso;
1835 cap->in_haskell = rtsTrue;
1836 errno = saved_errno;
1838 SetLastError(saved_winerror);
1841 /* We might have GC'd, mark the TSO dirty again */
1844 IF_DEBUG(sanity, checkTSO(tso));
1849 /* ---------------------------------------------------------------------------
1852 * scheduleThread puts a thread on the end of the runnable queue.
1853 * This will usually be done immediately after a thread is created.
1854 * The caller of scheduleThread must create the thread using e.g.
1855 * createThread and push an appropriate closure
1856 * on this thread's stack before the scheduler is invoked.
1857 * ------------------------------------------------------------------------ */
1860 scheduleThread(Capability *cap, StgTSO *tso)
1862 // The thread goes at the *end* of the run-queue, to avoid possible
1863 // starvation of any threads already on the queue.
1864 appendToRunQueue(cap,tso);
1868 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
1870 #if defined(THREADED_RTS)
1871 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
1872 // move this thread from now on.
1873 cpu %= RtsFlags.ParFlags.nNodes;
1874 if (cpu == cap->no) {
1875 appendToRunQueue(cap,tso);
1877 traceEventMigrateThread (cap, tso, capabilities[cpu].no);
1878 wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
1881 appendToRunQueue(cap,tso);
1886 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
1891 // We already created/initialised the Task
1892 task = cap->running_task;
1894 // This TSO is now a bound thread; make the Task and TSO
1895 // point to each other.
1896 tso->bound = task->incall;
1899 task->incall->tso = tso;
1901 task->stat = NoStatus;
1903 appendToRunQueue(cap,tso);
1906 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)id);
1908 cap = schedule(cap,task);
1910 ASSERT(task->stat != NoStatus);
1911 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
1913 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)id);
1917 /* ----------------------------------------------------------------------------
1919 * ------------------------------------------------------------------------- */
1921 #if defined(THREADED_RTS)
1922 void scheduleWorker (Capability *cap, Task *task)
1924 // schedule() runs without a lock.
1925 cap = schedule(cap,task);
1927 // On exit from schedule(), we have a Capability, but possibly not
1928 // the same one we started with.
1930 // During shutdown, the requirement is that after all the
1931 // Capabilities are shut down, all workers that are shutting down
1932 // have finished workerTaskStop(). This is why we hold on to
1933 // cap->lock until we've finished workerTaskStop() below.
1935 // There may be workers still involved in foreign calls; those
1936 // will just block in waitForReturnCapability() because the
1937 // Capability has been shut down.
1939 ACQUIRE_LOCK(&cap->lock);
1940 releaseCapability_(cap,rtsFalse);
1941 workerTaskStop(task);
1942 RELEASE_LOCK(&cap->lock);
1946 /* ---------------------------------------------------------------------------
1949 * Initialise the scheduler. This resets all the queues - if the
1950 * queues contained any threads, they'll be garbage collected at the
1953 * ------------------------------------------------------------------------ */
1958 #if !defined(THREADED_RTS)
1959 blocked_queue_hd = END_TSO_QUEUE;
1960 blocked_queue_tl = END_TSO_QUEUE;
1961 sleeping_queue = END_TSO_QUEUE;
1964 sched_state = SCHED_RUNNING;
1965 recent_activity = ACTIVITY_YES;
1967 #if defined(THREADED_RTS)
1968 /* Initialise the mutex and condition variables used by
1970 initMutex(&sched_mutex);
1973 ACQUIRE_LOCK(&sched_mutex);
1975 /* A capability holds the state a native thread needs in
1976 * order to execute STG code. At least one capability is
1977 * floating around (only THREADED_RTS builds have more than one).
1983 #if defined(THREADED_RTS)
1987 RELEASE_LOCK(&sched_mutex);
1989 #if defined(THREADED_RTS)
1991 * Eagerly start one worker to run each Capability, except for
1992 * Capability 0. The idea is that we're probably going to start a
1993 * bound thread on Capability 0 pretty soon, so we don't want a
1994 * worker task hogging it.
1999 for (i = 1; i < n_capabilities; i++) {
2000 cap = &capabilities[i];
2001 ACQUIRE_LOCK(&cap->lock);
2002 startWorkerTask(cap);
2003 RELEASE_LOCK(&cap->lock);
2011 rtsBool wait_foreign
2012 #if !defined(THREADED_RTS)
2013 __attribute__((unused))
2016 /* see Capability.c, shutdownCapability() */
2020 task = newBoundTask();
2022 // If we haven't killed all the threads yet, do it now.
2023 if (sched_state < SCHED_SHUTTING_DOWN) {
2024 sched_state = SCHED_INTERRUPTING;
2025 waitForReturnCapability(&task->cap,task);
2026 scheduleDoGC(task->cap,task,rtsFalse);
2027 ASSERT(task->incall->tso == NULL);
2028 releaseCapability(task->cap);
2030 sched_state = SCHED_SHUTTING_DOWN;
2032 #if defined(THREADED_RTS)
2036 for (i = 0; i < n_capabilities; i++) {
2037 ASSERT(task->incall->tso == NULL);
2038 shutdownCapability(&capabilities[i], task, wait_foreign);
2043 boundTaskExiting(task);
2047 freeScheduler( void )
2051 ACQUIRE_LOCK(&sched_mutex);
2052 still_running = freeTaskManager();
2053 // We can only free the Capabilities if there are no Tasks still
2054 // running. We might have a Task about to return from a foreign
2055 // call into waitForReturnCapability(), for example (actually,
2056 // this should be the *only* thing that a still-running Task can
2057 // do at this point, and it will block waiting for the
2059 if (still_running == 0) {
2061 if (n_capabilities != 1) {
2062 stgFree(capabilities);
2065 RELEASE_LOCK(&sched_mutex);
2066 #if defined(THREADED_RTS)
2067 closeMutex(&sched_mutex);
2071 /* -----------------------------------------------------------------------------
2074 This is the interface to the garbage collector from Haskell land.
2075 We provide this so that external C code can allocate and garbage
2076 collect when called from Haskell via _ccall_GC.
2077 -------------------------------------------------------------------------- */
2080 performGC_(rtsBool force_major)
2084 // We must grab a new Task here, because the existing Task may be
2085 // associated with a particular Capability, and chained onto the
2086 // suspended_ccalls queue.
2087 task = newBoundTask();
2089 waitForReturnCapability(&task->cap,task);
2090 scheduleDoGC(task->cap,task,force_major);
2091 releaseCapability(task->cap);
2092 boundTaskExiting(task);
2098 performGC_(rtsFalse);
2102 performMajorGC(void)
2104 performGC_(rtsTrue);
2107 /* -----------------------------------------------------------------------------
2110 If the thread has reached its maximum stack size, then raise the
2111 StackOverflow exception in the offending thread. Otherwise
2112 relocate the TSO into a larger chunk of memory and adjust its stack
2114 -------------------------------------------------------------------------- */
2117 threadStackOverflow(Capability *cap, StgTSO *tso)
2119 nat new_stack_size, stack_words;
2124 IF_DEBUG(sanity,checkTSO(tso));
2126 if (tso->stack_size >= tso->max_stack_size
2127 && !(tso->flags & TSO_BLOCKEX)) {
2128 // NB. never raise a StackOverflow exception if the thread is
2129 // inside Control.Exceptino.block. It is impractical to protect
2130 // against stack overflow exceptions, since virtually anything
2131 // can raise one (even 'catch'), so this is the only sensible
2132 // thing to do here. See bug #767.
2135 if (tso->flags & TSO_SQUEEZED) {
2138 // #3677: In a stack overflow situation, stack squeezing may
2139 // reduce the stack size, but we don't know whether it has been
2140 // reduced enough for the stack check to succeed if we try
2141 // again. Fortunately stack squeezing is idempotent, so all we
2142 // need to do is record whether *any* squeezing happened. If we
2143 // are at the stack's absolute -K limit, and stack squeezing
2144 // happened, then we try running the thread again. The
2145 // TSO_SQUEEZED flag is set by threadPaused() to tell us whether
2146 // squeezing happened or not.
2148 debugTrace(DEBUG_gc,
2149 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2150 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2152 /* If we're debugging, just print out the top of the stack */
2153 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2156 // Send this thread the StackOverflow exception
2157 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2162 // We also want to avoid enlarging the stack if squeezing has
2163 // already released some of it. However, we don't want to get into
2164 // a pathalogical situation where a thread has a nearly full stack
2165 // (near its current limit, but not near the absolute -K limit),
2166 // keeps allocating a little bit, squeezing removes a little bit,
2167 // and then it runs again. So to avoid this, if we squeezed *and*
2168 // there is still less than BLOCK_SIZE_W words free, then we enlarge
2169 // the stack anyway.
2170 if ((tso->flags & TSO_SQUEEZED) &&
2171 ((W_)(tso->sp - tso->stack) >= BLOCK_SIZE_W)) {
2175 /* Try to double the current stack size. If that takes us over the
2176 * maximum stack size for this thread, then use the maximum instead
2177 * (that is, unless we're already at or over the max size and we
2178 * can't raise the StackOverflow exception (see above), in which
2179 * case just double the size). Finally round up so the TSO ends up as
2180 * a whole number of blocks.
2182 if (tso->stack_size >= tso->max_stack_size) {
2183 new_stack_size = tso->stack_size * 2;
2185 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2187 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2188 TSO_STRUCT_SIZE)/sizeof(W_);
2189 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2190 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2192 debugTrace(DEBUG_sched,
2193 "increasing stack size from %ld words to %d.",
2194 (long)tso->stack_size, new_stack_size);
2196 dest = (StgTSO *)allocate(cap,new_tso_size);
2197 TICK_ALLOC_TSO(new_stack_size,0);
2199 /* copy the TSO block and the old stack into the new area */
2200 memcpy(dest,tso,TSO_STRUCT_SIZE);
2201 stack_words = tso->stack + tso->stack_size - tso->sp;
2202 new_sp = (P_)dest + new_tso_size - stack_words;
2203 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2205 /* relocate the stack pointers... */
2207 dest->stack_size = new_stack_size;
2209 /* Mark the old TSO as relocated. We have to check for relocated
2210 * TSOs in the garbage collector and any primops that deal with TSOs.
2212 * It's important to set the sp value to just beyond the end
2213 * of the stack, so we don't attempt to scavenge any part of the
2216 setTSOLink(cap,tso,dest);
2217 write_barrier(); // other threads seeing ThreadRelocated will look at _link
2218 tso->what_next = ThreadRelocated;
2219 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2220 tso->why_blocked = NotBlocked;
2222 IF_DEBUG(sanity,checkTSO(dest));
2224 IF_DEBUG(scheduler,printTSO(dest));
2231 threadStackUnderflow (Capability *cap, Task *task, StgTSO *tso)
2233 bdescr *bd, *new_bd;
2234 lnat free_w, tso_size_w;
2237 tso_size_w = tso_sizeW(tso);
2239 if (tso_size_w < MBLOCK_SIZE_W ||
2240 // TSO is less than 2 mblocks (since the first mblock is
2241 // shorter than MBLOCK_SIZE_W)
2242 (tso_size_w - BLOCKS_PER_MBLOCK*BLOCK_SIZE_W) % MBLOCK_SIZE_W != 0 ||
2243 // or TSO is not a whole number of megablocks (ensuring
2244 // precondition of splitLargeBlock() below)
2245 (tso_size_w <= round_up_to_mblocks(RtsFlags.GcFlags.initialStkSize)) ||
2246 // or TSO is smaller than the minimum stack size (rounded up)
2247 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2248 // or stack is using more than 1/4 of the available space
2254 // this is the number of words we'll free
2255 free_w = round_to_mblocks(tso_size_w/2);
2257 bd = Bdescr((StgPtr)tso);
2258 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2259 bd->free = bd->start + TSO_STRUCT_SIZEW;
2261 new_tso = (StgTSO *)new_bd->start;
2262 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2263 new_tso->stack_size = new_bd->free - new_tso->stack;
2265 // The original TSO was dirty and probably on the mutable
2266 // list. The new TSO is not yet on the mutable list, so we better
2269 new_tso->flags &= ~TSO_LINK_DIRTY;
2270 dirty_TSO(cap, new_tso);
2272 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2273 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2275 tso->_link = new_tso; // no write barrier reqd: same generation
2276 write_barrier(); // other threads seeing ThreadRelocated will look at _link
2277 tso->what_next = ThreadRelocated;
2279 // The TSO attached to this Task may have moved, so update the
2281 if (task->incall->tso == tso) {
2282 task->incall->tso = new_tso;
2285 IF_DEBUG(sanity,checkTSO(new_tso));
2290 /* ---------------------------------------------------------------------------
2292 - usually called inside a signal handler so it mustn't do anything fancy.
2293 ------------------------------------------------------------------------ */
2296 interruptStgRts(void)
2298 sched_state = SCHED_INTERRUPTING;
2299 setContextSwitches();
2300 #if defined(THREADED_RTS)
2305 /* -----------------------------------------------------------------------------
2308 This function causes at least one OS thread to wake up and run the
2309 scheduler loop. It is invoked when the RTS might be deadlocked, or
2310 an external event has arrived that may need servicing (eg. a
2311 keyboard interrupt).
2313 In the single-threaded RTS we don't do anything here; we only have
2314 one thread anyway, and the event that caused us to want to wake up
2315 will have interrupted any blocking system call in progress anyway.
2316 -------------------------------------------------------------------------- */
2318 #if defined(THREADED_RTS)
2319 void wakeUpRts(void)
2321 // This forces the IO Manager thread to wakeup, which will
2322 // in turn ensure that some OS thread wakes up and runs the
2323 // scheduler loop, which will cause a GC and deadlock check.
2328 /* -----------------------------------------------------------------------------
2331 This is used for interruption (^C) and forking, and corresponds to
2332 raising an exception but without letting the thread catch the
2334 -------------------------------------------------------------------------- */
2337 deleteThread (Capability *cap STG_UNUSED, StgTSO *tso)
2339 // NOTE: must only be called on a TSO that we have exclusive
2340 // access to, because we will call throwToSingleThreaded() below.
2341 // The TSO must be on the run queue of the Capability we own, or
2342 // we must own all Capabilities.
2344 if (tso->why_blocked != BlockedOnCCall &&
2345 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2346 throwToSingleThreaded(tso->cap,tso,NULL);
2350 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2352 deleteThread_(Capability *cap, StgTSO *tso)
2353 { // for forkProcess only:
2354 // like deleteThread(), but we delete threads in foreign calls, too.
2356 if (tso->why_blocked == BlockedOnCCall ||
2357 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2358 unblockOne(cap,tso);
2359 tso->what_next = ThreadKilled;
2361 deleteThread(cap,tso);
2366 /* -----------------------------------------------------------------------------
2367 raiseExceptionHelper
2369 This function is called by the raise# primitve, just so that we can
2370 move some of the tricky bits of raising an exception from C-- into
2371 C. Who knows, it might be a useful re-useable thing here too.
2372 -------------------------------------------------------------------------- */
2375 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2377 Capability *cap = regTableToCapability(reg);
2378 StgThunk *raise_closure = NULL;
2380 StgRetInfoTable *info;
2382 // This closure represents the expression 'raise# E' where E
2383 // is the exception raise. It is used to overwrite all the
2384 // thunks which are currently under evaluataion.
2387 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2388 // LDV profiling: stg_raise_info has THUNK as its closure
2389 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2390 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2391 // 1 does not cause any problem unless profiling is performed.
2392 // However, when LDV profiling goes on, we need to linearly scan
2393 // small object pool, where raise_closure is stored, so we should
2394 // use MIN_UPD_SIZE.
2396 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2397 // sizeofW(StgClosure)+1);
2401 // Walk up the stack, looking for the catch frame. On the way,
2402 // we update any closures pointed to from update frames with the
2403 // raise closure that we just built.
2407 info = get_ret_itbl((StgClosure *)p);
2408 next = p + stack_frame_sizeW((StgClosure *)p);
2409 switch (info->i.type) {
2412 // Only create raise_closure if we need to.
2413 if (raise_closure == NULL) {
2415 (StgThunk *)allocate(cap,sizeofW(StgThunk)+1);
2416 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2417 raise_closure->payload[0] = exception;
2419 updateThunk(cap, tso, ((StgUpdateFrame *)p)->updatee,
2420 (StgClosure *)raise_closure);
2424 case ATOMICALLY_FRAME:
2425 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2427 return ATOMICALLY_FRAME;
2433 case CATCH_STM_FRAME:
2434 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2436 return CATCH_STM_FRAME;
2442 case CATCH_RETRY_FRAME:
2451 /* -----------------------------------------------------------------------------
2452 findRetryFrameHelper
2454 This function is called by the retry# primitive. It traverses the stack
2455 leaving tso->sp referring to the frame which should handle the retry.
2457 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2458 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2460 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2461 create) because retries are not considered to be exceptions, despite the
2462 similar implementation.
2464 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2465 not be created within memory transactions.
2466 -------------------------------------------------------------------------- */
2469 findRetryFrameHelper (StgTSO *tso)
2472 StgRetInfoTable *info;
2476 info = get_ret_itbl((StgClosure *)p);
2477 next = p + stack_frame_sizeW((StgClosure *)p);
2478 switch (info->i.type) {
2480 case ATOMICALLY_FRAME:
2481 debugTrace(DEBUG_stm,
2482 "found ATOMICALLY_FRAME at %p during retry", p);
2484 return ATOMICALLY_FRAME;
2486 case CATCH_RETRY_FRAME:
2487 debugTrace(DEBUG_stm,
2488 "found CATCH_RETRY_FRAME at %p during retrry", p);
2490 return CATCH_RETRY_FRAME;
2492 case CATCH_STM_FRAME: {
2493 StgTRecHeader *trec = tso -> trec;
2494 StgTRecHeader *outer = trec -> enclosing_trec;
2495 debugTrace(DEBUG_stm,
2496 "found CATCH_STM_FRAME at %p during retry", p);
2497 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2498 stmAbortTransaction(tso -> cap, trec);
2499 stmFreeAbortedTRec(tso -> cap, trec);
2500 tso -> trec = outer;
2507 ASSERT(info->i.type != CATCH_FRAME);
2508 ASSERT(info->i.type != STOP_FRAME);
2515 /* -----------------------------------------------------------------------------
2516 resurrectThreads is called after garbage collection on the list of
2517 threads found to be garbage. Each of these threads will be woken
2518 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2519 on an MVar, or NonTermination if the thread was blocked on a Black
2522 Locks: assumes we hold *all* the capabilities.
2523 -------------------------------------------------------------------------- */
2526 resurrectThreads (StgTSO *threads)
2532 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2533 next = tso->global_link;
2535 gen = Bdescr((P_)tso)->gen;
2536 tso->global_link = gen->threads;
2539 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2541 // Wake up the thread on the Capability it was last on
2544 switch (tso->why_blocked) {
2546 /* Called by GC - sched_mutex lock is currently held. */
2547 throwToSingleThreaded(cap, tso,
2548 (StgClosure *)blockedIndefinitelyOnMVar_closure);
2550 case BlockedOnBlackHole:
2551 throwToSingleThreaded(cap, tso,
2552 (StgClosure *)nonTermination_closure);
2555 throwToSingleThreaded(cap, tso,
2556 (StgClosure *)blockedIndefinitelyOnSTM_closure);
2559 /* This might happen if the thread was blocked on a black hole
2560 * belonging to a thread that we've just woken up (raiseAsync
2561 * can wake up threads, remember...).
2565 barf("resurrectThreads: thread blocked in a strange way: %d",