1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2006
5 * The scheduler and thread-related functionality
7 * --------------------------------------------------------------------------*/
9 #include "PosixSource.h"
10 #define KEEP_LOCKCLOSURE
13 #include "sm/Storage.h"
17 #include "Interpreter.h"
19 #include "RtsSignals.h"
24 #include "ThreadLabels.h"
26 #include "Proftimer.h"
29 #include "sm/GC.h" // waitForGcThreads, releaseGCThreads, N
31 #include "Capability.h"
33 #include "AwaitEvent.h"
34 #if defined(mingw32_HOST_OS)
35 #include "win32/IOManager.h"
38 #include "RaiseAsync.h"
41 #include "ThreadPaused.h"
43 #ifdef HAVE_SYS_TYPES_H
44 #include <sys/types.h>
58 /* -----------------------------------------------------------------------------
60 * -------------------------------------------------------------------------- */
62 #if !defined(THREADED_RTS)
63 // Blocked/sleeping thrads
64 StgTSO *blocked_queue_hd = NULL;
65 StgTSO *blocked_queue_tl = NULL;
66 StgTSO *sleeping_queue = NULL; // perhaps replace with a hash table?
69 /* Threads blocked on blackholes.
70 * LOCK: sched_mutex+capability, or all capabilities
72 StgTSO *blackhole_queue = NULL;
74 /* The blackhole_queue should be checked for threads to wake up. See
75 * Schedule.h for more thorough comment.
76 * LOCK: none (doesn't matter if we miss an update)
78 rtsBool blackholes_need_checking = rtsFalse;
80 /* Set to true when the latest garbage collection failed to reclaim
81 * enough space, and the runtime should proceed to shut itself down in
82 * an orderly fashion (emitting profiling info etc.)
84 rtsBool heap_overflow = rtsFalse;
86 /* flag that tracks whether we have done any execution in this time slice.
87 * LOCK: currently none, perhaps we should lock (but needs to be
88 * updated in the fast path of the scheduler).
90 * NB. must be StgWord, we do xchg() on it.
92 volatile StgWord recent_activity = ACTIVITY_YES;
94 /* if this flag is set as well, give up execution
95 * LOCK: none (changes monotonically)
97 volatile StgWord sched_state = SCHED_RUNNING;
99 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
100 * exists - earlier gccs apparently didn't.
106 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
107 * in an MT setting, needed to signal that a worker thread shouldn't hang around
108 * in the scheduler when it is out of work.
110 rtsBool shutting_down_scheduler = rtsFalse;
113 * This mutex protects most of the global scheduler data in
114 * the THREADED_RTS runtime.
116 #if defined(THREADED_RTS)
120 #if !defined(mingw32_HOST_OS)
121 #define FORKPROCESS_PRIMOP_SUPPORTED
124 /* -----------------------------------------------------------------------------
125 * static function prototypes
126 * -------------------------------------------------------------------------- */
128 static Capability *schedule (Capability *initialCapability, Task *task);
131 // These function all encapsulate parts of the scheduler loop, and are
132 // abstracted only to make the structure and control flow of the
133 // scheduler clearer.
135 static void schedulePreLoop (void);
136 static void scheduleFindWork (Capability *cap);
137 #if defined(THREADED_RTS)
138 static void scheduleYield (Capability **pcap, Task *task, rtsBool);
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 static void schedulePushWork(Capability *cap, Task *task);
146 #if defined(THREADED_RTS)
147 static void scheduleActivateSpark(Capability *cap);
149 static void schedulePostRunThread(Capability *cap, StgTSO *t);
150 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
151 static void scheduleHandleStackOverflow( Capability *cap, Task *task,
153 static rtsBool scheduleHandleYield( Capability *cap, StgTSO *t,
154 nat prev_what_next );
155 static void scheduleHandleThreadBlocked( StgTSO *t );
156 static rtsBool scheduleHandleThreadFinished( Capability *cap, Task *task,
158 static rtsBool scheduleNeedHeapProfile(rtsBool ready_to_gc);
159 static Capability *scheduleDoGC(Capability *cap, Task *task,
160 rtsBool force_major);
162 static rtsBool checkBlackHoles(Capability *cap);
164 static StgTSO *threadStackOverflow(Capability *cap, StgTSO *tso);
165 static StgTSO *threadStackUnderflow(Task *task, StgTSO *tso);
167 static void deleteThread (Capability *cap, StgTSO *tso);
168 static void deleteAllThreads (Capability *cap);
170 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
171 static void deleteThread_(Capability *cap, StgTSO *tso);
174 /* -----------------------------------------------------------------------------
175 * Putting a thread on the run queue: different scheduling policies
176 * -------------------------------------------------------------------------- */
179 addToRunQueue( Capability *cap, StgTSO *t )
181 // this does round-robin scheduling; good for concurrency
182 appendToRunQueue(cap,t);
185 /* ---------------------------------------------------------------------------
186 Main scheduling loop.
188 We use round-robin scheduling, each thread returning to the
189 scheduler loop when one of these conditions is detected:
192 * timer expires (thread yields)
198 In a GranSim setup this loop iterates over the global event queue.
199 This revolves around the global event queue, which determines what
200 to do next. Therefore, it's more complicated than either the
201 concurrent or the parallel (GUM) setup.
202 This version has been entirely removed (JB 2008/08).
205 GUM iterates over incoming messages.
206 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
207 and sends out a fish whenever it has nothing to do; in-between
208 doing the actual reductions (shared code below) it processes the
209 incoming messages and deals with delayed operations
210 (see PendingFetches).
211 This is not the ugliest code you could imagine, but it's bloody close.
213 (JB 2008/08) This version was formerly indicated by a PP-Flag PAR,
214 now by PP-flag PARALLEL_HASKELL. The Eden RTS (in GHC-6.x) uses it,
215 as well as future GUM versions. This file has been refurbished to
216 only contain valid code, which is however incomplete, refers to
217 invalid includes etc.
219 ------------------------------------------------------------------------ */
222 schedule (Capability *initialCapability, Task *task)
226 StgThreadReturnCode ret;
229 #if defined(THREADED_RTS)
230 rtsBool first = rtsTrue;
231 rtsBool force_yield = rtsFalse;
234 cap = initialCapability;
236 // Pre-condition: this task owns initialCapability.
237 // The sched_mutex is *NOT* held
238 // NB. on return, we still hold a capability.
240 debugTrace (DEBUG_sched, "cap %d: schedule()", initialCapability->no);
244 // -----------------------------------------------------------
245 // Scheduler loop starts here:
249 // Check whether we have re-entered the RTS from Haskell without
250 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
252 if (cap->in_haskell) {
253 errorBelch("schedule: re-entered unsafely.\n"
254 " Perhaps a 'foreign import unsafe' should be 'safe'?");
255 stg_exit(EXIT_FAILURE);
258 // The interruption / shutdown sequence.
260 // In order to cleanly shut down the runtime, we want to:
261 // * make sure that all main threads return to their callers
262 // with the state 'Interrupted'.
263 // * clean up all OS threads assocated with the runtime
264 // * free all memory etc.
266 // So the sequence for ^C goes like this:
268 // * ^C handler sets sched_state := SCHED_INTERRUPTING and
269 // arranges for some Capability to wake up
271 // * all threads in the system are halted, and the zombies are
272 // placed on the run queue for cleaning up. We acquire all
273 // the capabilities in order to delete the threads, this is
274 // done by scheduleDoGC() for convenience (because GC already
275 // needs to acquire all the capabilities). We can't kill
276 // threads involved in foreign calls.
278 // * somebody calls shutdownHaskell(), which calls exitScheduler()
280 // * sched_state := SCHED_SHUTTING_DOWN
282 // * all workers exit when the run queue on their capability
283 // drains. All main threads will also exit when their TSO
284 // reaches the head of the run queue and they can return.
286 // * eventually all Capabilities will shut down, and the RTS can
289 // * We might be left with threads blocked in foreign calls,
290 // we should really attempt to kill these somehow (TODO);
292 switch (sched_state) {
295 case SCHED_INTERRUPTING:
296 debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
297 #if defined(THREADED_RTS)
298 discardSparksCap(cap);
300 /* scheduleDoGC() deletes all the threads */
301 cap = scheduleDoGC(cap,task,rtsFalse);
303 // after scheduleDoGC(), we must be shutting down. Either some
304 // other Capability did the final GC, or we did it above,
305 // either way we can fall through to the SCHED_SHUTTING_DOWN
307 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
310 case SCHED_SHUTTING_DOWN:
311 debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
312 // If we are a worker, just exit. If we're a bound thread
313 // then we will exit below when we've removed our TSO from
315 if (task->tso == NULL && emptyRunQueue(cap)) {
320 barf("sched_state: %d", sched_state);
323 scheduleFindWork(cap);
325 /* work pushing, currently relevant only for THREADED_RTS:
326 (pushes threads, wakes up idle capabilities for stealing) */
327 schedulePushWork(cap,task);
329 scheduleDetectDeadlock(cap,task);
331 #if defined(THREADED_RTS)
332 cap = task->cap; // reload cap, it might have changed
335 // Normally, the only way we can get here with no threads to
336 // run is if a keyboard interrupt received during
337 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
338 // Additionally, it is not fatal for the
339 // threaded RTS to reach here with no threads to run.
341 // win32: might be here due to awaitEvent() being abandoned
342 // as a result of a console event having been delivered.
344 #if defined(THREADED_RTS)
348 // // don't yield the first time, we want a chance to run this
349 // // thread for a bit, even if there are others banging at the
352 // ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
356 scheduleYield(&cap,task,force_yield);
357 force_yield = rtsFalse;
359 if (emptyRunQueue(cap)) continue; // look for work again
362 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
363 if ( emptyRunQueue(cap) ) {
364 ASSERT(sched_state >= SCHED_INTERRUPTING);
369 // Get a thread to run
371 t = popRunQueue(cap);
373 // Sanity check the thread we're about to run. This can be
374 // expensive if there is lots of thread switching going on...
375 IF_DEBUG(sanity,checkTSO(t));
377 #if defined(THREADED_RTS)
378 // Check whether we can run this thread in the current task.
379 // If not, we have to pass our capability to the right task.
381 Task *bound = t->bound;
385 // yes, the Haskell thread is bound to the current native thread
387 debugTrace(DEBUG_sched,
388 "thread %lu bound to another OS thread",
389 (unsigned long)t->id);
390 // no, bound to a different Haskell thread: pass to that thread
391 pushOnRunQueue(cap,t);
395 // The thread we want to run is unbound.
397 debugTrace(DEBUG_sched,
398 "this OS thread cannot run thread %lu",
399 (unsigned long)t->id);
400 // no, the current native thread is bound to a different
401 // Haskell thread, so pass it to any worker thread
402 pushOnRunQueue(cap,t);
409 // If we're shutting down, and this thread has not yet been
410 // killed, kill it now. This sometimes happens when a finalizer
411 // thread is created by the final GC, or a thread previously
412 // in a foreign call returns.
413 if (sched_state >= SCHED_INTERRUPTING &&
414 !(t->what_next == ThreadComplete || t->what_next == ThreadKilled)) {
418 /* context switches are initiated by the timer signal, unless
419 * the user specified "context switch as often as possible", with
422 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
423 && !emptyThreadQueues(cap)) {
424 cap->context_switch = 1;
429 // CurrentTSO is the thread to run. t might be different if we
430 // loop back to run_thread, so make sure to set CurrentTSO after
432 cap->r.rCurrentTSO = t;
434 startHeapProfTimer();
436 // Check for exceptions blocked on this thread
437 maybePerformBlockedException (cap, t);
439 // ----------------------------------------------------------------------
440 // Run the current thread
442 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
443 ASSERT(t->cap == cap);
444 ASSERT(t->bound ? t->bound->cap == cap : 1);
446 prev_what_next = t->what_next;
448 errno = t->saved_errno;
450 SetLastError(t->saved_winerror);
453 cap->in_haskell = rtsTrue;
457 #if defined(THREADED_RTS)
458 if (recent_activity == ACTIVITY_DONE_GC) {
459 // ACTIVITY_DONE_GC means we turned off the timer signal to
460 // conserve power (see #1623). Re-enable it here.
462 prev = xchg((P_)&recent_activity, ACTIVITY_YES);
463 if (prev == ACTIVITY_DONE_GC) {
467 recent_activity = ACTIVITY_YES;
471 traceSchedEvent(cap, EVENT_RUN_THREAD, t, 0);
473 switch (prev_what_next) {
477 /* Thread already finished, return to scheduler. */
478 ret = ThreadFinished;
484 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
485 cap = regTableToCapability(r);
490 case ThreadInterpret:
491 cap = interpretBCO(cap);
496 barf("schedule: invalid what_next field");
499 cap->in_haskell = rtsFalse;
501 // The TSO might have moved, eg. if it re-entered the RTS and a GC
502 // happened. So find the new location:
503 t = cap->r.rCurrentTSO;
505 // We have run some Haskell code: there might be blackhole-blocked
506 // threads to wake up now.
507 // Lock-free test here should be ok, we're just setting a flag.
508 if ( blackhole_queue != END_TSO_QUEUE ) {
509 blackholes_need_checking = rtsTrue;
512 // And save the current errno in this thread.
513 // XXX: possibly bogus for SMP because this thread might already
514 // be running again, see code below.
515 t->saved_errno = errno;
517 // Similarly for Windows error code
518 t->saved_winerror = GetLastError();
521 traceSchedEvent (cap, EVENT_STOP_THREAD, t, ret);
523 #if defined(THREADED_RTS)
524 // If ret is ThreadBlocked, and this Task is bound to the TSO that
525 // blocked, we are in limbo - the TSO is now owned by whatever it
526 // is blocked on, and may in fact already have been woken up,
527 // perhaps even on a different Capability. It may be the case
528 // that task->cap != cap. We better yield this Capability
529 // immediately and return to normaility.
530 if (ret == ThreadBlocked) {
531 force_yield = rtsTrue;
536 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
537 ASSERT(t->cap == cap);
539 // ----------------------------------------------------------------------
541 // Costs for the scheduler are assigned to CCS_SYSTEM
543 #if defined(PROFILING)
547 schedulePostRunThread(cap,t);
549 if (ret != StackOverflow) {
550 t = threadStackUnderflow(task,t);
553 ready_to_gc = rtsFalse;
557 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
561 scheduleHandleStackOverflow(cap,task,t);
565 if (scheduleHandleYield(cap, t, prev_what_next)) {
566 // shortcut for switching between compiler/interpreter:
572 scheduleHandleThreadBlocked(t);
576 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
577 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
581 barf("schedule: invalid thread return code %d", (int)ret);
584 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
585 cap = scheduleDoGC(cap,task,rtsFalse);
587 } /* end of while() */
590 /* ----------------------------------------------------------------------------
591 * Setting up the scheduler loop
592 * ------------------------------------------------------------------------- */
595 schedulePreLoop(void)
597 // initialisation for scheduler - what cannot go into initScheduler()
600 /* -----------------------------------------------------------------------------
603 * Search for work to do, and handle messages from elsewhere.
604 * -------------------------------------------------------------------------- */
607 scheduleFindWork (Capability *cap)
609 scheduleStartSignalHandlers(cap);
611 // Only check the black holes here if we've nothing else to do.
612 // During normal execution, the black hole list only gets checked
613 // at GC time, to avoid repeatedly traversing this possibly long
614 // list each time around the scheduler.
615 if (emptyRunQueue(cap)) { scheduleCheckBlackHoles(cap); }
617 scheduleCheckWakeupThreads(cap);
619 scheduleCheckBlockedThreads(cap);
621 #if defined(THREADED_RTS)
622 if (emptyRunQueue(cap)) { scheduleActivateSpark(cap); }
626 #if defined(THREADED_RTS)
627 STATIC_INLINE rtsBool
628 shouldYieldCapability (Capability *cap, Task *task)
630 // we need to yield this capability to someone else if..
631 // - another thread is initiating a GC
632 // - another Task is returning from a foreign call
633 // - the thread at the head of the run queue cannot be run
634 // by this Task (it is bound to another Task, or it is unbound
635 // and this task it bound).
636 return (waiting_for_gc ||
637 cap->returning_tasks_hd != NULL ||
638 (!emptyRunQueue(cap) && (task->tso == NULL
639 ? cap->run_queue_hd->bound != NULL
640 : cap->run_queue_hd->bound != task)));
643 // This is the single place where a Task goes to sleep. There are
644 // two reasons it might need to sleep:
645 // - there are no threads to run
646 // - we need to yield this Capability to someone else
647 // (see shouldYieldCapability())
649 // Careful: the scheduler loop is quite delicate. Make sure you run
650 // the tests in testsuite/concurrent (all ways) after modifying this,
651 // and also check the benchmarks in nofib/parallel for regressions.
654 scheduleYield (Capability **pcap, Task *task, rtsBool force_yield)
656 Capability *cap = *pcap;
658 // if we have work, and we don't need to give up the Capability, continue.
660 // The force_yield flag is used when a bound thread blocks. This
661 // is a particularly tricky situation: the current Task does not
662 // own the TSO any more, since it is on some queue somewhere, and
663 // might be woken up or manipulated by another thread at any time.
664 // The TSO and Task might be migrated to another Capability.
665 // Certain invariants might be in doubt, such as task->bound->cap
666 // == cap. We have to yield the current Capability immediately,
667 // no messing around.
670 !shouldYieldCapability(cap,task) &&
671 (!emptyRunQueue(cap) ||
672 !emptyWakeupQueue(cap) ||
673 blackholes_need_checking ||
674 sched_state >= SCHED_INTERRUPTING))
677 // otherwise yield (sleep), and keep yielding if necessary.
679 yieldCapability(&cap,task);
681 while (shouldYieldCapability(cap,task));
683 // note there may still be no threads on the run queue at this
684 // point, the caller has to check.
691 /* -----------------------------------------------------------------------------
694 * Push work to other Capabilities if we have some.
695 * -------------------------------------------------------------------------- */
698 schedulePushWork(Capability *cap USED_IF_THREADS,
699 Task *task USED_IF_THREADS)
701 /* following code not for PARALLEL_HASKELL. I kept the call general,
702 future GUM versions might use pushing in a distributed setup */
703 #if defined(THREADED_RTS)
705 Capability *free_caps[n_capabilities], *cap0;
708 // migration can be turned off with +RTS -qg
709 if (!RtsFlags.ParFlags.migrate) return;
711 // Check whether we have more threads on our run queue, or sparks
712 // in our pool, that we could hand to another Capability.
713 if (cap->run_queue_hd == END_TSO_QUEUE) {
714 if (sparkPoolSizeCap(cap) < 2) return;
716 if (cap->run_queue_hd->_link == END_TSO_QUEUE &&
717 sparkPoolSizeCap(cap) < 1) return;
720 // First grab as many free Capabilities as we can.
721 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
722 cap0 = &capabilities[i];
723 if (cap != cap0 && tryGrabCapability(cap0,task)) {
724 if (!emptyRunQueue(cap0) || cap->returning_tasks_hd != NULL) {
725 // it already has some work, we just grabbed it at
726 // the wrong moment. Or maybe it's deadlocked!
727 releaseCapability(cap0);
729 free_caps[n_free_caps++] = cap0;
734 // we now have n_free_caps free capabilities stashed in
735 // free_caps[]. Share our run queue equally with them. This is
736 // probably the simplest thing we could do; improvements we might
737 // want to do include:
739 // - giving high priority to moving relatively new threads, on
740 // the gournds that they haven't had time to build up a
741 // working set in the cache on this CPU/Capability.
743 // - giving low priority to moving long-lived threads
745 if (n_free_caps > 0) {
746 StgTSO *prev, *t, *next;
747 rtsBool pushed_to_all;
749 debugTrace(DEBUG_sched,
750 "cap %d: %s and %d free capabilities, sharing...",
752 (!emptyRunQueue(cap) && cap->run_queue_hd->_link != END_TSO_QUEUE)?
753 "excess threads on run queue":"sparks to share (>=2)",
757 pushed_to_all = rtsFalse;
759 if (cap->run_queue_hd != END_TSO_QUEUE) {
760 prev = cap->run_queue_hd;
762 prev->_link = END_TSO_QUEUE;
763 for (; t != END_TSO_QUEUE; t = next) {
765 t->_link = END_TSO_QUEUE;
766 if (t->what_next == ThreadRelocated
767 || t->bound == task // don't move my bound thread
768 || tsoLocked(t)) { // don't move a locked thread
769 setTSOLink(cap, prev, t);
771 } else if (i == n_free_caps) {
772 pushed_to_all = rtsTrue;
775 setTSOLink(cap, prev, t);
778 debugTrace(DEBUG_sched, "pushing thread %lu to capability %d", (unsigned long)t->id, free_caps[i]->no);
779 appendToRunQueue(free_caps[i],t);
781 traceSchedEvent (cap, EVENT_MIGRATE_THREAD, t, free_caps[i]->no);
783 if (t->bound) { t->bound->cap = free_caps[i]; }
784 t->cap = free_caps[i];
788 cap->run_queue_tl = prev;
792 /* JB I left this code in place, it would work but is not necessary */
794 // If there are some free capabilities that we didn't push any
795 // threads to, then try to push a spark to each one.
796 if (!pushed_to_all) {
798 // i is the next free capability to push to
799 for (; i < n_free_caps; i++) {
800 if (emptySparkPoolCap(free_caps[i])) {
801 spark = tryStealSpark(cap->sparks);
803 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
805 traceSchedEvent(free_caps[i], EVENT_STEAL_SPARK, t, cap->no);
807 newSpark(&(free_caps[i]->r), spark);
812 #endif /* SPARK_PUSHING */
814 // release the capabilities
815 for (i = 0; i < n_free_caps; i++) {
816 task->cap = free_caps[i];
817 releaseAndWakeupCapability(free_caps[i]);
820 task->cap = cap; // reset to point to our Capability.
822 #endif /* THREADED_RTS */
826 /* ----------------------------------------------------------------------------
827 * Start any pending signal handlers
828 * ------------------------------------------------------------------------- */
830 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
832 scheduleStartSignalHandlers(Capability *cap)
834 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
835 // safe outside the lock
836 startSignalHandlers(cap);
841 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
846 /* ----------------------------------------------------------------------------
847 * Check for blocked threads that can be woken up.
848 * ------------------------------------------------------------------------- */
851 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
853 #if !defined(THREADED_RTS)
855 // Check whether any waiting threads need to be woken up. If the
856 // run queue is empty, and there are no other tasks running, we
857 // can wait indefinitely for something to happen.
859 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
861 awaitEvent( emptyRunQueue(cap) && !blackholes_need_checking );
867 /* ----------------------------------------------------------------------------
868 * Check for threads woken up by other Capabilities
869 * ------------------------------------------------------------------------- */
872 scheduleCheckWakeupThreads(Capability *cap USED_IF_THREADS)
874 #if defined(THREADED_RTS)
875 // Any threads that were woken up by other Capabilities get
876 // appended to our run queue.
877 if (!emptyWakeupQueue(cap)) {
878 ACQUIRE_LOCK(&cap->lock);
879 if (emptyRunQueue(cap)) {
880 cap->run_queue_hd = cap->wakeup_queue_hd;
881 cap->run_queue_tl = cap->wakeup_queue_tl;
883 setTSOLink(cap, cap->run_queue_tl, cap->wakeup_queue_hd);
884 cap->run_queue_tl = cap->wakeup_queue_tl;
886 cap->wakeup_queue_hd = cap->wakeup_queue_tl = END_TSO_QUEUE;
887 RELEASE_LOCK(&cap->lock);
892 /* ----------------------------------------------------------------------------
893 * Check for threads blocked on BLACKHOLEs that can be woken up
894 * ------------------------------------------------------------------------- */
896 scheduleCheckBlackHoles (Capability *cap)
898 if ( blackholes_need_checking ) // check without the lock first
900 ACQUIRE_LOCK(&sched_mutex);
901 if ( blackholes_need_checking ) {
902 blackholes_need_checking = rtsFalse;
903 // important that we reset the flag *before* checking the
904 // blackhole queue, otherwise we could get deadlock. This
905 // happens as follows: we wake up a thread that
906 // immediately runs on another Capability, blocks on a
907 // blackhole, and then we reset the blackholes_need_checking flag.
908 checkBlackHoles(cap);
910 RELEASE_LOCK(&sched_mutex);
914 /* ----------------------------------------------------------------------------
915 * Detect deadlock conditions and attempt to resolve them.
916 * ------------------------------------------------------------------------- */
919 scheduleDetectDeadlock (Capability *cap, Task *task)
922 * Detect deadlock: when we have no threads to run, there are no
923 * threads blocked, waiting for I/O, or sleeping, and all the
924 * other tasks are waiting for work, we must have a deadlock of
927 if ( emptyThreadQueues(cap) )
929 #if defined(THREADED_RTS)
931 * In the threaded RTS, we only check for deadlock if there
932 * has been no activity in a complete timeslice. This means
933 * we won't eagerly start a full GC just because we don't have
934 * any threads to run currently.
936 if (recent_activity != ACTIVITY_INACTIVE) return;
939 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
941 // Garbage collection can release some new threads due to
942 // either (a) finalizers or (b) threads resurrected because
943 // they are unreachable and will therefore be sent an
944 // exception. Any threads thus released will be immediately
946 cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
947 // when force_major == rtsTrue. scheduleDoGC sets
948 // recent_activity to ACTIVITY_DONE_GC and turns off the timer
951 if ( !emptyRunQueue(cap) ) return;
953 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
954 /* If we have user-installed signal handlers, then wait
955 * for signals to arrive rather then bombing out with a
958 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
959 debugTrace(DEBUG_sched,
960 "still deadlocked, waiting for signals...");
964 if (signals_pending()) {
965 startSignalHandlers(cap);
968 // either we have threads to run, or we were interrupted:
969 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
975 #if !defined(THREADED_RTS)
976 /* Probably a real deadlock. Send the current main thread the
977 * Deadlock exception.
980 switch (task->tso->why_blocked) {
982 case BlockedOnBlackHole:
983 case BlockedOnException:
985 throwToSingleThreaded(cap, task->tso,
986 (StgClosure *)nonTermination_closure);
989 barf("deadlock: main thread blocked in a strange way");
998 /* ----------------------------------------------------------------------------
999 * Send pending messages (PARALLEL_HASKELL only)
1000 * ------------------------------------------------------------------------- */
1002 #if defined(PARALLEL_HASKELL)
1004 scheduleSendPendingMessages(void)
1007 # if defined(PAR) // global Mem.Mgmt., omit for now
1008 if (PendingFetches != END_BF_QUEUE) {
1013 if (RtsFlags.ParFlags.BufferTime) {
1014 // if we use message buffering, we must send away all message
1015 // packets which have become too old...
1021 /* ----------------------------------------------------------------------------
1022 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
1023 * ------------------------------------------------------------------------- */
1025 #if defined(THREADED_RTS)
1027 scheduleActivateSpark(Capability *cap)
1031 createSparkThread(cap);
1032 debugTrace(DEBUG_sched, "creating a spark thread");
1035 #endif // PARALLEL_HASKELL || THREADED_RTS
1037 /* ----------------------------------------------------------------------------
1038 * After running a thread...
1039 * ------------------------------------------------------------------------- */
1042 schedulePostRunThread (Capability *cap, StgTSO *t)
1044 // We have to be able to catch transactions that are in an
1045 // infinite loop as a result of seeing an inconsistent view of
1049 // [a,b] <- mapM readTVar [ta,tb]
1050 // when (a == b) loop
1052 // and a is never equal to b given a consistent view of memory.
1054 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1055 if (!stmValidateNestOfTransactions (t -> trec)) {
1056 debugTrace(DEBUG_sched | DEBUG_stm,
1057 "trec %p found wasting its time", t);
1059 // strip the stack back to the
1060 // ATOMICALLY_FRAME, aborting the (nested)
1061 // transaction, and saving the stack of any
1062 // partially-evaluated thunks on the heap.
1063 throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1065 // ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1069 /* some statistics gathering in the parallel case */
1072 /* -----------------------------------------------------------------------------
1073 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1074 * -------------------------------------------------------------------------- */
1077 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1079 // did the task ask for a large block?
1080 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1081 // if so, get one and push it on the front of the nursery.
1085 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1087 debugTrace(DEBUG_sched,
1088 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1089 (long)t->id, what_next_strs[t->what_next], blocks);
1091 // don't do this if the nursery is (nearly) full, we'll GC first.
1092 if (cap->r.rCurrentNursery->link != NULL ||
1093 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1094 // if the nursery has only one block.
1097 bd = allocGroup( blocks );
1099 cap->r.rNursery->n_blocks += blocks;
1101 // link the new group into the list
1102 bd->link = cap->r.rCurrentNursery;
1103 bd->u.back = cap->r.rCurrentNursery->u.back;
1104 if (cap->r.rCurrentNursery->u.back != NULL) {
1105 cap->r.rCurrentNursery->u.back->link = bd;
1107 cap->r.rNursery->blocks = bd;
1109 cap->r.rCurrentNursery->u.back = bd;
1111 // initialise it as a nursery block. We initialise the
1112 // step, gen_no, and flags field of *every* sub-block in
1113 // this large block, because this is easier than making
1114 // sure that we always find the block head of a large
1115 // block whenever we call Bdescr() (eg. evacuate() and
1116 // isAlive() in the GC would both have to do this, at
1120 for (x = bd; x < bd + blocks; x++) {
1121 x->step = cap->r.rNursery;
1127 // This assert can be a killer if the app is doing lots
1128 // of large block allocations.
1129 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1131 // now update the nursery to point to the new block
1132 cap->r.rCurrentNursery = bd;
1134 // we might be unlucky and have another thread get on the
1135 // run queue before us and steal the large block, but in that
1136 // case the thread will just end up requesting another large
1138 pushOnRunQueue(cap,t);
1139 return rtsFalse; /* not actually GC'ing */
1143 if (cap->r.rHpLim == NULL || cap->context_switch) {
1144 // Sometimes we miss a context switch, e.g. when calling
1145 // primitives in a tight loop, MAYBE_GC() doesn't check the
1146 // context switch flag, and we end up waiting for a GC.
1147 // See #1984, and concurrent/should_run/1984
1148 cap->context_switch = 0;
1149 addToRunQueue(cap,t);
1151 pushOnRunQueue(cap,t);
1154 /* actual GC is done at the end of the while loop in schedule() */
1157 /* -----------------------------------------------------------------------------
1158 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1159 * -------------------------------------------------------------------------- */
1162 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1164 /* just adjust the stack for this thread, then pop it back
1168 /* enlarge the stack */
1169 StgTSO *new_t = threadStackOverflow(cap, t);
1171 /* The TSO attached to this Task may have moved, so update the
1174 if (task->tso == t) {
1177 pushOnRunQueue(cap,new_t);
1181 /* -----------------------------------------------------------------------------
1182 * Handle a thread that returned to the scheduler with ThreadYielding
1183 * -------------------------------------------------------------------------- */
1186 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1188 // Reset the context switch flag. We don't do this just before
1189 // running the thread, because that would mean we would lose ticks
1190 // during GC, which can lead to unfair scheduling (a thread hogs
1191 // the CPU because the tick always arrives during GC). This way
1192 // penalises threads that do a lot of allocation, but that seems
1193 // better than the alternative.
1194 cap->context_switch = 0;
1196 /* put the thread back on the run queue. Then, if we're ready to
1197 * GC, check whether this is the last task to stop. If so, wake
1198 * up the GC thread. getThread will block during a GC until the
1202 if (t->what_next != prev_what_next) {
1203 debugTrace(DEBUG_sched,
1204 "--<< thread %ld (%s) stopped to switch evaluators",
1205 (long)t->id, what_next_strs[t->what_next]);
1210 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1212 ASSERT(t->_link == END_TSO_QUEUE);
1214 // Shortcut if we're just switching evaluators: don't bother
1215 // doing stack squeezing (which can be expensive), just run the
1217 if (t->what_next != prev_what_next) {
1221 addToRunQueue(cap,t);
1226 /* -----------------------------------------------------------------------------
1227 * Handle a thread that returned to the scheduler with ThreadBlocked
1228 * -------------------------------------------------------------------------- */
1231 scheduleHandleThreadBlocked( StgTSO *t
1238 // We don't need to do anything. The thread is blocked, and it
1239 // has tidied up its stack and placed itself on whatever queue
1240 // it needs to be on.
1242 // ASSERT(t->why_blocked != NotBlocked);
1243 // Not true: for example,
1244 // - in THREADED_RTS, the thread may already have been woken
1245 // up by another Capability. This actually happens: try
1246 // conc023 +RTS -N2.
1247 // - the thread may have woken itself up already, because
1248 // threadPaused() might have raised a blocked throwTo
1249 // exception, see maybePerformBlockedException().
1252 traceThreadStatus(DEBUG_sched, t);
1256 /* -----------------------------------------------------------------------------
1257 * Handle a thread that returned to the scheduler with ThreadFinished
1258 * -------------------------------------------------------------------------- */
1261 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1263 /* Need to check whether this was a main thread, and if so,
1264 * return with the return value.
1266 * We also end up here if the thread kills itself with an
1267 * uncaught exception, see Exception.cmm.
1270 // blocked exceptions can now complete, even if the thread was in
1271 // blocked mode (see #2910). This unconditionally calls
1272 // lockTSO(), which ensures that we don't miss any threads that
1273 // are engaged in throwTo() with this thread as a target.
1274 awakenBlockedExceptionQueue (cap, t);
1277 // Check whether the thread that just completed was a bound
1278 // thread, and if so return with the result.
1280 // There is an assumption here that all thread completion goes
1281 // through this point; we need to make sure that if a thread
1282 // ends up in the ThreadKilled state, that it stays on the run
1283 // queue so it can be dealt with here.
1288 if (t->bound != task) {
1289 #if !defined(THREADED_RTS)
1290 // Must be a bound thread that is not the topmost one. Leave
1291 // it on the run queue until the stack has unwound to the
1292 // point where we can deal with this. Leaving it on the run
1293 // queue also ensures that the garbage collector knows about
1294 // this thread and its return value (it gets dropped from the
1295 // step->threads list so there's no other way to find it).
1296 appendToRunQueue(cap,t);
1299 // this cannot happen in the threaded RTS, because a
1300 // bound thread can only be run by the appropriate Task.
1301 barf("finished bound thread that isn't mine");
1305 ASSERT(task->tso == t);
1307 if (t->what_next == ThreadComplete) {
1309 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1310 *(task->ret) = (StgClosure *)task->tso->sp[1];
1312 task->stat = Success;
1315 *(task->ret) = NULL;
1317 if (sched_state >= SCHED_INTERRUPTING) {
1318 if (heap_overflow) {
1319 task->stat = HeapExhausted;
1321 task->stat = Interrupted;
1324 task->stat = Killed;
1328 removeThreadLabel((StgWord)task->tso->id);
1330 return rtsTrue; // tells schedule() to return
1336 /* -----------------------------------------------------------------------------
1337 * Perform a heap census
1338 * -------------------------------------------------------------------------- */
1341 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1343 // When we have +RTS -i0 and we're heap profiling, do a census at
1344 // every GC. This lets us get repeatable runs for debugging.
1345 if (performHeapProfile ||
1346 (RtsFlags.ProfFlags.profileInterval==0 &&
1347 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1354 /* -----------------------------------------------------------------------------
1355 * Perform a garbage collection if necessary
1356 * -------------------------------------------------------------------------- */
1359 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1361 rtsBool heap_census;
1363 /* extern static volatile StgWord waiting_for_gc;
1364 lives inside capability.c */
1365 rtsBool gc_type, prev_pending_gc;
1369 if (sched_state == SCHED_SHUTTING_DOWN) {
1370 // The final GC has already been done, and the system is
1371 // shutting down. We'll probably deadlock if we try to GC
1377 if (sched_state < SCHED_INTERRUPTING
1378 && RtsFlags.ParFlags.parGcEnabled
1379 && N >= RtsFlags.ParFlags.parGcGen
1380 && ! oldest_gen->steps[0].mark)
1382 gc_type = PENDING_GC_PAR;
1384 gc_type = PENDING_GC_SEQ;
1387 // In order to GC, there must be no threads running Haskell code.
1388 // Therefore, the GC thread needs to hold *all* the capabilities,
1389 // and release them after the GC has completed.
1391 // This seems to be the simplest way: previous attempts involved
1392 // making all the threads with capabilities give up their
1393 // capabilities and sleep except for the *last* one, which
1394 // actually did the GC. But it's quite hard to arrange for all
1395 // the other tasks to sleep and stay asleep.
1398 /* Other capabilities are prevented from running yet more Haskell
1399 threads if waiting_for_gc is set. Tested inside
1400 yieldCapability() and releaseCapability() in Capability.c */
1402 prev_pending_gc = cas(&waiting_for_gc, 0, gc_type);
1403 if (prev_pending_gc) {
1405 debugTrace(DEBUG_sched, "someone else is trying to GC (%d)...",
1408 yieldCapability(&cap,task);
1409 } while (waiting_for_gc);
1410 return cap; // NOTE: task->cap might have changed here
1413 setContextSwitches();
1415 // The final shutdown GC is always single-threaded, because it's
1416 // possible that some of the Capabilities have no worker threads.
1418 if (gc_type == PENDING_GC_SEQ)
1420 traceSchedEvent(cap, EVENT_REQUEST_SEQ_GC, 0, 0);
1424 traceSchedEvent(cap, EVENT_REQUEST_PAR_GC, 0, 0);
1425 debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1428 // do this while the other Capabilities stop:
1429 if (cap) scheduleCheckBlackHoles(cap);
1431 if (gc_type == PENDING_GC_SEQ)
1433 // single-threaded GC: grab all the capabilities
1434 for (i=0; i < n_capabilities; i++) {
1435 debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1436 if (cap != &capabilities[i]) {
1437 Capability *pcap = &capabilities[i];
1438 // we better hope this task doesn't get migrated to
1439 // another Capability while we're waiting for this one.
1440 // It won't, because load balancing happens while we have
1441 // all the Capabilities, but even so it's a slightly
1442 // unsavoury invariant.
1444 waitForReturnCapability(&pcap, task);
1445 if (pcap != &capabilities[i]) {
1446 barf("scheduleDoGC: got the wrong capability");
1453 // multi-threaded GC: make sure all the Capabilities donate one
1455 waitForGcThreads(cap);
1459 IF_DEBUG(scheduler, printAllThreads());
1461 delete_threads_and_gc:
1463 * We now have all the capabilities; if we're in an interrupting
1464 * state, then we should take the opportunity to delete all the
1465 * threads in the system.
1467 if (sched_state == SCHED_INTERRUPTING) {
1468 deleteAllThreads(cap);
1469 sched_state = SCHED_SHUTTING_DOWN;
1472 heap_census = scheduleNeedHeapProfile(rtsTrue);
1474 #if defined(THREADED_RTS)
1475 traceSchedEvent(cap, EVENT_GC_START, 0, 0);
1476 // reset waiting_for_gc *before* GC, so that when the GC threads
1477 // emerge they don't immediately re-enter the GC.
1479 GarbageCollect(force_major || heap_census, gc_type, cap);
1481 GarbageCollect(force_major || heap_census, 0, cap);
1483 traceSchedEvent(cap, EVENT_GC_END, 0, 0);
1485 if (recent_activity == ACTIVITY_INACTIVE && force_major)
1487 // We are doing a GC because the system has been idle for a
1488 // timeslice and we need to check for deadlock. Record the
1489 // fact that we've done a GC and turn off the timer signal;
1490 // it will get re-enabled if we run any threads after the GC.
1491 recent_activity = ACTIVITY_DONE_GC;
1496 // the GC might have taken long enough for the timer to set
1497 // recent_activity = ACTIVITY_INACTIVE, but we aren't
1498 // necessarily deadlocked:
1499 recent_activity = ACTIVITY_YES;
1502 #if defined(THREADED_RTS)
1503 if (gc_type == PENDING_GC_PAR)
1505 releaseGCThreads(cap);
1510 debugTrace(DEBUG_sched, "performing heap census");
1512 performHeapProfile = rtsFalse;
1515 if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1516 // GC set the heap_overflow flag, so we should proceed with
1517 // an orderly shutdown now. Ultimately we want the main
1518 // thread to return to its caller with HeapExhausted, at which
1519 // point the caller should call hs_exit(). The first step is
1520 // to delete all the threads.
1522 // Another way to do this would be to raise an exception in
1523 // the main thread, which we really should do because it gives
1524 // the program a chance to clean up. But how do we find the
1525 // main thread? It should presumably be the same one that
1526 // gets ^C exceptions, but that's all done on the Haskell side
1527 // (GHC.TopHandler).
1528 sched_state = SCHED_INTERRUPTING;
1529 goto delete_threads_and_gc;
1534 Once we are all together... this would be the place to balance all
1535 spark pools. No concurrent stealing or adding of new sparks can
1536 occur. Should be defined in Sparks.c. */
1537 balanceSparkPoolsCaps(n_capabilities, capabilities);
1540 #if defined(THREADED_RTS)
1541 if (gc_type == PENDING_GC_SEQ) {
1542 // release our stash of capabilities.
1543 for (i = 0; i < n_capabilities; i++) {
1544 if (cap != &capabilities[i]) {
1545 task->cap = &capabilities[i];
1546 releaseCapability(&capabilities[i]);
1560 /* ---------------------------------------------------------------------------
1561 * Singleton fork(). Do not copy any running threads.
1562 * ------------------------------------------------------------------------- */
1565 forkProcess(HsStablePtr *entry
1566 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1571 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1578 #if defined(THREADED_RTS)
1579 if (RtsFlags.ParFlags.nNodes > 1) {
1580 errorBelch("forking not supported with +RTS -N<n> greater than 1");
1581 stg_exit(EXIT_FAILURE);
1585 debugTrace(DEBUG_sched, "forking!");
1587 // ToDo: for SMP, we should probably acquire *all* the capabilities
1590 // no funny business: hold locks while we fork, otherwise if some
1591 // other thread is holding a lock when the fork happens, the data
1592 // structure protected by the lock will forever be in an
1593 // inconsistent state in the child. See also #1391.
1594 ACQUIRE_LOCK(&sched_mutex);
1595 ACQUIRE_LOCK(&cap->lock);
1596 ACQUIRE_LOCK(&cap->running_task->lock);
1600 if (pid) { // parent
1602 RELEASE_LOCK(&sched_mutex);
1603 RELEASE_LOCK(&cap->lock);
1604 RELEASE_LOCK(&cap->running_task->lock);
1606 // just return the pid
1612 #if defined(THREADED_RTS)
1613 initMutex(&sched_mutex);
1614 initMutex(&cap->lock);
1615 initMutex(&cap->running_task->lock);
1618 // Now, all OS threads except the thread that forked are
1619 // stopped. We need to stop all Haskell threads, including
1620 // those involved in foreign calls. Also we need to delete
1621 // all Tasks, because they correspond to OS threads that are
1624 for (s = 0; s < total_steps; s++) {
1625 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1626 if (t->what_next == ThreadRelocated) {
1629 next = t->global_link;
1630 // don't allow threads to catch the ThreadKilled
1631 // exception, but we do want to raiseAsync() because these
1632 // threads may be evaluating thunks that we need later.
1633 deleteThread_(cap,t);
1638 // Empty the run queue. It seems tempting to let all the
1639 // killed threads stay on the run queue as zombies to be
1640 // cleaned up later, but some of them correspond to bound
1641 // threads for which the corresponding Task does not exist.
1642 cap->run_queue_hd = END_TSO_QUEUE;
1643 cap->run_queue_tl = END_TSO_QUEUE;
1645 // Any suspended C-calling Tasks are no more, their OS threads
1647 cap->suspended_ccalling_tasks = NULL;
1649 // Empty the threads lists. Otherwise, the garbage
1650 // collector may attempt to resurrect some of these threads.
1651 for (s = 0; s < total_steps; s++) {
1652 all_steps[s].threads = END_TSO_QUEUE;
1655 // Wipe the task list, except the current Task.
1656 ACQUIRE_LOCK(&sched_mutex);
1657 for (task = all_tasks; task != NULL; task=task->all_link) {
1658 if (task != cap->running_task) {
1659 #if defined(THREADED_RTS)
1660 initMutex(&task->lock); // see #1391
1665 RELEASE_LOCK(&sched_mutex);
1667 #if defined(THREADED_RTS)
1668 // Wipe our spare workers list, they no longer exist. New
1669 // workers will be created if necessary.
1670 cap->spare_workers = NULL;
1671 cap->returning_tasks_hd = NULL;
1672 cap->returning_tasks_tl = NULL;
1675 // On Unix, all timers are reset in the child, so we need to start
1680 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1681 rts_checkSchedStatus("forkProcess",cap);
1684 hs_exit(); // clean up and exit
1685 stg_exit(EXIT_SUCCESS);
1687 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1688 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1692 /* ---------------------------------------------------------------------------
1693 * Delete all the threads in the system
1694 * ------------------------------------------------------------------------- */
1697 deleteAllThreads ( Capability *cap )
1699 // NOTE: only safe to call if we own all capabilities.
1704 debugTrace(DEBUG_sched,"deleting all threads");
1705 for (s = 0; s < total_steps; s++) {
1706 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1707 if (t->what_next == ThreadRelocated) {
1710 next = t->global_link;
1711 deleteThread(cap,t);
1716 // The run queue now contains a bunch of ThreadKilled threads. We
1717 // must not throw these away: the main thread(s) will be in there
1718 // somewhere, and the main scheduler loop has to deal with it.
1719 // Also, the run queue is the only thing keeping these threads from
1720 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1722 #if !defined(THREADED_RTS)
1723 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1724 ASSERT(sleeping_queue == END_TSO_QUEUE);
1728 /* -----------------------------------------------------------------------------
1729 Managing the suspended_ccalling_tasks list.
1730 Locks required: sched_mutex
1731 -------------------------------------------------------------------------- */
1734 suspendTask (Capability *cap, Task *task)
1736 ASSERT(task->next == NULL && task->prev == NULL);
1737 task->next = cap->suspended_ccalling_tasks;
1739 if (cap->suspended_ccalling_tasks) {
1740 cap->suspended_ccalling_tasks->prev = task;
1742 cap->suspended_ccalling_tasks = task;
1746 recoverSuspendedTask (Capability *cap, Task *task)
1749 task->prev->next = task->next;
1751 ASSERT(cap->suspended_ccalling_tasks == task);
1752 cap->suspended_ccalling_tasks = task->next;
1755 task->next->prev = task->prev;
1757 task->next = task->prev = NULL;
1760 /* ---------------------------------------------------------------------------
1761 * Suspending & resuming Haskell threads.
1763 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1764 * its capability before calling the C function. This allows another
1765 * task to pick up the capability and carry on running Haskell
1766 * threads. It also means that if the C call blocks, it won't lock
1769 * The Haskell thread making the C call is put to sleep for the
1770 * duration of the call, on the susepended_ccalling_threads queue. We
1771 * give out a token to the task, which it can use to resume the thread
1772 * on return from the C function.
1773 * ------------------------------------------------------------------------- */
1776 suspendThread (StgRegTable *reg)
1783 StgWord32 saved_winerror;
1786 saved_errno = errno;
1788 saved_winerror = GetLastError();
1791 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1793 cap = regTableToCapability(reg);
1795 task = cap->running_task;
1796 tso = cap->r.rCurrentTSO;
1798 traceSchedEvent(cap, EVENT_STOP_THREAD, tso, THREAD_SUSPENDED_FOREIGN_CALL);
1800 // XXX this might not be necessary --SDM
1801 tso->what_next = ThreadRunGHC;
1803 threadPaused(cap,tso);
1805 if ((tso->flags & TSO_BLOCKEX) == 0) {
1806 tso->why_blocked = BlockedOnCCall;
1807 tso->flags |= TSO_BLOCKEX;
1808 tso->flags &= ~TSO_INTERRUPTIBLE;
1810 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1813 // Hand back capability
1814 task->suspended_tso = tso;
1816 ACQUIRE_LOCK(&cap->lock);
1818 suspendTask(cap,task);
1819 cap->in_haskell = rtsFalse;
1820 releaseCapability_(cap,rtsFalse);
1822 RELEASE_LOCK(&cap->lock);
1824 errno = saved_errno;
1826 SetLastError(saved_winerror);
1832 resumeThread (void *task_)
1839 StgWord32 saved_winerror;
1842 saved_errno = errno;
1844 saved_winerror = GetLastError();
1848 // Wait for permission to re-enter the RTS with the result.
1849 waitForReturnCapability(&cap,task);
1850 // we might be on a different capability now... but if so, our
1851 // entry on the suspended_ccalling_tasks list will also have been
1854 // Remove the thread from the suspended list
1855 recoverSuspendedTask(cap,task);
1857 tso = task->suspended_tso;
1858 task->suspended_tso = NULL;
1859 tso->_link = END_TSO_QUEUE; // no write barrier reqd
1861 traceSchedEvent(cap, EVENT_RUN_THREAD, tso, tso->what_next);
1863 if (tso->why_blocked == BlockedOnCCall) {
1864 // avoid locking the TSO if we don't have to
1865 if (tso->blocked_exceptions != END_TSO_QUEUE) {
1866 awakenBlockedExceptionQueue(cap,tso);
1868 tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
1871 /* Reset blocking status */
1872 tso->why_blocked = NotBlocked;
1874 cap->r.rCurrentTSO = tso;
1875 cap->in_haskell = rtsTrue;
1876 errno = saved_errno;
1878 SetLastError(saved_winerror);
1881 /* We might have GC'd, mark the TSO dirty again */
1884 IF_DEBUG(sanity, checkTSO(tso));
1889 /* ---------------------------------------------------------------------------
1892 * scheduleThread puts a thread on the end of the runnable queue.
1893 * This will usually be done immediately after a thread is created.
1894 * The caller of scheduleThread must create the thread using e.g.
1895 * createThread and push an appropriate closure
1896 * on this thread's stack before the scheduler is invoked.
1897 * ------------------------------------------------------------------------ */
1900 scheduleThread(Capability *cap, StgTSO *tso)
1902 // The thread goes at the *end* of the run-queue, to avoid possible
1903 // starvation of any threads already on the queue.
1904 appendToRunQueue(cap,tso);
1908 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
1910 #if defined(THREADED_RTS)
1911 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
1912 // move this thread from now on.
1913 cpu %= RtsFlags.ParFlags.nNodes;
1914 if (cpu == cap->no) {
1915 appendToRunQueue(cap,tso);
1917 traceSchedEvent (cap, EVENT_MIGRATE_THREAD, tso, capabilities[cpu].no);
1918 wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
1921 appendToRunQueue(cap,tso);
1926 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
1930 // We already created/initialised the Task
1931 task = cap->running_task;
1933 // This TSO is now a bound thread; make the Task and TSO
1934 // point to each other.
1940 task->stat = NoStatus;
1942 appendToRunQueue(cap,tso);
1944 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)tso->id);
1946 cap = schedule(cap,task);
1948 ASSERT(task->stat != NoStatus);
1949 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
1951 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)task->tso->id);
1955 /* ----------------------------------------------------------------------------
1957 * ------------------------------------------------------------------------- */
1959 #if defined(THREADED_RTS)
1960 void OSThreadProcAttr
1961 workerStart(Task *task)
1965 // See startWorkerTask().
1966 ACQUIRE_LOCK(&task->lock);
1968 RELEASE_LOCK(&task->lock);
1970 if (RtsFlags.ParFlags.setAffinity) {
1971 setThreadAffinity(cap->no, n_capabilities);
1974 // set the thread-local pointer to the Task:
1977 // schedule() runs without a lock.
1978 cap = schedule(cap,task);
1980 // On exit from schedule(), we have a Capability, but possibly not
1981 // the same one we started with.
1983 // During shutdown, the requirement is that after all the
1984 // Capabilities are shut down, all workers that are shutting down
1985 // have finished workerTaskStop(). This is why we hold on to
1986 // cap->lock until we've finished workerTaskStop() below.
1988 // There may be workers still involved in foreign calls; those
1989 // will just block in waitForReturnCapability() because the
1990 // Capability has been shut down.
1992 ACQUIRE_LOCK(&cap->lock);
1993 releaseCapability_(cap,rtsFalse);
1994 workerTaskStop(task);
1995 RELEASE_LOCK(&cap->lock);
1999 /* ---------------------------------------------------------------------------
2002 * Initialise the scheduler. This resets all the queues - if the
2003 * queues contained any threads, they'll be garbage collected at the
2006 * ------------------------------------------------------------------------ */
2011 #if !defined(THREADED_RTS)
2012 blocked_queue_hd = END_TSO_QUEUE;
2013 blocked_queue_tl = END_TSO_QUEUE;
2014 sleeping_queue = END_TSO_QUEUE;
2017 blackhole_queue = END_TSO_QUEUE;
2019 sched_state = SCHED_RUNNING;
2020 recent_activity = ACTIVITY_YES;
2022 #if defined(THREADED_RTS)
2023 /* Initialise the mutex and condition variables used by
2025 initMutex(&sched_mutex);
2028 ACQUIRE_LOCK(&sched_mutex);
2030 /* A capability holds the state a native thread needs in
2031 * order to execute STG code. At least one capability is
2032 * floating around (only THREADED_RTS builds have more than one).
2038 #if defined(THREADED_RTS)
2042 #if defined(THREADED_RTS)
2044 * Eagerly start one worker to run each Capability, except for
2045 * Capability 0. The idea is that we're probably going to start a
2046 * bound thread on Capability 0 pretty soon, so we don't want a
2047 * worker task hogging it.
2052 for (i = 1; i < n_capabilities; i++) {
2053 cap = &capabilities[i];
2054 ACQUIRE_LOCK(&cap->lock);
2055 startWorkerTask(cap, workerStart);
2056 RELEASE_LOCK(&cap->lock);
2061 RELEASE_LOCK(&sched_mutex);
2066 rtsBool wait_foreign
2067 #if !defined(THREADED_RTS)
2068 __attribute__((unused))
2071 /* see Capability.c, shutdownCapability() */
2075 task = newBoundTask();
2077 // If we haven't killed all the threads yet, do it now.
2078 if (sched_state < SCHED_SHUTTING_DOWN) {
2079 sched_state = SCHED_INTERRUPTING;
2080 waitForReturnCapability(&task->cap,task);
2081 scheduleDoGC(task->cap,task,rtsFalse);
2082 releaseCapability(task->cap);
2084 sched_state = SCHED_SHUTTING_DOWN;
2086 #if defined(THREADED_RTS)
2090 for (i = 0; i < n_capabilities; i++) {
2091 shutdownCapability(&capabilities[i], task, wait_foreign);
2093 boundTaskExiting(task);
2099 freeScheduler( void )
2103 ACQUIRE_LOCK(&sched_mutex);
2104 still_running = freeTaskManager();
2105 // We can only free the Capabilities if there are no Tasks still
2106 // running. We might have a Task about to return from a foreign
2107 // call into waitForReturnCapability(), for example (actually,
2108 // this should be the *only* thing that a still-running Task can
2109 // do at this point, and it will block waiting for the
2111 if (still_running == 0) {
2113 if (n_capabilities != 1) {
2114 stgFree(capabilities);
2117 RELEASE_LOCK(&sched_mutex);
2118 #if defined(THREADED_RTS)
2119 closeMutex(&sched_mutex);
2123 /* -----------------------------------------------------------------------------
2126 This is the interface to the garbage collector from Haskell land.
2127 We provide this so that external C code can allocate and garbage
2128 collect when called from Haskell via _ccall_GC.
2129 -------------------------------------------------------------------------- */
2132 performGC_(rtsBool force_major)
2136 // We must grab a new Task here, because the existing Task may be
2137 // associated with a particular Capability, and chained onto the
2138 // suspended_ccalling_tasks queue.
2139 task = newBoundTask();
2141 waitForReturnCapability(&task->cap,task);
2142 scheduleDoGC(task->cap,task,force_major);
2143 releaseCapability(task->cap);
2144 boundTaskExiting(task);
2150 performGC_(rtsFalse);
2154 performMajorGC(void)
2156 performGC_(rtsTrue);
2159 /* -----------------------------------------------------------------------------
2162 If the thread has reached its maximum stack size, then raise the
2163 StackOverflow exception in the offending thread. Otherwise
2164 relocate the TSO into a larger chunk of memory and adjust its stack
2166 -------------------------------------------------------------------------- */
2169 threadStackOverflow(Capability *cap, StgTSO *tso)
2171 nat new_stack_size, stack_words;
2176 IF_DEBUG(sanity,checkTSO(tso));
2178 // don't allow throwTo() to modify the blocked_exceptions queue
2179 // while we are moving the TSO:
2180 lockClosure((StgClosure *)tso);
2182 if (tso->stack_size >= tso->max_stack_size && !(tso->flags & TSO_BLOCKEX)) {
2183 // NB. never raise a StackOverflow exception if the thread is
2184 // inside Control.Exceptino.block. It is impractical to protect
2185 // against stack overflow exceptions, since virtually anything
2186 // can raise one (even 'catch'), so this is the only sensible
2187 // thing to do here. See bug #767.
2189 debugTrace(DEBUG_gc,
2190 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2191 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2193 /* If we're debugging, just print out the top of the stack */
2194 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2197 // Send this thread the StackOverflow exception
2199 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2203 /* Try to double the current stack size. If that takes us over the
2204 * maximum stack size for this thread, then use the maximum instead
2205 * (that is, unless we're already at or over the max size and we
2206 * can't raise the StackOverflow exception (see above), in which
2207 * case just double the size). Finally round up so the TSO ends up as
2208 * a whole number of blocks.
2210 if (tso->stack_size >= tso->max_stack_size) {
2211 new_stack_size = tso->stack_size * 2;
2213 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2215 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2216 TSO_STRUCT_SIZE)/sizeof(W_);
2217 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2218 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2220 debugTrace(DEBUG_sched,
2221 "increasing stack size from %ld words to %d.",
2222 (long)tso->stack_size, new_stack_size);
2224 dest = (StgTSO *)allocateLocal(cap,new_tso_size);
2225 TICK_ALLOC_TSO(new_stack_size,0);
2227 /* copy the TSO block and the old stack into the new area */
2228 memcpy(dest,tso,TSO_STRUCT_SIZE);
2229 stack_words = tso->stack + tso->stack_size - tso->sp;
2230 new_sp = (P_)dest + new_tso_size - stack_words;
2231 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2233 /* relocate the stack pointers... */
2235 dest->stack_size = new_stack_size;
2237 /* Mark the old TSO as relocated. We have to check for relocated
2238 * TSOs in the garbage collector and any primops that deal with TSOs.
2240 * It's important to set the sp value to just beyond the end
2241 * of the stack, so we don't attempt to scavenge any part of the
2244 tso->what_next = ThreadRelocated;
2245 setTSOLink(cap,tso,dest);
2246 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2247 tso->why_blocked = NotBlocked;
2252 IF_DEBUG(sanity,checkTSO(dest));
2254 IF_DEBUG(scheduler,printTSO(dest));
2261 threadStackUnderflow (Task *task STG_UNUSED, StgTSO *tso)
2263 bdescr *bd, *new_bd;
2264 lnat free_w, tso_size_w;
2267 tso_size_w = tso_sizeW(tso);
2269 if (tso_size_w < MBLOCK_SIZE_W ||
2270 // TSO is less than 2 mblocks (since the first mblock is
2271 // shorter than MBLOCK_SIZE_W)
2272 (tso_size_w - BLOCKS_PER_MBLOCK*BLOCK_SIZE_W) % MBLOCK_SIZE_W != 0 ||
2273 // or TSO is not a whole number of megablocks (ensuring
2274 // precondition of splitLargeBlock() below)
2275 (tso_size_w <= round_up_to_mblocks(RtsFlags.GcFlags.initialStkSize)) ||
2276 // or TSO is smaller than the minimum stack size (rounded up)
2277 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2278 // or stack is using more than 1/4 of the available space
2284 // don't allow throwTo() to modify the blocked_exceptions queue
2285 // while we are moving the TSO:
2286 lockClosure((StgClosure *)tso);
2288 // this is the number of words we'll free
2289 free_w = round_to_mblocks(tso_size_w/2);
2291 bd = Bdescr((StgPtr)tso);
2292 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2293 bd->free = bd->start + TSO_STRUCT_SIZEW;
2295 new_tso = (StgTSO *)new_bd->start;
2296 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2297 new_tso->stack_size = new_bd->free - new_tso->stack;
2299 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2300 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2302 tso->what_next = ThreadRelocated;
2303 tso->_link = new_tso; // no write barrier reqd: same generation
2305 // The TSO attached to this Task may have moved, so update the
2307 if (task->tso == tso) {
2308 task->tso = new_tso;
2314 IF_DEBUG(sanity,checkTSO(new_tso));
2319 /* ---------------------------------------------------------------------------
2321 - usually called inside a signal handler so it mustn't do anything fancy.
2322 ------------------------------------------------------------------------ */
2325 interruptStgRts(void)
2327 sched_state = SCHED_INTERRUPTING;
2328 setContextSwitches();
2329 #if defined(THREADED_RTS)
2334 /* -----------------------------------------------------------------------------
2337 This function causes at least one OS thread to wake up and run the
2338 scheduler loop. It is invoked when the RTS might be deadlocked, or
2339 an external event has arrived that may need servicing (eg. a
2340 keyboard interrupt).
2342 In the single-threaded RTS we don't do anything here; we only have
2343 one thread anyway, and the event that caused us to want to wake up
2344 will have interrupted any blocking system call in progress anyway.
2345 -------------------------------------------------------------------------- */
2347 #if defined(THREADED_RTS)
2348 void wakeUpRts(void)
2350 // This forces the IO Manager thread to wakeup, which will
2351 // in turn ensure that some OS thread wakes up and runs the
2352 // scheduler loop, which will cause a GC and deadlock check.
2357 /* -----------------------------------------------------------------------------
2360 * Check the blackhole_queue for threads that can be woken up. We do
2361 * this periodically: before every GC, and whenever the run queue is
2364 * An elegant solution might be to just wake up all the blocked
2365 * threads with awakenBlockedQueue occasionally: they'll go back to
2366 * sleep again if the object is still a BLACKHOLE. Unfortunately this
2367 * doesn't give us a way to tell whether we've actually managed to
2368 * wake up any threads, so we would be busy-waiting.
2370 * -------------------------------------------------------------------------- */
2373 checkBlackHoles (Capability *cap)
2376 rtsBool any_woke_up = rtsFalse;
2379 // blackhole_queue is global:
2380 ASSERT_LOCK_HELD(&sched_mutex);
2382 debugTrace(DEBUG_sched, "checking threads blocked on black holes");
2384 // ASSUMES: sched_mutex
2385 prev = &blackhole_queue;
2386 t = blackhole_queue;
2387 while (t != END_TSO_QUEUE) {
2388 if (t->what_next == ThreadRelocated) {
2392 ASSERT(t->why_blocked == BlockedOnBlackHole);
2393 type = get_itbl(UNTAG_CLOSURE(t->block_info.closure))->type;
2394 if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
2395 IF_DEBUG(sanity,checkTSO(t));
2396 t = unblockOne(cap, t);
2398 any_woke_up = rtsTrue;
2408 /* -----------------------------------------------------------------------------
2411 This is used for interruption (^C) and forking, and corresponds to
2412 raising an exception but without letting the thread catch the
2414 -------------------------------------------------------------------------- */
2417 deleteThread (Capability *cap, StgTSO *tso)
2419 // NOTE: must only be called on a TSO that we have exclusive
2420 // access to, because we will call throwToSingleThreaded() below.
2421 // The TSO must be on the run queue of the Capability we own, or
2422 // we must own all Capabilities.
2424 if (tso->why_blocked != BlockedOnCCall &&
2425 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2426 throwToSingleThreaded(cap,tso,NULL);
2430 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2432 deleteThread_(Capability *cap, StgTSO *tso)
2433 { // for forkProcess only:
2434 // like deleteThread(), but we delete threads in foreign calls, too.
2436 if (tso->why_blocked == BlockedOnCCall ||
2437 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2438 unblockOne(cap,tso);
2439 tso->what_next = ThreadKilled;
2441 deleteThread(cap,tso);
2446 /* -----------------------------------------------------------------------------
2447 raiseExceptionHelper
2449 This function is called by the raise# primitve, just so that we can
2450 move some of the tricky bits of raising an exception from C-- into
2451 C. Who knows, it might be a useful re-useable thing here too.
2452 -------------------------------------------------------------------------- */
2455 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2457 Capability *cap = regTableToCapability(reg);
2458 StgThunk *raise_closure = NULL;
2460 StgRetInfoTable *info;
2462 // This closure represents the expression 'raise# E' where E
2463 // is the exception raise. It is used to overwrite all the
2464 // thunks which are currently under evaluataion.
2467 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2468 // LDV profiling: stg_raise_info has THUNK as its closure
2469 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2470 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2471 // 1 does not cause any problem unless profiling is performed.
2472 // However, when LDV profiling goes on, we need to linearly scan
2473 // small object pool, where raise_closure is stored, so we should
2474 // use MIN_UPD_SIZE.
2476 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2477 // sizeofW(StgClosure)+1);
2481 // Walk up the stack, looking for the catch frame. On the way,
2482 // we update any closures pointed to from update frames with the
2483 // raise closure that we just built.
2487 info = get_ret_itbl((StgClosure *)p);
2488 next = p + stack_frame_sizeW((StgClosure *)p);
2489 switch (info->i.type) {
2492 // Only create raise_closure if we need to.
2493 if (raise_closure == NULL) {
2495 (StgThunk *)allocateLocal(cap,sizeofW(StgThunk)+1);
2496 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2497 raise_closure->payload[0] = exception;
2499 UPD_IND(((StgUpdateFrame *)p)->updatee,(StgClosure *)raise_closure);
2503 case ATOMICALLY_FRAME:
2504 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2506 return ATOMICALLY_FRAME;
2512 case CATCH_STM_FRAME:
2513 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2515 return CATCH_STM_FRAME;
2521 case CATCH_RETRY_FRAME:
2530 /* -----------------------------------------------------------------------------
2531 findRetryFrameHelper
2533 This function is called by the retry# primitive. It traverses the stack
2534 leaving tso->sp referring to the frame which should handle the retry.
2536 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2537 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2539 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2540 create) because retries are not considered to be exceptions, despite the
2541 similar implementation.
2543 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2544 not be created within memory transactions.
2545 -------------------------------------------------------------------------- */
2548 findRetryFrameHelper (StgTSO *tso)
2551 StgRetInfoTable *info;
2555 info = get_ret_itbl((StgClosure *)p);
2556 next = p + stack_frame_sizeW((StgClosure *)p);
2557 switch (info->i.type) {
2559 case ATOMICALLY_FRAME:
2560 debugTrace(DEBUG_stm,
2561 "found ATOMICALLY_FRAME at %p during retry", p);
2563 return ATOMICALLY_FRAME;
2565 case CATCH_RETRY_FRAME:
2566 debugTrace(DEBUG_stm,
2567 "found CATCH_RETRY_FRAME at %p during retrry", p);
2569 return CATCH_RETRY_FRAME;
2571 case CATCH_STM_FRAME: {
2572 StgTRecHeader *trec = tso -> trec;
2573 StgTRecHeader *outer = trec -> enclosing_trec;
2574 debugTrace(DEBUG_stm,
2575 "found CATCH_STM_FRAME at %p during retry", p);
2576 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2577 stmAbortTransaction(tso -> cap, trec);
2578 stmFreeAbortedTRec(tso -> cap, trec);
2579 tso -> trec = outer;
2586 ASSERT(info->i.type != CATCH_FRAME);
2587 ASSERT(info->i.type != STOP_FRAME);
2594 /* -----------------------------------------------------------------------------
2595 resurrectThreads is called after garbage collection on the list of
2596 threads found to be garbage. Each of these threads will be woken
2597 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2598 on an MVar, or NonTermination if the thread was blocked on a Black
2601 Locks: assumes we hold *all* the capabilities.
2602 -------------------------------------------------------------------------- */
2605 resurrectThreads (StgTSO *threads)
2611 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2612 next = tso->global_link;
2614 step = Bdescr((P_)tso)->step;
2615 tso->global_link = step->threads;
2616 step->threads = tso;
2618 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2620 // Wake up the thread on the Capability it was last on
2623 switch (tso->why_blocked) {
2625 /* Called by GC - sched_mutex lock is currently held. */
2626 throwToSingleThreaded(cap, tso,
2627 (StgClosure *)blockedIndefinitelyOnMVar_closure);
2629 case BlockedOnBlackHole:
2630 throwToSingleThreaded(cap, tso,
2631 (StgClosure *)nonTermination_closure);
2634 throwToSingleThreaded(cap, tso,
2635 (StgClosure *)blockedIndefinitelyOnSTM_closure);
2638 /* This might happen if the thread was blocked on a black hole
2639 * belonging to a thread that we've just woken up (raiseAsync
2640 * can wake up threads, remember...).
2643 case BlockedOnException:
2644 // throwTo should never block indefinitely: if the target
2645 // thread dies or completes, throwTo returns.
2646 barf("resurrectThreads: thread BlockedOnException");
2649 barf("resurrectThreads: thread blocked in a strange way");
2654 /* -----------------------------------------------------------------------------
2655 performPendingThrowTos is called after garbage collection, and
2656 passed a list of threads that were found to have pending throwTos
2657 (tso->blocked_exceptions was not empty), and were blocked.
2658 Normally this doesn't happen, because we would deliver the
2659 exception directly if the target thread is blocked, but there are
2660 small windows where it might occur on a multiprocessor (see
2663 NB. we must be holding all the capabilities at this point, just
2664 like resurrectThreads().
2665 -------------------------------------------------------------------------- */
2668 performPendingThrowTos (StgTSO *threads)
2672 Task *task, *saved_task;;
2678 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2679 next = tso->global_link;
2681 step = Bdescr((P_)tso)->step;
2682 tso->global_link = step->threads;
2683 step->threads = tso;
2685 debugTrace(DEBUG_sched, "performing blocked throwTo to thread %lu", (unsigned long)tso->id);
2687 // We must pretend this Capability belongs to the current Task
2688 // for the time being, as invariants will be broken otherwise.
2689 // In fact the current Task has exclusive access to the systme
2690 // at this point, so this is just bookkeeping:
2691 task->cap = tso->cap;
2692 saved_task = tso->cap->running_task;
2693 tso->cap->running_task = task;
2694 maybePerformBlockedException(tso->cap, tso);
2695 tso->cap->running_task = saved_task;
2698 // Restore our original Capability: