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"
36 /* PARALLEL_HASKELL includes go here */
39 #include "Capability.h"
41 #include "AwaitEvent.h"
42 #if defined(mingw32_HOST_OS)
43 #include "win32/IOManager.h"
46 #include "RaiseAsync.h"
48 #include "ThrIOManager.h"
50 #ifdef HAVE_SYS_TYPES_H
51 #include <sys/types.h>
65 // Turn off inlining when debugging - it obfuscates things
68 # define STATIC_INLINE static
71 /* -----------------------------------------------------------------------------
73 * -------------------------------------------------------------------------- */
75 #if !defined(THREADED_RTS)
76 // Blocked/sleeping thrads
77 StgTSO *blocked_queue_hd = NULL;
78 StgTSO *blocked_queue_tl = NULL;
79 StgTSO *sleeping_queue = NULL; // perhaps replace with a hash table?
82 /* Threads blocked on blackholes.
83 * LOCK: sched_mutex+capability, or all capabilities
85 StgTSO *blackhole_queue = NULL;
87 /* The blackhole_queue should be checked for threads to wake up. See
88 * Schedule.h for more thorough comment.
89 * LOCK: none (doesn't matter if we miss an update)
91 rtsBool blackholes_need_checking = rtsFalse;
93 /* Set to true when the latest garbage collection failed to reclaim
94 * enough space, and the runtime should proceed to shut itself down in
95 * an orderly fashion (emitting profiling info etc.)
97 rtsBool heap_overflow = rtsFalse;
99 /* flag that tracks whether we have done any execution in this time slice.
100 * LOCK: currently none, perhaps we should lock (but needs to be
101 * updated in the fast path of the scheduler).
103 * NB. must be StgWord, we do xchg() on it.
105 volatile StgWord recent_activity = ACTIVITY_YES;
107 /* if this flag is set as well, give up execution
108 * LOCK: none (changes monotonically)
110 volatile StgWord sched_state = SCHED_RUNNING;
112 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
113 * exists - earlier gccs apparently didn't.
119 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
120 * in an MT setting, needed to signal that a worker thread shouldn't hang around
121 * in the scheduler when it is out of work.
123 rtsBool shutting_down_scheduler = rtsFalse;
126 * This mutex protects most of the global scheduler data in
127 * the THREADED_RTS runtime.
129 #if defined(THREADED_RTS)
133 #if !defined(mingw32_HOST_OS)
134 #define FORKPROCESS_PRIMOP_SUPPORTED
137 /* -----------------------------------------------------------------------------
138 * static function prototypes
139 * -------------------------------------------------------------------------- */
141 static Capability *schedule (Capability *initialCapability, Task *task);
144 // These function all encapsulate parts of the scheduler loop, and are
145 // abstracted only to make the structure and control flow of the
146 // scheduler clearer.
148 static void schedulePreLoop (void);
149 static void scheduleFindWork (Capability *cap);
150 #if defined(THREADED_RTS)
151 static void scheduleYield (Capability **pcap, Task *task);
153 static void scheduleStartSignalHandlers (Capability *cap);
154 static void scheduleCheckBlockedThreads (Capability *cap);
155 static void scheduleCheckWakeupThreads(Capability *cap USED_IF_NOT_THREADS);
156 static void scheduleCheckBlackHoles (Capability *cap);
157 static void scheduleDetectDeadlock (Capability *cap, Task *task);
158 static void schedulePushWork(Capability *cap, Task *task);
159 #if defined(PARALLEL_HASKELL)
160 static rtsBool scheduleGetRemoteWork(Capability *cap);
161 static void scheduleSendPendingMessages(void);
163 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
164 static void scheduleActivateSpark(Capability *cap);
166 static void schedulePostRunThread(Capability *cap, StgTSO *t);
167 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
168 static void scheduleHandleStackOverflow( Capability *cap, Task *task,
170 static rtsBool scheduleHandleYield( Capability *cap, StgTSO *t,
171 nat prev_what_next );
172 static void scheduleHandleThreadBlocked( StgTSO *t );
173 static rtsBool scheduleHandleThreadFinished( Capability *cap, Task *task,
175 static rtsBool scheduleNeedHeapProfile(rtsBool ready_to_gc);
176 static Capability *scheduleDoGC(Capability *cap, Task *task,
177 rtsBool force_major);
179 static rtsBool checkBlackHoles(Capability *cap);
181 static StgTSO *threadStackOverflow(Capability *cap, StgTSO *tso);
182 static StgTSO *threadStackUnderflow(Task *task, StgTSO *tso);
184 static void deleteThread (Capability *cap, StgTSO *tso);
185 static void deleteAllThreads (Capability *cap);
187 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
188 static void deleteThread_(Capability *cap, StgTSO *tso);
192 static char *whatNext_strs[] = {
202 /* -----------------------------------------------------------------------------
203 * Putting a thread on the run queue: different scheduling policies
204 * -------------------------------------------------------------------------- */
207 addToRunQueue( Capability *cap, StgTSO *t )
209 #if defined(PARALLEL_HASKELL)
210 if (RtsFlags.ParFlags.doFairScheduling) {
211 // this does round-robin scheduling; good for concurrency
212 appendToRunQueue(cap,t);
214 // this does unfair scheduling; good for parallelism
215 pushOnRunQueue(cap,t);
218 // this does round-robin scheduling; good for concurrency
219 appendToRunQueue(cap,t);
223 /* ---------------------------------------------------------------------------
224 Main scheduling loop.
226 We use round-robin scheduling, each thread returning to the
227 scheduler loop when one of these conditions is detected:
230 * timer expires (thread yields)
236 In a GranSim setup this loop iterates over the global event queue.
237 This revolves around the global event queue, which determines what
238 to do next. Therefore, it's more complicated than either the
239 concurrent or the parallel (GUM) setup.
240 This version has been entirely removed (JB 2008/08).
243 GUM iterates over incoming messages.
244 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
245 and sends out a fish whenever it has nothing to do; in-between
246 doing the actual reductions (shared code below) it processes the
247 incoming messages and deals with delayed operations
248 (see PendingFetches).
249 This is not the ugliest code you could imagine, but it's bloody close.
251 (JB 2008/08) This version was formerly indicated by a PP-Flag PAR,
252 now by PP-flag PARALLEL_HASKELL. The Eden RTS (in GHC-6.x) uses it,
253 as well as future GUM versions. This file has been refurbished to
254 only contain valid code, which is however incomplete, refers to
255 invalid includes etc.
257 ------------------------------------------------------------------------ */
260 schedule (Capability *initialCapability, Task *task)
264 StgThreadReturnCode ret;
265 #if defined(PARALLEL_HASKELL)
266 rtsBool receivedFinish = rtsFalse;
270 #if defined(THREADED_RTS)
271 rtsBool first = rtsTrue;
274 cap = initialCapability;
276 // Pre-condition: this task owns initialCapability.
277 // The sched_mutex is *NOT* held
278 // NB. on return, we still hold a capability.
280 debugTrace (DEBUG_sched,
281 "### NEW SCHEDULER LOOP (task: %p, cap: %p)",
282 task, initialCapability);
286 // -----------------------------------------------------------
287 // Scheduler loop starts here:
289 #if defined(PARALLEL_HASKELL)
290 #define TERMINATION_CONDITION (!receivedFinish)
292 #define TERMINATION_CONDITION rtsTrue
295 while (TERMINATION_CONDITION) {
297 // Check whether we have re-entered the RTS from Haskell without
298 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
300 if (cap->in_haskell) {
301 errorBelch("schedule: re-entered unsafely.\n"
302 " Perhaps a 'foreign import unsafe' should be 'safe'?");
303 stg_exit(EXIT_FAILURE);
306 // The interruption / shutdown sequence.
308 // In order to cleanly shut down the runtime, we want to:
309 // * make sure that all main threads return to their callers
310 // with the state 'Interrupted'.
311 // * clean up all OS threads assocated with the runtime
312 // * free all memory etc.
314 // So the sequence for ^C goes like this:
316 // * ^C handler sets sched_state := SCHED_INTERRUPTING and
317 // arranges for some Capability to wake up
319 // * all threads in the system are halted, and the zombies are
320 // placed on the run queue for cleaning up. We acquire all
321 // the capabilities in order to delete the threads, this is
322 // done by scheduleDoGC() for convenience (because GC already
323 // needs to acquire all the capabilities). We can't kill
324 // threads involved in foreign calls.
326 // * somebody calls shutdownHaskell(), which calls exitScheduler()
328 // * sched_state := SCHED_SHUTTING_DOWN
330 // * all workers exit when the run queue on their capability
331 // drains. All main threads will also exit when their TSO
332 // reaches the head of the run queue and they can return.
334 // * eventually all Capabilities will shut down, and the RTS can
337 // * We might be left with threads blocked in foreign calls,
338 // we should really attempt to kill these somehow (TODO);
340 switch (sched_state) {
343 case SCHED_INTERRUPTING:
344 debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
345 #if defined(THREADED_RTS)
346 discardSparksCap(cap);
348 /* scheduleDoGC() deletes all the threads */
349 cap = scheduleDoGC(cap,task,rtsFalse);
351 // after scheduleDoGC(), we must be shutting down. Either some
352 // other Capability did the final GC, or we did it above,
353 // either way we can fall through to the SCHED_SHUTTING_DOWN
355 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
358 case SCHED_SHUTTING_DOWN:
359 debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
360 // If we are a worker, just exit. If we're a bound thread
361 // then we will exit below when we've removed our TSO from
363 if (task->tso == NULL && emptyRunQueue(cap)) {
368 barf("sched_state: %d", sched_state);
371 scheduleFindWork(cap);
373 /* work pushing, currently relevant only for THREADED_RTS:
374 (pushes threads, wakes up idle capabilities for stealing) */
375 schedulePushWork(cap,task);
377 #if defined(PARALLEL_HASKELL)
378 /* since we perform a blocking receive and continue otherwise,
379 either we never reach here or we definitely have work! */
380 // from here: non-empty run queue
381 ASSERT(!emptyRunQueue(cap));
383 if (PacketsWaiting()) { /* now process incoming messages, if any
386 CAUTION: scheduleGetRemoteWork called
387 above, waits for messages as well! */
388 processMessages(cap, &receivedFinish);
390 #endif // PARALLEL_HASKELL: non-empty run queue!
392 scheduleDetectDeadlock(cap,task);
394 #if defined(THREADED_RTS)
395 cap = task->cap; // reload cap, it might have changed
398 // Normally, the only way we can get here with no threads to
399 // run is if a keyboard interrupt received during
400 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
401 // Additionally, it is not fatal for the
402 // threaded RTS to reach here with no threads to run.
404 // win32: might be here due to awaitEvent() being abandoned
405 // as a result of a console event having been delivered.
407 #if defined(THREADED_RTS)
411 // // don't yield the first time, we want a chance to run this
412 // // thread for a bit, even if there are others banging at the
415 // ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
419 scheduleYield(&cap,task);
420 if (emptyRunQueue(cap)) continue; // look for work again
423 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
424 if ( emptyRunQueue(cap) ) {
425 ASSERT(sched_state >= SCHED_INTERRUPTING);
430 // Get a thread to run
432 t = popRunQueue(cap);
434 // Sanity check the thread we're about to run. This can be
435 // expensive if there is lots of thread switching going on...
436 IF_DEBUG(sanity,checkTSO(t));
438 #if defined(THREADED_RTS)
439 // Check whether we can run this thread in the current task.
440 // If not, we have to pass our capability to the right task.
442 Task *bound = t->bound;
446 debugTrace(DEBUG_sched,
447 "### Running thread %lu in bound thread", (unsigned long)t->id);
448 // yes, the Haskell thread is bound to the current native thread
450 debugTrace(DEBUG_sched,
451 "### thread %lu bound to another OS thread", (unsigned long)t->id);
452 // no, bound to a different Haskell thread: pass to that thread
453 pushOnRunQueue(cap,t);
457 // The thread we want to run is unbound.
459 debugTrace(DEBUG_sched,
460 "### this OS thread cannot run thread %lu", (unsigned long)t->id);
461 // no, the current native thread is bound to a different
462 // Haskell thread, so pass it to any worker thread
463 pushOnRunQueue(cap,t);
470 // If we're shutting down, and this thread has not yet been
471 // killed, kill it now. This sometimes happens when a finalizer
472 // thread is created by the final GC, or a thread previously
473 // in a foreign call returns.
474 if (sched_state >= SCHED_INTERRUPTING &&
475 !(t->what_next == ThreadComplete || t->what_next == ThreadKilled)) {
479 /* context switches are initiated by the timer signal, unless
480 * the user specified "context switch as often as possible", with
483 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
484 && !emptyThreadQueues(cap)) {
485 cap->context_switch = 1;
490 // CurrentTSO is the thread to run. t might be different if we
491 // loop back to run_thread, so make sure to set CurrentTSO after
493 cap->r.rCurrentTSO = t;
495 debugTrace(DEBUG_sched, "-->> running thread %ld %s ...",
496 (long)t->id, whatNext_strs[t->what_next]);
498 startHeapProfTimer();
500 // Check for exceptions blocked on this thread
501 maybePerformBlockedException (cap, t);
503 // ----------------------------------------------------------------------
504 // Run the current thread
506 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
507 ASSERT(t->cap == cap);
508 ASSERT(t->bound ? t->bound->cap == cap : 1);
510 prev_what_next = t->what_next;
512 errno = t->saved_errno;
514 SetLastError(t->saved_winerror);
517 cap->in_haskell = rtsTrue;
521 #if defined(THREADED_RTS)
522 if (recent_activity == ACTIVITY_DONE_GC) {
523 // ACTIVITY_DONE_GC means we turned off the timer signal to
524 // conserve power (see #1623). Re-enable it here.
526 prev = xchg((P_)&recent_activity, ACTIVITY_YES);
527 if (prev == ACTIVITY_DONE_GC) {
531 recent_activity = ACTIVITY_YES;
535 switch (prev_what_next) {
539 /* Thread already finished, return to scheduler. */
540 ret = ThreadFinished;
546 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
547 cap = regTableToCapability(r);
552 case ThreadInterpret:
553 cap = interpretBCO(cap);
558 barf("schedule: invalid what_next field");
561 cap->in_haskell = rtsFalse;
563 // The TSO might have moved, eg. if it re-entered the RTS and a GC
564 // happened. So find the new location:
565 t = cap->r.rCurrentTSO;
567 // We have run some Haskell code: there might be blackhole-blocked
568 // threads to wake up now.
569 // Lock-free test here should be ok, we're just setting a flag.
570 if ( blackhole_queue != END_TSO_QUEUE ) {
571 blackholes_need_checking = rtsTrue;
574 // And save the current errno in this thread.
575 // XXX: possibly bogus for SMP because this thread might already
576 // be running again, see code below.
577 t->saved_errno = errno;
579 // Similarly for Windows error code
580 t->saved_winerror = GetLastError();
583 #if defined(THREADED_RTS)
584 // If ret is ThreadBlocked, and this Task is bound to the TSO that
585 // blocked, we are in limbo - the TSO is now owned by whatever it
586 // is blocked on, and may in fact already have been woken up,
587 // perhaps even on a different Capability. It may be the case
588 // that task->cap != cap. We better yield this Capability
589 // immediately and return to normaility.
590 if (ret == ThreadBlocked) {
591 debugTrace(DEBUG_sched,
592 "--<< thread %lu (%s) stopped: blocked",
593 (unsigned long)t->id, whatNext_strs[t->what_next]);
598 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
599 ASSERT(t->cap == cap);
601 // ----------------------------------------------------------------------
603 // Costs for the scheduler are assigned to CCS_SYSTEM
605 #if defined(PROFILING)
609 schedulePostRunThread(cap,t);
611 t = threadStackUnderflow(task,t);
613 ready_to_gc = rtsFalse;
617 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
621 scheduleHandleStackOverflow(cap,task,t);
625 if (scheduleHandleYield(cap, t, prev_what_next)) {
626 // shortcut for switching between compiler/interpreter:
632 scheduleHandleThreadBlocked(t);
636 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
637 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
641 barf("schedule: invalid thread return code %d", (int)ret);
644 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
645 cap = scheduleDoGC(cap,task,rtsFalse);
647 } /* end of while() */
650 /* ----------------------------------------------------------------------------
651 * Setting up the scheduler loop
652 * ------------------------------------------------------------------------- */
655 schedulePreLoop(void)
657 // initialisation for scheduler - what cannot go into initScheduler()
660 /* -----------------------------------------------------------------------------
663 * Search for work to do, and handle messages from elsewhere.
664 * -------------------------------------------------------------------------- */
667 scheduleFindWork (Capability *cap)
669 scheduleStartSignalHandlers(cap);
671 // Only check the black holes here if we've nothing else to do.
672 // During normal execution, the black hole list only gets checked
673 // at GC time, to avoid repeatedly traversing this possibly long
674 // list each time around the scheduler.
675 if (emptyRunQueue(cap)) { scheduleCheckBlackHoles(cap); }
677 scheduleCheckWakeupThreads(cap);
679 scheduleCheckBlockedThreads(cap);
681 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
682 if (emptyRunQueue(cap)) { scheduleActivateSpark(cap); }
685 #if defined(PARALLEL_HASKELL)
686 // if messages have been buffered...
687 scheduleSendPendingMessages();
690 #if defined(PARALLEL_HASKELL)
691 if (emptyRunQueue(cap)) {
692 receivedFinish = scheduleGetRemoteWork(cap);
693 continue; // a new round, (hopefully) with new work
695 in GUM, this a) sends out a FISH and returns IF no fish is
697 b) (blocking) awaits and receives messages
699 in Eden, this is only the blocking receive, as b) in GUM.
705 #if defined(THREADED_RTS)
706 STATIC_INLINE rtsBool
707 shouldYieldCapability (Capability *cap, Task *task)
709 // we need to yield this capability to someone else if..
710 // - another thread is initiating a GC
711 // - another Task is returning from a foreign call
712 // - the thread at the head of the run queue cannot be run
713 // by this Task (it is bound to another Task, or it is unbound
714 // and this task it bound).
715 return (waiting_for_gc ||
716 cap->returning_tasks_hd != NULL ||
717 (!emptyRunQueue(cap) && (task->tso == NULL
718 ? cap->run_queue_hd->bound != NULL
719 : cap->run_queue_hd->bound != task)));
722 // This is the single place where a Task goes to sleep. There are
723 // two reasons it might need to sleep:
724 // - there are no threads to run
725 // - we need to yield this Capability to someone else
726 // (see shouldYieldCapability())
728 // Careful: the scheduler loop is quite delicate. Make sure you run
729 // the tests in testsuite/concurrent (all ways) after modifying this,
730 // and also check the benchmarks in nofib/parallel for regressions.
733 scheduleYield (Capability **pcap, Task *task)
735 Capability *cap = *pcap;
737 // if we have work, and we don't need to give up the Capability, continue.
738 if (!shouldYieldCapability(cap,task) &&
739 (!emptyRunQueue(cap) ||
740 blackholes_need_checking ||
741 sched_state >= SCHED_INTERRUPTING))
744 // otherwise yield (sleep), and keep yielding if necessary.
746 yieldCapability(&cap,task);
748 while (shouldYieldCapability(cap,task));
750 // note there may still be no threads on the run queue at this
751 // point, the caller has to check.
758 /* -----------------------------------------------------------------------------
761 * Push work to other Capabilities if we have some.
762 * -------------------------------------------------------------------------- */
765 schedulePushWork(Capability *cap USED_IF_THREADS,
766 Task *task USED_IF_THREADS)
768 /* following code not for PARALLEL_HASKELL. I kept the call general,
769 future GUM versions might use pushing in a distributed setup */
770 #if defined(THREADED_RTS)
772 Capability *free_caps[n_capabilities], *cap0;
775 // migration can be turned off with +RTS -qg
776 if (!RtsFlags.ParFlags.migrate) return;
778 // Check whether we have more threads on our run queue, or sparks
779 // in our pool, that we could hand to another Capability.
780 if (cap->run_queue_hd == END_TSO_QUEUE) {
781 if (sparkPoolSizeCap(cap) < 2) return;
783 if (cap->run_queue_hd->_link == END_TSO_QUEUE &&
784 sparkPoolSizeCap(cap) < 1) return;
787 // First grab as many free Capabilities as we can.
788 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
789 cap0 = &capabilities[i];
790 if (cap != cap0 && tryGrabCapability(cap0,task)) {
791 if (!emptyRunQueue(cap0) || cap->returning_tasks_hd != NULL) {
792 // it already has some work, we just grabbed it at
793 // the wrong moment. Or maybe it's deadlocked!
794 releaseCapability(cap0);
796 free_caps[n_free_caps++] = cap0;
801 // we now have n_free_caps free capabilities stashed in
802 // free_caps[]. Share our run queue equally with them. This is
803 // probably the simplest thing we could do; improvements we might
804 // want to do include:
806 // - giving high priority to moving relatively new threads, on
807 // the gournds that they haven't had time to build up a
808 // working set in the cache on this CPU/Capability.
810 // - giving low priority to moving long-lived threads
812 if (n_free_caps > 0) {
813 StgTSO *prev, *t, *next;
814 rtsBool pushed_to_all;
816 debugTrace(DEBUG_sched,
817 "cap %d: %s and %d free capabilities, sharing...",
819 (!emptyRunQueue(cap) && cap->run_queue_hd->_link != END_TSO_QUEUE)?
820 "excess threads on run queue":"sparks to share (>=2)",
824 pushed_to_all = rtsFalse;
826 if (cap->run_queue_hd != END_TSO_QUEUE) {
827 prev = cap->run_queue_hd;
829 prev->_link = END_TSO_QUEUE;
830 for (; t != END_TSO_QUEUE; t = next) {
832 t->_link = END_TSO_QUEUE;
833 if (t->what_next == ThreadRelocated
834 || t->bound == task // don't move my bound thread
835 || tsoLocked(t)) { // don't move a locked thread
836 setTSOLink(cap, prev, t);
838 } else if (i == n_free_caps) {
839 pushed_to_all = rtsTrue;
842 setTSOLink(cap, prev, t);
845 debugTrace(DEBUG_sched, "pushing thread %lu to capability %d", (unsigned long)t->id, free_caps[i]->no);
846 appendToRunQueue(free_caps[i],t);
847 if (t->bound) { t->bound->cap = free_caps[i]; }
848 t->cap = free_caps[i];
852 cap->run_queue_tl = prev;
856 /* JB I left this code in place, it would work but is not necessary */
858 // If there are some free capabilities that we didn't push any
859 // threads to, then try to push a spark to each one.
860 if (!pushed_to_all) {
862 // i is the next free capability to push to
863 for (; i < n_free_caps; i++) {
864 if (emptySparkPoolCap(free_caps[i])) {
865 spark = tryStealSpark(cap->sparks);
867 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
868 newSpark(&(free_caps[i]->r), spark);
873 #endif /* SPARK_PUSHING */
875 // release the capabilities
876 for (i = 0; i < n_free_caps; i++) {
877 task->cap = free_caps[i];
878 releaseAndWakeupCapability(free_caps[i]);
881 task->cap = cap; // reset to point to our Capability.
883 #endif /* THREADED_RTS */
887 /* ----------------------------------------------------------------------------
888 * Start any pending signal handlers
889 * ------------------------------------------------------------------------- */
891 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
893 scheduleStartSignalHandlers(Capability *cap)
895 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
896 // safe outside the lock
897 startSignalHandlers(cap);
902 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
907 /* ----------------------------------------------------------------------------
908 * Check for blocked threads that can be woken up.
909 * ------------------------------------------------------------------------- */
912 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
914 #if !defined(THREADED_RTS)
916 // Check whether any waiting threads need to be woken up. If the
917 // run queue is empty, and there are no other tasks running, we
918 // can wait indefinitely for something to happen.
920 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
922 awaitEvent( emptyRunQueue(cap) && !blackholes_need_checking );
928 /* ----------------------------------------------------------------------------
929 * Check for threads woken up by other Capabilities
930 * ------------------------------------------------------------------------- */
933 scheduleCheckWakeupThreads(Capability *cap USED_IF_THREADS)
935 #if defined(THREADED_RTS)
936 // Any threads that were woken up by other Capabilities get
937 // appended to our run queue.
938 if (!emptyWakeupQueue(cap)) {
939 ACQUIRE_LOCK(&cap->lock);
940 if (emptyRunQueue(cap)) {
941 cap->run_queue_hd = cap->wakeup_queue_hd;
942 cap->run_queue_tl = cap->wakeup_queue_tl;
944 setTSOLink(cap, cap->run_queue_tl, cap->wakeup_queue_hd);
945 cap->run_queue_tl = cap->wakeup_queue_tl;
947 cap->wakeup_queue_hd = cap->wakeup_queue_tl = END_TSO_QUEUE;
948 RELEASE_LOCK(&cap->lock);
953 /* ----------------------------------------------------------------------------
954 * Check for threads blocked on BLACKHOLEs that can be woken up
955 * ------------------------------------------------------------------------- */
957 scheduleCheckBlackHoles (Capability *cap)
959 if ( blackholes_need_checking ) // check without the lock first
961 ACQUIRE_LOCK(&sched_mutex);
962 if ( blackholes_need_checking ) {
963 blackholes_need_checking = rtsFalse;
964 // important that we reset the flag *before* checking the
965 // blackhole queue, otherwise we could get deadlock. This
966 // happens as follows: we wake up a thread that
967 // immediately runs on another Capability, blocks on a
968 // blackhole, and then we reset the blackholes_need_checking flag.
969 checkBlackHoles(cap);
971 RELEASE_LOCK(&sched_mutex);
975 /* ----------------------------------------------------------------------------
976 * Detect deadlock conditions and attempt to resolve them.
977 * ------------------------------------------------------------------------- */
980 scheduleDetectDeadlock (Capability *cap, Task *task)
983 #if defined(PARALLEL_HASKELL)
984 // ToDo: add deadlock detection in GUM (similar to THREADED_RTS) -- HWL
989 * Detect deadlock: when we have no threads to run, there are no
990 * threads blocked, waiting for I/O, or sleeping, and all the
991 * other tasks are waiting for work, we must have a deadlock of
994 if ( emptyThreadQueues(cap) )
996 #if defined(THREADED_RTS)
998 * In the threaded RTS, we only check for deadlock if there
999 * has been no activity in a complete timeslice. This means
1000 * we won't eagerly start a full GC just because we don't have
1001 * any threads to run currently.
1003 if (recent_activity != ACTIVITY_INACTIVE) return;
1006 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
1008 // Garbage collection can release some new threads due to
1009 // either (a) finalizers or (b) threads resurrected because
1010 // they are unreachable and will therefore be sent an
1011 // exception. Any threads thus released will be immediately
1013 cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
1014 // when force_major == rtsTrue. scheduleDoGC sets
1015 // recent_activity to ACTIVITY_DONE_GC and turns off the timer
1018 if ( !emptyRunQueue(cap) ) return;
1020 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
1021 /* If we have user-installed signal handlers, then wait
1022 * for signals to arrive rather then bombing out with a
1025 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
1026 debugTrace(DEBUG_sched,
1027 "still deadlocked, waiting for signals...");
1031 if (signals_pending()) {
1032 startSignalHandlers(cap);
1035 // either we have threads to run, or we were interrupted:
1036 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
1042 #if !defined(THREADED_RTS)
1043 /* Probably a real deadlock. Send the current main thread the
1044 * Deadlock exception.
1047 switch (task->tso->why_blocked) {
1049 case BlockedOnBlackHole:
1050 case BlockedOnException:
1052 throwToSingleThreaded(cap, task->tso,
1053 (StgClosure *)nonTermination_closure);
1056 barf("deadlock: main thread blocked in a strange way");
1065 /* ----------------------------------------------------------------------------
1066 * Send pending messages (PARALLEL_HASKELL only)
1067 * ------------------------------------------------------------------------- */
1069 #if defined(PARALLEL_HASKELL)
1071 scheduleSendPendingMessages(void)
1074 # if defined(PAR) // global Mem.Mgmt., omit for now
1075 if (PendingFetches != END_BF_QUEUE) {
1080 if (RtsFlags.ParFlags.BufferTime) {
1081 // if we use message buffering, we must send away all message
1082 // packets which have become too old...
1088 /* ----------------------------------------------------------------------------
1089 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
1090 * ------------------------------------------------------------------------- */
1092 #if defined(PARALLEL_HASKELL) || defined(THREADED_RTS)
1094 scheduleActivateSpark(Capability *cap)
1098 createSparkThread(cap);
1099 debugTrace(DEBUG_sched, "creating a spark thread");
1102 #endif // PARALLEL_HASKELL || THREADED_RTS
1104 /* ----------------------------------------------------------------------------
1105 * Get work from a remote node (PARALLEL_HASKELL only)
1106 * ------------------------------------------------------------------------- */
1108 #if defined(PARALLEL_HASKELL)
1109 static rtsBool /* return value used in PARALLEL_HASKELL only */
1110 scheduleGetRemoteWork (Capability *cap STG_UNUSED)
1112 #if defined(PARALLEL_HASKELL)
1113 rtsBool receivedFinish = rtsFalse;
1115 // idle() , i.e. send all buffers, wait for work
1116 if (RtsFlags.ParFlags.BufferTime) {
1117 IF_PAR_DEBUG(verbose,
1118 debugBelch("...send all pending data,"));
1121 for (i=1; i<=nPEs; i++)
1122 sendImmediately(i); // send all messages away immediately
1126 /* this would be the place for fishing in GUM...
1128 if (no-earlier-fish-around)
1129 sendFish(choosePe());
1132 // Eden:just look for incoming messages (blocking receive)
1133 IF_PAR_DEBUG(verbose,
1134 debugBelch("...wait for incoming messages...\n"));
1135 processMessages(cap, &receivedFinish); // blocking receive...
1138 return receivedFinish;
1139 // reenter scheduling look after having received something
1141 #else /* !PARALLEL_HASKELL, i.e. THREADED_RTS */
1143 return rtsFalse; /* return value unused in THREADED_RTS */
1145 #endif /* PARALLEL_HASKELL */
1147 #endif // PARALLEL_HASKELL || THREADED_RTS
1149 /* ----------------------------------------------------------------------------
1150 * After running a thread...
1151 * ------------------------------------------------------------------------- */
1154 schedulePostRunThread (Capability *cap, StgTSO *t)
1156 // We have to be able to catch transactions that are in an
1157 // infinite loop as a result of seeing an inconsistent view of
1161 // [a,b] <- mapM readTVar [ta,tb]
1162 // when (a == b) loop
1164 // and a is never equal to b given a consistent view of memory.
1166 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1167 if (!stmValidateNestOfTransactions (t -> trec)) {
1168 debugTrace(DEBUG_sched | DEBUG_stm,
1169 "trec %p found wasting its time", t);
1171 // strip the stack back to the
1172 // ATOMICALLY_FRAME, aborting the (nested)
1173 // transaction, and saving the stack of any
1174 // partially-evaluated thunks on the heap.
1175 throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1177 ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1181 /* some statistics gathering in the parallel case */
1184 /* -----------------------------------------------------------------------------
1185 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1186 * -------------------------------------------------------------------------- */
1189 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1191 // did the task ask for a large block?
1192 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1193 // if so, get one and push it on the front of the nursery.
1197 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1199 debugTrace(DEBUG_sched,
1200 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1201 (long)t->id, whatNext_strs[t->what_next], blocks);
1203 // don't do this if the nursery is (nearly) full, we'll GC first.
1204 if (cap->r.rCurrentNursery->link != NULL ||
1205 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1206 // if the nursery has only one block.
1209 bd = allocGroup( blocks );
1211 cap->r.rNursery->n_blocks += blocks;
1213 // link the new group into the list
1214 bd->link = cap->r.rCurrentNursery;
1215 bd->u.back = cap->r.rCurrentNursery->u.back;
1216 if (cap->r.rCurrentNursery->u.back != NULL) {
1217 cap->r.rCurrentNursery->u.back->link = bd;
1219 #if !defined(THREADED_RTS)
1220 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1221 g0s0 == cap->r.rNursery);
1223 cap->r.rNursery->blocks = bd;
1225 cap->r.rCurrentNursery->u.back = bd;
1227 // initialise it as a nursery block. We initialise the
1228 // step, gen_no, and flags field of *every* sub-block in
1229 // this large block, because this is easier than making
1230 // sure that we always find the block head of a large
1231 // block whenever we call Bdescr() (eg. evacuate() and
1232 // isAlive() in the GC would both have to do this, at
1236 for (x = bd; x < bd + blocks; x++) {
1237 x->step = cap->r.rNursery;
1243 // This assert can be a killer if the app is doing lots
1244 // of large block allocations.
1245 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1247 // now update the nursery to point to the new block
1248 cap->r.rCurrentNursery = bd;
1250 // we might be unlucky and have another thread get on the
1251 // run queue before us and steal the large block, but in that
1252 // case the thread will just end up requesting another large
1254 pushOnRunQueue(cap,t);
1255 return rtsFalse; /* not actually GC'ing */
1259 debugTrace(DEBUG_sched,
1260 "--<< thread %ld (%s) stopped: HeapOverflow",
1261 (long)t->id, whatNext_strs[t->what_next]);
1263 if (cap->context_switch) {
1264 // Sometimes we miss a context switch, e.g. when calling
1265 // primitives in a tight loop, MAYBE_GC() doesn't check the
1266 // context switch flag, and we end up waiting for a GC.
1267 // See #1984, and concurrent/should_run/1984
1268 cap->context_switch = 0;
1269 addToRunQueue(cap,t);
1271 pushOnRunQueue(cap,t);
1274 /* actual GC is done at the end of the while loop in schedule() */
1277 /* -----------------------------------------------------------------------------
1278 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1279 * -------------------------------------------------------------------------- */
1282 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1284 debugTrace (DEBUG_sched,
1285 "--<< thread %ld (%s) stopped, StackOverflow",
1286 (long)t->id, whatNext_strs[t->what_next]);
1288 /* just adjust the stack for this thread, then pop it back
1292 /* enlarge the stack */
1293 StgTSO *new_t = threadStackOverflow(cap, t);
1295 /* The TSO attached to this Task may have moved, so update the
1298 if (task->tso == t) {
1301 pushOnRunQueue(cap,new_t);
1305 /* -----------------------------------------------------------------------------
1306 * Handle a thread that returned to the scheduler with ThreadYielding
1307 * -------------------------------------------------------------------------- */
1310 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1312 // Reset the context switch flag. We don't do this just before
1313 // running the thread, because that would mean we would lose ticks
1314 // during GC, which can lead to unfair scheduling (a thread hogs
1315 // the CPU because the tick always arrives during GC). This way
1316 // penalises threads that do a lot of allocation, but that seems
1317 // better than the alternative.
1318 cap->context_switch = 0;
1320 /* put the thread back on the run queue. Then, if we're ready to
1321 * GC, check whether this is the last task to stop. If so, wake
1322 * up the GC thread. getThread will block during a GC until the
1326 if (t->what_next != prev_what_next) {
1327 debugTrace(DEBUG_sched,
1328 "--<< thread %ld (%s) stopped to switch evaluators",
1329 (long)t->id, whatNext_strs[t->what_next]);
1331 debugTrace(DEBUG_sched,
1332 "--<< thread %ld (%s) stopped, yielding",
1333 (long)t->id, whatNext_strs[t->what_next]);
1338 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1340 ASSERT(t->_link == END_TSO_QUEUE);
1342 // Shortcut if we're just switching evaluators: don't bother
1343 // doing stack squeezing (which can be expensive), just run the
1345 if (t->what_next != prev_what_next) {
1349 addToRunQueue(cap,t);
1354 /* -----------------------------------------------------------------------------
1355 * Handle a thread that returned to the scheduler with ThreadBlocked
1356 * -------------------------------------------------------------------------- */
1359 scheduleHandleThreadBlocked( StgTSO *t
1360 #if !defined(GRAN) && !defined(DEBUG)
1366 // We don't need to do anything. The thread is blocked, and it
1367 // has tidied up its stack and placed itself on whatever queue
1368 // it needs to be on.
1370 // ASSERT(t->why_blocked != NotBlocked);
1371 // Not true: for example,
1372 // - in THREADED_RTS, the thread may already have been woken
1373 // up by another Capability. This actually happens: try
1374 // conc023 +RTS -N2.
1375 // - the thread may have woken itself up already, because
1376 // threadPaused() might have raised a blocked throwTo
1377 // exception, see maybePerformBlockedException().
1380 if (traceClass(DEBUG_sched)) {
1381 debugTraceBegin("--<< thread %lu (%s) stopped: ",
1382 (unsigned long)t->id, whatNext_strs[t->what_next]);
1383 printThreadBlockage(t);
1389 /* -----------------------------------------------------------------------------
1390 * Handle a thread that returned to the scheduler with ThreadFinished
1391 * -------------------------------------------------------------------------- */
1394 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1396 /* Need to check whether this was a main thread, and if so,
1397 * return with the return value.
1399 * We also end up here if the thread kills itself with an
1400 * uncaught exception, see Exception.cmm.
1402 debugTrace(DEBUG_sched, "--++ thread %lu (%s) finished",
1403 (unsigned long)t->id, whatNext_strs[t->what_next]);
1405 // blocked exceptions can now complete, even if the thread was in
1406 // blocked mode (see #2910). The thread is already marked
1407 // ThreadComplete, so any further throwTos will complete
1408 // immediately and we don't need to worry about synchronising with
1410 awakenBlockedExceptionQueue (cap, t);
1413 // Check whether the thread that just completed was a bound
1414 // thread, and if so return with the result.
1416 // There is an assumption here that all thread completion goes
1417 // through this point; we need to make sure that if a thread
1418 // ends up in the ThreadKilled state, that it stays on the run
1419 // queue so it can be dealt with here.
1424 if (t->bound != task) {
1425 #if !defined(THREADED_RTS)
1426 // Must be a bound thread that is not the topmost one. Leave
1427 // it on the run queue until the stack has unwound to the
1428 // point where we can deal with this. Leaving it on the run
1429 // queue also ensures that the garbage collector knows about
1430 // this thread and its return value (it gets dropped from the
1431 // step->threads list so there's no other way to find it).
1432 appendToRunQueue(cap,t);
1435 // this cannot happen in the threaded RTS, because a
1436 // bound thread can only be run by the appropriate Task.
1437 barf("finished bound thread that isn't mine");
1441 ASSERT(task->tso == t);
1443 if (t->what_next == ThreadComplete) {
1445 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1446 *(task->ret) = (StgClosure *)task->tso->sp[1];
1448 task->stat = Success;
1451 *(task->ret) = NULL;
1453 if (sched_state >= SCHED_INTERRUPTING) {
1454 if (heap_overflow) {
1455 task->stat = HeapExhausted;
1457 task->stat = Interrupted;
1460 task->stat = Killed;
1464 removeThreadLabel((StgWord)task->tso->id);
1466 return rtsTrue; // tells schedule() to return
1472 /* -----------------------------------------------------------------------------
1473 * Perform a heap census
1474 * -------------------------------------------------------------------------- */
1477 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1479 // When we have +RTS -i0 and we're heap profiling, do a census at
1480 // every GC. This lets us get repeatable runs for debugging.
1481 if (performHeapProfile ||
1482 (RtsFlags.ProfFlags.profileInterval==0 &&
1483 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1490 /* -----------------------------------------------------------------------------
1491 * Perform a garbage collection if necessary
1492 * -------------------------------------------------------------------------- */
1495 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1497 rtsBool heap_census;
1499 /* extern static volatile StgWord waiting_for_gc;
1500 lives inside capability.c */
1501 rtsBool gc_type, prev_pending_gc;
1505 if (sched_state == SCHED_SHUTTING_DOWN) {
1506 // The final GC has already been done, and the system is
1507 // shutting down. We'll probably deadlock if we try to GC
1513 if (sched_state < SCHED_INTERRUPTING
1514 && RtsFlags.ParFlags.parGcEnabled
1515 && N >= RtsFlags.ParFlags.parGcGen
1516 && ! oldest_gen->steps[0].mark)
1518 gc_type = PENDING_GC_PAR;
1520 gc_type = PENDING_GC_SEQ;
1523 // In order to GC, there must be no threads running Haskell code.
1524 // Therefore, the GC thread needs to hold *all* the capabilities,
1525 // and release them after the GC has completed.
1527 // This seems to be the simplest way: previous attempts involved
1528 // making all the threads with capabilities give up their
1529 // capabilities and sleep except for the *last* one, which
1530 // actually did the GC. But it's quite hard to arrange for all
1531 // the other tasks to sleep and stay asleep.
1534 /* Other capabilities are prevented from running yet more Haskell
1535 threads if waiting_for_gc is set. Tested inside
1536 yieldCapability() and releaseCapability() in Capability.c */
1538 prev_pending_gc = cas(&waiting_for_gc, 0, gc_type);
1539 if (prev_pending_gc) {
1541 debugTrace(DEBUG_sched, "someone else is trying to GC (%d)...",
1544 yieldCapability(&cap,task);
1545 } while (waiting_for_gc);
1546 return cap; // NOTE: task->cap might have changed here
1549 setContextSwitches();
1551 // The final shutdown GC is always single-threaded, because it's
1552 // possible that some of the Capabilities have no worker threads.
1554 if (gc_type == PENDING_GC_SEQ)
1556 // single-threaded GC: grab all the capabilities
1557 for (i=0; i < n_capabilities; i++) {
1558 debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1559 if (cap != &capabilities[i]) {
1560 Capability *pcap = &capabilities[i];
1561 // we better hope this task doesn't get migrated to
1562 // another Capability while we're waiting for this one.
1563 // It won't, because load balancing happens while we have
1564 // all the Capabilities, but even so it's a slightly
1565 // unsavoury invariant.
1567 waitForReturnCapability(&pcap, task);
1568 if (pcap != &capabilities[i]) {
1569 barf("scheduleDoGC: got the wrong capability");
1576 // multi-threaded GC: make sure all the Capabilities donate one
1578 debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1580 waitForGcThreads(cap);
1584 // so this happens periodically:
1585 if (cap) scheduleCheckBlackHoles(cap);
1587 IF_DEBUG(scheduler, printAllThreads());
1589 delete_threads_and_gc:
1591 * We now have all the capabilities; if we're in an interrupting
1592 * state, then we should take the opportunity to delete all the
1593 * threads in the system.
1595 if (sched_state == SCHED_INTERRUPTING) {
1596 deleteAllThreads(cap);
1597 sched_state = SCHED_SHUTTING_DOWN;
1600 heap_census = scheduleNeedHeapProfile(rtsTrue);
1602 if (recent_activity == ACTIVITY_INACTIVE && force_major)
1604 // We are doing a GC because the system has been idle for a
1605 // timeslice and we need to check for deadlock. Record the
1606 // fact that we've done a GC and turn off the timer signal;
1607 // it will get re-enabled if we run any threads after the GC.
1609 // Note: this is done before GC, because after GC there might
1610 // be threads already running (GarbageCollect() releases the
1611 // GC threads when it completes), so we risk turning off the
1612 // timer signal when it should really be on.
1613 recent_activity = ACTIVITY_DONE_GC;
1617 #if defined(THREADED_RTS)
1618 debugTrace(DEBUG_sched, "doing GC");
1619 // reset waiting_for_gc *before* GC, so that when the GC threads
1620 // emerge they don't immediately re-enter the GC.
1622 GarbageCollect(force_major || heap_census, gc_type, cap);
1624 GarbageCollect(force_major || heap_census, 0, cap);
1628 debugTrace(DEBUG_sched, "performing heap census");
1630 performHeapProfile = rtsFalse;
1633 if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1634 // GC set the heap_overflow flag, so we should proceed with
1635 // an orderly shutdown now. Ultimately we want the main
1636 // thread to return to its caller with HeapExhausted, at which
1637 // point the caller should call hs_exit(). The first step is
1638 // to delete all the threads.
1640 // Another way to do this would be to raise an exception in
1641 // the main thread, which we really should do because it gives
1642 // the program a chance to clean up. But how do we find the
1643 // main thread? It should presumably be the same one that
1644 // gets ^C exceptions, but that's all done on the Haskell side
1645 // (GHC.TopHandler).
1646 sched_state = SCHED_INTERRUPTING;
1647 goto delete_threads_and_gc;
1652 Once we are all together... this would be the place to balance all
1653 spark pools. No concurrent stealing or adding of new sparks can
1654 occur. Should be defined in Sparks.c. */
1655 balanceSparkPoolsCaps(n_capabilities, capabilities);
1658 #if defined(THREADED_RTS)
1659 if (gc_type == PENDING_GC_SEQ) {
1660 // release our stash of capabilities.
1661 for (i = 0; i < n_capabilities; i++) {
1662 if (cap != &capabilities[i]) {
1663 task->cap = &capabilities[i];
1664 releaseCapability(&capabilities[i]);
1678 /* ---------------------------------------------------------------------------
1679 * Singleton fork(). Do not copy any running threads.
1680 * ------------------------------------------------------------------------- */
1683 forkProcess(HsStablePtr *entry
1684 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1689 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1696 #if defined(THREADED_RTS)
1697 if (RtsFlags.ParFlags.nNodes > 1) {
1698 errorBelch("forking not supported with +RTS -N<n> greater than 1");
1699 stg_exit(EXIT_FAILURE);
1703 debugTrace(DEBUG_sched, "forking!");
1705 // ToDo: for SMP, we should probably acquire *all* the capabilities
1708 // no funny business: hold locks while we fork, otherwise if some
1709 // other thread is holding a lock when the fork happens, the data
1710 // structure protected by the lock will forever be in an
1711 // inconsistent state in the child. See also #1391.
1712 ACQUIRE_LOCK(&sched_mutex);
1713 ACQUIRE_LOCK(&cap->lock);
1714 ACQUIRE_LOCK(&cap->running_task->lock);
1718 if (pid) { // parent
1720 RELEASE_LOCK(&sched_mutex);
1721 RELEASE_LOCK(&cap->lock);
1722 RELEASE_LOCK(&cap->running_task->lock);
1724 // just return the pid
1730 #if defined(THREADED_RTS)
1731 initMutex(&sched_mutex);
1732 initMutex(&cap->lock);
1733 initMutex(&cap->running_task->lock);
1736 // Now, all OS threads except the thread that forked are
1737 // stopped. We need to stop all Haskell threads, including
1738 // those involved in foreign calls. Also we need to delete
1739 // all Tasks, because they correspond to OS threads that are
1742 for (s = 0; s < total_steps; s++) {
1743 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1744 if (t->what_next == ThreadRelocated) {
1747 next = t->global_link;
1748 // don't allow threads to catch the ThreadKilled
1749 // exception, but we do want to raiseAsync() because these
1750 // threads may be evaluating thunks that we need later.
1751 deleteThread_(cap,t);
1756 // Empty the run queue. It seems tempting to let all the
1757 // killed threads stay on the run queue as zombies to be
1758 // cleaned up later, but some of them correspond to bound
1759 // threads for which the corresponding Task does not exist.
1760 cap->run_queue_hd = END_TSO_QUEUE;
1761 cap->run_queue_tl = END_TSO_QUEUE;
1763 // Any suspended C-calling Tasks are no more, their OS threads
1765 cap->suspended_ccalling_tasks = NULL;
1767 // Empty the threads lists. Otherwise, the garbage
1768 // collector may attempt to resurrect some of these threads.
1769 for (s = 0; s < total_steps; s++) {
1770 all_steps[s].threads = END_TSO_QUEUE;
1773 // Wipe the task list, except the current Task.
1774 ACQUIRE_LOCK(&sched_mutex);
1775 for (task = all_tasks; task != NULL; task=task->all_link) {
1776 if (task != cap->running_task) {
1777 #if defined(THREADED_RTS)
1778 initMutex(&task->lock); // see #1391
1783 RELEASE_LOCK(&sched_mutex);
1785 #if defined(THREADED_RTS)
1786 // Wipe our spare workers list, they no longer exist. New
1787 // workers will be created if necessary.
1788 cap->spare_workers = NULL;
1789 cap->returning_tasks_hd = NULL;
1790 cap->returning_tasks_tl = NULL;
1793 // On Unix, all timers are reset in the child, so we need to start
1798 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1799 rts_checkSchedStatus("forkProcess",cap);
1802 hs_exit(); // clean up and exit
1803 stg_exit(EXIT_SUCCESS);
1805 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1806 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1811 /* ---------------------------------------------------------------------------
1812 * Delete all the threads in the system
1813 * ------------------------------------------------------------------------- */
1816 deleteAllThreads ( Capability *cap )
1818 // NOTE: only safe to call if we own all capabilities.
1823 debugTrace(DEBUG_sched,"deleting all threads");
1824 for (s = 0; s < total_steps; s++) {
1825 for (t = all_steps[s].threads; t != END_TSO_QUEUE; t = next) {
1826 if (t->what_next == ThreadRelocated) {
1829 next = t->global_link;
1830 deleteThread(cap,t);
1835 // The run queue now contains a bunch of ThreadKilled threads. We
1836 // must not throw these away: the main thread(s) will be in there
1837 // somewhere, and the main scheduler loop has to deal with it.
1838 // Also, the run queue is the only thing keeping these threads from
1839 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1841 #if !defined(THREADED_RTS)
1842 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1843 ASSERT(sleeping_queue == END_TSO_QUEUE);
1847 /* -----------------------------------------------------------------------------
1848 Managing the suspended_ccalling_tasks list.
1849 Locks required: sched_mutex
1850 -------------------------------------------------------------------------- */
1853 suspendTask (Capability *cap, Task *task)
1855 ASSERT(task->next == NULL && task->prev == NULL);
1856 task->next = cap->suspended_ccalling_tasks;
1858 if (cap->suspended_ccalling_tasks) {
1859 cap->suspended_ccalling_tasks->prev = task;
1861 cap->suspended_ccalling_tasks = task;
1865 recoverSuspendedTask (Capability *cap, Task *task)
1868 task->prev->next = task->next;
1870 ASSERT(cap->suspended_ccalling_tasks == task);
1871 cap->suspended_ccalling_tasks = task->next;
1874 task->next->prev = task->prev;
1876 task->next = task->prev = NULL;
1879 /* ---------------------------------------------------------------------------
1880 * Suspending & resuming Haskell threads.
1882 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1883 * its capability before calling the C function. This allows another
1884 * task to pick up the capability and carry on running Haskell
1885 * threads. It also means that if the C call blocks, it won't lock
1888 * The Haskell thread making the C call is put to sleep for the
1889 * duration of the call, on the susepended_ccalling_threads queue. We
1890 * give out a token to the task, which it can use to resume the thread
1891 * on return from the C function.
1892 * ------------------------------------------------------------------------- */
1895 suspendThread (StgRegTable *reg)
1902 StgWord32 saved_winerror;
1905 saved_errno = errno;
1907 saved_winerror = GetLastError();
1910 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1912 cap = regTableToCapability(reg);
1914 task = cap->running_task;
1915 tso = cap->r.rCurrentTSO;
1917 debugTrace(DEBUG_sched,
1918 "thread %lu did a safe foreign call",
1919 (unsigned long)cap->r.rCurrentTSO->id);
1921 // XXX this might not be necessary --SDM
1922 tso->what_next = ThreadRunGHC;
1924 threadPaused(cap,tso);
1926 if ((tso->flags & TSO_BLOCKEX) == 0) {
1927 tso->why_blocked = BlockedOnCCall;
1928 tso->flags |= TSO_BLOCKEX;
1929 tso->flags &= ~TSO_INTERRUPTIBLE;
1931 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1934 // Hand back capability
1935 task->suspended_tso = tso;
1937 ACQUIRE_LOCK(&cap->lock);
1939 suspendTask(cap,task);
1940 cap->in_haskell = rtsFalse;
1941 releaseCapability_(cap,rtsFalse);
1943 RELEASE_LOCK(&cap->lock);
1945 #if defined(THREADED_RTS)
1946 /* Preparing to leave the RTS, so ensure there's a native thread/task
1947 waiting to take over.
1949 debugTrace(DEBUG_sched, "thread %lu: leaving RTS", (unsigned long)tso->id);
1952 errno = saved_errno;
1954 SetLastError(saved_winerror);
1960 resumeThread (void *task_)
1967 StgWord32 saved_winerror;
1970 saved_errno = errno;
1972 saved_winerror = GetLastError();
1976 // Wait for permission to re-enter the RTS with the result.
1977 waitForReturnCapability(&cap,task);
1978 // we might be on a different capability now... but if so, our
1979 // entry on the suspended_ccalling_tasks list will also have been
1982 // Remove the thread from the suspended list
1983 recoverSuspendedTask(cap,task);
1985 tso = task->suspended_tso;
1986 task->suspended_tso = NULL;
1987 tso->_link = END_TSO_QUEUE; // no write barrier reqd
1988 debugTrace(DEBUG_sched, "thread %lu: re-entering RTS", (unsigned long)tso->id);
1990 if (tso->why_blocked == BlockedOnCCall) {
1991 awakenBlockedExceptionQueue(cap,tso);
1992 tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
1995 /* Reset blocking status */
1996 tso->why_blocked = NotBlocked;
1998 cap->r.rCurrentTSO = tso;
1999 cap->in_haskell = rtsTrue;
2000 errno = saved_errno;
2002 SetLastError(saved_winerror);
2005 /* We might have GC'd, mark the TSO dirty again */
2008 IF_DEBUG(sanity, checkTSO(tso));
2013 /* ---------------------------------------------------------------------------
2016 * scheduleThread puts a thread on the end of the runnable queue.
2017 * This will usually be done immediately after a thread is created.
2018 * The caller of scheduleThread must create the thread using e.g.
2019 * createThread and push an appropriate closure
2020 * on this thread's stack before the scheduler is invoked.
2021 * ------------------------------------------------------------------------ */
2024 scheduleThread(Capability *cap, StgTSO *tso)
2026 // The thread goes at the *end* of the run-queue, to avoid possible
2027 // starvation of any threads already on the queue.
2028 appendToRunQueue(cap,tso);
2032 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
2034 #if defined(THREADED_RTS)
2035 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
2036 // move this thread from now on.
2037 cpu %= RtsFlags.ParFlags.nNodes;
2038 if (cpu == cap->no) {
2039 appendToRunQueue(cap,tso);
2041 wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
2044 appendToRunQueue(cap,tso);
2049 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
2053 // We already created/initialised the Task
2054 task = cap->running_task;
2056 // This TSO is now a bound thread; make the Task and TSO
2057 // point to each other.
2063 task->stat = NoStatus;
2065 appendToRunQueue(cap,tso);
2067 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)tso->id);
2069 cap = schedule(cap,task);
2071 ASSERT(task->stat != NoStatus);
2072 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
2074 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)task->tso->id);
2078 /* ----------------------------------------------------------------------------
2080 * ------------------------------------------------------------------------- */
2082 #if defined(THREADED_RTS)
2083 void OSThreadProcAttr
2084 workerStart(Task *task)
2088 // See startWorkerTask().
2089 ACQUIRE_LOCK(&task->lock);
2091 RELEASE_LOCK(&task->lock);
2093 // set the thread-local pointer to the Task:
2096 // schedule() runs without a lock.
2097 cap = schedule(cap,task);
2099 // On exit from schedule(), we have a Capability, but possibly not
2100 // the same one we started with.
2102 // During shutdown, the requirement is that after all the
2103 // Capabilities are shut down, all workers that are shutting down
2104 // have finished workerTaskStop(). This is why we hold on to
2105 // cap->lock until we've finished workerTaskStop() below.
2107 // There may be workers still involved in foreign calls; those
2108 // will just block in waitForReturnCapability() because the
2109 // Capability has been shut down.
2111 ACQUIRE_LOCK(&cap->lock);
2112 releaseCapability_(cap,rtsFalse);
2113 workerTaskStop(task);
2114 RELEASE_LOCK(&cap->lock);
2118 /* ---------------------------------------------------------------------------
2121 * Initialise the scheduler. This resets all the queues - if the
2122 * queues contained any threads, they'll be garbage collected at the
2125 * ------------------------------------------------------------------------ */
2130 #if !defined(THREADED_RTS)
2131 blocked_queue_hd = END_TSO_QUEUE;
2132 blocked_queue_tl = END_TSO_QUEUE;
2133 sleeping_queue = END_TSO_QUEUE;
2136 blackhole_queue = END_TSO_QUEUE;
2138 sched_state = SCHED_RUNNING;
2139 recent_activity = ACTIVITY_YES;
2141 #if defined(THREADED_RTS)
2142 /* Initialise the mutex and condition variables used by
2144 initMutex(&sched_mutex);
2147 ACQUIRE_LOCK(&sched_mutex);
2149 /* A capability holds the state a native thread needs in
2150 * order to execute STG code. At least one capability is
2151 * floating around (only THREADED_RTS builds have more than one).
2157 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
2161 #if defined(THREADED_RTS)
2163 * Eagerly start one worker to run each Capability, except for
2164 * Capability 0. The idea is that we're probably going to start a
2165 * bound thread on Capability 0 pretty soon, so we don't want a
2166 * worker task hogging it.
2171 for (i = 1; i < n_capabilities; i++) {
2172 cap = &capabilities[i];
2173 ACQUIRE_LOCK(&cap->lock);
2174 startWorkerTask(cap, workerStart);
2175 RELEASE_LOCK(&cap->lock);
2180 trace(TRACE_sched, "start: %d capabilities", n_capabilities);
2182 RELEASE_LOCK(&sched_mutex);
2187 rtsBool wait_foreign
2188 #if !defined(THREADED_RTS)
2189 __attribute__((unused))
2192 /* see Capability.c, shutdownCapability() */
2196 #if defined(THREADED_RTS)
2197 ACQUIRE_LOCK(&sched_mutex);
2198 task = newBoundTask();
2199 RELEASE_LOCK(&sched_mutex);
2202 // If we haven't killed all the threads yet, do it now.
2203 if (sched_state < SCHED_SHUTTING_DOWN) {
2204 sched_state = SCHED_INTERRUPTING;
2205 #if defined(THREADED_RTS)
2206 waitForReturnCapability(&task->cap,task);
2207 scheduleDoGC(task->cap,task,rtsFalse);
2208 releaseCapability(task->cap);
2210 scheduleDoGC(&MainCapability,task,rtsFalse);
2213 sched_state = SCHED_SHUTTING_DOWN;
2215 #if defined(THREADED_RTS)
2219 for (i = 0; i < n_capabilities; i++) {
2220 shutdownCapability(&capabilities[i], task, wait_foreign);
2222 boundTaskExiting(task);
2228 freeScheduler( void )
2232 ACQUIRE_LOCK(&sched_mutex);
2233 still_running = freeTaskManager();
2234 // We can only free the Capabilities if there are no Tasks still
2235 // running. We might have a Task about to return from a foreign
2236 // call into waitForReturnCapability(), for example (actually,
2237 // this should be the *only* thing that a still-running Task can
2238 // do at this point, and it will block waiting for the
2240 if (still_running == 0) {
2242 if (n_capabilities != 1) {
2243 stgFree(capabilities);
2246 RELEASE_LOCK(&sched_mutex);
2247 #if defined(THREADED_RTS)
2248 closeMutex(&sched_mutex);
2252 /* -----------------------------------------------------------------------------
2255 This is the interface to the garbage collector from Haskell land.
2256 We provide this so that external C code can allocate and garbage
2257 collect when called from Haskell via _ccall_GC.
2258 -------------------------------------------------------------------------- */
2261 performGC_(rtsBool force_major)
2265 // We must grab a new Task here, because the existing Task may be
2266 // associated with a particular Capability, and chained onto the
2267 // suspended_ccalling_tasks queue.
2268 ACQUIRE_LOCK(&sched_mutex);
2269 task = newBoundTask();
2270 RELEASE_LOCK(&sched_mutex);
2272 waitForReturnCapability(&task->cap,task);
2273 scheduleDoGC(task->cap,task,force_major);
2274 releaseCapability(task->cap);
2275 boundTaskExiting(task);
2281 performGC_(rtsFalse);
2285 performMajorGC(void)
2287 performGC_(rtsTrue);
2290 /* -----------------------------------------------------------------------------
2293 If the thread has reached its maximum stack size, then raise the
2294 StackOverflow exception in the offending thread. Otherwise
2295 relocate the TSO into a larger chunk of memory and adjust its stack
2297 -------------------------------------------------------------------------- */
2300 threadStackOverflow(Capability *cap, StgTSO *tso)
2302 nat new_stack_size, stack_words;
2307 IF_DEBUG(sanity,checkTSO(tso));
2309 // don't allow throwTo() to modify the blocked_exceptions queue
2310 // while we are moving the TSO:
2311 lockClosure((StgClosure *)tso);
2313 if (tso->stack_size >= tso->max_stack_size && !(tso->flags & TSO_BLOCKEX)) {
2314 // NB. never raise a StackOverflow exception if the thread is
2315 // inside Control.Exceptino.block. It is impractical to protect
2316 // against stack overflow exceptions, since virtually anything
2317 // can raise one (even 'catch'), so this is the only sensible
2318 // thing to do here. See bug #767.
2320 debugTrace(DEBUG_gc,
2321 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2322 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2324 /* If we're debugging, just print out the top of the stack */
2325 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2328 // Send this thread the StackOverflow exception
2330 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2334 /* Try to double the current stack size. If that takes us over the
2335 * maximum stack size for this thread, then use the maximum instead
2336 * (that is, unless we're already at or over the max size and we
2337 * can't raise the StackOverflow exception (see above), in which
2338 * case just double the size). Finally round up so the TSO ends up as
2339 * a whole number of blocks.
2341 if (tso->stack_size >= tso->max_stack_size) {
2342 new_stack_size = tso->stack_size * 2;
2344 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2346 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2347 TSO_STRUCT_SIZE)/sizeof(W_);
2348 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2349 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2351 debugTrace(DEBUG_sched,
2352 "increasing stack size from %ld words to %d.",
2353 (long)tso->stack_size, new_stack_size);
2355 dest = (StgTSO *)allocateLocal(cap,new_tso_size);
2356 TICK_ALLOC_TSO(new_stack_size,0);
2358 /* copy the TSO block and the old stack into the new area */
2359 memcpy(dest,tso,TSO_STRUCT_SIZE);
2360 stack_words = tso->stack + tso->stack_size - tso->sp;
2361 new_sp = (P_)dest + new_tso_size - stack_words;
2362 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2364 /* relocate the stack pointers... */
2366 dest->stack_size = new_stack_size;
2368 /* Mark the old TSO as relocated. We have to check for relocated
2369 * TSOs in the garbage collector and any primops that deal with TSOs.
2371 * It's important to set the sp value to just beyond the end
2372 * of the stack, so we don't attempt to scavenge any part of the
2375 tso->what_next = ThreadRelocated;
2376 setTSOLink(cap,tso,dest);
2377 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2378 tso->why_blocked = NotBlocked;
2380 IF_PAR_DEBUG(verbose,
2381 debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2382 tso->id, tso, tso->stack_size);
2383 /* If we're debugging, just print out the top of the stack */
2384 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2390 IF_DEBUG(sanity,checkTSO(dest));
2392 IF_DEBUG(scheduler,printTSO(dest));
2399 threadStackUnderflow (Task *task STG_UNUSED, StgTSO *tso)
2401 bdescr *bd, *new_bd;
2402 lnat free_w, tso_size_w;
2405 tso_size_w = tso_sizeW(tso);
2407 if (tso_size_w < MBLOCK_SIZE_W ||
2408 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2413 // don't allow throwTo() to modify the blocked_exceptions queue
2414 // while we are moving the TSO:
2415 lockClosure((StgClosure *)tso);
2417 // this is the number of words we'll free
2418 free_w = round_to_mblocks(tso_size_w/2);
2420 bd = Bdescr((StgPtr)tso);
2421 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2422 bd->free = bd->start + TSO_STRUCT_SIZEW;
2424 new_tso = (StgTSO *)new_bd->start;
2425 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2426 new_tso->stack_size = new_bd->free - new_tso->stack;
2428 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2429 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2431 tso->what_next = ThreadRelocated;
2432 tso->_link = new_tso; // no write barrier reqd: same generation
2434 // The TSO attached to this Task may have moved, so update the
2436 if (task->tso == tso) {
2437 task->tso = new_tso;
2443 IF_DEBUG(sanity,checkTSO(new_tso));
2448 /* ---------------------------------------------------------------------------
2450 - usually called inside a signal handler so it mustn't do anything fancy.
2451 ------------------------------------------------------------------------ */
2454 interruptStgRts(void)
2456 sched_state = SCHED_INTERRUPTING;
2457 setContextSwitches();
2461 /* -----------------------------------------------------------------------------
2464 This function causes at least one OS thread to wake up and run the
2465 scheduler loop. It is invoked when the RTS might be deadlocked, or
2466 an external event has arrived that may need servicing (eg. a
2467 keyboard interrupt).
2469 In the single-threaded RTS we don't do anything here; we only have
2470 one thread anyway, and the event that caused us to want to wake up
2471 will have interrupted any blocking system call in progress anyway.
2472 -------------------------------------------------------------------------- */
2477 #if defined(THREADED_RTS)
2478 // This forces the IO Manager thread to wakeup, which will
2479 // in turn ensure that some OS thread wakes up and runs the
2480 // scheduler loop, which will cause a GC and deadlock check.
2485 /* -----------------------------------------------------------------------------
2488 * Check the blackhole_queue for threads that can be woken up. We do
2489 * this periodically: before every GC, and whenever the run queue is
2492 * An elegant solution might be to just wake up all the blocked
2493 * threads with awakenBlockedQueue occasionally: they'll go back to
2494 * sleep again if the object is still a BLACKHOLE. Unfortunately this
2495 * doesn't give us a way to tell whether we've actually managed to
2496 * wake up any threads, so we would be busy-waiting.
2498 * -------------------------------------------------------------------------- */
2501 checkBlackHoles (Capability *cap)
2504 rtsBool any_woke_up = rtsFalse;
2507 // blackhole_queue is global:
2508 ASSERT_LOCK_HELD(&sched_mutex);
2510 debugTrace(DEBUG_sched, "checking threads blocked on black holes");
2512 // ASSUMES: sched_mutex
2513 prev = &blackhole_queue;
2514 t = blackhole_queue;
2515 while (t != END_TSO_QUEUE) {
2516 ASSERT(t->why_blocked == BlockedOnBlackHole);
2517 type = get_itbl(UNTAG_CLOSURE(t->block_info.closure))->type;
2518 if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
2519 IF_DEBUG(sanity,checkTSO(t));
2520 t = unblockOne(cap, t);
2522 any_woke_up = rtsTrue;
2532 /* -----------------------------------------------------------------------------
2535 This is used for interruption (^C) and forking, and corresponds to
2536 raising an exception but without letting the thread catch the
2538 -------------------------------------------------------------------------- */
2541 deleteThread (Capability *cap, StgTSO *tso)
2543 // NOTE: must only be called on a TSO that we have exclusive
2544 // access to, because we will call throwToSingleThreaded() below.
2545 // The TSO must be on the run queue of the Capability we own, or
2546 // we must own all Capabilities.
2548 if (tso->why_blocked != BlockedOnCCall &&
2549 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2550 throwToSingleThreaded(cap,tso,NULL);
2554 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2556 deleteThread_(Capability *cap, StgTSO *tso)
2557 { // for forkProcess only:
2558 // like deleteThread(), but we delete threads in foreign calls, too.
2560 if (tso->why_blocked == BlockedOnCCall ||
2561 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2562 unblockOne(cap,tso);
2563 tso->what_next = ThreadKilled;
2565 deleteThread(cap,tso);
2570 /* -----------------------------------------------------------------------------
2571 raiseExceptionHelper
2573 This function is called by the raise# primitve, just so that we can
2574 move some of the tricky bits of raising an exception from C-- into
2575 C. Who knows, it might be a useful re-useable thing here too.
2576 -------------------------------------------------------------------------- */
2579 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2581 Capability *cap = regTableToCapability(reg);
2582 StgThunk *raise_closure = NULL;
2584 StgRetInfoTable *info;
2586 // This closure represents the expression 'raise# E' where E
2587 // is the exception raise. It is used to overwrite all the
2588 // thunks which are currently under evaluataion.
2591 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2592 // LDV profiling: stg_raise_info has THUNK as its closure
2593 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2594 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2595 // 1 does not cause any problem unless profiling is performed.
2596 // However, when LDV profiling goes on, we need to linearly scan
2597 // small object pool, where raise_closure is stored, so we should
2598 // use MIN_UPD_SIZE.
2600 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2601 // sizeofW(StgClosure)+1);
2605 // Walk up the stack, looking for the catch frame. On the way,
2606 // we update any closures pointed to from update frames with the
2607 // raise closure that we just built.
2611 info = get_ret_itbl((StgClosure *)p);
2612 next = p + stack_frame_sizeW((StgClosure *)p);
2613 switch (info->i.type) {
2616 // Only create raise_closure if we need to.
2617 if (raise_closure == NULL) {
2619 (StgThunk *)allocateLocal(cap,sizeofW(StgThunk)+1);
2620 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2621 raise_closure->payload[0] = exception;
2623 UPD_IND(((StgUpdateFrame *)p)->updatee,(StgClosure *)raise_closure);
2627 case ATOMICALLY_FRAME:
2628 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2630 return ATOMICALLY_FRAME;
2636 case CATCH_STM_FRAME:
2637 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2639 return CATCH_STM_FRAME;
2645 case CATCH_RETRY_FRAME:
2654 /* -----------------------------------------------------------------------------
2655 findRetryFrameHelper
2657 This function is called by the retry# primitive. It traverses the stack
2658 leaving tso->sp referring to the frame which should handle the retry.
2660 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2661 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2663 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2664 create) because retries are not considered to be exceptions, despite the
2665 similar implementation.
2667 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2668 not be created within memory transactions.
2669 -------------------------------------------------------------------------- */
2672 findRetryFrameHelper (StgTSO *tso)
2675 StgRetInfoTable *info;
2679 info = get_ret_itbl((StgClosure *)p);
2680 next = p + stack_frame_sizeW((StgClosure *)p);
2681 switch (info->i.type) {
2683 case ATOMICALLY_FRAME:
2684 debugTrace(DEBUG_stm,
2685 "found ATOMICALLY_FRAME at %p during retry", p);
2687 return ATOMICALLY_FRAME;
2689 case CATCH_RETRY_FRAME:
2690 debugTrace(DEBUG_stm,
2691 "found CATCH_RETRY_FRAME at %p during retrry", p);
2693 return CATCH_RETRY_FRAME;
2695 case CATCH_STM_FRAME: {
2696 StgTRecHeader *trec = tso -> trec;
2697 StgTRecHeader *outer = stmGetEnclosingTRec(trec);
2698 debugTrace(DEBUG_stm,
2699 "found CATCH_STM_FRAME at %p during retry", p);
2700 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2701 stmAbortTransaction(tso -> cap, trec);
2702 stmFreeAbortedTRec(tso -> cap, trec);
2703 tso -> trec = outer;
2710 ASSERT(info->i.type != CATCH_FRAME);
2711 ASSERT(info->i.type != STOP_FRAME);
2718 /* -----------------------------------------------------------------------------
2719 resurrectThreads is called after garbage collection on the list of
2720 threads found to be garbage. Each of these threads will be woken
2721 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2722 on an MVar, or NonTermination if the thread was blocked on a Black
2725 Locks: assumes we hold *all* the capabilities.
2726 -------------------------------------------------------------------------- */
2729 resurrectThreads (StgTSO *threads)
2735 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2736 next = tso->global_link;
2738 step = Bdescr((P_)tso)->step;
2739 tso->global_link = step->threads;
2740 step->threads = tso;
2742 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2744 // Wake up the thread on the Capability it was last on
2747 switch (tso->why_blocked) {
2749 case BlockedOnException:
2750 /* Called by GC - sched_mutex lock is currently held. */
2751 throwToSingleThreaded(cap, tso,
2752 (StgClosure *)blockedOnDeadMVar_closure);
2754 case BlockedOnBlackHole:
2755 throwToSingleThreaded(cap, tso,
2756 (StgClosure *)nonTermination_closure);
2759 throwToSingleThreaded(cap, tso,
2760 (StgClosure *)blockedIndefinitely_closure);
2763 /* This might happen if the thread was blocked on a black hole
2764 * belonging to a thread that we've just woken up (raiseAsync
2765 * can wake up threads, remember...).
2769 barf("resurrectThreads: thread blocked in a strange way");
2774 /* -----------------------------------------------------------------------------
2775 performPendingThrowTos is called after garbage collection, and
2776 passed a list of threads that were found to have pending throwTos
2777 (tso->blocked_exceptions was not empty), and were blocked.
2778 Normally this doesn't happen, because we would deliver the
2779 exception directly if the target thread is blocked, but there are
2780 small windows where it might occur on a multiprocessor (see
2783 NB. we must be holding all the capabilities at this point, just
2784 like resurrectThreads().
2785 -------------------------------------------------------------------------- */
2788 performPendingThrowTos (StgTSO *threads)
2794 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2795 next = tso->global_link;
2797 step = Bdescr((P_)tso)->step;
2798 tso->global_link = step->threads;
2799 step->threads = tso;
2801 debugTrace(DEBUG_sched, "performing blocked throwTo to thread %lu", (unsigned long)tso->id);
2804 maybePerformBlockedException(cap, tso);