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 static void scheduleStartSignalHandlers (Capability *cap);
141 static void scheduleCheckBlockedThreads (Capability *cap);
142 static void scheduleCheckWakeupThreads(Capability *cap USED_IF_NOT_THREADS);
143 static void scheduleCheckBlackHoles (Capability *cap);
144 static void scheduleDetectDeadlock (Capability *cap, Task *task);
145 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
146 static void schedulePushWork(Capability *cap, Task *task);
147 static rtsBool scheduleGetRemoteWork(Capability *cap);
148 #if defined(PARALLEL_HASKELL)
149 static void scheduleSendPendingMessages(void);
151 static void scheduleActivateSpark(Capability *cap);
153 static void schedulePostRunThread(Capability *cap, 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);
294 /* inside yieldCapability, attempts to steal work from other
295 capabilities, unless the capability has own work.
301 /* THIS WAS THE PLACE FOR THREADED_RTS::schedulePushWork(cap,task) */
303 // Check whether we have re-entered the RTS from Haskell without
304 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
306 if (cap->in_haskell) {
307 errorBelch("schedule: re-entered unsafely.\n"
308 " Perhaps a 'foreign import unsafe' should be 'safe'?");
309 stg_exit(EXIT_FAILURE);
312 // The interruption / shutdown sequence.
314 // In order to cleanly shut down the runtime, we want to:
315 // * make sure that all main threads return to their callers
316 // with the state 'Interrupted'.
317 // * clean up all OS threads assocated with the runtime
318 // * free all memory etc.
320 // So the sequence for ^C goes like this:
322 // * ^C handler sets sched_state := SCHED_INTERRUPTING and
323 // arranges for some Capability to wake up
325 // * all threads in the system are halted, and the zombies are
326 // placed on the run queue for cleaning up. We acquire all
327 // the capabilities in order to delete the threads, this is
328 // done by scheduleDoGC() for convenience (because GC already
329 // needs to acquire all the capabilities). We can't kill
330 // threads involved in foreign calls.
332 // * somebody calls shutdownHaskell(), which calls exitScheduler()
334 // * sched_state := SCHED_SHUTTING_DOWN
336 // * all workers exit when the run queue on their capability
337 // drains. All main threads will also exit when their TSO
338 // reaches the head of the run queue and they can return.
340 // * eventually all Capabilities will shut down, and the RTS can
343 // * We might be left with threads blocked in foreign calls,
344 // we should really attempt to kill these somehow (TODO);
346 switch (sched_state) {
349 case SCHED_INTERRUPTING:
350 debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
351 #if defined(THREADED_RTS)
352 discardSparksCap(cap);
354 /* scheduleDoGC() deletes all the threads */
355 cap = scheduleDoGC(cap,task,rtsFalse);
357 case SCHED_SHUTTING_DOWN:
358 debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
359 // If we are a worker, just exit. If we're a bound thread
360 // then we will exit below when we've removed our TSO from
362 if (task->tso == NULL && emptyRunQueue(cap)) {
367 barf("sched_state: %d", sched_state);
370 /* this was the place to activate a spark, now below... */
372 scheduleStartSignalHandlers(cap);
374 // Only check the black holes here if we've nothing else to do.
375 // During normal execution, the black hole list only gets checked
376 // at GC time, to avoid repeatedly traversing this possibly long
377 // list each time around the scheduler.
378 if (emptyRunQueue(cap)) { scheduleCheckBlackHoles(cap); }
380 scheduleCheckWakeupThreads(cap);
382 scheduleCheckBlockedThreads(cap);
384 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
385 /* work distribution in multithreaded and parallel systems
387 REMARK: IMHO best location for work-stealing as well.
388 tests above might yield some new jobs, so no need to steal a
389 spark in some cases. I believe the yieldCapability.. above
390 should be moved here.
393 #if defined(PARALLEL_HASKELL)
394 /* if messages have been buffered... a NOOP in THREADED_RTS */
395 scheduleSendPendingMessages();
398 /* If the run queue is empty,...*/
399 if (emptyRunQueue(cap)) {
400 /* ...take one of our own sparks and turn it into a thread */
401 scheduleActivateSpark(cap);
403 /* if this did not work, try to steal a spark from someone else */
404 if (emptyRunQueue(cap)) {
405 #if defined(PARALLEL_HASKELL)
406 receivedFinish = scheduleGetRemoteWork(cap);
407 continue; // a new round, (hopefully) with new work
409 in GUM, this a) sends out a FISH and returns IF no fish is
411 b) (blocking) awaits and receives messages
413 in Eden, this is only the blocking receive, as b) in GUM.
415 in Threaded-RTS, this does plain nothing. Stealing routine
416 is inside Capability.c and called from
417 yieldCapability() at the very beginning, see REMARK.
421 } else { /* i.e. run queue was (initially) not empty */
422 schedulePushWork(cap,task);
423 /* work pushing, currently relevant only for THREADED_RTS:
424 (pushes threads, wakes up idle capabilities for stealing) */
427 #if defined(PARALLEL_HASKELL)
428 /* since we perform a blocking receive and continue otherwise,
429 either we never reach here or we definitely have work! */
430 // from here: non-empty run queue
431 ASSERT(!emptyRunQueue(cap));
433 if (PacketsWaiting()) { /* now process incoming messages, if any
436 CAUTION: scheduleGetRemoteWork called
437 above, waits for messages as well! */
438 processMessages(cap, &receivedFinish);
440 #endif // PARALLEL_HASKELL: non-empty run queue!
442 #endif /* THREADED_RTS || PARALLEL_HASKELL */
444 scheduleDetectDeadlock(cap,task);
445 #if defined(THREADED_RTS)
446 cap = task->cap; // reload cap, it might have changed
449 // Normally, the only way we can get here with no threads to
450 // run is if a keyboard interrupt received during
451 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
452 // Additionally, it is not fatal for the
453 // threaded RTS to reach here with no threads to run.
455 // win32: might be here due to awaitEvent() being abandoned
456 // as a result of a console event having been delivered.
457 if ( emptyRunQueue(cap) ) {
458 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
459 ASSERT(sched_state >= SCHED_INTERRUPTING);
461 continue; // nothing to do
465 // Get a thread to run
467 t = popRunQueue(cap);
469 // Sanity check the thread we're about to run. This can be
470 // expensive if there is lots of thread switching going on...
471 IF_DEBUG(sanity,checkTSO(t));
473 #if defined(THREADED_RTS)
474 // Check whether we can run this thread in the current task.
475 // If not, we have to pass our capability to the right task.
477 Task *bound = t->bound;
481 debugTrace(DEBUG_sched,
482 "### Running thread %lu in bound thread", (unsigned long)t->id);
483 // yes, the Haskell thread is bound to the current native thread
485 debugTrace(DEBUG_sched,
486 "### thread %lu bound to another OS thread", (unsigned long)t->id);
487 // no, bound to a different Haskell thread: pass to that thread
488 pushOnRunQueue(cap,t);
492 // The thread we want to run is unbound.
494 debugTrace(DEBUG_sched,
495 "### this OS thread cannot run thread %lu", (unsigned long)t->id);
496 // no, the current native thread is bound to a different
497 // Haskell thread, so pass it to any worker thread
498 pushOnRunQueue(cap,t);
505 /* context switches are initiated by the timer signal, unless
506 * the user specified "context switch as often as possible", with
509 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
510 && !emptyThreadQueues(cap)) {
511 cap->context_switch = 1;
516 // CurrentTSO is the thread to run. t might be different if we
517 // loop back to run_thread, so make sure to set CurrentTSO after
519 cap->r.rCurrentTSO = t;
521 debugTrace(DEBUG_sched, "-->> running thread %ld %s ...",
522 (long)t->id, whatNext_strs[t->what_next]);
524 startHeapProfTimer();
526 // Check for exceptions blocked on this thread
527 maybePerformBlockedException (cap, t);
529 // ----------------------------------------------------------------------
530 // Run the current thread
532 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
533 ASSERT(t->cap == cap);
535 prev_what_next = t->what_next;
537 errno = t->saved_errno;
539 SetLastError(t->saved_winerror);
542 cap->in_haskell = rtsTrue;
546 #if defined(THREADED_RTS)
547 if (recent_activity == ACTIVITY_DONE_GC) {
548 // ACTIVITY_DONE_GC means we turned off the timer signal to
549 // conserve power (see #1623). Re-enable it here.
551 prev = xchg((P_)&recent_activity, ACTIVITY_YES);
552 if (prev == ACTIVITY_DONE_GC) {
556 recent_activity = ACTIVITY_YES;
560 switch (prev_what_next) {
564 /* Thread already finished, return to scheduler. */
565 ret = ThreadFinished;
571 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
572 cap = regTableToCapability(r);
577 case ThreadInterpret:
578 cap = interpretBCO(cap);
583 barf("schedule: invalid what_next field");
586 cap->in_haskell = rtsFalse;
588 // The TSO might have moved, eg. if it re-entered the RTS and a GC
589 // happened. So find the new location:
590 t = cap->r.rCurrentTSO;
592 // We have run some Haskell code: there might be blackhole-blocked
593 // threads to wake up now.
594 // Lock-free test here should be ok, we're just setting a flag.
595 if ( blackhole_queue != END_TSO_QUEUE ) {
596 blackholes_need_checking = rtsTrue;
599 // And save the current errno in this thread.
600 // XXX: possibly bogus for SMP because this thread might already
601 // be running again, see code below.
602 t->saved_errno = errno;
604 // Similarly for Windows error code
605 t->saved_winerror = GetLastError();
608 #if defined(THREADED_RTS)
609 // If ret is ThreadBlocked, and this Task is bound to the TSO that
610 // blocked, we are in limbo - the TSO is now owned by whatever it
611 // is blocked on, and may in fact already have been woken up,
612 // perhaps even on a different Capability. It may be the case
613 // that task->cap != cap. We better yield this Capability
614 // immediately and return to normaility.
615 if (ret == ThreadBlocked) {
616 debugTrace(DEBUG_sched,
617 "--<< thread %lu (%s) stopped: blocked",
618 (unsigned long)t->id, whatNext_strs[t->what_next]);
623 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
624 ASSERT(t->cap == cap);
626 // ----------------------------------------------------------------------
628 // Costs for the scheduler are assigned to CCS_SYSTEM
630 #if defined(PROFILING)
634 schedulePostRunThread(cap,t);
636 t = threadStackUnderflow(task,t);
638 ready_to_gc = rtsFalse;
642 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
646 scheduleHandleStackOverflow(cap,task,t);
650 if (scheduleHandleYield(cap, t, prev_what_next)) {
651 // shortcut for switching between compiler/interpreter:
657 scheduleHandleThreadBlocked(t);
661 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
662 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
666 barf("schedule: invalid thread return code %d", (int)ret);
669 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
670 cap = scheduleDoGC(cap,task,rtsFalse);
672 } /* end of while() */
675 /* ----------------------------------------------------------------------------
676 * Setting up the scheduler loop
677 * ------------------------------------------------------------------------- */
680 schedulePreLoop(void)
682 // initialisation for scheduler - what cannot go into initScheduler()
685 /* -----------------------------------------------------------------------------
688 * Push work to other Capabilities if we have some.
689 * -------------------------------------------------------------------------- */
691 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
693 schedulePushWork(Capability *cap USED_IF_THREADS,
694 Task *task USED_IF_THREADS)
696 /* following code not for PARALLEL_HASKELL. I kept the call general,
697 future GUM versions might use pushing in a distributed setup */
698 #if defined(THREADED_RTS)
700 Capability *free_caps[n_capabilities], *cap0;
703 // migration can be turned off with +RTS -qg
704 if (!RtsFlags.ParFlags.migrate) return;
706 // Check whether we have more threads on our run queue, or sparks
707 // in our pool, that we could hand to another Capability.
708 if ((emptyRunQueue(cap) || cap->run_queue_hd->_link == END_TSO_QUEUE)
709 && sparkPoolSizeCap(cap) < 2) {
713 // First grab as many free Capabilities as we can.
714 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
715 cap0 = &capabilities[i];
716 if (cap != cap0 && tryGrabCapability(cap0,task)) {
717 if (!emptyRunQueue(cap0) || cap->returning_tasks_hd != NULL) {
718 // it already has some work, we just grabbed it at
719 // the wrong moment. Or maybe it's deadlocked!
720 releaseCapability(cap0);
722 free_caps[n_free_caps++] = cap0;
727 // we now have n_free_caps free capabilities stashed in
728 // free_caps[]. Share our run queue equally with them. This is
729 // probably the simplest thing we could do; improvements we might
730 // want to do include:
732 // - giving high priority to moving relatively new threads, on
733 // the gournds that they haven't had time to build up a
734 // working set in the cache on this CPU/Capability.
736 // - giving low priority to moving long-lived threads
738 if (n_free_caps > 0) {
739 StgTSO *prev, *t, *next;
740 rtsBool pushed_to_all;
742 debugTrace(DEBUG_sched,
743 "cap %d: %s and %d free capabilities, sharing...",
745 (!emptyRunQueue(cap) && cap->run_queue_hd->_link != END_TSO_QUEUE)?
746 "excess threads on run queue":"sparks to share (>=2)",
750 pushed_to_all = rtsFalse;
752 if (cap->run_queue_hd != END_TSO_QUEUE) {
753 prev = cap->run_queue_hd;
755 prev->_link = END_TSO_QUEUE;
756 for (; t != END_TSO_QUEUE; t = next) {
758 t->_link = END_TSO_QUEUE;
759 if (t->what_next == ThreadRelocated
760 || t->bound == task // don't move my bound thread
761 || tsoLocked(t)) { // don't move a locked thread
762 setTSOLink(cap, prev, t);
764 } else if (i == n_free_caps) {
765 pushed_to_all = rtsTrue;
768 setTSOLink(cap, prev, t);
771 debugTrace(DEBUG_sched, "pushing thread %lu to capability %d", (unsigned long)t->id, free_caps[i]->no);
772 appendToRunQueue(free_caps[i],t);
773 if (t->bound) { t->bound->cap = free_caps[i]; }
774 t->cap = free_caps[i];
778 cap->run_queue_tl = prev;
782 /* JB I left this code in place, it would work but is not necessary */
784 // If there are some free capabilities that we didn't push any
785 // threads to, then try to push a spark to each one.
786 if (!pushed_to_all) {
788 // i is the next free capability to push to
789 for (; i < n_free_caps; i++) {
790 if (emptySparkPoolCap(free_caps[i])) {
791 spark = findSpark(cap);
793 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
794 newSpark(&(free_caps[i]->r), spark);
799 #endif /* SPARK_PUSHING */
801 // release the capabilities
802 for (i = 0; i < n_free_caps; i++) {
803 task->cap = free_caps[i];
804 releaseCapability(free_caps[i]);
806 // now wake them all up, and they might steal sparks if
807 // the did not get a thread
808 prodAllCapabilities();
810 task->cap = cap; // reset to point to our Capability.
812 #endif /* THREADED_RTS */
815 #endif /* THREADED_RTS || PARALLEL_HASKELL */
817 /* ----------------------------------------------------------------------------
818 * Start any pending signal handlers
819 * ------------------------------------------------------------------------- */
821 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
823 scheduleStartSignalHandlers(Capability *cap)
825 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
826 // safe outside the lock
827 startSignalHandlers(cap);
832 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
837 /* ----------------------------------------------------------------------------
838 * Check for blocked threads that can be woken up.
839 * ------------------------------------------------------------------------- */
842 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
844 #if !defined(THREADED_RTS)
846 // Check whether any waiting threads need to be woken up. If the
847 // run queue is empty, and there are no other tasks running, we
848 // can wait indefinitely for something to happen.
850 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
852 awaitEvent( emptyRunQueue(cap) && !blackholes_need_checking );
858 /* ----------------------------------------------------------------------------
859 * Check for threads woken up by other Capabilities
860 * ------------------------------------------------------------------------- */
863 scheduleCheckWakeupThreads(Capability *cap USED_IF_THREADS)
865 #if defined(THREADED_RTS)
866 // Any threads that were woken up by other Capabilities get
867 // appended to our run queue.
868 if (!emptyWakeupQueue(cap)) {
869 ACQUIRE_LOCK(&cap->lock);
870 if (emptyRunQueue(cap)) {
871 cap->run_queue_hd = cap->wakeup_queue_hd;
872 cap->run_queue_tl = cap->wakeup_queue_tl;
874 setTSOLink(cap, cap->run_queue_tl, cap->wakeup_queue_hd);
875 cap->run_queue_tl = cap->wakeup_queue_tl;
877 cap->wakeup_queue_hd = cap->wakeup_queue_tl = END_TSO_QUEUE;
878 RELEASE_LOCK(&cap->lock);
883 /* ----------------------------------------------------------------------------
884 * Check for threads blocked on BLACKHOLEs that can be woken up
885 * ------------------------------------------------------------------------- */
887 scheduleCheckBlackHoles (Capability *cap)
889 if ( blackholes_need_checking ) // check without the lock first
891 ACQUIRE_LOCK(&sched_mutex);
892 if ( blackholes_need_checking ) {
893 checkBlackHoles(cap);
894 blackholes_need_checking = rtsFalse;
896 RELEASE_LOCK(&sched_mutex);
900 /* ----------------------------------------------------------------------------
901 * Detect deadlock conditions and attempt to resolve them.
902 * ------------------------------------------------------------------------- */
905 scheduleDetectDeadlock (Capability *cap, Task *task)
908 #if defined(PARALLEL_HASKELL)
909 // ToDo: add deadlock detection in GUM (similar to THREADED_RTS) -- HWL
914 * Detect deadlock: when we have no threads to run, there are no
915 * threads blocked, waiting for I/O, or sleeping, and all the
916 * other tasks are waiting for work, we must have a deadlock of
919 if ( emptyThreadQueues(cap) )
921 #if defined(THREADED_RTS)
923 * In the threaded RTS, we only check for deadlock if there
924 * has been no activity in a complete timeslice. This means
925 * we won't eagerly start a full GC just because we don't have
926 * any threads to run currently.
928 if (recent_activity != ACTIVITY_INACTIVE) return;
931 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
933 // Garbage collection can release some new threads due to
934 // either (a) finalizers or (b) threads resurrected because
935 // they are unreachable and will therefore be sent an
936 // exception. Any threads thus released will be immediately
938 cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
940 recent_activity = ACTIVITY_DONE_GC;
941 // disable timer signals (see #1623)
944 if ( !emptyRunQueue(cap) ) return;
946 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
947 /* If we have user-installed signal handlers, then wait
948 * for signals to arrive rather then bombing out with a
951 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
952 debugTrace(DEBUG_sched,
953 "still deadlocked, waiting for signals...");
957 if (signals_pending()) {
958 startSignalHandlers(cap);
961 // either we have threads to run, or we were interrupted:
962 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
968 #if !defined(THREADED_RTS)
969 /* Probably a real deadlock. Send the current main thread the
970 * Deadlock exception.
973 switch (task->tso->why_blocked) {
975 case BlockedOnBlackHole:
976 case BlockedOnException:
978 throwToSingleThreaded(cap, task->tso,
979 (StgClosure *)nonTermination_closure);
982 barf("deadlock: main thread blocked in a strange way");
991 /* ----------------------------------------------------------------------------
992 * Send pending messages (PARALLEL_HASKELL only)
993 * ------------------------------------------------------------------------- */
995 #if defined(PARALLEL_HASKELL)
997 scheduleSendPendingMessages(void)
1000 # if defined(PAR) // global Mem.Mgmt., omit for now
1001 if (PendingFetches != END_BF_QUEUE) {
1006 if (RtsFlags.ParFlags.BufferTime) {
1007 // if we use message buffering, we must send away all message
1008 // packets which have become too old...
1014 /* ----------------------------------------------------------------------------
1015 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
1016 * ------------------------------------------------------------------------- */
1018 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
1020 scheduleActivateSpark(Capability *cap)
1024 /* We only want to stay here if the run queue is empty and we want some
1025 work. We try to turn a spark into a thread, and add it to the run
1026 queue, from where it will be picked up in the next iteration of the
1029 if (!emptyRunQueue(cap))
1030 /* In the threaded RTS, another task might have pushed a thread
1031 on our run queue in the meantime ? But would need a lock.. */
1034 spark = findSpark(cap); // defined in Sparks.c
1036 if (spark != NULL) {
1037 debugTrace(DEBUG_sched,
1038 "turning spark of closure %p into a thread",
1039 (StgClosure *)spark);
1040 createSparkThread(cap,spark); // defined in Sparks.c
1043 #endif // PARALLEL_HASKELL || THREADED_RTS
1045 /* ----------------------------------------------------------------------------
1046 * Get work from a remote node (PARALLEL_HASKELL only)
1047 * ------------------------------------------------------------------------- */
1049 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
1050 static rtsBool /* return value used in PARALLEL_HASKELL only */
1051 scheduleGetRemoteWork(Capability *cap)
1053 #if defined(PARALLEL_HASKELL)
1054 rtsBool receivedFinish = rtsFalse;
1056 // idle() , i.e. send all buffers, wait for work
1057 if (RtsFlags.ParFlags.BufferTime) {
1058 IF_PAR_DEBUG(verbose,
1059 debugBelch("...send all pending data,"));
1062 for (i=1; i<=nPEs; i++)
1063 sendImmediately(i); // send all messages away immediately
1067 /* this would be the place for fishing in GUM...
1069 if (no-earlier-fish-around)
1070 sendFish(choosePe());
1073 // Eden:just look for incoming messages (blocking receive)
1074 IF_PAR_DEBUG(verbose,
1075 debugBelch("...wait for incoming messages...\n"));
1076 processMessages(cap, &receivedFinish); // blocking receive...
1079 return receivedFinish;
1080 // reenter scheduling look after having received something
1082 #else /* !PARALLEL_HASKELL, i.e. THREADED_RTS */
1084 return rtsFalse; /* return value unused in THREADED_RTS */
1086 #endif /* PARALLEL_HASKELL */
1088 #endif // PARALLEL_HASKELL || THREADED_RTS
1090 /* ----------------------------------------------------------------------------
1091 * After running a thread...
1092 * ------------------------------------------------------------------------- */
1095 schedulePostRunThread (Capability *cap, StgTSO *t)
1097 // We have to be able to catch transactions that are in an
1098 // infinite loop as a result of seeing an inconsistent view of
1102 // [a,b] <- mapM readTVar [ta,tb]
1103 // when (a == b) loop
1105 // and a is never equal to b given a consistent view of memory.
1107 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1108 if (!stmValidateNestOfTransactions (t -> trec)) {
1109 debugTrace(DEBUG_sched | DEBUG_stm,
1110 "trec %p found wasting its time", t);
1112 // strip the stack back to the
1113 // ATOMICALLY_FRAME, aborting the (nested)
1114 // transaction, and saving the stack of any
1115 // partially-evaluated thunks on the heap.
1116 throwToSingleThreaded_(cap, t, NULL, rtsTrue, NULL);
1118 ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1122 /* some statistics gathering in the parallel case */
1125 /* -----------------------------------------------------------------------------
1126 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1127 * -------------------------------------------------------------------------- */
1130 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1132 // did the task ask for a large block?
1133 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1134 // if so, get one and push it on the front of the nursery.
1138 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1140 debugTrace(DEBUG_sched,
1141 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1142 (long)t->id, whatNext_strs[t->what_next], blocks);
1144 // don't do this if the nursery is (nearly) full, we'll GC first.
1145 if (cap->r.rCurrentNursery->link != NULL ||
1146 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1147 // if the nursery has only one block.
1150 bd = allocGroup( blocks );
1152 cap->r.rNursery->n_blocks += blocks;
1154 // link the new group into the list
1155 bd->link = cap->r.rCurrentNursery;
1156 bd->u.back = cap->r.rCurrentNursery->u.back;
1157 if (cap->r.rCurrentNursery->u.back != NULL) {
1158 cap->r.rCurrentNursery->u.back->link = bd;
1160 #if !defined(THREADED_RTS)
1161 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1162 g0s0 == cap->r.rNursery);
1164 cap->r.rNursery->blocks = bd;
1166 cap->r.rCurrentNursery->u.back = bd;
1168 // initialise it as a nursery block. We initialise the
1169 // step, gen_no, and flags field of *every* sub-block in
1170 // this large block, because this is easier than making
1171 // sure that we always find the block head of a large
1172 // block whenever we call Bdescr() (eg. evacuate() and
1173 // isAlive() in the GC would both have to do this, at
1177 for (x = bd; x < bd + blocks; x++) {
1178 x->step = cap->r.rNursery;
1184 // This assert can be a killer if the app is doing lots
1185 // of large block allocations.
1186 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1188 // now update the nursery to point to the new block
1189 cap->r.rCurrentNursery = bd;
1191 // we might be unlucky and have another thread get on the
1192 // run queue before us and steal the large block, but in that
1193 // case the thread will just end up requesting another large
1195 pushOnRunQueue(cap,t);
1196 return rtsFalse; /* not actually GC'ing */
1200 debugTrace(DEBUG_sched,
1201 "--<< thread %ld (%s) stopped: HeapOverflow",
1202 (long)t->id, whatNext_strs[t->what_next]);
1204 if (cap->context_switch) {
1205 // Sometimes we miss a context switch, e.g. when calling
1206 // primitives in a tight loop, MAYBE_GC() doesn't check the
1207 // context switch flag, and we end up waiting for a GC.
1208 // See #1984, and concurrent/should_run/1984
1209 cap->context_switch = 0;
1210 addToRunQueue(cap,t);
1212 pushOnRunQueue(cap,t);
1215 /* actual GC is done at the end of the while loop in schedule() */
1218 /* -----------------------------------------------------------------------------
1219 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1220 * -------------------------------------------------------------------------- */
1223 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1225 debugTrace (DEBUG_sched,
1226 "--<< thread %ld (%s) stopped, StackOverflow",
1227 (long)t->id, whatNext_strs[t->what_next]);
1229 /* just adjust the stack for this thread, then pop it back
1233 /* enlarge the stack */
1234 StgTSO *new_t = threadStackOverflow(cap, t);
1236 /* The TSO attached to this Task may have moved, so update the
1239 if (task->tso == t) {
1242 pushOnRunQueue(cap,new_t);
1246 /* -----------------------------------------------------------------------------
1247 * Handle a thread that returned to the scheduler with ThreadYielding
1248 * -------------------------------------------------------------------------- */
1251 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1253 // Reset the context switch flag. We don't do this just before
1254 // running the thread, because that would mean we would lose ticks
1255 // during GC, which can lead to unfair scheduling (a thread hogs
1256 // the CPU because the tick always arrives during GC). This way
1257 // penalises threads that do a lot of allocation, but that seems
1258 // better than the alternative.
1259 cap->context_switch = 0;
1261 /* put the thread back on the run queue. Then, if we're ready to
1262 * GC, check whether this is the last task to stop. If so, wake
1263 * up the GC thread. getThread will block during a GC until the
1267 if (t->what_next != prev_what_next) {
1268 debugTrace(DEBUG_sched,
1269 "--<< thread %ld (%s) stopped to switch evaluators",
1270 (long)t->id, whatNext_strs[t->what_next]);
1272 debugTrace(DEBUG_sched,
1273 "--<< thread %ld (%s) stopped, yielding",
1274 (long)t->id, whatNext_strs[t->what_next]);
1279 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1281 ASSERT(t->_link == END_TSO_QUEUE);
1283 // Shortcut if we're just switching evaluators: don't bother
1284 // doing stack squeezing (which can be expensive), just run the
1286 if (t->what_next != prev_what_next) {
1290 addToRunQueue(cap,t);
1295 /* -----------------------------------------------------------------------------
1296 * Handle a thread that returned to the scheduler with ThreadBlocked
1297 * -------------------------------------------------------------------------- */
1300 scheduleHandleThreadBlocked( StgTSO *t
1301 #if !defined(GRAN) && !defined(DEBUG)
1307 // We don't need to do anything. The thread is blocked, and it
1308 // has tidied up its stack and placed itself on whatever queue
1309 // it needs to be on.
1311 // ASSERT(t->why_blocked != NotBlocked);
1312 // Not true: for example,
1313 // - in THREADED_RTS, the thread may already have been woken
1314 // up by another Capability. This actually happens: try
1315 // conc023 +RTS -N2.
1316 // - the thread may have woken itself up already, because
1317 // threadPaused() might have raised a blocked throwTo
1318 // exception, see maybePerformBlockedException().
1321 if (traceClass(DEBUG_sched)) {
1322 debugTraceBegin("--<< thread %lu (%s) stopped: ",
1323 (unsigned long)t->id, whatNext_strs[t->what_next]);
1324 printThreadBlockage(t);
1330 /* -----------------------------------------------------------------------------
1331 * Handle a thread that returned to the scheduler with ThreadFinished
1332 * -------------------------------------------------------------------------- */
1335 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1337 /* Need to check whether this was a main thread, and if so,
1338 * return with the return value.
1340 * We also end up here if the thread kills itself with an
1341 * uncaught exception, see Exception.cmm.
1343 debugTrace(DEBUG_sched, "--++ thread %lu (%s) finished",
1344 (unsigned long)t->id, whatNext_strs[t->what_next]);
1347 // Check whether the thread that just completed was a bound
1348 // thread, and if so return with the result.
1350 // There is an assumption here that all thread completion goes
1351 // through this point; we need to make sure that if a thread
1352 // ends up in the ThreadKilled state, that it stays on the run
1353 // queue so it can be dealt with here.
1358 if (t->bound != task) {
1359 #if !defined(THREADED_RTS)
1360 // Must be a bound thread that is not the topmost one. Leave
1361 // it on the run queue until the stack has unwound to the
1362 // point where we can deal with this. Leaving it on the run
1363 // queue also ensures that the garbage collector knows about
1364 // this thread and its return value (it gets dropped from the
1365 // step->threads list so there's no other way to find it).
1366 appendToRunQueue(cap,t);
1369 // this cannot happen in the threaded RTS, because a
1370 // bound thread can only be run by the appropriate Task.
1371 barf("finished bound thread that isn't mine");
1375 ASSERT(task->tso == t);
1377 if (t->what_next == ThreadComplete) {
1379 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1380 *(task->ret) = (StgClosure *)task->tso->sp[1];
1382 task->stat = Success;
1385 *(task->ret) = NULL;
1387 if (sched_state >= SCHED_INTERRUPTING) {
1388 task->stat = Interrupted;
1390 task->stat = Killed;
1394 removeThreadLabel((StgWord)task->tso->id);
1396 return rtsTrue; // tells schedule() to return
1402 /* -----------------------------------------------------------------------------
1403 * Perform a heap census
1404 * -------------------------------------------------------------------------- */
1407 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1409 // When we have +RTS -i0 and we're heap profiling, do a census at
1410 // every GC. This lets us get repeatable runs for debugging.
1411 if (performHeapProfile ||
1412 (RtsFlags.ProfFlags.profileInterval==0 &&
1413 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1420 /* -----------------------------------------------------------------------------
1421 * Perform a garbage collection if necessary
1422 * -------------------------------------------------------------------------- */
1425 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1427 rtsBool heap_census;
1429 /* extern static volatile StgWord waiting_for_gc;
1430 lives inside capability.c */
1431 rtsBool was_waiting;
1436 // In order to GC, there must be no threads running Haskell code.
1437 // Therefore, the GC thread needs to hold *all* the capabilities,
1438 // and release them after the GC has completed.
1440 // This seems to be the simplest way: previous attempts involved
1441 // making all the threads with capabilities give up their
1442 // capabilities and sleep except for the *last* one, which
1443 // actually did the GC. But it's quite hard to arrange for all
1444 // the other tasks to sleep and stay asleep.
1447 /* Other capabilities are prevented from running yet more Haskell
1448 threads if waiting_for_gc is set. Tested inside
1449 yieldCapability() and releaseCapability() in Capability.c */
1451 was_waiting = cas(&waiting_for_gc, 0, 1);
1454 debugTrace(DEBUG_sched, "someone else is trying to GC...");
1455 if (cap) yieldCapability(&cap,task);
1456 } while (waiting_for_gc);
1457 return cap; // NOTE: task->cap might have changed here
1460 setContextSwitches();
1461 for (i=0; i < n_capabilities; i++) {
1462 debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1463 if (cap != &capabilities[i]) {
1464 Capability *pcap = &capabilities[i];
1465 // we better hope this task doesn't get migrated to
1466 // another Capability while we're waiting for this one.
1467 // It won't, because load balancing happens while we have
1468 // all the Capabilities, but even so it's a slightly
1469 // unsavoury invariant.
1471 waitForReturnCapability(&pcap, task);
1472 if (pcap != &capabilities[i]) {
1473 barf("scheduleDoGC: got the wrong capability");
1478 waiting_for_gc = rtsFalse;
1481 // so this happens periodically:
1482 if (cap) scheduleCheckBlackHoles(cap);
1484 IF_DEBUG(scheduler, printAllThreads());
1487 * We now have all the capabilities; if we're in an interrupting
1488 * state, then we should take the opportunity to delete all the
1489 * threads in the system.
1491 if (sched_state >= SCHED_INTERRUPTING) {
1492 deleteAllThreads(&capabilities[0]);
1493 sched_state = SCHED_SHUTTING_DOWN;
1496 heap_census = scheduleNeedHeapProfile(rtsTrue);
1498 /* everybody back, start the GC.
1499 * Could do it in this thread, or signal a condition var
1500 * to do it in another thread. Either way, we need to
1501 * broadcast on gc_pending_cond afterward.
1503 #if defined(THREADED_RTS)
1504 debugTrace(DEBUG_sched, "doing GC");
1506 GarbageCollect(force_major || heap_census);
1509 debugTrace(DEBUG_sched, "performing heap census");
1511 performHeapProfile = rtsFalse;
1516 Once we are all together... this would be the place to balance all
1517 spark pools. No concurrent stealing or adding of new sparks can
1518 occur. Should be defined in Sparks.c. */
1519 balanceSparkPoolsCaps(n_capabilities, capabilities);
1522 #if defined(THREADED_RTS)
1523 // release our stash of capabilities.
1524 for (i = 0; i < n_capabilities; i++) {
1525 if (cap != &capabilities[i]) {
1526 task->cap = &capabilities[i];
1527 releaseCapability(&capabilities[i]);
1540 /* ---------------------------------------------------------------------------
1541 * Singleton fork(). Do not copy any running threads.
1542 * ------------------------------------------------------------------------- */
1545 forkProcess(HsStablePtr *entry
1546 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1551 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1558 #if defined(THREADED_RTS)
1559 if (RtsFlags.ParFlags.nNodes > 1) {
1560 errorBelch("forking not supported with +RTS -N<n> greater than 1");
1561 stg_exit(EXIT_FAILURE);
1565 debugTrace(DEBUG_sched, "forking!");
1567 // ToDo: for SMP, we should probably acquire *all* the capabilities
1570 // no funny business: hold locks while we fork, otherwise if some
1571 // other thread is holding a lock when the fork happens, the data
1572 // structure protected by the lock will forever be in an
1573 // inconsistent state in the child. See also #1391.
1574 ACQUIRE_LOCK(&sched_mutex);
1575 ACQUIRE_LOCK(&cap->lock);
1576 ACQUIRE_LOCK(&cap->running_task->lock);
1580 if (pid) { // parent
1582 RELEASE_LOCK(&sched_mutex);
1583 RELEASE_LOCK(&cap->lock);
1584 RELEASE_LOCK(&cap->running_task->lock);
1586 // just return the pid
1592 #if defined(THREADED_RTS)
1593 initMutex(&sched_mutex);
1594 initMutex(&cap->lock);
1595 initMutex(&cap->running_task->lock);
1598 // Now, all OS threads except the thread that forked are
1599 // stopped. We need to stop all Haskell threads, including
1600 // those involved in foreign calls. Also we need to delete
1601 // all Tasks, because they correspond to OS threads that are
1604 for (s = 0; s < total_steps; s++) {
1605 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1606 if (t->what_next == ThreadRelocated) {
1609 next = t->global_link;
1610 // don't allow threads to catch the ThreadKilled
1611 // exception, but we do want to raiseAsync() because these
1612 // threads may be evaluating thunks that we need later.
1613 deleteThread_(cap,t);
1618 // Empty the run queue. It seems tempting to let all the
1619 // killed threads stay on the run queue as zombies to be
1620 // cleaned up later, but some of them correspond to bound
1621 // threads for which the corresponding Task does not exist.
1622 cap->run_queue_hd = END_TSO_QUEUE;
1623 cap->run_queue_tl = END_TSO_QUEUE;
1625 // Any suspended C-calling Tasks are no more, their OS threads
1627 cap->suspended_ccalling_tasks = NULL;
1629 // Empty the threads lists. Otherwise, the garbage
1630 // collector may attempt to resurrect some of these threads.
1631 for (s = 0; s < total_steps; s++) {
1632 all_steps[s].threads = END_TSO_QUEUE;
1635 // Wipe the task list, except the current Task.
1636 ACQUIRE_LOCK(&sched_mutex);
1637 for (task = all_tasks; task != NULL; task=task->all_link) {
1638 if (task != cap->running_task) {
1639 #if defined(THREADED_RTS)
1640 initMutex(&task->lock); // see #1391
1645 RELEASE_LOCK(&sched_mutex);
1647 #if defined(THREADED_RTS)
1648 // Wipe our spare workers list, they no longer exist. New
1649 // workers will be created if necessary.
1650 cap->spare_workers = NULL;
1651 cap->returning_tasks_hd = NULL;
1652 cap->returning_tasks_tl = NULL;
1655 // On Unix, all timers are reset in the child, so we need to start
1660 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1661 rts_checkSchedStatus("forkProcess",cap);
1664 hs_exit(); // clean up and exit
1665 stg_exit(EXIT_SUCCESS);
1667 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1668 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1673 /* ---------------------------------------------------------------------------
1674 * Delete all the threads in the system
1675 * ------------------------------------------------------------------------- */
1678 deleteAllThreads ( Capability *cap )
1680 // NOTE: only safe to call if we own all capabilities.
1685 debugTrace(DEBUG_sched,"deleting all threads");
1686 for (s = 0; s < total_steps; s++) {
1687 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1688 if (t->what_next == ThreadRelocated) {
1691 next = t->global_link;
1692 deleteThread(cap,t);
1697 // The run queue now contains a bunch of ThreadKilled threads. We
1698 // must not throw these away: the main thread(s) will be in there
1699 // somewhere, and the main scheduler loop has to deal with it.
1700 // Also, the run queue is the only thing keeping these threads from
1701 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1703 #if !defined(THREADED_RTS)
1704 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1705 ASSERT(sleeping_queue == END_TSO_QUEUE);
1709 /* -----------------------------------------------------------------------------
1710 Managing the suspended_ccalling_tasks list.
1711 Locks required: sched_mutex
1712 -------------------------------------------------------------------------- */
1715 suspendTask (Capability *cap, Task *task)
1717 ASSERT(task->next == NULL && task->prev == NULL);
1718 task->next = cap->suspended_ccalling_tasks;
1720 if (cap->suspended_ccalling_tasks) {
1721 cap->suspended_ccalling_tasks->prev = task;
1723 cap->suspended_ccalling_tasks = task;
1727 recoverSuspendedTask (Capability *cap, Task *task)
1730 task->prev->next = task->next;
1732 ASSERT(cap->suspended_ccalling_tasks == task);
1733 cap->suspended_ccalling_tasks = task->next;
1736 task->next->prev = task->prev;
1738 task->next = task->prev = NULL;
1741 /* ---------------------------------------------------------------------------
1742 * Suspending & resuming Haskell threads.
1744 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1745 * its capability before calling the C function. This allows another
1746 * task to pick up the capability and carry on running Haskell
1747 * threads. It also means that if the C call blocks, it won't lock
1750 * The Haskell thread making the C call is put to sleep for the
1751 * duration of the call, on the susepended_ccalling_threads queue. We
1752 * give out a token to the task, which it can use to resume the thread
1753 * on return from the C function.
1754 * ------------------------------------------------------------------------- */
1757 suspendThread (StgRegTable *reg)
1764 StgWord32 saved_winerror;
1767 saved_errno = errno;
1769 saved_winerror = GetLastError();
1772 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1774 cap = regTableToCapability(reg);
1776 task = cap->running_task;
1777 tso = cap->r.rCurrentTSO;
1779 debugTrace(DEBUG_sched,
1780 "thread %lu did a safe foreign call",
1781 (unsigned long)cap->r.rCurrentTSO->id);
1783 // XXX this might not be necessary --SDM
1784 tso->what_next = ThreadRunGHC;
1786 threadPaused(cap,tso);
1788 if ((tso->flags & TSO_BLOCKEX) == 0) {
1789 tso->why_blocked = BlockedOnCCall;
1790 tso->flags |= TSO_BLOCKEX;
1791 tso->flags &= ~TSO_INTERRUPTIBLE;
1793 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1796 // Hand back capability
1797 task->suspended_tso = tso;
1799 ACQUIRE_LOCK(&cap->lock);
1801 suspendTask(cap,task);
1802 cap->in_haskell = rtsFalse;
1803 releaseCapability_(cap);
1805 RELEASE_LOCK(&cap->lock);
1807 #if defined(THREADED_RTS)
1808 /* Preparing to leave the RTS, so ensure there's a native thread/task
1809 waiting to take over.
1811 debugTrace(DEBUG_sched, "thread %lu: leaving RTS", (unsigned long)tso->id);
1814 errno = saved_errno;
1816 SetLastError(saved_winerror);
1822 resumeThread (void *task_)
1829 StgWord32 saved_winerror;
1832 saved_errno = errno;
1834 saved_winerror = GetLastError();
1838 // Wait for permission to re-enter the RTS with the result.
1839 waitForReturnCapability(&cap,task);
1840 // we might be on a different capability now... but if so, our
1841 // entry on the suspended_ccalling_tasks list will also have been
1844 // Remove the thread from the suspended list
1845 recoverSuspendedTask(cap,task);
1847 tso = task->suspended_tso;
1848 task->suspended_tso = NULL;
1849 tso->_link = END_TSO_QUEUE; // no write barrier reqd
1850 debugTrace(DEBUG_sched, "thread %lu: re-entering RTS", (unsigned long)tso->id);
1852 if (tso->why_blocked == BlockedOnCCall) {
1853 awakenBlockedExceptionQueue(cap,tso);
1854 tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
1857 /* Reset blocking status */
1858 tso->why_blocked = NotBlocked;
1860 cap->r.rCurrentTSO = tso;
1861 cap->in_haskell = rtsTrue;
1862 errno = saved_errno;
1864 SetLastError(saved_winerror);
1867 /* We might have GC'd, mark the TSO dirty again */
1870 IF_DEBUG(sanity, checkTSO(tso));
1875 /* ---------------------------------------------------------------------------
1878 * scheduleThread puts a thread on the end of the runnable queue.
1879 * This will usually be done immediately after a thread is created.
1880 * The caller of scheduleThread must create the thread using e.g.
1881 * createThread and push an appropriate closure
1882 * on this thread's stack before the scheduler is invoked.
1883 * ------------------------------------------------------------------------ */
1886 scheduleThread(Capability *cap, StgTSO *tso)
1888 // The thread goes at the *end* of the run-queue, to avoid possible
1889 // starvation of any threads already on the queue.
1890 appendToRunQueue(cap,tso);
1894 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
1896 #if defined(THREADED_RTS)
1897 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
1898 // move this thread from now on.
1899 cpu %= RtsFlags.ParFlags.nNodes;
1900 if (cpu == cap->no) {
1901 appendToRunQueue(cap,tso);
1903 wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
1906 appendToRunQueue(cap,tso);
1911 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
1915 // We already created/initialised the Task
1916 task = cap->running_task;
1918 // This TSO is now a bound thread; make the Task and TSO
1919 // point to each other.
1925 task->stat = NoStatus;
1927 appendToRunQueue(cap,tso);
1929 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)tso->id);
1931 cap = schedule(cap,task);
1933 ASSERT(task->stat != NoStatus);
1934 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
1936 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)task->tso->id);
1940 /* ----------------------------------------------------------------------------
1942 * ------------------------------------------------------------------------- */
1944 #if defined(THREADED_RTS)
1945 void OSThreadProcAttr
1946 workerStart(Task *task)
1950 // See startWorkerTask().
1951 ACQUIRE_LOCK(&task->lock);
1953 RELEASE_LOCK(&task->lock);
1955 // set the thread-local pointer to the Task:
1958 // schedule() runs without a lock.
1959 cap = schedule(cap,task);
1961 // On exit from schedule(), we have a Capability.
1962 releaseCapability(cap);
1963 workerTaskStop(task);
1967 /* ---------------------------------------------------------------------------
1970 * Initialise the scheduler. This resets all the queues - if the
1971 * queues contained any threads, they'll be garbage collected at the
1974 * ------------------------------------------------------------------------ */
1979 #if !defined(THREADED_RTS)
1980 blocked_queue_hd = END_TSO_QUEUE;
1981 blocked_queue_tl = END_TSO_QUEUE;
1982 sleeping_queue = END_TSO_QUEUE;
1985 blackhole_queue = END_TSO_QUEUE;
1987 sched_state = SCHED_RUNNING;
1988 recent_activity = ACTIVITY_YES;
1990 #if defined(THREADED_RTS)
1991 /* Initialise the mutex and condition variables used by
1993 initMutex(&sched_mutex);
1996 ACQUIRE_LOCK(&sched_mutex);
1998 /* A capability holds the state a native thread needs in
1999 * order to execute STG code. At least one capability is
2000 * floating around (only THREADED_RTS builds have more than one).
2006 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
2010 #if defined(THREADED_RTS)
2012 * Eagerly start one worker to run each Capability, except for
2013 * Capability 0. The idea is that we're probably going to start a
2014 * bound thread on Capability 0 pretty soon, so we don't want a
2015 * worker task hogging it.
2020 for (i = 1; i < n_capabilities; i++) {
2021 cap = &capabilities[i];
2022 ACQUIRE_LOCK(&cap->lock);
2023 startWorkerTask(cap, workerStart);
2024 RELEASE_LOCK(&cap->lock);
2029 trace(TRACE_sched, "start: %d capabilities", n_capabilities);
2031 RELEASE_LOCK(&sched_mutex);
2036 rtsBool wait_foreign
2037 #if !defined(THREADED_RTS)
2038 __attribute__((unused))
2041 /* see Capability.c, shutdownCapability() */
2045 #if defined(THREADED_RTS)
2046 ACQUIRE_LOCK(&sched_mutex);
2047 task = newBoundTask();
2048 RELEASE_LOCK(&sched_mutex);
2051 // If we haven't killed all the threads yet, do it now.
2052 if (sched_state < SCHED_SHUTTING_DOWN) {
2053 sched_state = SCHED_INTERRUPTING;
2054 scheduleDoGC(NULL,task,rtsFalse);
2056 sched_state = SCHED_SHUTTING_DOWN;
2058 #if defined(THREADED_RTS)
2062 for (i = 0; i < n_capabilities; i++) {
2063 shutdownCapability(&capabilities[i], task, wait_foreign);
2065 boundTaskExiting(task);
2069 freeCapability(&MainCapability);
2074 freeScheduler( void )
2077 if (n_capabilities != 1) {
2078 stgFree(capabilities);
2080 #if defined(THREADED_RTS)
2081 closeMutex(&sched_mutex);
2085 /* -----------------------------------------------------------------------------
2088 This is the interface to the garbage collector from Haskell land.
2089 We provide this so that external C code can allocate and garbage
2090 collect when called from Haskell via _ccall_GC.
2091 -------------------------------------------------------------------------- */
2094 performGC_(rtsBool force_major)
2097 // We must grab a new Task here, because the existing Task may be
2098 // associated with a particular Capability, and chained onto the
2099 // suspended_ccalling_tasks queue.
2100 ACQUIRE_LOCK(&sched_mutex);
2101 task = newBoundTask();
2102 RELEASE_LOCK(&sched_mutex);
2103 scheduleDoGC(NULL,task,force_major);
2104 boundTaskExiting(task);
2110 performGC_(rtsFalse);
2114 performMajorGC(void)
2116 performGC_(rtsTrue);
2119 /* -----------------------------------------------------------------------------
2122 If the thread has reached its maximum stack size, then raise the
2123 StackOverflow exception in the offending thread. Otherwise
2124 relocate the TSO into a larger chunk of memory and adjust its stack
2126 -------------------------------------------------------------------------- */
2129 threadStackOverflow(Capability *cap, StgTSO *tso)
2131 nat new_stack_size, stack_words;
2136 IF_DEBUG(sanity,checkTSO(tso));
2138 // don't allow throwTo() to modify the blocked_exceptions queue
2139 // while we are moving the TSO:
2140 lockClosure((StgClosure *)tso);
2142 if (tso->stack_size >= tso->max_stack_size && !(tso->flags & TSO_BLOCKEX)) {
2143 // NB. never raise a StackOverflow exception if the thread is
2144 // inside Control.Exceptino.block. It is impractical to protect
2145 // against stack overflow exceptions, since virtually anything
2146 // can raise one (even 'catch'), so this is the only sensible
2147 // thing to do here. See bug #767.
2149 debugTrace(DEBUG_gc,
2150 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2151 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2153 /* If we're debugging, just print out the top of the stack */
2154 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2157 // Send this thread the StackOverflow exception
2159 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2163 /* Try to double the current stack size. If that takes us over the
2164 * maximum stack size for this thread, then use the maximum instead
2165 * (that is, unless we're already at or over the max size and we
2166 * can't raise the StackOverflow exception (see above), in which
2167 * case just double the size). Finally round up so the TSO ends up as
2168 * a whole number of blocks.
2170 if (tso->stack_size >= tso->max_stack_size) {
2171 new_stack_size = tso->stack_size * 2;
2173 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2175 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2176 TSO_STRUCT_SIZE)/sizeof(W_);
2177 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2178 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2180 debugTrace(DEBUG_sched,
2181 "increasing stack size from %ld words to %d.",
2182 (long)tso->stack_size, new_stack_size);
2184 dest = (StgTSO *)allocateLocal(cap,new_tso_size);
2185 TICK_ALLOC_TSO(new_stack_size,0);
2187 /* copy the TSO block and the old stack into the new area */
2188 memcpy(dest,tso,TSO_STRUCT_SIZE);
2189 stack_words = tso->stack + tso->stack_size - tso->sp;
2190 new_sp = (P_)dest + new_tso_size - stack_words;
2191 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2193 /* relocate the stack pointers... */
2195 dest->stack_size = new_stack_size;
2197 /* Mark the old TSO as relocated. We have to check for relocated
2198 * TSOs in the garbage collector and any primops that deal with TSOs.
2200 * It's important to set the sp value to just beyond the end
2201 * of the stack, so we don't attempt to scavenge any part of the
2204 tso->what_next = ThreadRelocated;
2205 setTSOLink(cap,tso,dest);
2206 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2207 tso->why_blocked = NotBlocked;
2209 IF_PAR_DEBUG(verbose,
2210 debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2211 tso->id, tso, tso->stack_size);
2212 /* If we're debugging, just print out the top of the stack */
2213 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2219 IF_DEBUG(sanity,checkTSO(dest));
2221 IF_DEBUG(scheduler,printTSO(dest));
2228 threadStackUnderflow (Task *task STG_UNUSED, StgTSO *tso)
2230 bdescr *bd, *new_bd;
2231 lnat free_w, tso_size_w;
2234 tso_size_w = tso_sizeW(tso);
2236 if (tso_size_w < MBLOCK_SIZE_W ||
2237 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2242 // don't allow throwTo() to modify the blocked_exceptions queue
2243 // while we are moving the TSO:
2244 lockClosure((StgClosure *)tso);
2246 // this is the number of words we'll free
2247 free_w = round_to_mblocks(tso_size_w/2);
2249 bd = Bdescr((StgPtr)tso);
2250 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2251 bd->free = bd->start + TSO_STRUCT_SIZEW;
2253 new_tso = (StgTSO *)new_bd->start;
2254 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2255 new_tso->stack_size = new_bd->free - new_tso->stack;
2257 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2258 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2260 tso->what_next = ThreadRelocated;
2261 tso->_link = new_tso; // no write barrier reqd: same generation
2263 // The TSO attached to this Task may have moved, so update the
2265 if (task->tso == tso) {
2266 task->tso = new_tso;
2272 IF_DEBUG(sanity,checkTSO(new_tso));
2277 /* ---------------------------------------------------------------------------
2279 - usually called inside a signal handler so it mustn't do anything fancy.
2280 ------------------------------------------------------------------------ */
2283 interruptStgRts(void)
2285 sched_state = SCHED_INTERRUPTING;
2286 setContextSwitches();
2290 /* -----------------------------------------------------------------------------
2293 This function causes at least one OS thread to wake up and run the
2294 scheduler loop. It is invoked when the RTS might be deadlocked, or
2295 an external event has arrived that may need servicing (eg. a
2296 keyboard interrupt).
2298 In the single-threaded RTS we don't do anything here; we only have
2299 one thread anyway, and the event that caused us to want to wake up
2300 will have interrupted any blocking system call in progress anyway.
2301 -------------------------------------------------------------------------- */
2306 #if defined(THREADED_RTS)
2307 // This forces the IO Manager thread to wakeup, which will
2308 // in turn ensure that some OS thread wakes up and runs the
2309 // scheduler loop, which will cause a GC and deadlock check.
2314 /* -----------------------------------------------------------------------------
2317 * Check the blackhole_queue for threads that can be woken up. We do
2318 * this periodically: before every GC, and whenever the run queue is
2321 * An elegant solution might be to just wake up all the blocked
2322 * threads with awakenBlockedQueue occasionally: they'll go back to
2323 * sleep again if the object is still a BLACKHOLE. Unfortunately this
2324 * doesn't give us a way to tell whether we've actually managed to
2325 * wake up any threads, so we would be busy-waiting.
2327 * -------------------------------------------------------------------------- */
2330 checkBlackHoles (Capability *cap)
2333 rtsBool any_woke_up = rtsFalse;
2336 // blackhole_queue is global:
2337 ASSERT_LOCK_HELD(&sched_mutex);
2339 debugTrace(DEBUG_sched, "checking threads blocked on black holes");
2341 // ASSUMES: sched_mutex
2342 prev = &blackhole_queue;
2343 t = blackhole_queue;
2344 while (t != END_TSO_QUEUE) {
2345 ASSERT(t->why_blocked == BlockedOnBlackHole);
2346 type = get_itbl(UNTAG_CLOSURE(t->block_info.closure))->type;
2347 if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
2348 IF_DEBUG(sanity,checkTSO(t));
2349 t = unblockOne(cap, t);
2351 any_woke_up = rtsTrue;
2361 /* -----------------------------------------------------------------------------
2364 This is used for interruption (^C) and forking, and corresponds to
2365 raising an exception but without letting the thread catch the
2367 -------------------------------------------------------------------------- */
2370 deleteThread (Capability *cap, StgTSO *tso)
2372 // NOTE: must only be called on a TSO that we have exclusive
2373 // access to, because we will call throwToSingleThreaded() below.
2374 // The TSO must be on the run queue of the Capability we own, or
2375 // we must own all Capabilities.
2377 if (tso->why_blocked != BlockedOnCCall &&
2378 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2379 throwToSingleThreaded(cap,tso,NULL);
2383 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2385 deleteThread_(Capability *cap, StgTSO *tso)
2386 { // for forkProcess only:
2387 // like deleteThread(), but we delete threads in foreign calls, too.
2389 if (tso->why_blocked == BlockedOnCCall ||
2390 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2391 unblockOne(cap,tso);
2392 tso->what_next = ThreadKilled;
2394 deleteThread(cap,tso);
2399 /* -----------------------------------------------------------------------------
2400 raiseExceptionHelper
2402 This function is called by the raise# primitve, just so that we can
2403 move some of the tricky bits of raising an exception from C-- into
2404 C. Who knows, it might be a useful re-useable thing here too.
2405 -------------------------------------------------------------------------- */
2408 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2410 Capability *cap = regTableToCapability(reg);
2411 StgThunk *raise_closure = NULL;
2413 StgRetInfoTable *info;
2415 // This closure represents the expression 'raise# E' where E
2416 // is the exception raise. It is used to overwrite all the
2417 // thunks which are currently under evaluataion.
2420 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2421 // LDV profiling: stg_raise_info has THUNK as its closure
2422 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2423 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2424 // 1 does not cause any problem unless profiling is performed.
2425 // However, when LDV profiling goes on, we need to linearly scan
2426 // small object pool, where raise_closure is stored, so we should
2427 // use MIN_UPD_SIZE.
2429 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2430 // sizeofW(StgClosure)+1);
2434 // Walk up the stack, looking for the catch frame. On the way,
2435 // we update any closures pointed to from update frames with the
2436 // raise closure that we just built.
2440 info = get_ret_itbl((StgClosure *)p);
2441 next = p + stack_frame_sizeW((StgClosure *)p);
2442 switch (info->i.type) {
2445 // Only create raise_closure if we need to.
2446 if (raise_closure == NULL) {
2448 (StgThunk *)allocateLocal(cap,sizeofW(StgThunk)+1);
2449 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2450 raise_closure->payload[0] = exception;
2452 UPD_IND(((StgUpdateFrame *)p)->updatee,(StgClosure *)raise_closure);
2456 case ATOMICALLY_FRAME:
2457 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2459 return ATOMICALLY_FRAME;
2465 case CATCH_STM_FRAME:
2466 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2468 return CATCH_STM_FRAME;
2474 case CATCH_RETRY_FRAME:
2483 /* -----------------------------------------------------------------------------
2484 findRetryFrameHelper
2486 This function is called by the retry# primitive. It traverses the stack
2487 leaving tso->sp referring to the frame which should handle the retry.
2489 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2490 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2492 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2493 create) because retries are not considered to be exceptions, despite the
2494 similar implementation.
2496 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2497 not be created within memory transactions.
2498 -------------------------------------------------------------------------- */
2501 findRetryFrameHelper (StgTSO *tso)
2504 StgRetInfoTable *info;
2508 info = get_ret_itbl((StgClosure *)p);
2509 next = p + stack_frame_sizeW((StgClosure *)p);
2510 switch (info->i.type) {
2512 case ATOMICALLY_FRAME:
2513 debugTrace(DEBUG_stm,
2514 "found ATOMICALLY_FRAME at %p during retry", p);
2516 return ATOMICALLY_FRAME;
2518 case CATCH_RETRY_FRAME:
2519 debugTrace(DEBUG_stm,
2520 "found CATCH_RETRY_FRAME at %p during retrry", p);
2522 return CATCH_RETRY_FRAME;
2524 case CATCH_STM_FRAME: {
2525 StgTRecHeader *trec = tso -> trec;
2526 StgTRecHeader *outer = stmGetEnclosingTRec(trec);
2527 debugTrace(DEBUG_stm,
2528 "found CATCH_STM_FRAME at %p during retry", p);
2529 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2530 stmAbortTransaction(tso -> cap, trec);
2531 stmFreeAbortedTRec(tso -> cap, trec);
2532 tso -> trec = outer;
2539 ASSERT(info->i.type != CATCH_FRAME);
2540 ASSERT(info->i.type != STOP_FRAME);
2547 /* -----------------------------------------------------------------------------
2548 resurrectThreads is called after garbage collection on the list of
2549 threads found to be garbage. Each of these threads will be woken
2550 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2551 on an MVar, or NonTermination if the thread was blocked on a Black
2554 Locks: assumes we hold *all* the capabilities.
2555 -------------------------------------------------------------------------- */
2558 resurrectThreads (StgTSO *threads)
2564 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2565 next = tso->global_link;
2567 step = Bdescr((P_)tso)->step;
2568 tso->global_link = step->threads;
2569 step->threads = tso;
2571 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2573 // Wake up the thread on the Capability it was last on
2576 switch (tso->why_blocked) {
2578 case BlockedOnException:
2579 /* Called by GC - sched_mutex lock is currently held. */
2580 throwToSingleThreaded(cap, tso,
2581 (StgClosure *)blockedOnDeadMVar_closure);
2583 case BlockedOnBlackHole:
2584 throwToSingleThreaded(cap, tso,
2585 (StgClosure *)nonTermination_closure);
2588 throwToSingleThreaded(cap, tso,
2589 (StgClosure *)blockedIndefinitely_closure);
2592 /* This might happen if the thread was blocked on a black hole
2593 * belonging to a thread that we've just woken up (raiseAsync
2594 * can wake up threads, remember...).
2598 barf("resurrectThreads: thread blocked in a strange way");
2603 /* -----------------------------------------------------------------------------
2604 performPendingThrowTos is called after garbage collection, and
2605 passed a list of threads that were found to have pending throwTos
2606 (tso->blocked_exceptions was not empty), and were blocked.
2607 Normally this doesn't happen, because we would deliver the
2608 exception directly if the target thread is blocked, but there are
2609 small windows where it might occur on a multiprocessor (see
2612 NB. we must be holding all the capabilities at this point, just
2613 like resurrectThreads().
2614 -------------------------------------------------------------------------- */
2617 performPendingThrowTos (StgTSO *threads)
2623 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2624 next = tso->global_link;
2626 step = Bdescr((P_)tso)->step;
2627 tso->global_link = step->threads;
2628 step->threads = tso;
2630 debugTrace(DEBUG_sched, "performing blocked throwTo to thread %lu", (unsigned long)tso->id);
2633 maybePerformBlockedException(cap, tso);