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);
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 Main scheduling loop.
164 We use round-robin scheduling, each thread returning to the
165 scheduler loop when one of these conditions is detected:
168 * timer expires (thread yields)
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).
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.
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.
195 ------------------------------------------------------------------------ */
198 schedule (Capability *initialCapability, Task *task)
202 StgThreadReturnCode ret;
205 #if defined(THREADED_RTS)
206 rtsBool first = rtsTrue;
209 cap = initialCapability;
211 // Pre-condition: this task owns initialCapability.
212 // The sched_mutex is *NOT* held
213 // NB. on return, we still hold a capability.
215 debugTrace (DEBUG_sched, "cap %d: schedule()", initialCapability->no);
219 // -----------------------------------------------------------
220 // Scheduler loop starts here:
224 // Check whether we have re-entered the RTS from Haskell without
225 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
227 if (cap->in_haskell) {
228 errorBelch("schedule: re-entered unsafely.\n"
229 " Perhaps a 'foreign import unsafe' should be 'safe'?");
230 stg_exit(EXIT_FAILURE);
233 // The interruption / shutdown sequence.
235 // In order to cleanly shut down the runtime, we want to:
236 // * make sure that all main threads return to their callers
237 // with the state 'Interrupted'.
238 // * clean up all OS threads assocated with the runtime
239 // * free all memory etc.
241 // So the sequence for ^C goes like this:
243 // * ^C handler sets sched_state := SCHED_INTERRUPTING and
244 // arranges for some Capability to wake up
246 // * all threads in the system are halted, and the zombies are
247 // placed on the run queue for cleaning up. We acquire all
248 // the capabilities in order to delete the threads, this is
249 // done by scheduleDoGC() for convenience (because GC already
250 // needs to acquire all the capabilities). We can't kill
251 // threads involved in foreign calls.
253 // * somebody calls shutdownHaskell(), which calls exitScheduler()
255 // * sched_state := SCHED_SHUTTING_DOWN
257 // * all workers exit when the run queue on their capability
258 // drains. All main threads will also exit when their TSO
259 // reaches the head of the run queue and they can return.
261 // * eventually all Capabilities will shut down, and the RTS can
264 // * We might be left with threads blocked in foreign calls,
265 // we should really attempt to kill these somehow (TODO);
267 switch (sched_state) {
270 case SCHED_INTERRUPTING:
271 debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
272 #if defined(THREADED_RTS)
273 discardSparksCap(cap);
275 /* scheduleDoGC() deletes all the threads */
276 cap = scheduleDoGC(cap,task,rtsFalse);
278 // after scheduleDoGC(), we must be shutting down. Either some
279 // other Capability did the final GC, or we did it above,
280 // either way we can fall through to the SCHED_SHUTTING_DOWN
282 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
285 case SCHED_SHUTTING_DOWN:
286 debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
287 // If we are a worker, just exit. If we're a bound thread
288 // then we will exit below when we've removed our TSO from
290 if (!isBoundTask(task) && emptyRunQueue(cap)) {
295 barf("sched_state: %d", sched_state);
298 scheduleFindWork(cap);
300 /* work pushing, currently relevant only for THREADED_RTS:
301 (pushes threads, wakes up idle capabilities for stealing) */
302 schedulePushWork(cap,task);
304 scheduleDetectDeadlock(cap,task);
306 #if defined(THREADED_RTS)
307 cap = task->cap; // reload cap, it might have changed
310 // Normally, the only way we can get here with no threads to
311 // run is if a keyboard interrupt received during
312 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
313 // Additionally, it is not fatal for the
314 // threaded RTS to reach here with no threads to run.
316 // win32: might be here due to awaitEvent() being abandoned
317 // as a result of a console event having been delivered.
319 #if defined(THREADED_RTS)
323 // // don't yield the first time, we want a chance to run this
324 // // thread for a bit, even if there are others banging at the
327 // ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
330 scheduleYield(&cap,task);
332 if (emptyRunQueue(cap)) continue; // look for work again
335 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
336 if ( emptyRunQueue(cap) ) {
337 ASSERT(sched_state >= SCHED_INTERRUPTING);
342 // Get a thread to run
344 t = popRunQueue(cap);
346 // Sanity check the thread we're about to run. This can be
347 // expensive if there is lots of thread switching going on...
348 IF_DEBUG(sanity,checkTSO(t));
350 #if defined(THREADED_RTS)
351 // Check whether we can run this thread in the current task.
352 // If not, we have to pass our capability to the right task.
354 InCall *bound = t->bound;
357 if (bound->task == task) {
358 // yes, the Haskell thread is bound to the current native thread
360 debugTrace(DEBUG_sched,
361 "thread %lu bound to another OS thread",
362 (unsigned long)t->id);
363 // no, bound to a different Haskell thread: pass to that thread
364 pushOnRunQueue(cap,t);
368 // The thread we want to run is unbound.
369 if (task->incall->tso) {
370 debugTrace(DEBUG_sched,
371 "this OS thread cannot run thread %lu",
372 (unsigned long)t->id);
373 // no, the current native thread is bound to a different
374 // Haskell thread, so pass it to any worker thread
375 pushOnRunQueue(cap,t);
382 // If we're shutting down, and this thread has not yet been
383 // killed, kill it now. This sometimes happens when a finalizer
384 // thread is created by the final GC, or a thread previously
385 // in a foreign call returns.
386 if (sched_state >= SCHED_INTERRUPTING &&
387 !(t->what_next == ThreadComplete || t->what_next == ThreadKilled)) {
391 /* context switches are initiated by the timer signal, unless
392 * the user specified "context switch as often as possible", with
395 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
396 && !emptyThreadQueues(cap)) {
397 cap->context_switch = 1;
402 // CurrentTSO is the thread to run. t might be different if we
403 // loop back to run_thread, so make sure to set CurrentTSO after
405 cap->r.rCurrentTSO = t;
407 startHeapProfTimer();
409 // ----------------------------------------------------------------------
410 // Run the current thread
412 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
413 ASSERT(t->cap == cap);
414 ASSERT(t->bound ? t->bound->task->cap == cap : 1);
416 prev_what_next = t->what_next;
418 errno = t->saved_errno;
420 SetLastError(t->saved_winerror);
423 cap->in_haskell = rtsTrue;
427 #if defined(THREADED_RTS)
428 if (recent_activity == ACTIVITY_DONE_GC) {
429 // ACTIVITY_DONE_GC means we turned off the timer signal to
430 // conserve power (see #1623). Re-enable it here.
432 prev = xchg((P_)&recent_activity, ACTIVITY_YES);
433 if (prev == ACTIVITY_DONE_GC) {
436 } else if (recent_activity != ACTIVITY_INACTIVE) {
437 // If we reached ACTIVITY_INACTIVE, then don't reset it until
438 // we've done the GC. The thread running here might just be
439 // the IO manager thread that handle_tick() woke up via
441 recent_activity = ACTIVITY_YES;
445 traceEventRunThread(cap, t);
447 switch (prev_what_next) {
451 /* Thread already finished, return to scheduler. */
452 ret = ThreadFinished;
458 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
459 cap = regTableToCapability(r);
464 case ThreadInterpret:
465 cap = interpretBCO(cap);
470 barf("schedule: invalid what_next field");
473 cap->in_haskell = rtsFalse;
475 // The TSO might have moved, eg. if it re-entered the RTS and a GC
476 // happened. So find the new location:
477 t = cap->r.rCurrentTSO;
479 // And save the current errno in this thread.
480 // XXX: possibly bogus for SMP because this thread might already
481 // be running again, see code below.
482 t->saved_errno = errno;
484 // Similarly for Windows error code
485 t->saved_winerror = GetLastError();
488 traceEventStopThread(cap, t, ret);
490 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
491 ASSERT(t->cap == cap);
493 // ----------------------------------------------------------------------
495 // Costs for the scheduler are assigned to CCS_SYSTEM
497 #if defined(PROFILING)
501 schedulePostRunThread(cap,t);
503 if (ret != StackOverflow) {
504 t = threadStackUnderflow(cap,task,t);
507 ready_to_gc = rtsFalse;
511 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
515 scheduleHandleStackOverflow(cap,task,t);
519 if (scheduleHandleYield(cap, t, prev_what_next)) {
520 // shortcut for switching between compiler/interpreter:
526 scheduleHandleThreadBlocked(t);
530 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
531 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
535 barf("schedule: invalid thread return code %d", (int)ret);
538 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
539 cap = scheduleDoGC(cap,task,rtsFalse);
541 } /* end of while() */
544 /* -----------------------------------------------------------------------------
545 * Run queue operations
546 * -------------------------------------------------------------------------- */
549 removeFromRunQueue (Capability *cap, StgTSO *tso)
551 if (tso->block_info.prev == END_TSO_QUEUE) {
552 ASSERT(cap->run_queue_hd == tso);
553 cap->run_queue_hd = tso->_link;
555 setTSOLink(cap, tso->block_info.prev, tso->_link);
557 if (tso->_link == END_TSO_QUEUE) {
558 ASSERT(cap->run_queue_tl == tso);
559 cap->run_queue_tl = tso->block_info.prev;
561 setTSOPrev(cap, tso->_link, tso->block_info.prev);
563 tso->_link = tso->block_info.prev = END_TSO_QUEUE;
565 IF_DEBUG(sanity, checkRunQueue(cap));
568 /* ----------------------------------------------------------------------------
569 * Setting up the scheduler loop
570 * ------------------------------------------------------------------------- */
573 schedulePreLoop(void)
575 // initialisation for scheduler - what cannot go into initScheduler()
578 /* -----------------------------------------------------------------------------
581 * Search for work to do, and handle messages from elsewhere.
582 * -------------------------------------------------------------------------- */
585 scheduleFindWork (Capability *cap)
587 scheduleStartSignalHandlers(cap);
589 scheduleProcessInbox(cap);
591 scheduleCheckBlockedThreads(cap);
593 #if defined(THREADED_RTS)
594 if (emptyRunQueue(cap)) { scheduleActivateSpark(cap); }
598 #if defined(THREADED_RTS)
599 STATIC_INLINE rtsBool
600 shouldYieldCapability (Capability *cap, Task *task)
602 // we need to yield this capability to someone else if..
603 // - another thread is initiating a GC
604 // - another Task is returning from a foreign call
605 // - the thread at the head of the run queue cannot be run
606 // by this Task (it is bound to another Task, or it is unbound
607 // and this task it bound).
608 return (waiting_for_gc ||
609 cap->returning_tasks_hd != NULL ||
610 (!emptyRunQueue(cap) && (task->incall->tso == NULL
611 ? cap->run_queue_hd->bound != NULL
612 : cap->run_queue_hd->bound != task->incall)));
615 // This is the single place where a Task goes to sleep. There are
616 // two reasons it might need to sleep:
617 // - there are no threads to run
618 // - we need to yield this Capability to someone else
619 // (see shouldYieldCapability())
621 // Careful: the scheduler loop is quite delicate. Make sure you run
622 // the tests in testsuite/concurrent (all ways) after modifying this,
623 // and also check the benchmarks in nofib/parallel for regressions.
626 scheduleYield (Capability **pcap, Task *task)
628 Capability *cap = *pcap;
630 // if we have work, and we don't need to give up the Capability, continue.
632 if (!shouldYieldCapability(cap,task) &&
633 (!emptyRunQueue(cap) ||
635 sched_state >= SCHED_INTERRUPTING))
638 // otherwise yield (sleep), and keep yielding if necessary.
640 yieldCapability(&cap,task);
642 while (shouldYieldCapability(cap,task));
644 // note there may still be no threads on the run queue at this
645 // point, the caller has to check.
652 /* -----------------------------------------------------------------------------
655 * Push work to other Capabilities if we have some.
656 * -------------------------------------------------------------------------- */
659 schedulePushWork(Capability *cap USED_IF_THREADS,
660 Task *task USED_IF_THREADS)
662 /* following code not for PARALLEL_HASKELL. I kept the call general,
663 future GUM versions might use pushing in a distributed setup */
664 #if defined(THREADED_RTS)
666 Capability *free_caps[n_capabilities], *cap0;
669 // migration can be turned off with +RTS -qm
670 if (!RtsFlags.ParFlags.migrate) return;
672 // Check whether we have more threads on our run queue, or sparks
673 // in our pool, that we could hand to another Capability.
674 if (cap->run_queue_hd == END_TSO_QUEUE) {
675 if (sparkPoolSizeCap(cap) < 2) return;
677 if (cap->run_queue_hd->_link == END_TSO_QUEUE &&
678 sparkPoolSizeCap(cap) < 1) return;
681 // First grab as many free Capabilities as we can.
682 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
683 cap0 = &capabilities[i];
684 if (cap != cap0 && tryGrabCapability(cap0,task)) {
685 if (!emptyRunQueue(cap0)
686 || cap->returning_tasks_hd != NULL
687 || cap->inbox != (Message*)END_TSO_QUEUE) {
688 // it already has some work, we just grabbed it at
689 // the wrong moment. Or maybe it's deadlocked!
690 releaseCapability(cap0);
692 free_caps[n_free_caps++] = cap0;
697 // we now have n_free_caps free capabilities stashed in
698 // free_caps[]. Share our run queue equally with them. This is
699 // probably the simplest thing we could do; improvements we might
700 // want to do include:
702 // - giving high priority to moving relatively new threads, on
703 // the gournds that they haven't had time to build up a
704 // working set in the cache on this CPU/Capability.
706 // - giving low priority to moving long-lived threads
708 if (n_free_caps > 0) {
709 StgTSO *prev, *t, *next;
710 rtsBool pushed_to_all;
712 debugTrace(DEBUG_sched,
713 "cap %d: %s and %d free capabilities, sharing...",
715 (!emptyRunQueue(cap) && cap->run_queue_hd->_link != END_TSO_QUEUE)?
716 "excess threads on run queue":"sparks to share (>=2)",
720 pushed_to_all = rtsFalse;
722 if (cap->run_queue_hd != END_TSO_QUEUE) {
723 prev = cap->run_queue_hd;
725 prev->_link = END_TSO_QUEUE;
726 for (; t != END_TSO_QUEUE; t = next) {
728 t->_link = END_TSO_QUEUE;
729 if (t->what_next == ThreadRelocated
730 || t->bound == task->incall // don't move my bound thread
731 || tsoLocked(t)) { // don't move a locked thread
732 setTSOLink(cap, prev, t);
733 setTSOPrev(cap, t, prev);
735 } else if (i == n_free_caps) {
736 pushed_to_all = rtsTrue;
739 setTSOLink(cap, prev, t);
740 setTSOPrev(cap, t, prev);
743 appendToRunQueue(free_caps[i],t);
745 traceEventMigrateThread (cap, t, free_caps[i]->no);
747 if (t->bound) { t->bound->task->cap = free_caps[i]; }
748 t->cap = free_caps[i];
752 cap->run_queue_tl = prev;
754 IF_DEBUG(sanity, checkRunQueue(cap));
758 /* JB I left this code in place, it would work but is not necessary */
760 // If there are some free capabilities that we didn't push any
761 // threads to, then try to push a spark to each one.
762 if (!pushed_to_all) {
764 // i is the next free capability to push to
765 for (; i < n_free_caps; i++) {
766 if (emptySparkPoolCap(free_caps[i])) {
767 spark = tryStealSpark(cap->sparks);
769 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
771 traceEventStealSpark(free_caps[i], t, cap->no);
773 newSpark(&(free_caps[i]->r), spark);
778 #endif /* SPARK_PUSHING */
780 // release the capabilities
781 for (i = 0; i < n_free_caps; i++) {
782 task->cap = free_caps[i];
783 releaseAndWakeupCapability(free_caps[i]);
786 task->cap = cap; // reset to point to our Capability.
788 #endif /* THREADED_RTS */
792 /* ----------------------------------------------------------------------------
793 * Start any pending signal handlers
794 * ------------------------------------------------------------------------- */
796 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
798 scheduleStartSignalHandlers(Capability *cap)
800 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
801 // safe outside the lock
802 startSignalHandlers(cap);
807 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
812 /* ----------------------------------------------------------------------------
813 * Check for blocked threads that can be woken up.
814 * ------------------------------------------------------------------------- */
817 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
819 #if !defined(THREADED_RTS)
821 // Check whether any waiting threads need to be woken up. If the
822 // run queue is empty, and there are no other tasks running, we
823 // can wait indefinitely for something to happen.
825 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
827 awaitEvent (emptyRunQueue(cap));
832 /* ----------------------------------------------------------------------------
833 * Detect deadlock conditions and attempt to resolve them.
834 * ------------------------------------------------------------------------- */
837 scheduleDetectDeadlock (Capability *cap, Task *task)
840 * Detect deadlock: when we have no threads to run, there are no
841 * threads blocked, waiting for I/O, or sleeping, and all the
842 * other tasks are waiting for work, we must have a deadlock of
845 if ( emptyThreadQueues(cap) )
847 #if defined(THREADED_RTS)
849 * In the threaded RTS, we only check for deadlock if there
850 * has been no activity in a complete timeslice. This means
851 * we won't eagerly start a full GC just because we don't have
852 * any threads to run currently.
854 if (recent_activity != ACTIVITY_INACTIVE) return;
857 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
859 // Garbage collection can release some new threads due to
860 // either (a) finalizers or (b) threads resurrected because
861 // they are unreachable and will therefore be sent an
862 // exception. Any threads thus released will be immediately
864 cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
865 // when force_major == rtsTrue. scheduleDoGC sets
866 // recent_activity to ACTIVITY_DONE_GC and turns off the timer
869 if ( !emptyRunQueue(cap) ) return;
871 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
872 /* If we have user-installed signal handlers, then wait
873 * for signals to arrive rather then bombing out with a
876 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
877 debugTrace(DEBUG_sched,
878 "still deadlocked, waiting for signals...");
882 if (signals_pending()) {
883 startSignalHandlers(cap);
886 // either we have threads to run, or we were interrupted:
887 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
893 #if !defined(THREADED_RTS)
894 /* Probably a real deadlock. Send the current main thread the
895 * Deadlock exception.
897 if (task->incall->tso) {
898 switch (task->incall->tso->why_blocked) {
900 case BlockedOnBlackHole:
901 case BlockedOnMsgThrowTo:
903 throwToSingleThreaded(cap, task->incall->tso,
904 (StgClosure *)nonTermination_closure);
907 barf("deadlock: main thread blocked in a strange way");
916 /* ----------------------------------------------------------------------------
917 * Send pending messages (PARALLEL_HASKELL only)
918 * ------------------------------------------------------------------------- */
920 #if defined(PARALLEL_HASKELL)
922 scheduleSendPendingMessages(void)
925 # if defined(PAR) // global Mem.Mgmt., omit for now
926 if (PendingFetches != END_BF_QUEUE) {
931 if (RtsFlags.ParFlags.BufferTime) {
932 // if we use message buffering, we must send away all message
933 // packets which have become too old...
939 /* ----------------------------------------------------------------------------
940 * Process message in the current Capability's inbox
941 * ------------------------------------------------------------------------- */
944 scheduleProcessInbox (Capability *cap USED_IF_THREADS)
946 #if defined(THREADED_RTS)
949 while (!emptyInbox(cap)) {
950 ACQUIRE_LOCK(&cap->lock);
952 cap->inbox = m->link;
953 RELEASE_LOCK(&cap->lock);
954 executeMessage(cap, (Message *)m);
959 /* ----------------------------------------------------------------------------
960 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
961 * ------------------------------------------------------------------------- */
963 #if defined(THREADED_RTS)
965 scheduleActivateSpark(Capability *cap)
969 createSparkThread(cap);
970 debugTrace(DEBUG_sched, "creating a spark thread");
973 #endif // PARALLEL_HASKELL || THREADED_RTS
975 /* ----------------------------------------------------------------------------
976 * After running a thread...
977 * ------------------------------------------------------------------------- */
980 schedulePostRunThread (Capability *cap, StgTSO *t)
982 // We have to be able to catch transactions that are in an
983 // infinite loop as a result of seeing an inconsistent view of
987 // [a,b] <- mapM readTVar [ta,tb]
988 // when (a == b) loop
990 // and a is never equal to b given a consistent view of memory.
992 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
993 if (!stmValidateNestOfTransactions (t -> trec)) {
994 debugTrace(DEBUG_sched | DEBUG_stm,
995 "trec %p found wasting its time", t);
997 // strip the stack back to the
998 // ATOMICALLY_FRAME, aborting the (nested)
999 // transaction, and saving the stack of any
1000 // partially-evaluated thunks on the heap.
1001 throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1003 // ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1007 /* some statistics gathering in the parallel case */
1010 /* -----------------------------------------------------------------------------
1011 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1012 * -------------------------------------------------------------------------- */
1015 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1017 // did the task ask for a large block?
1018 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1019 // if so, get one and push it on the front of the nursery.
1023 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1025 debugTrace(DEBUG_sched,
1026 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1027 (long)t->id, what_next_strs[t->what_next], blocks);
1029 // don't do this if the nursery is (nearly) full, we'll GC first.
1030 if (cap->r.rCurrentNursery->link != NULL ||
1031 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1032 // if the nursery has only one block.
1035 bd = allocGroup( blocks );
1037 cap->r.rNursery->n_blocks += blocks;
1039 // link the new group into the list
1040 bd->link = cap->r.rCurrentNursery;
1041 bd->u.back = cap->r.rCurrentNursery->u.back;
1042 if (cap->r.rCurrentNursery->u.back != NULL) {
1043 cap->r.rCurrentNursery->u.back->link = bd;
1045 cap->r.rNursery->blocks = bd;
1047 cap->r.rCurrentNursery->u.back = bd;
1049 // initialise it as a nursery block. We initialise the
1050 // step, gen_no, and flags field of *every* sub-block in
1051 // this large block, because this is easier than making
1052 // sure that we always find the block head of a large
1053 // block whenever we call Bdescr() (eg. evacuate() and
1054 // isAlive() in the GC would both have to do this, at
1058 for (x = bd; x < bd + blocks; x++) {
1059 initBdescr(x,g0,g0);
1065 // This assert can be a killer if the app is doing lots
1066 // of large block allocations.
1067 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1069 // now update the nursery to point to the new block
1070 cap->r.rCurrentNursery = bd;
1072 // we might be unlucky and have another thread get on the
1073 // run queue before us and steal the large block, but in that
1074 // case the thread will just end up requesting another large
1076 pushOnRunQueue(cap,t);
1077 return rtsFalse; /* not actually GC'ing */
1081 if (cap->r.rHpLim == NULL || cap->context_switch) {
1082 // Sometimes we miss a context switch, e.g. when calling
1083 // primitives in a tight loop, MAYBE_GC() doesn't check the
1084 // context switch flag, and we end up waiting for a GC.
1085 // See #1984, and concurrent/should_run/1984
1086 cap->context_switch = 0;
1087 appendToRunQueue(cap,t);
1089 pushOnRunQueue(cap,t);
1092 /* actual GC is done at the end of the while loop in schedule() */
1095 /* -----------------------------------------------------------------------------
1096 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1097 * -------------------------------------------------------------------------- */
1100 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1102 /* just adjust the stack for this thread, then pop it back
1106 /* enlarge the stack */
1107 StgTSO *new_t = threadStackOverflow(cap, t);
1109 /* The TSO attached to this Task may have moved, so update the
1112 if (task->incall->tso == t) {
1113 task->incall->tso = new_t;
1115 pushOnRunQueue(cap,new_t);
1119 /* -----------------------------------------------------------------------------
1120 * Handle a thread that returned to the scheduler with ThreadYielding
1121 * -------------------------------------------------------------------------- */
1124 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1126 /* put the thread back on the run queue. Then, if we're ready to
1127 * GC, check whether this is the last task to stop. If so, wake
1128 * up the GC thread. getThread will block during a GC until the
1132 ASSERT(t->_link == END_TSO_QUEUE);
1134 // Shortcut if we're just switching evaluators: don't bother
1135 // doing stack squeezing (which can be expensive), just run the
1137 if (cap->context_switch == 0 && t->what_next != prev_what_next) {
1138 debugTrace(DEBUG_sched,
1139 "--<< thread %ld (%s) stopped to switch evaluators",
1140 (long)t->id, what_next_strs[t->what_next]);
1144 // Reset the context switch flag. We don't do this just before
1145 // running the thread, because that would mean we would lose ticks
1146 // during GC, which can lead to unfair scheduling (a thread hogs
1147 // the CPU because the tick always arrives during GC). This way
1148 // penalises threads that do a lot of allocation, but that seems
1149 // better than the alternative.
1150 cap->context_switch = 0;
1153 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1156 appendToRunQueue(cap,t);
1161 /* -----------------------------------------------------------------------------
1162 * Handle a thread that returned to the scheduler with ThreadBlocked
1163 * -------------------------------------------------------------------------- */
1166 scheduleHandleThreadBlocked( StgTSO *t
1173 // We don't need to do anything. The thread is blocked, and it
1174 // has tidied up its stack and placed itself on whatever queue
1175 // it needs to be on.
1177 // ASSERT(t->why_blocked != NotBlocked);
1178 // Not true: for example,
1179 // - the thread may have woken itself up already, because
1180 // threadPaused() might have raised a blocked throwTo
1181 // exception, see maybePerformBlockedException().
1184 traceThreadStatus(DEBUG_sched, t);
1188 /* -----------------------------------------------------------------------------
1189 * Handle a thread that returned to the scheduler with ThreadFinished
1190 * -------------------------------------------------------------------------- */
1193 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1195 /* Need to check whether this was a main thread, and if so,
1196 * return with the return value.
1198 * We also end up here if the thread kills itself with an
1199 * uncaught exception, see Exception.cmm.
1202 // blocked exceptions can now complete, even if the thread was in
1203 // blocked mode (see #2910).
1204 awakenBlockedExceptionQueue (cap, t);
1207 // Check whether the thread that just completed was a bound
1208 // thread, and if so return with the result.
1210 // There is an assumption here that all thread completion goes
1211 // through this point; we need to make sure that if a thread
1212 // ends up in the ThreadKilled state, that it stays on the run
1213 // queue so it can be dealt with here.
1218 if (t->bound != task->incall) {
1219 #if !defined(THREADED_RTS)
1220 // Must be a bound thread that is not the topmost one. Leave
1221 // it on the run queue until the stack has unwound to the
1222 // point where we can deal with this. Leaving it on the run
1223 // queue also ensures that the garbage collector knows about
1224 // this thread and its return value (it gets dropped from the
1225 // step->threads list so there's no other way to find it).
1226 appendToRunQueue(cap,t);
1229 // this cannot happen in the threaded RTS, because a
1230 // bound thread can only be run by the appropriate Task.
1231 barf("finished bound thread that isn't mine");
1235 ASSERT(task->incall->tso == t);
1237 if (t->what_next == ThreadComplete) {
1238 if (task->incall->ret) {
1239 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1240 *(task->incall->ret) = (StgClosure *)task->incall->tso->sp[1];
1242 task->incall->stat = Success;
1244 if (task->incall->ret) {
1245 *(task->incall->ret) = NULL;
1247 if (sched_state >= SCHED_INTERRUPTING) {
1248 if (heap_overflow) {
1249 task->incall->stat = HeapExhausted;
1251 task->incall->stat = Interrupted;
1254 task->incall->stat = Killed;
1258 removeThreadLabel((StgWord)task->incall->tso->id);
1261 // We no longer consider this thread and task to be bound to
1262 // each other. The TSO lives on until it is GC'd, but the
1263 // task is about to be released by the caller, and we don't
1264 // want anyone following the pointer from the TSO to the
1265 // defunct task (which might have already been
1266 // re-used). This was a real bug: the GC updated
1267 // tso->bound->tso which lead to a deadlock.
1269 task->incall->tso = NULL;
1271 return rtsTrue; // tells schedule() to return
1277 /* -----------------------------------------------------------------------------
1278 * Perform a heap census
1279 * -------------------------------------------------------------------------- */
1282 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1284 // When we have +RTS -i0 and we're heap profiling, do a census at
1285 // every GC. This lets us get repeatable runs for debugging.
1286 if (performHeapProfile ||
1287 (RtsFlags.ProfFlags.profileInterval==0 &&
1288 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1295 /* -----------------------------------------------------------------------------
1296 * Perform a garbage collection if necessary
1297 * -------------------------------------------------------------------------- */
1300 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1302 rtsBool heap_census;
1304 /* extern static volatile StgWord waiting_for_gc;
1305 lives inside capability.c */
1306 rtsBool gc_type, prev_pending_gc;
1310 if (sched_state == SCHED_SHUTTING_DOWN) {
1311 // The final GC has already been done, and the system is
1312 // shutting down. We'll probably deadlock if we try to GC
1318 if (sched_state < SCHED_INTERRUPTING
1319 && RtsFlags.ParFlags.parGcEnabled
1320 && N >= RtsFlags.ParFlags.parGcGen
1321 && ! oldest_gen->mark)
1323 gc_type = PENDING_GC_PAR;
1325 gc_type = PENDING_GC_SEQ;
1328 // In order to GC, there must be no threads running Haskell code.
1329 // Therefore, the GC thread needs to hold *all* the capabilities,
1330 // and release them after the GC has completed.
1332 // This seems to be the simplest way: previous attempts involved
1333 // making all the threads with capabilities give up their
1334 // capabilities and sleep except for the *last* one, which
1335 // actually did the GC. But it's quite hard to arrange for all
1336 // the other tasks to sleep and stay asleep.
1339 /* Other capabilities are prevented from running yet more Haskell
1340 threads if waiting_for_gc is set. Tested inside
1341 yieldCapability() and releaseCapability() in Capability.c */
1343 prev_pending_gc = cas(&waiting_for_gc, 0, gc_type);
1344 if (prev_pending_gc) {
1346 debugTrace(DEBUG_sched, "someone else is trying to GC (%d)...",
1349 yieldCapability(&cap,task);
1350 } while (waiting_for_gc);
1351 return cap; // NOTE: task->cap might have changed here
1354 setContextSwitches();
1356 // The final shutdown GC is always single-threaded, because it's
1357 // possible that some of the Capabilities have no worker threads.
1359 if (gc_type == PENDING_GC_SEQ)
1361 traceEventRequestSeqGc(cap);
1365 traceEventRequestParGc(cap);
1366 debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1369 if (gc_type == PENDING_GC_SEQ)
1371 // single-threaded GC: grab all the capabilities
1372 for (i=0; i < n_capabilities; i++) {
1373 debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1374 if (cap != &capabilities[i]) {
1375 Capability *pcap = &capabilities[i];
1376 // we better hope this task doesn't get migrated to
1377 // another Capability while we're waiting for this one.
1378 // It won't, because load balancing happens while we have
1379 // all the Capabilities, but even so it's a slightly
1380 // unsavoury invariant.
1382 waitForReturnCapability(&pcap, task);
1383 if (pcap != &capabilities[i]) {
1384 barf("scheduleDoGC: got the wrong capability");
1391 // multi-threaded GC: make sure all the Capabilities donate one
1393 waitForGcThreads(cap);
1398 IF_DEBUG(scheduler, printAllThreads());
1400 delete_threads_and_gc:
1402 * We now have all the capabilities; if we're in an interrupting
1403 * state, then we should take the opportunity to delete all the
1404 * threads in the system.
1406 if (sched_state == SCHED_INTERRUPTING) {
1407 deleteAllThreads(cap);
1408 sched_state = SCHED_SHUTTING_DOWN;
1411 heap_census = scheduleNeedHeapProfile(rtsTrue);
1413 traceEventGcStart(cap);
1414 #if defined(THREADED_RTS)
1415 // reset waiting_for_gc *before* GC, so that when the GC threads
1416 // emerge they don't immediately re-enter the GC.
1418 GarbageCollect(force_major || heap_census, gc_type, cap);
1420 GarbageCollect(force_major || heap_census, 0, cap);
1422 traceEventGcEnd(cap);
1424 if (recent_activity == ACTIVITY_INACTIVE && force_major)
1426 // We are doing a GC because the system has been idle for a
1427 // timeslice and we need to check for deadlock. Record the
1428 // fact that we've done a GC and turn off the timer signal;
1429 // it will get re-enabled if we run any threads after the GC.
1430 recent_activity = ACTIVITY_DONE_GC;
1435 // the GC might have taken long enough for the timer to set
1436 // recent_activity = ACTIVITY_INACTIVE, but we aren't
1437 // necessarily deadlocked:
1438 recent_activity = ACTIVITY_YES;
1441 #if defined(THREADED_RTS)
1442 if (gc_type == PENDING_GC_PAR)
1444 releaseGCThreads(cap);
1449 debugTrace(DEBUG_sched, "performing heap census");
1451 performHeapProfile = rtsFalse;
1454 if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1455 // GC set the heap_overflow flag, so we should proceed with
1456 // an orderly shutdown now. Ultimately we want the main
1457 // thread to return to its caller with HeapExhausted, at which
1458 // point the caller should call hs_exit(). The first step is
1459 // to delete all the threads.
1461 // Another way to do this would be to raise an exception in
1462 // the main thread, which we really should do because it gives
1463 // the program a chance to clean up. But how do we find the
1464 // main thread? It should presumably be the same one that
1465 // gets ^C exceptions, but that's all done on the Haskell side
1466 // (GHC.TopHandler).
1467 sched_state = SCHED_INTERRUPTING;
1468 goto delete_threads_and_gc;
1473 Once we are all together... this would be the place to balance all
1474 spark pools. No concurrent stealing or adding of new sparks can
1475 occur. Should be defined in Sparks.c. */
1476 balanceSparkPoolsCaps(n_capabilities, capabilities);
1479 #if defined(THREADED_RTS)
1480 if (gc_type == PENDING_GC_SEQ) {
1481 // release our stash of capabilities.
1482 for (i = 0; i < n_capabilities; i++) {
1483 if (cap != &capabilities[i]) {
1484 task->cap = &capabilities[i];
1485 releaseCapability(&capabilities[i]);
1499 /* ---------------------------------------------------------------------------
1500 * Singleton fork(). Do not copy any running threads.
1501 * ------------------------------------------------------------------------- */
1504 forkProcess(HsStablePtr *entry
1505 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1510 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1516 #if defined(THREADED_RTS)
1517 if (RtsFlags.ParFlags.nNodes > 1) {
1518 errorBelch("forking not supported with +RTS -N<n> greater than 1");
1519 stg_exit(EXIT_FAILURE);
1523 debugTrace(DEBUG_sched, "forking!");
1525 // ToDo: for SMP, we should probably acquire *all* the capabilities
1528 // no funny business: hold locks while we fork, otherwise if some
1529 // other thread is holding a lock when the fork happens, the data
1530 // structure protected by the lock will forever be in an
1531 // inconsistent state in the child. See also #1391.
1532 ACQUIRE_LOCK(&sched_mutex);
1533 ACQUIRE_LOCK(&cap->lock);
1534 ACQUIRE_LOCK(&cap->running_task->lock);
1536 stopTimer(); // See #4074
1540 if (pid) { // parent
1542 startTimer(); // #4074
1544 RELEASE_LOCK(&sched_mutex);
1545 RELEASE_LOCK(&cap->lock);
1546 RELEASE_LOCK(&cap->running_task->lock);
1548 // just return the pid
1554 #if defined(THREADED_RTS)
1555 initMutex(&sched_mutex);
1556 initMutex(&cap->lock);
1557 initMutex(&cap->running_task->lock);
1560 // Now, all OS threads except the thread that forked are
1561 // stopped. We need to stop all Haskell threads, including
1562 // those involved in foreign calls. Also we need to delete
1563 // all Tasks, because they correspond to OS threads that are
1566 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1567 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1568 if (t->what_next == ThreadRelocated) {
1571 next = t->global_link;
1572 // don't allow threads to catch the ThreadKilled
1573 // exception, but we do want to raiseAsync() because these
1574 // threads may be evaluating thunks that we need later.
1575 deleteThread_(cap,t);
1577 // stop the GC from updating the InCall to point to
1578 // the TSO. This is only necessary because the
1579 // OSThread bound to the TSO has been killed, and
1580 // won't get a chance to exit in the usual way (see
1581 // also scheduleHandleThreadFinished).
1587 // Empty the run queue. It seems tempting to let all the
1588 // killed threads stay on the run queue as zombies to be
1589 // cleaned up later, but some of them correspond to bound
1590 // threads for which the corresponding Task does not exist.
1591 cap->run_queue_hd = END_TSO_QUEUE;
1592 cap->run_queue_tl = END_TSO_QUEUE;
1594 // Any suspended C-calling Tasks are no more, their OS threads
1596 cap->suspended_ccalls = NULL;
1598 // Empty the threads lists. Otherwise, the garbage
1599 // collector may attempt to resurrect some of these threads.
1600 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1601 generations[g].threads = END_TSO_QUEUE;
1604 discardTasksExcept(cap->running_task);
1606 #if defined(THREADED_RTS)
1607 // Wipe our spare workers list, they no longer exist. New
1608 // workers will be created if necessary.
1609 cap->spare_workers = NULL;
1610 cap->returning_tasks_hd = NULL;
1611 cap->returning_tasks_tl = NULL;
1614 // On Unix, all timers are reset in the child, so we need to start
1619 #if defined(THREADED_RTS)
1620 cap = ioManagerStartCap(cap);
1623 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1624 rts_checkSchedStatus("forkProcess",cap);
1627 hs_exit(); // clean up and exit
1628 stg_exit(EXIT_SUCCESS);
1630 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1631 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1635 /* ---------------------------------------------------------------------------
1636 * Delete all the threads in the system
1637 * ------------------------------------------------------------------------- */
1640 deleteAllThreads ( Capability *cap )
1642 // NOTE: only safe to call if we own all capabilities.
1647 debugTrace(DEBUG_sched,"deleting all threads");
1648 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1649 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1650 if (t->what_next == ThreadRelocated) {
1653 next = t->global_link;
1654 deleteThread(cap,t);
1659 // The run queue now contains a bunch of ThreadKilled threads. We
1660 // must not throw these away: the main thread(s) will be in there
1661 // somewhere, and the main scheduler loop has to deal with it.
1662 // Also, the run queue is the only thing keeping these threads from
1663 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1665 #if !defined(THREADED_RTS)
1666 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1667 ASSERT(sleeping_queue == END_TSO_QUEUE);
1671 /* -----------------------------------------------------------------------------
1672 Managing the suspended_ccalls list.
1673 Locks required: sched_mutex
1674 -------------------------------------------------------------------------- */
1677 suspendTask (Capability *cap, Task *task)
1681 incall = task->incall;
1682 ASSERT(incall->next == NULL && incall->prev == NULL);
1683 incall->next = cap->suspended_ccalls;
1684 incall->prev = NULL;
1685 if (cap->suspended_ccalls) {
1686 cap->suspended_ccalls->prev = incall;
1688 cap->suspended_ccalls = incall;
1692 recoverSuspendedTask (Capability *cap, Task *task)
1696 incall = task->incall;
1698 incall->prev->next = incall->next;
1700 ASSERT(cap->suspended_ccalls == incall);
1701 cap->suspended_ccalls = incall->next;
1704 incall->next->prev = incall->prev;
1706 incall->next = incall->prev = NULL;
1709 /* ---------------------------------------------------------------------------
1710 * Suspending & resuming Haskell threads.
1712 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1713 * its capability before calling the C function. This allows another
1714 * task to pick up the capability and carry on running Haskell
1715 * threads. It also means that if the C call blocks, it won't lock
1718 * The Haskell thread making the C call is put to sleep for the
1719 * duration of the call, on the susepended_ccalling_threads queue. We
1720 * give out a token to the task, which it can use to resume the thread
1721 * on return from the C function.
1722 * ------------------------------------------------------------------------- */
1725 suspendThread (StgRegTable *reg)
1732 StgWord32 saved_winerror;
1735 saved_errno = errno;
1737 saved_winerror = GetLastError();
1740 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1742 cap = regTableToCapability(reg);
1744 task = cap->running_task;
1745 tso = cap->r.rCurrentTSO;
1747 traceEventStopThread(cap, tso, THREAD_SUSPENDED_FOREIGN_CALL);
1749 // XXX this might not be necessary --SDM
1750 tso->what_next = ThreadRunGHC;
1752 threadPaused(cap,tso);
1754 if ((tso->flags & TSO_BLOCKEX) == 0) {
1755 tso->why_blocked = BlockedOnCCall;
1756 tso->flags |= TSO_BLOCKEX;
1757 tso->flags &= ~TSO_INTERRUPTIBLE;
1759 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1762 // Hand back capability
1763 task->incall->suspended_tso = tso;
1764 task->incall->suspended_cap = cap;
1766 ACQUIRE_LOCK(&cap->lock);
1768 suspendTask(cap,task);
1769 cap->in_haskell = rtsFalse;
1770 releaseCapability_(cap,rtsFalse);
1772 RELEASE_LOCK(&cap->lock);
1774 errno = saved_errno;
1776 SetLastError(saved_winerror);
1782 resumeThread (void *task_)
1790 StgWord32 saved_winerror;
1793 saved_errno = errno;
1795 saved_winerror = GetLastError();
1798 incall = task->incall;
1799 cap = incall->suspended_cap;
1802 // Wait for permission to re-enter the RTS with the result.
1803 waitForReturnCapability(&cap,task);
1804 // we might be on a different capability now... but if so, our
1805 // entry on the suspended_ccalls list will also have been
1808 // Remove the thread from the suspended list
1809 recoverSuspendedTask(cap,task);
1811 tso = incall->suspended_tso;
1812 incall->suspended_tso = NULL;
1813 incall->suspended_cap = NULL;
1814 tso->_link = END_TSO_QUEUE; // no write barrier reqd
1816 traceEventRunThread(cap, tso);
1818 if (tso->why_blocked == BlockedOnCCall) {
1819 // avoid locking the TSO if we don't have to
1820 if (tso->blocked_exceptions != END_BLOCKED_EXCEPTIONS_QUEUE) {
1821 awakenBlockedExceptionQueue(cap,tso);
1823 tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
1826 /* Reset blocking status */
1827 tso->why_blocked = NotBlocked;
1829 cap->r.rCurrentTSO = tso;
1830 cap->in_haskell = rtsTrue;
1831 errno = saved_errno;
1833 SetLastError(saved_winerror);
1836 /* We might have GC'd, mark the TSO dirty again */
1839 IF_DEBUG(sanity, checkTSO(tso));
1844 /* ---------------------------------------------------------------------------
1847 * scheduleThread puts a thread on the end of the runnable queue.
1848 * This will usually be done immediately after a thread is created.
1849 * The caller of scheduleThread must create the thread using e.g.
1850 * createThread and push an appropriate closure
1851 * on this thread's stack before the scheduler is invoked.
1852 * ------------------------------------------------------------------------ */
1855 scheduleThread(Capability *cap, StgTSO *tso)
1857 // The thread goes at the *end* of the run-queue, to avoid possible
1858 // starvation of any threads already on the queue.
1859 appendToRunQueue(cap,tso);
1863 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
1865 #if defined(THREADED_RTS)
1866 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
1867 // move this thread from now on.
1868 cpu %= RtsFlags.ParFlags.nNodes;
1869 if (cpu == cap->no) {
1870 appendToRunQueue(cap,tso);
1872 migrateThread(cap, tso, &capabilities[cpu]);
1875 appendToRunQueue(cap,tso);
1880 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
1885 // We already created/initialised the Task
1886 task = cap->running_task;
1888 // This TSO is now a bound thread; make the Task and TSO
1889 // point to each other.
1890 tso->bound = task->incall;
1893 task->incall->tso = tso;
1894 task->incall->ret = ret;
1895 task->incall->stat = NoStatus;
1897 appendToRunQueue(cap,tso);
1900 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)id);
1902 cap = schedule(cap,task);
1904 ASSERT(task->incall->stat != NoStatus);
1905 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
1907 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)id);
1911 /* ----------------------------------------------------------------------------
1913 * ------------------------------------------------------------------------- */
1915 #if defined(THREADED_RTS)
1916 void scheduleWorker (Capability *cap, Task *task)
1918 // schedule() runs without a lock.
1919 cap = schedule(cap,task);
1921 // On exit from schedule(), we have a Capability, but possibly not
1922 // the same one we started with.
1924 // During shutdown, the requirement is that after all the
1925 // Capabilities are shut down, all workers that are shutting down
1926 // have finished workerTaskStop(). This is why we hold on to
1927 // cap->lock until we've finished workerTaskStop() below.
1929 // There may be workers still involved in foreign calls; those
1930 // will just block in waitForReturnCapability() because the
1931 // Capability has been shut down.
1933 ACQUIRE_LOCK(&cap->lock);
1934 releaseCapability_(cap,rtsFalse);
1935 workerTaskStop(task);
1936 RELEASE_LOCK(&cap->lock);
1940 /* ---------------------------------------------------------------------------
1943 * Initialise the scheduler. This resets all the queues - if the
1944 * queues contained any threads, they'll be garbage collected at the
1947 * ------------------------------------------------------------------------ */
1952 #if !defined(THREADED_RTS)
1953 blocked_queue_hd = END_TSO_QUEUE;
1954 blocked_queue_tl = END_TSO_QUEUE;
1955 sleeping_queue = END_TSO_QUEUE;
1958 sched_state = SCHED_RUNNING;
1959 recent_activity = ACTIVITY_YES;
1961 #if defined(THREADED_RTS)
1962 /* Initialise the mutex and condition variables used by
1964 initMutex(&sched_mutex);
1967 ACQUIRE_LOCK(&sched_mutex);
1969 /* A capability holds the state a native thread needs in
1970 * order to execute STG code. At least one capability is
1971 * floating around (only THREADED_RTS builds have more than one).
1977 #if defined(THREADED_RTS)
1981 RELEASE_LOCK(&sched_mutex);
1983 #if defined(THREADED_RTS)
1985 * Eagerly start one worker to run each Capability, except for
1986 * Capability 0. The idea is that we're probably going to start a
1987 * bound thread on Capability 0 pretty soon, so we don't want a
1988 * worker task hogging it.
1993 for (i = 1; i < n_capabilities; i++) {
1994 cap = &capabilities[i];
1995 ACQUIRE_LOCK(&cap->lock);
1996 startWorkerTask(cap);
1997 RELEASE_LOCK(&cap->lock);
2004 exitScheduler (rtsBool wait_foreign USED_IF_THREADS)
2005 /* see Capability.c, shutdownCapability() */
2009 task = newBoundTask();
2011 // If we haven't killed all the threads yet, do it now.
2012 if (sched_state < SCHED_SHUTTING_DOWN) {
2013 sched_state = SCHED_INTERRUPTING;
2014 waitForReturnCapability(&task->cap,task);
2015 scheduleDoGC(task->cap,task,rtsFalse);
2016 ASSERT(task->incall->tso == NULL);
2017 releaseCapability(task->cap);
2019 sched_state = SCHED_SHUTTING_DOWN;
2021 #if defined(THREADED_RTS)
2025 for (i = 0; i < n_capabilities; i++) {
2026 ASSERT(task->incall->tso == NULL);
2027 shutdownCapability(&capabilities[i], task, wait_foreign);
2032 boundTaskExiting(task);
2036 freeScheduler( void )
2040 ACQUIRE_LOCK(&sched_mutex);
2041 still_running = freeTaskManager();
2042 // We can only free the Capabilities if there are no Tasks still
2043 // running. We might have a Task about to return from a foreign
2044 // call into waitForReturnCapability(), for example (actually,
2045 // this should be the *only* thing that a still-running Task can
2046 // do at this point, and it will block waiting for the
2048 if (still_running == 0) {
2050 if (n_capabilities != 1) {
2051 stgFree(capabilities);
2054 RELEASE_LOCK(&sched_mutex);
2055 #if defined(THREADED_RTS)
2056 closeMutex(&sched_mutex);
2060 /* -----------------------------------------------------------------------------
2063 This is the interface to the garbage collector from Haskell land.
2064 We provide this so that external C code can allocate and garbage
2065 collect when called from Haskell via _ccall_GC.
2066 -------------------------------------------------------------------------- */
2069 performGC_(rtsBool force_major)
2073 // We must grab a new Task here, because the existing Task may be
2074 // associated with a particular Capability, and chained onto the
2075 // suspended_ccalls queue.
2076 task = newBoundTask();
2078 waitForReturnCapability(&task->cap,task);
2079 scheduleDoGC(task->cap,task,force_major);
2080 releaseCapability(task->cap);
2081 boundTaskExiting(task);
2087 performGC_(rtsFalse);
2091 performMajorGC(void)
2093 performGC_(rtsTrue);
2096 /* -----------------------------------------------------------------------------
2099 If the thread has reached its maximum stack size, then raise the
2100 StackOverflow exception in the offending thread. Otherwise
2101 relocate the TSO into a larger chunk of memory and adjust its stack
2103 -------------------------------------------------------------------------- */
2106 threadStackOverflow(Capability *cap, StgTSO *tso)
2108 nat new_stack_size, stack_words;
2113 IF_DEBUG(sanity,checkTSO(tso));
2115 if (tso->stack_size >= tso->max_stack_size
2116 && !(tso->flags & TSO_BLOCKEX)) {
2117 // NB. never raise a StackOverflow exception if the thread is
2118 // inside Control.Exceptino.block. It is impractical to protect
2119 // against stack overflow exceptions, since virtually anything
2120 // can raise one (even 'catch'), so this is the only sensible
2121 // thing to do here. See bug #767.
2124 if (tso->flags & TSO_SQUEEZED) {
2127 // #3677: In a stack overflow situation, stack squeezing may
2128 // reduce the stack size, but we don't know whether it has been
2129 // reduced enough for the stack check to succeed if we try
2130 // again. Fortunately stack squeezing is idempotent, so all we
2131 // need to do is record whether *any* squeezing happened. If we
2132 // are at the stack's absolute -K limit, and stack squeezing
2133 // happened, then we try running the thread again. The
2134 // TSO_SQUEEZED flag is set by threadPaused() to tell us whether
2135 // squeezing happened or not.
2137 debugTrace(DEBUG_gc,
2138 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2139 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2141 /* If we're debugging, just print out the top of the stack */
2142 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2145 // Send this thread the StackOverflow exception
2146 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2151 // We also want to avoid enlarging the stack if squeezing has
2152 // already released some of it. However, we don't want to get into
2153 // a pathalogical situation where a thread has a nearly full stack
2154 // (near its current limit, but not near the absolute -K limit),
2155 // keeps allocating a little bit, squeezing removes a little bit,
2156 // and then it runs again. So to avoid this, if we squeezed *and*
2157 // there is still less than BLOCK_SIZE_W words free, then we enlarge
2158 // the stack anyway.
2159 if ((tso->flags & TSO_SQUEEZED) &&
2160 ((W_)(tso->sp - tso->stack) >= BLOCK_SIZE_W)) {
2164 /* Try to double the current stack size. If that takes us over the
2165 * maximum stack size for this thread, then use the maximum instead
2166 * (that is, unless we're already at or over the max size and we
2167 * can't raise the StackOverflow exception (see above), in which
2168 * case just double the size). Finally round up so the TSO ends up as
2169 * a whole number of blocks.
2171 if (tso->stack_size >= tso->max_stack_size) {
2172 new_stack_size = tso->stack_size * 2;
2174 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2176 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2177 TSO_STRUCT_SIZE)/sizeof(W_);
2178 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2179 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2181 debugTrace(DEBUG_sched,
2182 "increasing stack size from %ld words to %d.",
2183 (long)tso->stack_size, new_stack_size);
2185 dest = (StgTSO *)allocate(cap,new_tso_size);
2186 TICK_ALLOC_TSO(new_stack_size,0);
2188 /* copy the TSO block and the old stack into the new area */
2189 memcpy(dest,tso,TSO_STRUCT_SIZE);
2190 stack_words = tso->stack + tso->stack_size - tso->sp;
2191 new_sp = (P_)dest + new_tso_size - stack_words;
2192 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2194 /* relocate the stack pointers... */
2196 dest->stack_size = new_stack_size;
2198 /* Mark the old TSO as relocated. We have to check for relocated
2199 * TSOs in the garbage collector and any primops that deal with TSOs.
2201 * It's important to set the sp value to just beyond the end
2202 * of the stack, so we don't attempt to scavenge any part of the
2205 setTSOLink(cap,tso,dest);
2206 write_barrier(); // other threads seeing ThreadRelocated will look at _link
2207 tso->what_next = ThreadRelocated;
2208 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2209 tso->why_blocked = NotBlocked;
2211 IF_DEBUG(sanity,checkTSO(dest));
2213 IF_DEBUG(scheduler,printTSO(dest));
2220 threadStackUnderflow (Capability *cap, Task *task, StgTSO *tso)
2222 bdescr *bd, *new_bd;
2223 lnat free_w, tso_size_w;
2226 tso_size_w = tso_sizeW(tso);
2228 if (tso_size_w < MBLOCK_SIZE_W ||
2229 // TSO is less than 2 mblocks (since the first mblock is
2230 // shorter than MBLOCK_SIZE_W)
2231 (tso_size_w - BLOCKS_PER_MBLOCK*BLOCK_SIZE_W) % MBLOCK_SIZE_W != 0 ||
2232 // or TSO is not a whole number of megablocks (ensuring
2233 // precondition of splitLargeBlock() below)
2234 (tso_size_w <= round_up_to_mblocks(RtsFlags.GcFlags.initialStkSize)) ||
2235 // or TSO is smaller than the minimum stack size (rounded up)
2236 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2237 // or stack is using more than 1/4 of the available space
2243 // this is the number of words we'll free
2244 free_w = round_to_mblocks(tso_size_w/2);
2246 bd = Bdescr((StgPtr)tso);
2247 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2248 bd->free = bd->start + TSO_STRUCT_SIZEW;
2250 new_tso = (StgTSO *)new_bd->start;
2251 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2252 new_tso->stack_size = new_bd->free - new_tso->stack;
2254 // The original TSO was dirty and probably on the mutable
2255 // list. The new TSO is not yet on the mutable list, so we better
2258 new_tso->flags &= ~TSO_LINK_DIRTY;
2259 dirty_TSO(cap, new_tso);
2261 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2262 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2264 tso->_link = new_tso; // no write barrier reqd: same generation
2265 write_barrier(); // other threads seeing ThreadRelocated will look at _link
2266 tso->what_next = ThreadRelocated;
2268 // The TSO attached to this Task may have moved, so update the
2270 if (task->incall->tso == tso) {
2271 task->incall->tso = new_tso;
2274 IF_DEBUG(sanity,checkTSO(new_tso));
2279 /* ---------------------------------------------------------------------------
2281 - usually called inside a signal handler so it mustn't do anything fancy.
2282 ------------------------------------------------------------------------ */
2285 interruptStgRts(void)
2287 sched_state = SCHED_INTERRUPTING;
2288 setContextSwitches();
2289 #if defined(THREADED_RTS)
2294 /* -----------------------------------------------------------------------------
2297 This function causes at least one OS thread to wake up and run the
2298 scheduler loop. It is invoked when the RTS might be deadlocked, or
2299 an external event has arrived that may need servicing (eg. a
2300 keyboard interrupt).
2302 In the single-threaded RTS we don't do anything here; we only have
2303 one thread anyway, and the event that caused us to want to wake up
2304 will have interrupted any blocking system call in progress anyway.
2305 -------------------------------------------------------------------------- */
2307 #if defined(THREADED_RTS)
2308 void wakeUpRts(void)
2310 // This forces the IO Manager thread to wakeup, which will
2311 // in turn ensure that some OS thread wakes up and runs the
2312 // scheduler loop, which will cause a GC and deadlock check.
2317 /* -----------------------------------------------------------------------------
2320 This is used for interruption (^C) and forking, and corresponds to
2321 raising an exception but without letting the thread catch the
2323 -------------------------------------------------------------------------- */
2326 deleteThread (Capability *cap STG_UNUSED, StgTSO *tso)
2328 // NOTE: must only be called on a TSO that we have exclusive
2329 // access to, because we will call throwToSingleThreaded() below.
2330 // The TSO must be on the run queue of the Capability we own, or
2331 // we must own all Capabilities.
2333 if (tso->why_blocked != BlockedOnCCall &&
2334 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2335 throwToSingleThreaded(tso->cap,tso,NULL);
2339 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2341 deleteThread_(Capability *cap, StgTSO *tso)
2342 { // for forkProcess only:
2343 // like deleteThread(), but we delete threads in foreign calls, too.
2345 if (tso->why_blocked == BlockedOnCCall ||
2346 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2347 tso->what_next = ThreadKilled;
2348 appendToRunQueue(tso->cap, tso);
2350 deleteThread(cap,tso);
2355 /* -----------------------------------------------------------------------------
2356 raiseExceptionHelper
2358 This function is called by the raise# primitve, just so that we can
2359 move some of the tricky bits of raising an exception from C-- into
2360 C. Who knows, it might be a useful re-useable thing here too.
2361 -------------------------------------------------------------------------- */
2364 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2366 Capability *cap = regTableToCapability(reg);
2367 StgThunk *raise_closure = NULL;
2369 StgRetInfoTable *info;
2371 // This closure represents the expression 'raise# E' where E
2372 // is the exception raise. It is used to overwrite all the
2373 // thunks which are currently under evaluataion.
2376 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2377 // LDV profiling: stg_raise_info has THUNK as its closure
2378 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2379 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2380 // 1 does not cause any problem unless profiling is performed.
2381 // However, when LDV profiling goes on, we need to linearly scan
2382 // small object pool, where raise_closure is stored, so we should
2383 // use MIN_UPD_SIZE.
2385 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2386 // sizeofW(StgClosure)+1);
2390 // Walk up the stack, looking for the catch frame. On the way,
2391 // we update any closures pointed to from update frames with the
2392 // raise closure that we just built.
2396 info = get_ret_itbl((StgClosure *)p);
2397 next = p + stack_frame_sizeW((StgClosure *)p);
2398 switch (info->i.type) {
2401 // Only create raise_closure if we need to.
2402 if (raise_closure == NULL) {
2404 (StgThunk *)allocate(cap,sizeofW(StgThunk)+1);
2405 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2406 raise_closure->payload[0] = exception;
2408 updateThunk(cap, tso, ((StgUpdateFrame *)p)->updatee,
2409 (StgClosure *)raise_closure);
2413 case ATOMICALLY_FRAME:
2414 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2416 return ATOMICALLY_FRAME;
2422 case CATCH_STM_FRAME:
2423 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2425 return CATCH_STM_FRAME;
2431 case CATCH_RETRY_FRAME:
2440 /* -----------------------------------------------------------------------------
2441 findRetryFrameHelper
2443 This function is called by the retry# primitive. It traverses the stack
2444 leaving tso->sp referring to the frame which should handle the retry.
2446 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2447 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2449 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2450 create) because retries are not considered to be exceptions, despite the
2451 similar implementation.
2453 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2454 not be created within memory transactions.
2455 -------------------------------------------------------------------------- */
2458 findRetryFrameHelper (StgTSO *tso)
2461 StgRetInfoTable *info;
2465 info = get_ret_itbl((StgClosure *)p);
2466 next = p + stack_frame_sizeW((StgClosure *)p);
2467 switch (info->i.type) {
2469 case ATOMICALLY_FRAME:
2470 debugTrace(DEBUG_stm,
2471 "found ATOMICALLY_FRAME at %p during retry", p);
2473 return ATOMICALLY_FRAME;
2475 case CATCH_RETRY_FRAME:
2476 debugTrace(DEBUG_stm,
2477 "found CATCH_RETRY_FRAME at %p during retrry", p);
2479 return CATCH_RETRY_FRAME;
2481 case CATCH_STM_FRAME: {
2482 StgTRecHeader *trec = tso -> trec;
2483 StgTRecHeader *outer = trec -> enclosing_trec;
2484 debugTrace(DEBUG_stm,
2485 "found CATCH_STM_FRAME at %p during retry", p);
2486 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2487 stmAbortTransaction(tso -> cap, trec);
2488 stmFreeAbortedTRec(tso -> cap, trec);
2489 tso -> trec = outer;
2496 ASSERT(info->i.type != CATCH_FRAME);
2497 ASSERT(info->i.type != STOP_FRAME);
2504 /* -----------------------------------------------------------------------------
2505 resurrectThreads is called after garbage collection on the list of
2506 threads found to be garbage. Each of these threads will be woken
2507 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2508 on an MVar, or NonTermination if the thread was blocked on a Black
2511 Locks: assumes we hold *all* the capabilities.
2512 -------------------------------------------------------------------------- */
2515 resurrectThreads (StgTSO *threads)
2521 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2522 next = tso->global_link;
2524 gen = Bdescr((P_)tso)->gen;
2525 tso->global_link = gen->threads;
2528 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2530 // Wake up the thread on the Capability it was last on
2533 switch (tso->why_blocked) {
2535 /* Called by GC - sched_mutex lock is currently held. */
2536 throwToSingleThreaded(cap, tso,
2537 (StgClosure *)blockedIndefinitelyOnMVar_closure);
2539 case BlockedOnBlackHole:
2540 throwToSingleThreaded(cap, tso,
2541 (StgClosure *)nonTermination_closure);
2544 throwToSingleThreaded(cap, tso,
2545 (StgClosure *)blockedIndefinitelyOnSTM_closure);
2548 /* This might happen if the thread was blocked on a black hole
2549 * belonging to a thread that we've just woken up (raiseAsync
2550 * can wake up threads, remember...).
2553 case BlockedOnMsgThrowTo:
2554 // This can happen if the target is masking, blocks on a
2555 // black hole, and then is found to be unreachable. In
2556 // this case, we want to let the target wake up and carry
2557 // on, and do nothing to this thread.
2560 barf("resurrectThreads: thread blocked in a strange way: %d",