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 * NB. must be StgWord, we do xchg() on it.
98 volatile StgWord recent_activity = ACTIVITY_YES;
100 /* if this flag is set as well, give up execution
101 * LOCK: none (changes monotonically)
103 volatile StgWord sched_state = SCHED_RUNNING;
105 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
106 * exists - earlier gccs apparently didn't.
112 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
113 * in an MT setting, needed to signal that a worker thread shouldn't hang around
114 * in the scheduler when it is out of work.
116 rtsBool shutting_down_scheduler = rtsFalse;
119 * This mutex protects most of the global scheduler data in
120 * the THREADED_RTS runtime.
122 #if defined(THREADED_RTS)
126 #if !defined(mingw32_HOST_OS)
127 #define FORKPROCESS_PRIMOP_SUPPORTED
130 /* -----------------------------------------------------------------------------
131 * static function prototypes
132 * -------------------------------------------------------------------------- */
134 static Capability *schedule (Capability *initialCapability, Task *task);
137 // These function all encapsulate parts of the scheduler loop, and are
138 // abstracted only to make the structure and control flow of the
139 // scheduler clearer.
141 static void schedulePreLoop (void);
142 static void scheduleFindWork (Capability *cap);
143 #if defined(THREADED_RTS)
144 static void scheduleYield (Capability **pcap, Task *task);
146 static void scheduleStartSignalHandlers (Capability *cap);
147 static void scheduleCheckBlockedThreads (Capability *cap);
148 static void scheduleCheckWakeupThreads(Capability *cap USED_IF_NOT_THREADS);
149 static void scheduleCheckBlackHoles (Capability *cap);
150 static void scheduleDetectDeadlock (Capability *cap, Task *task);
151 static void schedulePushWork(Capability *cap, Task *task);
152 #if defined(PARALLEL_HASKELL)
153 static rtsBool scheduleGetRemoteWork(Capability *cap);
154 static void scheduleSendPendingMessages(void);
156 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
157 static void scheduleActivateSpark(Capability *cap);
159 static void schedulePostRunThread(Capability *cap, StgTSO *t);
160 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
161 static void scheduleHandleStackOverflow( Capability *cap, Task *task,
163 static rtsBool scheduleHandleYield( Capability *cap, StgTSO *t,
164 nat prev_what_next );
165 static void scheduleHandleThreadBlocked( StgTSO *t );
166 static rtsBool scheduleHandleThreadFinished( Capability *cap, Task *task,
168 static rtsBool scheduleNeedHeapProfile(rtsBool ready_to_gc);
169 static Capability *scheduleDoGC(Capability *cap, Task *task,
170 rtsBool force_major);
172 static rtsBool checkBlackHoles(Capability *cap);
174 static StgTSO *threadStackOverflow(Capability *cap, StgTSO *tso);
175 static StgTSO *threadStackUnderflow(Task *task, StgTSO *tso);
177 static void deleteThread (Capability *cap, StgTSO *tso);
178 static void deleteAllThreads (Capability *cap);
180 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
181 static void deleteThread_(Capability *cap, StgTSO *tso);
185 static char *whatNext_strs[] = {
195 /* -----------------------------------------------------------------------------
196 * Putting a thread on the run queue: different scheduling policies
197 * -------------------------------------------------------------------------- */
200 addToRunQueue( Capability *cap, StgTSO *t )
202 #if defined(PARALLEL_HASKELL)
203 if (RtsFlags.ParFlags.doFairScheduling) {
204 // this does round-robin scheduling; good for concurrency
205 appendToRunQueue(cap,t);
207 // this does unfair scheduling; good for parallelism
208 pushOnRunQueue(cap,t);
211 // this does round-robin scheduling; good for concurrency
212 appendToRunQueue(cap,t);
216 /* ---------------------------------------------------------------------------
217 Main scheduling loop.
219 We use round-robin scheduling, each thread returning to the
220 scheduler loop when one of these conditions is detected:
223 * timer expires (thread yields)
229 In a GranSim setup this loop iterates over the global event queue.
230 This revolves around the global event queue, which determines what
231 to do next. Therefore, it's more complicated than either the
232 concurrent or the parallel (GUM) setup.
233 This version has been entirely removed (JB 2008/08).
236 GUM iterates over incoming messages.
237 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
238 and sends out a fish whenever it has nothing to do; in-between
239 doing the actual reductions (shared code below) it processes the
240 incoming messages and deals with delayed operations
241 (see PendingFetches).
242 This is not the ugliest code you could imagine, but it's bloody close.
244 (JB 2008/08) This version was formerly indicated by a PP-Flag PAR,
245 now by PP-flag PARALLEL_HASKELL. The Eden RTS (in GHC-6.x) uses it,
246 as well as future GUM versions. This file has been refurbished to
247 only contain valid code, which is however incomplete, refers to
248 invalid includes etc.
250 ------------------------------------------------------------------------ */
253 schedule (Capability *initialCapability, Task *task)
257 StgThreadReturnCode ret;
258 #if defined(PARALLEL_HASKELL)
259 rtsBool receivedFinish = rtsFalse;
263 #if defined(THREADED_RTS)
264 rtsBool first = rtsTrue;
267 cap = initialCapability;
269 // Pre-condition: this task owns initialCapability.
270 // The sched_mutex is *NOT* held
271 // NB. on return, we still hold a capability.
273 debugTrace (DEBUG_sched,
274 "### NEW SCHEDULER LOOP (task: %p, cap: %p)",
275 task, initialCapability);
279 // -----------------------------------------------------------
280 // Scheduler loop starts here:
282 #if defined(PARALLEL_HASKELL)
283 #define TERMINATION_CONDITION (!receivedFinish)
285 #define TERMINATION_CONDITION rtsTrue
288 while (TERMINATION_CONDITION) {
290 // Check whether we have re-entered the RTS from Haskell without
291 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
293 if (cap->in_haskell) {
294 errorBelch("schedule: re-entered unsafely.\n"
295 " Perhaps a 'foreign import unsafe' should be 'safe'?");
296 stg_exit(EXIT_FAILURE);
299 // The interruption / shutdown sequence.
301 // In order to cleanly shut down the runtime, we want to:
302 // * make sure that all main threads return to their callers
303 // with the state 'Interrupted'.
304 // * clean up all OS threads assocated with the runtime
305 // * free all memory etc.
307 // So the sequence for ^C goes like this:
309 // * ^C handler sets sched_state := SCHED_INTERRUPTING and
310 // arranges for some Capability to wake up
312 // * all threads in the system are halted, and the zombies are
313 // placed on the run queue for cleaning up. We acquire all
314 // the capabilities in order to delete the threads, this is
315 // done by scheduleDoGC() for convenience (because GC already
316 // needs to acquire all the capabilities). We can't kill
317 // threads involved in foreign calls.
319 // * somebody calls shutdownHaskell(), which calls exitScheduler()
321 // * sched_state := SCHED_SHUTTING_DOWN
323 // * all workers exit when the run queue on their capability
324 // drains. All main threads will also exit when their TSO
325 // reaches the head of the run queue and they can return.
327 // * eventually all Capabilities will shut down, and the RTS can
330 // * We might be left with threads blocked in foreign calls,
331 // we should really attempt to kill these somehow (TODO);
333 switch (sched_state) {
336 case SCHED_INTERRUPTING:
337 debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
338 #if defined(THREADED_RTS)
339 discardSparksCap(cap);
341 /* scheduleDoGC() deletes all the threads */
342 cap = scheduleDoGC(cap,task,rtsFalse);
344 // after scheduleDoGC(), we must be shutting down. Either some
345 // other Capability did the final GC, or we did it above,
346 // either way we can fall through to the SCHED_SHUTTING_DOWN
348 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
351 case SCHED_SHUTTING_DOWN:
352 debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
353 // If we are a worker, just exit. If we're a bound thread
354 // then we will exit below when we've removed our TSO from
356 if (task->tso == NULL && emptyRunQueue(cap)) {
361 barf("sched_state: %d", sched_state);
364 scheduleFindWork(cap);
366 /* work pushing, currently relevant only for THREADED_RTS:
367 (pushes threads, wakes up idle capabilities for stealing) */
368 schedulePushWork(cap,task);
370 #if defined(PARALLEL_HASKELL)
371 /* since we perform a blocking receive and continue otherwise,
372 either we never reach here or we definitely have work! */
373 // from here: non-empty run queue
374 ASSERT(!emptyRunQueue(cap));
376 if (PacketsWaiting()) { /* now process incoming messages, if any
379 CAUTION: scheduleGetRemoteWork called
380 above, waits for messages as well! */
381 processMessages(cap, &receivedFinish);
383 #endif // PARALLEL_HASKELL: non-empty run queue!
385 scheduleDetectDeadlock(cap,task);
387 #if defined(THREADED_RTS)
388 cap = task->cap; // reload cap, it might have changed
391 // Normally, the only way we can get here with no threads to
392 // run is if a keyboard interrupt received during
393 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
394 // Additionally, it is not fatal for the
395 // threaded RTS to reach here with no threads to run.
397 // win32: might be here due to awaitEvent() being abandoned
398 // as a result of a console event having been delivered.
400 #if defined(THREADED_RTS)
404 // // don't yield the first time, we want a chance to run this
405 // // thread for a bit, even if there are others banging at the
408 // ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
412 scheduleYield(&cap,task);
413 if (emptyRunQueue(cap)) continue; // look for work again
416 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
417 if ( emptyRunQueue(cap) ) {
418 ASSERT(sched_state >= SCHED_INTERRUPTING);
423 // Get a thread to run
425 t = popRunQueue(cap);
427 // Sanity check the thread we're about to run. This can be
428 // expensive if there is lots of thread switching going on...
429 IF_DEBUG(sanity,checkTSO(t));
431 #if defined(THREADED_RTS)
432 // Check whether we can run this thread in the current task.
433 // If not, we have to pass our capability to the right task.
435 Task *bound = t->bound;
439 debugTrace(DEBUG_sched,
440 "### Running thread %lu in bound thread", (unsigned long)t->id);
441 // yes, the Haskell thread is bound to the current native thread
443 debugTrace(DEBUG_sched,
444 "### thread %lu bound to another OS thread", (unsigned long)t->id);
445 // no, bound to a different Haskell thread: pass to that thread
446 pushOnRunQueue(cap,t);
450 // The thread we want to run is unbound.
452 debugTrace(DEBUG_sched,
453 "### this OS thread cannot run thread %lu", (unsigned long)t->id);
454 // no, the current native thread is bound to a different
455 // Haskell thread, so pass it to any worker thread
456 pushOnRunQueue(cap,t);
463 // If we're shutting down, and this thread has not yet been
464 // killed, kill it now. This sometimes happens when a finalizer
465 // thread is created by the final GC, or a thread previously
466 // in a foreign call returns.
467 if (sched_state >= SCHED_INTERRUPTING &&
468 !(t->what_next == ThreadComplete || t->what_next == ThreadKilled)) {
472 /* context switches are initiated by the timer signal, unless
473 * the user specified "context switch as often as possible", with
476 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
477 && !emptyThreadQueues(cap)) {
478 cap->context_switch = 1;
483 // CurrentTSO is the thread to run. t might be different if we
484 // loop back to run_thread, so make sure to set CurrentTSO after
486 cap->r.rCurrentTSO = t;
488 debugTrace(DEBUG_sched, "-->> running thread %ld %s ...",
489 (long)t->id, whatNext_strs[t->what_next]);
491 startHeapProfTimer();
493 // Check for exceptions blocked on this thread
494 maybePerformBlockedException (cap, t);
496 // ----------------------------------------------------------------------
497 // Run the current thread
499 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
500 ASSERT(t->cap == cap);
501 ASSERT(t->bound ? t->bound->cap == cap : 1);
503 prev_what_next = t->what_next;
505 errno = t->saved_errno;
507 SetLastError(t->saved_winerror);
510 cap->in_haskell = rtsTrue;
514 #if defined(THREADED_RTS)
515 if (recent_activity == ACTIVITY_DONE_GC) {
516 // ACTIVITY_DONE_GC means we turned off the timer signal to
517 // conserve power (see #1623). Re-enable it here.
519 prev = xchg((P_)&recent_activity, ACTIVITY_YES);
520 if (prev == ACTIVITY_DONE_GC) {
524 recent_activity = ACTIVITY_YES;
528 switch (prev_what_next) {
532 /* Thread already finished, return to scheduler. */
533 ret = ThreadFinished;
539 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
540 cap = regTableToCapability(r);
545 case ThreadInterpret:
546 cap = interpretBCO(cap);
551 barf("schedule: invalid what_next field");
554 cap->in_haskell = rtsFalse;
556 // The TSO might have moved, eg. if it re-entered the RTS and a GC
557 // happened. So find the new location:
558 t = cap->r.rCurrentTSO;
560 // We have run some Haskell code: there might be blackhole-blocked
561 // threads to wake up now.
562 // Lock-free test here should be ok, we're just setting a flag.
563 if ( blackhole_queue != END_TSO_QUEUE ) {
564 blackholes_need_checking = rtsTrue;
567 // And save the current errno in this thread.
568 // XXX: possibly bogus for SMP because this thread might already
569 // be running again, see code below.
570 t->saved_errno = errno;
572 // Similarly for Windows error code
573 t->saved_winerror = GetLastError();
576 #if defined(THREADED_RTS)
577 // If ret is ThreadBlocked, and this Task is bound to the TSO that
578 // blocked, we are in limbo - the TSO is now owned by whatever it
579 // is blocked on, and may in fact already have been woken up,
580 // perhaps even on a different Capability. It may be the case
581 // that task->cap != cap. We better yield this Capability
582 // immediately and return to normaility.
583 if (ret == ThreadBlocked) {
584 debugTrace(DEBUG_sched,
585 "--<< thread %lu (%s) stopped: blocked",
586 (unsigned long)t->id, whatNext_strs[t->what_next]);
591 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
592 ASSERT(t->cap == cap);
594 // ----------------------------------------------------------------------
596 // Costs for the scheduler are assigned to CCS_SYSTEM
598 #if defined(PROFILING)
602 schedulePostRunThread(cap,t);
604 t = threadStackUnderflow(task,t);
606 ready_to_gc = rtsFalse;
610 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
614 scheduleHandleStackOverflow(cap,task,t);
618 if (scheduleHandleYield(cap, t, prev_what_next)) {
619 // shortcut for switching between compiler/interpreter:
625 scheduleHandleThreadBlocked(t);
629 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
630 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
634 barf("schedule: invalid thread return code %d", (int)ret);
637 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
638 cap = scheduleDoGC(cap,task,rtsFalse);
640 } /* end of while() */
643 /* ----------------------------------------------------------------------------
644 * Setting up the scheduler loop
645 * ------------------------------------------------------------------------- */
648 schedulePreLoop(void)
650 // initialisation for scheduler - what cannot go into initScheduler()
653 /* -----------------------------------------------------------------------------
656 * Search for work to do, and handle messages from elsewhere.
657 * -------------------------------------------------------------------------- */
660 scheduleFindWork (Capability *cap)
662 scheduleStartSignalHandlers(cap);
664 // Only check the black holes here if we've nothing else to do.
665 // During normal execution, the black hole list only gets checked
666 // at GC time, to avoid repeatedly traversing this possibly long
667 // list each time around the scheduler.
668 if (emptyRunQueue(cap)) { scheduleCheckBlackHoles(cap); }
670 scheduleCheckWakeupThreads(cap);
672 scheduleCheckBlockedThreads(cap);
674 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
675 if (emptyRunQueue(cap)) { scheduleActivateSpark(cap); }
678 #if defined(PARALLEL_HASKELL)
679 // if messages have been buffered...
680 scheduleSendPendingMessages();
683 #if defined(PARALLEL_HASKELL)
684 if (emptyRunQueue(cap)) {
685 receivedFinish = scheduleGetRemoteWork(cap);
686 continue; // a new round, (hopefully) with new work
688 in GUM, this a) sends out a FISH and returns IF no fish is
690 b) (blocking) awaits and receives messages
692 in Eden, this is only the blocking receive, as b) in GUM.
698 #if defined(THREADED_RTS)
699 STATIC_INLINE rtsBool
700 shouldYieldCapability (Capability *cap, Task *task)
702 // we need to yield this capability to someone else if..
703 // - another thread is initiating a GC
704 // - another Task is returning from a foreign call
705 // - the thread at the head of the run queue cannot be run
706 // by this Task (it is bound to another Task, or it is unbound
707 // and this task it bound).
708 return (waiting_for_gc ||
709 cap->returning_tasks_hd != NULL ||
710 (!emptyRunQueue(cap) && (task->tso == NULL
711 ? cap->run_queue_hd->bound != NULL
712 : cap->run_queue_hd->bound != task)));
715 // This is the single place where a Task goes to sleep. There are
716 // two reasons it might need to sleep:
717 // - there are no threads to run
718 // - we need to yield this Capability to someone else
719 // (see shouldYieldCapability())
721 // Careful: the scheduler loop is quite delicate. Make sure you run
722 // the tests in testsuite/concurrent (all ways) after modifying this,
723 // and also check the benchmarks in nofib/parallel for regressions.
726 scheduleYield (Capability **pcap, Task *task)
728 Capability *cap = *pcap;
730 // if we have work, and we don't need to give up the Capability, continue.
731 if (!shouldYieldCapability(cap,task) &&
732 (!emptyRunQueue(cap) ||
733 blackholes_need_checking ||
734 sched_state >= SCHED_INTERRUPTING))
737 // otherwise yield (sleep), and keep yielding if necessary.
739 yieldCapability(&cap,task);
741 while (shouldYieldCapability(cap,task));
743 // note there may still be no threads on the run queue at this
744 // point, the caller has to check.
751 /* -----------------------------------------------------------------------------
754 * Push work to other Capabilities if we have some.
755 * -------------------------------------------------------------------------- */
758 schedulePushWork(Capability *cap USED_IF_THREADS,
759 Task *task USED_IF_THREADS)
761 /* following code not for PARALLEL_HASKELL. I kept the call general,
762 future GUM versions might use pushing in a distributed setup */
763 #if defined(THREADED_RTS)
765 Capability *free_caps[n_capabilities], *cap0;
768 // migration can be turned off with +RTS -qg
769 if (!RtsFlags.ParFlags.migrate) return;
771 // Check whether we have more threads on our run queue, or sparks
772 // in our pool, that we could hand to another Capability.
773 if ((emptyRunQueue(cap) || cap->run_queue_hd->_link == END_TSO_QUEUE)
774 && sparkPoolSizeCap(cap) < 2) {
778 // First grab as many free Capabilities as we can.
779 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
780 cap0 = &capabilities[i];
781 if (cap != cap0 && tryGrabCapability(cap0,task)) {
782 if (!emptyRunQueue(cap0) || cap->returning_tasks_hd != NULL) {
783 // it already has some work, we just grabbed it at
784 // the wrong moment. Or maybe it's deadlocked!
785 releaseCapability(cap0);
787 free_caps[n_free_caps++] = cap0;
792 // we now have n_free_caps free capabilities stashed in
793 // free_caps[]. Share our run queue equally with them. This is
794 // probably the simplest thing we could do; improvements we might
795 // want to do include:
797 // - giving high priority to moving relatively new threads, on
798 // the gournds that they haven't had time to build up a
799 // working set in the cache on this CPU/Capability.
801 // - giving low priority to moving long-lived threads
803 if (n_free_caps > 0) {
804 StgTSO *prev, *t, *next;
805 rtsBool pushed_to_all;
807 debugTrace(DEBUG_sched,
808 "cap %d: %s and %d free capabilities, sharing...",
810 (!emptyRunQueue(cap) && cap->run_queue_hd->_link != END_TSO_QUEUE)?
811 "excess threads on run queue":"sparks to share (>=2)",
815 pushed_to_all = rtsFalse;
817 if (cap->run_queue_hd != END_TSO_QUEUE) {
818 prev = cap->run_queue_hd;
820 prev->_link = END_TSO_QUEUE;
821 for (; t != END_TSO_QUEUE; t = next) {
823 t->_link = END_TSO_QUEUE;
824 if (t->what_next == ThreadRelocated
825 || t->bound == task // don't move my bound thread
826 || tsoLocked(t)) { // don't move a locked thread
827 setTSOLink(cap, prev, t);
829 } else if (i == n_free_caps) {
830 pushed_to_all = rtsTrue;
833 setTSOLink(cap, prev, t);
836 debugTrace(DEBUG_sched, "pushing thread %lu to capability %d", (unsigned long)t->id, free_caps[i]->no);
837 appendToRunQueue(free_caps[i],t);
838 if (t->bound) { t->bound->cap = free_caps[i]; }
839 t->cap = free_caps[i];
843 cap->run_queue_tl = prev;
847 /* JB I left this code in place, it would work but is not necessary */
849 // If there are some free capabilities that we didn't push any
850 // threads to, then try to push a spark to each one.
851 if (!pushed_to_all) {
853 // i is the next free capability to push to
854 for (; i < n_free_caps; i++) {
855 if (emptySparkPoolCap(free_caps[i])) {
856 spark = tryStealSpark(cap->sparks);
858 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
859 newSpark(&(free_caps[i]->r), spark);
864 #endif /* SPARK_PUSHING */
866 // release the capabilities
867 for (i = 0; i < n_free_caps; i++) {
868 task->cap = free_caps[i];
869 releaseAndWakeupCapability(free_caps[i]);
872 task->cap = cap; // reset to point to our Capability.
874 #endif /* THREADED_RTS */
878 /* ----------------------------------------------------------------------------
879 * Start any pending signal handlers
880 * ------------------------------------------------------------------------- */
882 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
884 scheduleStartSignalHandlers(Capability *cap)
886 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
887 // safe outside the lock
888 startSignalHandlers(cap);
893 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
898 /* ----------------------------------------------------------------------------
899 * Check for blocked threads that can be woken up.
900 * ------------------------------------------------------------------------- */
903 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
905 #if !defined(THREADED_RTS)
907 // Check whether any waiting threads need to be woken up. If the
908 // run queue is empty, and there are no other tasks running, we
909 // can wait indefinitely for something to happen.
911 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
913 awaitEvent( emptyRunQueue(cap) && !blackholes_need_checking );
919 /* ----------------------------------------------------------------------------
920 * Check for threads woken up by other Capabilities
921 * ------------------------------------------------------------------------- */
924 scheduleCheckWakeupThreads(Capability *cap USED_IF_THREADS)
926 #if defined(THREADED_RTS)
927 // Any threads that were woken up by other Capabilities get
928 // appended to our run queue.
929 if (!emptyWakeupQueue(cap)) {
930 ACQUIRE_LOCK(&cap->lock);
931 if (emptyRunQueue(cap)) {
932 cap->run_queue_hd = cap->wakeup_queue_hd;
933 cap->run_queue_tl = cap->wakeup_queue_tl;
935 setTSOLink(cap, cap->run_queue_tl, cap->wakeup_queue_hd);
936 cap->run_queue_tl = cap->wakeup_queue_tl;
938 cap->wakeup_queue_hd = cap->wakeup_queue_tl = END_TSO_QUEUE;
939 RELEASE_LOCK(&cap->lock);
944 /* ----------------------------------------------------------------------------
945 * Check for threads blocked on BLACKHOLEs that can be woken up
946 * ------------------------------------------------------------------------- */
948 scheduleCheckBlackHoles (Capability *cap)
950 if ( blackholes_need_checking ) // check without the lock first
952 ACQUIRE_LOCK(&sched_mutex);
953 if ( blackholes_need_checking ) {
954 blackholes_need_checking = rtsFalse;
955 // important that we reset the flag *before* checking the
956 // blackhole queue, otherwise we could get deadlock. This
957 // happens as follows: we wake up a thread that
958 // immediately runs on another Capability, blocks on a
959 // blackhole, and then we reset the blackholes_need_checking flag.
960 checkBlackHoles(cap);
962 RELEASE_LOCK(&sched_mutex);
966 /* ----------------------------------------------------------------------------
967 * Detect deadlock conditions and attempt to resolve them.
968 * ------------------------------------------------------------------------- */
971 scheduleDetectDeadlock (Capability *cap, Task *task)
974 #if defined(PARALLEL_HASKELL)
975 // ToDo: add deadlock detection in GUM (similar to THREADED_RTS) -- HWL
980 * Detect deadlock: when we have no threads to run, there are no
981 * threads blocked, waiting for I/O, or sleeping, and all the
982 * other tasks are waiting for work, we must have a deadlock of
985 if ( emptyThreadQueues(cap) )
987 #if defined(THREADED_RTS)
989 * In the threaded RTS, we only check for deadlock if there
990 * has been no activity in a complete timeslice. This means
991 * we won't eagerly start a full GC just because we don't have
992 * any threads to run currently.
994 if (recent_activity != ACTIVITY_INACTIVE) return;
997 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
999 // Garbage collection can release some new threads due to
1000 // either (a) finalizers or (b) threads resurrected because
1001 // they are unreachable and will therefore be sent an
1002 // exception. Any threads thus released will be immediately
1004 cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
1006 recent_activity = ACTIVITY_DONE_GC;
1007 // disable timer signals (see #1623)
1010 if ( !emptyRunQueue(cap) ) return;
1012 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
1013 /* If we have user-installed signal handlers, then wait
1014 * for signals to arrive rather then bombing out with a
1017 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
1018 debugTrace(DEBUG_sched,
1019 "still deadlocked, waiting for signals...");
1023 if (signals_pending()) {
1024 startSignalHandlers(cap);
1027 // either we have threads to run, or we were interrupted:
1028 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
1034 #if !defined(THREADED_RTS)
1035 /* Probably a real deadlock. Send the current main thread the
1036 * Deadlock exception.
1039 switch (task->tso->why_blocked) {
1041 case BlockedOnBlackHole:
1042 case BlockedOnException:
1044 throwToSingleThreaded(cap, task->tso,
1045 (StgClosure *)nonTermination_closure);
1048 barf("deadlock: main thread blocked in a strange way");
1057 /* ----------------------------------------------------------------------------
1058 * Send pending messages (PARALLEL_HASKELL only)
1059 * ------------------------------------------------------------------------- */
1061 #if defined(PARALLEL_HASKELL)
1063 scheduleSendPendingMessages(void)
1066 # if defined(PAR) // global Mem.Mgmt., omit for now
1067 if (PendingFetches != END_BF_QUEUE) {
1072 if (RtsFlags.ParFlags.BufferTime) {
1073 // if we use message buffering, we must send away all message
1074 // packets which have become too old...
1080 /* ----------------------------------------------------------------------------
1081 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
1082 * ------------------------------------------------------------------------- */
1084 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
1086 scheduleActivateSpark(Capability *cap)
1090 createSparkThread(cap);
1091 debugTrace(DEBUG_sched, "creating a spark thread");
1094 #endif // PARALLEL_HASKELL || THREADED_RTS
1096 /* ----------------------------------------------------------------------------
1097 * Get work from a remote node (PARALLEL_HASKELL only)
1098 * ------------------------------------------------------------------------- */
1100 #if defined(PARALLEL_HASKELL)
1101 static rtsBool /* return value used in PARALLEL_HASKELL only */
1102 scheduleGetRemoteWork (Capability *cap STG_UNUSED)
1104 #if defined(PARALLEL_HASKELL)
1105 rtsBool receivedFinish = rtsFalse;
1107 // idle() , i.e. send all buffers, wait for work
1108 if (RtsFlags.ParFlags.BufferTime) {
1109 IF_PAR_DEBUG(verbose,
1110 debugBelch("...send all pending data,"));
1113 for (i=1; i<=nPEs; i++)
1114 sendImmediately(i); // send all messages away immediately
1118 /* this would be the place for fishing in GUM...
1120 if (no-earlier-fish-around)
1121 sendFish(choosePe());
1124 // Eden:just look for incoming messages (blocking receive)
1125 IF_PAR_DEBUG(verbose,
1126 debugBelch("...wait for incoming messages...\n"));
1127 processMessages(cap, &receivedFinish); // blocking receive...
1130 return receivedFinish;
1131 // reenter scheduling look after having received something
1133 #else /* !PARALLEL_HASKELL, i.e. THREADED_RTS */
1135 return rtsFalse; /* return value unused in THREADED_RTS */
1137 #endif /* PARALLEL_HASKELL */
1139 #endif // PARALLEL_HASKELL || THREADED_RTS
1141 /* ----------------------------------------------------------------------------
1142 * After running a thread...
1143 * ------------------------------------------------------------------------- */
1146 schedulePostRunThread (Capability *cap, StgTSO *t)
1148 // We have to be able to catch transactions that are in an
1149 // infinite loop as a result of seeing an inconsistent view of
1153 // [a,b] <- mapM readTVar [ta,tb]
1154 // when (a == b) loop
1156 // and a is never equal to b given a consistent view of memory.
1158 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1159 if (!stmValidateNestOfTransactions (t -> trec)) {
1160 debugTrace(DEBUG_sched | DEBUG_stm,
1161 "trec %p found wasting its time", t);
1163 // strip the stack back to the
1164 // ATOMICALLY_FRAME, aborting the (nested)
1165 // transaction, and saving the stack of any
1166 // partially-evaluated thunks on the heap.
1167 throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1169 ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1173 /* some statistics gathering in the parallel case */
1176 /* -----------------------------------------------------------------------------
1177 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1178 * -------------------------------------------------------------------------- */
1181 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1183 // did the task ask for a large block?
1184 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1185 // if so, get one and push it on the front of the nursery.
1189 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1191 debugTrace(DEBUG_sched,
1192 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1193 (long)t->id, whatNext_strs[t->what_next], blocks);
1195 // don't do this if the nursery is (nearly) full, we'll GC first.
1196 if (cap->r.rCurrentNursery->link != NULL ||
1197 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1198 // if the nursery has only one block.
1201 bd = allocGroup( blocks );
1203 cap->r.rNursery->n_blocks += blocks;
1205 // link the new group into the list
1206 bd->link = cap->r.rCurrentNursery;
1207 bd->u.back = cap->r.rCurrentNursery->u.back;
1208 if (cap->r.rCurrentNursery->u.back != NULL) {
1209 cap->r.rCurrentNursery->u.back->link = bd;
1211 #if !defined(THREADED_RTS)
1212 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1213 g0s0 == cap->r.rNursery);
1215 cap->r.rNursery->blocks = bd;
1217 cap->r.rCurrentNursery->u.back = bd;
1219 // initialise it as a nursery block. We initialise the
1220 // step, gen_no, and flags field of *every* sub-block in
1221 // this large block, because this is easier than making
1222 // sure that we always find the block head of a large
1223 // block whenever we call Bdescr() (eg. evacuate() and
1224 // isAlive() in the GC would both have to do this, at
1228 for (x = bd; x < bd + blocks; x++) {
1229 x->step = cap->r.rNursery;
1235 // This assert can be a killer if the app is doing lots
1236 // of large block allocations.
1237 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1239 // now update the nursery to point to the new block
1240 cap->r.rCurrentNursery = bd;
1242 // we might be unlucky and have another thread get on the
1243 // run queue before us and steal the large block, but in that
1244 // case the thread will just end up requesting another large
1246 pushOnRunQueue(cap,t);
1247 return rtsFalse; /* not actually GC'ing */
1251 debugTrace(DEBUG_sched,
1252 "--<< thread %ld (%s) stopped: HeapOverflow",
1253 (long)t->id, whatNext_strs[t->what_next]);
1255 if (cap->context_switch) {
1256 // Sometimes we miss a context switch, e.g. when calling
1257 // primitives in a tight loop, MAYBE_GC() doesn't check the
1258 // context switch flag, and we end up waiting for a GC.
1259 // See #1984, and concurrent/should_run/1984
1260 cap->context_switch = 0;
1261 addToRunQueue(cap,t);
1263 pushOnRunQueue(cap,t);
1266 /* actual GC is done at the end of the while loop in schedule() */
1269 /* -----------------------------------------------------------------------------
1270 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1271 * -------------------------------------------------------------------------- */
1274 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1276 debugTrace (DEBUG_sched,
1277 "--<< thread %ld (%s) stopped, StackOverflow",
1278 (long)t->id, whatNext_strs[t->what_next]);
1280 /* just adjust the stack for this thread, then pop it back
1284 /* enlarge the stack */
1285 StgTSO *new_t = threadStackOverflow(cap, t);
1287 /* The TSO attached to this Task may have moved, so update the
1290 if (task->tso == t) {
1293 pushOnRunQueue(cap,new_t);
1297 /* -----------------------------------------------------------------------------
1298 * Handle a thread that returned to the scheduler with ThreadYielding
1299 * -------------------------------------------------------------------------- */
1302 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1304 // Reset the context switch flag. We don't do this just before
1305 // running the thread, because that would mean we would lose ticks
1306 // during GC, which can lead to unfair scheduling (a thread hogs
1307 // the CPU because the tick always arrives during GC). This way
1308 // penalises threads that do a lot of allocation, but that seems
1309 // better than the alternative.
1310 cap->context_switch = 0;
1312 /* put the thread back on the run queue. Then, if we're ready to
1313 * GC, check whether this is the last task to stop. If so, wake
1314 * up the GC thread. getThread will block during a GC until the
1318 if (t->what_next != prev_what_next) {
1319 debugTrace(DEBUG_sched,
1320 "--<< thread %ld (%s) stopped to switch evaluators",
1321 (long)t->id, whatNext_strs[t->what_next]);
1323 debugTrace(DEBUG_sched,
1324 "--<< thread %ld (%s) stopped, yielding",
1325 (long)t->id, whatNext_strs[t->what_next]);
1330 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1332 ASSERT(t->_link == END_TSO_QUEUE);
1334 // Shortcut if we're just switching evaluators: don't bother
1335 // doing stack squeezing (which can be expensive), just run the
1337 if (t->what_next != prev_what_next) {
1341 addToRunQueue(cap,t);
1346 /* -----------------------------------------------------------------------------
1347 * Handle a thread that returned to the scheduler with ThreadBlocked
1348 * -------------------------------------------------------------------------- */
1351 scheduleHandleThreadBlocked( StgTSO *t
1352 #if !defined(GRAN) && !defined(DEBUG)
1358 // We don't need to do anything. The thread is blocked, and it
1359 // has tidied up its stack and placed itself on whatever queue
1360 // it needs to be on.
1362 // ASSERT(t->why_blocked != NotBlocked);
1363 // Not true: for example,
1364 // - in THREADED_RTS, the thread may already have been woken
1365 // up by another Capability. This actually happens: try
1366 // conc023 +RTS -N2.
1367 // - the thread may have woken itself up already, because
1368 // threadPaused() might have raised a blocked throwTo
1369 // exception, see maybePerformBlockedException().
1372 if (traceClass(DEBUG_sched)) {
1373 debugTraceBegin("--<< thread %lu (%s) stopped: ",
1374 (unsigned long)t->id, whatNext_strs[t->what_next]);
1375 printThreadBlockage(t);
1381 /* -----------------------------------------------------------------------------
1382 * Handle a thread that returned to the scheduler with ThreadFinished
1383 * -------------------------------------------------------------------------- */
1386 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1388 /* Need to check whether this was a main thread, and if so,
1389 * return with the return value.
1391 * We also end up here if the thread kills itself with an
1392 * uncaught exception, see Exception.cmm.
1394 debugTrace(DEBUG_sched, "--++ thread %lu (%s) finished",
1395 (unsigned long)t->id, whatNext_strs[t->what_next]);
1398 // Check whether the thread that just completed was a bound
1399 // thread, and if so return with the result.
1401 // There is an assumption here that all thread completion goes
1402 // through this point; we need to make sure that if a thread
1403 // ends up in the ThreadKilled state, that it stays on the run
1404 // queue so it can be dealt with here.
1409 if (t->bound != task) {
1410 #if !defined(THREADED_RTS)
1411 // Must be a bound thread that is not the topmost one. Leave
1412 // it on the run queue until the stack has unwound to the
1413 // point where we can deal with this. Leaving it on the run
1414 // queue also ensures that the garbage collector knows about
1415 // this thread and its return value (it gets dropped from the
1416 // step->threads list so there's no other way to find it).
1417 appendToRunQueue(cap,t);
1420 // this cannot happen in the threaded RTS, because a
1421 // bound thread can only be run by the appropriate Task.
1422 barf("finished bound thread that isn't mine");
1426 ASSERT(task->tso == t);
1428 if (t->what_next == ThreadComplete) {
1430 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1431 *(task->ret) = (StgClosure *)task->tso->sp[1];
1433 task->stat = Success;
1436 *(task->ret) = NULL;
1438 if (sched_state >= SCHED_INTERRUPTING) {
1439 task->stat = Interrupted;
1441 task->stat = Killed;
1445 removeThreadLabel((StgWord)task->tso->id);
1447 return rtsTrue; // tells schedule() to return
1453 /* -----------------------------------------------------------------------------
1454 * Perform a heap census
1455 * -------------------------------------------------------------------------- */
1458 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1460 // When we have +RTS -i0 and we're heap profiling, do a census at
1461 // every GC. This lets us get repeatable runs for debugging.
1462 if (performHeapProfile ||
1463 (RtsFlags.ProfFlags.profileInterval==0 &&
1464 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1471 /* -----------------------------------------------------------------------------
1472 * Perform a garbage collection if necessary
1473 * -------------------------------------------------------------------------- */
1476 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1478 rtsBool heap_census;
1480 /* extern static volatile StgWord waiting_for_gc;
1481 lives inside capability.c */
1482 rtsBool was_waiting;
1486 if (sched_state == SCHED_SHUTTING_DOWN) {
1487 // The final GC has already been done, and the system is
1488 // shutting down. We'll probably deadlock if we try to GC
1494 // In order to GC, there must be no threads running Haskell code.
1495 // Therefore, the GC thread needs to hold *all* the capabilities,
1496 // and release them after the GC has completed.
1498 // This seems to be the simplest way: previous attempts involved
1499 // making all the threads with capabilities give up their
1500 // capabilities and sleep except for the *last* one, which
1501 // actually did the GC. But it's quite hard to arrange for all
1502 // the other tasks to sleep and stay asleep.
1505 /* Other capabilities are prevented from running yet more Haskell
1506 threads if waiting_for_gc is set. Tested inside
1507 yieldCapability() and releaseCapability() in Capability.c */
1509 was_waiting = cas(&waiting_for_gc, 0, 1);
1512 debugTrace(DEBUG_sched, "someone else is trying to GC...");
1513 if (cap) yieldCapability(&cap,task);
1514 } while (waiting_for_gc);
1515 return cap; // NOTE: task->cap might have changed here
1518 setContextSwitches();
1519 for (i=0; i < n_capabilities; i++) {
1520 debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1521 if (cap != &capabilities[i]) {
1522 Capability *pcap = &capabilities[i];
1523 // we better hope this task doesn't get migrated to
1524 // another Capability while we're waiting for this one.
1525 // It won't, because load balancing happens while we have
1526 // all the Capabilities, but even so it's a slightly
1527 // unsavoury invariant.
1529 waitForReturnCapability(&pcap, task);
1530 if (pcap != &capabilities[i]) {
1531 barf("scheduleDoGC: got the wrong capability");
1536 waiting_for_gc = rtsFalse;
1539 // so this happens periodically:
1540 if (cap) scheduleCheckBlackHoles(cap);
1542 IF_DEBUG(scheduler, printAllThreads());
1545 * We now have all the capabilities; if we're in an interrupting
1546 * state, then we should take the opportunity to delete all the
1547 * threads in the system.
1549 if (sched_state >= SCHED_INTERRUPTING) {
1550 deleteAllThreads(&capabilities[0]);
1551 sched_state = SCHED_SHUTTING_DOWN;
1554 heap_census = scheduleNeedHeapProfile(rtsTrue);
1556 /* everybody back, start the GC.
1557 * Could do it in this thread, or signal a condition var
1558 * to do it in another thread. Either way, we need to
1559 * broadcast on gc_pending_cond afterward.
1561 #if defined(THREADED_RTS)
1562 debugTrace(DEBUG_sched, "doing GC");
1564 GarbageCollect(force_major || heap_census);
1567 debugTrace(DEBUG_sched, "performing heap census");
1569 performHeapProfile = rtsFalse;
1574 Once we are all together... this would be the place to balance all
1575 spark pools. No concurrent stealing or adding of new sparks can
1576 occur. Should be defined in Sparks.c. */
1577 balanceSparkPoolsCaps(n_capabilities, capabilities);
1580 #if defined(THREADED_RTS)
1581 // release our stash of capabilities.
1582 for (i = 0; i < n_capabilities; i++) {
1583 if (cap != &capabilities[i]) {
1584 task->cap = &capabilities[i];
1585 releaseCapability(&capabilities[i]);
1598 /* ---------------------------------------------------------------------------
1599 * Singleton fork(). Do not copy any running threads.
1600 * ------------------------------------------------------------------------- */
1603 forkProcess(HsStablePtr *entry
1604 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1609 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1616 #if defined(THREADED_RTS)
1617 if (RtsFlags.ParFlags.nNodes > 1) {
1618 errorBelch("forking not supported with +RTS -N<n> greater than 1");
1619 stg_exit(EXIT_FAILURE);
1623 debugTrace(DEBUG_sched, "forking!");
1625 // ToDo: for SMP, we should probably acquire *all* the capabilities
1628 // no funny business: hold locks while we fork, otherwise if some
1629 // other thread is holding a lock when the fork happens, the data
1630 // structure protected by the lock will forever be in an
1631 // inconsistent state in the child. See also #1391.
1632 ACQUIRE_LOCK(&sched_mutex);
1633 ACQUIRE_LOCK(&cap->lock);
1634 ACQUIRE_LOCK(&cap->running_task->lock);
1638 if (pid) { // parent
1640 RELEASE_LOCK(&sched_mutex);
1641 RELEASE_LOCK(&cap->lock);
1642 RELEASE_LOCK(&cap->running_task->lock);
1644 // just return the pid
1650 #if defined(THREADED_RTS)
1651 initMutex(&sched_mutex);
1652 initMutex(&cap->lock);
1653 initMutex(&cap->running_task->lock);
1656 // Now, all OS threads except the thread that forked are
1657 // stopped. We need to stop all Haskell threads, including
1658 // those involved in foreign calls. Also we need to delete
1659 // all Tasks, because they correspond to OS threads that are
1662 for (s = 0; s < total_steps; s++) {
1663 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1664 if (t->what_next == ThreadRelocated) {
1667 next = t->global_link;
1668 // don't allow threads to catch the ThreadKilled
1669 // exception, but we do want to raiseAsync() because these
1670 // threads may be evaluating thunks that we need later.
1671 deleteThread_(cap,t);
1676 // Empty the run queue. It seems tempting to let all the
1677 // killed threads stay on the run queue as zombies to be
1678 // cleaned up later, but some of them correspond to bound
1679 // threads for which the corresponding Task does not exist.
1680 cap->run_queue_hd = END_TSO_QUEUE;
1681 cap->run_queue_tl = END_TSO_QUEUE;
1683 // Any suspended C-calling Tasks are no more, their OS threads
1685 cap->suspended_ccalling_tasks = NULL;
1687 // Empty the threads lists. Otherwise, the garbage
1688 // collector may attempt to resurrect some of these threads.
1689 for (s = 0; s < total_steps; s++) {
1690 all_steps[s].threads = END_TSO_QUEUE;
1693 // Wipe the task list, except the current Task.
1694 ACQUIRE_LOCK(&sched_mutex);
1695 for (task = all_tasks; task != NULL; task=task->all_link) {
1696 if (task != cap->running_task) {
1697 #if defined(THREADED_RTS)
1698 initMutex(&task->lock); // see #1391
1703 RELEASE_LOCK(&sched_mutex);
1705 #if defined(THREADED_RTS)
1706 // Wipe our spare workers list, they no longer exist. New
1707 // workers will be created if necessary.
1708 cap->spare_workers = NULL;
1709 cap->returning_tasks_hd = NULL;
1710 cap->returning_tasks_tl = NULL;
1713 // On Unix, all timers are reset in the child, so we need to start
1718 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1719 rts_checkSchedStatus("forkProcess",cap);
1722 hs_exit(); // clean up and exit
1723 stg_exit(EXIT_SUCCESS);
1725 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1726 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1731 /* ---------------------------------------------------------------------------
1732 * Delete all the threads in the system
1733 * ------------------------------------------------------------------------- */
1736 deleteAllThreads ( Capability *cap )
1738 // NOTE: only safe to call if we own all capabilities.
1743 debugTrace(DEBUG_sched,"deleting all threads");
1744 for (s = 0; s < total_steps; s++) {
1745 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1746 if (t->what_next == ThreadRelocated) {
1749 next = t->global_link;
1750 deleteThread(cap,t);
1755 // The run queue now contains a bunch of ThreadKilled threads. We
1756 // must not throw these away: the main thread(s) will be in there
1757 // somewhere, and the main scheduler loop has to deal with it.
1758 // Also, the run queue is the only thing keeping these threads from
1759 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1761 #if !defined(THREADED_RTS)
1762 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1763 ASSERT(sleeping_queue == END_TSO_QUEUE);
1767 /* -----------------------------------------------------------------------------
1768 Managing the suspended_ccalling_tasks list.
1769 Locks required: sched_mutex
1770 -------------------------------------------------------------------------- */
1773 suspendTask (Capability *cap, Task *task)
1775 ASSERT(task->next == NULL && task->prev == NULL);
1776 task->next = cap->suspended_ccalling_tasks;
1778 if (cap->suspended_ccalling_tasks) {
1779 cap->suspended_ccalling_tasks->prev = task;
1781 cap->suspended_ccalling_tasks = task;
1785 recoverSuspendedTask (Capability *cap, Task *task)
1788 task->prev->next = task->next;
1790 ASSERT(cap->suspended_ccalling_tasks == task);
1791 cap->suspended_ccalling_tasks = task->next;
1794 task->next->prev = task->prev;
1796 task->next = task->prev = NULL;
1799 /* ---------------------------------------------------------------------------
1800 * Suspending & resuming Haskell threads.
1802 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1803 * its capability before calling the C function. This allows another
1804 * task to pick up the capability and carry on running Haskell
1805 * threads. It also means that if the C call blocks, it won't lock
1808 * The Haskell thread making the C call is put to sleep for the
1809 * duration of the call, on the susepended_ccalling_threads queue. We
1810 * give out a token to the task, which it can use to resume the thread
1811 * on return from the C function.
1812 * ------------------------------------------------------------------------- */
1815 suspendThread (StgRegTable *reg)
1822 StgWord32 saved_winerror;
1825 saved_errno = errno;
1827 saved_winerror = GetLastError();
1830 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1832 cap = regTableToCapability(reg);
1834 task = cap->running_task;
1835 tso = cap->r.rCurrentTSO;
1837 debugTrace(DEBUG_sched,
1838 "thread %lu did a safe foreign call",
1839 (unsigned long)cap->r.rCurrentTSO->id);
1841 // XXX this might not be necessary --SDM
1842 tso->what_next = ThreadRunGHC;
1844 threadPaused(cap,tso);
1846 if ((tso->flags & TSO_BLOCKEX) == 0) {
1847 tso->why_blocked = BlockedOnCCall;
1848 tso->flags |= TSO_BLOCKEX;
1849 tso->flags &= ~TSO_INTERRUPTIBLE;
1851 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1854 // Hand back capability
1855 task->suspended_tso = tso;
1857 ACQUIRE_LOCK(&cap->lock);
1859 suspendTask(cap,task);
1860 cap->in_haskell = rtsFalse;
1861 releaseCapability_(cap,rtsFalse);
1863 RELEASE_LOCK(&cap->lock);
1865 #if defined(THREADED_RTS)
1866 /* Preparing to leave the RTS, so ensure there's a native thread/task
1867 waiting to take over.
1869 debugTrace(DEBUG_sched, "thread %lu: leaving RTS", (unsigned long)tso->id);
1872 errno = saved_errno;
1874 SetLastError(saved_winerror);
1880 resumeThread (void *task_)
1887 StgWord32 saved_winerror;
1890 saved_errno = errno;
1892 saved_winerror = GetLastError();
1896 // Wait for permission to re-enter the RTS with the result.
1897 waitForReturnCapability(&cap,task);
1898 // we might be on a different capability now... but if so, our
1899 // entry on the suspended_ccalling_tasks list will also have been
1902 // Remove the thread from the suspended list
1903 recoverSuspendedTask(cap,task);
1905 tso = task->suspended_tso;
1906 task->suspended_tso = NULL;
1907 tso->_link = END_TSO_QUEUE; // no write barrier reqd
1908 debugTrace(DEBUG_sched, "thread %lu: re-entering RTS", (unsigned long)tso->id);
1910 if (tso->why_blocked == BlockedOnCCall) {
1911 awakenBlockedExceptionQueue(cap,tso);
1912 tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
1915 /* Reset blocking status */
1916 tso->why_blocked = NotBlocked;
1918 cap->r.rCurrentTSO = tso;
1919 cap->in_haskell = rtsTrue;
1920 errno = saved_errno;
1922 SetLastError(saved_winerror);
1925 /* We might have GC'd, mark the TSO dirty again */
1928 IF_DEBUG(sanity, checkTSO(tso));
1933 /* ---------------------------------------------------------------------------
1936 * scheduleThread puts a thread on the end of the runnable queue.
1937 * This will usually be done immediately after a thread is created.
1938 * The caller of scheduleThread must create the thread using e.g.
1939 * createThread and push an appropriate closure
1940 * on this thread's stack before the scheduler is invoked.
1941 * ------------------------------------------------------------------------ */
1944 scheduleThread(Capability *cap, StgTSO *tso)
1946 // The thread goes at the *end* of the run-queue, to avoid possible
1947 // starvation of any threads already on the queue.
1948 appendToRunQueue(cap,tso);
1952 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
1954 #if defined(THREADED_RTS)
1955 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
1956 // move this thread from now on.
1957 cpu %= RtsFlags.ParFlags.nNodes;
1958 if (cpu == cap->no) {
1959 appendToRunQueue(cap,tso);
1961 wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
1964 appendToRunQueue(cap,tso);
1969 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
1973 // We already created/initialised the Task
1974 task = cap->running_task;
1976 // This TSO is now a bound thread; make the Task and TSO
1977 // point to each other.
1983 task->stat = NoStatus;
1985 appendToRunQueue(cap,tso);
1987 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)tso->id);
1989 cap = schedule(cap,task);
1991 ASSERT(task->stat != NoStatus);
1992 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
1994 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)task->tso->id);
1998 /* ----------------------------------------------------------------------------
2000 * ------------------------------------------------------------------------- */
2002 #if defined(THREADED_RTS)
2003 void OSThreadProcAttr
2004 workerStart(Task *task)
2008 // See startWorkerTask().
2009 ACQUIRE_LOCK(&task->lock);
2011 RELEASE_LOCK(&task->lock);
2013 // set the thread-local pointer to the Task:
2016 // schedule() runs without a lock.
2017 cap = schedule(cap,task);
2019 // On exit from schedule(), we have a Capability, but possibly not
2020 // the same one we started with.
2022 // During shutdown, the requirement is that after all the
2023 // Capabilities are shut down, all workers that are shutting down
2024 // have finished workerTaskStop(). This is why we hold on to
2025 // cap->lock until we've finished workerTaskStop() below.
2027 // There may be workers still involved in foreign calls; those
2028 // will just block in waitForReturnCapability() because the
2029 // Capability has been shut down.
2031 ACQUIRE_LOCK(&cap->lock);
2032 releaseCapability_(cap,rtsFalse);
2033 workerTaskStop(task);
2034 RELEASE_LOCK(&cap->lock);
2038 /* ---------------------------------------------------------------------------
2041 * Initialise the scheduler. This resets all the queues - if the
2042 * queues contained any threads, they'll be garbage collected at the
2045 * ------------------------------------------------------------------------ */
2050 #if !defined(THREADED_RTS)
2051 blocked_queue_hd = END_TSO_QUEUE;
2052 blocked_queue_tl = END_TSO_QUEUE;
2053 sleeping_queue = END_TSO_QUEUE;
2056 blackhole_queue = END_TSO_QUEUE;
2058 sched_state = SCHED_RUNNING;
2059 recent_activity = ACTIVITY_YES;
2061 #if defined(THREADED_RTS)
2062 /* Initialise the mutex and condition variables used by
2064 initMutex(&sched_mutex);
2067 ACQUIRE_LOCK(&sched_mutex);
2069 /* A capability holds the state a native thread needs in
2070 * order to execute STG code. At least one capability is
2071 * floating around (only THREADED_RTS builds have more than one).
2077 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
2081 #if defined(THREADED_RTS)
2083 * Eagerly start one worker to run each Capability, except for
2084 * Capability 0. The idea is that we're probably going to start a
2085 * bound thread on Capability 0 pretty soon, so we don't want a
2086 * worker task hogging it.
2091 for (i = 1; i < n_capabilities; i++) {
2092 cap = &capabilities[i];
2093 ACQUIRE_LOCK(&cap->lock);
2094 startWorkerTask(cap, workerStart);
2095 RELEASE_LOCK(&cap->lock);
2100 trace(TRACE_sched, "start: %d capabilities", n_capabilities);
2102 RELEASE_LOCK(&sched_mutex);
2107 rtsBool wait_foreign
2108 #if !defined(THREADED_RTS)
2109 __attribute__((unused))
2112 /* see Capability.c, shutdownCapability() */
2116 #if defined(THREADED_RTS)
2117 ACQUIRE_LOCK(&sched_mutex);
2118 task = newBoundTask();
2119 RELEASE_LOCK(&sched_mutex);
2122 // If we haven't killed all the threads yet, do it now.
2123 if (sched_state < SCHED_SHUTTING_DOWN) {
2124 sched_state = SCHED_INTERRUPTING;
2125 scheduleDoGC(NULL,task,rtsFalse);
2127 sched_state = SCHED_SHUTTING_DOWN;
2129 #if defined(THREADED_RTS)
2133 for (i = 0; i < n_capabilities; i++) {
2134 shutdownCapability(&capabilities[i], task, wait_foreign);
2136 boundTaskExiting(task);
2142 freeScheduler( void )
2146 ACQUIRE_LOCK(&sched_mutex);
2147 still_running = freeTaskManager();
2148 // We can only free the Capabilities if there are no Tasks still
2149 // running. We might have a Task about to return from a foreign
2150 // call into waitForReturnCapability(), for example (actually,
2151 // this should be the *only* thing that a still-running Task can
2152 // do at this point, and it will block waiting for the
2154 if (still_running == 0) {
2156 if (n_capabilities != 1) {
2157 stgFree(capabilities);
2160 RELEASE_LOCK(&sched_mutex);
2161 #if defined(THREADED_RTS)
2162 closeMutex(&sched_mutex);
2166 /* -----------------------------------------------------------------------------
2169 This is the interface to the garbage collector from Haskell land.
2170 We provide this so that external C code can allocate and garbage
2171 collect when called from Haskell via _ccall_GC.
2172 -------------------------------------------------------------------------- */
2175 performGC_(rtsBool force_major)
2178 // We must grab a new Task here, because the existing Task may be
2179 // associated with a particular Capability, and chained onto the
2180 // suspended_ccalling_tasks queue.
2181 ACQUIRE_LOCK(&sched_mutex);
2182 task = newBoundTask();
2183 RELEASE_LOCK(&sched_mutex);
2184 scheduleDoGC(NULL,task,force_major);
2185 boundTaskExiting(task);
2191 performGC_(rtsFalse);
2195 performMajorGC(void)
2197 performGC_(rtsTrue);
2200 /* -----------------------------------------------------------------------------
2203 If the thread has reached its maximum stack size, then raise the
2204 StackOverflow exception in the offending thread. Otherwise
2205 relocate the TSO into a larger chunk of memory and adjust its stack
2207 -------------------------------------------------------------------------- */
2210 threadStackOverflow(Capability *cap, StgTSO *tso)
2212 nat new_stack_size, stack_words;
2217 IF_DEBUG(sanity,checkTSO(tso));
2219 // don't allow throwTo() to modify the blocked_exceptions queue
2220 // while we are moving the TSO:
2221 lockClosure((StgClosure *)tso);
2223 if (tso->stack_size >= tso->max_stack_size && !(tso->flags & TSO_BLOCKEX)) {
2224 // NB. never raise a StackOverflow exception if the thread is
2225 // inside Control.Exceptino.block. It is impractical to protect
2226 // against stack overflow exceptions, since virtually anything
2227 // can raise one (even 'catch'), so this is the only sensible
2228 // thing to do here. See bug #767.
2230 debugTrace(DEBUG_gc,
2231 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2232 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2234 /* If we're debugging, just print out the top of the stack */
2235 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2238 // Send this thread the StackOverflow exception
2240 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2244 /* Try to double the current stack size. If that takes us over the
2245 * maximum stack size for this thread, then use the maximum instead
2246 * (that is, unless we're already at or over the max size and we
2247 * can't raise the StackOverflow exception (see above), in which
2248 * case just double the size). Finally round up so the TSO ends up as
2249 * a whole number of blocks.
2251 if (tso->stack_size >= tso->max_stack_size) {
2252 new_stack_size = tso->stack_size * 2;
2254 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2256 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2257 TSO_STRUCT_SIZE)/sizeof(W_);
2258 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2259 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2261 debugTrace(DEBUG_sched,
2262 "increasing stack size from %ld words to %d.",
2263 (long)tso->stack_size, new_stack_size);
2265 dest = (StgTSO *)allocateLocal(cap,new_tso_size);
2266 TICK_ALLOC_TSO(new_stack_size,0);
2268 /* copy the TSO block and the old stack into the new area */
2269 memcpy(dest,tso,TSO_STRUCT_SIZE);
2270 stack_words = tso->stack + tso->stack_size - tso->sp;
2271 new_sp = (P_)dest + new_tso_size - stack_words;
2272 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2274 /* relocate the stack pointers... */
2276 dest->stack_size = new_stack_size;
2278 /* Mark the old TSO as relocated. We have to check for relocated
2279 * TSOs in the garbage collector and any primops that deal with TSOs.
2281 * It's important to set the sp value to just beyond the end
2282 * of the stack, so we don't attempt to scavenge any part of the
2285 tso->what_next = ThreadRelocated;
2286 setTSOLink(cap,tso,dest);
2287 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2288 tso->why_blocked = NotBlocked;
2290 IF_PAR_DEBUG(verbose,
2291 debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2292 tso->id, tso, tso->stack_size);
2293 /* If we're debugging, just print out the top of the stack */
2294 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2300 IF_DEBUG(sanity,checkTSO(dest));
2302 IF_DEBUG(scheduler,printTSO(dest));
2309 threadStackUnderflow (Task *task STG_UNUSED, StgTSO *tso)
2311 bdescr *bd, *new_bd;
2312 lnat free_w, tso_size_w;
2315 tso_size_w = tso_sizeW(tso);
2317 if (tso_size_w < MBLOCK_SIZE_W ||
2318 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2323 // don't allow throwTo() to modify the blocked_exceptions queue
2324 // while we are moving the TSO:
2325 lockClosure((StgClosure *)tso);
2327 // this is the number of words we'll free
2328 free_w = round_to_mblocks(tso_size_w/2);
2330 bd = Bdescr((StgPtr)tso);
2331 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2332 bd->free = bd->start + TSO_STRUCT_SIZEW;
2334 new_tso = (StgTSO *)new_bd->start;
2335 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2336 new_tso->stack_size = new_bd->free - new_tso->stack;
2338 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2339 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2341 tso->what_next = ThreadRelocated;
2342 tso->_link = new_tso; // no write barrier reqd: same generation
2344 // The TSO attached to this Task may have moved, so update the
2346 if (task->tso == tso) {
2347 task->tso = new_tso;
2353 IF_DEBUG(sanity,checkTSO(new_tso));
2358 /* ---------------------------------------------------------------------------
2360 - usually called inside a signal handler so it mustn't do anything fancy.
2361 ------------------------------------------------------------------------ */
2364 interruptStgRts(void)
2366 sched_state = SCHED_INTERRUPTING;
2367 setContextSwitches();
2371 /* -----------------------------------------------------------------------------
2374 This function causes at least one OS thread to wake up and run the
2375 scheduler loop. It is invoked when the RTS might be deadlocked, or
2376 an external event has arrived that may need servicing (eg. a
2377 keyboard interrupt).
2379 In the single-threaded RTS we don't do anything here; we only have
2380 one thread anyway, and the event that caused us to want to wake up
2381 will have interrupted any blocking system call in progress anyway.
2382 -------------------------------------------------------------------------- */
2387 #if defined(THREADED_RTS)
2388 // This forces the IO Manager thread to wakeup, which will
2389 // in turn ensure that some OS thread wakes up and runs the
2390 // scheduler loop, which will cause a GC and deadlock check.
2395 /* -----------------------------------------------------------------------------
2398 * Check the blackhole_queue for threads that can be woken up. We do
2399 * this periodically: before every GC, and whenever the run queue is
2402 * An elegant solution might be to just wake up all the blocked
2403 * threads with awakenBlockedQueue occasionally: they'll go back to
2404 * sleep again if the object is still a BLACKHOLE. Unfortunately this
2405 * doesn't give us a way to tell whether we've actually managed to
2406 * wake up any threads, so we would be busy-waiting.
2408 * -------------------------------------------------------------------------- */
2411 checkBlackHoles (Capability *cap)
2414 rtsBool any_woke_up = rtsFalse;
2417 // blackhole_queue is global:
2418 ASSERT_LOCK_HELD(&sched_mutex);
2420 debugTrace(DEBUG_sched, "checking threads blocked on black holes");
2422 // ASSUMES: sched_mutex
2423 prev = &blackhole_queue;
2424 t = blackhole_queue;
2425 while (t != END_TSO_QUEUE) {
2426 ASSERT(t->why_blocked == BlockedOnBlackHole);
2427 type = get_itbl(UNTAG_CLOSURE(t->block_info.closure))->type;
2428 if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
2429 IF_DEBUG(sanity,checkTSO(t));
2430 t = unblockOne(cap, t);
2432 any_woke_up = rtsTrue;
2442 /* -----------------------------------------------------------------------------
2445 This is used for interruption (^C) and forking, and corresponds to
2446 raising an exception but without letting the thread catch the
2448 -------------------------------------------------------------------------- */
2451 deleteThread (Capability *cap, StgTSO *tso)
2453 // NOTE: must only be called on a TSO that we have exclusive
2454 // access to, because we will call throwToSingleThreaded() below.
2455 // The TSO must be on the run queue of the Capability we own, or
2456 // we must own all Capabilities.
2458 if (tso->why_blocked != BlockedOnCCall &&
2459 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2460 throwToSingleThreaded(cap,tso,NULL);
2464 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2466 deleteThread_(Capability *cap, StgTSO *tso)
2467 { // for forkProcess only:
2468 // like deleteThread(), but we delete threads in foreign calls, too.
2470 if (tso->why_blocked == BlockedOnCCall ||
2471 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2472 unblockOne(cap,tso);
2473 tso->what_next = ThreadKilled;
2475 deleteThread(cap,tso);
2480 /* -----------------------------------------------------------------------------
2481 raiseExceptionHelper
2483 This function is called by the raise# primitve, just so that we can
2484 move some of the tricky bits of raising an exception from C-- into
2485 C. Who knows, it might be a useful re-useable thing here too.
2486 -------------------------------------------------------------------------- */
2489 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2491 Capability *cap = regTableToCapability(reg);
2492 StgThunk *raise_closure = NULL;
2494 StgRetInfoTable *info;
2496 // This closure represents the expression 'raise# E' where E
2497 // is the exception raise. It is used to overwrite all the
2498 // thunks which are currently under evaluataion.
2501 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2502 // LDV profiling: stg_raise_info has THUNK as its closure
2503 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2504 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2505 // 1 does not cause any problem unless profiling is performed.
2506 // However, when LDV profiling goes on, we need to linearly scan
2507 // small object pool, where raise_closure is stored, so we should
2508 // use MIN_UPD_SIZE.
2510 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2511 // sizeofW(StgClosure)+1);
2515 // Walk up the stack, looking for the catch frame. On the way,
2516 // we update any closures pointed to from update frames with the
2517 // raise closure that we just built.
2521 info = get_ret_itbl((StgClosure *)p);
2522 next = p + stack_frame_sizeW((StgClosure *)p);
2523 switch (info->i.type) {
2526 // Only create raise_closure if we need to.
2527 if (raise_closure == NULL) {
2529 (StgThunk *)allocateLocal(cap,sizeofW(StgThunk)+1);
2530 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2531 raise_closure->payload[0] = exception;
2533 UPD_IND(((StgUpdateFrame *)p)->updatee,(StgClosure *)raise_closure);
2537 case ATOMICALLY_FRAME:
2538 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2540 return ATOMICALLY_FRAME;
2546 case CATCH_STM_FRAME:
2547 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2549 return CATCH_STM_FRAME;
2555 case CATCH_RETRY_FRAME:
2564 /* -----------------------------------------------------------------------------
2565 findRetryFrameHelper
2567 This function is called by the retry# primitive. It traverses the stack
2568 leaving tso->sp referring to the frame which should handle the retry.
2570 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2571 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2573 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2574 create) because retries are not considered to be exceptions, despite the
2575 similar implementation.
2577 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2578 not be created within memory transactions.
2579 -------------------------------------------------------------------------- */
2582 findRetryFrameHelper (StgTSO *tso)
2585 StgRetInfoTable *info;
2589 info = get_ret_itbl((StgClosure *)p);
2590 next = p + stack_frame_sizeW((StgClosure *)p);
2591 switch (info->i.type) {
2593 case ATOMICALLY_FRAME:
2594 debugTrace(DEBUG_stm,
2595 "found ATOMICALLY_FRAME at %p during retry", p);
2597 return ATOMICALLY_FRAME;
2599 case CATCH_RETRY_FRAME:
2600 debugTrace(DEBUG_stm,
2601 "found CATCH_RETRY_FRAME at %p during retrry", p);
2603 return CATCH_RETRY_FRAME;
2605 case CATCH_STM_FRAME: {
2606 StgTRecHeader *trec = tso -> trec;
2607 StgTRecHeader *outer = stmGetEnclosingTRec(trec);
2608 debugTrace(DEBUG_stm,
2609 "found CATCH_STM_FRAME at %p during retry", p);
2610 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2611 stmAbortTransaction(tso -> cap, trec);
2612 stmFreeAbortedTRec(tso -> cap, trec);
2613 tso -> trec = outer;
2620 ASSERT(info->i.type != CATCH_FRAME);
2621 ASSERT(info->i.type != STOP_FRAME);
2628 /* -----------------------------------------------------------------------------
2629 resurrectThreads is called after garbage collection on the list of
2630 threads found to be garbage. Each of these threads will be woken
2631 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2632 on an MVar, or NonTermination if the thread was blocked on a Black
2635 Locks: assumes we hold *all* the capabilities.
2636 -------------------------------------------------------------------------- */
2639 resurrectThreads (StgTSO *threads)
2645 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2646 next = tso->global_link;
2648 step = Bdescr((P_)tso)->step;
2649 tso->global_link = step->threads;
2650 step->threads = tso;
2652 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2654 // Wake up the thread on the Capability it was last on
2657 switch (tso->why_blocked) {
2659 case BlockedOnException:
2660 /* Called by GC - sched_mutex lock is currently held. */
2661 throwToSingleThreaded(cap, tso,
2662 (StgClosure *)blockedOnDeadMVar_closure);
2664 case BlockedOnBlackHole:
2665 throwToSingleThreaded(cap, tso,
2666 (StgClosure *)nonTermination_closure);
2669 throwToSingleThreaded(cap, tso,
2670 (StgClosure *)blockedIndefinitely_closure);
2673 /* This might happen if the thread was blocked on a black hole
2674 * belonging to a thread that we've just woken up (raiseAsync
2675 * can wake up threads, remember...).
2679 barf("resurrectThreads: thread blocked in a strange way");
2684 /* -----------------------------------------------------------------------------
2685 performPendingThrowTos is called after garbage collection, and
2686 passed a list of threads that were found to have pending throwTos
2687 (tso->blocked_exceptions was not empty), and were blocked.
2688 Normally this doesn't happen, because we would deliver the
2689 exception directly if the target thread is blocked, but there are
2690 small windows where it might occur on a multiprocessor (see
2693 NB. we must be holding all the capabilities at this point, just
2694 like resurrectThreads().
2695 -------------------------------------------------------------------------- */
2698 performPendingThrowTos (StgTSO *threads)
2704 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2705 next = tso->global_link;
2707 step = Bdescr((P_)tso)->step;
2708 tso->global_link = step->threads;
2709 step->threads = tso;
2711 debugTrace(DEBUG_sched, "performing blocked throwTo to thread %lu", (unsigned long)tso->id);
2714 maybePerformBlockedException(cap, tso);