1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2006
5 * The scheduler and thread-related functionality
7 * --------------------------------------------------------------------------*/
9 #include "PosixSource.h"
10 #define KEEP_LOCKCLOSURE
13 #include "sm/Storage.h"
17 #include "Interpreter.h"
19 #include "RtsSignals.h"
20 #include "sm/Sanity.h"
24 #include "ThreadLabels.h"
26 #include "Proftimer.h"
29 #include "sm/GC.h" // waitForGcThreads, releaseGCThreads, N
31 #include "Capability.h"
33 #include "AwaitEvent.h"
34 #if defined(mingw32_HOST_OS)
35 #include "win32/IOManager.h"
38 #include "RaiseAsync.h"
41 #include "ThreadPaused.h"
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
59 /* -----------------------------------------------------------------------------
61 * -------------------------------------------------------------------------- */
63 #if !defined(THREADED_RTS)
64 // Blocked/sleeping thrads
65 StgTSO *blocked_queue_hd = NULL;
66 StgTSO *blocked_queue_tl = NULL;
67 StgTSO *sleeping_queue = NULL; // perhaps replace with a hash table?
70 /* Set to true when the latest garbage collection failed to reclaim
71 * enough space, and the runtime should proceed to shut itself down in
72 * an orderly fashion (emitting profiling info etc.)
74 rtsBool heap_overflow = rtsFalse;
76 /* flag that tracks whether we have done any execution in this time slice.
77 * LOCK: currently none, perhaps we should lock (but needs to be
78 * updated in the fast path of the scheduler).
80 * NB. must be StgWord, we do xchg() on it.
82 volatile StgWord recent_activity = ACTIVITY_YES;
84 /* if this flag is set as well, give up execution
85 * LOCK: none (changes monotonically)
87 volatile StgWord sched_state = SCHED_RUNNING;
89 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
90 * exists - earlier gccs apparently didn't.
96 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
97 * in an MT setting, needed to signal that a worker thread shouldn't hang around
98 * in the scheduler when it is out of work.
100 rtsBool shutting_down_scheduler = rtsFalse;
103 * This mutex protects most of the global scheduler data in
104 * the THREADED_RTS runtime.
106 #if defined(THREADED_RTS)
110 #if !defined(mingw32_HOST_OS)
111 #define FORKPROCESS_PRIMOP_SUPPORTED
114 /* -----------------------------------------------------------------------------
115 * static function prototypes
116 * -------------------------------------------------------------------------- */
118 static Capability *schedule (Capability *initialCapability, Task *task);
121 // These function all encapsulate parts of the scheduler loop, and are
122 // abstracted only to make the structure and control flow of the
123 // scheduler clearer.
125 static void schedulePreLoop (void);
126 static void scheduleFindWork (Capability *cap);
127 #if defined(THREADED_RTS)
128 static void scheduleYield (Capability **pcap, Task *task, rtsBool);
130 static void scheduleStartSignalHandlers (Capability *cap);
131 static void scheduleCheckBlockedThreads (Capability *cap);
132 static void scheduleProcessInbox(Capability *cap);
133 static void scheduleDetectDeadlock (Capability *cap, Task *task);
134 static void schedulePushWork(Capability *cap, Task *task);
135 #if defined(THREADED_RTS)
136 static void scheduleActivateSpark(Capability *cap);
138 static void schedulePostRunThread(Capability *cap, StgTSO *t);
139 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
140 static void scheduleHandleStackOverflow( Capability *cap, Task *task,
142 static rtsBool scheduleHandleYield( Capability *cap, StgTSO *t,
143 nat prev_what_next );
144 static void scheduleHandleThreadBlocked( StgTSO *t );
145 static rtsBool scheduleHandleThreadFinished( Capability *cap, Task *task,
147 static rtsBool scheduleNeedHeapProfile(rtsBool ready_to_gc);
148 static Capability *scheduleDoGC(Capability *cap, Task *task,
149 rtsBool force_major);
151 static StgTSO *threadStackOverflow(Capability *cap, StgTSO *tso);
152 static StgTSO *threadStackUnderflow(Capability *cap, Task *task, StgTSO *tso);
154 static void deleteThread (Capability *cap, StgTSO *tso);
155 static void deleteAllThreads (Capability *cap);
157 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
158 static void deleteThread_(Capability *cap, StgTSO *tso);
161 /* ---------------------------------------------------------------------------
162 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;
207 rtsBool force_yield = rtsFalse;
210 cap = initialCapability;
212 // Pre-condition: this task owns initialCapability.
213 // The sched_mutex is *NOT* held
214 // NB. on return, we still hold a capability.
216 debugTrace (DEBUG_sched, "cap %d: schedule()", initialCapability->no);
220 // -----------------------------------------------------------
221 // Scheduler loop starts here:
225 // Check whether we have re-entered the RTS from Haskell without
226 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
228 if (cap->in_haskell) {
229 errorBelch("schedule: re-entered unsafely.\n"
230 " Perhaps a 'foreign import unsafe' should be 'safe'?");
231 stg_exit(EXIT_FAILURE);
234 // The interruption / shutdown sequence.
236 // In order to cleanly shut down the runtime, we want to:
237 // * make sure that all main threads return to their callers
238 // with the state 'Interrupted'.
239 // * clean up all OS threads assocated with the runtime
240 // * free all memory etc.
242 // So the sequence for ^C goes like this:
244 // * ^C handler sets sched_state := SCHED_INTERRUPTING and
245 // arranges for some Capability to wake up
247 // * all threads in the system are halted, and the zombies are
248 // placed on the run queue for cleaning up. We acquire all
249 // the capabilities in order to delete the threads, this is
250 // done by scheduleDoGC() for convenience (because GC already
251 // needs to acquire all the capabilities). We can't kill
252 // threads involved in foreign calls.
254 // * somebody calls shutdownHaskell(), which calls exitScheduler()
256 // * sched_state := SCHED_SHUTTING_DOWN
258 // * all workers exit when the run queue on their capability
259 // drains. All main threads will also exit when their TSO
260 // reaches the head of the run queue and they can return.
262 // * eventually all Capabilities will shut down, and the RTS can
265 // * We might be left with threads blocked in foreign calls,
266 // we should really attempt to kill these somehow (TODO);
268 switch (sched_state) {
271 case SCHED_INTERRUPTING:
272 debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
273 #if defined(THREADED_RTS)
274 discardSparksCap(cap);
276 /* scheduleDoGC() deletes all the threads */
277 cap = scheduleDoGC(cap,task,rtsFalse);
279 // after scheduleDoGC(), we must be shutting down. Either some
280 // other Capability did the final GC, or we did it above,
281 // either way we can fall through to the SCHED_SHUTTING_DOWN
283 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
286 case SCHED_SHUTTING_DOWN:
287 debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
288 // If we are a worker, just exit. If we're a bound thread
289 // then we will exit below when we've removed our TSO from
291 if (!isBoundTask(task) && emptyRunQueue(cap)) {
296 barf("sched_state: %d", sched_state);
299 scheduleFindWork(cap);
301 /* work pushing, currently relevant only for THREADED_RTS:
302 (pushes threads, wakes up idle capabilities for stealing) */
303 schedulePushWork(cap,task);
305 scheduleDetectDeadlock(cap,task);
307 #if defined(THREADED_RTS)
308 cap = task->cap; // reload cap, it might have changed
311 // Normally, the only way we can get here with no threads to
312 // run is if a keyboard interrupt received during
313 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
314 // Additionally, it is not fatal for the
315 // threaded RTS to reach here with no threads to run.
317 // win32: might be here due to awaitEvent() being abandoned
318 // as a result of a console event having been delivered.
320 #if defined(THREADED_RTS)
324 // // don't yield the first time, we want a chance to run this
325 // // thread for a bit, even if there are others banging at the
328 // ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
332 scheduleYield(&cap,task,force_yield);
333 force_yield = rtsFalse;
335 if (emptyRunQueue(cap)) continue; // look for work again
338 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
339 if ( emptyRunQueue(cap) ) {
340 ASSERT(sched_state >= SCHED_INTERRUPTING);
345 // Get a thread to run
347 t = popRunQueue(cap);
349 // Sanity check the thread we're about to run. This can be
350 // expensive if there is lots of thread switching going on...
351 IF_DEBUG(sanity,checkTSO(t));
353 #if defined(THREADED_RTS)
354 // Check whether we can run this thread in the current task.
355 // If not, we have to pass our capability to the right task.
357 InCall *bound = t->bound;
360 if (bound->task == task) {
361 // yes, the Haskell thread is bound to the current native thread
363 debugTrace(DEBUG_sched,
364 "thread %lu bound to another OS thread",
365 (unsigned long)t->id);
366 // no, bound to a different Haskell thread: pass to that thread
367 pushOnRunQueue(cap,t);
371 // The thread we want to run is unbound.
372 if (task->incall->tso) {
373 debugTrace(DEBUG_sched,
374 "this OS thread cannot run thread %lu",
375 (unsigned long)t->id);
376 // no, the current native thread is bound to a different
377 // Haskell thread, so pass it to any worker thread
378 pushOnRunQueue(cap,t);
385 // If we're shutting down, and this thread has not yet been
386 // killed, kill it now. This sometimes happens when a finalizer
387 // thread is created by the final GC, or a thread previously
388 // in a foreign call returns.
389 if (sched_state >= SCHED_INTERRUPTING &&
390 !(t->what_next == ThreadComplete || t->what_next == ThreadKilled)) {
394 /* context switches are initiated by the timer signal, unless
395 * the user specified "context switch as often as possible", with
398 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
399 && !emptyThreadQueues(cap)) {
400 cap->context_switch = 1;
405 // CurrentTSO is the thread to run. t might be different if we
406 // loop back to run_thread, so make sure to set CurrentTSO after
408 cap->r.rCurrentTSO = t;
410 startHeapProfTimer();
412 // ----------------------------------------------------------------------
413 // Run the current thread
415 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
416 ASSERT(t->cap == cap);
417 ASSERT(t->bound ? t->bound->task->cap == cap : 1);
419 prev_what_next = t->what_next;
421 errno = t->saved_errno;
423 SetLastError(t->saved_winerror);
426 cap->in_haskell = rtsTrue;
430 #if defined(THREADED_RTS)
431 if (recent_activity == ACTIVITY_DONE_GC) {
432 // ACTIVITY_DONE_GC means we turned off the timer signal to
433 // conserve power (see #1623). Re-enable it here.
435 prev = xchg((P_)&recent_activity, ACTIVITY_YES);
436 if (prev == ACTIVITY_DONE_GC) {
439 } else if (recent_activity != ACTIVITY_INACTIVE) {
440 // If we reached ACTIVITY_INACTIVE, then don't reset it until
441 // we've done the GC. The thread running here might just be
442 // the IO manager thread that handle_tick() woke up via
444 recent_activity = ACTIVITY_YES;
448 traceEventRunThread(cap, t);
450 switch (prev_what_next) {
454 /* Thread already finished, return to scheduler. */
455 ret = ThreadFinished;
461 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
462 cap = regTableToCapability(r);
467 case ThreadInterpret:
468 cap = interpretBCO(cap);
473 barf("schedule: invalid what_next field");
476 cap->in_haskell = rtsFalse;
478 // The TSO might have moved, eg. if it re-entered the RTS and a GC
479 // happened. So find the new location:
480 t = cap->r.rCurrentTSO;
482 // And save the current errno in this thread.
483 // XXX: possibly bogus for SMP because this thread might already
484 // be running again, see code below.
485 t->saved_errno = errno;
487 // Similarly for Windows error code
488 t->saved_winerror = GetLastError();
491 traceEventStopThread(cap, t, ret);
493 #if defined(THREADED_RTS)
494 // If ret is ThreadBlocked, and this Task is bound to the TSO that
495 // blocked, we are in limbo - the TSO is now owned by whatever it
496 // is blocked on, and may in fact already have been woken up,
497 // perhaps even on a different Capability. It may be the case
498 // that task->cap != cap. We better yield this Capability
499 // immediately and return to normaility.
500 if (ret == ThreadBlocked) {
501 force_yield = rtsTrue;
506 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
507 ASSERT(t->cap == cap);
509 // ----------------------------------------------------------------------
511 // Costs for the scheduler are assigned to CCS_SYSTEM
513 #if defined(PROFILING)
517 schedulePostRunThread(cap,t);
519 if (ret != StackOverflow) {
520 t = threadStackUnderflow(cap,task,t);
523 ready_to_gc = rtsFalse;
527 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
531 scheduleHandleStackOverflow(cap,task,t);
535 if (scheduleHandleYield(cap, t, prev_what_next)) {
536 // shortcut for switching between compiler/interpreter:
542 scheduleHandleThreadBlocked(t);
546 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
547 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
551 barf("schedule: invalid thread return code %d", (int)ret);
554 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
555 cap = scheduleDoGC(cap,task,rtsFalse);
557 } /* end of while() */
560 /* -----------------------------------------------------------------------------
561 * Run queue operations
562 * -------------------------------------------------------------------------- */
565 removeFromRunQueue (Capability *cap, StgTSO *tso)
567 if (tso->block_info.prev == END_TSO_QUEUE) {
568 ASSERT(cap->run_queue_hd == tso);
569 cap->run_queue_hd = tso->_link;
571 setTSOLink(cap, tso->block_info.prev, tso->_link);
573 if (tso->_link == END_TSO_QUEUE) {
574 ASSERT(cap->run_queue_tl == tso);
575 cap->run_queue_tl = tso->block_info.prev;
577 setTSOPrev(cap, tso->_link, tso->block_info.prev);
579 tso->_link = tso->block_info.prev = END_TSO_QUEUE;
581 IF_DEBUG(sanity, checkRunQueue(cap));
584 /* ----------------------------------------------------------------------------
585 * Setting up the scheduler loop
586 * ------------------------------------------------------------------------- */
589 schedulePreLoop(void)
591 // initialisation for scheduler - what cannot go into initScheduler()
594 /* -----------------------------------------------------------------------------
597 * Search for work to do, and handle messages from elsewhere.
598 * -------------------------------------------------------------------------- */
601 scheduleFindWork (Capability *cap)
603 scheduleStartSignalHandlers(cap);
605 scheduleProcessInbox(cap);
607 scheduleCheckBlockedThreads(cap);
609 #if defined(THREADED_RTS)
610 if (emptyRunQueue(cap)) { scheduleActivateSpark(cap); }
614 #if defined(THREADED_RTS)
615 STATIC_INLINE rtsBool
616 shouldYieldCapability (Capability *cap, Task *task)
618 // we need to yield this capability to someone else if..
619 // - another thread is initiating a GC
620 // - another Task is returning from a foreign call
621 // - the thread at the head of the run queue cannot be run
622 // by this Task (it is bound to another Task, or it is unbound
623 // and this task it bound).
624 return (waiting_for_gc ||
625 cap->returning_tasks_hd != NULL ||
626 (!emptyRunQueue(cap) && (task->incall->tso == NULL
627 ? cap->run_queue_hd->bound != NULL
628 : cap->run_queue_hd->bound != task->incall)));
631 // This is the single place where a Task goes to sleep. There are
632 // two reasons it might need to sleep:
633 // - there are no threads to run
634 // - we need to yield this Capability to someone else
635 // (see shouldYieldCapability())
637 // Careful: the scheduler loop is quite delicate. Make sure you run
638 // the tests in testsuite/concurrent (all ways) after modifying this,
639 // and also check the benchmarks in nofib/parallel for regressions.
642 scheduleYield (Capability **pcap, Task *task, rtsBool force_yield)
644 Capability *cap = *pcap;
646 // if we have work, and we don't need to give up the Capability, continue.
648 // The force_yield flag is used when a bound thread blocks. This
649 // is a particularly tricky situation: the current Task does not
650 // own the TSO any more, since it is on some queue somewhere, and
651 // might be woken up or manipulated by another thread at any time.
652 // The TSO and Task might be migrated to another Capability.
653 // Certain invariants might be in doubt, such as task->bound->cap
654 // == cap. We have to yield the current Capability immediately,
655 // no messing around.
658 !shouldYieldCapability(cap,task) &&
659 (!emptyRunQueue(cap) ||
661 sched_state >= SCHED_INTERRUPTING))
664 // otherwise yield (sleep), and keep yielding if necessary.
666 yieldCapability(&cap,task);
668 while (shouldYieldCapability(cap,task));
670 // note there may still be no threads on the run queue at this
671 // point, the caller has to check.
678 /* -----------------------------------------------------------------------------
681 * Push work to other Capabilities if we have some.
682 * -------------------------------------------------------------------------- */
685 schedulePushWork(Capability *cap USED_IF_THREADS,
686 Task *task USED_IF_THREADS)
688 /* following code not for PARALLEL_HASKELL. I kept the call general,
689 future GUM versions might use pushing in a distributed setup */
690 #if defined(THREADED_RTS)
692 Capability *free_caps[n_capabilities], *cap0;
695 // migration can be turned off with +RTS -qm
696 if (!RtsFlags.ParFlags.migrate) return;
698 // Check whether we have more threads on our run queue, or sparks
699 // in our pool, that we could hand to another Capability.
700 if (cap->run_queue_hd == END_TSO_QUEUE) {
701 if (sparkPoolSizeCap(cap) < 2) return;
703 if (cap->run_queue_hd->_link == END_TSO_QUEUE &&
704 sparkPoolSizeCap(cap) < 1) return;
707 // First grab as many free Capabilities as we can.
708 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
709 cap0 = &capabilities[i];
710 if (cap != cap0 && tryGrabCapability(cap0,task)) {
711 if (!emptyRunQueue(cap0)
712 || cap->returning_tasks_hd != NULL
713 || cap->inbox != (Message*)END_TSO_QUEUE) {
714 // it already has some work, we just grabbed it at
715 // the wrong moment. Or maybe it's deadlocked!
716 releaseCapability(cap0);
718 free_caps[n_free_caps++] = cap0;
723 // we now have n_free_caps free capabilities stashed in
724 // free_caps[]. Share our run queue equally with them. This is
725 // probably the simplest thing we could do; improvements we might
726 // want to do include:
728 // - giving high priority to moving relatively new threads, on
729 // the gournds that they haven't had time to build up a
730 // working set in the cache on this CPU/Capability.
732 // - giving low priority to moving long-lived threads
734 if (n_free_caps > 0) {
735 StgTSO *prev, *t, *next;
736 rtsBool pushed_to_all;
738 debugTrace(DEBUG_sched,
739 "cap %d: %s and %d free capabilities, sharing...",
741 (!emptyRunQueue(cap) && cap->run_queue_hd->_link != END_TSO_QUEUE)?
742 "excess threads on run queue":"sparks to share (>=2)",
746 pushed_to_all = rtsFalse;
748 if (cap->run_queue_hd != END_TSO_QUEUE) {
749 prev = cap->run_queue_hd;
751 prev->_link = END_TSO_QUEUE;
752 for (; t != END_TSO_QUEUE; t = next) {
754 t->_link = END_TSO_QUEUE;
755 if (t->what_next == ThreadRelocated
756 || t->bound == task->incall // don't move my bound thread
757 || tsoLocked(t)) { // don't move a locked thread
758 setTSOLink(cap, prev, t);
759 setTSOPrev(cap, t, prev);
761 } else if (i == n_free_caps) {
762 pushed_to_all = rtsTrue;
765 setTSOLink(cap, prev, t);
766 setTSOPrev(cap, t, prev);
769 appendToRunQueue(free_caps[i],t);
771 traceEventMigrateThread (cap, t, free_caps[i]->no);
773 if (t->bound) { t->bound->task->cap = free_caps[i]; }
774 t->cap = free_caps[i];
778 cap->run_queue_tl = prev;
780 IF_DEBUG(sanity, checkRunQueue(cap));
784 /* JB I left this code in place, it would work but is not necessary */
786 // If there are some free capabilities that we didn't push any
787 // threads to, then try to push a spark to each one.
788 if (!pushed_to_all) {
790 // i is the next free capability to push to
791 for (; i < n_free_caps; i++) {
792 if (emptySparkPoolCap(free_caps[i])) {
793 spark = tryStealSpark(cap->sparks);
795 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
797 traceEventStealSpark(free_caps[i], t, cap->no);
799 newSpark(&(free_caps[i]->r), spark);
804 #endif /* SPARK_PUSHING */
806 // release the capabilities
807 for (i = 0; i < n_free_caps; i++) {
808 task->cap = free_caps[i];
809 releaseAndWakeupCapability(free_caps[i]);
812 task->cap = cap; // reset to point to our Capability.
814 #endif /* THREADED_RTS */
818 /* ----------------------------------------------------------------------------
819 * Start any pending signal handlers
820 * ------------------------------------------------------------------------- */
822 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
824 scheduleStartSignalHandlers(Capability *cap)
826 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
827 // safe outside the lock
828 startSignalHandlers(cap);
833 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
838 /* ----------------------------------------------------------------------------
839 * Check for blocked threads that can be woken up.
840 * ------------------------------------------------------------------------- */
843 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
845 #if !defined(THREADED_RTS)
847 // Check whether any waiting threads need to be woken up. If the
848 // run queue is empty, and there are no other tasks running, we
849 // can wait indefinitely for something to happen.
851 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
853 awaitEvent (emptyRunQueue(cap));
858 /* ----------------------------------------------------------------------------
859 * Detect deadlock conditions and attempt to resolve them.
860 * ------------------------------------------------------------------------- */
863 scheduleDetectDeadlock (Capability *cap, Task *task)
866 * Detect deadlock: when we have no threads to run, there are no
867 * threads blocked, waiting for I/O, or sleeping, and all the
868 * other tasks are waiting for work, we must have a deadlock of
871 if ( emptyThreadQueues(cap) )
873 #if defined(THREADED_RTS)
875 * In the threaded RTS, we only check for deadlock if there
876 * has been no activity in a complete timeslice. This means
877 * we won't eagerly start a full GC just because we don't have
878 * any threads to run currently.
880 if (recent_activity != ACTIVITY_INACTIVE) return;
883 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
885 // Garbage collection can release some new threads due to
886 // either (a) finalizers or (b) threads resurrected because
887 // they are unreachable and will therefore be sent an
888 // exception. Any threads thus released will be immediately
890 cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
891 // when force_major == rtsTrue. scheduleDoGC sets
892 // recent_activity to ACTIVITY_DONE_GC and turns off the timer
895 if ( !emptyRunQueue(cap) ) return;
897 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
898 /* If we have user-installed signal handlers, then wait
899 * for signals to arrive rather then bombing out with a
902 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
903 debugTrace(DEBUG_sched,
904 "still deadlocked, waiting for signals...");
908 if (signals_pending()) {
909 startSignalHandlers(cap);
912 // either we have threads to run, or we were interrupted:
913 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
919 #if !defined(THREADED_RTS)
920 /* Probably a real deadlock. Send the current main thread the
921 * Deadlock exception.
923 if (task->incall->tso) {
924 switch (task->incall->tso->why_blocked) {
926 case BlockedOnBlackHole:
927 case BlockedOnMsgThrowTo:
929 throwToSingleThreaded(cap, task->incall->tso,
930 (StgClosure *)nonTermination_closure);
933 barf("deadlock: main thread blocked in a strange way");
942 /* ----------------------------------------------------------------------------
943 * Send pending messages (PARALLEL_HASKELL only)
944 * ------------------------------------------------------------------------- */
946 #if defined(PARALLEL_HASKELL)
948 scheduleSendPendingMessages(void)
951 # if defined(PAR) // global Mem.Mgmt., omit for now
952 if (PendingFetches != END_BF_QUEUE) {
957 if (RtsFlags.ParFlags.BufferTime) {
958 // if we use message buffering, we must send away all message
959 // packets which have become too old...
965 /* ----------------------------------------------------------------------------
966 * Process message in the current Capability's inbox
967 * ------------------------------------------------------------------------- */
970 scheduleProcessInbox (Capability *cap USED_IF_THREADS)
972 #if defined(THREADED_RTS)
975 while (!emptyInbox(cap)) {
976 ACQUIRE_LOCK(&cap->lock);
978 cap->inbox = m->link;
979 RELEASE_LOCK(&cap->lock);
980 executeMessage(cap, (Message *)m);
985 /* ----------------------------------------------------------------------------
986 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
987 * ------------------------------------------------------------------------- */
989 #if defined(THREADED_RTS)
991 scheduleActivateSpark(Capability *cap)
995 createSparkThread(cap);
996 debugTrace(DEBUG_sched, "creating a spark thread");
999 #endif // PARALLEL_HASKELL || THREADED_RTS
1001 /* ----------------------------------------------------------------------------
1002 * After running a thread...
1003 * ------------------------------------------------------------------------- */
1006 schedulePostRunThread (Capability *cap, StgTSO *t)
1008 // We have to be able to catch transactions that are in an
1009 // infinite loop as a result of seeing an inconsistent view of
1013 // [a,b] <- mapM readTVar [ta,tb]
1014 // when (a == b) loop
1016 // and a is never equal to b given a consistent view of memory.
1018 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1019 if (!stmValidateNestOfTransactions (t -> trec)) {
1020 debugTrace(DEBUG_sched | DEBUG_stm,
1021 "trec %p found wasting its time", t);
1023 // strip the stack back to the
1024 // ATOMICALLY_FRAME, aborting the (nested)
1025 // transaction, and saving the stack of any
1026 // partially-evaluated thunks on the heap.
1027 throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1029 // ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1033 /* some statistics gathering in the parallel case */
1036 /* -----------------------------------------------------------------------------
1037 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1038 * -------------------------------------------------------------------------- */
1041 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1043 // did the task ask for a large block?
1044 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1045 // if so, get one and push it on the front of the nursery.
1049 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1051 debugTrace(DEBUG_sched,
1052 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1053 (long)t->id, what_next_strs[t->what_next], blocks);
1055 // don't do this if the nursery is (nearly) full, we'll GC first.
1056 if (cap->r.rCurrentNursery->link != NULL ||
1057 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1058 // if the nursery has only one block.
1061 bd = allocGroup( blocks );
1063 cap->r.rNursery->n_blocks += blocks;
1065 // link the new group into the list
1066 bd->link = cap->r.rCurrentNursery;
1067 bd->u.back = cap->r.rCurrentNursery->u.back;
1068 if (cap->r.rCurrentNursery->u.back != NULL) {
1069 cap->r.rCurrentNursery->u.back->link = bd;
1071 cap->r.rNursery->blocks = bd;
1073 cap->r.rCurrentNursery->u.back = bd;
1075 // initialise it as a nursery block. We initialise the
1076 // step, gen_no, and flags field of *every* sub-block in
1077 // this large block, because this is easier than making
1078 // sure that we always find the block head of a large
1079 // block whenever we call Bdescr() (eg. evacuate() and
1080 // isAlive() in the GC would both have to do this, at
1084 for (x = bd; x < bd + blocks; x++) {
1085 initBdescr(x,g0,g0);
1091 // This assert can be a killer if the app is doing lots
1092 // of large block allocations.
1093 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1095 // now update the nursery to point to the new block
1096 cap->r.rCurrentNursery = bd;
1098 // we might be unlucky and have another thread get on the
1099 // run queue before us and steal the large block, but in that
1100 // case the thread will just end up requesting another large
1102 pushOnRunQueue(cap,t);
1103 return rtsFalse; /* not actually GC'ing */
1107 if (cap->r.rHpLim == NULL || cap->context_switch) {
1108 // Sometimes we miss a context switch, e.g. when calling
1109 // primitives in a tight loop, MAYBE_GC() doesn't check the
1110 // context switch flag, and we end up waiting for a GC.
1111 // See #1984, and concurrent/should_run/1984
1112 cap->context_switch = 0;
1113 appendToRunQueue(cap,t);
1115 pushOnRunQueue(cap,t);
1118 /* actual GC is done at the end of the while loop in schedule() */
1121 /* -----------------------------------------------------------------------------
1122 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1123 * -------------------------------------------------------------------------- */
1126 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1128 /* just adjust the stack for this thread, then pop it back
1132 /* enlarge the stack */
1133 StgTSO *new_t = threadStackOverflow(cap, t);
1135 /* The TSO attached to this Task may have moved, so update the
1138 if (task->incall->tso == t) {
1139 task->incall->tso = new_t;
1141 pushOnRunQueue(cap,new_t);
1145 /* -----------------------------------------------------------------------------
1146 * Handle a thread that returned to the scheduler with ThreadYielding
1147 * -------------------------------------------------------------------------- */
1150 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1152 /* put the thread back on the run queue. Then, if we're ready to
1153 * GC, check whether this is the last task to stop. If so, wake
1154 * up the GC thread. getThread will block during a GC until the
1158 ASSERT(t->_link == END_TSO_QUEUE);
1160 // Shortcut if we're just switching evaluators: don't bother
1161 // doing stack squeezing (which can be expensive), just run the
1163 if (cap->context_switch == 0 && t->what_next != prev_what_next) {
1164 debugTrace(DEBUG_sched,
1165 "--<< thread %ld (%s) stopped to switch evaluators",
1166 (long)t->id, what_next_strs[t->what_next]);
1170 // Reset the context switch flag. We don't do this just before
1171 // running the thread, because that would mean we would lose ticks
1172 // during GC, which can lead to unfair scheduling (a thread hogs
1173 // the CPU because the tick always arrives during GC). This way
1174 // penalises threads that do a lot of allocation, but that seems
1175 // better than the alternative.
1176 cap->context_switch = 0;
1179 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1182 appendToRunQueue(cap,t);
1187 /* -----------------------------------------------------------------------------
1188 * Handle a thread that returned to the scheduler with ThreadBlocked
1189 * -------------------------------------------------------------------------- */
1192 scheduleHandleThreadBlocked( StgTSO *t
1199 // We don't need to do anything. The thread is blocked, and it
1200 // has tidied up its stack and placed itself on whatever queue
1201 // it needs to be on.
1203 // ASSERT(t->why_blocked != NotBlocked);
1204 // Not true: for example,
1205 // - the thread may have woken itself up already, because
1206 // threadPaused() might have raised a blocked throwTo
1207 // exception, see maybePerformBlockedException().
1210 traceThreadStatus(DEBUG_sched, t);
1214 /* -----------------------------------------------------------------------------
1215 * Handle a thread that returned to the scheduler with ThreadFinished
1216 * -------------------------------------------------------------------------- */
1219 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1221 /* Need to check whether this was a main thread, and if so,
1222 * return with the return value.
1224 * We also end up here if the thread kills itself with an
1225 * uncaught exception, see Exception.cmm.
1228 // blocked exceptions can now complete, even if the thread was in
1229 // blocked mode (see #2910).
1230 awakenBlockedExceptionQueue (cap, t);
1233 // Check whether the thread that just completed was a bound
1234 // thread, and if so return with the result.
1236 // There is an assumption here that all thread completion goes
1237 // through this point; we need to make sure that if a thread
1238 // ends up in the ThreadKilled state, that it stays on the run
1239 // queue so it can be dealt with here.
1244 if (t->bound != task->incall) {
1245 #if !defined(THREADED_RTS)
1246 // Must be a bound thread that is not the topmost one. Leave
1247 // it on the run queue until the stack has unwound to the
1248 // point where we can deal with this. Leaving it on the run
1249 // queue also ensures that the garbage collector knows about
1250 // this thread and its return value (it gets dropped from the
1251 // step->threads list so there's no other way to find it).
1252 appendToRunQueue(cap,t);
1255 // this cannot happen in the threaded RTS, because a
1256 // bound thread can only be run by the appropriate Task.
1257 barf("finished bound thread that isn't mine");
1261 ASSERT(task->incall->tso == t);
1263 if (t->what_next == ThreadComplete) {
1265 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1266 *(task->ret) = (StgClosure *)task->incall->tso->sp[1];
1268 task->stat = Success;
1271 *(task->ret) = NULL;
1273 if (sched_state >= SCHED_INTERRUPTING) {
1274 if (heap_overflow) {
1275 task->stat = HeapExhausted;
1277 task->stat = Interrupted;
1280 task->stat = Killed;
1284 removeThreadLabel((StgWord)task->incall->tso->id);
1287 // We no longer consider this thread and task to be bound to
1288 // each other. The TSO lives on until it is GC'd, but the
1289 // task is about to be released by the caller, and we don't
1290 // want anyone following the pointer from the TSO to the
1291 // defunct task (which might have already been
1292 // re-used). This was a real bug: the GC updated
1293 // tso->bound->tso which lead to a deadlock.
1295 task->incall->tso = NULL;
1297 return rtsTrue; // tells schedule() to return
1303 /* -----------------------------------------------------------------------------
1304 * Perform a heap census
1305 * -------------------------------------------------------------------------- */
1308 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1310 // When we have +RTS -i0 and we're heap profiling, do a census at
1311 // every GC. This lets us get repeatable runs for debugging.
1312 if (performHeapProfile ||
1313 (RtsFlags.ProfFlags.profileInterval==0 &&
1314 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1321 /* -----------------------------------------------------------------------------
1322 * Perform a garbage collection if necessary
1323 * -------------------------------------------------------------------------- */
1326 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1328 rtsBool heap_census;
1330 /* extern static volatile StgWord waiting_for_gc;
1331 lives inside capability.c */
1332 rtsBool gc_type, prev_pending_gc;
1336 if (sched_state == SCHED_SHUTTING_DOWN) {
1337 // The final GC has already been done, and the system is
1338 // shutting down. We'll probably deadlock if we try to GC
1344 if (sched_state < SCHED_INTERRUPTING
1345 && RtsFlags.ParFlags.parGcEnabled
1346 && N >= RtsFlags.ParFlags.parGcGen
1347 && ! oldest_gen->mark)
1349 gc_type = PENDING_GC_PAR;
1351 gc_type = PENDING_GC_SEQ;
1354 // In order to GC, there must be no threads running Haskell code.
1355 // Therefore, the GC thread needs to hold *all* the capabilities,
1356 // and release them after the GC has completed.
1358 // This seems to be the simplest way: previous attempts involved
1359 // making all the threads with capabilities give up their
1360 // capabilities and sleep except for the *last* one, which
1361 // actually did the GC. But it's quite hard to arrange for all
1362 // the other tasks to sleep and stay asleep.
1365 /* Other capabilities are prevented from running yet more Haskell
1366 threads if waiting_for_gc is set. Tested inside
1367 yieldCapability() and releaseCapability() in Capability.c */
1369 prev_pending_gc = cas(&waiting_for_gc, 0, gc_type);
1370 if (prev_pending_gc) {
1372 debugTrace(DEBUG_sched, "someone else is trying to GC (%d)...",
1375 yieldCapability(&cap,task);
1376 } while (waiting_for_gc);
1377 return cap; // NOTE: task->cap might have changed here
1380 setContextSwitches();
1382 // The final shutdown GC is always single-threaded, because it's
1383 // possible that some of the Capabilities have no worker threads.
1385 if (gc_type == PENDING_GC_SEQ)
1387 traceEventRequestSeqGc(cap);
1391 traceEventRequestParGc(cap);
1392 debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1395 if (gc_type == PENDING_GC_SEQ)
1397 // single-threaded GC: grab all the capabilities
1398 for (i=0; i < n_capabilities; i++) {
1399 debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1400 if (cap != &capabilities[i]) {
1401 Capability *pcap = &capabilities[i];
1402 // we better hope this task doesn't get migrated to
1403 // another Capability while we're waiting for this one.
1404 // It won't, because load balancing happens while we have
1405 // all the Capabilities, but even so it's a slightly
1406 // unsavoury invariant.
1408 waitForReturnCapability(&pcap, task);
1409 if (pcap != &capabilities[i]) {
1410 barf("scheduleDoGC: got the wrong capability");
1417 // multi-threaded GC: make sure all the Capabilities donate one
1419 waitForGcThreads(cap);
1424 IF_DEBUG(scheduler, printAllThreads());
1426 delete_threads_and_gc:
1428 * We now have all the capabilities; if we're in an interrupting
1429 * state, then we should take the opportunity to delete all the
1430 * threads in the system.
1432 if (sched_state == SCHED_INTERRUPTING) {
1433 deleteAllThreads(cap);
1434 sched_state = SCHED_SHUTTING_DOWN;
1437 heap_census = scheduleNeedHeapProfile(rtsTrue);
1439 traceEventGcStart(cap);
1440 #if defined(THREADED_RTS)
1441 // reset waiting_for_gc *before* GC, so that when the GC threads
1442 // emerge they don't immediately re-enter the GC.
1444 GarbageCollect(force_major || heap_census, gc_type, cap);
1446 GarbageCollect(force_major || heap_census, 0, cap);
1448 traceEventGcEnd(cap);
1450 if (recent_activity == ACTIVITY_INACTIVE && force_major)
1452 // We are doing a GC because the system has been idle for a
1453 // timeslice and we need to check for deadlock. Record the
1454 // fact that we've done a GC and turn off the timer signal;
1455 // it will get re-enabled if we run any threads after the GC.
1456 recent_activity = ACTIVITY_DONE_GC;
1461 // the GC might have taken long enough for the timer to set
1462 // recent_activity = ACTIVITY_INACTIVE, but we aren't
1463 // necessarily deadlocked:
1464 recent_activity = ACTIVITY_YES;
1467 #if defined(THREADED_RTS)
1468 if (gc_type == PENDING_GC_PAR)
1470 releaseGCThreads(cap);
1475 debugTrace(DEBUG_sched, "performing heap census");
1477 performHeapProfile = rtsFalse;
1480 if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1481 // GC set the heap_overflow flag, so we should proceed with
1482 // an orderly shutdown now. Ultimately we want the main
1483 // thread to return to its caller with HeapExhausted, at which
1484 // point the caller should call hs_exit(). The first step is
1485 // to delete all the threads.
1487 // Another way to do this would be to raise an exception in
1488 // the main thread, which we really should do because it gives
1489 // the program a chance to clean up. But how do we find the
1490 // main thread? It should presumably be the same one that
1491 // gets ^C exceptions, but that's all done on the Haskell side
1492 // (GHC.TopHandler).
1493 sched_state = SCHED_INTERRUPTING;
1494 goto delete_threads_and_gc;
1499 Once we are all together... this would be the place to balance all
1500 spark pools. No concurrent stealing or adding of new sparks can
1501 occur. Should be defined in Sparks.c. */
1502 balanceSparkPoolsCaps(n_capabilities, capabilities);
1505 #if defined(THREADED_RTS)
1506 if (gc_type == PENDING_GC_SEQ) {
1507 // release our stash of capabilities.
1508 for (i = 0; i < n_capabilities; i++) {
1509 if (cap != &capabilities[i]) {
1510 task->cap = &capabilities[i];
1511 releaseCapability(&capabilities[i]);
1525 /* ---------------------------------------------------------------------------
1526 * Singleton fork(). Do not copy any running threads.
1527 * ------------------------------------------------------------------------- */
1530 forkProcess(HsStablePtr *entry
1531 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1536 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1542 #if defined(THREADED_RTS)
1543 if (RtsFlags.ParFlags.nNodes > 1) {
1544 errorBelch("forking not supported with +RTS -N<n> greater than 1");
1545 stg_exit(EXIT_FAILURE);
1549 debugTrace(DEBUG_sched, "forking!");
1551 // ToDo: for SMP, we should probably acquire *all* the capabilities
1554 // no funny business: hold locks while we fork, otherwise if some
1555 // other thread is holding a lock when the fork happens, the data
1556 // structure protected by the lock will forever be in an
1557 // inconsistent state in the child. See also #1391.
1558 ACQUIRE_LOCK(&sched_mutex);
1559 ACQUIRE_LOCK(&cap->lock);
1560 ACQUIRE_LOCK(&cap->running_task->lock);
1564 if (pid) { // parent
1566 RELEASE_LOCK(&sched_mutex);
1567 RELEASE_LOCK(&cap->lock);
1568 RELEASE_LOCK(&cap->running_task->lock);
1570 // just return the pid
1576 #if defined(THREADED_RTS)
1577 initMutex(&sched_mutex);
1578 initMutex(&cap->lock);
1579 initMutex(&cap->running_task->lock);
1582 // Now, all OS threads except the thread that forked are
1583 // stopped. We need to stop all Haskell threads, including
1584 // those involved in foreign calls. Also we need to delete
1585 // all Tasks, because they correspond to OS threads that are
1588 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1589 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1590 if (t->what_next == ThreadRelocated) {
1593 next = t->global_link;
1594 // don't allow threads to catch the ThreadKilled
1595 // exception, but we do want to raiseAsync() because these
1596 // threads may be evaluating thunks that we need later.
1597 deleteThread_(cap,t);
1599 // stop the GC from updating the InCall to point to
1600 // the TSO. This is only necessary because the
1601 // OSThread bound to the TSO has been killed, and
1602 // won't get a chance to exit in the usual way (see
1603 // also scheduleHandleThreadFinished).
1609 // Empty the run queue. It seems tempting to let all the
1610 // killed threads stay on the run queue as zombies to be
1611 // cleaned up later, but some of them correspond to bound
1612 // threads for which the corresponding Task does not exist.
1613 cap->run_queue_hd = END_TSO_QUEUE;
1614 cap->run_queue_tl = END_TSO_QUEUE;
1616 // Any suspended C-calling Tasks are no more, their OS threads
1618 cap->suspended_ccalls = NULL;
1620 // Empty the threads lists. Otherwise, the garbage
1621 // collector may attempt to resurrect some of these threads.
1622 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1623 generations[g].threads = END_TSO_QUEUE;
1626 discardTasksExcept(cap->running_task);
1628 #if defined(THREADED_RTS)
1629 // Wipe our spare workers list, they no longer exist. New
1630 // workers will be created if necessary.
1631 cap->spare_workers = NULL;
1632 cap->returning_tasks_hd = NULL;
1633 cap->returning_tasks_tl = NULL;
1636 // On Unix, all timers are reset in the child, so we need to start
1641 #if defined(THREADED_RTS)
1642 cap = ioManagerStartCap(cap);
1645 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1646 rts_checkSchedStatus("forkProcess",cap);
1649 hs_exit(); // clean up and exit
1650 stg_exit(EXIT_SUCCESS);
1652 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1653 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1657 /* ---------------------------------------------------------------------------
1658 * Delete all the threads in the system
1659 * ------------------------------------------------------------------------- */
1662 deleteAllThreads ( Capability *cap )
1664 // NOTE: only safe to call if we own all capabilities.
1669 debugTrace(DEBUG_sched,"deleting all threads");
1670 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1671 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1672 if (t->what_next == ThreadRelocated) {
1675 next = t->global_link;
1676 deleteThread(cap,t);
1681 // The run queue now contains a bunch of ThreadKilled threads. We
1682 // must not throw these away: the main thread(s) will be in there
1683 // somewhere, and the main scheduler loop has to deal with it.
1684 // Also, the run queue is the only thing keeping these threads from
1685 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1687 #if !defined(THREADED_RTS)
1688 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1689 ASSERT(sleeping_queue == END_TSO_QUEUE);
1693 /* -----------------------------------------------------------------------------
1694 Managing the suspended_ccalls list.
1695 Locks required: sched_mutex
1696 -------------------------------------------------------------------------- */
1699 suspendTask (Capability *cap, Task *task)
1703 incall = task->incall;
1704 ASSERT(incall->next == NULL && incall->prev == NULL);
1705 incall->next = cap->suspended_ccalls;
1706 incall->prev = NULL;
1707 if (cap->suspended_ccalls) {
1708 cap->suspended_ccalls->prev = incall;
1710 cap->suspended_ccalls = incall;
1714 recoverSuspendedTask (Capability *cap, Task *task)
1718 incall = task->incall;
1720 incall->prev->next = incall->next;
1722 ASSERT(cap->suspended_ccalls == incall);
1723 cap->suspended_ccalls = incall->next;
1726 incall->next->prev = incall->prev;
1728 incall->next = incall->prev = NULL;
1731 /* ---------------------------------------------------------------------------
1732 * Suspending & resuming Haskell threads.
1734 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1735 * its capability before calling the C function. This allows another
1736 * task to pick up the capability and carry on running Haskell
1737 * threads. It also means that if the C call blocks, it won't lock
1740 * The Haskell thread making the C call is put to sleep for the
1741 * duration of the call, on the susepended_ccalling_threads queue. We
1742 * give out a token to the task, which it can use to resume the thread
1743 * on return from the C function.
1744 * ------------------------------------------------------------------------- */
1747 suspendThread (StgRegTable *reg)
1754 StgWord32 saved_winerror;
1757 saved_errno = errno;
1759 saved_winerror = GetLastError();
1762 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1764 cap = regTableToCapability(reg);
1766 task = cap->running_task;
1767 tso = cap->r.rCurrentTSO;
1769 traceEventStopThread(cap, tso, THREAD_SUSPENDED_FOREIGN_CALL);
1771 // XXX this might not be necessary --SDM
1772 tso->what_next = ThreadRunGHC;
1774 threadPaused(cap,tso);
1776 if ((tso->flags & TSO_BLOCKEX) == 0) {
1777 tso->why_blocked = BlockedOnCCall;
1778 tso->flags |= TSO_BLOCKEX;
1779 tso->flags &= ~TSO_INTERRUPTIBLE;
1781 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1784 // Hand back capability
1785 task->incall->suspended_tso = tso;
1786 task->incall->suspended_cap = cap;
1788 ACQUIRE_LOCK(&cap->lock);
1790 suspendTask(cap,task);
1791 cap->in_haskell = rtsFalse;
1792 releaseCapability_(cap,rtsFalse);
1794 RELEASE_LOCK(&cap->lock);
1796 errno = saved_errno;
1798 SetLastError(saved_winerror);
1804 resumeThread (void *task_)
1812 StgWord32 saved_winerror;
1815 saved_errno = errno;
1817 saved_winerror = GetLastError();
1820 incall = task->incall;
1821 cap = incall->suspended_cap;
1824 // Wait for permission to re-enter the RTS with the result.
1825 waitForReturnCapability(&cap,task);
1826 // we might be on a different capability now... but if so, our
1827 // entry on the suspended_ccalls list will also have been
1830 // Remove the thread from the suspended list
1831 recoverSuspendedTask(cap,task);
1833 tso = incall->suspended_tso;
1834 incall->suspended_tso = NULL;
1835 incall->suspended_cap = NULL;
1836 tso->_link = END_TSO_QUEUE; // no write barrier reqd
1838 traceEventRunThread(cap, tso);
1840 if (tso->why_blocked == BlockedOnCCall) {
1841 // avoid locking the TSO if we don't have to
1842 if (tso->blocked_exceptions != END_BLOCKED_EXCEPTIONS_QUEUE) {
1843 awakenBlockedExceptionQueue(cap,tso);
1845 tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
1848 /* Reset blocking status */
1849 tso->why_blocked = NotBlocked;
1851 cap->r.rCurrentTSO = tso;
1852 cap->in_haskell = rtsTrue;
1853 errno = saved_errno;
1855 SetLastError(saved_winerror);
1858 /* We might have GC'd, mark the TSO dirty again */
1861 IF_DEBUG(sanity, checkTSO(tso));
1866 /* ---------------------------------------------------------------------------
1869 * scheduleThread puts a thread on the end of the runnable queue.
1870 * This will usually be done immediately after a thread is created.
1871 * The caller of scheduleThread must create the thread using e.g.
1872 * createThread and push an appropriate closure
1873 * on this thread's stack before the scheduler is invoked.
1874 * ------------------------------------------------------------------------ */
1877 scheduleThread(Capability *cap, StgTSO *tso)
1879 // The thread goes at the *end* of the run-queue, to avoid possible
1880 // starvation of any threads already on the queue.
1881 appendToRunQueue(cap,tso);
1885 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
1887 #if defined(THREADED_RTS)
1888 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
1889 // move this thread from now on.
1890 cpu %= RtsFlags.ParFlags.nNodes;
1891 if (cpu == cap->no) {
1892 appendToRunQueue(cap,tso);
1894 traceEventMigrateThread (cap, tso, capabilities[cpu].no);
1895 wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
1898 appendToRunQueue(cap,tso);
1903 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
1908 // We already created/initialised the Task
1909 task = cap->running_task;
1911 // This TSO is now a bound thread; make the Task and TSO
1912 // point to each other.
1913 tso->bound = task->incall;
1916 task->incall->tso = tso;
1918 task->stat = NoStatus;
1920 appendToRunQueue(cap,tso);
1923 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)id);
1925 cap = schedule(cap,task);
1927 ASSERT(task->stat != NoStatus);
1928 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
1930 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)id);
1934 /* ----------------------------------------------------------------------------
1936 * ------------------------------------------------------------------------- */
1938 #if defined(THREADED_RTS)
1939 void scheduleWorker (Capability *cap, Task *task)
1941 // schedule() runs without a lock.
1942 cap = schedule(cap,task);
1944 // On exit from schedule(), we have a Capability, but possibly not
1945 // the same one we started with.
1947 // During shutdown, the requirement is that after all the
1948 // Capabilities are shut down, all workers that are shutting down
1949 // have finished workerTaskStop(). This is why we hold on to
1950 // cap->lock until we've finished workerTaskStop() below.
1952 // There may be workers still involved in foreign calls; those
1953 // will just block in waitForReturnCapability() because the
1954 // Capability has been shut down.
1956 ACQUIRE_LOCK(&cap->lock);
1957 releaseCapability_(cap,rtsFalse);
1958 workerTaskStop(task);
1959 RELEASE_LOCK(&cap->lock);
1963 /* ---------------------------------------------------------------------------
1966 * Initialise the scheduler. This resets all the queues - if the
1967 * queues contained any threads, they'll be garbage collected at the
1970 * ------------------------------------------------------------------------ */
1975 #if !defined(THREADED_RTS)
1976 blocked_queue_hd = END_TSO_QUEUE;
1977 blocked_queue_tl = END_TSO_QUEUE;
1978 sleeping_queue = END_TSO_QUEUE;
1981 sched_state = SCHED_RUNNING;
1982 recent_activity = ACTIVITY_YES;
1984 #if defined(THREADED_RTS)
1985 /* Initialise the mutex and condition variables used by
1987 initMutex(&sched_mutex);
1990 ACQUIRE_LOCK(&sched_mutex);
1992 /* A capability holds the state a native thread needs in
1993 * order to execute STG code. At least one capability is
1994 * floating around (only THREADED_RTS builds have more than one).
2000 #if defined(THREADED_RTS)
2004 RELEASE_LOCK(&sched_mutex);
2006 #if defined(THREADED_RTS)
2008 * Eagerly start one worker to run each Capability, except for
2009 * Capability 0. The idea is that we're probably going to start a
2010 * bound thread on Capability 0 pretty soon, so we don't want a
2011 * worker task hogging it.
2016 for (i = 1; i < n_capabilities; i++) {
2017 cap = &capabilities[i];
2018 ACQUIRE_LOCK(&cap->lock);
2019 startWorkerTask(cap);
2020 RELEASE_LOCK(&cap->lock);
2028 rtsBool wait_foreign
2029 #if !defined(THREADED_RTS)
2030 __attribute__((unused))
2033 /* see Capability.c, shutdownCapability() */
2037 task = newBoundTask();
2039 // If we haven't killed all the threads yet, do it now.
2040 if (sched_state < SCHED_SHUTTING_DOWN) {
2041 sched_state = SCHED_INTERRUPTING;
2042 waitForReturnCapability(&task->cap,task);
2043 scheduleDoGC(task->cap,task,rtsFalse);
2044 ASSERT(task->incall->tso == NULL);
2045 releaseCapability(task->cap);
2047 sched_state = SCHED_SHUTTING_DOWN;
2049 #if defined(THREADED_RTS)
2053 for (i = 0; i < n_capabilities; i++) {
2054 ASSERT(task->incall->tso == NULL);
2055 shutdownCapability(&capabilities[i], task, wait_foreign);
2060 boundTaskExiting(task);
2064 freeScheduler( void )
2068 ACQUIRE_LOCK(&sched_mutex);
2069 still_running = freeTaskManager();
2070 // We can only free the Capabilities if there are no Tasks still
2071 // running. We might have a Task about to return from a foreign
2072 // call into waitForReturnCapability(), for example (actually,
2073 // this should be the *only* thing that a still-running Task can
2074 // do at this point, and it will block waiting for the
2076 if (still_running == 0) {
2078 if (n_capabilities != 1) {
2079 stgFree(capabilities);
2082 RELEASE_LOCK(&sched_mutex);
2083 #if defined(THREADED_RTS)
2084 closeMutex(&sched_mutex);
2088 /* -----------------------------------------------------------------------------
2091 This is the interface to the garbage collector from Haskell land.
2092 We provide this so that external C code can allocate and garbage
2093 collect when called from Haskell via _ccall_GC.
2094 -------------------------------------------------------------------------- */
2097 performGC_(rtsBool force_major)
2101 // We must grab a new Task here, because the existing Task may be
2102 // associated with a particular Capability, and chained onto the
2103 // suspended_ccalls queue.
2104 task = newBoundTask();
2106 waitForReturnCapability(&task->cap,task);
2107 scheduleDoGC(task->cap,task,force_major);
2108 releaseCapability(task->cap);
2109 boundTaskExiting(task);
2115 performGC_(rtsFalse);
2119 performMajorGC(void)
2121 performGC_(rtsTrue);
2124 /* -----------------------------------------------------------------------------
2127 If the thread has reached its maximum stack size, then raise the
2128 StackOverflow exception in the offending thread. Otherwise
2129 relocate the TSO into a larger chunk of memory and adjust its stack
2131 -------------------------------------------------------------------------- */
2134 threadStackOverflow(Capability *cap, StgTSO *tso)
2136 nat new_stack_size, stack_words;
2141 IF_DEBUG(sanity,checkTSO(tso));
2143 if (tso->stack_size >= tso->max_stack_size
2144 && !(tso->flags & TSO_BLOCKEX)) {
2145 // NB. never raise a StackOverflow exception if the thread is
2146 // inside Control.Exceptino.block. It is impractical to protect
2147 // against stack overflow exceptions, since virtually anything
2148 // can raise one (even 'catch'), so this is the only sensible
2149 // thing to do here. See bug #767.
2152 if (tso->flags & TSO_SQUEEZED) {
2155 // #3677: In a stack overflow situation, stack squeezing may
2156 // reduce the stack size, but we don't know whether it has been
2157 // reduced enough for the stack check to succeed if we try
2158 // again. Fortunately stack squeezing is idempotent, so all we
2159 // need to do is record whether *any* squeezing happened. If we
2160 // are at the stack's absolute -K limit, and stack squeezing
2161 // happened, then we try running the thread again. The
2162 // TSO_SQUEEZED flag is set by threadPaused() to tell us whether
2163 // squeezing happened or not.
2165 debugTrace(DEBUG_gc,
2166 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2167 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2169 /* If we're debugging, just print out the top of the stack */
2170 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2173 // Send this thread the StackOverflow exception
2174 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2179 // We also want to avoid enlarging the stack if squeezing has
2180 // already released some of it. However, we don't want to get into
2181 // a pathalogical situation where a thread has a nearly full stack
2182 // (near its current limit, but not near the absolute -K limit),
2183 // keeps allocating a little bit, squeezing removes a little bit,
2184 // and then it runs again. So to avoid this, if we squeezed *and*
2185 // there is still less than BLOCK_SIZE_W words free, then we enlarge
2186 // the stack anyway.
2187 if ((tso->flags & TSO_SQUEEZED) &&
2188 ((W_)(tso->sp - tso->stack) >= BLOCK_SIZE_W)) {
2192 /* Try to double the current stack size. If that takes us over the
2193 * maximum stack size for this thread, then use the maximum instead
2194 * (that is, unless we're already at or over the max size and we
2195 * can't raise the StackOverflow exception (see above), in which
2196 * case just double the size). Finally round up so the TSO ends up as
2197 * a whole number of blocks.
2199 if (tso->stack_size >= tso->max_stack_size) {
2200 new_stack_size = tso->stack_size * 2;
2202 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2204 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2205 TSO_STRUCT_SIZE)/sizeof(W_);
2206 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2207 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2209 debugTrace(DEBUG_sched,
2210 "increasing stack size from %ld words to %d.",
2211 (long)tso->stack_size, new_stack_size);
2213 dest = (StgTSO *)allocate(cap,new_tso_size);
2214 TICK_ALLOC_TSO(new_stack_size,0);
2216 /* copy the TSO block and the old stack into the new area */
2217 memcpy(dest,tso,TSO_STRUCT_SIZE);
2218 stack_words = tso->stack + tso->stack_size - tso->sp;
2219 new_sp = (P_)dest + new_tso_size - stack_words;
2220 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2222 /* relocate the stack pointers... */
2224 dest->stack_size = new_stack_size;
2226 /* Mark the old TSO as relocated. We have to check for relocated
2227 * TSOs in the garbage collector and any primops that deal with TSOs.
2229 * It's important to set the sp value to just beyond the end
2230 * of the stack, so we don't attempt to scavenge any part of the
2233 setTSOLink(cap,tso,dest);
2234 write_barrier(); // other threads seeing ThreadRelocated will look at _link
2235 tso->what_next = ThreadRelocated;
2236 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2237 tso->why_blocked = NotBlocked;
2239 IF_DEBUG(sanity,checkTSO(dest));
2241 IF_DEBUG(scheduler,printTSO(dest));
2248 threadStackUnderflow (Capability *cap, Task *task, StgTSO *tso)
2250 bdescr *bd, *new_bd;
2251 lnat free_w, tso_size_w;
2254 tso_size_w = tso_sizeW(tso);
2256 if (tso_size_w < MBLOCK_SIZE_W ||
2257 // TSO is less than 2 mblocks (since the first mblock is
2258 // shorter than MBLOCK_SIZE_W)
2259 (tso_size_w - BLOCKS_PER_MBLOCK*BLOCK_SIZE_W) % MBLOCK_SIZE_W != 0 ||
2260 // or TSO is not a whole number of megablocks (ensuring
2261 // precondition of splitLargeBlock() below)
2262 (tso_size_w <= round_up_to_mblocks(RtsFlags.GcFlags.initialStkSize)) ||
2263 // or TSO is smaller than the minimum stack size (rounded up)
2264 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2265 // or stack is using more than 1/4 of the available space
2271 // this is the number of words we'll free
2272 free_w = round_to_mblocks(tso_size_w/2);
2274 bd = Bdescr((StgPtr)tso);
2275 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2276 bd->free = bd->start + TSO_STRUCT_SIZEW;
2278 new_tso = (StgTSO *)new_bd->start;
2279 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2280 new_tso->stack_size = new_bd->free - new_tso->stack;
2282 // The original TSO was dirty and probably on the mutable
2283 // list. The new TSO is not yet on the mutable list, so we better
2286 new_tso->flags &= ~TSO_LINK_DIRTY;
2287 dirty_TSO(cap, new_tso);
2289 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2290 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2292 tso->_link = new_tso; // no write barrier reqd: same generation
2293 write_barrier(); // other threads seeing ThreadRelocated will look at _link
2294 tso->what_next = ThreadRelocated;
2296 // The TSO attached to this Task may have moved, so update the
2298 if (task->incall->tso == tso) {
2299 task->incall->tso = new_tso;
2302 IF_DEBUG(sanity,checkTSO(new_tso));
2307 /* ---------------------------------------------------------------------------
2309 - usually called inside a signal handler so it mustn't do anything fancy.
2310 ------------------------------------------------------------------------ */
2313 interruptStgRts(void)
2315 sched_state = SCHED_INTERRUPTING;
2316 setContextSwitches();
2317 #if defined(THREADED_RTS)
2322 /* -----------------------------------------------------------------------------
2325 This function causes at least one OS thread to wake up and run the
2326 scheduler loop. It is invoked when the RTS might be deadlocked, or
2327 an external event has arrived that may need servicing (eg. a
2328 keyboard interrupt).
2330 In the single-threaded RTS we don't do anything here; we only have
2331 one thread anyway, and the event that caused us to want to wake up
2332 will have interrupted any blocking system call in progress anyway.
2333 -------------------------------------------------------------------------- */
2335 #if defined(THREADED_RTS)
2336 void wakeUpRts(void)
2338 // This forces the IO Manager thread to wakeup, which will
2339 // in turn ensure that some OS thread wakes up and runs the
2340 // scheduler loop, which will cause a GC and deadlock check.
2345 /* -----------------------------------------------------------------------------
2348 This is used for interruption (^C) and forking, and corresponds to
2349 raising an exception but without letting the thread catch the
2351 -------------------------------------------------------------------------- */
2354 deleteThread (Capability *cap STG_UNUSED, StgTSO *tso)
2356 // NOTE: must only be called on a TSO that we have exclusive
2357 // access to, because we will call throwToSingleThreaded() below.
2358 // The TSO must be on the run queue of the Capability we own, or
2359 // we must own all Capabilities.
2361 if (tso->why_blocked != BlockedOnCCall &&
2362 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2363 throwToSingleThreaded(tso->cap,tso,NULL);
2367 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2369 deleteThread_(Capability *cap, StgTSO *tso)
2370 { // for forkProcess only:
2371 // like deleteThread(), but we delete threads in foreign calls, too.
2373 if (tso->why_blocked == BlockedOnCCall ||
2374 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2375 unblockOne(cap,tso);
2376 tso->what_next = ThreadKilled;
2378 deleteThread(cap,tso);
2383 /* -----------------------------------------------------------------------------
2384 raiseExceptionHelper
2386 This function is called by the raise# primitve, just so that we can
2387 move some of the tricky bits of raising an exception from C-- into
2388 C. Who knows, it might be a useful re-useable thing here too.
2389 -------------------------------------------------------------------------- */
2392 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2394 Capability *cap = regTableToCapability(reg);
2395 StgThunk *raise_closure = NULL;
2397 StgRetInfoTable *info;
2399 // This closure represents the expression 'raise# E' where E
2400 // is the exception raise. It is used to overwrite all the
2401 // thunks which are currently under evaluataion.
2404 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2405 // LDV profiling: stg_raise_info has THUNK as its closure
2406 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2407 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2408 // 1 does not cause any problem unless profiling is performed.
2409 // However, when LDV profiling goes on, we need to linearly scan
2410 // small object pool, where raise_closure is stored, so we should
2411 // use MIN_UPD_SIZE.
2413 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2414 // sizeofW(StgClosure)+1);
2418 // Walk up the stack, looking for the catch frame. On the way,
2419 // we update any closures pointed to from update frames with the
2420 // raise closure that we just built.
2424 info = get_ret_itbl((StgClosure *)p);
2425 next = p + stack_frame_sizeW((StgClosure *)p);
2426 switch (info->i.type) {
2429 // Only create raise_closure if we need to.
2430 if (raise_closure == NULL) {
2432 (StgThunk *)allocate(cap,sizeofW(StgThunk)+1);
2433 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2434 raise_closure->payload[0] = exception;
2436 updateThunk(cap, tso, ((StgUpdateFrame *)p)->updatee,
2437 (StgClosure *)raise_closure);
2441 case ATOMICALLY_FRAME:
2442 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2444 return ATOMICALLY_FRAME;
2450 case CATCH_STM_FRAME:
2451 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2453 return CATCH_STM_FRAME;
2459 case CATCH_RETRY_FRAME:
2468 /* -----------------------------------------------------------------------------
2469 findRetryFrameHelper
2471 This function is called by the retry# primitive. It traverses the stack
2472 leaving tso->sp referring to the frame which should handle the retry.
2474 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2475 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2477 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2478 create) because retries are not considered to be exceptions, despite the
2479 similar implementation.
2481 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2482 not be created within memory transactions.
2483 -------------------------------------------------------------------------- */
2486 findRetryFrameHelper (StgTSO *tso)
2489 StgRetInfoTable *info;
2493 info = get_ret_itbl((StgClosure *)p);
2494 next = p + stack_frame_sizeW((StgClosure *)p);
2495 switch (info->i.type) {
2497 case ATOMICALLY_FRAME:
2498 debugTrace(DEBUG_stm,
2499 "found ATOMICALLY_FRAME at %p during retry", p);
2501 return ATOMICALLY_FRAME;
2503 case CATCH_RETRY_FRAME:
2504 debugTrace(DEBUG_stm,
2505 "found CATCH_RETRY_FRAME at %p during retrry", p);
2507 return CATCH_RETRY_FRAME;
2509 case CATCH_STM_FRAME: {
2510 StgTRecHeader *trec = tso -> trec;
2511 StgTRecHeader *outer = trec -> enclosing_trec;
2512 debugTrace(DEBUG_stm,
2513 "found CATCH_STM_FRAME at %p during retry", p);
2514 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2515 stmAbortTransaction(tso -> cap, trec);
2516 stmFreeAbortedTRec(tso -> cap, trec);
2517 tso -> trec = outer;
2524 ASSERT(info->i.type != CATCH_FRAME);
2525 ASSERT(info->i.type != STOP_FRAME);
2532 /* -----------------------------------------------------------------------------
2533 resurrectThreads is called after garbage collection on the list of
2534 threads found to be garbage. Each of these threads will be woken
2535 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2536 on an MVar, or NonTermination if the thread was blocked on a Black
2539 Locks: assumes we hold *all* the capabilities.
2540 -------------------------------------------------------------------------- */
2543 resurrectThreads (StgTSO *threads)
2549 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2550 next = tso->global_link;
2552 gen = Bdescr((P_)tso)->gen;
2553 tso->global_link = gen->threads;
2556 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2558 // Wake up the thread on the Capability it was last on
2561 switch (tso->why_blocked) {
2563 /* Called by GC - sched_mutex lock is currently held. */
2564 throwToSingleThreaded(cap, tso,
2565 (StgClosure *)blockedIndefinitelyOnMVar_closure);
2567 case BlockedOnBlackHole:
2568 throwToSingleThreaded(cap, tso,
2569 (StgClosure *)nonTermination_closure);
2572 throwToSingleThreaded(cap, tso,
2573 (StgClosure *)blockedIndefinitelyOnSTM_closure);
2576 /* This might happen if the thread was blocked on a black hole
2577 * belonging to a thread that we've just woken up (raiseAsync
2578 * can wake up threads, remember...).
2582 barf("resurrectThreads: thread blocked in a strange way: %d",