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);
885 postEvent(free_caps[i], EVENT_STEAL_SPARK, t->id, cap->no);
887 newSpark(&(free_caps[i]->r), spark);
892 #endif /* SPARK_PUSHING */
894 // release the capabilities
895 for (i = 0; i < n_free_caps; i++) {
896 task->cap = free_caps[i];
897 releaseAndWakeupCapability(free_caps[i]);
900 task->cap = cap; // reset to point to our Capability.
902 #endif /* THREADED_RTS */
906 /* ----------------------------------------------------------------------------
907 * Start any pending signal handlers
908 * ------------------------------------------------------------------------- */
910 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
912 scheduleStartSignalHandlers(Capability *cap)
914 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
915 // safe outside the lock
916 startSignalHandlers(cap);
921 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
926 /* ----------------------------------------------------------------------------
927 * Check for blocked threads that can be woken up.
928 * ------------------------------------------------------------------------- */
931 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
933 #if !defined(THREADED_RTS)
935 // Check whether any waiting threads need to be woken up. If the
936 // run queue is empty, and there are no other tasks running, we
937 // can wait indefinitely for something to happen.
939 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
941 awaitEvent( emptyRunQueue(cap) && !blackholes_need_checking );
947 /* ----------------------------------------------------------------------------
948 * Check for threads woken up by other Capabilities
949 * ------------------------------------------------------------------------- */
952 scheduleCheckWakeupThreads(Capability *cap USED_IF_THREADS)
954 #if defined(THREADED_RTS)
955 // Any threads that were woken up by other Capabilities get
956 // appended to our run queue.
957 if (!emptyWakeupQueue(cap)) {
958 ACQUIRE_LOCK(&cap->lock);
959 if (emptyRunQueue(cap)) {
960 cap->run_queue_hd = cap->wakeup_queue_hd;
961 cap->run_queue_tl = cap->wakeup_queue_tl;
963 setTSOLink(cap, cap->run_queue_tl, cap->wakeup_queue_hd);
964 cap->run_queue_tl = cap->wakeup_queue_tl;
966 cap->wakeup_queue_hd = cap->wakeup_queue_tl = END_TSO_QUEUE;
967 RELEASE_LOCK(&cap->lock);
972 /* ----------------------------------------------------------------------------
973 * Check for threads blocked on BLACKHOLEs that can be woken up
974 * ------------------------------------------------------------------------- */
976 scheduleCheckBlackHoles (Capability *cap)
978 if ( blackholes_need_checking ) // check without the lock first
980 ACQUIRE_LOCK(&sched_mutex);
981 if ( blackholes_need_checking ) {
982 blackholes_need_checking = rtsFalse;
983 // important that we reset the flag *before* checking the
984 // blackhole queue, otherwise we could get deadlock. This
985 // happens as follows: we wake up a thread that
986 // immediately runs on another Capability, blocks on a
987 // blackhole, and then we reset the blackholes_need_checking flag.
988 checkBlackHoles(cap);
990 RELEASE_LOCK(&sched_mutex);
994 /* ----------------------------------------------------------------------------
995 * Detect deadlock conditions and attempt to resolve them.
996 * ------------------------------------------------------------------------- */
999 scheduleDetectDeadlock (Capability *cap, Task *task)
1002 #if defined(PARALLEL_HASKELL)
1003 // ToDo: add deadlock detection in GUM (similar to THREADED_RTS) -- HWL
1008 * Detect deadlock: when we have no threads to run, there are no
1009 * threads blocked, waiting for I/O, or sleeping, and all the
1010 * other tasks are waiting for work, we must have a deadlock of
1013 if ( emptyThreadQueues(cap) )
1015 #if defined(THREADED_RTS)
1017 * In the threaded RTS, we only check for deadlock if there
1018 * has been no activity in a complete timeslice. This means
1019 * we won't eagerly start a full GC just because we don't have
1020 * any threads to run currently.
1022 if (recent_activity != ACTIVITY_INACTIVE) return;
1025 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
1027 // Garbage collection can release some new threads due to
1028 // either (a) finalizers or (b) threads resurrected because
1029 // they are unreachable and will therefore be sent an
1030 // exception. Any threads thus released will be immediately
1032 cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
1033 // when force_major == rtsTrue. scheduleDoGC sets
1034 // recent_activity to ACTIVITY_DONE_GC and turns off the timer
1037 if ( !emptyRunQueue(cap) ) return;
1039 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
1040 /* If we have user-installed signal handlers, then wait
1041 * for signals to arrive rather then bombing out with a
1044 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
1045 debugTrace(DEBUG_sched,
1046 "still deadlocked, waiting for signals...");
1050 if (signals_pending()) {
1051 startSignalHandlers(cap);
1054 // either we have threads to run, or we were interrupted:
1055 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
1061 #if !defined(THREADED_RTS)
1062 /* Probably a real deadlock. Send the current main thread the
1063 * Deadlock exception.
1066 switch (task->tso->why_blocked) {
1068 case BlockedOnBlackHole:
1069 case BlockedOnException:
1071 throwToSingleThreaded(cap, task->tso,
1072 (StgClosure *)nonTermination_closure);
1075 barf("deadlock: main thread blocked in a strange way");
1084 /* ----------------------------------------------------------------------------
1085 * Send pending messages (PARALLEL_HASKELL only)
1086 * ------------------------------------------------------------------------- */
1088 #if defined(PARALLEL_HASKELL)
1090 scheduleSendPendingMessages(void)
1093 # if defined(PAR) // global Mem.Mgmt., omit for now
1094 if (PendingFetches != END_BF_QUEUE) {
1099 if (RtsFlags.ParFlags.BufferTime) {
1100 // if we use message buffering, we must send away all message
1101 // packets which have become too old...
1107 /* ----------------------------------------------------------------------------
1108 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
1109 * ------------------------------------------------------------------------- */
1111 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
1113 scheduleActivateSpark(Capability *cap)
1117 createSparkThread(cap);
1118 debugTrace(DEBUG_sched, "creating a spark thread");
1121 #endif // PARALLEL_HASKELL || THREADED_RTS
1123 /* ----------------------------------------------------------------------------
1124 * Get work from a remote node (PARALLEL_HASKELL only)
1125 * ------------------------------------------------------------------------- */
1127 #if defined(PARALLEL_HASKELL)
1128 static rtsBool /* return value used in PARALLEL_HASKELL only */
1129 scheduleGetRemoteWork (Capability *cap STG_UNUSED)
1131 #if defined(PARALLEL_HASKELL)
1132 rtsBool receivedFinish = rtsFalse;
1134 // idle() , i.e. send all buffers, wait for work
1135 if (RtsFlags.ParFlags.BufferTime) {
1136 IF_PAR_DEBUG(verbose,
1137 debugBelch("...send all pending data,"));
1140 for (i=1; i<=nPEs; i++)
1141 sendImmediately(i); // send all messages away immediately
1145 /* this would be the place for fishing in GUM...
1147 if (no-earlier-fish-around)
1148 sendFish(choosePe());
1151 // Eden:just look for incoming messages (blocking receive)
1152 IF_PAR_DEBUG(verbose,
1153 debugBelch("...wait for incoming messages...\n"));
1154 processMessages(cap, &receivedFinish); // blocking receive...
1157 return receivedFinish;
1158 // reenter scheduling look after having received something
1160 #else /* !PARALLEL_HASKELL, i.e. THREADED_RTS */
1162 return rtsFalse; /* return value unused in THREADED_RTS */
1164 #endif /* PARALLEL_HASKELL */
1166 #endif // PARALLEL_HASKELL || THREADED_RTS
1168 /* ----------------------------------------------------------------------------
1169 * After running a thread...
1170 * ------------------------------------------------------------------------- */
1173 schedulePostRunThread (Capability *cap, StgTSO *t)
1175 // We have to be able to catch transactions that are in an
1176 // infinite loop as a result of seeing an inconsistent view of
1180 // [a,b] <- mapM readTVar [ta,tb]
1181 // when (a == b) loop
1183 // and a is never equal to b given a consistent view of memory.
1185 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1186 if (!stmValidateNestOfTransactions (t -> trec)) {
1187 debugTrace(DEBUG_sched | DEBUG_stm,
1188 "trec %p found wasting its time", t);
1190 // strip the stack back to the
1191 // ATOMICALLY_FRAME, aborting the (nested)
1192 // transaction, and saving the stack of any
1193 // partially-evaluated thunks on the heap.
1194 throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1196 ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1200 /* some statistics gathering in the parallel case */
1203 /* -----------------------------------------------------------------------------
1204 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1205 * -------------------------------------------------------------------------- */
1208 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1210 // did the task ask for a large block?
1211 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1212 // if so, get one and push it on the front of the nursery.
1216 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1218 debugTrace(DEBUG_sched,
1219 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1220 (long)t->id, whatNext_strs[t->what_next], blocks);
1222 // don't do this if the nursery is (nearly) full, we'll GC first.
1223 if (cap->r.rCurrentNursery->link != NULL ||
1224 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1225 // if the nursery has only one block.
1228 bd = allocGroup( blocks );
1230 cap->r.rNursery->n_blocks += blocks;
1232 // link the new group into the list
1233 bd->link = cap->r.rCurrentNursery;
1234 bd->u.back = cap->r.rCurrentNursery->u.back;
1235 if (cap->r.rCurrentNursery->u.back != NULL) {
1236 cap->r.rCurrentNursery->u.back->link = bd;
1238 #if !defined(THREADED_RTS)
1239 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1240 g0s0 == cap->r.rNursery);
1242 cap->r.rNursery->blocks = bd;
1244 cap->r.rCurrentNursery->u.back = bd;
1246 // initialise it as a nursery block. We initialise the
1247 // step, gen_no, and flags field of *every* sub-block in
1248 // this large block, because this is easier than making
1249 // sure that we always find the block head of a large
1250 // block whenever we call Bdescr() (eg. evacuate() and
1251 // isAlive() in the GC would both have to do this, at
1255 for (x = bd; x < bd + blocks; x++) {
1256 x->step = cap->r.rNursery;
1262 // This assert can be a killer if the app is doing lots
1263 // of large block allocations.
1264 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1266 // now update the nursery to point to the new block
1267 cap->r.rCurrentNursery = bd;
1269 // we might be unlucky and have another thread get on the
1270 // run queue before us and steal the large block, but in that
1271 // case the thread will just end up requesting another large
1273 pushOnRunQueue(cap,t);
1274 return rtsFalse; /* not actually GC'ing */
1278 debugTrace(DEBUG_sched,
1279 "--<< thread %ld (%s) stopped: HeapOverflow",
1280 (long)t->id, whatNext_strs[t->what_next]);
1282 if (cap->r.rHpLim == NULL || cap->context_switch) {
1283 // Sometimes we miss a context switch, e.g. when calling
1284 // primitives in a tight loop, MAYBE_GC() doesn't check the
1285 // context switch flag, and we end up waiting for a GC.
1286 // See #1984, and concurrent/should_run/1984
1287 cap->context_switch = 0;
1288 addToRunQueue(cap,t);
1290 pushOnRunQueue(cap,t);
1293 /* actual GC is done at the end of the while loop in schedule() */
1296 /* -----------------------------------------------------------------------------
1297 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1298 * -------------------------------------------------------------------------- */
1301 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1303 debugTrace (DEBUG_sched,
1304 "--<< thread %ld (%s) stopped, StackOverflow",
1305 (long)t->id, whatNext_strs[t->what_next]);
1307 /* just adjust the stack for this thread, then pop it back
1311 /* enlarge the stack */
1312 StgTSO *new_t = threadStackOverflow(cap, t);
1314 /* The TSO attached to this Task may have moved, so update the
1317 if (task->tso == t) {
1320 pushOnRunQueue(cap,new_t);
1324 /* -----------------------------------------------------------------------------
1325 * Handle a thread that returned to the scheduler with ThreadYielding
1326 * -------------------------------------------------------------------------- */
1329 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1331 // Reset the context switch flag. We don't do this just before
1332 // running the thread, because that would mean we would lose ticks
1333 // during GC, which can lead to unfair scheduling (a thread hogs
1334 // the CPU because the tick always arrives during GC). This way
1335 // penalises threads that do a lot of allocation, but that seems
1336 // better than the alternative.
1337 cap->context_switch = 0;
1339 /* put the thread back on the run queue. Then, if we're ready to
1340 * GC, check whether this is the last task to stop. If so, wake
1341 * up the GC thread. getThread will block during a GC until the
1345 if (t->what_next != prev_what_next) {
1346 debugTrace(DEBUG_sched,
1347 "--<< thread %ld (%s) stopped to switch evaluators",
1348 (long)t->id, whatNext_strs[t->what_next]);
1350 debugTrace(DEBUG_sched,
1351 "--<< thread %ld (%s) stopped, yielding",
1352 (long)t->id, whatNext_strs[t->what_next]);
1357 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1359 ASSERT(t->_link == END_TSO_QUEUE);
1361 // Shortcut if we're just switching evaluators: don't bother
1362 // doing stack squeezing (which can be expensive), just run the
1364 if (t->what_next != prev_what_next) {
1368 addToRunQueue(cap,t);
1373 /* -----------------------------------------------------------------------------
1374 * Handle a thread that returned to the scheduler with ThreadBlocked
1375 * -------------------------------------------------------------------------- */
1378 scheduleHandleThreadBlocked( StgTSO *t
1379 #if !defined(GRAN) && !defined(DEBUG)
1385 // We don't need to do anything. The thread is blocked, and it
1386 // has tidied up its stack and placed itself on whatever queue
1387 // it needs to be on.
1389 // ASSERT(t->why_blocked != NotBlocked);
1390 // Not true: for example,
1391 // - in THREADED_RTS, the thread may already have been woken
1392 // up by another Capability. This actually happens: try
1393 // conc023 +RTS -N2.
1394 // - the thread may have woken itself up already, because
1395 // threadPaused() might have raised a blocked throwTo
1396 // exception, see maybePerformBlockedException().
1399 if (traceClass(DEBUG_sched)) {
1400 debugTraceBegin("--<< thread %lu (%s) stopped: ",
1401 (unsigned long)t->id, whatNext_strs[t->what_next]);
1402 printThreadBlockage(t);
1408 /* -----------------------------------------------------------------------------
1409 * Handle a thread that returned to the scheduler with ThreadFinished
1410 * -------------------------------------------------------------------------- */
1413 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1415 /* Need to check whether this was a main thread, and if so,
1416 * return with the return value.
1418 * We also end up here if the thread kills itself with an
1419 * uncaught exception, see Exception.cmm.
1421 debugTrace(DEBUG_sched, "--++ thread %lu (%s) finished",
1422 (unsigned long)t->id, whatNext_strs[t->what_next]);
1424 // blocked exceptions can now complete, even if the thread was in
1425 // blocked mode (see #2910). This unconditionally calls
1426 // lockTSO(), which ensures that we don't miss any threads that
1427 // are engaged in throwTo() with this thread as a target.
1428 awakenBlockedExceptionQueue (cap, t);
1431 // Check whether the thread that just completed was a bound
1432 // thread, and if so return with the result.
1434 // There is an assumption here that all thread completion goes
1435 // through this point; we need to make sure that if a thread
1436 // ends up in the ThreadKilled state, that it stays on the run
1437 // queue so it can be dealt with here.
1442 if (t->bound != task) {
1443 #if !defined(THREADED_RTS)
1444 // Must be a bound thread that is not the topmost one. Leave
1445 // it on the run queue until the stack has unwound to the
1446 // point where we can deal with this. Leaving it on the run
1447 // queue also ensures that the garbage collector knows about
1448 // this thread and its return value (it gets dropped from the
1449 // step->threads list so there's no other way to find it).
1450 appendToRunQueue(cap,t);
1453 // this cannot happen in the threaded RTS, because a
1454 // bound thread can only be run by the appropriate Task.
1455 barf("finished bound thread that isn't mine");
1459 ASSERT(task->tso == t);
1461 if (t->what_next == ThreadComplete) {
1463 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1464 *(task->ret) = (StgClosure *)task->tso->sp[1];
1466 task->stat = Success;
1469 *(task->ret) = NULL;
1471 if (sched_state >= SCHED_INTERRUPTING) {
1472 if (heap_overflow) {
1473 task->stat = HeapExhausted;
1475 task->stat = Interrupted;
1478 task->stat = Killed;
1482 removeThreadLabel((StgWord)task->tso->id);
1484 return rtsTrue; // tells schedule() to return
1490 /* -----------------------------------------------------------------------------
1491 * Perform a heap census
1492 * -------------------------------------------------------------------------- */
1495 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1497 // When we have +RTS -i0 and we're heap profiling, do a census at
1498 // every GC. This lets us get repeatable runs for debugging.
1499 if (performHeapProfile ||
1500 (RtsFlags.ProfFlags.profileInterval==0 &&
1501 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1508 /* -----------------------------------------------------------------------------
1509 * Perform a garbage collection if necessary
1510 * -------------------------------------------------------------------------- */
1513 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1515 rtsBool heap_census;
1517 /* extern static volatile StgWord waiting_for_gc;
1518 lives inside capability.c */
1519 rtsBool gc_type, prev_pending_gc;
1523 if (sched_state == SCHED_SHUTTING_DOWN) {
1524 // The final GC has already been done, and the system is
1525 // shutting down. We'll probably deadlock if we try to GC
1531 if (sched_state < SCHED_INTERRUPTING
1532 && RtsFlags.ParFlags.parGcEnabled
1533 && N >= RtsFlags.ParFlags.parGcGen
1534 && ! oldest_gen->steps[0].mark)
1536 gc_type = PENDING_GC_PAR;
1538 gc_type = PENDING_GC_SEQ;
1541 // In order to GC, there must be no threads running Haskell code.
1542 // Therefore, the GC thread needs to hold *all* the capabilities,
1543 // and release them after the GC has completed.
1545 // This seems to be the simplest way: previous attempts involved
1546 // making all the threads with capabilities give up their
1547 // capabilities and sleep except for the *last* one, which
1548 // actually did the GC. But it's quite hard to arrange for all
1549 // the other tasks to sleep and stay asleep.
1552 /* Other capabilities are prevented from running yet more Haskell
1553 threads if waiting_for_gc is set. Tested inside
1554 yieldCapability() and releaseCapability() in Capability.c */
1556 prev_pending_gc = cas(&waiting_for_gc, 0, gc_type);
1557 if (prev_pending_gc) {
1559 debugTrace(DEBUG_sched, "someone else is trying to GC (%d)...",
1562 yieldCapability(&cap,task);
1563 } while (waiting_for_gc);
1564 return cap; // NOTE: task->cap might have changed here
1567 setContextSwitches();
1569 // The final shutdown GC is always single-threaded, because it's
1570 // possible that some of the Capabilities have no worker threads.
1572 if (gc_type == PENDING_GC_SEQ)
1574 postEvent(cap, EVENT_REQUEST_SEQ_GC, 0, 0);
1575 // single-threaded GC: grab all the capabilities
1576 for (i=0; i < n_capabilities; i++) {
1577 debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1578 if (cap != &capabilities[i]) {
1579 Capability *pcap = &capabilities[i];
1580 // we better hope this task doesn't get migrated to
1581 // another Capability while we're waiting for this one.
1582 // It won't, because load balancing happens while we have
1583 // all the Capabilities, but even so it's a slightly
1584 // unsavoury invariant.
1586 waitForReturnCapability(&pcap, task);
1587 if (pcap != &capabilities[i]) {
1588 barf("scheduleDoGC: got the wrong capability");
1595 // multi-threaded GC: make sure all the Capabilities donate one
1597 postEvent(cap, EVENT_REQUEST_PAR_GC, 0, 0);
1598 debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1600 waitForGcThreads(cap);
1604 // so this happens periodically:
1605 if (cap) scheduleCheckBlackHoles(cap);
1607 IF_DEBUG(scheduler, printAllThreads());
1609 delete_threads_and_gc:
1611 * We now have all the capabilities; if we're in an interrupting
1612 * state, then we should take the opportunity to delete all the
1613 * threads in the system.
1615 if (sched_state == SCHED_INTERRUPTING) {
1616 deleteAllThreads(cap);
1617 sched_state = SCHED_SHUTTING_DOWN;
1620 heap_census = scheduleNeedHeapProfile(rtsTrue);
1622 #if defined(THREADED_RTS)
1623 postEvent(cap, EVENT_GC_START, 0, 0);
1624 debugTrace(DEBUG_sched, "doing GC");
1625 // reset waiting_for_gc *before* GC, so that when the GC threads
1626 // emerge they don't immediately re-enter the GC.
1628 GarbageCollect(force_major || heap_census, gc_type, cap);
1630 GarbageCollect(force_major || heap_census, 0, cap);
1632 postEvent(cap, EVENT_GC_END, 0, 0);
1634 if (recent_activity == ACTIVITY_INACTIVE && force_major)
1636 // We are doing a GC because the system has been idle for a
1637 // timeslice and we need to check for deadlock. Record the
1638 // fact that we've done a GC and turn off the timer signal;
1639 // it will get re-enabled if we run any threads after the GC.
1640 recent_activity = ACTIVITY_DONE_GC;
1645 // the GC might have taken long enough for the timer to set
1646 // recent_activity = ACTIVITY_INACTIVE, but we aren't
1647 // necessarily deadlocked:
1648 recent_activity = ACTIVITY_YES;
1651 #if defined(THREADED_RTS)
1652 if (gc_type == PENDING_GC_PAR)
1654 releaseGCThreads(cap);
1659 debugTrace(DEBUG_sched, "performing heap census");
1661 performHeapProfile = rtsFalse;
1664 if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1665 // GC set the heap_overflow flag, so we should proceed with
1666 // an orderly shutdown now. Ultimately we want the main
1667 // thread to return to its caller with HeapExhausted, at which
1668 // point the caller should call hs_exit(). The first step is
1669 // to delete all the threads.
1671 // Another way to do this would be to raise an exception in
1672 // the main thread, which we really should do because it gives
1673 // the program a chance to clean up. But how do we find the
1674 // main thread? It should presumably be the same one that
1675 // gets ^C exceptions, but that's all done on the Haskell side
1676 // (GHC.TopHandler).
1677 sched_state = SCHED_INTERRUPTING;
1678 goto delete_threads_and_gc;
1683 Once we are all together... this would be the place to balance all
1684 spark pools. No concurrent stealing or adding of new sparks can
1685 occur. Should be defined in Sparks.c. */
1686 balanceSparkPoolsCaps(n_capabilities, capabilities);
1689 #if defined(THREADED_RTS)
1690 if (gc_type == PENDING_GC_SEQ) {
1691 // release our stash of capabilities.
1692 for (i = 0; i < n_capabilities; i++) {
1693 if (cap != &capabilities[i]) {
1694 task->cap = &capabilities[i];
1695 releaseCapability(&capabilities[i]);
1709 /* ---------------------------------------------------------------------------
1710 * Singleton fork(). Do not copy any running threads.
1711 * ------------------------------------------------------------------------- */
1714 forkProcess(HsStablePtr *entry
1715 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1720 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1727 #if defined(THREADED_RTS)
1728 if (RtsFlags.ParFlags.nNodes > 1) {
1729 errorBelch("forking not supported with +RTS -N<n> greater than 1");
1730 stg_exit(EXIT_FAILURE);
1734 debugTrace(DEBUG_sched, "forking!");
1736 // ToDo: for SMP, we should probably acquire *all* the capabilities
1739 // no funny business: hold locks while we fork, otherwise if some
1740 // other thread is holding a lock when the fork happens, the data
1741 // structure protected by the lock will forever be in an
1742 // inconsistent state in the child. See also #1391.
1743 ACQUIRE_LOCK(&sched_mutex);
1744 ACQUIRE_LOCK(&cap->lock);
1745 ACQUIRE_LOCK(&cap->running_task->lock);
1749 if (pid) { // parent
1751 RELEASE_LOCK(&sched_mutex);
1752 RELEASE_LOCK(&cap->lock);
1753 RELEASE_LOCK(&cap->running_task->lock);
1755 // just return the pid
1761 #if defined(THREADED_RTS)
1762 initMutex(&sched_mutex);
1763 initMutex(&cap->lock);
1764 initMutex(&cap->running_task->lock);
1767 // Now, all OS threads except the thread that forked are
1768 // stopped. We need to stop all Haskell threads, including
1769 // those involved in foreign calls. Also we need to delete
1770 // all Tasks, because they correspond to OS threads that are
1773 for (s = 0; s < total_steps; s++) {
1774 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1775 if (t->what_next == ThreadRelocated) {
1778 next = t->global_link;
1779 // don't allow threads to catch the ThreadKilled
1780 // exception, but we do want to raiseAsync() because these
1781 // threads may be evaluating thunks that we need later.
1782 deleteThread_(cap,t);
1787 // Empty the run queue. It seems tempting to let all the
1788 // killed threads stay on the run queue as zombies to be
1789 // cleaned up later, but some of them correspond to bound
1790 // threads for which the corresponding Task does not exist.
1791 cap->run_queue_hd = END_TSO_QUEUE;
1792 cap->run_queue_tl = END_TSO_QUEUE;
1794 // Any suspended C-calling Tasks are no more, their OS threads
1796 cap->suspended_ccalling_tasks = NULL;
1798 // Empty the threads lists. Otherwise, the garbage
1799 // collector may attempt to resurrect some of these threads.
1800 for (s = 0; s < total_steps; s++) {
1801 all_steps[s].threads = END_TSO_QUEUE;
1804 // Wipe the task list, except the current Task.
1805 ACQUIRE_LOCK(&sched_mutex);
1806 for (task = all_tasks; task != NULL; task=task->all_link) {
1807 if (task != cap->running_task) {
1808 #if defined(THREADED_RTS)
1809 initMutex(&task->lock); // see #1391
1814 RELEASE_LOCK(&sched_mutex);
1816 #if defined(THREADED_RTS)
1817 // Wipe our spare workers list, they no longer exist. New
1818 // workers will be created if necessary.
1819 cap->spare_workers = NULL;
1820 cap->returning_tasks_hd = NULL;
1821 cap->returning_tasks_tl = NULL;
1824 // On Unix, all timers are reset in the child, so we need to start
1829 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1830 rts_checkSchedStatus("forkProcess",cap);
1833 hs_exit(); // clean up and exit
1834 stg_exit(EXIT_SUCCESS);
1836 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1837 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1842 /* ---------------------------------------------------------------------------
1843 * Delete all the threads in the system
1844 * ------------------------------------------------------------------------- */
1847 deleteAllThreads ( Capability *cap )
1849 // NOTE: only safe to call if we own all capabilities.
1854 debugTrace(DEBUG_sched,"deleting all threads");
1855 for (s = 0; s < total_steps; s++) {
1856 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1857 if (t->what_next == ThreadRelocated) {
1860 next = t->global_link;
1861 deleteThread(cap,t);
1866 // The run queue now contains a bunch of ThreadKilled threads. We
1867 // must not throw these away: the main thread(s) will be in there
1868 // somewhere, and the main scheduler loop has to deal with it.
1869 // Also, the run queue is the only thing keeping these threads from
1870 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1872 #if !defined(THREADED_RTS)
1873 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1874 ASSERT(sleeping_queue == END_TSO_QUEUE);
1878 /* -----------------------------------------------------------------------------
1879 Managing the suspended_ccalling_tasks list.
1880 Locks required: sched_mutex
1881 -------------------------------------------------------------------------- */
1884 suspendTask (Capability *cap, Task *task)
1886 ASSERT(task->next == NULL && task->prev == NULL);
1887 task->next = cap->suspended_ccalling_tasks;
1889 if (cap->suspended_ccalling_tasks) {
1890 cap->suspended_ccalling_tasks->prev = task;
1892 cap->suspended_ccalling_tasks = task;
1896 recoverSuspendedTask (Capability *cap, Task *task)
1899 task->prev->next = task->next;
1901 ASSERT(cap->suspended_ccalling_tasks == task);
1902 cap->suspended_ccalling_tasks = task->next;
1905 task->next->prev = task->prev;
1907 task->next = task->prev = NULL;
1910 /* ---------------------------------------------------------------------------
1911 * Suspending & resuming Haskell threads.
1913 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1914 * its capability before calling the C function. This allows another
1915 * task to pick up the capability and carry on running Haskell
1916 * threads. It also means that if the C call blocks, it won't lock
1919 * The Haskell thread making the C call is put to sleep for the
1920 * duration of the call, on the susepended_ccalling_threads queue. We
1921 * give out a token to the task, which it can use to resume the thread
1922 * on return from the C function.
1923 * ------------------------------------------------------------------------- */
1926 suspendThread (StgRegTable *reg)
1933 StgWord32 saved_winerror;
1936 saved_errno = errno;
1938 saved_winerror = GetLastError();
1941 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1943 cap = regTableToCapability(reg);
1945 task = cap->running_task;
1946 tso = cap->r.rCurrentTSO;
1948 postEvent(cap, EVENT_STOP_THREAD, tso->id, THREAD_SUSPENDED_FOREIGN_CALL);
1949 debugTrace(DEBUG_sched,
1950 "thread %lu did a safe foreign call",
1951 (unsigned long)cap->r.rCurrentTSO->id);
1953 // XXX this might not be necessary --SDM
1954 tso->what_next = ThreadRunGHC;
1956 threadPaused(cap,tso);
1958 if ((tso->flags & TSO_BLOCKEX) == 0) {
1959 tso->why_blocked = BlockedOnCCall;
1960 tso->flags |= TSO_BLOCKEX;
1961 tso->flags &= ~TSO_INTERRUPTIBLE;
1963 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1966 // Hand back capability
1967 task->suspended_tso = tso;
1969 ACQUIRE_LOCK(&cap->lock);
1971 suspendTask(cap,task);
1972 cap->in_haskell = rtsFalse;
1973 releaseCapability_(cap,rtsFalse);
1975 RELEASE_LOCK(&cap->lock);
1977 #if defined(THREADED_RTS)
1978 /* Preparing to leave the RTS, so ensure there's a native thread/task
1979 waiting to take over.
1981 debugTrace(DEBUG_sched, "thread %lu: leaving RTS", (unsigned long)tso->id);
1984 errno = saved_errno;
1986 SetLastError(saved_winerror);
1992 resumeThread (void *task_)
1999 StgWord32 saved_winerror;
2002 saved_errno = errno;
2004 saved_winerror = GetLastError();
2008 // Wait for permission to re-enter the RTS with the result.
2009 waitForReturnCapability(&cap,task);
2010 // we might be on a different capability now... but if so, our
2011 // entry on the suspended_ccalling_tasks list will also have been
2014 // Remove the thread from the suspended list
2015 recoverSuspendedTask(cap,task);
2017 tso = task->suspended_tso;
2018 task->suspended_tso = NULL;
2019 tso->_link = END_TSO_QUEUE; // no write barrier reqd
2021 postEvent(cap, EVENT_RUN_THREAD, tso->id, 0);
2022 debugTrace(DEBUG_sched, "thread %lu: re-entering RTS", (unsigned long)tso->id);
2024 if (tso->why_blocked == BlockedOnCCall) {
2025 // avoid locking the TSO if we don't have to
2026 if (tso->blocked_exceptions != END_TSO_QUEUE) {
2027 awakenBlockedExceptionQueue(cap,tso);
2029 tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
2032 /* Reset blocking status */
2033 tso->why_blocked = NotBlocked;
2035 cap->r.rCurrentTSO = tso;
2036 cap->in_haskell = rtsTrue;
2037 errno = saved_errno;
2039 SetLastError(saved_winerror);
2042 /* We might have GC'd, mark the TSO dirty again */
2045 IF_DEBUG(sanity, checkTSO(tso));
2050 /* ---------------------------------------------------------------------------
2053 * scheduleThread puts a thread on the end of the runnable queue.
2054 * This will usually be done immediately after a thread is created.
2055 * The caller of scheduleThread must create the thread using e.g.
2056 * createThread and push an appropriate closure
2057 * on this thread's stack before the scheduler is invoked.
2058 * ------------------------------------------------------------------------ */
2061 scheduleThread(Capability *cap, StgTSO *tso)
2063 // The thread goes at the *end* of the run-queue, to avoid possible
2064 // starvation of any threads already on the queue.
2065 appendToRunQueue(cap,tso);
2069 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
2071 #if defined(THREADED_RTS)
2072 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
2073 // move this thread from now on.
2074 cpu %= RtsFlags.ParFlags.nNodes;
2075 if (cpu == cap->no) {
2076 appendToRunQueue(cap,tso);
2078 postEvent (cap, EVENT_MIGRATE_THREAD, tso->id, capabilities[cpu].no);
2079 wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
2082 appendToRunQueue(cap,tso);
2087 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
2091 // We already created/initialised the Task
2092 task = cap->running_task;
2094 // This TSO is now a bound thread; make the Task and TSO
2095 // point to each other.
2101 task->stat = NoStatus;
2103 appendToRunQueue(cap,tso);
2105 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)tso->id);
2107 cap = schedule(cap,task);
2109 ASSERT(task->stat != NoStatus);
2110 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
2112 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)task->tso->id);
2116 /* ----------------------------------------------------------------------------
2118 * ------------------------------------------------------------------------- */
2120 #if defined(THREADED_RTS)
2121 void OSThreadProcAttr
2122 workerStart(Task *task)
2126 // See startWorkerTask().
2127 ACQUIRE_LOCK(&task->lock);
2129 RELEASE_LOCK(&task->lock);
2131 if (RtsFlags.ParFlags.setAffinity) {
2132 setThreadAffinity(cap->no, n_capabilities);
2135 // set the thread-local pointer to the Task:
2138 // schedule() runs without a lock.
2139 cap = schedule(cap,task);
2141 // On exit from schedule(), we have a Capability, but possibly not
2142 // the same one we started with.
2144 // During shutdown, the requirement is that after all the
2145 // Capabilities are shut down, all workers that are shutting down
2146 // have finished workerTaskStop(). This is why we hold on to
2147 // cap->lock until we've finished workerTaskStop() below.
2149 // There may be workers still involved in foreign calls; those
2150 // will just block in waitForReturnCapability() because the
2151 // Capability has been shut down.
2153 ACQUIRE_LOCK(&cap->lock);
2154 releaseCapability_(cap,rtsFalse);
2155 workerTaskStop(task);
2156 RELEASE_LOCK(&cap->lock);
2160 /* ---------------------------------------------------------------------------
2163 * Initialise the scheduler. This resets all the queues - if the
2164 * queues contained any threads, they'll be garbage collected at the
2167 * ------------------------------------------------------------------------ */
2172 #if !defined(THREADED_RTS)
2173 blocked_queue_hd = END_TSO_QUEUE;
2174 blocked_queue_tl = END_TSO_QUEUE;
2175 sleeping_queue = END_TSO_QUEUE;
2178 blackhole_queue = END_TSO_QUEUE;
2180 sched_state = SCHED_RUNNING;
2181 recent_activity = ACTIVITY_YES;
2183 #if defined(THREADED_RTS)
2184 /* Initialise the mutex and condition variables used by
2186 initMutex(&sched_mutex);
2189 ACQUIRE_LOCK(&sched_mutex);
2191 /* A capability holds the state a native thread needs in
2192 * order to execute STG code. At least one capability is
2193 * floating around (only THREADED_RTS builds have more than one).
2199 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
2203 #if defined(THREADED_RTS)
2205 * Eagerly start one worker to run each Capability, except for
2206 * Capability 0. The idea is that we're probably going to start a
2207 * bound thread on Capability 0 pretty soon, so we don't want a
2208 * worker task hogging it.
2213 for (i = 1; i < n_capabilities; i++) {
2214 cap = &capabilities[i];
2215 ACQUIRE_LOCK(&cap->lock);
2216 startWorkerTask(cap, workerStart);
2217 RELEASE_LOCK(&cap->lock);
2222 RELEASE_LOCK(&sched_mutex);
2227 rtsBool wait_foreign
2228 #if !defined(THREADED_RTS)
2229 __attribute__((unused))
2232 /* see Capability.c, shutdownCapability() */
2236 ACQUIRE_LOCK(&sched_mutex);
2237 task = newBoundTask();
2238 RELEASE_LOCK(&sched_mutex);
2240 // If we haven't killed all the threads yet, do it now.
2241 if (sched_state < SCHED_SHUTTING_DOWN) {
2242 sched_state = SCHED_INTERRUPTING;
2243 waitForReturnCapability(&task->cap,task);
2244 scheduleDoGC(task->cap,task,rtsFalse);
2245 releaseCapability(task->cap);
2247 sched_state = SCHED_SHUTTING_DOWN;
2249 #if defined(THREADED_RTS)
2253 for (i = 0; i < n_capabilities; i++) {
2254 shutdownCapability(&capabilities[i], task, wait_foreign);
2256 boundTaskExiting(task);
2262 freeScheduler( void )
2266 ACQUIRE_LOCK(&sched_mutex);
2267 still_running = freeTaskManager();
2268 // We can only free the Capabilities if there are no Tasks still
2269 // running. We might have a Task about to return from a foreign
2270 // call into waitForReturnCapability(), for example (actually,
2271 // this should be the *only* thing that a still-running Task can
2272 // do at this point, and it will block waiting for the
2274 if (still_running == 0) {
2276 if (n_capabilities != 1) {
2277 stgFree(capabilities);
2280 RELEASE_LOCK(&sched_mutex);
2281 #if defined(THREADED_RTS)
2282 closeMutex(&sched_mutex);
2286 /* -----------------------------------------------------------------------------
2289 This is the interface to the garbage collector from Haskell land.
2290 We provide this so that external C code can allocate and garbage
2291 collect when called from Haskell via _ccall_GC.
2292 -------------------------------------------------------------------------- */
2295 performGC_(rtsBool force_major)
2299 // We must grab a new Task here, because the existing Task may be
2300 // associated with a particular Capability, and chained onto the
2301 // suspended_ccalling_tasks queue.
2302 ACQUIRE_LOCK(&sched_mutex);
2303 task = newBoundTask();
2304 RELEASE_LOCK(&sched_mutex);
2306 waitForReturnCapability(&task->cap,task);
2307 scheduleDoGC(task->cap,task,force_major);
2308 releaseCapability(task->cap);
2309 boundTaskExiting(task);
2315 performGC_(rtsFalse);
2319 performMajorGC(void)
2321 performGC_(rtsTrue);
2324 /* -----------------------------------------------------------------------------
2327 If the thread has reached its maximum stack size, then raise the
2328 StackOverflow exception in the offending thread. Otherwise
2329 relocate the TSO into a larger chunk of memory and adjust its stack
2331 -------------------------------------------------------------------------- */
2334 threadStackOverflow(Capability *cap, StgTSO *tso)
2336 nat new_stack_size, stack_words;
2341 IF_DEBUG(sanity,checkTSO(tso));
2343 // don't allow throwTo() to modify the blocked_exceptions queue
2344 // while we are moving the TSO:
2345 lockClosure((StgClosure *)tso);
2347 if (tso->stack_size >= tso->max_stack_size && !(tso->flags & TSO_BLOCKEX)) {
2348 // NB. never raise a StackOverflow exception if the thread is
2349 // inside Control.Exceptino.block. It is impractical to protect
2350 // against stack overflow exceptions, since virtually anything
2351 // can raise one (even 'catch'), so this is the only sensible
2352 // thing to do here. See bug #767.
2354 debugTrace(DEBUG_gc,
2355 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2356 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2358 /* If we're debugging, just print out the top of the stack */
2359 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2362 // Send this thread the StackOverflow exception
2364 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2368 /* Try to double the current stack size. If that takes us over the
2369 * maximum stack size for this thread, then use the maximum instead
2370 * (that is, unless we're already at or over the max size and we
2371 * can't raise the StackOverflow exception (see above), in which
2372 * case just double the size). Finally round up so the TSO ends up as
2373 * a whole number of blocks.
2375 if (tso->stack_size >= tso->max_stack_size) {
2376 new_stack_size = tso->stack_size * 2;
2378 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2380 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2381 TSO_STRUCT_SIZE)/sizeof(W_);
2382 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2383 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2385 debugTrace(DEBUG_sched,
2386 "increasing stack size from %ld words to %d.",
2387 (long)tso->stack_size, new_stack_size);
2389 dest = (StgTSO *)allocateLocal(cap,new_tso_size);
2390 TICK_ALLOC_TSO(new_stack_size,0);
2392 /* copy the TSO block and the old stack into the new area */
2393 memcpy(dest,tso,TSO_STRUCT_SIZE);
2394 stack_words = tso->stack + tso->stack_size - tso->sp;
2395 new_sp = (P_)dest + new_tso_size - stack_words;
2396 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2398 /* relocate the stack pointers... */
2400 dest->stack_size = new_stack_size;
2402 /* Mark the old TSO as relocated. We have to check for relocated
2403 * TSOs in the garbage collector and any primops that deal with TSOs.
2405 * It's important to set the sp value to just beyond the end
2406 * of the stack, so we don't attempt to scavenge any part of the
2409 tso->what_next = ThreadRelocated;
2410 setTSOLink(cap,tso,dest);
2411 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2412 tso->why_blocked = NotBlocked;
2414 IF_PAR_DEBUG(verbose,
2415 debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2416 tso->id, tso, tso->stack_size);
2417 /* If we're debugging, just print out the top of the stack */
2418 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2424 IF_DEBUG(sanity,checkTSO(dest));
2426 IF_DEBUG(scheduler,printTSO(dest));
2433 threadStackUnderflow (Task *task STG_UNUSED, StgTSO *tso)
2435 bdescr *bd, *new_bd;
2436 lnat free_w, tso_size_w;
2439 tso_size_w = tso_sizeW(tso);
2441 if (tso_size_w < MBLOCK_SIZE_W ||
2442 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2447 // don't allow throwTo() to modify the blocked_exceptions queue
2448 // while we are moving the TSO:
2449 lockClosure((StgClosure *)tso);
2451 // this is the number of words we'll free
2452 free_w = round_to_mblocks(tso_size_w/2);
2454 bd = Bdescr((StgPtr)tso);
2455 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2456 bd->free = bd->start + TSO_STRUCT_SIZEW;
2458 new_tso = (StgTSO *)new_bd->start;
2459 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2460 new_tso->stack_size = new_bd->free - new_tso->stack;
2462 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2463 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2465 tso->what_next = ThreadRelocated;
2466 tso->_link = new_tso; // no write barrier reqd: same generation
2468 // The TSO attached to this Task may have moved, so update the
2470 if (task->tso == tso) {
2471 task->tso = new_tso;
2477 IF_DEBUG(sanity,checkTSO(new_tso));
2482 /* ---------------------------------------------------------------------------
2484 - usually called inside a signal handler so it mustn't do anything fancy.
2485 ------------------------------------------------------------------------ */
2488 interruptStgRts(void)
2490 sched_state = SCHED_INTERRUPTING;
2491 setContextSwitches();
2495 /* -----------------------------------------------------------------------------
2498 This function causes at least one OS thread to wake up and run the
2499 scheduler loop. It is invoked when the RTS might be deadlocked, or
2500 an external event has arrived that may need servicing (eg. a
2501 keyboard interrupt).
2503 In the single-threaded RTS we don't do anything here; we only have
2504 one thread anyway, and the event that caused us to want to wake up
2505 will have interrupted any blocking system call in progress anyway.
2506 -------------------------------------------------------------------------- */
2511 #if defined(THREADED_RTS)
2512 // This forces the IO Manager thread to wakeup, which will
2513 // in turn ensure that some OS thread wakes up and runs the
2514 // scheduler loop, which will cause a GC and deadlock check.
2519 /* -----------------------------------------------------------------------------
2522 * Check the blackhole_queue for threads that can be woken up. We do
2523 * this periodically: before every GC, and whenever the run queue is
2526 * An elegant solution might be to just wake up all the blocked
2527 * threads with awakenBlockedQueue occasionally: they'll go back to
2528 * sleep again if the object is still a BLACKHOLE. Unfortunately this
2529 * doesn't give us a way to tell whether we've actually managed to
2530 * wake up any threads, so we would be busy-waiting.
2532 * -------------------------------------------------------------------------- */
2535 checkBlackHoles (Capability *cap)
2538 rtsBool any_woke_up = rtsFalse;
2541 // blackhole_queue is global:
2542 ASSERT_LOCK_HELD(&sched_mutex);
2544 debugTrace(DEBUG_sched, "checking threads blocked on black holes");
2546 // ASSUMES: sched_mutex
2547 prev = &blackhole_queue;
2548 t = blackhole_queue;
2549 while (t != END_TSO_QUEUE) {
2550 if (t->what_next == ThreadRelocated) {
2554 ASSERT(t->why_blocked == BlockedOnBlackHole);
2555 type = get_itbl(UNTAG_CLOSURE(t->block_info.closure))->type;
2556 if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
2557 IF_DEBUG(sanity,checkTSO(t));
2558 t = unblockOne(cap, t);
2560 any_woke_up = rtsTrue;
2570 /* -----------------------------------------------------------------------------
2573 This is used for interruption (^C) and forking, and corresponds to
2574 raising an exception but without letting the thread catch the
2576 -------------------------------------------------------------------------- */
2579 deleteThread (Capability *cap, StgTSO *tso)
2581 // NOTE: must only be called on a TSO that we have exclusive
2582 // access to, because we will call throwToSingleThreaded() below.
2583 // The TSO must be on the run queue of the Capability we own, or
2584 // we must own all Capabilities.
2586 if (tso->why_blocked != BlockedOnCCall &&
2587 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2588 throwToSingleThreaded(cap,tso,NULL);
2592 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2594 deleteThread_(Capability *cap, StgTSO *tso)
2595 { // for forkProcess only:
2596 // like deleteThread(), but we delete threads in foreign calls, too.
2598 if (tso->why_blocked == BlockedOnCCall ||
2599 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2600 unblockOne(cap,tso);
2601 tso->what_next = ThreadKilled;
2603 deleteThread(cap,tso);
2608 /* -----------------------------------------------------------------------------
2609 raiseExceptionHelper
2611 This function is called by the raise# primitve, just so that we can
2612 move some of the tricky bits of raising an exception from C-- into
2613 C. Who knows, it might be a useful re-useable thing here too.
2614 -------------------------------------------------------------------------- */
2617 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2619 Capability *cap = regTableToCapability(reg);
2620 StgThunk *raise_closure = NULL;
2622 StgRetInfoTable *info;
2624 // This closure represents the expression 'raise# E' where E
2625 // is the exception raise. It is used to overwrite all the
2626 // thunks which are currently under evaluataion.
2629 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2630 // LDV profiling: stg_raise_info has THUNK as its closure
2631 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2632 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2633 // 1 does not cause any problem unless profiling is performed.
2634 // However, when LDV profiling goes on, we need to linearly scan
2635 // small object pool, where raise_closure is stored, so we should
2636 // use MIN_UPD_SIZE.
2638 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2639 // sizeofW(StgClosure)+1);
2643 // Walk up the stack, looking for the catch frame. On the way,
2644 // we update any closures pointed to from update frames with the
2645 // raise closure that we just built.
2649 info = get_ret_itbl((StgClosure *)p);
2650 next = p + stack_frame_sizeW((StgClosure *)p);
2651 switch (info->i.type) {
2654 // Only create raise_closure if we need to.
2655 if (raise_closure == NULL) {
2657 (StgThunk *)allocateLocal(cap,sizeofW(StgThunk)+1);
2658 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2659 raise_closure->payload[0] = exception;
2661 UPD_IND(((StgUpdateFrame *)p)->updatee,(StgClosure *)raise_closure);
2665 case ATOMICALLY_FRAME:
2666 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2668 return ATOMICALLY_FRAME;
2674 case CATCH_STM_FRAME:
2675 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2677 return CATCH_STM_FRAME;
2683 case CATCH_RETRY_FRAME:
2692 /* -----------------------------------------------------------------------------
2693 findRetryFrameHelper
2695 This function is called by the retry# primitive. It traverses the stack
2696 leaving tso->sp referring to the frame which should handle the retry.
2698 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2699 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2701 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2702 create) because retries are not considered to be exceptions, despite the
2703 similar implementation.
2705 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2706 not be created within memory transactions.
2707 -------------------------------------------------------------------------- */
2710 findRetryFrameHelper (StgTSO *tso)
2713 StgRetInfoTable *info;
2717 info = get_ret_itbl((StgClosure *)p);
2718 next = p + stack_frame_sizeW((StgClosure *)p);
2719 switch (info->i.type) {
2721 case ATOMICALLY_FRAME:
2722 debugTrace(DEBUG_stm,
2723 "found ATOMICALLY_FRAME at %p during retry", p);
2725 return ATOMICALLY_FRAME;
2727 case CATCH_RETRY_FRAME:
2728 debugTrace(DEBUG_stm,
2729 "found CATCH_RETRY_FRAME at %p during retrry", p);
2731 return CATCH_RETRY_FRAME;
2733 case CATCH_STM_FRAME: {
2734 StgTRecHeader *trec = tso -> trec;
2735 StgTRecHeader *outer = stmGetEnclosingTRec(trec);
2736 debugTrace(DEBUG_stm,
2737 "found CATCH_STM_FRAME at %p during retry", p);
2738 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2739 stmAbortTransaction(tso -> cap, trec);
2740 stmFreeAbortedTRec(tso -> cap, trec);
2741 tso -> trec = outer;
2748 ASSERT(info->i.type != CATCH_FRAME);
2749 ASSERT(info->i.type != STOP_FRAME);
2756 /* -----------------------------------------------------------------------------
2757 resurrectThreads is called after garbage collection on the list of
2758 threads found to be garbage. Each of these threads will be woken
2759 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2760 on an MVar, or NonTermination if the thread was blocked on a Black
2763 Locks: assumes we hold *all* the capabilities.
2764 -------------------------------------------------------------------------- */
2767 resurrectThreads (StgTSO *threads)
2773 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2774 next = tso->global_link;
2776 step = Bdescr((P_)tso)->step;
2777 tso->global_link = step->threads;
2778 step->threads = tso;
2780 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2782 // Wake up the thread on the Capability it was last on
2785 switch (tso->why_blocked) {
2787 case BlockedOnException:
2788 /* Called by GC - sched_mutex lock is currently held. */
2789 throwToSingleThreaded(cap, tso,
2790 (StgClosure *)blockedOnDeadMVar_closure);
2792 case BlockedOnBlackHole:
2793 throwToSingleThreaded(cap, tso,
2794 (StgClosure *)nonTermination_closure);
2797 throwToSingleThreaded(cap, tso,
2798 (StgClosure *)blockedIndefinitely_closure);
2801 /* This might happen if the thread was blocked on a black hole
2802 * belonging to a thread that we've just woken up (raiseAsync
2803 * can wake up threads, remember...).
2807 barf("resurrectThreads: thread blocked in a strange way");
2812 /* -----------------------------------------------------------------------------
2813 performPendingThrowTos is called after garbage collection, and
2814 passed a list of threads that were found to have pending throwTos
2815 (tso->blocked_exceptions was not empty), and were blocked.
2816 Normally this doesn't happen, because we would deliver the
2817 exception directly if the target thread is blocked, but there are
2818 small windows where it might occur on a multiprocessor (see
2821 NB. we must be holding all the capabilities at this point, just
2822 like resurrectThreads().
2823 -------------------------------------------------------------------------- */
2826 performPendingThrowTos (StgTSO *threads)
2832 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2833 next = tso->global_link;
2835 step = Bdescr((P_)tso)->step;
2836 tso->global_link = step->threads;
2837 step->threads = tso;
2839 debugTrace(DEBUG_sched, "performing blocked throwTo to thread %lu", (unsigned long)tso->id);
2842 maybePerformBlockedException(cap, tso);