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);
1538 if (pid) { // parent
1540 RELEASE_LOCK(&sched_mutex);
1541 RELEASE_LOCK(&cap->lock);
1542 RELEASE_LOCK(&cap->running_task->lock);
1544 // just return the pid
1550 #if defined(THREADED_RTS)
1551 initMutex(&sched_mutex);
1552 initMutex(&cap->lock);
1553 initMutex(&cap->running_task->lock);
1556 // Now, all OS threads except the thread that forked are
1557 // stopped. We need to stop all Haskell threads, including
1558 // those involved in foreign calls. Also we need to delete
1559 // all Tasks, because they correspond to OS threads that are
1562 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1563 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1564 if (t->what_next == ThreadRelocated) {
1567 next = t->global_link;
1568 // don't allow threads to catch the ThreadKilled
1569 // exception, but we do want to raiseAsync() because these
1570 // threads may be evaluating thunks that we need later.
1571 deleteThread_(cap,t);
1573 // stop the GC from updating the InCall to point to
1574 // the TSO. This is only necessary because the
1575 // OSThread bound to the TSO has been killed, and
1576 // won't get a chance to exit in the usual way (see
1577 // also scheduleHandleThreadFinished).
1583 // Empty the run queue. It seems tempting to let all the
1584 // killed threads stay on the run queue as zombies to be
1585 // cleaned up later, but some of them correspond to bound
1586 // threads for which the corresponding Task does not exist.
1587 cap->run_queue_hd = END_TSO_QUEUE;
1588 cap->run_queue_tl = END_TSO_QUEUE;
1590 // Any suspended C-calling Tasks are no more, their OS threads
1592 cap->suspended_ccalls = NULL;
1594 // Empty the threads lists. Otherwise, the garbage
1595 // collector may attempt to resurrect some of these threads.
1596 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1597 generations[g].threads = END_TSO_QUEUE;
1600 discardTasksExcept(cap->running_task);
1602 #if defined(THREADED_RTS)
1603 // Wipe our spare workers list, they no longer exist. New
1604 // workers will be created if necessary.
1605 cap->spare_workers = NULL;
1606 cap->returning_tasks_hd = NULL;
1607 cap->returning_tasks_tl = NULL;
1610 // On Unix, all timers are reset in the child, so we need to start
1615 #if defined(THREADED_RTS)
1616 cap = ioManagerStartCap(cap);
1619 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1620 rts_checkSchedStatus("forkProcess",cap);
1623 hs_exit(); // clean up and exit
1624 stg_exit(EXIT_SUCCESS);
1626 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1627 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1631 /* ---------------------------------------------------------------------------
1632 * Delete all the threads in the system
1633 * ------------------------------------------------------------------------- */
1636 deleteAllThreads ( Capability *cap )
1638 // NOTE: only safe to call if we own all capabilities.
1643 debugTrace(DEBUG_sched,"deleting all threads");
1644 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1645 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1646 if (t->what_next == ThreadRelocated) {
1649 next = t->global_link;
1650 deleteThread(cap,t);
1655 // The run queue now contains a bunch of ThreadKilled threads. We
1656 // must not throw these away: the main thread(s) will be in there
1657 // somewhere, and the main scheduler loop has to deal with it.
1658 // Also, the run queue is the only thing keeping these threads from
1659 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1661 #if !defined(THREADED_RTS)
1662 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1663 ASSERT(sleeping_queue == END_TSO_QUEUE);
1667 /* -----------------------------------------------------------------------------
1668 Managing the suspended_ccalls list.
1669 Locks required: sched_mutex
1670 -------------------------------------------------------------------------- */
1673 suspendTask (Capability *cap, Task *task)
1677 incall = task->incall;
1678 ASSERT(incall->next == NULL && incall->prev == NULL);
1679 incall->next = cap->suspended_ccalls;
1680 incall->prev = NULL;
1681 if (cap->suspended_ccalls) {
1682 cap->suspended_ccalls->prev = incall;
1684 cap->suspended_ccalls = incall;
1688 recoverSuspendedTask (Capability *cap, Task *task)
1692 incall = task->incall;
1694 incall->prev->next = incall->next;
1696 ASSERT(cap->suspended_ccalls == incall);
1697 cap->suspended_ccalls = incall->next;
1700 incall->next->prev = incall->prev;
1702 incall->next = incall->prev = NULL;
1705 /* ---------------------------------------------------------------------------
1706 * Suspending & resuming Haskell threads.
1708 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1709 * its capability before calling the C function. This allows another
1710 * task to pick up the capability and carry on running Haskell
1711 * threads. It also means that if the C call blocks, it won't lock
1714 * The Haskell thread making the C call is put to sleep for the
1715 * duration of the call, on the susepended_ccalling_threads queue. We
1716 * give out a token to the task, which it can use to resume the thread
1717 * on return from the C function.
1718 * ------------------------------------------------------------------------- */
1721 suspendThread (StgRegTable *reg)
1728 StgWord32 saved_winerror;
1731 saved_errno = errno;
1733 saved_winerror = GetLastError();
1736 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1738 cap = regTableToCapability(reg);
1740 task = cap->running_task;
1741 tso = cap->r.rCurrentTSO;
1743 traceEventStopThread(cap, tso, THREAD_SUSPENDED_FOREIGN_CALL);
1745 // XXX this might not be necessary --SDM
1746 tso->what_next = ThreadRunGHC;
1748 threadPaused(cap,tso);
1750 if ((tso->flags & TSO_BLOCKEX) == 0) {
1751 tso->why_blocked = BlockedOnCCall;
1752 tso->flags |= TSO_BLOCKEX;
1753 tso->flags &= ~TSO_INTERRUPTIBLE;
1755 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1758 // Hand back capability
1759 task->incall->suspended_tso = tso;
1760 task->incall->suspended_cap = cap;
1762 ACQUIRE_LOCK(&cap->lock);
1764 suspendTask(cap,task);
1765 cap->in_haskell = rtsFalse;
1766 releaseCapability_(cap,rtsFalse);
1768 RELEASE_LOCK(&cap->lock);
1770 errno = saved_errno;
1772 SetLastError(saved_winerror);
1778 resumeThread (void *task_)
1786 StgWord32 saved_winerror;
1789 saved_errno = errno;
1791 saved_winerror = GetLastError();
1794 incall = task->incall;
1795 cap = incall->suspended_cap;
1798 // Wait for permission to re-enter the RTS with the result.
1799 waitForReturnCapability(&cap,task);
1800 // we might be on a different capability now... but if so, our
1801 // entry on the suspended_ccalls list will also have been
1804 // Remove the thread from the suspended list
1805 recoverSuspendedTask(cap,task);
1807 tso = incall->suspended_tso;
1808 incall->suspended_tso = NULL;
1809 incall->suspended_cap = NULL;
1810 tso->_link = END_TSO_QUEUE; // no write barrier reqd
1812 traceEventRunThread(cap, tso);
1814 if (tso->why_blocked == BlockedOnCCall) {
1815 // avoid locking the TSO if we don't have to
1816 if (tso->blocked_exceptions != END_BLOCKED_EXCEPTIONS_QUEUE) {
1817 awakenBlockedExceptionQueue(cap,tso);
1819 tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
1822 /* Reset blocking status */
1823 tso->why_blocked = NotBlocked;
1825 cap->r.rCurrentTSO = tso;
1826 cap->in_haskell = rtsTrue;
1827 errno = saved_errno;
1829 SetLastError(saved_winerror);
1832 /* We might have GC'd, mark the TSO dirty again */
1835 IF_DEBUG(sanity, checkTSO(tso));
1840 /* ---------------------------------------------------------------------------
1843 * scheduleThread puts a thread on the end of the runnable queue.
1844 * This will usually be done immediately after a thread is created.
1845 * The caller of scheduleThread must create the thread using e.g.
1846 * createThread and push an appropriate closure
1847 * on this thread's stack before the scheduler is invoked.
1848 * ------------------------------------------------------------------------ */
1851 scheduleThread(Capability *cap, StgTSO *tso)
1853 // The thread goes at the *end* of the run-queue, to avoid possible
1854 // starvation of any threads already on the queue.
1855 appendToRunQueue(cap,tso);
1859 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
1861 #if defined(THREADED_RTS)
1862 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
1863 // move this thread from now on.
1864 cpu %= RtsFlags.ParFlags.nNodes;
1865 if (cpu == cap->no) {
1866 appendToRunQueue(cap,tso);
1868 migrateThread(cap, tso, &capabilities[cpu]);
1871 appendToRunQueue(cap,tso);
1876 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
1881 // We already created/initialised the Task
1882 task = cap->running_task;
1884 // This TSO is now a bound thread; make the Task and TSO
1885 // point to each other.
1886 tso->bound = task->incall;
1889 task->incall->tso = tso;
1890 task->incall->ret = ret;
1891 task->incall->stat = NoStatus;
1893 appendToRunQueue(cap,tso);
1896 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)id);
1898 cap = schedule(cap,task);
1900 ASSERT(task->incall->stat != NoStatus);
1901 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
1903 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)id);
1907 /* ----------------------------------------------------------------------------
1909 * ------------------------------------------------------------------------- */
1911 #if defined(THREADED_RTS)
1912 void scheduleWorker (Capability *cap, Task *task)
1914 // schedule() runs without a lock.
1915 cap = schedule(cap,task);
1917 // On exit from schedule(), we have a Capability, but possibly not
1918 // the same one we started with.
1920 // During shutdown, the requirement is that after all the
1921 // Capabilities are shut down, all workers that are shutting down
1922 // have finished workerTaskStop(). This is why we hold on to
1923 // cap->lock until we've finished workerTaskStop() below.
1925 // There may be workers still involved in foreign calls; those
1926 // will just block in waitForReturnCapability() because the
1927 // Capability has been shut down.
1929 ACQUIRE_LOCK(&cap->lock);
1930 releaseCapability_(cap,rtsFalse);
1931 workerTaskStop(task);
1932 RELEASE_LOCK(&cap->lock);
1936 /* ---------------------------------------------------------------------------
1939 * Initialise the scheduler. This resets all the queues - if the
1940 * queues contained any threads, they'll be garbage collected at the
1943 * ------------------------------------------------------------------------ */
1948 #if !defined(THREADED_RTS)
1949 blocked_queue_hd = END_TSO_QUEUE;
1950 blocked_queue_tl = END_TSO_QUEUE;
1951 sleeping_queue = END_TSO_QUEUE;
1954 sched_state = SCHED_RUNNING;
1955 recent_activity = ACTIVITY_YES;
1957 #if defined(THREADED_RTS)
1958 /* Initialise the mutex and condition variables used by
1960 initMutex(&sched_mutex);
1963 ACQUIRE_LOCK(&sched_mutex);
1965 /* A capability holds the state a native thread needs in
1966 * order to execute STG code. At least one capability is
1967 * floating around (only THREADED_RTS builds have more than one).
1973 #if defined(THREADED_RTS)
1977 RELEASE_LOCK(&sched_mutex);
1979 #if defined(THREADED_RTS)
1981 * Eagerly start one worker to run each Capability, except for
1982 * Capability 0. The idea is that we're probably going to start a
1983 * bound thread on Capability 0 pretty soon, so we don't want a
1984 * worker task hogging it.
1989 for (i = 1; i < n_capabilities; i++) {
1990 cap = &capabilities[i];
1991 ACQUIRE_LOCK(&cap->lock);
1992 startWorkerTask(cap);
1993 RELEASE_LOCK(&cap->lock);
2000 exitScheduler (rtsBool wait_foreign USED_IF_THREADS)
2001 /* see Capability.c, shutdownCapability() */
2005 task = newBoundTask();
2007 // If we haven't killed all the threads yet, do it now.
2008 if (sched_state < SCHED_SHUTTING_DOWN) {
2009 sched_state = SCHED_INTERRUPTING;
2010 waitForReturnCapability(&task->cap,task);
2011 scheduleDoGC(task->cap,task,rtsFalse);
2012 ASSERT(task->incall->tso == NULL);
2013 releaseCapability(task->cap);
2015 sched_state = SCHED_SHUTTING_DOWN;
2017 #if defined(THREADED_RTS)
2021 for (i = 0; i < n_capabilities; i++) {
2022 ASSERT(task->incall->tso == NULL);
2023 shutdownCapability(&capabilities[i], task, wait_foreign);
2028 boundTaskExiting(task);
2032 freeScheduler( void )
2036 ACQUIRE_LOCK(&sched_mutex);
2037 still_running = freeTaskManager();
2038 // We can only free the Capabilities if there are no Tasks still
2039 // running. We might have a Task about to return from a foreign
2040 // call into waitForReturnCapability(), for example (actually,
2041 // this should be the *only* thing that a still-running Task can
2042 // do at this point, and it will block waiting for the
2044 if (still_running == 0) {
2046 if (n_capabilities != 1) {
2047 stgFree(capabilities);
2050 RELEASE_LOCK(&sched_mutex);
2051 #if defined(THREADED_RTS)
2052 closeMutex(&sched_mutex);
2056 /* -----------------------------------------------------------------------------
2059 This is the interface to the garbage collector from Haskell land.
2060 We provide this so that external C code can allocate and garbage
2061 collect when called from Haskell via _ccall_GC.
2062 -------------------------------------------------------------------------- */
2065 performGC_(rtsBool force_major)
2069 // We must grab a new Task here, because the existing Task may be
2070 // associated with a particular Capability, and chained onto the
2071 // suspended_ccalls queue.
2072 task = newBoundTask();
2074 waitForReturnCapability(&task->cap,task);
2075 scheduleDoGC(task->cap,task,force_major);
2076 releaseCapability(task->cap);
2077 boundTaskExiting(task);
2083 performGC_(rtsFalse);
2087 performMajorGC(void)
2089 performGC_(rtsTrue);
2092 /* -----------------------------------------------------------------------------
2095 If the thread has reached its maximum stack size, then raise the
2096 StackOverflow exception in the offending thread. Otherwise
2097 relocate the TSO into a larger chunk of memory and adjust its stack
2099 -------------------------------------------------------------------------- */
2102 threadStackOverflow(Capability *cap, StgTSO *tso)
2104 nat new_stack_size, stack_words;
2109 IF_DEBUG(sanity,checkTSO(tso));
2111 if (tso->stack_size >= tso->max_stack_size
2112 && !(tso->flags & TSO_BLOCKEX)) {
2113 // NB. never raise a StackOverflow exception if the thread is
2114 // inside Control.Exceptino.block. It is impractical to protect
2115 // against stack overflow exceptions, since virtually anything
2116 // can raise one (even 'catch'), so this is the only sensible
2117 // thing to do here. See bug #767.
2120 if (tso->flags & TSO_SQUEEZED) {
2123 // #3677: In a stack overflow situation, stack squeezing may
2124 // reduce the stack size, but we don't know whether it has been
2125 // reduced enough for the stack check to succeed if we try
2126 // again. Fortunately stack squeezing is idempotent, so all we
2127 // need to do is record whether *any* squeezing happened. If we
2128 // are at the stack's absolute -K limit, and stack squeezing
2129 // happened, then we try running the thread again. The
2130 // TSO_SQUEEZED flag is set by threadPaused() to tell us whether
2131 // squeezing happened or not.
2133 debugTrace(DEBUG_gc,
2134 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2135 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2137 /* If we're debugging, just print out the top of the stack */
2138 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2141 // Send this thread the StackOverflow exception
2142 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2147 // We also want to avoid enlarging the stack if squeezing has
2148 // already released some of it. However, we don't want to get into
2149 // a pathalogical situation where a thread has a nearly full stack
2150 // (near its current limit, but not near the absolute -K limit),
2151 // keeps allocating a little bit, squeezing removes a little bit,
2152 // and then it runs again. So to avoid this, if we squeezed *and*
2153 // there is still less than BLOCK_SIZE_W words free, then we enlarge
2154 // the stack anyway.
2155 if ((tso->flags & TSO_SQUEEZED) &&
2156 ((W_)(tso->sp - tso->stack) >= BLOCK_SIZE_W)) {
2160 /* Try to double the current stack size. If that takes us over the
2161 * maximum stack size for this thread, then use the maximum instead
2162 * (that is, unless we're already at or over the max size and we
2163 * can't raise the StackOverflow exception (see above), in which
2164 * case just double the size). Finally round up so the TSO ends up as
2165 * a whole number of blocks.
2167 if (tso->stack_size >= tso->max_stack_size) {
2168 new_stack_size = tso->stack_size * 2;
2170 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2172 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2173 TSO_STRUCT_SIZE)/sizeof(W_);
2174 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2175 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2177 debugTrace(DEBUG_sched,
2178 "increasing stack size from %ld words to %d.",
2179 (long)tso->stack_size, new_stack_size);
2181 dest = (StgTSO *)allocate(cap,new_tso_size);
2182 TICK_ALLOC_TSO(new_stack_size,0);
2184 /* copy the TSO block and the old stack into the new area */
2185 memcpy(dest,tso,TSO_STRUCT_SIZE);
2186 stack_words = tso->stack + tso->stack_size - tso->sp;
2187 new_sp = (P_)dest + new_tso_size - stack_words;
2188 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2190 /* relocate the stack pointers... */
2192 dest->stack_size = new_stack_size;
2194 /* Mark the old TSO as relocated. We have to check for relocated
2195 * TSOs in the garbage collector and any primops that deal with TSOs.
2197 * It's important to set the sp value to just beyond the end
2198 * of the stack, so we don't attempt to scavenge any part of the
2201 setTSOLink(cap,tso,dest);
2202 write_barrier(); // other threads seeing ThreadRelocated will look at _link
2203 tso->what_next = ThreadRelocated;
2204 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2205 tso->why_blocked = NotBlocked;
2207 IF_DEBUG(sanity,checkTSO(dest));
2209 IF_DEBUG(scheduler,printTSO(dest));
2216 threadStackUnderflow (Capability *cap, Task *task, StgTSO *tso)
2218 bdescr *bd, *new_bd;
2219 lnat free_w, tso_size_w;
2222 tso_size_w = tso_sizeW(tso);
2224 if (tso_size_w < MBLOCK_SIZE_W ||
2225 // TSO is less than 2 mblocks (since the first mblock is
2226 // shorter than MBLOCK_SIZE_W)
2227 (tso_size_w - BLOCKS_PER_MBLOCK*BLOCK_SIZE_W) % MBLOCK_SIZE_W != 0 ||
2228 // or TSO is not a whole number of megablocks (ensuring
2229 // precondition of splitLargeBlock() below)
2230 (tso_size_w <= round_up_to_mblocks(RtsFlags.GcFlags.initialStkSize)) ||
2231 // or TSO is smaller than the minimum stack size (rounded up)
2232 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2233 // or stack is using more than 1/4 of the available space
2239 // this is the number of words we'll free
2240 free_w = round_to_mblocks(tso_size_w/2);
2242 bd = Bdescr((StgPtr)tso);
2243 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2244 bd->free = bd->start + TSO_STRUCT_SIZEW;
2246 new_tso = (StgTSO *)new_bd->start;
2247 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2248 new_tso->stack_size = new_bd->free - new_tso->stack;
2250 // The original TSO was dirty and probably on the mutable
2251 // list. The new TSO is not yet on the mutable list, so we better
2254 new_tso->flags &= ~TSO_LINK_DIRTY;
2255 dirty_TSO(cap, new_tso);
2257 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2258 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2260 tso->_link = new_tso; // no write barrier reqd: same generation
2261 write_barrier(); // other threads seeing ThreadRelocated will look at _link
2262 tso->what_next = ThreadRelocated;
2264 // The TSO attached to this Task may have moved, so update the
2266 if (task->incall->tso == tso) {
2267 task->incall->tso = new_tso;
2270 IF_DEBUG(sanity,checkTSO(new_tso));
2275 /* ---------------------------------------------------------------------------
2277 - usually called inside a signal handler so it mustn't do anything fancy.
2278 ------------------------------------------------------------------------ */
2281 interruptStgRts(void)
2283 sched_state = SCHED_INTERRUPTING;
2284 setContextSwitches();
2285 #if defined(THREADED_RTS)
2290 /* -----------------------------------------------------------------------------
2293 This function causes at least one OS thread to wake up and run the
2294 scheduler loop. It is invoked when the RTS might be deadlocked, or
2295 an external event has arrived that may need servicing (eg. a
2296 keyboard interrupt).
2298 In the single-threaded RTS we don't do anything here; we only have
2299 one thread anyway, and the event that caused us to want to wake up
2300 will have interrupted any blocking system call in progress anyway.
2301 -------------------------------------------------------------------------- */
2303 #if defined(THREADED_RTS)
2304 void wakeUpRts(void)
2306 // This forces the IO Manager thread to wakeup, which will
2307 // in turn ensure that some OS thread wakes up and runs the
2308 // scheduler loop, which will cause a GC and deadlock check.
2313 /* -----------------------------------------------------------------------------
2316 This is used for interruption (^C) and forking, and corresponds to
2317 raising an exception but without letting the thread catch the
2319 -------------------------------------------------------------------------- */
2322 deleteThread (Capability *cap STG_UNUSED, StgTSO *tso)
2324 // NOTE: must only be called on a TSO that we have exclusive
2325 // access to, because we will call throwToSingleThreaded() below.
2326 // The TSO must be on the run queue of the Capability we own, or
2327 // we must own all Capabilities.
2329 if (tso->why_blocked != BlockedOnCCall &&
2330 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2331 throwToSingleThreaded(tso->cap,tso,NULL);
2335 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2337 deleteThread_(Capability *cap, StgTSO *tso)
2338 { // for forkProcess only:
2339 // like deleteThread(), but we delete threads in foreign calls, too.
2341 if (tso->why_blocked == BlockedOnCCall ||
2342 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2343 tso->what_next = ThreadKilled;
2344 appendToRunQueue(tso->cap, tso);
2346 deleteThread(cap,tso);
2351 /* -----------------------------------------------------------------------------
2352 raiseExceptionHelper
2354 This function is called by the raise# primitve, just so that we can
2355 move some of the tricky bits of raising an exception from C-- into
2356 C. Who knows, it might be a useful re-useable thing here too.
2357 -------------------------------------------------------------------------- */
2360 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2362 Capability *cap = regTableToCapability(reg);
2363 StgThunk *raise_closure = NULL;
2365 StgRetInfoTable *info;
2367 // This closure represents the expression 'raise# E' where E
2368 // is the exception raise. It is used to overwrite all the
2369 // thunks which are currently under evaluataion.
2372 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2373 // LDV profiling: stg_raise_info has THUNK as its closure
2374 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2375 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2376 // 1 does not cause any problem unless profiling is performed.
2377 // However, when LDV profiling goes on, we need to linearly scan
2378 // small object pool, where raise_closure is stored, so we should
2379 // use MIN_UPD_SIZE.
2381 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2382 // sizeofW(StgClosure)+1);
2386 // Walk up the stack, looking for the catch frame. On the way,
2387 // we update any closures pointed to from update frames with the
2388 // raise closure that we just built.
2392 info = get_ret_itbl((StgClosure *)p);
2393 next = p + stack_frame_sizeW((StgClosure *)p);
2394 switch (info->i.type) {
2397 // Only create raise_closure if we need to.
2398 if (raise_closure == NULL) {
2400 (StgThunk *)allocate(cap,sizeofW(StgThunk)+1);
2401 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2402 raise_closure->payload[0] = exception;
2404 updateThunk(cap, tso, ((StgUpdateFrame *)p)->updatee,
2405 (StgClosure *)raise_closure);
2409 case ATOMICALLY_FRAME:
2410 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2412 return ATOMICALLY_FRAME;
2418 case CATCH_STM_FRAME:
2419 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2421 return CATCH_STM_FRAME;
2427 case CATCH_RETRY_FRAME:
2436 /* -----------------------------------------------------------------------------
2437 findRetryFrameHelper
2439 This function is called by the retry# primitive. It traverses the stack
2440 leaving tso->sp referring to the frame which should handle the retry.
2442 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2443 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2445 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2446 create) because retries are not considered to be exceptions, despite the
2447 similar implementation.
2449 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2450 not be created within memory transactions.
2451 -------------------------------------------------------------------------- */
2454 findRetryFrameHelper (StgTSO *tso)
2457 StgRetInfoTable *info;
2461 info = get_ret_itbl((StgClosure *)p);
2462 next = p + stack_frame_sizeW((StgClosure *)p);
2463 switch (info->i.type) {
2465 case ATOMICALLY_FRAME:
2466 debugTrace(DEBUG_stm,
2467 "found ATOMICALLY_FRAME at %p during retry", p);
2469 return ATOMICALLY_FRAME;
2471 case CATCH_RETRY_FRAME:
2472 debugTrace(DEBUG_stm,
2473 "found CATCH_RETRY_FRAME at %p during retrry", p);
2475 return CATCH_RETRY_FRAME;
2477 case CATCH_STM_FRAME: {
2478 StgTRecHeader *trec = tso -> trec;
2479 StgTRecHeader *outer = trec -> enclosing_trec;
2480 debugTrace(DEBUG_stm,
2481 "found CATCH_STM_FRAME at %p during retry", p);
2482 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2483 stmAbortTransaction(tso -> cap, trec);
2484 stmFreeAbortedTRec(tso -> cap, trec);
2485 tso -> trec = outer;
2492 ASSERT(info->i.type != CATCH_FRAME);
2493 ASSERT(info->i.type != STOP_FRAME);
2500 /* -----------------------------------------------------------------------------
2501 resurrectThreads is called after garbage collection on the list of
2502 threads found to be garbage. Each of these threads will be woken
2503 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2504 on an MVar, or NonTermination if the thread was blocked on a Black
2507 Locks: assumes we hold *all* the capabilities.
2508 -------------------------------------------------------------------------- */
2511 resurrectThreads (StgTSO *threads)
2517 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2518 next = tso->global_link;
2520 gen = Bdescr((P_)tso)->gen;
2521 tso->global_link = gen->threads;
2524 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2526 // Wake up the thread on the Capability it was last on
2529 switch (tso->why_blocked) {
2531 /* Called by GC - sched_mutex lock is currently held. */
2532 throwToSingleThreaded(cap, tso,
2533 (StgClosure *)blockedIndefinitelyOnMVar_closure);
2535 case BlockedOnBlackHole:
2536 throwToSingleThreaded(cap, tso,
2537 (StgClosure *)nonTermination_closure);
2540 throwToSingleThreaded(cap, tso,
2541 (StgClosure *)blockedIndefinitelyOnSTM_closure);
2544 /* This might happen if the thread was blocked on a black hole
2545 * belonging to a thread that we've just woken up (raiseAsync
2546 * can wake up threads, remember...).
2549 case BlockedOnMsgThrowTo:
2550 // This can happen if the target is masking, blocks on a
2551 // black hole, and then is found to be unreachable. In
2552 // this case, we want to let the target wake up and carry
2553 // on, and do nothing to this thread.
2556 barf("resurrectThreads: thread blocked in a strange way: %d",