1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2006
5 * The scheduler and thread-related functionality
7 * --------------------------------------------------------------------------*/
9 #include "PosixSource.h"
10 #define KEEP_LOCKCLOSURE
15 #include "OSThreads.h"
20 #include "StgMiscClosures.h"
21 #include "Interpreter.h"
23 #include "RtsSignals.h"
29 #include "ThreadLabels.h"
30 #include "LdvProfile.h"
32 #include "Proftimer.h"
35 /* PARALLEL_HASKELL includes go here */
38 #include "Capability.h"
40 #include "AwaitEvent.h"
41 #if defined(mingw32_HOST_OS)
42 #include "win32/IOManager.h"
45 #include "RaiseAsync.h"
47 #include "ThrIOManager.h"
49 #ifdef HAVE_SYS_TYPES_H
50 #include <sys/types.h>
64 // Turn off inlining when debugging - it obfuscates things
67 # define STATIC_INLINE static
70 /* -----------------------------------------------------------------------------
72 * -------------------------------------------------------------------------- */
74 #if !defined(THREADED_RTS)
75 // Blocked/sleeping thrads
76 StgTSO *blocked_queue_hd = NULL;
77 StgTSO *blocked_queue_tl = NULL;
78 StgTSO *sleeping_queue = NULL; // perhaps replace with a hash table?
81 /* Threads blocked on blackholes.
82 * LOCK: sched_mutex+capability, or all capabilities
84 StgTSO *blackhole_queue = NULL;
86 /* The blackhole_queue should be checked for threads to wake up. See
87 * Schedule.h for more thorough comment.
88 * LOCK: none (doesn't matter if we miss an update)
90 rtsBool blackholes_need_checking = rtsFalse;
92 /* flag that tracks whether we have done any execution in this time slice.
93 * LOCK: currently none, perhaps we should lock (but needs to be
94 * updated in the fast path of the scheduler).
96 nat recent_activity = ACTIVITY_YES;
98 /* if this flag is set as well, give up execution
99 * LOCK: none (changes once, from false->true)
101 rtsBool sched_state = SCHED_RUNNING;
103 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
104 * exists - earlier gccs apparently didn't.
110 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
111 * in an MT setting, needed to signal that a worker thread shouldn't hang around
112 * in the scheduler when it is out of work.
114 rtsBool shutting_down_scheduler = rtsFalse;
117 * This mutex protects most of the global scheduler data in
118 * the THREADED_RTS runtime.
120 #if defined(THREADED_RTS)
124 #if !defined(mingw32_HOST_OS)
125 #define FORKPROCESS_PRIMOP_SUPPORTED
128 /* -----------------------------------------------------------------------------
129 * static function prototypes
130 * -------------------------------------------------------------------------- */
132 static Capability *schedule (Capability *initialCapability, Task *task);
135 // These function all encapsulate parts of the scheduler loop, and are
136 // abstracted only to make the structure and control flow of the
137 // scheduler clearer.
139 static void schedulePreLoop (void);
140 #if defined(THREADED_RTS)
141 static void schedulePushWork(Capability *cap, Task *task);
143 static void scheduleStartSignalHandlers (Capability *cap);
144 static void scheduleCheckBlockedThreads (Capability *cap);
145 static void scheduleCheckWakeupThreads(Capability *cap USED_IF_NOT_THREADS);
146 static void scheduleCheckBlackHoles (Capability *cap);
147 static void scheduleDetectDeadlock (Capability *cap, Task *task);
148 #if defined(PARALLEL_HASKELL)
149 static rtsBool scheduleGetRemoteWork(Capability *cap);
150 static void scheduleSendPendingMessages(void);
151 static void scheduleActivateSpark(Capability *cap);
153 static void schedulePostRunThread(StgTSO *t);
154 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
155 static void scheduleHandleStackOverflow( Capability *cap, Task *task,
157 static rtsBool scheduleHandleYield( Capability *cap, StgTSO *t,
158 nat prev_what_next );
159 static void scheduleHandleThreadBlocked( StgTSO *t );
160 static rtsBool scheduleHandleThreadFinished( Capability *cap, Task *task,
162 static rtsBool scheduleNeedHeapProfile(rtsBool ready_to_gc);
163 static Capability *scheduleDoGC(Capability *cap, Task *task,
164 rtsBool force_major);
166 static rtsBool checkBlackHoles(Capability *cap);
168 static StgTSO *threadStackOverflow(Capability *cap, StgTSO *tso);
169 static StgTSO *threadStackUnderflow(Task *task, StgTSO *tso);
171 static void deleteThread (Capability *cap, StgTSO *tso);
172 static void deleteAllThreads (Capability *cap);
174 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
175 static void deleteThread_(Capability *cap, StgTSO *tso);
179 static char *whatNext_strs[] = {
189 /* -----------------------------------------------------------------------------
190 * Putting a thread on the run queue: different scheduling policies
191 * -------------------------------------------------------------------------- */
194 addToRunQueue( Capability *cap, StgTSO *t )
196 #if defined(PARALLEL_HASKELL)
197 if (RtsFlags.ParFlags.doFairScheduling) {
198 // this does round-robin scheduling; good for concurrency
199 appendToRunQueue(cap,t);
201 // this does unfair scheduling; good for parallelism
202 pushOnRunQueue(cap,t);
205 // this does round-robin scheduling; good for concurrency
206 appendToRunQueue(cap,t);
210 /* ---------------------------------------------------------------------------
211 Main scheduling loop.
213 We use round-robin scheduling, each thread returning to the
214 scheduler loop when one of these conditions is detected:
217 * timer expires (thread yields)
223 In a GranSim setup this loop iterates over the global event queue.
224 This revolves around the global event queue, which determines what
225 to do next. Therefore, it's more complicated than either the
226 concurrent or the parallel (GUM) setup.
227 This version has been entirely removed (JB 2008/08).
230 GUM iterates over incoming messages.
231 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
232 and sends out a fish whenever it has nothing to do; in-between
233 doing the actual reductions (shared code below) it processes the
234 incoming messages and deals with delayed operations
235 (see PendingFetches).
236 This is not the ugliest code you could imagine, but it's bloody close.
238 (JB 2008/08) This version was formerly indicated by a PP-Flag PAR,
239 now by PP-flag PARALLEL_HASKELL. The Eden RTS (in GHC-6.x) uses it,
240 as well as future GUM versions. This file has been refurbished to
241 only contain valid code, which is however incomplete, refers to
242 invalid includes etc.
244 ------------------------------------------------------------------------ */
247 schedule (Capability *initialCapability, Task *task)
251 StgThreadReturnCode ret;
252 #if defined(PARALLEL_HASKELL)
253 rtsBool receivedFinish = rtsFalse;
257 #if defined(THREADED_RTS)
258 rtsBool first = rtsTrue;
261 cap = initialCapability;
263 // Pre-condition: this task owns initialCapability.
264 // The sched_mutex is *NOT* held
265 // NB. on return, we still hold a capability.
267 debugTrace (DEBUG_sched,
268 "### NEW SCHEDULER LOOP (task: %p, cap: %p)",
269 task, initialCapability);
273 // -----------------------------------------------------------
274 // Scheduler loop starts here:
276 #if defined(PARALLEL_HASKELL)
277 #define TERMINATION_CONDITION (!receivedFinish)
279 #define TERMINATION_CONDITION rtsTrue
282 while (TERMINATION_CONDITION) {
284 #if defined(THREADED_RTS)
286 // don't yield the first time, we want a chance to run this
287 // thread for a bit, even if there are others banging at the
290 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
292 // Yield the capability to higher-priority tasks if necessary.
293 yieldCapability(&cap, task);
297 #if defined(THREADED_RTS)
298 schedulePushWork(cap,task);
301 // Check whether we have re-entered the RTS from Haskell without
302 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
304 if (cap->in_haskell) {
305 errorBelch("schedule: re-entered unsafely.\n"
306 " Perhaps a 'foreign import unsafe' should be 'safe'?");
307 stg_exit(EXIT_FAILURE);
310 // The interruption / shutdown sequence.
312 // In order to cleanly shut down the runtime, we want to:
313 // * make sure that all main threads return to their callers
314 // with the state 'Interrupted'.
315 // * clean up all OS threads assocated with the runtime
316 // * free all memory etc.
318 // So the sequence for ^C goes like this:
320 // * ^C handler sets sched_state := SCHED_INTERRUPTING and
321 // arranges for some Capability to wake up
323 // * all threads in the system are halted, and the zombies are
324 // placed on the run queue for cleaning up. We acquire all
325 // the capabilities in order to delete the threads, this is
326 // done by scheduleDoGC() for convenience (because GC already
327 // needs to acquire all the capabilities). We can't kill
328 // threads involved in foreign calls.
330 // * somebody calls shutdownHaskell(), which calls exitScheduler()
332 // * sched_state := SCHED_SHUTTING_DOWN
334 // * all workers exit when the run queue on their capability
335 // drains. All main threads will also exit when their TSO
336 // reaches the head of the run queue and they can return.
338 // * eventually all Capabilities will shut down, and the RTS can
341 // * We might be left with threads blocked in foreign calls,
342 // we should really attempt to kill these somehow (TODO);
344 switch (sched_state) {
347 case SCHED_INTERRUPTING:
348 debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
349 #if defined(THREADED_RTS)
350 discardSparksCap(cap);
352 /* scheduleDoGC() deletes all the threads */
353 cap = scheduleDoGC(cap,task,rtsFalse);
355 case SCHED_SHUTTING_DOWN:
356 debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
357 // If we are a worker, just exit. If we're a bound thread
358 // then we will exit below when we've removed our TSO from
360 if (task->tso == NULL && emptyRunQueue(cap)) {
365 barf("sched_state: %d", sched_state);
368 #if defined(THREADED_RTS)
369 // If the run queue is empty, take a spark and turn it into a thread.
371 if (emptyRunQueue(cap)) {
373 spark = findSpark(cap);
375 debugTrace(DEBUG_sched,
376 "turning spark of closure %p into a thread",
377 (StgClosure *)spark);
378 createSparkThread(cap,spark);
382 #endif // THREADED_RTS
384 scheduleStartSignalHandlers(cap);
386 // Only check the black holes here if we've nothing else to do.
387 // During normal execution, the black hole list only gets checked
388 // at GC time, to avoid repeatedly traversing this possibly long
389 // list each time around the scheduler.
390 if (emptyRunQueue(cap)) { scheduleCheckBlackHoles(cap); }
392 scheduleCheckWakeupThreads(cap);
394 scheduleCheckBlockedThreads(cap);
396 #if defined(PARALLEL_HASKELL)
397 /* message processing and work distribution goes here */
399 /* if messages have been buffered... a NOOP in THREADED_RTS */
400 scheduleSendPendingMessages();
402 /* If the run queue is empty,...*/
403 if (emptyRunQueue(cap)) {
404 /* ...take one of our own sparks and turn it into a thread */
405 scheduleActivateSpark(cap);
407 /* if this did not work, try to steal a spark from someone else */
408 if (emptyRunQueue(cap)) {
409 receivedFinish = scheduleGetRemoteWork(cap);
410 continue; // a new round, (hopefully) with new work
412 in GUM, this a) sends out a FISH and returns IF no fish is
414 b) (blocking) awaits and receives messages
416 in Eden, this is only the blocking receive, as b) in GUM.
421 /* since we perform a blocking receive and continue otherwise,
422 either we never reach here or we definitely have work! */
423 // from here: non-empty run queue
424 ASSERT(!emptyRunQueue(cap));
426 if (PacketsWaiting()) { /* now process incoming messages, if any
429 CAUTION: scheduleGetRemoteWork called
430 above, waits for messages as well! */
431 processMessages(cap, &receivedFinish);
433 #endif // PARALLEL_HASKELL
435 scheduleDetectDeadlock(cap,task);
436 #if defined(THREADED_RTS)
437 cap = task->cap; // reload cap, it might have changed
440 // Normally, the only way we can get here with no threads to
441 // run is if a keyboard interrupt received during
442 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
443 // Additionally, it is not fatal for the
444 // threaded RTS to reach here with no threads to run.
446 // win32: might be here due to awaitEvent() being abandoned
447 // as a result of a console event having been delivered.
448 if ( emptyRunQueue(cap) ) {
449 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
450 ASSERT(sched_state >= SCHED_INTERRUPTING);
452 continue; // nothing to do
456 // Get a thread to run
458 t = popRunQueue(cap);
460 // Sanity check the thread we're about to run. This can be
461 // expensive if there is lots of thread switching going on...
462 IF_DEBUG(sanity,checkTSO(t));
464 #if defined(THREADED_RTS)
465 // Check whether we can run this thread in the current task.
466 // If not, we have to pass our capability to the right task.
468 Task *bound = t->bound;
472 debugTrace(DEBUG_sched,
473 "### Running thread %lu in bound thread", (unsigned long)t->id);
474 // yes, the Haskell thread is bound to the current native thread
476 debugTrace(DEBUG_sched,
477 "### thread %lu bound to another OS thread", (unsigned long)t->id);
478 // no, bound to a different Haskell thread: pass to that thread
479 pushOnRunQueue(cap,t);
483 // The thread we want to run is unbound.
485 debugTrace(DEBUG_sched,
486 "### this OS thread cannot run thread %lu", (unsigned long)t->id);
487 // no, the current native thread is bound to a different
488 // Haskell thread, so pass it to any worker thread
489 pushOnRunQueue(cap,t);
496 /* context switches are initiated by the timer signal, unless
497 * the user specified "context switch as often as possible", with
500 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
501 && !emptyThreadQueues(cap)) {
502 cap->context_switch = 1;
507 // CurrentTSO is the thread to run. t might be different if we
508 // loop back to run_thread, so make sure to set CurrentTSO after
510 cap->r.rCurrentTSO = t;
512 debugTrace(DEBUG_sched, "-->> running thread %ld %s ...",
513 (long)t->id, whatNext_strs[t->what_next]);
515 startHeapProfTimer();
517 // Check for exceptions blocked on this thread
518 maybePerformBlockedException (cap, t);
520 // ----------------------------------------------------------------------
521 // Run the current thread
523 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
524 ASSERT(t->cap == cap);
526 prev_what_next = t->what_next;
528 errno = t->saved_errno;
530 SetLastError(t->saved_winerror);
533 cap->in_haskell = rtsTrue;
537 #if defined(THREADED_RTS)
538 if (recent_activity == ACTIVITY_DONE_GC) {
539 // ACTIVITY_DONE_GC means we turned off the timer signal to
540 // conserve power (see #1623). Re-enable it here.
542 prev = xchg((P_)&recent_activity, ACTIVITY_YES);
543 if (prev == ACTIVITY_DONE_GC) {
547 recent_activity = ACTIVITY_YES;
551 switch (prev_what_next) {
555 /* Thread already finished, return to scheduler. */
556 ret = ThreadFinished;
562 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
563 cap = regTableToCapability(r);
568 case ThreadInterpret:
569 cap = interpretBCO(cap);
574 barf("schedule: invalid what_next field");
577 cap->in_haskell = rtsFalse;
579 // The TSO might have moved, eg. if it re-entered the RTS and a GC
580 // happened. So find the new location:
581 t = cap->r.rCurrentTSO;
583 // We have run some Haskell code: there might be blackhole-blocked
584 // threads to wake up now.
585 // Lock-free test here should be ok, we're just setting a flag.
586 if ( blackhole_queue != END_TSO_QUEUE ) {
587 blackholes_need_checking = rtsTrue;
590 // And save the current errno in this thread.
591 // XXX: possibly bogus for SMP because this thread might already
592 // be running again, see code below.
593 t->saved_errno = errno;
595 // Similarly for Windows error code
596 t->saved_winerror = GetLastError();
599 #if defined(THREADED_RTS)
600 // If ret is ThreadBlocked, and this Task is bound to the TSO that
601 // blocked, we are in limbo - the TSO is now owned by whatever it
602 // is blocked on, and may in fact already have been woken up,
603 // perhaps even on a different Capability. It may be the case
604 // that task->cap != cap. We better yield this Capability
605 // immediately and return to normaility.
606 if (ret == ThreadBlocked) {
607 debugTrace(DEBUG_sched,
608 "--<< thread %lu (%s) stopped: blocked",
609 (unsigned long)t->id, whatNext_strs[t->what_next]);
614 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
615 ASSERT(t->cap == cap);
617 // ----------------------------------------------------------------------
619 // Costs for the scheduler are assigned to CCS_SYSTEM
621 #if defined(PROFILING)
625 schedulePostRunThread(t);
627 t = threadStackUnderflow(task,t);
629 ready_to_gc = rtsFalse;
633 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
637 scheduleHandleStackOverflow(cap,task,t);
641 if (scheduleHandleYield(cap, t, prev_what_next)) {
642 // shortcut for switching between compiler/interpreter:
648 scheduleHandleThreadBlocked(t);
652 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
653 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
657 barf("schedule: invalid thread return code %d", (int)ret);
660 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
661 cap = scheduleDoGC(cap,task,rtsFalse);
663 } /* end of while() */
666 /* ----------------------------------------------------------------------------
667 * Setting up the scheduler loop
668 * ------------------------------------------------------------------------- */
671 schedulePreLoop(void)
673 // initialisation for scheduler - what cannot go into initScheduler()
676 /* -----------------------------------------------------------------------------
679 * Push work to other Capabilities if we have some.
680 * -------------------------------------------------------------------------- */
682 #if defined(THREADED_RTS)
684 schedulePushWork(Capability *cap USED_IF_THREADS,
685 Task *task USED_IF_THREADS)
687 Capability *free_caps[n_capabilities], *cap0;
690 // migration can be turned off with +RTS -qg
691 if (!RtsFlags.ParFlags.migrate) return;
693 // Check whether we have more threads on our run queue, or sparks
694 // in our pool, that we could hand to another Capability.
695 if ((emptyRunQueue(cap) || cap->run_queue_hd->_link == END_TSO_QUEUE)
696 && sparkPoolSizeCap(cap) < 2) {
700 // First grab as many free Capabilities as we can.
701 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
702 cap0 = &capabilities[i];
703 if (cap != cap0 && tryGrabCapability(cap0,task)) {
704 if (!emptyRunQueue(cap0) || cap->returning_tasks_hd != NULL) {
705 // it already has some work, we just grabbed it at
706 // the wrong moment. Or maybe it's deadlocked!
707 releaseCapability(cap0);
709 free_caps[n_free_caps++] = cap0;
714 // we now have n_free_caps free capabilities stashed in
715 // free_caps[]. Share our run queue equally with them. This is
716 // probably the simplest thing we could do; improvements we might
717 // want to do include:
719 // - giving high priority to moving relatively new threads, on
720 // the gournds that they haven't had time to build up a
721 // working set in the cache on this CPU/Capability.
723 // - giving low priority to moving long-lived threads
725 if (n_free_caps > 0) {
726 StgTSO *prev, *t, *next;
727 rtsBool pushed_to_all;
729 debugTrace(DEBUG_sched, "excess threads on run queue and %d free capabilities, sharing...", n_free_caps);
732 pushed_to_all = rtsFalse;
734 if (cap->run_queue_hd != END_TSO_QUEUE) {
735 prev = cap->run_queue_hd;
737 prev->_link = END_TSO_QUEUE;
738 for (; t != END_TSO_QUEUE; t = next) {
740 t->_link = END_TSO_QUEUE;
741 if (t->what_next == ThreadRelocated
742 || t->bound == task // don't move my bound thread
743 || tsoLocked(t)) { // don't move a locked thread
744 setTSOLink(cap, prev, t);
746 } else if (i == n_free_caps) {
747 pushed_to_all = rtsTrue;
750 setTSOLink(cap, prev, t);
753 debugTrace(DEBUG_sched, "pushing thread %lu to capability %d", (unsigned long)t->id, free_caps[i]->no);
754 appendToRunQueue(free_caps[i],t);
755 if (t->bound) { t->bound->cap = free_caps[i]; }
756 t->cap = free_caps[i];
760 cap->run_queue_tl = prev;
763 // If there are some free capabilities that we didn't push any
764 // threads to, then try to push a spark to each one.
765 if (!pushed_to_all) {
767 // i is the next free capability to push to
768 for (; i < n_free_caps; i++) {
769 if (emptySparkPoolCap(free_caps[i])) {
770 spark = findSpark(cap);
772 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
773 newSpark(&(free_caps[i]->r), spark);
779 // release the capabilities
780 for (i = 0; i < n_free_caps; i++) {
781 task->cap = free_caps[i];
782 releaseCapability(free_caps[i]);
785 task->cap = cap; // reset to point to our Capability.
789 /* ----------------------------------------------------------------------------
790 * Start any pending signal handlers
791 * ------------------------------------------------------------------------- */
793 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
795 scheduleStartSignalHandlers(Capability *cap)
797 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
798 // safe outside the lock
799 startSignalHandlers(cap);
804 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
809 /* ----------------------------------------------------------------------------
810 * Check for blocked threads that can be woken up.
811 * ------------------------------------------------------------------------- */
814 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
816 #if !defined(THREADED_RTS)
818 // Check whether any waiting threads need to be woken up. If the
819 // run queue is empty, and there are no other tasks running, we
820 // can wait indefinitely for something to happen.
822 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
824 awaitEvent( emptyRunQueue(cap) && !blackholes_need_checking );
830 /* ----------------------------------------------------------------------------
831 * Check for threads woken up by other Capabilities
832 * ------------------------------------------------------------------------- */
835 scheduleCheckWakeupThreads(Capability *cap USED_IF_THREADS)
837 #if defined(THREADED_RTS)
838 // Any threads that were woken up by other Capabilities get
839 // appended to our run queue.
840 if (!emptyWakeupQueue(cap)) {
841 ACQUIRE_LOCK(&cap->lock);
842 if (emptyRunQueue(cap)) {
843 cap->run_queue_hd = cap->wakeup_queue_hd;
844 cap->run_queue_tl = cap->wakeup_queue_tl;
846 setTSOLink(cap, cap->run_queue_tl, cap->wakeup_queue_hd);
847 cap->run_queue_tl = cap->wakeup_queue_tl;
849 cap->wakeup_queue_hd = cap->wakeup_queue_tl = END_TSO_QUEUE;
850 RELEASE_LOCK(&cap->lock);
855 /* ----------------------------------------------------------------------------
856 * Check for threads blocked on BLACKHOLEs that can be woken up
857 * ------------------------------------------------------------------------- */
859 scheduleCheckBlackHoles (Capability *cap)
861 if ( blackholes_need_checking ) // check without the lock first
863 ACQUIRE_LOCK(&sched_mutex);
864 if ( blackholes_need_checking ) {
865 checkBlackHoles(cap);
866 blackholes_need_checking = rtsFalse;
868 RELEASE_LOCK(&sched_mutex);
872 /* ----------------------------------------------------------------------------
873 * Detect deadlock conditions and attempt to resolve them.
874 * ------------------------------------------------------------------------- */
877 scheduleDetectDeadlock (Capability *cap, Task *task)
880 #if defined(PARALLEL_HASKELL)
881 // ToDo: add deadlock detection in GUM (similar to THREADED_RTS) -- HWL
886 * Detect deadlock: when we have no threads to run, there are no
887 * threads blocked, waiting for I/O, or sleeping, and all the
888 * other tasks are waiting for work, we must have a deadlock of
891 if ( emptyThreadQueues(cap) )
893 #if defined(THREADED_RTS)
895 * In the threaded RTS, we only check for deadlock if there
896 * has been no activity in a complete timeslice. This means
897 * we won't eagerly start a full GC just because we don't have
898 * any threads to run currently.
900 if (recent_activity != ACTIVITY_INACTIVE) return;
903 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
905 // Garbage collection can release some new threads due to
906 // either (a) finalizers or (b) threads resurrected because
907 // they are unreachable and will therefore be sent an
908 // exception. Any threads thus released will be immediately
910 cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
912 recent_activity = ACTIVITY_DONE_GC;
913 // disable timer signals (see #1623)
916 if ( !emptyRunQueue(cap) ) return;
918 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
919 /* If we have user-installed signal handlers, then wait
920 * for signals to arrive rather then bombing out with a
923 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
924 debugTrace(DEBUG_sched,
925 "still deadlocked, waiting for signals...");
929 if (signals_pending()) {
930 startSignalHandlers(cap);
933 // either we have threads to run, or we were interrupted:
934 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
940 #if !defined(THREADED_RTS)
941 /* Probably a real deadlock. Send the current main thread the
942 * Deadlock exception.
945 switch (task->tso->why_blocked) {
947 case BlockedOnBlackHole:
948 case BlockedOnException:
950 throwToSingleThreaded(cap, task->tso,
951 (StgClosure *)nonTermination_closure);
954 barf("deadlock: main thread blocked in a strange way");
963 /* ----------------------------------------------------------------------------
964 * Send pending messages (PARALLEL_HASKELL only)
965 * ------------------------------------------------------------------------- */
967 #if defined(PARALLEL_HASKELL)
969 scheduleSendPendingMessages(void)
972 # if defined(PAR) // global Mem.Mgmt., omit for now
973 if (PendingFetches != END_BF_QUEUE) {
978 if (RtsFlags.ParFlags.BufferTime) {
979 // if we use message buffering, we must send away all message
980 // packets which have become too old...
986 /* ----------------------------------------------------------------------------
987 * Activate spark threads (PARALLEL_HASKELL only)
988 * ------------------------------------------------------------------------- */
990 #if defined(PARALLEL_HASKELL)
992 scheduleActivateSpark(Capability *cap)
996 /* We only want to stay here if the run queue is empty and we want some
997 work. We try to turn a spark into a thread, and add it to the run
998 queue, from where it will be picked up in the next iteration of the
1001 if (!emptyRunQueue(cap))
1002 /* In the threaded RTS, another task might have pushed a thread
1003 on our run queue in the meantime ? But would need a lock.. */
1006 spark = findSpark(cap); // defined in Sparks.c
1008 if (spark != NULL) {
1009 debugTrace(DEBUG_sched,
1010 "turning spark of closure %p into a thread",
1011 (StgClosure *)spark);
1012 createSparkThread(cap,spark); // defined in Sparks.c
1015 #endif // PARALLEL_HASKELL
1017 /* ----------------------------------------------------------------------------
1018 * Get work from a remote node (PARALLEL_HASKELL only)
1019 * ------------------------------------------------------------------------- */
1021 #if defined(PARALLEL_HASKELL)
1023 scheduleGetRemoteWork(Capability *cap)
1025 #if defined(PARALLEL_HASKELL)
1026 rtsBool receivedFinish = rtsFalse;
1028 // idle() , i.e. send all buffers, wait for work
1029 if (RtsFlags.ParFlags.BufferTime) {
1030 IF_PAR_DEBUG(verbose,
1031 debugBelch("...send all pending data,"));
1034 for (i=1; i<=nPEs; i++)
1035 sendImmediately(i); // send all messages away immediately
1039 /* this would be the place for fishing in GUM...
1041 if (no-earlier-fish-around)
1042 sendFish(choosePe());
1045 // Eden:just look for incoming messages (blocking receive)
1046 IF_PAR_DEBUG(verbose,
1047 debugBelch("...wait for incoming messages...\n"));
1048 processMessages(cap, &receivedFinish); // blocking receive...
1051 return receivedFinish;
1052 // reenter scheduling look after having received something
1054 #else /* !PARALLEL_HASKELL, i.e. THREADED_RTS */
1056 return rtsFalse; /* return value unused in THREADED_RTS */
1058 #endif /* PARALLEL_HASKELL */
1060 #endif // PARALLEL_HASKELL
1062 /* ----------------------------------------------------------------------------
1063 * After running a thread...
1064 * ------------------------------------------------------------------------- */
1067 schedulePostRunThread (StgTSO *t)
1069 // We have to be able to catch transactions that are in an
1070 // infinite loop as a result of seeing an inconsistent view of
1074 // [a,b] <- mapM readTVar [ta,tb]
1075 // when (a == b) loop
1077 // and a is never equal to b given a consistent view of memory.
1079 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1080 if (!stmValidateNestOfTransactions (t -> trec)) {
1081 debugTrace(DEBUG_sched | DEBUG_stm,
1082 "trec %p found wasting its time", t);
1084 // strip the stack back to the
1085 // ATOMICALLY_FRAME, aborting the (nested)
1086 // transaction, and saving the stack of any
1087 // partially-evaluated thunks on the heap.
1088 throwToSingleThreaded_(&capabilities[0], t,
1089 NULL, rtsTrue, NULL);
1091 ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1095 /* some statistics gathering in the parallel case */
1098 /* -----------------------------------------------------------------------------
1099 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1100 * -------------------------------------------------------------------------- */
1103 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1105 // did the task ask for a large block?
1106 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1107 // if so, get one and push it on the front of the nursery.
1111 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1113 debugTrace(DEBUG_sched,
1114 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1115 (long)t->id, whatNext_strs[t->what_next], blocks);
1117 // don't do this if the nursery is (nearly) full, we'll GC first.
1118 if (cap->r.rCurrentNursery->link != NULL ||
1119 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1120 // if the nursery has only one block.
1123 bd = allocGroup( blocks );
1125 cap->r.rNursery->n_blocks += blocks;
1127 // link the new group into the list
1128 bd->link = cap->r.rCurrentNursery;
1129 bd->u.back = cap->r.rCurrentNursery->u.back;
1130 if (cap->r.rCurrentNursery->u.back != NULL) {
1131 cap->r.rCurrentNursery->u.back->link = bd;
1133 #if !defined(THREADED_RTS)
1134 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1135 g0s0 == cap->r.rNursery);
1137 cap->r.rNursery->blocks = bd;
1139 cap->r.rCurrentNursery->u.back = bd;
1141 // initialise it as a nursery block. We initialise the
1142 // step, gen_no, and flags field of *every* sub-block in
1143 // this large block, because this is easier than making
1144 // sure that we always find the block head of a large
1145 // block whenever we call Bdescr() (eg. evacuate() and
1146 // isAlive() in the GC would both have to do this, at
1150 for (x = bd; x < bd + blocks; x++) {
1151 x->step = cap->r.rNursery;
1157 // This assert can be a killer if the app is doing lots
1158 // of large block allocations.
1159 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1161 // now update the nursery to point to the new block
1162 cap->r.rCurrentNursery = bd;
1164 // we might be unlucky and have another thread get on the
1165 // run queue before us and steal the large block, but in that
1166 // case the thread will just end up requesting another large
1168 pushOnRunQueue(cap,t);
1169 return rtsFalse; /* not actually GC'ing */
1173 debugTrace(DEBUG_sched,
1174 "--<< thread %ld (%s) stopped: HeapOverflow",
1175 (long)t->id, whatNext_strs[t->what_next]);
1177 if (cap->context_switch) {
1178 // Sometimes we miss a context switch, e.g. when calling
1179 // primitives in a tight loop, MAYBE_GC() doesn't check the
1180 // context switch flag, and we end up waiting for a GC.
1181 // See #1984, and concurrent/should_run/1984
1182 cap->context_switch = 0;
1183 addToRunQueue(cap,t);
1185 pushOnRunQueue(cap,t);
1188 /* actual GC is done at the end of the while loop in schedule() */
1191 /* -----------------------------------------------------------------------------
1192 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1193 * -------------------------------------------------------------------------- */
1196 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1198 debugTrace (DEBUG_sched,
1199 "--<< thread %ld (%s) stopped, StackOverflow",
1200 (long)t->id, whatNext_strs[t->what_next]);
1202 /* just adjust the stack for this thread, then pop it back
1206 /* enlarge the stack */
1207 StgTSO *new_t = threadStackOverflow(cap, t);
1209 /* The TSO attached to this Task may have moved, so update the
1212 if (task->tso == t) {
1215 pushOnRunQueue(cap,new_t);
1219 /* -----------------------------------------------------------------------------
1220 * Handle a thread that returned to the scheduler with ThreadYielding
1221 * -------------------------------------------------------------------------- */
1224 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1226 // Reset the context switch flag. We don't do this just before
1227 // running the thread, because that would mean we would lose ticks
1228 // during GC, which can lead to unfair scheduling (a thread hogs
1229 // the CPU because the tick always arrives during GC). This way
1230 // penalises threads that do a lot of allocation, but that seems
1231 // better than the alternative.
1232 cap->context_switch = 0;
1234 /* put the thread back on the run queue. Then, if we're ready to
1235 * GC, check whether this is the last task to stop. If so, wake
1236 * up the GC thread. getThread will block during a GC until the
1240 if (t->what_next != prev_what_next) {
1241 debugTrace(DEBUG_sched,
1242 "--<< thread %ld (%s) stopped to switch evaluators",
1243 (long)t->id, whatNext_strs[t->what_next]);
1245 debugTrace(DEBUG_sched,
1246 "--<< thread %ld (%s) stopped, yielding",
1247 (long)t->id, whatNext_strs[t->what_next]);
1252 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1254 ASSERT(t->_link == END_TSO_QUEUE);
1256 // Shortcut if we're just switching evaluators: don't bother
1257 // doing stack squeezing (which can be expensive), just run the
1259 if (t->what_next != prev_what_next) {
1263 addToRunQueue(cap,t);
1268 /* -----------------------------------------------------------------------------
1269 * Handle a thread that returned to the scheduler with ThreadBlocked
1270 * -------------------------------------------------------------------------- */
1273 scheduleHandleThreadBlocked( StgTSO *t
1274 #if !defined(GRAN) && !defined(DEBUG)
1280 // We don't need to do anything. The thread is blocked, and it
1281 // has tidied up its stack and placed itself on whatever queue
1282 // it needs to be on.
1284 // ASSERT(t->why_blocked != NotBlocked);
1285 // Not true: for example,
1286 // - in THREADED_RTS, the thread may already have been woken
1287 // up by another Capability. This actually happens: try
1288 // conc023 +RTS -N2.
1289 // - the thread may have woken itself up already, because
1290 // threadPaused() might have raised a blocked throwTo
1291 // exception, see maybePerformBlockedException().
1294 if (traceClass(DEBUG_sched)) {
1295 debugTraceBegin("--<< thread %lu (%s) stopped: ",
1296 (unsigned long)t->id, whatNext_strs[t->what_next]);
1297 printThreadBlockage(t);
1303 /* -----------------------------------------------------------------------------
1304 * Handle a thread that returned to the scheduler with ThreadFinished
1305 * -------------------------------------------------------------------------- */
1308 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1310 /* Need to check whether this was a main thread, and if so,
1311 * return with the return value.
1313 * We also end up here if the thread kills itself with an
1314 * uncaught exception, see Exception.cmm.
1316 debugTrace(DEBUG_sched, "--++ thread %lu (%s) finished",
1317 (unsigned long)t->id, whatNext_strs[t->what_next]);
1320 // Check whether the thread that just completed was a bound
1321 // thread, and if so return with the result.
1323 // There is an assumption here that all thread completion goes
1324 // through this point; we need to make sure that if a thread
1325 // ends up in the ThreadKilled state, that it stays on the run
1326 // queue so it can be dealt with here.
1331 if (t->bound != task) {
1332 #if !defined(THREADED_RTS)
1333 // Must be a bound thread that is not the topmost one. Leave
1334 // it on the run queue until the stack has unwound to the
1335 // point where we can deal with this. Leaving it on the run
1336 // queue also ensures that the garbage collector knows about
1337 // this thread and its return value (it gets dropped from the
1338 // step->threads list so there's no other way to find it).
1339 appendToRunQueue(cap,t);
1342 // this cannot happen in the threaded RTS, because a
1343 // bound thread can only be run by the appropriate Task.
1344 barf("finished bound thread that isn't mine");
1348 ASSERT(task->tso == t);
1350 if (t->what_next == ThreadComplete) {
1352 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1353 *(task->ret) = (StgClosure *)task->tso->sp[1];
1355 task->stat = Success;
1358 *(task->ret) = NULL;
1360 if (sched_state >= SCHED_INTERRUPTING) {
1361 task->stat = Interrupted;
1363 task->stat = Killed;
1367 removeThreadLabel((StgWord)task->tso->id);
1369 return rtsTrue; // tells schedule() to return
1375 /* -----------------------------------------------------------------------------
1376 * Perform a heap census
1377 * -------------------------------------------------------------------------- */
1380 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1382 // When we have +RTS -i0 and we're heap profiling, do a census at
1383 // every GC. This lets us get repeatable runs for debugging.
1384 if (performHeapProfile ||
1385 (RtsFlags.ProfFlags.profileInterval==0 &&
1386 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1393 /* -----------------------------------------------------------------------------
1394 * Perform a garbage collection if necessary
1395 * -------------------------------------------------------------------------- */
1398 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1400 rtsBool heap_census;
1402 /* extern static volatile StgWord waiting_for_gc;
1403 lives inside capability.c */
1404 rtsBool was_waiting;
1409 // In order to GC, there must be no threads running Haskell code.
1410 // Therefore, the GC thread needs to hold *all* the capabilities,
1411 // and release them after the GC has completed.
1413 // This seems to be the simplest way: previous attempts involved
1414 // making all the threads with capabilities give up their
1415 // capabilities and sleep except for the *last* one, which
1416 // actually did the GC. But it's quite hard to arrange for all
1417 // the other tasks to sleep and stay asleep.
1420 /* Other capabilities are prevented from running yet more Haskell
1421 threads if waiting_for_gc is set. Tested inside
1422 yieldCapability() and releaseCapability() in Capability.c */
1424 was_waiting = cas(&waiting_for_gc, 0, 1);
1427 debugTrace(DEBUG_sched, "someone else is trying to GC...");
1428 if (cap) yieldCapability(&cap,task);
1429 } while (waiting_for_gc);
1430 return cap; // NOTE: task->cap might have changed here
1433 setContextSwitches();
1434 for (i=0; i < n_capabilities; i++) {
1435 debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1436 if (cap != &capabilities[i]) {
1437 Capability *pcap = &capabilities[i];
1438 // we better hope this task doesn't get migrated to
1439 // another Capability while we're waiting for this one.
1440 // It won't, because load balancing happens while we have
1441 // all the Capabilities, but even so it's a slightly
1442 // unsavoury invariant.
1444 waitForReturnCapability(&pcap, task);
1445 if (pcap != &capabilities[i]) {
1446 barf("scheduleDoGC: got the wrong capability");
1451 waiting_for_gc = rtsFalse;
1454 // so this happens periodically:
1455 if (cap) scheduleCheckBlackHoles(cap);
1457 IF_DEBUG(scheduler, printAllThreads());
1460 * We now have all the capabilities; if we're in an interrupting
1461 * state, then we should take the opportunity to delete all the
1462 * threads in the system.
1464 if (sched_state >= SCHED_INTERRUPTING) {
1465 deleteAllThreads(&capabilities[0]);
1466 sched_state = SCHED_SHUTTING_DOWN;
1469 heap_census = scheduleNeedHeapProfile(rtsTrue);
1471 /* everybody back, start the GC.
1472 * Could do it in this thread, or signal a condition var
1473 * to do it in another thread. Either way, we need to
1474 * broadcast on gc_pending_cond afterward.
1476 #if defined(THREADED_RTS)
1477 debugTrace(DEBUG_sched, "doing GC");
1479 GarbageCollect(force_major || heap_census);
1482 debugTrace(DEBUG_sched, "performing heap census");
1484 performHeapProfile = rtsFalse;
1487 #if defined(THREADED_RTS)
1488 // release our stash of capabilities.
1489 for (i = 0; i < n_capabilities; i++) {
1490 if (cap != &capabilities[i]) {
1491 task->cap = &capabilities[i];
1492 releaseCapability(&capabilities[i]);
1505 /* ---------------------------------------------------------------------------
1506 * Singleton fork(). Do not copy any running threads.
1507 * ------------------------------------------------------------------------- */
1510 forkProcess(HsStablePtr *entry
1511 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1516 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1523 #if defined(THREADED_RTS)
1524 if (RtsFlags.ParFlags.nNodes > 1) {
1525 errorBelch("forking not supported with +RTS -N<n> greater than 1");
1526 stg_exit(EXIT_FAILURE);
1530 debugTrace(DEBUG_sched, "forking!");
1532 // ToDo: for SMP, we should probably acquire *all* the capabilities
1535 // no funny business: hold locks while we fork, otherwise if some
1536 // other thread is holding a lock when the fork happens, the data
1537 // structure protected by the lock will forever be in an
1538 // inconsistent state in the child. See also #1391.
1539 ACQUIRE_LOCK(&sched_mutex);
1540 ACQUIRE_LOCK(&cap->lock);
1541 ACQUIRE_LOCK(&cap->running_task->lock);
1545 if (pid) { // parent
1547 RELEASE_LOCK(&sched_mutex);
1548 RELEASE_LOCK(&cap->lock);
1549 RELEASE_LOCK(&cap->running_task->lock);
1551 // just return the pid
1557 #if defined(THREADED_RTS)
1558 initMutex(&sched_mutex);
1559 initMutex(&cap->lock);
1560 initMutex(&cap->running_task->lock);
1563 // Now, all OS threads except the thread that forked are
1564 // stopped. We need to stop all Haskell threads, including
1565 // those involved in foreign calls. Also we need to delete
1566 // all Tasks, because they correspond to OS threads that are
1569 for (s = 0; s < total_steps; s++) {
1570 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1571 if (t->what_next == ThreadRelocated) {
1574 next = t->global_link;
1575 // don't allow threads to catch the ThreadKilled
1576 // exception, but we do want to raiseAsync() because these
1577 // threads may be evaluating thunks that we need later.
1578 deleteThread_(cap,t);
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_ccalling_tasks = NULL;
1594 // Empty the threads lists. Otherwise, the garbage
1595 // collector may attempt to resurrect some of these threads.
1596 for (s = 0; s < total_steps; s++) {
1597 all_steps[s].threads = END_TSO_QUEUE;
1600 // Wipe the task list, except the current Task.
1601 ACQUIRE_LOCK(&sched_mutex);
1602 for (task = all_tasks; task != NULL; task=task->all_link) {
1603 if (task != cap->running_task) {
1604 #if defined(THREADED_RTS)
1605 initMutex(&task->lock); // see #1391
1610 RELEASE_LOCK(&sched_mutex);
1612 #if defined(THREADED_RTS)
1613 // Wipe our spare workers list, they no longer exist. New
1614 // workers will be created if necessary.
1615 cap->spare_workers = NULL;
1616 cap->returning_tasks_hd = NULL;
1617 cap->returning_tasks_tl = NULL;
1620 // On Unix, all timers are reset in the child, so we need to start
1625 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1626 rts_checkSchedStatus("forkProcess",cap);
1629 hs_exit(); // clean up and exit
1630 stg_exit(EXIT_SUCCESS);
1632 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1633 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1638 /* ---------------------------------------------------------------------------
1639 * Delete all the threads in the system
1640 * ------------------------------------------------------------------------- */
1643 deleteAllThreads ( Capability *cap )
1645 // NOTE: only safe to call if we own all capabilities.
1650 debugTrace(DEBUG_sched,"deleting all threads");
1651 for (s = 0; s < total_steps; s++) {
1652 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1653 if (t->what_next == ThreadRelocated) {
1656 next = t->global_link;
1657 deleteThread(cap,t);
1662 // The run queue now contains a bunch of ThreadKilled threads. We
1663 // must not throw these away: the main thread(s) will be in there
1664 // somewhere, and the main scheduler loop has to deal with it.
1665 // Also, the run queue is the only thing keeping these threads from
1666 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1668 #if !defined(THREADED_RTS)
1669 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1670 ASSERT(sleeping_queue == END_TSO_QUEUE);
1674 /* -----------------------------------------------------------------------------
1675 Managing the suspended_ccalling_tasks list.
1676 Locks required: sched_mutex
1677 -------------------------------------------------------------------------- */
1680 suspendTask (Capability *cap, Task *task)
1682 ASSERT(task->next == NULL && task->prev == NULL);
1683 task->next = cap->suspended_ccalling_tasks;
1685 if (cap->suspended_ccalling_tasks) {
1686 cap->suspended_ccalling_tasks->prev = task;
1688 cap->suspended_ccalling_tasks = task;
1692 recoverSuspendedTask (Capability *cap, Task *task)
1695 task->prev->next = task->next;
1697 ASSERT(cap->suspended_ccalling_tasks == task);
1698 cap->suspended_ccalling_tasks = task->next;
1701 task->next->prev = task->prev;
1703 task->next = task->prev = NULL;
1706 /* ---------------------------------------------------------------------------
1707 * Suspending & resuming Haskell threads.
1709 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1710 * its capability before calling the C function. This allows another
1711 * task to pick up the capability and carry on running Haskell
1712 * threads. It also means that if the C call blocks, it won't lock
1715 * The Haskell thread making the C call is put to sleep for the
1716 * duration of the call, on the susepended_ccalling_threads queue. We
1717 * give out a token to the task, which it can use to resume the thread
1718 * on return from the C function.
1719 * ------------------------------------------------------------------------- */
1722 suspendThread (StgRegTable *reg)
1729 StgWord32 saved_winerror;
1732 saved_errno = errno;
1734 saved_winerror = GetLastError();
1737 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1739 cap = regTableToCapability(reg);
1741 task = cap->running_task;
1742 tso = cap->r.rCurrentTSO;
1744 debugTrace(DEBUG_sched,
1745 "thread %lu did a safe foreign call",
1746 (unsigned long)cap->r.rCurrentTSO->id);
1748 // XXX this might not be necessary --SDM
1749 tso->what_next = ThreadRunGHC;
1751 threadPaused(cap,tso);
1753 if ((tso->flags & TSO_BLOCKEX) == 0) {
1754 tso->why_blocked = BlockedOnCCall;
1755 tso->flags |= TSO_BLOCKEX;
1756 tso->flags &= ~TSO_INTERRUPTIBLE;
1758 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1761 // Hand back capability
1762 task->suspended_tso = tso;
1764 ACQUIRE_LOCK(&cap->lock);
1766 suspendTask(cap,task);
1767 cap->in_haskell = rtsFalse;
1768 releaseCapability_(cap);
1770 RELEASE_LOCK(&cap->lock);
1772 #if defined(THREADED_RTS)
1773 /* Preparing to leave the RTS, so ensure there's a native thread/task
1774 waiting to take over.
1776 debugTrace(DEBUG_sched, "thread %lu: leaving RTS", (unsigned long)tso->id);
1779 errno = saved_errno;
1781 SetLastError(saved_winerror);
1787 resumeThread (void *task_)
1794 StgWord32 saved_winerror;
1797 saved_errno = errno;
1799 saved_winerror = GetLastError();
1803 // Wait for permission to re-enter the RTS with the result.
1804 waitForReturnCapability(&cap,task);
1805 // we might be on a different capability now... but if so, our
1806 // entry on the suspended_ccalling_tasks list will also have been
1809 // Remove the thread from the suspended list
1810 recoverSuspendedTask(cap,task);
1812 tso = task->suspended_tso;
1813 task->suspended_tso = NULL;
1814 tso->_link = END_TSO_QUEUE; // no write barrier reqd
1815 debugTrace(DEBUG_sched, "thread %lu: re-entering RTS", (unsigned long)tso->id);
1817 if (tso->why_blocked == BlockedOnCCall) {
1818 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 wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
1871 appendToRunQueue(cap,tso);
1876 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
1880 // We already created/initialised the Task
1881 task = cap->running_task;
1883 // This TSO is now a bound thread; make the Task and TSO
1884 // point to each other.
1890 task->stat = NoStatus;
1892 appendToRunQueue(cap,tso);
1894 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)tso->id);
1896 cap = schedule(cap,task);
1898 ASSERT(task->stat != NoStatus);
1899 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
1901 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)task->tso->id);
1905 /* ----------------------------------------------------------------------------
1907 * ------------------------------------------------------------------------- */
1909 #if defined(THREADED_RTS)
1910 void OSThreadProcAttr
1911 workerStart(Task *task)
1915 // See startWorkerTask().
1916 ACQUIRE_LOCK(&task->lock);
1918 RELEASE_LOCK(&task->lock);
1920 // set the thread-local pointer to the Task:
1923 // schedule() runs without a lock.
1924 cap = schedule(cap,task);
1926 // On exit from schedule(), we have a Capability.
1927 releaseCapability(cap);
1928 workerTaskStop(task);
1932 /* ---------------------------------------------------------------------------
1935 * Initialise the scheduler. This resets all the queues - if the
1936 * queues contained any threads, they'll be garbage collected at the
1939 * ------------------------------------------------------------------------ */
1944 #if !defined(THREADED_RTS)
1945 blocked_queue_hd = END_TSO_QUEUE;
1946 blocked_queue_tl = END_TSO_QUEUE;
1947 sleeping_queue = END_TSO_QUEUE;
1950 blackhole_queue = END_TSO_QUEUE;
1952 sched_state = SCHED_RUNNING;
1953 recent_activity = ACTIVITY_YES;
1955 #if defined(THREADED_RTS)
1956 /* Initialise the mutex and condition variables used by
1958 initMutex(&sched_mutex);
1961 ACQUIRE_LOCK(&sched_mutex);
1963 /* A capability holds the state a native thread needs in
1964 * order to execute STG code. At least one capability is
1965 * floating around (only THREADED_RTS builds have more than one).
1971 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
1975 #if defined(THREADED_RTS)
1977 * Eagerly start one worker to run each Capability, except for
1978 * Capability 0. The idea is that we're probably going to start a
1979 * bound thread on Capability 0 pretty soon, so we don't want a
1980 * worker task hogging it.
1985 for (i = 1; i < n_capabilities; i++) {
1986 cap = &capabilities[i];
1987 ACQUIRE_LOCK(&cap->lock);
1988 startWorkerTask(cap, workerStart);
1989 RELEASE_LOCK(&cap->lock);
1994 trace(TRACE_sched, "start: %d capabilities", n_capabilities);
1996 RELEASE_LOCK(&sched_mutex);
2001 rtsBool wait_foreign
2002 #if !defined(THREADED_RTS)
2003 __attribute__((unused))
2006 /* see Capability.c, shutdownCapability() */
2010 #if defined(THREADED_RTS)
2011 ACQUIRE_LOCK(&sched_mutex);
2012 task = newBoundTask();
2013 RELEASE_LOCK(&sched_mutex);
2016 // If we haven't killed all the threads yet, do it now.
2017 if (sched_state < SCHED_SHUTTING_DOWN) {
2018 sched_state = SCHED_INTERRUPTING;
2019 scheduleDoGC(NULL,task,rtsFalse);
2021 sched_state = SCHED_SHUTTING_DOWN;
2023 #if defined(THREADED_RTS)
2027 for (i = 0; i < n_capabilities; i++) {
2028 shutdownCapability(&capabilities[i], task, wait_foreign);
2030 boundTaskExiting(task);
2034 freeCapability(&MainCapability);
2039 freeScheduler( void )
2042 if (n_capabilities != 1) {
2043 stgFree(capabilities);
2045 #if defined(THREADED_RTS)
2046 closeMutex(&sched_mutex);
2050 /* -----------------------------------------------------------------------------
2053 This is the interface to the garbage collector from Haskell land.
2054 We provide this so that external C code can allocate and garbage
2055 collect when called from Haskell via _ccall_GC.
2056 -------------------------------------------------------------------------- */
2059 performGC_(rtsBool force_major)
2062 // We must grab a new Task here, because the existing Task may be
2063 // associated with a particular Capability, and chained onto the
2064 // suspended_ccalling_tasks queue.
2065 ACQUIRE_LOCK(&sched_mutex);
2066 task = newBoundTask();
2067 RELEASE_LOCK(&sched_mutex);
2068 scheduleDoGC(NULL,task,force_major);
2069 boundTaskExiting(task);
2075 performGC_(rtsFalse);
2079 performMajorGC(void)
2081 performGC_(rtsTrue);
2084 /* -----------------------------------------------------------------------------
2087 If the thread has reached its maximum stack size, then raise the
2088 StackOverflow exception in the offending thread. Otherwise
2089 relocate the TSO into a larger chunk of memory and adjust its stack
2091 -------------------------------------------------------------------------- */
2094 threadStackOverflow(Capability *cap, StgTSO *tso)
2096 nat new_stack_size, stack_words;
2101 IF_DEBUG(sanity,checkTSO(tso));
2103 // don't allow throwTo() to modify the blocked_exceptions queue
2104 // while we are moving the TSO:
2105 lockClosure((StgClosure *)tso);
2107 if (tso->stack_size >= tso->max_stack_size && !(tso->flags & TSO_BLOCKEX)) {
2108 // NB. never raise a StackOverflow exception if the thread is
2109 // inside Control.Exceptino.block. It is impractical to protect
2110 // against stack overflow exceptions, since virtually anything
2111 // can raise one (even 'catch'), so this is the only sensible
2112 // thing to do here. See bug #767.
2114 debugTrace(DEBUG_gc,
2115 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2116 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2118 /* If we're debugging, just print out the top of the stack */
2119 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2122 // Send this thread the StackOverflow exception
2124 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2128 /* Try to double the current stack size. If that takes us over the
2129 * maximum stack size for this thread, then use the maximum instead.
2130 * Finally round up so the TSO ends up as a whole number of blocks.
2132 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2133 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2134 TSO_STRUCT_SIZE)/sizeof(W_);
2135 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2136 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2138 debugTrace(DEBUG_sched,
2139 "increasing stack size from %ld words to %d.",
2140 (long)tso->stack_size, new_stack_size);
2142 dest = (StgTSO *)allocateLocal(cap,new_tso_size);
2143 TICK_ALLOC_TSO(new_stack_size,0);
2145 /* copy the TSO block and the old stack into the new area */
2146 memcpy(dest,tso,TSO_STRUCT_SIZE);
2147 stack_words = tso->stack + tso->stack_size - tso->sp;
2148 new_sp = (P_)dest + new_tso_size - stack_words;
2149 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2151 /* relocate the stack pointers... */
2153 dest->stack_size = new_stack_size;
2155 /* Mark the old TSO as relocated. We have to check for relocated
2156 * TSOs in the garbage collector and any primops that deal with TSOs.
2158 * It's important to set the sp value to just beyond the end
2159 * of the stack, so we don't attempt to scavenge any part of the
2162 tso->what_next = ThreadRelocated;
2163 setTSOLink(cap,tso,dest);
2164 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2165 tso->why_blocked = NotBlocked;
2167 IF_PAR_DEBUG(verbose,
2168 debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2169 tso->id, tso, tso->stack_size);
2170 /* If we're debugging, just print out the top of the stack */
2171 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2177 IF_DEBUG(sanity,checkTSO(dest));
2179 IF_DEBUG(scheduler,printTSO(dest));
2186 threadStackUnderflow (Task *task STG_UNUSED, StgTSO *tso)
2188 bdescr *bd, *new_bd;
2189 lnat free_w, tso_size_w;
2192 tso_size_w = tso_sizeW(tso);
2194 if (tso_size_w < MBLOCK_SIZE_W ||
2195 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2200 // don't allow throwTo() to modify the blocked_exceptions queue
2201 // while we are moving the TSO:
2202 lockClosure((StgClosure *)tso);
2204 // this is the number of words we'll free
2205 free_w = round_to_mblocks(tso_size_w/2);
2207 bd = Bdescr((StgPtr)tso);
2208 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2209 bd->free = bd->start + TSO_STRUCT_SIZEW;
2211 new_tso = (StgTSO *)new_bd->start;
2212 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2213 new_tso->stack_size = new_bd->free - new_tso->stack;
2215 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2216 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2218 tso->what_next = ThreadRelocated;
2219 tso->_link = new_tso; // no write barrier reqd: same generation
2221 // The TSO attached to this Task may have moved, so update the
2223 if (task->tso == tso) {
2224 task->tso = new_tso;
2230 IF_DEBUG(sanity,checkTSO(new_tso));
2235 /* ---------------------------------------------------------------------------
2237 - usually called inside a signal handler so it mustn't do anything fancy.
2238 ------------------------------------------------------------------------ */
2241 interruptStgRts(void)
2243 sched_state = SCHED_INTERRUPTING;
2244 setContextSwitches();
2248 /* -----------------------------------------------------------------------------
2251 This function causes at least one OS thread to wake up and run the
2252 scheduler loop. It is invoked when the RTS might be deadlocked, or
2253 an external event has arrived that may need servicing (eg. a
2254 keyboard interrupt).
2256 In the single-threaded RTS we don't do anything here; we only have
2257 one thread anyway, and the event that caused us to want to wake up
2258 will have interrupted any blocking system call in progress anyway.
2259 -------------------------------------------------------------------------- */
2264 #if defined(THREADED_RTS)
2265 // This forces the IO Manager thread to wakeup, which will
2266 // in turn ensure that some OS thread wakes up and runs the
2267 // scheduler loop, which will cause a GC and deadlock check.
2272 /* -----------------------------------------------------------------------------
2275 * Check the blackhole_queue for threads that can be woken up. We do
2276 * this periodically: before every GC, and whenever the run queue is
2279 * An elegant solution might be to just wake up all the blocked
2280 * threads with awakenBlockedQueue occasionally: they'll go back to
2281 * sleep again if the object is still a BLACKHOLE. Unfortunately this
2282 * doesn't give us a way to tell whether we've actually managed to
2283 * wake up any threads, so we would be busy-waiting.
2285 * -------------------------------------------------------------------------- */
2288 checkBlackHoles (Capability *cap)
2291 rtsBool any_woke_up = rtsFalse;
2294 // blackhole_queue is global:
2295 ASSERT_LOCK_HELD(&sched_mutex);
2297 debugTrace(DEBUG_sched, "checking threads blocked on black holes");
2299 // ASSUMES: sched_mutex
2300 prev = &blackhole_queue;
2301 t = blackhole_queue;
2302 while (t != END_TSO_QUEUE) {
2303 ASSERT(t->why_blocked == BlockedOnBlackHole);
2304 type = get_itbl(UNTAG_CLOSURE(t->block_info.closure))->type;
2305 if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
2306 IF_DEBUG(sanity,checkTSO(t));
2307 t = unblockOne(cap, t);
2309 any_woke_up = rtsTrue;
2319 /* -----------------------------------------------------------------------------
2322 This is used for interruption (^C) and forking, and corresponds to
2323 raising an exception but without letting the thread catch the
2325 -------------------------------------------------------------------------- */
2328 deleteThread (Capability *cap, StgTSO *tso)
2330 // NOTE: must only be called on a TSO that we have exclusive
2331 // access to, because we will call throwToSingleThreaded() below.
2332 // The TSO must be on the run queue of the Capability we own, or
2333 // we must own all Capabilities.
2335 if (tso->why_blocked != BlockedOnCCall &&
2336 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2337 throwToSingleThreaded(cap,tso,NULL);
2341 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2343 deleteThread_(Capability *cap, StgTSO *tso)
2344 { // for forkProcess only:
2345 // like deleteThread(), but we delete threads in foreign calls, too.
2347 if (tso->why_blocked == BlockedOnCCall ||
2348 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2349 unblockOne(cap,tso);
2350 tso->what_next = ThreadKilled;
2352 deleteThread(cap,tso);
2357 /* -----------------------------------------------------------------------------
2358 raiseExceptionHelper
2360 This function is called by the raise# primitve, just so that we can
2361 move some of the tricky bits of raising an exception from C-- into
2362 C. Who knows, it might be a useful re-useable thing here too.
2363 -------------------------------------------------------------------------- */
2366 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2368 Capability *cap = regTableToCapability(reg);
2369 StgThunk *raise_closure = NULL;
2371 StgRetInfoTable *info;
2373 // This closure represents the expression 'raise# E' where E
2374 // is the exception raise. It is used to overwrite all the
2375 // thunks which are currently under evaluataion.
2378 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2379 // LDV profiling: stg_raise_info has THUNK as its closure
2380 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2381 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2382 // 1 does not cause any problem unless profiling is performed.
2383 // However, when LDV profiling goes on, we need to linearly scan
2384 // small object pool, where raise_closure is stored, so we should
2385 // use MIN_UPD_SIZE.
2387 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2388 // sizeofW(StgClosure)+1);
2392 // Walk up the stack, looking for the catch frame. On the way,
2393 // we update any closures pointed to from update frames with the
2394 // raise closure that we just built.
2398 info = get_ret_itbl((StgClosure *)p);
2399 next = p + stack_frame_sizeW((StgClosure *)p);
2400 switch (info->i.type) {
2403 // Only create raise_closure if we need to.
2404 if (raise_closure == NULL) {
2406 (StgThunk *)allocateLocal(cap,sizeofW(StgThunk)+1);
2407 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2408 raise_closure->payload[0] = exception;
2410 UPD_IND(((StgUpdateFrame *)p)->updatee,(StgClosure *)raise_closure);
2414 case ATOMICALLY_FRAME:
2415 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2417 return ATOMICALLY_FRAME;
2423 case CATCH_STM_FRAME:
2424 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2426 return CATCH_STM_FRAME;
2432 case CATCH_RETRY_FRAME:
2441 /* -----------------------------------------------------------------------------
2442 findRetryFrameHelper
2444 This function is called by the retry# primitive. It traverses the stack
2445 leaving tso->sp referring to the frame which should handle the retry.
2447 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2448 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2450 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2451 create) because retries are not considered to be exceptions, despite the
2452 similar implementation.
2454 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2455 not be created within memory transactions.
2456 -------------------------------------------------------------------------- */
2459 findRetryFrameHelper (StgTSO *tso)
2462 StgRetInfoTable *info;
2466 info = get_ret_itbl((StgClosure *)p);
2467 next = p + stack_frame_sizeW((StgClosure *)p);
2468 switch (info->i.type) {
2470 case ATOMICALLY_FRAME:
2471 debugTrace(DEBUG_stm,
2472 "found ATOMICALLY_FRAME at %p during retry", p);
2474 return ATOMICALLY_FRAME;
2476 case CATCH_RETRY_FRAME:
2477 debugTrace(DEBUG_stm,
2478 "found CATCH_RETRY_FRAME at %p during retrry", p);
2480 return CATCH_RETRY_FRAME;
2482 case CATCH_STM_FRAME: {
2483 StgTRecHeader *trec = tso -> trec;
2484 StgTRecHeader *outer = stmGetEnclosingTRec(trec);
2485 debugTrace(DEBUG_stm,
2486 "found CATCH_STM_FRAME at %p during retry", p);
2487 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2488 stmAbortTransaction(tso -> cap, trec);
2489 stmFreeAbortedTRec(tso -> cap, trec);
2490 tso -> trec = outer;
2497 ASSERT(info->i.type != CATCH_FRAME);
2498 ASSERT(info->i.type != STOP_FRAME);
2505 /* -----------------------------------------------------------------------------
2506 resurrectThreads is called after garbage collection on the list of
2507 threads found to be garbage. Each of these threads will be woken
2508 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2509 on an MVar, or NonTermination if the thread was blocked on a Black
2512 Locks: assumes we hold *all* the capabilities.
2513 -------------------------------------------------------------------------- */
2516 resurrectThreads (StgTSO *threads)
2522 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2523 next = tso->global_link;
2525 step = Bdescr((P_)tso)->step;
2526 tso->global_link = step->threads;
2527 step->threads = tso;
2529 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2531 // Wake up the thread on the Capability it was last on
2534 switch (tso->why_blocked) {
2536 case BlockedOnException:
2537 /* Called by GC - sched_mutex lock is currently held. */
2538 throwToSingleThreaded(cap, tso,
2539 (StgClosure *)blockedOnDeadMVar_closure);
2541 case BlockedOnBlackHole:
2542 throwToSingleThreaded(cap, tso,
2543 (StgClosure *)nonTermination_closure);
2546 throwToSingleThreaded(cap, tso,
2547 (StgClosure *)blockedIndefinitely_closure);
2550 /* This might happen if the thread was blocked on a black hole
2551 * belonging to a thread that we've just woken up (raiseAsync
2552 * can wake up threads, remember...).
2556 barf("resurrectThreads: thread blocked in a strange way");
2561 /* -----------------------------------------------------------------------------
2562 performPendingThrowTos is called after garbage collection, and
2563 passed a list of threads that were found to have pending throwTos
2564 (tso->blocked_exceptions was not empty), and were blocked.
2565 Normally this doesn't happen, because we would deliver the
2566 exception directly if the target thread is blocked, but there are
2567 small windows where it might occur on a multiprocessor (see
2570 NB. we must be holding all the capabilities at this point, just
2571 like resurrectThreads().
2572 -------------------------------------------------------------------------- */
2575 performPendingThrowTos (StgTSO *threads)
2581 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2582 next = tso->global_link;
2584 step = Bdescr((P_)tso)->step;
2585 tso->global_link = step->threads;
2586 step->threads = tso;
2588 debugTrace(DEBUG_sched, "performing blocked throwTo to thread %lu", (unsigned long)tso->id);
2591 maybePerformBlockedException(cap, tso);