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"
38 /* PARALLEL_HASKELL includes go here */
41 #include "Capability.h"
43 #include "AwaitEvent.h"
44 #if defined(mingw32_HOST_OS)
45 #include "win32/IOManager.h"
48 #include "RaiseAsync.h"
50 #include "ThrIOManager.h"
52 #ifdef HAVE_SYS_TYPES_H
53 #include <sys/types.h>
67 // Turn off inlining when debugging - it obfuscates things
70 # define STATIC_INLINE static
73 /* -----------------------------------------------------------------------------
75 * -------------------------------------------------------------------------- */
77 #if !defined(THREADED_RTS)
78 // Blocked/sleeping thrads
79 StgTSO *blocked_queue_hd = NULL;
80 StgTSO *blocked_queue_tl = NULL;
81 StgTSO *sleeping_queue = NULL; // perhaps replace with a hash table?
84 /* Threads blocked on blackholes.
85 * LOCK: sched_mutex+capability, or all capabilities
87 StgTSO *blackhole_queue = NULL;
89 /* The blackhole_queue should be checked for threads to wake up. See
90 * Schedule.h for more thorough comment.
91 * LOCK: none (doesn't matter if we miss an update)
93 rtsBool blackholes_need_checking = rtsFalse;
95 /* Set to true when the latest garbage collection failed to reclaim
96 * enough space, and the runtime should proceed to shut itself down in
97 * an orderly fashion (emitting profiling info etc.)
99 rtsBool heap_overflow = rtsFalse;
101 /* flag that tracks whether we have done any execution in this time slice.
102 * LOCK: currently none, perhaps we should lock (but needs to be
103 * updated in the fast path of the scheduler).
105 * NB. must be StgWord, we do xchg() on it.
107 volatile StgWord recent_activity = ACTIVITY_YES;
109 /* if this flag is set as well, give up execution
110 * LOCK: none (changes monotonically)
112 volatile StgWord sched_state = SCHED_RUNNING;
114 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
115 * exists - earlier gccs apparently didn't.
121 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
122 * in an MT setting, needed to signal that a worker thread shouldn't hang around
123 * in the scheduler when it is out of work.
125 rtsBool shutting_down_scheduler = rtsFalse;
128 * This mutex protects most of the global scheduler data in
129 * the THREADED_RTS runtime.
131 #if defined(THREADED_RTS)
135 #if !defined(mingw32_HOST_OS)
136 #define FORKPROCESS_PRIMOP_SUPPORTED
139 /* -----------------------------------------------------------------------------
140 * static function prototypes
141 * -------------------------------------------------------------------------- */
143 static Capability *schedule (Capability *initialCapability, Task *task);
146 // These function all encapsulate parts of the scheduler loop, and are
147 // abstracted only to make the structure and control flow of the
148 // scheduler clearer.
150 static void schedulePreLoop (void);
151 static void scheduleFindWork (Capability *cap);
152 #if defined(THREADED_RTS)
153 static void scheduleYield (Capability **pcap, Task *task);
155 static void scheduleStartSignalHandlers (Capability *cap);
156 static void scheduleCheckBlockedThreads (Capability *cap);
157 static void scheduleCheckWakeupThreads(Capability *cap USED_IF_NOT_THREADS);
158 static void scheduleCheckBlackHoles (Capability *cap);
159 static void scheduleDetectDeadlock (Capability *cap, Task *task);
160 static void schedulePushWork(Capability *cap, Task *task);
161 #if defined(PARALLEL_HASKELL)
162 static rtsBool scheduleGetRemoteWork(Capability *cap);
163 static void scheduleSendPendingMessages(void);
165 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
166 static void scheduleActivateSpark(Capability *cap);
168 static void schedulePostRunThread(Capability *cap, StgTSO *t);
169 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
170 static void scheduleHandleStackOverflow( Capability *cap, Task *task,
172 static rtsBool scheduleHandleYield( Capability *cap, StgTSO *t,
173 nat prev_what_next );
174 static void scheduleHandleThreadBlocked( StgTSO *t );
175 static rtsBool scheduleHandleThreadFinished( Capability *cap, Task *task,
177 static rtsBool scheduleNeedHeapProfile(rtsBool ready_to_gc);
178 static Capability *scheduleDoGC(Capability *cap, Task *task,
179 rtsBool force_major);
181 static rtsBool checkBlackHoles(Capability *cap);
183 static StgTSO *threadStackOverflow(Capability *cap, StgTSO *tso);
184 static StgTSO *threadStackUnderflow(Task *task, StgTSO *tso);
186 static void deleteThread (Capability *cap, StgTSO *tso);
187 static void deleteAllThreads (Capability *cap);
189 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
190 static void deleteThread_(Capability *cap, StgTSO *tso);
194 static char *whatNext_strs[] = {
204 /* -----------------------------------------------------------------------------
205 * Putting a thread on the run queue: different scheduling policies
206 * -------------------------------------------------------------------------- */
209 addToRunQueue( Capability *cap, StgTSO *t )
211 #if defined(PARALLEL_HASKELL)
212 if (RtsFlags.ParFlags.doFairScheduling) {
213 // this does round-robin scheduling; good for concurrency
214 appendToRunQueue(cap,t);
216 // this does unfair scheduling; good for parallelism
217 pushOnRunQueue(cap,t);
220 // this does round-robin scheduling; good for concurrency
221 appendToRunQueue(cap,t);
225 /* ---------------------------------------------------------------------------
226 Main scheduling loop.
228 We use round-robin scheduling, each thread returning to the
229 scheduler loop when one of these conditions is detected:
232 * timer expires (thread yields)
238 In a GranSim setup this loop iterates over the global event queue.
239 This revolves around the global event queue, which determines what
240 to do next. Therefore, it's more complicated than either the
241 concurrent or the parallel (GUM) setup.
242 This version has been entirely removed (JB 2008/08).
245 GUM iterates over incoming messages.
246 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
247 and sends out a fish whenever it has nothing to do; in-between
248 doing the actual reductions (shared code below) it processes the
249 incoming messages and deals with delayed operations
250 (see PendingFetches).
251 This is not the ugliest code you could imagine, but it's bloody close.
253 (JB 2008/08) This version was formerly indicated by a PP-Flag PAR,
254 now by PP-flag PARALLEL_HASKELL. The Eden RTS (in GHC-6.x) uses it,
255 as well as future GUM versions. This file has been refurbished to
256 only contain valid code, which is however incomplete, refers to
257 invalid includes etc.
259 ------------------------------------------------------------------------ */
262 schedule (Capability *initialCapability, Task *task)
266 StgThreadReturnCode ret;
267 #if defined(PARALLEL_HASKELL)
268 rtsBool receivedFinish = rtsFalse;
272 #if defined(THREADED_RTS)
273 rtsBool first = rtsTrue;
276 cap = initialCapability;
278 // Pre-condition: this task owns initialCapability.
279 // The sched_mutex is *NOT* held
280 // NB. on return, we still hold a capability.
282 debugTrace (DEBUG_sched,
283 "### NEW SCHEDULER LOOP (task: %p, cap: %p)",
284 task, initialCapability);
286 if (running_finalizers) {
287 errorBelch("error: a C finalizer called back into Haskell.\n"
288 " use Foreign.Concurrent.newForeignPtr for Haskell finalizers.");
289 stg_exit(EXIT_FAILURE);
294 // -----------------------------------------------------------
295 // Scheduler loop starts here:
297 #if defined(PARALLEL_HASKELL)
298 #define TERMINATION_CONDITION (!receivedFinish)
300 #define TERMINATION_CONDITION rtsTrue
303 while (TERMINATION_CONDITION) {
305 // Check whether we have re-entered the RTS from Haskell without
306 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
308 if (cap->in_haskell) {
309 errorBelch("schedule: re-entered unsafely.\n"
310 " Perhaps a 'foreign import unsafe' should be 'safe'?");
311 stg_exit(EXIT_FAILURE);
314 // The interruption / shutdown sequence.
316 // In order to cleanly shut down the runtime, we want to:
317 // * make sure that all main threads return to their callers
318 // with the state 'Interrupted'.
319 // * clean up all OS threads assocated with the runtime
320 // * free all memory etc.
322 // So the sequence for ^C goes like this:
324 // * ^C handler sets sched_state := SCHED_INTERRUPTING and
325 // arranges for some Capability to wake up
327 // * all threads in the system are halted, and the zombies are
328 // placed on the run queue for cleaning up. We acquire all
329 // the capabilities in order to delete the threads, this is
330 // done by scheduleDoGC() for convenience (because GC already
331 // needs to acquire all the capabilities). We can't kill
332 // threads involved in foreign calls.
334 // * somebody calls shutdownHaskell(), which calls exitScheduler()
336 // * sched_state := SCHED_SHUTTING_DOWN
338 // * all workers exit when the run queue on their capability
339 // drains. All main threads will also exit when their TSO
340 // reaches the head of the run queue and they can return.
342 // * eventually all Capabilities will shut down, and the RTS can
345 // * We might be left with threads blocked in foreign calls,
346 // we should really attempt to kill these somehow (TODO);
348 switch (sched_state) {
351 case SCHED_INTERRUPTING:
352 debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
353 #if defined(THREADED_RTS)
354 discardSparksCap(cap);
356 /* scheduleDoGC() deletes all the threads */
357 cap = scheduleDoGC(cap,task,rtsFalse);
359 // after scheduleDoGC(), we must be shutting down. Either some
360 // other Capability did the final GC, or we did it above,
361 // either way we can fall through to the SCHED_SHUTTING_DOWN
363 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
366 case SCHED_SHUTTING_DOWN:
367 debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
368 // If we are a worker, just exit. If we're a bound thread
369 // then we will exit below when we've removed our TSO from
371 if (task->tso == NULL && emptyRunQueue(cap)) {
376 barf("sched_state: %d", sched_state);
379 scheduleFindWork(cap);
381 /* work pushing, currently relevant only for THREADED_RTS:
382 (pushes threads, wakes up idle capabilities for stealing) */
383 schedulePushWork(cap,task);
385 #if defined(PARALLEL_HASKELL)
386 /* since we perform a blocking receive and continue otherwise,
387 either we never reach here or we definitely have work! */
388 // from here: non-empty run queue
389 ASSERT(!emptyRunQueue(cap));
391 if (PacketsWaiting()) { /* now process incoming messages, if any
394 CAUTION: scheduleGetRemoteWork called
395 above, waits for messages as well! */
396 processMessages(cap, &receivedFinish);
398 #endif // PARALLEL_HASKELL: non-empty run queue!
400 scheduleDetectDeadlock(cap,task);
402 #if defined(THREADED_RTS)
403 cap = task->cap; // reload cap, it might have changed
406 // Normally, the only way we can get here with no threads to
407 // run is if a keyboard interrupt received during
408 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
409 // Additionally, it is not fatal for the
410 // threaded RTS to reach here with no threads to run.
412 // win32: might be here due to awaitEvent() being abandoned
413 // as a result of a console event having been delivered.
415 #if defined(THREADED_RTS)
419 // // don't yield the first time, we want a chance to run this
420 // // thread for a bit, even if there are others banging at the
423 // ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
427 scheduleYield(&cap,task);
428 if (emptyRunQueue(cap)) continue; // look for work again
431 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
432 if ( emptyRunQueue(cap) ) {
433 ASSERT(sched_state >= SCHED_INTERRUPTING);
438 // Get a thread to run
440 t = popRunQueue(cap);
442 // Sanity check the thread we're about to run. This can be
443 // expensive if there is lots of thread switching going on...
444 IF_DEBUG(sanity,checkTSO(t));
446 #if defined(THREADED_RTS)
447 // Check whether we can run this thread in the current task.
448 // If not, we have to pass our capability to the right task.
450 Task *bound = t->bound;
454 debugTrace(DEBUG_sched,
455 "### Running thread %lu in bound thread", (unsigned long)t->id);
456 // yes, the Haskell thread is bound to the current native thread
458 debugTrace(DEBUG_sched,
459 "### thread %lu bound to another OS thread", (unsigned long)t->id);
460 // no, bound to a different Haskell thread: pass to that thread
461 pushOnRunQueue(cap,t);
465 // The thread we want to run is unbound.
467 debugTrace(DEBUG_sched,
468 "### this OS thread cannot run thread %lu", (unsigned long)t->id);
469 // no, the current native thread is bound to a different
470 // Haskell thread, so pass it to any worker thread
471 pushOnRunQueue(cap,t);
478 // If we're shutting down, and this thread has not yet been
479 // killed, kill it now. This sometimes happens when a finalizer
480 // thread is created by the final GC, or a thread previously
481 // in a foreign call returns.
482 if (sched_state >= SCHED_INTERRUPTING &&
483 !(t->what_next == ThreadComplete || t->what_next == ThreadKilled)) {
487 /* context switches are initiated by the timer signal, unless
488 * the user specified "context switch as often as possible", with
491 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
492 && !emptyThreadQueues(cap)) {
493 cap->context_switch = 1;
498 // CurrentTSO is the thread to run. t might be different if we
499 // loop back to run_thread, so make sure to set CurrentTSO after
501 cap->r.rCurrentTSO = t;
503 debugTrace(DEBUG_sched, "-->> running thread %ld %s ...",
504 (long)t->id, whatNext_strs[t->what_next]);
506 startHeapProfTimer();
508 // Check for exceptions blocked on this thread
509 maybePerformBlockedException (cap, t);
511 // ----------------------------------------------------------------------
512 // Run the current thread
514 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
515 ASSERT(t->cap == cap);
516 ASSERT(t->bound ? t->bound->cap == cap : 1);
518 prev_what_next = t->what_next;
520 errno = t->saved_errno;
522 SetLastError(t->saved_winerror);
525 cap->in_haskell = rtsTrue;
529 #if defined(THREADED_RTS)
530 if (recent_activity == ACTIVITY_DONE_GC) {
531 // ACTIVITY_DONE_GC means we turned off the timer signal to
532 // conserve power (see #1623). Re-enable it here.
534 prev = xchg((P_)&recent_activity, ACTIVITY_YES);
535 if (prev == ACTIVITY_DONE_GC) {
539 recent_activity = ACTIVITY_YES;
543 postEvent(cap, EVENT_RUN_THREAD, t->id, 0);
545 switch (prev_what_next) {
549 /* Thread already finished, return to scheduler. */
550 ret = ThreadFinished;
556 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
557 cap = regTableToCapability(r);
562 case ThreadInterpret:
563 cap = interpretBCO(cap);
568 barf("schedule: invalid what_next field");
571 cap->in_haskell = rtsFalse;
573 // The TSO might have moved, eg. if it re-entered the RTS and a GC
574 // happened. So find the new location:
575 t = cap->r.rCurrentTSO;
577 // We have run some Haskell code: there might be blackhole-blocked
578 // threads to wake up now.
579 // Lock-free test here should be ok, we're just setting a flag.
580 if ( blackhole_queue != END_TSO_QUEUE ) {
581 blackholes_need_checking = rtsTrue;
584 // And save the current errno in this thread.
585 // XXX: possibly bogus for SMP because this thread might already
586 // be running again, see code below.
587 t->saved_errno = errno;
589 // Similarly for Windows error code
590 t->saved_winerror = GetLastError();
593 postEvent (cap, EVENT_STOP_THREAD, t->id, ret);
595 #if defined(THREADED_RTS)
596 // If ret is ThreadBlocked, and this Task is bound to the TSO that
597 // blocked, we are in limbo - the TSO is now owned by whatever it
598 // is blocked on, and may in fact already have been woken up,
599 // perhaps even on a different Capability. It may be the case
600 // that task->cap != cap. We better yield this Capability
601 // immediately and return to normaility.
602 if (ret == ThreadBlocked) {
603 debugTrace(DEBUG_sched,
604 "--<< thread %lu (%s) stopped: blocked",
605 (unsigned long)t->id, whatNext_strs[t->what_next]);
610 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
611 ASSERT(t->cap == cap);
613 // ----------------------------------------------------------------------
615 // Costs for the scheduler are assigned to CCS_SYSTEM
617 #if defined(PROFILING)
621 schedulePostRunThread(cap,t);
623 t = threadStackUnderflow(task,t);
625 ready_to_gc = rtsFalse;
629 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
633 scheduleHandleStackOverflow(cap,task,t);
637 if (scheduleHandleYield(cap, t, prev_what_next)) {
638 // shortcut for switching between compiler/interpreter:
644 scheduleHandleThreadBlocked(t);
648 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
649 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
653 barf("schedule: invalid thread return code %d", (int)ret);
656 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
657 cap = scheduleDoGC(cap,task,rtsFalse);
659 } /* end of while() */
662 /* ----------------------------------------------------------------------------
663 * Setting up the scheduler loop
664 * ------------------------------------------------------------------------- */
667 schedulePreLoop(void)
669 // initialisation for scheduler - what cannot go into initScheduler()
672 /* -----------------------------------------------------------------------------
675 * Search for work to do, and handle messages from elsewhere.
676 * -------------------------------------------------------------------------- */
679 scheduleFindWork (Capability *cap)
681 scheduleStartSignalHandlers(cap);
683 // Only check the black holes here if we've nothing else to do.
684 // During normal execution, the black hole list only gets checked
685 // at GC time, to avoid repeatedly traversing this possibly long
686 // list each time around the scheduler.
687 if (emptyRunQueue(cap)) { scheduleCheckBlackHoles(cap); }
689 scheduleCheckWakeupThreads(cap);
691 scheduleCheckBlockedThreads(cap);
693 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
694 if (emptyRunQueue(cap)) { scheduleActivateSpark(cap); }
697 #if defined(PARALLEL_HASKELL)
698 // if messages have been buffered...
699 scheduleSendPendingMessages();
702 #if defined(PARALLEL_HASKELL)
703 if (emptyRunQueue(cap)) {
704 receivedFinish = scheduleGetRemoteWork(cap);
705 continue; // a new round, (hopefully) with new work
707 in GUM, this a) sends out a FISH and returns IF no fish is
709 b) (blocking) awaits and receives messages
711 in Eden, this is only the blocking receive, as b) in GUM.
717 #if defined(THREADED_RTS)
718 STATIC_INLINE rtsBool
719 shouldYieldCapability (Capability *cap, Task *task)
721 // we need to yield this capability to someone else if..
722 // - another thread is initiating a GC
723 // - another Task is returning from a foreign call
724 // - the thread at the head of the run queue cannot be run
725 // by this Task (it is bound to another Task, or it is unbound
726 // and this task it bound).
727 return (waiting_for_gc ||
728 cap->returning_tasks_hd != NULL ||
729 (!emptyRunQueue(cap) && (task->tso == NULL
730 ? cap->run_queue_hd->bound != NULL
731 : cap->run_queue_hd->bound != task)));
734 // This is the single place where a Task goes to sleep. There are
735 // two reasons it might need to sleep:
736 // - there are no threads to run
737 // - we need to yield this Capability to someone else
738 // (see shouldYieldCapability())
740 // Careful: the scheduler loop is quite delicate. Make sure you run
741 // the tests in testsuite/concurrent (all ways) after modifying this,
742 // and also check the benchmarks in nofib/parallel for regressions.
745 scheduleYield (Capability **pcap, Task *task)
747 Capability *cap = *pcap;
749 // if we have work, and we don't need to give up the Capability, continue.
750 if (!shouldYieldCapability(cap,task) &&
751 (!emptyRunQueue(cap) ||
752 !emptyWakeupQueue(cap) ||
753 blackholes_need_checking ||
754 sched_state >= SCHED_INTERRUPTING))
757 // otherwise yield (sleep), and keep yielding if necessary.
759 yieldCapability(&cap,task);
761 while (shouldYieldCapability(cap,task));
763 // note there may still be no threads on the run queue at this
764 // point, the caller has to check.
771 /* -----------------------------------------------------------------------------
774 * Push work to other Capabilities if we have some.
775 * -------------------------------------------------------------------------- */
778 schedulePushWork(Capability *cap USED_IF_THREADS,
779 Task *task USED_IF_THREADS)
781 /* following code not for PARALLEL_HASKELL. I kept the call general,
782 future GUM versions might use pushing in a distributed setup */
783 #if defined(THREADED_RTS)
785 Capability *free_caps[n_capabilities], *cap0;
788 // migration can be turned off with +RTS -qg
789 if (!RtsFlags.ParFlags.migrate) return;
791 // Check whether we have more threads on our run queue, or sparks
792 // in our pool, that we could hand to another Capability.
793 if (cap->run_queue_hd == END_TSO_QUEUE) {
794 if (sparkPoolSizeCap(cap) < 2) return;
796 if (cap->run_queue_hd->_link == END_TSO_QUEUE &&
797 sparkPoolSizeCap(cap) < 1) return;
800 // First grab as many free Capabilities as we can.
801 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
802 cap0 = &capabilities[i];
803 if (cap != cap0 && tryGrabCapability(cap0,task)) {
804 if (!emptyRunQueue(cap0) || cap->returning_tasks_hd != NULL) {
805 // it already has some work, we just grabbed it at
806 // the wrong moment. Or maybe it's deadlocked!
807 releaseCapability(cap0);
809 free_caps[n_free_caps++] = cap0;
814 // we now have n_free_caps free capabilities stashed in
815 // free_caps[]. Share our run queue equally with them. This is
816 // probably the simplest thing we could do; improvements we might
817 // want to do include:
819 // - giving high priority to moving relatively new threads, on
820 // the gournds that they haven't had time to build up a
821 // working set in the cache on this CPU/Capability.
823 // - giving low priority to moving long-lived threads
825 if (n_free_caps > 0) {
826 StgTSO *prev, *t, *next;
827 rtsBool pushed_to_all;
829 debugTrace(DEBUG_sched,
830 "cap %d: %s and %d free capabilities, sharing...",
832 (!emptyRunQueue(cap) && cap->run_queue_hd->_link != END_TSO_QUEUE)?
833 "excess threads on run queue":"sparks to share (>=2)",
837 pushed_to_all = rtsFalse;
839 if (cap->run_queue_hd != END_TSO_QUEUE) {
840 prev = cap->run_queue_hd;
842 prev->_link = END_TSO_QUEUE;
843 for (; t != END_TSO_QUEUE; t = next) {
845 t->_link = END_TSO_QUEUE;
846 if (t->what_next == ThreadRelocated
847 || t->bound == task // don't move my bound thread
848 || tsoLocked(t)) { // don't move a locked thread
849 setTSOLink(cap, prev, t);
851 } else if (i == n_free_caps) {
852 pushed_to_all = rtsTrue;
855 setTSOLink(cap, prev, t);
858 debugTrace(DEBUG_sched, "pushing thread %lu to capability %d", (unsigned long)t->id, free_caps[i]->no);
859 appendToRunQueue(free_caps[i],t);
861 postEvent (cap, EVENT_MIGRATE_THREAD, t->id, free_caps[i]->no);
863 if (t->bound) { t->bound->cap = free_caps[i]; }
864 t->cap = free_caps[i];
868 cap->run_queue_tl = prev;
872 /* JB I left this code in place, it would work but is not necessary */
874 // If there are some free capabilities that we didn't push any
875 // threads to, then try to push a spark to each one.
876 if (!pushed_to_all) {
878 // i is the next free capability to push to
879 for (; i < n_free_caps; i++) {
880 if (emptySparkPoolCap(free_caps[i])) {
881 spark = tryStealSpark(cap->sparks);
883 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
884 newSpark(&(free_caps[i]->r), spark);
889 #endif /* SPARK_PUSHING */
891 // release the capabilities
892 for (i = 0; i < n_free_caps; i++) {
893 task->cap = free_caps[i];
894 releaseAndWakeupCapability(free_caps[i]);
897 task->cap = cap; // reset to point to our Capability.
899 #endif /* THREADED_RTS */
903 /* ----------------------------------------------------------------------------
904 * Start any pending signal handlers
905 * ------------------------------------------------------------------------- */
907 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
909 scheduleStartSignalHandlers(Capability *cap)
911 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
912 // safe outside the lock
913 startSignalHandlers(cap);
918 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
923 /* ----------------------------------------------------------------------------
924 * Check for blocked threads that can be woken up.
925 * ------------------------------------------------------------------------- */
928 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
930 #if !defined(THREADED_RTS)
932 // Check whether any waiting threads need to be woken up. If the
933 // run queue is empty, and there are no other tasks running, we
934 // can wait indefinitely for something to happen.
936 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
938 awaitEvent( emptyRunQueue(cap) && !blackholes_need_checking );
944 /* ----------------------------------------------------------------------------
945 * Check for threads woken up by other Capabilities
946 * ------------------------------------------------------------------------- */
949 scheduleCheckWakeupThreads(Capability *cap USED_IF_THREADS)
951 #if defined(THREADED_RTS)
952 // Any threads that were woken up by other Capabilities get
953 // appended to our run queue.
954 if (!emptyWakeupQueue(cap)) {
955 ACQUIRE_LOCK(&cap->lock);
956 if (emptyRunQueue(cap)) {
957 cap->run_queue_hd = cap->wakeup_queue_hd;
958 cap->run_queue_tl = cap->wakeup_queue_tl;
960 setTSOLink(cap, cap->run_queue_tl, cap->wakeup_queue_hd);
961 cap->run_queue_tl = cap->wakeup_queue_tl;
963 cap->wakeup_queue_hd = cap->wakeup_queue_tl = END_TSO_QUEUE;
964 RELEASE_LOCK(&cap->lock);
969 /* ----------------------------------------------------------------------------
970 * Check for threads blocked on BLACKHOLEs that can be woken up
971 * ------------------------------------------------------------------------- */
973 scheduleCheckBlackHoles (Capability *cap)
975 if ( blackholes_need_checking ) // check without the lock first
977 ACQUIRE_LOCK(&sched_mutex);
978 if ( blackholes_need_checking ) {
979 blackholes_need_checking = rtsFalse;
980 // important that we reset the flag *before* checking the
981 // blackhole queue, otherwise we could get deadlock. This
982 // happens as follows: we wake up a thread that
983 // immediately runs on another Capability, blocks on a
984 // blackhole, and then we reset the blackholes_need_checking flag.
985 checkBlackHoles(cap);
987 RELEASE_LOCK(&sched_mutex);
991 /* ----------------------------------------------------------------------------
992 * Detect deadlock conditions and attempt to resolve them.
993 * ------------------------------------------------------------------------- */
996 scheduleDetectDeadlock (Capability *cap, Task *task)
999 #if defined(PARALLEL_HASKELL)
1000 // ToDo: add deadlock detection in GUM (similar to THREADED_RTS) -- HWL
1005 * Detect deadlock: when we have no threads to run, there are no
1006 * threads blocked, waiting for I/O, or sleeping, and all the
1007 * other tasks are waiting for work, we must have a deadlock of
1010 if ( emptyThreadQueues(cap) )
1012 #if defined(THREADED_RTS)
1014 * In the threaded RTS, we only check for deadlock if there
1015 * has been no activity in a complete timeslice. This means
1016 * we won't eagerly start a full GC just because we don't have
1017 * any threads to run currently.
1019 if (recent_activity != ACTIVITY_INACTIVE) return;
1022 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
1024 // Garbage collection can release some new threads due to
1025 // either (a) finalizers or (b) threads resurrected because
1026 // they are unreachable and will therefore be sent an
1027 // exception. Any threads thus released will be immediately
1029 cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
1030 // when force_major == rtsTrue. scheduleDoGC sets
1031 // recent_activity to ACTIVITY_DONE_GC and turns off the timer
1034 if ( !emptyRunQueue(cap) ) return;
1036 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
1037 /* If we have user-installed signal handlers, then wait
1038 * for signals to arrive rather then bombing out with a
1041 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
1042 debugTrace(DEBUG_sched,
1043 "still deadlocked, waiting for signals...");
1047 if (signals_pending()) {
1048 startSignalHandlers(cap);
1051 // either we have threads to run, or we were interrupted:
1052 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
1058 #if !defined(THREADED_RTS)
1059 /* Probably a real deadlock. Send the current main thread the
1060 * Deadlock exception.
1063 switch (task->tso->why_blocked) {
1065 case BlockedOnBlackHole:
1066 case BlockedOnException:
1068 throwToSingleThreaded(cap, task->tso,
1069 (StgClosure *)nonTermination_closure);
1072 barf("deadlock: main thread blocked in a strange way");
1081 /* ----------------------------------------------------------------------------
1082 * Send pending messages (PARALLEL_HASKELL only)
1083 * ------------------------------------------------------------------------- */
1085 #if defined(PARALLEL_HASKELL)
1087 scheduleSendPendingMessages(void)
1090 # if defined(PAR) // global Mem.Mgmt., omit for now
1091 if (PendingFetches != END_BF_QUEUE) {
1096 if (RtsFlags.ParFlags.BufferTime) {
1097 // if we use message buffering, we must send away all message
1098 // packets which have become too old...
1104 /* ----------------------------------------------------------------------------
1105 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
1106 * ------------------------------------------------------------------------- */
1108 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
1110 scheduleActivateSpark(Capability *cap)
1114 createSparkThread(cap);
1115 debugTrace(DEBUG_sched, "creating a spark thread");
1118 #endif // PARALLEL_HASKELL || THREADED_RTS
1120 /* ----------------------------------------------------------------------------
1121 * Get work from a remote node (PARALLEL_HASKELL only)
1122 * ------------------------------------------------------------------------- */
1124 #if defined(PARALLEL_HASKELL)
1125 static rtsBool /* return value used in PARALLEL_HASKELL only */
1126 scheduleGetRemoteWork (Capability *cap STG_UNUSED)
1128 #if defined(PARALLEL_HASKELL)
1129 rtsBool receivedFinish = rtsFalse;
1131 // idle() , i.e. send all buffers, wait for work
1132 if (RtsFlags.ParFlags.BufferTime) {
1133 IF_PAR_DEBUG(verbose,
1134 debugBelch("...send all pending data,"));
1137 for (i=1; i<=nPEs; i++)
1138 sendImmediately(i); // send all messages away immediately
1142 /* this would be the place for fishing in GUM...
1144 if (no-earlier-fish-around)
1145 sendFish(choosePe());
1148 // Eden:just look for incoming messages (blocking receive)
1149 IF_PAR_DEBUG(verbose,
1150 debugBelch("...wait for incoming messages...\n"));
1151 processMessages(cap, &receivedFinish); // blocking receive...
1154 return receivedFinish;
1155 // reenter scheduling look after having received something
1157 #else /* !PARALLEL_HASKELL, i.e. THREADED_RTS */
1159 return rtsFalse; /* return value unused in THREADED_RTS */
1161 #endif /* PARALLEL_HASKELL */
1163 #endif // PARALLEL_HASKELL || THREADED_RTS
1165 /* ----------------------------------------------------------------------------
1166 * After running a thread...
1167 * ------------------------------------------------------------------------- */
1170 schedulePostRunThread (Capability *cap, StgTSO *t)
1172 // We have to be able to catch transactions that are in an
1173 // infinite loop as a result of seeing an inconsistent view of
1177 // [a,b] <- mapM readTVar [ta,tb]
1178 // when (a == b) loop
1180 // and a is never equal to b given a consistent view of memory.
1182 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1183 if (!stmValidateNestOfTransactions (t -> trec)) {
1184 debugTrace(DEBUG_sched | DEBUG_stm,
1185 "trec %p found wasting its time", t);
1187 // strip the stack back to the
1188 // ATOMICALLY_FRAME, aborting the (nested)
1189 // transaction, and saving the stack of any
1190 // partially-evaluated thunks on the heap.
1191 throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1193 ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1197 /* some statistics gathering in the parallel case */
1200 /* -----------------------------------------------------------------------------
1201 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1202 * -------------------------------------------------------------------------- */
1205 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1207 // did the task ask for a large block?
1208 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1209 // if so, get one and push it on the front of the nursery.
1213 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1215 debugTrace(DEBUG_sched,
1216 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1217 (long)t->id, whatNext_strs[t->what_next], blocks);
1219 // don't do this if the nursery is (nearly) full, we'll GC first.
1220 if (cap->r.rCurrentNursery->link != NULL ||
1221 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1222 // if the nursery has only one block.
1225 bd = allocGroup( blocks );
1227 cap->r.rNursery->n_blocks += blocks;
1229 // link the new group into the list
1230 bd->link = cap->r.rCurrentNursery;
1231 bd->u.back = cap->r.rCurrentNursery->u.back;
1232 if (cap->r.rCurrentNursery->u.back != NULL) {
1233 cap->r.rCurrentNursery->u.back->link = bd;
1235 #if !defined(THREADED_RTS)
1236 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1237 g0s0 == cap->r.rNursery);
1239 cap->r.rNursery->blocks = bd;
1241 cap->r.rCurrentNursery->u.back = bd;
1243 // initialise it as a nursery block. We initialise the
1244 // step, gen_no, and flags field of *every* sub-block in
1245 // this large block, because this is easier than making
1246 // sure that we always find the block head of a large
1247 // block whenever we call Bdescr() (eg. evacuate() and
1248 // isAlive() in the GC would both have to do this, at
1252 for (x = bd; x < bd + blocks; x++) {
1253 x->step = cap->r.rNursery;
1259 // This assert can be a killer if the app is doing lots
1260 // of large block allocations.
1261 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1263 // now update the nursery to point to the new block
1264 cap->r.rCurrentNursery = bd;
1266 // we might be unlucky and have another thread get on the
1267 // run queue before us and steal the large block, but in that
1268 // case the thread will just end up requesting another large
1270 pushOnRunQueue(cap,t);
1271 return rtsFalse; /* not actually GC'ing */
1275 debugTrace(DEBUG_sched,
1276 "--<< thread %ld (%s) stopped: HeapOverflow",
1277 (long)t->id, whatNext_strs[t->what_next]);
1279 if (cap->r.rHpLim == NULL || cap->context_switch) {
1280 // Sometimes we miss a context switch, e.g. when calling
1281 // primitives in a tight loop, MAYBE_GC() doesn't check the
1282 // context switch flag, and we end up waiting for a GC.
1283 // See #1984, and concurrent/should_run/1984
1284 cap->context_switch = 0;
1285 addToRunQueue(cap,t);
1287 pushOnRunQueue(cap,t);
1290 /* actual GC is done at the end of the while loop in schedule() */
1293 /* -----------------------------------------------------------------------------
1294 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1295 * -------------------------------------------------------------------------- */
1298 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1300 debugTrace (DEBUG_sched,
1301 "--<< thread %ld (%s) stopped, StackOverflow",
1302 (long)t->id, whatNext_strs[t->what_next]);
1304 /* just adjust the stack for this thread, then pop it back
1308 /* enlarge the stack */
1309 StgTSO *new_t = threadStackOverflow(cap, t);
1311 /* The TSO attached to this Task may have moved, so update the
1314 if (task->tso == t) {
1317 pushOnRunQueue(cap,new_t);
1321 /* -----------------------------------------------------------------------------
1322 * Handle a thread that returned to the scheduler with ThreadYielding
1323 * -------------------------------------------------------------------------- */
1326 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1328 // Reset the context switch flag. We don't do this just before
1329 // running the thread, because that would mean we would lose ticks
1330 // during GC, which can lead to unfair scheduling (a thread hogs
1331 // the CPU because the tick always arrives during GC). This way
1332 // penalises threads that do a lot of allocation, but that seems
1333 // better than the alternative.
1334 cap->context_switch = 0;
1336 /* put the thread back on the run queue. Then, if we're ready to
1337 * GC, check whether this is the last task to stop. If so, wake
1338 * up the GC thread. getThread will block during a GC until the
1342 if (t->what_next != prev_what_next) {
1343 debugTrace(DEBUG_sched,
1344 "--<< thread %ld (%s) stopped to switch evaluators",
1345 (long)t->id, whatNext_strs[t->what_next]);
1347 debugTrace(DEBUG_sched,
1348 "--<< thread %ld (%s) stopped, yielding",
1349 (long)t->id, whatNext_strs[t->what_next]);
1354 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1356 ASSERT(t->_link == END_TSO_QUEUE);
1358 // Shortcut if we're just switching evaluators: don't bother
1359 // doing stack squeezing (which can be expensive), just run the
1361 if (t->what_next != prev_what_next) {
1365 addToRunQueue(cap,t);
1370 /* -----------------------------------------------------------------------------
1371 * Handle a thread that returned to the scheduler with ThreadBlocked
1372 * -------------------------------------------------------------------------- */
1375 scheduleHandleThreadBlocked( StgTSO *t
1376 #if !defined(GRAN) && !defined(DEBUG)
1382 // We don't need to do anything. The thread is blocked, and it
1383 // has tidied up its stack and placed itself on whatever queue
1384 // it needs to be on.
1386 // ASSERT(t->why_blocked != NotBlocked);
1387 // Not true: for example,
1388 // - in THREADED_RTS, the thread may already have been woken
1389 // up by another Capability. This actually happens: try
1390 // conc023 +RTS -N2.
1391 // - the thread may have woken itself up already, because
1392 // threadPaused() might have raised a blocked throwTo
1393 // exception, see maybePerformBlockedException().
1396 if (traceClass(DEBUG_sched)) {
1397 debugTraceBegin("--<< thread %lu (%s) stopped: ",
1398 (unsigned long)t->id, whatNext_strs[t->what_next]);
1399 printThreadBlockage(t);
1405 /* -----------------------------------------------------------------------------
1406 * Handle a thread that returned to the scheduler with ThreadFinished
1407 * -------------------------------------------------------------------------- */
1410 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1412 /* Need to check whether this was a main thread, and if so,
1413 * return with the return value.
1415 * We also end up here if the thread kills itself with an
1416 * uncaught exception, see Exception.cmm.
1418 debugTrace(DEBUG_sched, "--++ thread %lu (%s) finished",
1419 (unsigned long)t->id, whatNext_strs[t->what_next]);
1421 // blocked exceptions can now complete, even if the thread was in
1422 // blocked mode (see #2910). This unconditionally calls
1423 // lockTSO(), which ensures that we don't miss any threads that
1424 // are engaged in throwTo() with this thread as a target.
1425 awakenBlockedExceptionQueue (cap, t);
1428 // Check whether the thread that just completed was a bound
1429 // thread, and if so return with the result.
1431 // There is an assumption here that all thread completion goes
1432 // through this point; we need to make sure that if a thread
1433 // ends up in the ThreadKilled state, that it stays on the run
1434 // queue so it can be dealt with here.
1439 if (t->bound != task) {
1440 #if !defined(THREADED_RTS)
1441 // Must be a bound thread that is not the topmost one. Leave
1442 // it on the run queue until the stack has unwound to the
1443 // point where we can deal with this. Leaving it on the run
1444 // queue also ensures that the garbage collector knows about
1445 // this thread and its return value (it gets dropped from the
1446 // step->threads list so there's no other way to find it).
1447 appendToRunQueue(cap,t);
1450 // this cannot happen in the threaded RTS, because a
1451 // bound thread can only be run by the appropriate Task.
1452 barf("finished bound thread that isn't mine");
1456 ASSERT(task->tso == t);
1458 if (t->what_next == ThreadComplete) {
1460 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1461 *(task->ret) = (StgClosure *)task->tso->sp[1];
1463 task->stat = Success;
1466 *(task->ret) = NULL;
1468 if (sched_state >= SCHED_INTERRUPTING) {
1469 if (heap_overflow) {
1470 task->stat = HeapExhausted;
1472 task->stat = Interrupted;
1475 task->stat = Killed;
1479 removeThreadLabel((StgWord)task->tso->id);
1481 return rtsTrue; // tells schedule() to return
1487 /* -----------------------------------------------------------------------------
1488 * Perform a heap census
1489 * -------------------------------------------------------------------------- */
1492 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1494 // When we have +RTS -i0 and we're heap profiling, do a census at
1495 // every GC. This lets us get repeatable runs for debugging.
1496 if (performHeapProfile ||
1497 (RtsFlags.ProfFlags.profileInterval==0 &&
1498 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1505 /* -----------------------------------------------------------------------------
1506 * Perform a garbage collection if necessary
1507 * -------------------------------------------------------------------------- */
1510 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1512 rtsBool heap_census;
1514 /* extern static volatile StgWord waiting_for_gc;
1515 lives inside capability.c */
1516 rtsBool gc_type, prev_pending_gc;
1520 if (sched_state == SCHED_SHUTTING_DOWN) {
1521 // The final GC has already been done, and the system is
1522 // shutting down. We'll probably deadlock if we try to GC
1528 if (sched_state < SCHED_INTERRUPTING
1529 && RtsFlags.ParFlags.parGcEnabled
1530 && N >= RtsFlags.ParFlags.parGcGen
1531 && ! oldest_gen->steps[0].mark)
1533 gc_type = PENDING_GC_PAR;
1535 gc_type = PENDING_GC_SEQ;
1538 // In order to GC, there must be no threads running Haskell code.
1539 // Therefore, the GC thread needs to hold *all* the capabilities,
1540 // and release them after the GC has completed.
1542 // This seems to be the simplest way: previous attempts involved
1543 // making all the threads with capabilities give up their
1544 // capabilities and sleep except for the *last* one, which
1545 // actually did the GC. But it's quite hard to arrange for all
1546 // the other tasks to sleep and stay asleep.
1549 /* Other capabilities are prevented from running yet more Haskell
1550 threads if waiting_for_gc is set. Tested inside
1551 yieldCapability() and releaseCapability() in Capability.c */
1553 prev_pending_gc = cas(&waiting_for_gc, 0, gc_type);
1554 if (prev_pending_gc) {
1556 debugTrace(DEBUG_sched, "someone else is trying to GC (%d)...",
1559 yieldCapability(&cap,task);
1560 } while (waiting_for_gc);
1561 return cap; // NOTE: task->cap might have changed here
1564 setContextSwitches();
1566 // The final shutdown GC is always single-threaded, because it's
1567 // possible that some of the Capabilities have no worker threads.
1569 if (gc_type == PENDING_GC_SEQ)
1571 postEvent(cap, EVENT_REQUEST_SEQ_GC, 0, 0);
1572 // single-threaded GC: grab all the capabilities
1573 for (i=0; i < n_capabilities; i++) {
1574 debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1575 if (cap != &capabilities[i]) {
1576 Capability *pcap = &capabilities[i];
1577 // we better hope this task doesn't get migrated to
1578 // another Capability while we're waiting for this one.
1579 // It won't, because load balancing happens while we have
1580 // all the Capabilities, but even so it's a slightly
1581 // unsavoury invariant.
1583 waitForReturnCapability(&pcap, task);
1584 if (pcap != &capabilities[i]) {
1585 barf("scheduleDoGC: got the wrong capability");
1592 // multi-threaded GC: make sure all the Capabilities donate one
1594 postEvent(cap, EVENT_REQUEST_PAR_GC, 0, 0);
1595 debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1597 waitForGcThreads(cap);
1601 // so this happens periodically:
1602 if (cap) scheduleCheckBlackHoles(cap);
1604 IF_DEBUG(scheduler, printAllThreads());
1606 delete_threads_and_gc:
1608 * We now have all the capabilities; if we're in an interrupting
1609 * state, then we should take the opportunity to delete all the
1610 * threads in the system.
1612 if (sched_state == SCHED_INTERRUPTING) {
1613 deleteAllThreads(cap);
1614 sched_state = SCHED_SHUTTING_DOWN;
1617 heap_census = scheduleNeedHeapProfile(rtsTrue);
1619 #if defined(THREADED_RTS)
1620 postEvent(cap, EVENT_GC_START, 0, 0);
1621 debugTrace(DEBUG_sched, "doing GC");
1622 // reset waiting_for_gc *before* GC, so that when the GC threads
1623 // emerge they don't immediately re-enter the GC.
1625 GarbageCollect(force_major || heap_census, gc_type, cap);
1627 GarbageCollect(force_major || heap_census, 0, cap);
1629 postEvent(cap, EVENT_GC_END, 0, 0);
1631 if (recent_activity == ACTIVITY_INACTIVE && force_major)
1633 // We are doing a GC because the system has been idle for a
1634 // timeslice and we need to check for deadlock. Record the
1635 // fact that we've done a GC and turn off the timer signal;
1636 // it will get re-enabled if we run any threads after the GC.
1637 recent_activity = ACTIVITY_DONE_GC;
1642 // the GC might have taken long enough for the timer to set
1643 // recent_activity = ACTIVITY_INACTIVE, but we aren't
1644 // necessarily deadlocked:
1645 recent_activity = ACTIVITY_YES;
1648 #if defined(THREADED_RTS)
1649 if (gc_type == PENDING_GC_PAR)
1651 releaseGCThreads(cap);
1656 debugTrace(DEBUG_sched, "performing heap census");
1658 performHeapProfile = rtsFalse;
1661 if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1662 // GC set the heap_overflow flag, so we should proceed with
1663 // an orderly shutdown now. Ultimately we want the main
1664 // thread to return to its caller with HeapExhausted, at which
1665 // point the caller should call hs_exit(). The first step is
1666 // to delete all the threads.
1668 // Another way to do this would be to raise an exception in
1669 // the main thread, which we really should do because it gives
1670 // the program a chance to clean up. But how do we find the
1671 // main thread? It should presumably be the same one that
1672 // gets ^C exceptions, but that's all done on the Haskell side
1673 // (GHC.TopHandler).
1674 sched_state = SCHED_INTERRUPTING;
1675 goto delete_threads_and_gc;
1680 Once we are all together... this would be the place to balance all
1681 spark pools. No concurrent stealing or adding of new sparks can
1682 occur. Should be defined in Sparks.c. */
1683 balanceSparkPoolsCaps(n_capabilities, capabilities);
1686 #if defined(THREADED_RTS)
1687 if (gc_type == PENDING_GC_SEQ) {
1688 // release our stash of capabilities.
1689 for (i = 0; i < n_capabilities; i++) {
1690 if (cap != &capabilities[i]) {
1691 task->cap = &capabilities[i];
1692 releaseCapability(&capabilities[i]);
1706 /* ---------------------------------------------------------------------------
1707 * Singleton fork(). Do not copy any running threads.
1708 * ------------------------------------------------------------------------- */
1711 forkProcess(HsStablePtr *entry
1712 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1717 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1724 #if defined(THREADED_RTS)
1725 if (RtsFlags.ParFlags.nNodes > 1) {
1726 errorBelch("forking not supported with +RTS -N<n> greater than 1");
1727 stg_exit(EXIT_FAILURE);
1731 debugTrace(DEBUG_sched, "forking!");
1733 // ToDo: for SMP, we should probably acquire *all* the capabilities
1736 // no funny business: hold locks while we fork, otherwise if some
1737 // other thread is holding a lock when the fork happens, the data
1738 // structure protected by the lock will forever be in an
1739 // inconsistent state in the child. See also #1391.
1740 ACQUIRE_LOCK(&sched_mutex);
1741 ACQUIRE_LOCK(&cap->lock);
1742 ACQUIRE_LOCK(&cap->running_task->lock);
1746 if (pid) { // parent
1748 RELEASE_LOCK(&sched_mutex);
1749 RELEASE_LOCK(&cap->lock);
1750 RELEASE_LOCK(&cap->running_task->lock);
1752 // just return the pid
1758 #if defined(THREADED_RTS)
1759 initMutex(&sched_mutex);
1760 initMutex(&cap->lock);
1761 initMutex(&cap->running_task->lock);
1764 // Now, all OS threads except the thread that forked are
1765 // stopped. We need to stop all Haskell threads, including
1766 // those involved in foreign calls. Also we need to delete
1767 // all Tasks, because they correspond to OS threads that are
1770 for (s = 0; s < total_steps; s++) {
1771 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1772 if (t->what_next == ThreadRelocated) {
1775 next = t->global_link;
1776 // don't allow threads to catch the ThreadKilled
1777 // exception, but we do want to raiseAsync() because these
1778 // threads may be evaluating thunks that we need later.
1779 deleteThread_(cap,t);
1784 // Empty the run queue. It seems tempting to let all the
1785 // killed threads stay on the run queue as zombies to be
1786 // cleaned up later, but some of them correspond to bound
1787 // threads for which the corresponding Task does not exist.
1788 cap->run_queue_hd = END_TSO_QUEUE;
1789 cap->run_queue_tl = END_TSO_QUEUE;
1791 // Any suspended C-calling Tasks are no more, their OS threads
1793 cap->suspended_ccalling_tasks = NULL;
1795 // Empty the threads lists. Otherwise, the garbage
1796 // collector may attempt to resurrect some of these threads.
1797 for (s = 0; s < total_steps; s++) {
1798 all_steps[s].threads = END_TSO_QUEUE;
1801 // Wipe the task list, except the current Task.
1802 ACQUIRE_LOCK(&sched_mutex);
1803 for (task = all_tasks; task != NULL; task=task->all_link) {
1804 if (task != cap->running_task) {
1805 #if defined(THREADED_RTS)
1806 initMutex(&task->lock); // see #1391
1811 RELEASE_LOCK(&sched_mutex);
1813 #if defined(THREADED_RTS)
1814 // Wipe our spare workers list, they no longer exist. New
1815 // workers will be created if necessary.
1816 cap->spare_workers = NULL;
1817 cap->returning_tasks_hd = NULL;
1818 cap->returning_tasks_tl = NULL;
1821 // On Unix, all timers are reset in the child, so we need to start
1826 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1827 rts_checkSchedStatus("forkProcess",cap);
1830 hs_exit(); // clean up and exit
1831 stg_exit(EXIT_SUCCESS);
1833 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1834 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1839 /* ---------------------------------------------------------------------------
1840 * Delete all the threads in the system
1841 * ------------------------------------------------------------------------- */
1844 deleteAllThreads ( Capability *cap )
1846 // NOTE: only safe to call if we own all capabilities.
1851 debugTrace(DEBUG_sched,"deleting all threads");
1852 for (s = 0; s < total_steps; s++) {
1853 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1854 if (t->what_next == ThreadRelocated) {
1857 next = t->global_link;
1858 deleteThread(cap,t);
1863 // The run queue now contains a bunch of ThreadKilled threads. We
1864 // must not throw these away: the main thread(s) will be in there
1865 // somewhere, and the main scheduler loop has to deal with it.
1866 // Also, the run queue is the only thing keeping these threads from
1867 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1869 #if !defined(THREADED_RTS)
1870 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1871 ASSERT(sleeping_queue == END_TSO_QUEUE);
1875 /* -----------------------------------------------------------------------------
1876 Managing the suspended_ccalling_tasks list.
1877 Locks required: sched_mutex
1878 -------------------------------------------------------------------------- */
1881 suspendTask (Capability *cap, Task *task)
1883 ASSERT(task->next == NULL && task->prev == NULL);
1884 task->next = cap->suspended_ccalling_tasks;
1886 if (cap->suspended_ccalling_tasks) {
1887 cap->suspended_ccalling_tasks->prev = task;
1889 cap->suspended_ccalling_tasks = task;
1893 recoverSuspendedTask (Capability *cap, Task *task)
1896 task->prev->next = task->next;
1898 ASSERT(cap->suspended_ccalling_tasks == task);
1899 cap->suspended_ccalling_tasks = task->next;
1902 task->next->prev = task->prev;
1904 task->next = task->prev = NULL;
1907 /* ---------------------------------------------------------------------------
1908 * Suspending & resuming Haskell threads.
1910 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1911 * its capability before calling the C function. This allows another
1912 * task to pick up the capability and carry on running Haskell
1913 * threads. It also means that if the C call blocks, it won't lock
1916 * The Haskell thread making the C call is put to sleep for the
1917 * duration of the call, on the susepended_ccalling_threads queue. We
1918 * give out a token to the task, which it can use to resume the thread
1919 * on return from the C function.
1920 * ------------------------------------------------------------------------- */
1923 suspendThread (StgRegTable *reg)
1930 StgWord32 saved_winerror;
1933 saved_errno = errno;
1935 saved_winerror = GetLastError();
1938 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1940 cap = regTableToCapability(reg);
1942 task = cap->running_task;
1943 tso = cap->r.rCurrentTSO;
1945 postEvent(cap, EVENT_STOP_THREAD, tso->id, THREAD_SUSPENDED_FOREIGN_CALL);
1946 debugTrace(DEBUG_sched,
1947 "thread %lu did a safe foreign call",
1948 (unsigned long)cap->r.rCurrentTSO->id);
1950 // XXX this might not be necessary --SDM
1951 tso->what_next = ThreadRunGHC;
1953 threadPaused(cap,tso);
1955 if ((tso->flags & TSO_BLOCKEX) == 0) {
1956 tso->why_blocked = BlockedOnCCall;
1957 tso->flags |= TSO_BLOCKEX;
1958 tso->flags &= ~TSO_INTERRUPTIBLE;
1960 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1963 // Hand back capability
1964 task->suspended_tso = tso;
1966 ACQUIRE_LOCK(&cap->lock);
1968 suspendTask(cap,task);
1969 cap->in_haskell = rtsFalse;
1970 releaseCapability_(cap,rtsFalse);
1972 RELEASE_LOCK(&cap->lock);
1974 #if defined(THREADED_RTS)
1975 /* Preparing to leave the RTS, so ensure there's a native thread/task
1976 waiting to take over.
1978 debugTrace(DEBUG_sched, "thread %lu: leaving RTS", (unsigned long)tso->id);
1981 errno = saved_errno;
1983 SetLastError(saved_winerror);
1989 resumeThread (void *task_)
1996 StgWord32 saved_winerror;
1999 saved_errno = errno;
2001 saved_winerror = GetLastError();
2005 // Wait for permission to re-enter the RTS with the result.
2006 waitForReturnCapability(&cap,task);
2007 // we might be on a different capability now... but if so, our
2008 // entry on the suspended_ccalling_tasks list will also have been
2011 // Remove the thread from the suspended list
2012 recoverSuspendedTask(cap,task);
2014 tso = task->suspended_tso;
2015 task->suspended_tso = NULL;
2016 tso->_link = END_TSO_QUEUE; // no write barrier reqd
2018 postEvent(cap, EVENT_RUN_THREAD, tso->id, 0);
2019 debugTrace(DEBUG_sched, "thread %lu: re-entering RTS", (unsigned long)tso->id);
2021 if (tso->why_blocked == BlockedOnCCall) {
2022 // avoid locking the TSO if we don't have to
2023 if (tso->blocked_exceptions != END_TSO_QUEUE) {
2024 awakenBlockedExceptionQueue(cap,tso);
2026 tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
2029 /* Reset blocking status */
2030 tso->why_blocked = NotBlocked;
2032 cap->r.rCurrentTSO = tso;
2033 cap->in_haskell = rtsTrue;
2034 errno = saved_errno;
2036 SetLastError(saved_winerror);
2039 /* We might have GC'd, mark the TSO dirty again */
2042 IF_DEBUG(sanity, checkTSO(tso));
2047 /* ---------------------------------------------------------------------------
2050 * scheduleThread puts a thread on the end of the runnable queue.
2051 * This will usually be done immediately after a thread is created.
2052 * The caller of scheduleThread must create the thread using e.g.
2053 * createThread and push an appropriate closure
2054 * on this thread's stack before the scheduler is invoked.
2055 * ------------------------------------------------------------------------ */
2058 scheduleThread(Capability *cap, StgTSO *tso)
2060 // The thread goes at the *end* of the run-queue, to avoid possible
2061 // starvation of any threads already on the queue.
2062 appendToRunQueue(cap,tso);
2066 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
2068 #if defined(THREADED_RTS)
2069 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
2070 // move this thread from now on.
2071 cpu %= RtsFlags.ParFlags.nNodes;
2072 if (cpu == cap->no) {
2073 appendToRunQueue(cap,tso);
2075 postEvent (cap, EVENT_MIGRATE_THREAD, tso->id, capabilities[cpu].no);
2076 wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
2079 appendToRunQueue(cap,tso);
2084 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
2088 // We already created/initialised the Task
2089 task = cap->running_task;
2091 // This TSO is now a bound thread; make the Task and TSO
2092 // point to each other.
2098 task->stat = NoStatus;
2100 appendToRunQueue(cap,tso);
2102 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)tso->id);
2104 cap = schedule(cap,task);
2106 ASSERT(task->stat != NoStatus);
2107 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
2109 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)task->tso->id);
2113 /* ----------------------------------------------------------------------------
2115 * ------------------------------------------------------------------------- */
2117 #if defined(THREADED_RTS)
2118 void OSThreadProcAttr
2119 workerStart(Task *task)
2123 // See startWorkerTask().
2124 ACQUIRE_LOCK(&task->lock);
2126 RELEASE_LOCK(&task->lock);
2128 if (RtsFlags.ParFlags.setAffinity) {
2129 setThreadAffinity(cap->no, n_capabilities);
2132 // set the thread-local pointer to the Task:
2135 // schedule() runs without a lock.
2136 cap = schedule(cap,task);
2138 // On exit from schedule(), we have a Capability, but possibly not
2139 // the same one we started with.
2141 // During shutdown, the requirement is that after all the
2142 // Capabilities are shut down, all workers that are shutting down
2143 // have finished workerTaskStop(). This is why we hold on to
2144 // cap->lock until we've finished workerTaskStop() below.
2146 // There may be workers still involved in foreign calls; those
2147 // will just block in waitForReturnCapability() because the
2148 // Capability has been shut down.
2150 ACQUIRE_LOCK(&cap->lock);
2151 releaseCapability_(cap,rtsFalse);
2152 workerTaskStop(task);
2153 RELEASE_LOCK(&cap->lock);
2157 /* ---------------------------------------------------------------------------
2160 * Initialise the scheduler. This resets all the queues - if the
2161 * queues contained any threads, they'll be garbage collected at the
2164 * ------------------------------------------------------------------------ */
2169 #if !defined(THREADED_RTS)
2170 blocked_queue_hd = END_TSO_QUEUE;
2171 blocked_queue_tl = END_TSO_QUEUE;
2172 sleeping_queue = END_TSO_QUEUE;
2175 blackhole_queue = END_TSO_QUEUE;
2177 sched_state = SCHED_RUNNING;
2178 recent_activity = ACTIVITY_YES;
2180 #if defined(THREADED_RTS)
2181 /* Initialise the mutex and condition variables used by
2183 initMutex(&sched_mutex);
2186 ACQUIRE_LOCK(&sched_mutex);
2188 /* A capability holds the state a native thread needs in
2189 * order to execute STG code. At least one capability is
2190 * floating around (only THREADED_RTS builds have more than one).
2196 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
2200 #if defined(THREADED_RTS)
2202 * Eagerly start one worker to run each Capability, except for
2203 * Capability 0. The idea is that we're probably going to start a
2204 * bound thread on Capability 0 pretty soon, so we don't want a
2205 * worker task hogging it.
2210 for (i = 1; i < n_capabilities; i++) {
2211 cap = &capabilities[i];
2212 ACQUIRE_LOCK(&cap->lock);
2213 startWorkerTask(cap, workerStart);
2214 RELEASE_LOCK(&cap->lock);
2219 RELEASE_LOCK(&sched_mutex);
2224 rtsBool wait_foreign
2225 #if !defined(THREADED_RTS)
2226 __attribute__((unused))
2229 /* see Capability.c, shutdownCapability() */
2233 ACQUIRE_LOCK(&sched_mutex);
2234 task = newBoundTask();
2235 RELEASE_LOCK(&sched_mutex);
2237 // If we haven't killed all the threads yet, do it now.
2238 if (sched_state < SCHED_SHUTTING_DOWN) {
2239 sched_state = SCHED_INTERRUPTING;
2240 waitForReturnCapability(&task->cap,task);
2241 scheduleDoGC(task->cap,task,rtsFalse);
2242 releaseCapability(task->cap);
2244 sched_state = SCHED_SHUTTING_DOWN;
2246 #if defined(THREADED_RTS)
2250 for (i = 0; i < n_capabilities; i++) {
2251 shutdownCapability(&capabilities[i], task, wait_foreign);
2253 boundTaskExiting(task);
2259 freeScheduler( void )
2263 ACQUIRE_LOCK(&sched_mutex);
2264 still_running = freeTaskManager();
2265 // We can only free the Capabilities if there are no Tasks still
2266 // running. We might have a Task about to return from a foreign
2267 // call into waitForReturnCapability(), for example (actually,
2268 // this should be the *only* thing that a still-running Task can
2269 // do at this point, and it will block waiting for the
2271 if (still_running == 0) {
2273 if (n_capabilities != 1) {
2274 stgFree(capabilities);
2277 RELEASE_LOCK(&sched_mutex);
2278 #if defined(THREADED_RTS)
2279 closeMutex(&sched_mutex);
2283 /* -----------------------------------------------------------------------------
2286 This is the interface to the garbage collector from Haskell land.
2287 We provide this so that external C code can allocate and garbage
2288 collect when called from Haskell via _ccall_GC.
2289 -------------------------------------------------------------------------- */
2292 performGC_(rtsBool force_major)
2296 // We must grab a new Task here, because the existing Task may be
2297 // associated with a particular Capability, and chained onto the
2298 // suspended_ccalling_tasks queue.
2299 ACQUIRE_LOCK(&sched_mutex);
2300 task = newBoundTask();
2301 RELEASE_LOCK(&sched_mutex);
2303 waitForReturnCapability(&task->cap,task);
2304 scheduleDoGC(task->cap,task,force_major);
2305 releaseCapability(task->cap);
2306 boundTaskExiting(task);
2312 performGC_(rtsFalse);
2316 performMajorGC(void)
2318 performGC_(rtsTrue);
2321 /* -----------------------------------------------------------------------------
2324 If the thread has reached its maximum stack size, then raise the
2325 StackOverflow exception in the offending thread. Otherwise
2326 relocate the TSO into a larger chunk of memory and adjust its stack
2328 -------------------------------------------------------------------------- */
2331 threadStackOverflow(Capability *cap, StgTSO *tso)
2333 nat new_stack_size, stack_words;
2338 IF_DEBUG(sanity,checkTSO(tso));
2340 // don't allow throwTo() to modify the blocked_exceptions queue
2341 // while we are moving the TSO:
2342 lockClosure((StgClosure *)tso);
2344 if (tso->stack_size >= tso->max_stack_size && !(tso->flags & TSO_BLOCKEX)) {
2345 // NB. never raise a StackOverflow exception if the thread is
2346 // inside Control.Exceptino.block. It is impractical to protect
2347 // against stack overflow exceptions, since virtually anything
2348 // can raise one (even 'catch'), so this is the only sensible
2349 // thing to do here. See bug #767.
2351 debugTrace(DEBUG_gc,
2352 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2353 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2355 /* If we're debugging, just print out the top of the stack */
2356 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2359 // Send this thread the StackOverflow exception
2361 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2365 /* Try to double the current stack size. If that takes us over the
2366 * maximum stack size for this thread, then use the maximum instead
2367 * (that is, unless we're already at or over the max size and we
2368 * can't raise the StackOverflow exception (see above), in which
2369 * case just double the size). Finally round up so the TSO ends up as
2370 * a whole number of blocks.
2372 if (tso->stack_size >= tso->max_stack_size) {
2373 new_stack_size = tso->stack_size * 2;
2375 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2377 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2378 TSO_STRUCT_SIZE)/sizeof(W_);
2379 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2380 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2382 debugTrace(DEBUG_sched,
2383 "increasing stack size from %ld words to %d.",
2384 (long)tso->stack_size, new_stack_size);
2386 dest = (StgTSO *)allocateLocal(cap,new_tso_size);
2387 TICK_ALLOC_TSO(new_stack_size,0);
2389 /* copy the TSO block and the old stack into the new area */
2390 memcpy(dest,tso,TSO_STRUCT_SIZE);
2391 stack_words = tso->stack + tso->stack_size - tso->sp;
2392 new_sp = (P_)dest + new_tso_size - stack_words;
2393 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2395 /* relocate the stack pointers... */
2397 dest->stack_size = new_stack_size;
2399 /* Mark the old TSO as relocated. We have to check for relocated
2400 * TSOs in the garbage collector and any primops that deal with TSOs.
2402 * It's important to set the sp value to just beyond the end
2403 * of the stack, so we don't attempt to scavenge any part of the
2406 tso->what_next = ThreadRelocated;
2407 setTSOLink(cap,tso,dest);
2408 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2409 tso->why_blocked = NotBlocked;
2411 IF_PAR_DEBUG(verbose,
2412 debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2413 tso->id, tso, tso->stack_size);
2414 /* If we're debugging, just print out the top of the stack */
2415 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2421 IF_DEBUG(sanity,checkTSO(dest));
2423 IF_DEBUG(scheduler,printTSO(dest));
2430 threadStackUnderflow (Task *task STG_UNUSED, StgTSO *tso)
2432 bdescr *bd, *new_bd;
2433 lnat free_w, tso_size_w;
2436 tso_size_w = tso_sizeW(tso);
2438 if (tso_size_w < MBLOCK_SIZE_W ||
2439 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2444 // don't allow throwTo() to modify the blocked_exceptions queue
2445 // while we are moving the TSO:
2446 lockClosure((StgClosure *)tso);
2448 // this is the number of words we'll free
2449 free_w = round_to_mblocks(tso_size_w/2);
2451 bd = Bdescr((StgPtr)tso);
2452 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2453 bd->free = bd->start + TSO_STRUCT_SIZEW;
2455 new_tso = (StgTSO *)new_bd->start;
2456 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2457 new_tso->stack_size = new_bd->free - new_tso->stack;
2459 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2460 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2462 tso->what_next = ThreadRelocated;
2463 tso->_link = new_tso; // no write barrier reqd: same generation
2465 // The TSO attached to this Task may have moved, so update the
2467 if (task->tso == tso) {
2468 task->tso = new_tso;
2474 IF_DEBUG(sanity,checkTSO(new_tso));
2479 /* ---------------------------------------------------------------------------
2481 - usually called inside a signal handler so it mustn't do anything fancy.
2482 ------------------------------------------------------------------------ */
2485 interruptStgRts(void)
2487 sched_state = SCHED_INTERRUPTING;
2488 setContextSwitches();
2492 /* -----------------------------------------------------------------------------
2495 This function causes at least one OS thread to wake up and run the
2496 scheduler loop. It is invoked when the RTS might be deadlocked, or
2497 an external event has arrived that may need servicing (eg. a
2498 keyboard interrupt).
2500 In the single-threaded RTS we don't do anything here; we only have
2501 one thread anyway, and the event that caused us to want to wake up
2502 will have interrupted any blocking system call in progress anyway.
2503 -------------------------------------------------------------------------- */
2508 #if defined(THREADED_RTS)
2509 // This forces the IO Manager thread to wakeup, which will
2510 // in turn ensure that some OS thread wakes up and runs the
2511 // scheduler loop, which will cause a GC and deadlock check.
2516 /* -----------------------------------------------------------------------------
2519 * Check the blackhole_queue for threads that can be woken up. We do
2520 * this periodically: before every GC, and whenever the run queue is
2523 * An elegant solution might be to just wake up all the blocked
2524 * threads with awakenBlockedQueue occasionally: they'll go back to
2525 * sleep again if the object is still a BLACKHOLE. Unfortunately this
2526 * doesn't give us a way to tell whether we've actually managed to
2527 * wake up any threads, so we would be busy-waiting.
2529 * -------------------------------------------------------------------------- */
2532 checkBlackHoles (Capability *cap)
2535 rtsBool any_woke_up = rtsFalse;
2538 // blackhole_queue is global:
2539 ASSERT_LOCK_HELD(&sched_mutex);
2541 debugTrace(DEBUG_sched, "checking threads blocked on black holes");
2543 // ASSUMES: sched_mutex
2544 prev = &blackhole_queue;
2545 t = blackhole_queue;
2546 while (t != END_TSO_QUEUE) {
2547 ASSERT(t->why_blocked == BlockedOnBlackHole);
2548 type = get_itbl(UNTAG_CLOSURE(t->block_info.closure))->type;
2549 if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
2550 IF_DEBUG(sanity,checkTSO(t));
2551 t = unblockOne(cap, t);
2553 any_woke_up = rtsTrue;
2563 /* -----------------------------------------------------------------------------
2566 This is used for interruption (^C) and forking, and corresponds to
2567 raising an exception but without letting the thread catch the
2569 -------------------------------------------------------------------------- */
2572 deleteThread (Capability *cap, StgTSO *tso)
2574 // NOTE: must only be called on a TSO that we have exclusive
2575 // access to, because we will call throwToSingleThreaded() below.
2576 // The TSO must be on the run queue of the Capability we own, or
2577 // we must own all Capabilities.
2579 if (tso->why_blocked != BlockedOnCCall &&
2580 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2581 throwToSingleThreaded(cap,tso,NULL);
2585 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2587 deleteThread_(Capability *cap, StgTSO *tso)
2588 { // for forkProcess only:
2589 // like deleteThread(), but we delete threads in foreign calls, too.
2591 if (tso->why_blocked == BlockedOnCCall ||
2592 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2593 unblockOne(cap,tso);
2594 tso->what_next = ThreadKilled;
2596 deleteThread(cap,tso);
2601 /* -----------------------------------------------------------------------------
2602 raiseExceptionHelper
2604 This function is called by the raise# primitve, just so that we can
2605 move some of the tricky bits of raising an exception from C-- into
2606 C. Who knows, it might be a useful re-useable thing here too.
2607 -------------------------------------------------------------------------- */
2610 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2612 Capability *cap = regTableToCapability(reg);
2613 StgThunk *raise_closure = NULL;
2615 StgRetInfoTable *info;
2617 // This closure represents the expression 'raise# E' where E
2618 // is the exception raise. It is used to overwrite all the
2619 // thunks which are currently under evaluataion.
2622 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2623 // LDV profiling: stg_raise_info has THUNK as its closure
2624 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2625 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2626 // 1 does not cause any problem unless profiling is performed.
2627 // However, when LDV profiling goes on, we need to linearly scan
2628 // small object pool, where raise_closure is stored, so we should
2629 // use MIN_UPD_SIZE.
2631 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2632 // sizeofW(StgClosure)+1);
2636 // Walk up the stack, looking for the catch frame. On the way,
2637 // we update any closures pointed to from update frames with the
2638 // raise closure that we just built.
2642 info = get_ret_itbl((StgClosure *)p);
2643 next = p + stack_frame_sizeW((StgClosure *)p);
2644 switch (info->i.type) {
2647 // Only create raise_closure if we need to.
2648 if (raise_closure == NULL) {
2650 (StgThunk *)allocateLocal(cap,sizeofW(StgThunk)+1);
2651 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2652 raise_closure->payload[0] = exception;
2654 UPD_IND(((StgUpdateFrame *)p)->updatee,(StgClosure *)raise_closure);
2658 case ATOMICALLY_FRAME:
2659 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2661 return ATOMICALLY_FRAME;
2667 case CATCH_STM_FRAME:
2668 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2670 return CATCH_STM_FRAME;
2676 case CATCH_RETRY_FRAME:
2685 /* -----------------------------------------------------------------------------
2686 findRetryFrameHelper
2688 This function is called by the retry# primitive. It traverses the stack
2689 leaving tso->sp referring to the frame which should handle the retry.
2691 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2692 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2694 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2695 create) because retries are not considered to be exceptions, despite the
2696 similar implementation.
2698 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2699 not be created within memory transactions.
2700 -------------------------------------------------------------------------- */
2703 findRetryFrameHelper (StgTSO *tso)
2706 StgRetInfoTable *info;
2710 info = get_ret_itbl((StgClosure *)p);
2711 next = p + stack_frame_sizeW((StgClosure *)p);
2712 switch (info->i.type) {
2714 case ATOMICALLY_FRAME:
2715 debugTrace(DEBUG_stm,
2716 "found ATOMICALLY_FRAME at %p during retry", p);
2718 return ATOMICALLY_FRAME;
2720 case CATCH_RETRY_FRAME:
2721 debugTrace(DEBUG_stm,
2722 "found CATCH_RETRY_FRAME at %p during retrry", p);
2724 return CATCH_RETRY_FRAME;
2726 case CATCH_STM_FRAME: {
2727 StgTRecHeader *trec = tso -> trec;
2728 StgTRecHeader *outer = stmGetEnclosingTRec(trec);
2729 debugTrace(DEBUG_stm,
2730 "found CATCH_STM_FRAME at %p during retry", p);
2731 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2732 stmAbortTransaction(tso -> cap, trec);
2733 stmFreeAbortedTRec(tso -> cap, trec);
2734 tso -> trec = outer;
2741 ASSERT(info->i.type != CATCH_FRAME);
2742 ASSERT(info->i.type != STOP_FRAME);
2749 /* -----------------------------------------------------------------------------
2750 resurrectThreads is called after garbage collection on the list of
2751 threads found to be garbage. Each of these threads will be woken
2752 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2753 on an MVar, or NonTermination if the thread was blocked on a Black
2756 Locks: assumes we hold *all* the capabilities.
2757 -------------------------------------------------------------------------- */
2760 resurrectThreads (StgTSO *threads)
2766 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2767 next = tso->global_link;
2769 step = Bdescr((P_)tso)->step;
2770 tso->global_link = step->threads;
2771 step->threads = tso;
2773 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2775 // Wake up the thread on the Capability it was last on
2778 switch (tso->why_blocked) {
2780 case BlockedOnException:
2781 /* Called by GC - sched_mutex lock is currently held. */
2782 throwToSingleThreaded(cap, tso,
2783 (StgClosure *)blockedOnDeadMVar_closure);
2785 case BlockedOnBlackHole:
2786 throwToSingleThreaded(cap, tso,
2787 (StgClosure *)nonTermination_closure);
2790 throwToSingleThreaded(cap, tso,
2791 (StgClosure *)blockedIndefinitely_closure);
2794 /* This might happen if the thread was blocked on a black hole
2795 * belonging to a thread that we've just woken up (raiseAsync
2796 * can wake up threads, remember...).
2800 barf("resurrectThreads: thread blocked in a strange way");
2805 /* -----------------------------------------------------------------------------
2806 performPendingThrowTos is called after garbage collection, and
2807 passed a list of threads that were found to have pending throwTos
2808 (tso->blocked_exceptions was not empty), and were blocked.
2809 Normally this doesn't happen, because we would deliver the
2810 exception directly if the target thread is blocked, but there are
2811 small windows where it might occur on a multiprocessor (see
2814 NB. we must be holding all the capabilities at this point, just
2815 like resurrectThreads().
2816 -------------------------------------------------------------------------- */
2819 performPendingThrowTos (StgTSO *threads)
2825 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2826 next = tso->global_link;
2828 step = Bdescr((P_)tso)->step;
2829 tso->global_link = step->threads;
2830 step->threads = tso;
2832 debugTrace(DEBUG_sched, "performing blocked throwTo to thread %lu", (unsigned long)tso->id);
2835 maybePerformBlockedException(cap, tso);