1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2006
5 * The scheduler and thread-related functionality
7 * --------------------------------------------------------------------------*/
9 #include "PosixSource.h"
10 #define KEEP_LOCKCLOSURE
13 #include "sm/Storage.h"
17 #include "Interpreter.h"
19 #include "RtsSignals.h"
20 #include "sm/Sanity.h"
24 #include "ThreadLabels.h"
26 #include "Proftimer.h"
29 #include "sm/GC.h" // waitForGcThreads, releaseGCThreads, N
31 #include "Capability.h"
33 #include "AwaitEvent.h"
34 #if defined(mingw32_HOST_OS)
35 #include "win32/IOManager.h"
38 #include "RaiseAsync.h"
41 #include "ThreadPaused.h"
43 #ifdef HAVE_SYS_TYPES_H
44 #include <sys/types.h>
58 /* -----------------------------------------------------------------------------
60 * -------------------------------------------------------------------------- */
62 #if !defined(THREADED_RTS)
63 // Blocked/sleeping thrads
64 StgTSO *blocked_queue_hd = NULL;
65 StgTSO *blocked_queue_tl = NULL;
66 StgTSO *sleeping_queue = NULL; // perhaps replace with a hash table?
69 /* Threads blocked on blackholes.
70 * LOCK: sched_mutex+capability, or all capabilities
72 StgTSO *blackhole_queue = NULL;
74 /* The blackhole_queue should be checked for threads to wake up. See
75 * Schedule.h for more thorough comment.
76 * LOCK: none (doesn't matter if we miss an update)
78 rtsBool blackholes_need_checking = rtsFalse;
80 /* Set to true when the latest garbage collection failed to reclaim
81 * enough space, and the runtime should proceed to shut itself down in
82 * an orderly fashion (emitting profiling info etc.)
84 rtsBool heap_overflow = rtsFalse;
86 /* flag that tracks whether we have done any execution in this time slice.
87 * LOCK: currently none, perhaps we should lock (but needs to be
88 * updated in the fast path of the scheduler).
90 * NB. must be StgWord, we do xchg() on it.
92 volatile StgWord recent_activity = ACTIVITY_YES;
94 /* if this flag is set as well, give up execution
95 * LOCK: none (changes monotonically)
97 volatile StgWord sched_state = SCHED_RUNNING;
99 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
100 * exists - earlier gccs apparently didn't.
106 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
107 * in an MT setting, needed to signal that a worker thread shouldn't hang around
108 * in the scheduler when it is out of work.
110 rtsBool shutting_down_scheduler = rtsFalse;
113 * This mutex protects most of the global scheduler data in
114 * the THREADED_RTS runtime.
116 #if defined(THREADED_RTS)
120 #if !defined(mingw32_HOST_OS)
121 #define FORKPROCESS_PRIMOP_SUPPORTED
124 /* -----------------------------------------------------------------------------
125 * static function prototypes
126 * -------------------------------------------------------------------------- */
128 static Capability *schedule (Capability *initialCapability, Task *task);
131 // These function all encapsulate parts of the scheduler loop, and are
132 // abstracted only to make the structure and control flow of the
133 // scheduler clearer.
135 static void schedulePreLoop (void);
136 static void scheduleFindWork (Capability *cap);
137 #if defined(THREADED_RTS)
138 static void scheduleYield (Capability **pcap, Task *task, rtsBool);
140 static void scheduleStartSignalHandlers (Capability *cap);
141 static void scheduleCheckBlockedThreads (Capability *cap);
142 static void scheduleCheckWakeupThreads(Capability *cap USED_IF_NOT_THREADS);
143 static void scheduleCheckBlackHoles (Capability *cap);
144 static void scheduleDetectDeadlock (Capability *cap, Task *task);
145 static void schedulePushWork(Capability *cap, Task *task);
146 #if defined(THREADED_RTS)
147 static void scheduleActivateSpark(Capability *cap);
149 static void schedulePostRunThread(Capability *cap, StgTSO *t);
150 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
151 static void scheduleHandleStackOverflow( Capability *cap, Task *task,
153 static rtsBool scheduleHandleYield( Capability *cap, StgTSO *t,
154 nat prev_what_next );
155 static void scheduleHandleThreadBlocked( StgTSO *t );
156 static rtsBool scheduleHandleThreadFinished( Capability *cap, Task *task,
158 static rtsBool scheduleNeedHeapProfile(rtsBool ready_to_gc);
159 static Capability *scheduleDoGC(Capability *cap, Task *task,
160 rtsBool force_major);
162 static rtsBool checkBlackHoles(Capability *cap);
164 static StgTSO *threadStackOverflow(Capability *cap, StgTSO *tso);
165 static StgTSO *threadStackUnderflow(Capability *cap, Task *task, StgTSO *tso);
167 static void deleteThread (Capability *cap, StgTSO *tso);
168 static void deleteAllThreads (Capability *cap);
170 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
171 static void deleteThread_(Capability *cap, StgTSO *tso);
174 /* -----------------------------------------------------------------------------
175 * Putting a thread on the run queue: different scheduling policies
176 * -------------------------------------------------------------------------- */
179 addToRunQueue( Capability *cap, StgTSO *t )
181 // this does round-robin scheduling; good for concurrency
182 appendToRunQueue(cap,t);
185 /* ---------------------------------------------------------------------------
186 Main scheduling loop.
188 We use round-robin scheduling, each thread returning to the
189 scheduler loop when one of these conditions is detected:
192 * timer expires (thread yields)
198 In a GranSim setup this loop iterates over the global event queue.
199 This revolves around the global event queue, which determines what
200 to do next. Therefore, it's more complicated than either the
201 concurrent or the parallel (GUM) setup.
202 This version has been entirely removed (JB 2008/08).
205 GUM iterates over incoming messages.
206 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
207 and sends out a fish whenever it has nothing to do; in-between
208 doing the actual reductions (shared code below) it processes the
209 incoming messages and deals with delayed operations
210 (see PendingFetches).
211 This is not the ugliest code you could imagine, but it's bloody close.
213 (JB 2008/08) This version was formerly indicated by a PP-Flag PAR,
214 now by PP-flag PARALLEL_HASKELL. The Eden RTS (in GHC-6.x) uses it,
215 as well as future GUM versions. This file has been refurbished to
216 only contain valid code, which is however incomplete, refers to
217 invalid includes etc.
219 ------------------------------------------------------------------------ */
222 schedule (Capability *initialCapability, Task *task)
226 StgThreadReturnCode ret;
229 #if defined(THREADED_RTS)
230 rtsBool first = rtsTrue;
231 rtsBool force_yield = rtsFalse;
234 cap = initialCapability;
236 // Pre-condition: this task owns initialCapability.
237 // The sched_mutex is *NOT* held
238 // NB. on return, we still hold a capability.
240 debugTrace (DEBUG_sched, "cap %d: schedule()", initialCapability->no);
244 // -----------------------------------------------------------
245 // Scheduler loop starts here:
249 // Check whether we have re-entered the RTS from Haskell without
250 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
252 if (cap->in_haskell) {
253 errorBelch("schedule: re-entered unsafely.\n"
254 " Perhaps a 'foreign import unsafe' should be 'safe'?");
255 stg_exit(EXIT_FAILURE);
258 // The interruption / shutdown sequence.
260 // In order to cleanly shut down the runtime, we want to:
261 // * make sure that all main threads return to their callers
262 // with the state 'Interrupted'.
263 // * clean up all OS threads assocated with the runtime
264 // * free all memory etc.
266 // So the sequence for ^C goes like this:
268 // * ^C handler sets sched_state := SCHED_INTERRUPTING and
269 // arranges for some Capability to wake up
271 // * all threads in the system are halted, and the zombies are
272 // placed on the run queue for cleaning up. We acquire all
273 // the capabilities in order to delete the threads, this is
274 // done by scheduleDoGC() for convenience (because GC already
275 // needs to acquire all the capabilities). We can't kill
276 // threads involved in foreign calls.
278 // * somebody calls shutdownHaskell(), which calls exitScheduler()
280 // * sched_state := SCHED_SHUTTING_DOWN
282 // * all workers exit when the run queue on their capability
283 // drains. All main threads will also exit when their TSO
284 // reaches the head of the run queue and they can return.
286 // * eventually all Capabilities will shut down, and the RTS can
289 // * We might be left with threads blocked in foreign calls,
290 // we should really attempt to kill these somehow (TODO);
292 switch (sched_state) {
295 case SCHED_INTERRUPTING:
296 debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
297 #if defined(THREADED_RTS)
298 discardSparksCap(cap);
300 /* scheduleDoGC() deletes all the threads */
301 cap = scheduleDoGC(cap,task,rtsFalse);
303 // after scheduleDoGC(), we must be shutting down. Either some
304 // other Capability did the final GC, or we did it above,
305 // either way we can fall through to the SCHED_SHUTTING_DOWN
307 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
310 case SCHED_SHUTTING_DOWN:
311 debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
312 // If we are a worker, just exit. If we're a bound thread
313 // then we will exit below when we've removed our TSO from
315 if (!isBoundTask(task) && emptyRunQueue(cap)) {
320 barf("sched_state: %d", sched_state);
323 scheduleFindWork(cap);
325 /* work pushing, currently relevant only for THREADED_RTS:
326 (pushes threads, wakes up idle capabilities for stealing) */
327 schedulePushWork(cap,task);
329 scheduleDetectDeadlock(cap,task);
331 #if defined(THREADED_RTS)
332 cap = task->cap; // reload cap, it might have changed
335 // Normally, the only way we can get here with no threads to
336 // run is if a keyboard interrupt received during
337 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
338 // Additionally, it is not fatal for the
339 // threaded RTS to reach here with no threads to run.
341 // win32: might be here due to awaitEvent() being abandoned
342 // as a result of a console event having been delivered.
344 #if defined(THREADED_RTS)
348 // // don't yield the first time, we want a chance to run this
349 // // thread for a bit, even if there are others banging at the
352 // ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
356 scheduleYield(&cap,task,force_yield);
357 force_yield = rtsFalse;
359 if (emptyRunQueue(cap)) continue; // look for work again
362 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
363 if ( emptyRunQueue(cap) ) {
364 ASSERT(sched_state >= SCHED_INTERRUPTING);
369 // Get a thread to run
371 t = popRunQueue(cap);
373 // Sanity check the thread we're about to run. This can be
374 // expensive if there is lots of thread switching going on...
375 IF_DEBUG(sanity,checkTSO(t));
377 #if defined(THREADED_RTS)
378 // Check whether we can run this thread in the current task.
379 // If not, we have to pass our capability to the right task.
381 InCall *bound = t->bound;
384 if (bound->task == task) {
385 // yes, the Haskell thread is bound to the current native thread
387 debugTrace(DEBUG_sched,
388 "thread %lu bound to another OS thread",
389 (unsigned long)t->id);
390 // no, bound to a different Haskell thread: pass to that thread
391 pushOnRunQueue(cap,t);
395 // The thread we want to run is unbound.
396 if (task->incall->tso) {
397 debugTrace(DEBUG_sched,
398 "this OS thread cannot run thread %lu",
399 (unsigned long)t->id);
400 // no, the current native thread is bound to a different
401 // Haskell thread, so pass it to any worker thread
402 pushOnRunQueue(cap,t);
409 // If we're shutting down, and this thread has not yet been
410 // killed, kill it now. This sometimes happens when a finalizer
411 // thread is created by the final GC, or a thread previously
412 // in a foreign call returns.
413 if (sched_state >= SCHED_INTERRUPTING &&
414 !(t->what_next == ThreadComplete || t->what_next == ThreadKilled)) {
418 /* context switches are initiated by the timer signal, unless
419 * the user specified "context switch as often as possible", with
422 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
423 && !emptyThreadQueues(cap)) {
424 cap->context_switch = 1;
429 // CurrentTSO is the thread to run. t might be different if we
430 // loop back to run_thread, so make sure to set CurrentTSO after
432 cap->r.rCurrentTSO = t;
434 startHeapProfTimer();
436 // Check for exceptions blocked on this thread
437 maybePerformBlockedException (cap, t);
439 // ----------------------------------------------------------------------
440 // Run the current thread
442 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
443 ASSERT(t->cap == cap);
444 ASSERT(t->bound ? t->bound->task->cap == cap : 1);
446 prev_what_next = t->what_next;
448 errno = t->saved_errno;
450 SetLastError(t->saved_winerror);
453 cap->in_haskell = rtsTrue;
457 #if defined(THREADED_RTS)
458 if (recent_activity == ACTIVITY_DONE_GC) {
459 // ACTIVITY_DONE_GC means we turned off the timer signal to
460 // conserve power (see #1623). Re-enable it here.
462 prev = xchg((P_)&recent_activity, ACTIVITY_YES);
463 if (prev == ACTIVITY_DONE_GC) {
466 } else if (recent_activity != ACTIVITY_INACTIVE) {
467 // If we reached ACTIVITY_INACTIVE, then don't reset it until
468 // we've done the GC. The thread running here might just be
469 // the IO manager thread that handle_tick() woke up via
471 recent_activity = ACTIVITY_YES;
475 traceEventRunThread(cap, t);
477 switch (prev_what_next) {
481 /* Thread already finished, return to scheduler. */
482 ret = ThreadFinished;
488 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
489 cap = regTableToCapability(r);
494 case ThreadInterpret:
495 cap = interpretBCO(cap);
500 barf("schedule: invalid what_next field");
503 cap->in_haskell = rtsFalse;
505 // The TSO might have moved, eg. if it re-entered the RTS and a GC
506 // happened. So find the new location:
507 t = cap->r.rCurrentTSO;
509 // We have run some Haskell code: there might be blackhole-blocked
510 // threads to wake up now.
511 // Lock-free test here should be ok, we're just setting a flag.
512 if ( blackhole_queue != END_TSO_QUEUE ) {
513 blackholes_need_checking = rtsTrue;
516 // And save the current errno in this thread.
517 // XXX: possibly bogus for SMP because this thread might already
518 // be running again, see code below.
519 t->saved_errno = errno;
521 // Similarly for Windows error code
522 t->saved_winerror = GetLastError();
525 traceEventStopThread(cap, t, ret);
527 #if defined(THREADED_RTS)
528 // If ret is ThreadBlocked, and this Task is bound to the TSO that
529 // blocked, we are in limbo - the TSO is now owned by whatever it
530 // is blocked on, and may in fact already have been woken up,
531 // perhaps even on a different Capability. It may be the case
532 // that task->cap != cap. We better yield this Capability
533 // immediately and return to normaility.
534 if (ret == ThreadBlocked) {
535 force_yield = rtsTrue;
540 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
541 ASSERT(t->cap == cap);
543 // ----------------------------------------------------------------------
545 // Costs for the scheduler are assigned to CCS_SYSTEM
547 #if defined(PROFILING)
551 schedulePostRunThread(cap,t);
553 if (ret != StackOverflow) {
554 t = threadStackUnderflow(cap,task,t);
557 ready_to_gc = rtsFalse;
561 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
565 scheduleHandleStackOverflow(cap,task,t);
569 if (scheduleHandleYield(cap, t, prev_what_next)) {
570 // shortcut for switching between compiler/interpreter:
576 scheduleHandleThreadBlocked(t);
580 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
581 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
585 barf("schedule: invalid thread return code %d", (int)ret);
588 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
589 cap = scheduleDoGC(cap,task,rtsFalse);
591 } /* end of while() */
594 /* ----------------------------------------------------------------------------
595 * Setting up the scheduler loop
596 * ------------------------------------------------------------------------- */
599 schedulePreLoop(void)
601 // initialisation for scheduler - what cannot go into initScheduler()
604 /* -----------------------------------------------------------------------------
607 * Search for work to do, and handle messages from elsewhere.
608 * -------------------------------------------------------------------------- */
611 scheduleFindWork (Capability *cap)
613 scheduleStartSignalHandlers(cap);
615 // Only check the black holes here if we've nothing else to do.
616 // During normal execution, the black hole list only gets checked
617 // at GC time, to avoid repeatedly traversing this possibly long
618 // list each time around the scheduler.
619 if (emptyRunQueue(cap)) { scheduleCheckBlackHoles(cap); }
621 scheduleCheckWakeupThreads(cap);
623 scheduleCheckBlockedThreads(cap);
625 #if defined(THREADED_RTS)
626 if (emptyRunQueue(cap)) { scheduleActivateSpark(cap); }
630 #if defined(THREADED_RTS)
631 STATIC_INLINE rtsBool
632 shouldYieldCapability (Capability *cap, Task *task)
634 // we need to yield this capability to someone else if..
635 // - another thread is initiating a GC
636 // - another Task is returning from a foreign call
637 // - the thread at the head of the run queue cannot be run
638 // by this Task (it is bound to another Task, or it is unbound
639 // and this task it bound).
640 return (waiting_for_gc ||
641 cap->returning_tasks_hd != NULL ||
642 (!emptyRunQueue(cap) && (task->incall->tso == NULL
643 ? cap->run_queue_hd->bound != NULL
644 : cap->run_queue_hd->bound != task->incall)));
647 // This is the single place where a Task goes to sleep. There are
648 // two reasons it might need to sleep:
649 // - there are no threads to run
650 // - we need to yield this Capability to someone else
651 // (see shouldYieldCapability())
653 // Careful: the scheduler loop is quite delicate. Make sure you run
654 // the tests in testsuite/concurrent (all ways) after modifying this,
655 // and also check the benchmarks in nofib/parallel for regressions.
658 scheduleYield (Capability **pcap, Task *task, rtsBool force_yield)
660 Capability *cap = *pcap;
662 // if we have work, and we don't need to give up the Capability, continue.
664 // The force_yield flag is used when a bound thread blocks. This
665 // is a particularly tricky situation: the current Task does not
666 // own the TSO any more, since it is on some queue somewhere, and
667 // might be woken up or manipulated by another thread at any time.
668 // The TSO and Task might be migrated to another Capability.
669 // Certain invariants might be in doubt, such as task->bound->cap
670 // == cap. We have to yield the current Capability immediately,
671 // no messing around.
674 !shouldYieldCapability(cap,task) &&
675 (!emptyRunQueue(cap) ||
676 !emptyWakeupQueue(cap) ||
677 blackholes_need_checking ||
678 sched_state >= SCHED_INTERRUPTING))
681 // otherwise yield (sleep), and keep yielding if necessary.
683 yieldCapability(&cap,task);
685 while (shouldYieldCapability(cap,task));
687 // note there may still be no threads on the run queue at this
688 // point, the caller has to check.
695 /* -----------------------------------------------------------------------------
698 * Push work to other Capabilities if we have some.
699 * -------------------------------------------------------------------------- */
702 schedulePushWork(Capability *cap USED_IF_THREADS,
703 Task *task USED_IF_THREADS)
705 /* following code not for PARALLEL_HASKELL. I kept the call general,
706 future GUM versions might use pushing in a distributed setup */
707 #if defined(THREADED_RTS)
709 Capability *free_caps[n_capabilities], *cap0;
712 // migration can be turned off with +RTS -qm
713 if (!RtsFlags.ParFlags.migrate) return;
715 // Check whether we have more threads on our run queue, or sparks
716 // in our pool, that we could hand to another Capability.
717 if (cap->run_queue_hd == END_TSO_QUEUE) {
718 if (sparkPoolSizeCap(cap) < 2) return;
720 if (cap->run_queue_hd->_link == END_TSO_QUEUE &&
721 sparkPoolSizeCap(cap) < 1) return;
724 // First grab as many free Capabilities as we can.
725 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
726 cap0 = &capabilities[i];
727 if (cap != cap0 && tryGrabCapability(cap0,task)) {
728 if (!emptyRunQueue(cap0) || cap->returning_tasks_hd != NULL) {
729 // it already has some work, we just grabbed it at
730 // the wrong moment. Or maybe it's deadlocked!
731 releaseCapability(cap0);
733 free_caps[n_free_caps++] = cap0;
738 // we now have n_free_caps free capabilities stashed in
739 // free_caps[]. Share our run queue equally with them. This is
740 // probably the simplest thing we could do; improvements we might
741 // want to do include:
743 // - giving high priority to moving relatively new threads, on
744 // the gournds that they haven't had time to build up a
745 // working set in the cache on this CPU/Capability.
747 // - giving low priority to moving long-lived threads
749 if (n_free_caps > 0) {
750 StgTSO *prev, *t, *next;
751 rtsBool pushed_to_all;
753 debugTrace(DEBUG_sched,
754 "cap %d: %s and %d free capabilities, sharing...",
756 (!emptyRunQueue(cap) && cap->run_queue_hd->_link != END_TSO_QUEUE)?
757 "excess threads on run queue":"sparks to share (>=2)",
761 pushed_to_all = rtsFalse;
763 if (cap->run_queue_hd != END_TSO_QUEUE) {
764 prev = cap->run_queue_hd;
766 prev->_link = END_TSO_QUEUE;
767 for (; t != END_TSO_QUEUE; t = next) {
769 t->_link = END_TSO_QUEUE;
770 if (t->what_next == ThreadRelocated
771 || t->bound == task->incall // don't move my bound thread
772 || tsoLocked(t)) { // don't move a locked thread
773 setTSOLink(cap, prev, t);
775 } else if (i == n_free_caps) {
776 pushed_to_all = rtsTrue;
779 setTSOLink(cap, prev, t);
782 appendToRunQueue(free_caps[i],t);
784 traceEventMigrateThread (cap, t, free_caps[i]->no);
786 if (t->bound) { t->bound->task->cap = free_caps[i]; }
787 t->cap = free_caps[i];
791 cap->run_queue_tl = prev;
795 /* JB I left this code in place, it would work but is not necessary */
797 // If there are some free capabilities that we didn't push any
798 // threads to, then try to push a spark to each one.
799 if (!pushed_to_all) {
801 // i is the next free capability to push to
802 for (; i < n_free_caps; i++) {
803 if (emptySparkPoolCap(free_caps[i])) {
804 spark = tryStealSpark(cap->sparks);
806 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
808 traceEventStealSpark(free_caps[i], t, cap->no);
810 newSpark(&(free_caps[i]->r), spark);
815 #endif /* SPARK_PUSHING */
817 // release the capabilities
818 for (i = 0; i < n_free_caps; i++) {
819 task->cap = free_caps[i];
820 releaseAndWakeupCapability(free_caps[i]);
823 task->cap = cap; // reset to point to our Capability.
825 #endif /* THREADED_RTS */
829 /* ----------------------------------------------------------------------------
830 * Start any pending signal handlers
831 * ------------------------------------------------------------------------- */
833 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
835 scheduleStartSignalHandlers(Capability *cap)
837 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
838 // safe outside the lock
839 startSignalHandlers(cap);
844 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
849 /* ----------------------------------------------------------------------------
850 * Check for blocked threads that can be woken up.
851 * ------------------------------------------------------------------------- */
854 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
856 #if !defined(THREADED_RTS)
858 // Check whether any waiting threads need to be woken up. If the
859 // run queue is empty, and there are no other tasks running, we
860 // can wait indefinitely for something to happen.
862 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
864 awaitEvent( emptyRunQueue(cap) && !blackholes_need_checking );
870 /* ----------------------------------------------------------------------------
871 * Check for threads woken up by other Capabilities
872 * ------------------------------------------------------------------------- */
875 scheduleCheckWakeupThreads(Capability *cap USED_IF_THREADS)
877 #if defined(THREADED_RTS)
878 // Any threads that were woken up by other Capabilities get
879 // appended to our run queue.
880 if (!emptyWakeupQueue(cap)) {
881 ACQUIRE_LOCK(&cap->lock);
882 if (emptyRunQueue(cap)) {
883 cap->run_queue_hd = cap->wakeup_queue_hd;
884 cap->run_queue_tl = cap->wakeup_queue_tl;
886 setTSOLink(cap, cap->run_queue_tl, cap->wakeup_queue_hd);
887 cap->run_queue_tl = cap->wakeup_queue_tl;
889 cap->wakeup_queue_hd = cap->wakeup_queue_tl = END_TSO_QUEUE;
890 RELEASE_LOCK(&cap->lock);
895 /* ----------------------------------------------------------------------------
896 * Check for threads blocked on BLACKHOLEs that can be woken up
897 * ------------------------------------------------------------------------- */
899 scheduleCheckBlackHoles (Capability *cap)
901 if ( blackholes_need_checking ) // check without the lock first
903 ACQUIRE_LOCK(&sched_mutex);
904 if ( blackholes_need_checking ) {
905 blackholes_need_checking = rtsFalse;
906 // important that we reset the flag *before* checking the
907 // blackhole queue, otherwise we could get deadlock. This
908 // happens as follows: we wake up a thread that
909 // immediately runs on another Capability, blocks on a
910 // blackhole, and then we reset the blackholes_need_checking flag.
911 checkBlackHoles(cap);
913 RELEASE_LOCK(&sched_mutex);
917 /* ----------------------------------------------------------------------------
918 * Detect deadlock conditions and attempt to resolve them.
919 * ------------------------------------------------------------------------- */
922 scheduleDetectDeadlock (Capability *cap, Task *task)
925 * Detect deadlock: when we have no threads to run, there are no
926 * threads blocked, waiting for I/O, or sleeping, and all the
927 * other tasks are waiting for work, we must have a deadlock of
930 if ( emptyThreadQueues(cap) )
932 #if defined(THREADED_RTS)
934 * In the threaded RTS, we only check for deadlock if there
935 * has been no activity in a complete timeslice. This means
936 * we won't eagerly start a full GC just because we don't have
937 * any threads to run currently.
939 if (recent_activity != ACTIVITY_INACTIVE) return;
942 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
944 // Garbage collection can release some new threads due to
945 // either (a) finalizers or (b) threads resurrected because
946 // they are unreachable and will therefore be sent an
947 // exception. Any threads thus released will be immediately
949 cap = scheduleDoGC (cap, task, rtsTrue/*force major GC*/);
950 // when force_major == rtsTrue. scheduleDoGC sets
951 // recent_activity to ACTIVITY_DONE_GC and turns off the timer
954 if ( !emptyRunQueue(cap) ) return;
956 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
957 /* If we have user-installed signal handlers, then wait
958 * for signals to arrive rather then bombing out with a
961 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
962 debugTrace(DEBUG_sched,
963 "still deadlocked, waiting for signals...");
967 if (signals_pending()) {
968 startSignalHandlers(cap);
971 // either we have threads to run, or we were interrupted:
972 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
978 #if !defined(THREADED_RTS)
979 /* Probably a real deadlock. Send the current main thread the
980 * Deadlock exception.
982 if (task->incall->tso) {
983 switch (task->incall->tso->why_blocked) {
985 case BlockedOnBlackHole:
986 case BlockedOnException:
988 throwToSingleThreaded(cap, task->incall->tso,
989 (StgClosure *)nonTermination_closure);
992 barf("deadlock: main thread blocked in a strange way");
1001 /* ----------------------------------------------------------------------------
1002 * Send pending messages (PARALLEL_HASKELL only)
1003 * ------------------------------------------------------------------------- */
1005 #if defined(PARALLEL_HASKELL)
1007 scheduleSendPendingMessages(void)
1010 # if defined(PAR) // global Mem.Mgmt., omit for now
1011 if (PendingFetches != END_BF_QUEUE) {
1016 if (RtsFlags.ParFlags.BufferTime) {
1017 // if we use message buffering, we must send away all message
1018 // packets which have become too old...
1024 /* ----------------------------------------------------------------------------
1025 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
1026 * ------------------------------------------------------------------------- */
1028 #if defined(THREADED_RTS)
1030 scheduleActivateSpark(Capability *cap)
1034 createSparkThread(cap);
1035 debugTrace(DEBUG_sched, "creating a spark thread");
1038 #endif // PARALLEL_HASKELL || THREADED_RTS
1040 /* ----------------------------------------------------------------------------
1041 * After running a thread...
1042 * ------------------------------------------------------------------------- */
1045 schedulePostRunThread (Capability *cap, StgTSO *t)
1047 // We have to be able to catch transactions that are in an
1048 // infinite loop as a result of seeing an inconsistent view of
1052 // [a,b] <- mapM readTVar [ta,tb]
1053 // when (a == b) loop
1055 // and a is never equal to b given a consistent view of memory.
1057 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1058 if (!stmValidateNestOfTransactions (t -> trec)) {
1059 debugTrace(DEBUG_sched | DEBUG_stm,
1060 "trec %p found wasting its time", t);
1062 // strip the stack back to the
1063 // ATOMICALLY_FRAME, aborting the (nested)
1064 // transaction, and saving the stack of any
1065 // partially-evaluated thunks on the heap.
1066 throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1068 // ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1072 /* some statistics gathering in the parallel case */
1075 /* -----------------------------------------------------------------------------
1076 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1077 * -------------------------------------------------------------------------- */
1080 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1082 // did the task ask for a large block?
1083 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1084 // if so, get one and push it on the front of the nursery.
1088 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1090 debugTrace(DEBUG_sched,
1091 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1092 (long)t->id, what_next_strs[t->what_next], blocks);
1094 // don't do this if the nursery is (nearly) full, we'll GC first.
1095 if (cap->r.rCurrentNursery->link != NULL ||
1096 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1097 // if the nursery has only one block.
1100 bd = allocGroup( blocks );
1102 cap->r.rNursery->n_blocks += blocks;
1104 // link the new group into the list
1105 bd->link = cap->r.rCurrentNursery;
1106 bd->u.back = cap->r.rCurrentNursery->u.back;
1107 if (cap->r.rCurrentNursery->u.back != NULL) {
1108 cap->r.rCurrentNursery->u.back->link = bd;
1110 cap->r.rNursery->blocks = bd;
1112 cap->r.rCurrentNursery->u.back = bd;
1114 // initialise it as a nursery block. We initialise the
1115 // step, gen_no, and flags field of *every* sub-block in
1116 // this large block, because this is easier than making
1117 // sure that we always find the block head of a large
1118 // block whenever we call Bdescr() (eg. evacuate() and
1119 // isAlive() in the GC would both have to do this, at
1123 for (x = bd; x < bd + blocks; x++) {
1124 initBdescr(x,g0,g0);
1130 // This assert can be a killer if the app is doing lots
1131 // of large block allocations.
1132 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1134 // now update the nursery to point to the new block
1135 cap->r.rCurrentNursery = bd;
1137 // we might be unlucky and have another thread get on the
1138 // run queue before us and steal the large block, but in that
1139 // case the thread will just end up requesting another large
1141 pushOnRunQueue(cap,t);
1142 return rtsFalse; /* not actually GC'ing */
1146 if (cap->r.rHpLim == NULL || cap->context_switch) {
1147 // Sometimes we miss a context switch, e.g. when calling
1148 // primitives in a tight loop, MAYBE_GC() doesn't check the
1149 // context switch flag, and we end up waiting for a GC.
1150 // See #1984, and concurrent/should_run/1984
1151 cap->context_switch = 0;
1152 addToRunQueue(cap,t);
1154 pushOnRunQueue(cap,t);
1157 /* actual GC is done at the end of the while loop in schedule() */
1160 /* -----------------------------------------------------------------------------
1161 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1162 * -------------------------------------------------------------------------- */
1165 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1167 /* just adjust the stack for this thread, then pop it back
1171 /* enlarge the stack */
1172 StgTSO *new_t = threadStackOverflow(cap, t);
1174 /* The TSO attached to this Task may have moved, so update the
1177 if (task->incall->tso == t) {
1178 task->incall->tso = new_t;
1180 pushOnRunQueue(cap,new_t);
1184 /* -----------------------------------------------------------------------------
1185 * Handle a thread that returned to the scheduler with ThreadYielding
1186 * -------------------------------------------------------------------------- */
1189 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1191 /* put the thread back on the run queue. Then, if we're ready to
1192 * GC, check whether this is the last task to stop. If so, wake
1193 * up the GC thread. getThread will block during a GC until the
1197 ASSERT(t->_link == END_TSO_QUEUE);
1199 // Shortcut if we're just switching evaluators: don't bother
1200 // doing stack squeezing (which can be expensive), just run the
1202 if (cap->context_switch == 0 && t->what_next != prev_what_next) {
1203 debugTrace(DEBUG_sched,
1204 "--<< thread %ld (%s) stopped to switch evaluators",
1205 (long)t->id, what_next_strs[t->what_next]);
1209 // Reset the context switch flag. We don't do this just before
1210 // running the thread, because that would mean we would lose ticks
1211 // during GC, which can lead to unfair scheduling (a thread hogs
1212 // the CPU because the tick always arrives during GC). This way
1213 // penalises threads that do a lot of allocation, but that seems
1214 // better than the alternative.
1215 cap->context_switch = 0;
1218 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1221 addToRunQueue(cap,t);
1226 /* -----------------------------------------------------------------------------
1227 * Handle a thread that returned to the scheduler with ThreadBlocked
1228 * -------------------------------------------------------------------------- */
1231 scheduleHandleThreadBlocked( StgTSO *t
1238 // We don't need to do anything. The thread is blocked, and it
1239 // has tidied up its stack and placed itself on whatever queue
1240 // it needs to be on.
1242 // ASSERT(t->why_blocked != NotBlocked);
1243 // Not true: for example,
1244 // - in THREADED_RTS, the thread may already have been woken
1245 // up by another Capability. This actually happens: try
1246 // conc023 +RTS -N2.
1247 // - the thread may have woken itself up already, because
1248 // threadPaused() might have raised a blocked throwTo
1249 // exception, see maybePerformBlockedException().
1252 traceThreadStatus(DEBUG_sched, t);
1256 /* -----------------------------------------------------------------------------
1257 * Handle a thread that returned to the scheduler with ThreadFinished
1258 * -------------------------------------------------------------------------- */
1261 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1263 /* Need to check whether this was a main thread, and if so,
1264 * return with the return value.
1266 * We also end up here if the thread kills itself with an
1267 * uncaught exception, see Exception.cmm.
1270 // blocked exceptions can now complete, even if the thread was in
1271 // blocked mode (see #2910). This unconditionally calls
1272 // lockTSO(), which ensures that we don't miss any threads that
1273 // are engaged in throwTo() with this thread as a target.
1274 awakenBlockedExceptionQueue (cap, t);
1277 // Check whether the thread that just completed was a bound
1278 // thread, and if so return with the result.
1280 // There is an assumption here that all thread completion goes
1281 // through this point; we need to make sure that if a thread
1282 // ends up in the ThreadKilled state, that it stays on the run
1283 // queue so it can be dealt with here.
1288 if (t->bound != task->incall) {
1289 #if !defined(THREADED_RTS)
1290 // Must be a bound thread that is not the topmost one. Leave
1291 // it on the run queue until the stack has unwound to the
1292 // point where we can deal with this. Leaving it on the run
1293 // queue also ensures that the garbage collector knows about
1294 // this thread and its return value (it gets dropped from the
1295 // step->threads list so there's no other way to find it).
1296 appendToRunQueue(cap,t);
1299 // this cannot happen in the threaded RTS, because a
1300 // bound thread can only be run by the appropriate Task.
1301 barf("finished bound thread that isn't mine");
1305 ASSERT(task->incall->tso == t);
1307 if (t->what_next == ThreadComplete) {
1309 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1310 *(task->ret) = (StgClosure *)task->incall->tso->sp[1];
1312 task->stat = Success;
1315 *(task->ret) = NULL;
1317 if (sched_state >= SCHED_INTERRUPTING) {
1318 if (heap_overflow) {
1319 task->stat = HeapExhausted;
1321 task->stat = Interrupted;
1324 task->stat = Killed;
1328 removeThreadLabel((StgWord)task->incall->tso->id);
1331 // We no longer consider this thread and task to be bound to
1332 // each other. The TSO lives on until it is GC'd, but the
1333 // task is about to be released by the caller, and we don't
1334 // want anyone following the pointer from the TSO to the
1335 // defunct task (which might have already been
1336 // re-used). This was a real bug: the GC updated
1337 // tso->bound->tso which lead to a deadlock.
1339 task->incall->tso = NULL;
1341 return rtsTrue; // tells schedule() to return
1347 /* -----------------------------------------------------------------------------
1348 * Perform a heap census
1349 * -------------------------------------------------------------------------- */
1352 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1354 // When we have +RTS -i0 and we're heap profiling, do a census at
1355 // every GC. This lets us get repeatable runs for debugging.
1356 if (performHeapProfile ||
1357 (RtsFlags.ProfFlags.profileInterval==0 &&
1358 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1365 /* -----------------------------------------------------------------------------
1366 * Perform a garbage collection if necessary
1367 * -------------------------------------------------------------------------- */
1370 scheduleDoGC (Capability *cap, Task *task USED_IF_THREADS, rtsBool force_major)
1372 rtsBool heap_census;
1374 /* extern static volatile StgWord waiting_for_gc;
1375 lives inside capability.c */
1376 rtsBool gc_type, prev_pending_gc;
1380 if (sched_state == SCHED_SHUTTING_DOWN) {
1381 // The final GC has already been done, and the system is
1382 // shutting down. We'll probably deadlock if we try to GC
1388 if (sched_state < SCHED_INTERRUPTING
1389 && RtsFlags.ParFlags.parGcEnabled
1390 && N >= RtsFlags.ParFlags.parGcGen
1391 && ! oldest_gen->mark)
1393 gc_type = PENDING_GC_PAR;
1395 gc_type = PENDING_GC_SEQ;
1398 // In order to GC, there must be no threads running Haskell code.
1399 // Therefore, the GC thread needs to hold *all* the capabilities,
1400 // and release them after the GC has completed.
1402 // This seems to be the simplest way: previous attempts involved
1403 // making all the threads with capabilities give up their
1404 // capabilities and sleep except for the *last* one, which
1405 // actually did the GC. But it's quite hard to arrange for all
1406 // the other tasks to sleep and stay asleep.
1409 /* Other capabilities are prevented from running yet more Haskell
1410 threads if waiting_for_gc is set. Tested inside
1411 yieldCapability() and releaseCapability() in Capability.c */
1413 prev_pending_gc = cas(&waiting_for_gc, 0, gc_type);
1414 if (prev_pending_gc) {
1416 debugTrace(DEBUG_sched, "someone else is trying to GC (%d)...",
1419 yieldCapability(&cap,task);
1420 } while (waiting_for_gc);
1421 return cap; // NOTE: task->cap might have changed here
1424 setContextSwitches();
1426 // The final shutdown GC is always single-threaded, because it's
1427 // possible that some of the Capabilities have no worker threads.
1429 if (gc_type == PENDING_GC_SEQ)
1431 traceEventRequestSeqGc(cap);
1435 traceEventRequestParGc(cap);
1436 debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1439 // do this while the other Capabilities stop:
1440 if (cap) scheduleCheckBlackHoles(cap);
1442 if (gc_type == PENDING_GC_SEQ)
1444 // single-threaded GC: grab all the capabilities
1445 for (i=0; i < n_capabilities; i++) {
1446 debugTrace(DEBUG_sched, "ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities);
1447 if (cap != &capabilities[i]) {
1448 Capability *pcap = &capabilities[i];
1449 // we better hope this task doesn't get migrated to
1450 // another Capability while we're waiting for this one.
1451 // It won't, because load balancing happens while we have
1452 // all the Capabilities, but even so it's a slightly
1453 // unsavoury invariant.
1455 waitForReturnCapability(&pcap, task);
1456 if (pcap != &capabilities[i]) {
1457 barf("scheduleDoGC: got the wrong capability");
1464 // multi-threaded GC: make sure all the Capabilities donate one
1466 waitForGcThreads(cap);
1469 #else /* !THREADED_RTS */
1471 // do this while the other Capabilities stop:
1472 if (cap) scheduleCheckBlackHoles(cap);
1476 IF_DEBUG(scheduler, printAllThreads());
1478 delete_threads_and_gc:
1480 * We now have all the capabilities; if we're in an interrupting
1481 * state, then we should take the opportunity to delete all the
1482 * threads in the system.
1484 if (sched_state == SCHED_INTERRUPTING) {
1485 deleteAllThreads(cap);
1486 sched_state = SCHED_SHUTTING_DOWN;
1489 heap_census = scheduleNeedHeapProfile(rtsTrue);
1491 traceEventGcStart(cap);
1492 #if defined(THREADED_RTS)
1493 // reset waiting_for_gc *before* GC, so that when the GC threads
1494 // emerge they don't immediately re-enter the GC.
1496 GarbageCollect(force_major || heap_census, gc_type, cap);
1498 GarbageCollect(force_major || heap_census, 0, cap);
1500 traceEventGcEnd(cap);
1502 if (recent_activity == ACTIVITY_INACTIVE && force_major)
1504 // We are doing a GC because the system has been idle for a
1505 // timeslice and we need to check for deadlock. Record the
1506 // fact that we've done a GC and turn off the timer signal;
1507 // it will get re-enabled if we run any threads after the GC.
1508 recent_activity = ACTIVITY_DONE_GC;
1513 // the GC might have taken long enough for the timer to set
1514 // recent_activity = ACTIVITY_INACTIVE, but we aren't
1515 // necessarily deadlocked:
1516 recent_activity = ACTIVITY_YES;
1519 #if defined(THREADED_RTS)
1520 if (gc_type == PENDING_GC_PAR)
1522 releaseGCThreads(cap);
1527 debugTrace(DEBUG_sched, "performing heap census");
1529 performHeapProfile = rtsFalse;
1532 if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1533 // GC set the heap_overflow flag, so we should proceed with
1534 // an orderly shutdown now. Ultimately we want the main
1535 // thread to return to its caller with HeapExhausted, at which
1536 // point the caller should call hs_exit(). The first step is
1537 // to delete all the threads.
1539 // Another way to do this would be to raise an exception in
1540 // the main thread, which we really should do because it gives
1541 // the program a chance to clean up. But how do we find the
1542 // main thread? It should presumably be the same one that
1543 // gets ^C exceptions, but that's all done on the Haskell side
1544 // (GHC.TopHandler).
1545 sched_state = SCHED_INTERRUPTING;
1546 goto delete_threads_and_gc;
1551 Once we are all together... this would be the place to balance all
1552 spark pools. No concurrent stealing or adding of new sparks can
1553 occur. Should be defined in Sparks.c. */
1554 balanceSparkPoolsCaps(n_capabilities, capabilities);
1557 #if defined(THREADED_RTS)
1558 if (gc_type == PENDING_GC_SEQ) {
1559 // release our stash of capabilities.
1560 for (i = 0; i < n_capabilities; i++) {
1561 if (cap != &capabilities[i]) {
1562 task->cap = &capabilities[i];
1563 releaseCapability(&capabilities[i]);
1577 /* ---------------------------------------------------------------------------
1578 * Singleton fork(). Do not copy any running threads.
1579 * ------------------------------------------------------------------------- */
1582 forkProcess(HsStablePtr *entry
1583 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1588 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1594 #if defined(THREADED_RTS)
1595 if (RtsFlags.ParFlags.nNodes > 1) {
1596 errorBelch("forking not supported with +RTS -N<n> greater than 1");
1597 stg_exit(EXIT_FAILURE);
1601 debugTrace(DEBUG_sched, "forking!");
1603 // ToDo: for SMP, we should probably acquire *all* the capabilities
1606 // no funny business: hold locks while we fork, otherwise if some
1607 // other thread is holding a lock when the fork happens, the data
1608 // structure protected by the lock will forever be in an
1609 // inconsistent state in the child. See also #1391.
1610 ACQUIRE_LOCK(&sched_mutex);
1611 ACQUIRE_LOCK(&cap->lock);
1612 ACQUIRE_LOCK(&cap->running_task->lock);
1616 if (pid) { // parent
1618 RELEASE_LOCK(&sched_mutex);
1619 RELEASE_LOCK(&cap->lock);
1620 RELEASE_LOCK(&cap->running_task->lock);
1622 // just return the pid
1628 #if defined(THREADED_RTS)
1629 initMutex(&sched_mutex);
1630 initMutex(&cap->lock);
1631 initMutex(&cap->running_task->lock);
1634 // Now, all OS threads except the thread that forked are
1635 // stopped. We need to stop all Haskell threads, including
1636 // those involved in foreign calls. Also we need to delete
1637 // all Tasks, because they correspond to OS threads that are
1640 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1641 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1642 if (t->what_next == ThreadRelocated) {
1645 next = t->global_link;
1646 // don't allow threads to catch the ThreadKilled
1647 // exception, but we do want to raiseAsync() because these
1648 // threads may be evaluating thunks that we need later.
1649 deleteThread_(cap,t);
1654 // Empty the run queue. It seems tempting to let all the
1655 // killed threads stay on the run queue as zombies to be
1656 // cleaned up later, but some of them correspond to bound
1657 // threads for which the corresponding Task does not exist.
1658 cap->run_queue_hd = END_TSO_QUEUE;
1659 cap->run_queue_tl = END_TSO_QUEUE;
1661 // Any suspended C-calling Tasks are no more, their OS threads
1663 cap->suspended_ccalls = NULL;
1665 // Empty the threads lists. Otherwise, the garbage
1666 // collector may attempt to resurrect some of these threads.
1667 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1668 generations[g].threads = END_TSO_QUEUE;
1671 discardTasksExcept(cap->running_task);
1673 #if defined(THREADED_RTS)
1674 // Wipe our spare workers list, they no longer exist. New
1675 // workers will be created if necessary.
1676 cap->spare_workers = NULL;
1677 cap->returning_tasks_hd = NULL;
1678 cap->returning_tasks_tl = NULL;
1681 // On Unix, all timers are reset in the child, so we need to start
1686 #if defined(THREADED_RTS)
1687 cap = ioManagerStartCap(cap);
1690 cap = rts_evalStableIO(cap, entry, NULL); // run the action
1691 rts_checkSchedStatus("forkProcess",cap);
1694 hs_exit(); // clean up and exit
1695 stg_exit(EXIT_SUCCESS);
1697 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1698 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1702 /* ---------------------------------------------------------------------------
1703 * Delete all the threads in the system
1704 * ------------------------------------------------------------------------- */
1707 deleteAllThreads ( Capability *cap )
1709 // NOTE: only safe to call if we own all capabilities.
1714 debugTrace(DEBUG_sched,"deleting all threads");
1715 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1716 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1717 if (t->what_next == ThreadRelocated) {
1720 next = t->global_link;
1721 deleteThread(cap,t);
1726 // The run queue now contains a bunch of ThreadKilled threads. We
1727 // must not throw these away: the main thread(s) will be in there
1728 // somewhere, and the main scheduler loop has to deal with it.
1729 // Also, the run queue is the only thing keeping these threads from
1730 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1732 #if !defined(THREADED_RTS)
1733 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1734 ASSERT(sleeping_queue == END_TSO_QUEUE);
1738 /* -----------------------------------------------------------------------------
1739 Managing the suspended_ccalls list.
1740 Locks required: sched_mutex
1741 -------------------------------------------------------------------------- */
1744 suspendTask (Capability *cap, Task *task)
1748 incall = task->incall;
1749 ASSERT(incall->next == NULL && incall->prev == NULL);
1750 incall->next = cap->suspended_ccalls;
1751 incall->prev = NULL;
1752 if (cap->suspended_ccalls) {
1753 cap->suspended_ccalls->prev = incall;
1755 cap->suspended_ccalls = incall;
1759 recoverSuspendedTask (Capability *cap, Task *task)
1763 incall = task->incall;
1765 incall->prev->next = incall->next;
1767 ASSERT(cap->suspended_ccalls == incall);
1768 cap->suspended_ccalls = incall->next;
1771 incall->next->prev = incall->prev;
1773 incall->next = incall->prev = NULL;
1776 /* ---------------------------------------------------------------------------
1777 * Suspending & resuming Haskell threads.
1779 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1780 * its capability before calling the C function. This allows another
1781 * task to pick up the capability and carry on running Haskell
1782 * threads. It also means that if the C call blocks, it won't lock
1785 * The Haskell thread making the C call is put to sleep for the
1786 * duration of the call, on the susepended_ccalling_threads queue. We
1787 * give out a token to the task, which it can use to resume the thread
1788 * on return from the C function.
1789 * ------------------------------------------------------------------------- */
1792 suspendThread (StgRegTable *reg)
1799 StgWord32 saved_winerror;
1802 saved_errno = errno;
1804 saved_winerror = GetLastError();
1807 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
1809 cap = regTableToCapability(reg);
1811 task = cap->running_task;
1812 tso = cap->r.rCurrentTSO;
1814 traceEventStopThread(cap, tso, THREAD_SUSPENDED_FOREIGN_CALL);
1816 // XXX this might not be necessary --SDM
1817 tso->what_next = ThreadRunGHC;
1819 threadPaused(cap,tso);
1821 if ((tso->flags & TSO_BLOCKEX) == 0) {
1822 tso->why_blocked = BlockedOnCCall;
1823 tso->flags |= TSO_BLOCKEX;
1824 tso->flags &= ~TSO_INTERRUPTIBLE;
1826 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
1829 // Hand back capability
1830 task->incall->suspended_tso = tso;
1831 task->incall->suspended_cap = cap;
1833 ACQUIRE_LOCK(&cap->lock);
1835 suspendTask(cap,task);
1836 cap->in_haskell = rtsFalse;
1837 releaseCapability_(cap,rtsFalse);
1839 RELEASE_LOCK(&cap->lock);
1841 errno = saved_errno;
1843 SetLastError(saved_winerror);
1849 resumeThread (void *task_)
1857 StgWord32 saved_winerror;
1860 saved_errno = errno;
1862 saved_winerror = GetLastError();
1865 incall = task->incall;
1866 cap = incall->suspended_cap;
1869 // Wait for permission to re-enter the RTS with the result.
1870 waitForReturnCapability(&cap,task);
1871 // we might be on a different capability now... but if so, our
1872 // entry on the suspended_ccalls list will also have been
1875 // Remove the thread from the suspended list
1876 recoverSuspendedTask(cap,task);
1878 tso = incall->suspended_tso;
1879 incall->suspended_tso = NULL;
1880 incall->suspended_cap = NULL;
1881 tso->_link = END_TSO_QUEUE; // no write barrier reqd
1883 traceEventRunThread(cap, tso);
1885 if (tso->why_blocked == BlockedOnCCall) {
1886 // avoid locking the TSO if we don't have to
1887 if (tso->blocked_exceptions != END_TSO_QUEUE) {
1888 awakenBlockedExceptionQueue(cap,tso);
1890 tso->flags &= ~(TSO_BLOCKEX | TSO_INTERRUPTIBLE);
1893 /* Reset blocking status */
1894 tso->why_blocked = NotBlocked;
1896 cap->r.rCurrentTSO = tso;
1897 cap->in_haskell = rtsTrue;
1898 errno = saved_errno;
1900 SetLastError(saved_winerror);
1903 /* We might have GC'd, mark the TSO dirty again */
1906 IF_DEBUG(sanity, checkTSO(tso));
1911 /* ---------------------------------------------------------------------------
1914 * scheduleThread puts a thread on the end of the runnable queue.
1915 * This will usually be done immediately after a thread is created.
1916 * The caller of scheduleThread must create the thread using e.g.
1917 * createThread and push an appropriate closure
1918 * on this thread's stack before the scheduler is invoked.
1919 * ------------------------------------------------------------------------ */
1922 scheduleThread(Capability *cap, StgTSO *tso)
1924 // The thread goes at the *end* of the run-queue, to avoid possible
1925 // starvation of any threads already on the queue.
1926 appendToRunQueue(cap,tso);
1930 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
1932 #if defined(THREADED_RTS)
1933 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
1934 // move this thread from now on.
1935 cpu %= RtsFlags.ParFlags.nNodes;
1936 if (cpu == cap->no) {
1937 appendToRunQueue(cap,tso);
1939 traceEventMigrateThread (cap, tso, capabilities[cpu].no);
1940 wakeupThreadOnCapability(cap, &capabilities[cpu], tso);
1943 appendToRunQueue(cap,tso);
1948 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
1953 // We already created/initialised the Task
1954 task = cap->running_task;
1956 // This TSO is now a bound thread; make the Task and TSO
1957 // point to each other.
1958 tso->bound = task->incall;
1961 task->incall->tso = tso;
1963 task->stat = NoStatus;
1965 appendToRunQueue(cap,tso);
1968 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)id);
1970 cap = schedule(cap,task);
1972 ASSERT(task->stat != NoStatus);
1973 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
1975 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)id);
1979 /* ----------------------------------------------------------------------------
1981 * ------------------------------------------------------------------------- */
1983 #if defined(THREADED_RTS)
1984 void scheduleWorker (Capability *cap, Task *task)
1986 // schedule() runs without a lock.
1987 cap = schedule(cap,task);
1989 // On exit from schedule(), we have a Capability, but possibly not
1990 // the same one we started with.
1992 // During shutdown, the requirement is that after all the
1993 // Capabilities are shut down, all workers that are shutting down
1994 // have finished workerTaskStop(). This is why we hold on to
1995 // cap->lock until we've finished workerTaskStop() below.
1997 // There may be workers still involved in foreign calls; those
1998 // will just block in waitForReturnCapability() because the
1999 // Capability has been shut down.
2001 ACQUIRE_LOCK(&cap->lock);
2002 releaseCapability_(cap,rtsFalse);
2003 workerTaskStop(task);
2004 RELEASE_LOCK(&cap->lock);
2008 /* ---------------------------------------------------------------------------
2011 * Initialise the scheduler. This resets all the queues - if the
2012 * queues contained any threads, they'll be garbage collected at the
2015 * ------------------------------------------------------------------------ */
2020 #if !defined(THREADED_RTS)
2021 blocked_queue_hd = END_TSO_QUEUE;
2022 blocked_queue_tl = END_TSO_QUEUE;
2023 sleeping_queue = END_TSO_QUEUE;
2026 blackhole_queue = END_TSO_QUEUE;
2028 sched_state = SCHED_RUNNING;
2029 recent_activity = ACTIVITY_YES;
2031 #if defined(THREADED_RTS)
2032 /* Initialise the mutex and condition variables used by
2034 initMutex(&sched_mutex);
2037 ACQUIRE_LOCK(&sched_mutex);
2039 /* A capability holds the state a native thread needs in
2040 * order to execute STG code. At least one capability is
2041 * floating around (only THREADED_RTS builds have more than one).
2047 #if defined(THREADED_RTS)
2051 RELEASE_LOCK(&sched_mutex);
2053 #if defined(THREADED_RTS)
2055 * Eagerly start one worker to run each Capability, except for
2056 * Capability 0. The idea is that we're probably going to start a
2057 * bound thread on Capability 0 pretty soon, so we don't want a
2058 * worker task hogging it.
2063 for (i = 1; i < n_capabilities; i++) {
2064 cap = &capabilities[i];
2065 ACQUIRE_LOCK(&cap->lock);
2066 startWorkerTask(cap);
2067 RELEASE_LOCK(&cap->lock);
2075 rtsBool wait_foreign
2076 #if !defined(THREADED_RTS)
2077 __attribute__((unused))
2080 /* see Capability.c, shutdownCapability() */
2084 task = newBoundTask();
2086 // If we haven't killed all the threads yet, do it now.
2087 if (sched_state < SCHED_SHUTTING_DOWN) {
2088 sched_state = SCHED_INTERRUPTING;
2089 waitForReturnCapability(&task->cap,task);
2090 scheduleDoGC(task->cap,task,rtsFalse);
2091 ASSERT(task->incall->tso == NULL);
2092 releaseCapability(task->cap);
2094 sched_state = SCHED_SHUTTING_DOWN;
2096 #if defined(THREADED_RTS)
2100 for (i = 0; i < n_capabilities; i++) {
2101 ASSERT(task->incall->tso == NULL);
2102 shutdownCapability(&capabilities[i], task, wait_foreign);
2107 boundTaskExiting(task);
2111 freeScheduler( void )
2115 ACQUIRE_LOCK(&sched_mutex);
2116 still_running = freeTaskManager();
2117 // We can only free the Capabilities if there are no Tasks still
2118 // running. We might have a Task about to return from a foreign
2119 // call into waitForReturnCapability(), for example (actually,
2120 // this should be the *only* thing that a still-running Task can
2121 // do at this point, and it will block waiting for the
2123 if (still_running == 0) {
2125 if (n_capabilities != 1) {
2126 stgFree(capabilities);
2129 RELEASE_LOCK(&sched_mutex);
2130 #if defined(THREADED_RTS)
2131 closeMutex(&sched_mutex);
2135 /* -----------------------------------------------------------------------------
2138 This is the interface to the garbage collector from Haskell land.
2139 We provide this so that external C code can allocate and garbage
2140 collect when called from Haskell via _ccall_GC.
2141 -------------------------------------------------------------------------- */
2144 performGC_(rtsBool force_major)
2148 // We must grab a new Task here, because the existing Task may be
2149 // associated with a particular Capability, and chained onto the
2150 // suspended_ccalls queue.
2151 task = newBoundTask();
2153 waitForReturnCapability(&task->cap,task);
2154 scheduleDoGC(task->cap,task,force_major);
2155 releaseCapability(task->cap);
2156 boundTaskExiting(task);
2162 performGC_(rtsFalse);
2166 performMajorGC(void)
2168 performGC_(rtsTrue);
2171 /* -----------------------------------------------------------------------------
2174 If the thread has reached its maximum stack size, then raise the
2175 StackOverflow exception in the offending thread. Otherwise
2176 relocate the TSO into a larger chunk of memory and adjust its stack
2178 -------------------------------------------------------------------------- */
2181 threadStackOverflow(Capability *cap, StgTSO *tso)
2183 nat new_stack_size, stack_words;
2188 IF_DEBUG(sanity,checkTSO(tso));
2190 // don't allow throwTo() to modify the blocked_exceptions queue
2191 // while we are moving the TSO:
2192 lockClosure((StgClosure *)tso);
2194 if (tso->stack_size >= tso->max_stack_size
2195 && !(tso->flags & TSO_BLOCKEX)) {
2196 // NB. never raise a StackOverflow exception if the thread is
2197 // inside Control.Exceptino.block. It is impractical to protect
2198 // against stack overflow exceptions, since virtually anything
2199 // can raise one (even 'catch'), so this is the only sensible
2200 // thing to do here. See bug #767.
2203 if (tso->flags & TSO_SQUEEZED) {
2207 // #3677: In a stack overflow situation, stack squeezing may
2208 // reduce the stack size, but we don't know whether it has been
2209 // reduced enough for the stack check to succeed if we try
2210 // again. Fortunately stack squeezing is idempotent, so all we
2211 // need to do is record whether *any* squeezing happened. If we
2212 // are at the stack's absolute -K limit, and stack squeezing
2213 // happened, then we try running the thread again. The
2214 // TSO_SQUEEZED flag is set by threadPaused() to tell us whether
2215 // squeezing happened or not.
2217 debugTrace(DEBUG_gc,
2218 "threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)",
2219 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2221 /* If we're debugging, just print out the top of the stack */
2222 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2225 // Send this thread the StackOverflow exception
2227 throwToSingleThreaded(cap, tso, (StgClosure *)stackOverflow_closure);
2232 // We also want to avoid enlarging the stack if squeezing has
2233 // already released some of it. However, we don't want to get into
2234 // a pathalogical situation where a thread has a nearly full stack
2235 // (near its current limit, but not near the absolute -K limit),
2236 // keeps allocating a little bit, squeezing removes a little bit,
2237 // and then it runs again. So to avoid this, if we squeezed *and*
2238 // there is still less than BLOCK_SIZE_W words free, then we enlarge
2239 // the stack anyway.
2240 if ((tso->flags & TSO_SQUEEZED) &&
2241 ((W_)(tso->sp - tso->stack) >= BLOCK_SIZE_W)) {
2246 /* Try to double the current stack size. If that takes us over the
2247 * maximum stack size for this thread, then use the maximum instead
2248 * (that is, unless we're already at or over the max size and we
2249 * can't raise the StackOverflow exception (see above), in which
2250 * case just double the size). Finally round up so the TSO ends up as
2251 * a whole number of blocks.
2253 if (tso->stack_size >= tso->max_stack_size) {
2254 new_stack_size = tso->stack_size * 2;
2256 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2258 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2259 TSO_STRUCT_SIZE)/sizeof(W_);
2260 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2261 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2263 debugTrace(DEBUG_sched,
2264 "increasing stack size from %ld words to %d.",
2265 (long)tso->stack_size, new_stack_size);
2267 dest = (StgTSO *)allocate(cap,new_tso_size);
2268 TICK_ALLOC_TSO(new_stack_size,0);
2270 /* copy the TSO block and the old stack into the new area */
2271 memcpy(dest,tso,TSO_STRUCT_SIZE);
2272 stack_words = tso->stack + tso->stack_size - tso->sp;
2273 new_sp = (P_)dest + new_tso_size - stack_words;
2274 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2276 /* relocate the stack pointers... */
2278 dest->stack_size = new_stack_size;
2280 /* Mark the old TSO as relocated. We have to check for relocated
2281 * TSOs in the garbage collector and any primops that deal with TSOs.
2283 * It's important to set the sp value to just beyond the end
2284 * of the stack, so we don't attempt to scavenge any part of the
2287 tso->what_next = ThreadRelocated;
2288 setTSOLink(cap,tso,dest);
2289 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2290 tso->why_blocked = NotBlocked;
2295 IF_DEBUG(sanity,checkTSO(dest));
2297 IF_DEBUG(scheduler,printTSO(dest));
2304 threadStackUnderflow (Capability *cap, Task *task, StgTSO *tso)
2306 bdescr *bd, *new_bd;
2307 lnat free_w, tso_size_w;
2310 tso_size_w = tso_sizeW(tso);
2312 if (tso_size_w < MBLOCK_SIZE_W ||
2313 // TSO is less than 2 mblocks (since the first mblock is
2314 // shorter than MBLOCK_SIZE_W)
2315 (tso_size_w - BLOCKS_PER_MBLOCK*BLOCK_SIZE_W) % MBLOCK_SIZE_W != 0 ||
2316 // or TSO is not a whole number of megablocks (ensuring
2317 // precondition of splitLargeBlock() below)
2318 (tso_size_w <= round_up_to_mblocks(RtsFlags.GcFlags.initialStkSize)) ||
2319 // or TSO is smaller than the minimum stack size (rounded up)
2320 (nat)(tso->stack + tso->stack_size - tso->sp) > tso->stack_size / 4)
2321 // or stack is using more than 1/4 of the available space
2327 // don't allow throwTo() to modify the blocked_exceptions queue
2328 // while we are moving the TSO:
2329 lockClosure((StgClosure *)tso);
2331 // this is the number of words we'll free
2332 free_w = round_to_mblocks(tso_size_w/2);
2334 bd = Bdescr((StgPtr)tso);
2335 new_bd = splitLargeBlock(bd, free_w / BLOCK_SIZE_W);
2336 bd->free = bd->start + TSO_STRUCT_SIZEW;
2338 new_tso = (StgTSO *)new_bd->start;
2339 memcpy(new_tso,tso,TSO_STRUCT_SIZE);
2340 new_tso->stack_size = new_bd->free - new_tso->stack;
2342 // The original TSO was dirty and probably on the mutable
2343 // list. The new TSO is not yet on the mutable list, so we better
2346 new_tso->flags &= ~TSO_LINK_DIRTY;
2347 dirty_TSO(cap, new_tso);
2349 debugTrace(DEBUG_sched, "thread %ld: reducing TSO size from %lu words to %lu",
2350 (long)tso->id, tso_size_w, tso_sizeW(new_tso));
2352 tso->what_next = ThreadRelocated;
2353 tso->_link = new_tso; // no write barrier reqd: same generation
2355 // The TSO attached to this Task may have moved, so update the
2357 if (task->incall->tso == tso) {
2358 task->incall->tso = new_tso;
2364 IF_DEBUG(sanity,checkTSO(new_tso));
2369 /* ---------------------------------------------------------------------------
2371 - usually called inside a signal handler so it mustn't do anything fancy.
2372 ------------------------------------------------------------------------ */
2375 interruptStgRts(void)
2377 sched_state = SCHED_INTERRUPTING;
2378 setContextSwitches();
2379 #if defined(THREADED_RTS)
2384 /* -----------------------------------------------------------------------------
2387 This function causes at least one OS thread to wake up and run the
2388 scheduler loop. It is invoked when the RTS might be deadlocked, or
2389 an external event has arrived that may need servicing (eg. a
2390 keyboard interrupt).
2392 In the single-threaded RTS we don't do anything here; we only have
2393 one thread anyway, and the event that caused us to want to wake up
2394 will have interrupted any blocking system call in progress anyway.
2395 -------------------------------------------------------------------------- */
2397 #if defined(THREADED_RTS)
2398 void wakeUpRts(void)
2400 // This forces the IO Manager thread to wakeup, which will
2401 // in turn ensure that some OS thread wakes up and runs the
2402 // scheduler loop, which will cause a GC and deadlock check.
2407 /* -----------------------------------------------------------------------------
2410 * Check the blackhole_queue for threads that can be woken up. We do
2411 * this periodically: before every GC, and whenever the run queue is
2414 * An elegant solution might be to just wake up all the blocked
2415 * threads with awakenBlockedQueue occasionally: they'll go back to
2416 * sleep again if the object is still a BLACKHOLE. Unfortunately this
2417 * doesn't give us a way to tell whether we've actually managed to
2418 * wake up any threads, so we would be busy-waiting.
2420 * -------------------------------------------------------------------------- */
2423 checkBlackHoles (Capability *cap)
2426 rtsBool any_woke_up = rtsFalse;
2429 // blackhole_queue is global:
2430 ASSERT_LOCK_HELD(&sched_mutex);
2432 debugTrace(DEBUG_sched, "checking threads blocked on black holes");
2434 // ASSUMES: sched_mutex
2435 prev = &blackhole_queue;
2436 t = blackhole_queue;
2437 while (t != END_TSO_QUEUE) {
2438 if (t->what_next == ThreadRelocated) {
2442 ASSERT(t->why_blocked == BlockedOnBlackHole);
2443 type = get_itbl(UNTAG_CLOSURE(t->block_info.closure))->type;
2444 if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
2445 IF_DEBUG(sanity,checkTSO(t));
2446 t = unblockOne(cap, t);
2448 any_woke_up = rtsTrue;
2458 /* -----------------------------------------------------------------------------
2461 This is used for interruption (^C) and forking, and corresponds to
2462 raising an exception but without letting the thread catch the
2464 -------------------------------------------------------------------------- */
2467 deleteThread (Capability *cap, StgTSO *tso)
2469 // NOTE: must only be called on a TSO that we have exclusive
2470 // access to, because we will call throwToSingleThreaded() below.
2471 // The TSO must be on the run queue of the Capability we own, or
2472 // we must own all Capabilities.
2474 if (tso->why_blocked != BlockedOnCCall &&
2475 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2476 throwToSingleThreaded(cap,tso,NULL);
2480 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2482 deleteThread_(Capability *cap, StgTSO *tso)
2483 { // for forkProcess only:
2484 // like deleteThread(), but we delete threads in foreign calls, too.
2486 if (tso->why_blocked == BlockedOnCCall ||
2487 tso->why_blocked == BlockedOnCCall_NoUnblockExc) {
2488 unblockOne(cap,tso);
2489 tso->what_next = ThreadKilled;
2491 deleteThread(cap,tso);
2496 /* -----------------------------------------------------------------------------
2497 raiseExceptionHelper
2499 This function is called by the raise# primitve, just so that we can
2500 move some of the tricky bits of raising an exception from C-- into
2501 C. Who knows, it might be a useful re-useable thing here too.
2502 -------------------------------------------------------------------------- */
2505 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2507 Capability *cap = regTableToCapability(reg);
2508 StgThunk *raise_closure = NULL;
2510 StgRetInfoTable *info;
2512 // This closure represents the expression 'raise# E' where E
2513 // is the exception raise. It is used to overwrite all the
2514 // thunks which are currently under evaluataion.
2517 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2518 // LDV profiling: stg_raise_info has THUNK as its closure
2519 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2520 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2521 // 1 does not cause any problem unless profiling is performed.
2522 // However, when LDV profiling goes on, we need to linearly scan
2523 // small object pool, where raise_closure is stored, so we should
2524 // use MIN_UPD_SIZE.
2526 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2527 // sizeofW(StgClosure)+1);
2531 // Walk up the stack, looking for the catch frame. On the way,
2532 // we update any closures pointed to from update frames with the
2533 // raise closure that we just built.
2537 info = get_ret_itbl((StgClosure *)p);
2538 next = p + stack_frame_sizeW((StgClosure *)p);
2539 switch (info->i.type) {
2542 // Only create raise_closure if we need to.
2543 if (raise_closure == NULL) {
2545 (StgThunk *)allocate(cap,sizeofW(StgThunk)+1);
2546 SET_HDR(raise_closure, &stg_raise_info, CCCS);
2547 raise_closure->payload[0] = exception;
2549 UPD_IND(cap, ((StgUpdateFrame *)p)->updatee,
2550 (StgClosure *)raise_closure);
2554 case ATOMICALLY_FRAME:
2555 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2557 return ATOMICALLY_FRAME;
2563 case CATCH_STM_FRAME:
2564 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2566 return CATCH_STM_FRAME;
2572 case CATCH_RETRY_FRAME:
2581 /* -----------------------------------------------------------------------------
2582 findRetryFrameHelper
2584 This function is called by the retry# primitive. It traverses the stack
2585 leaving tso->sp referring to the frame which should handle the retry.
2587 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2588 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2590 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2591 create) because retries are not considered to be exceptions, despite the
2592 similar implementation.
2594 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2595 not be created within memory transactions.
2596 -------------------------------------------------------------------------- */
2599 findRetryFrameHelper (StgTSO *tso)
2602 StgRetInfoTable *info;
2606 info = get_ret_itbl((StgClosure *)p);
2607 next = p + stack_frame_sizeW((StgClosure *)p);
2608 switch (info->i.type) {
2610 case ATOMICALLY_FRAME:
2611 debugTrace(DEBUG_stm,
2612 "found ATOMICALLY_FRAME at %p during retry", p);
2614 return ATOMICALLY_FRAME;
2616 case CATCH_RETRY_FRAME:
2617 debugTrace(DEBUG_stm,
2618 "found CATCH_RETRY_FRAME at %p during retrry", p);
2620 return CATCH_RETRY_FRAME;
2622 case CATCH_STM_FRAME: {
2623 StgTRecHeader *trec = tso -> trec;
2624 StgTRecHeader *outer = trec -> enclosing_trec;
2625 debugTrace(DEBUG_stm,
2626 "found CATCH_STM_FRAME at %p during retry", p);
2627 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2628 stmAbortTransaction(tso -> cap, trec);
2629 stmFreeAbortedTRec(tso -> cap, trec);
2630 tso -> trec = outer;
2637 ASSERT(info->i.type != CATCH_FRAME);
2638 ASSERT(info->i.type != STOP_FRAME);
2645 /* -----------------------------------------------------------------------------
2646 resurrectThreads is called after garbage collection on the list of
2647 threads found to be garbage. Each of these threads will be woken
2648 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2649 on an MVar, or NonTermination if the thread was blocked on a Black
2652 Locks: assumes we hold *all* the capabilities.
2653 -------------------------------------------------------------------------- */
2656 resurrectThreads (StgTSO *threads)
2662 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2663 next = tso->global_link;
2665 gen = Bdescr((P_)tso)->gen;
2666 tso->global_link = gen->threads;
2669 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2671 // Wake up the thread on the Capability it was last on
2674 switch (tso->why_blocked) {
2676 /* Called by GC - sched_mutex lock is currently held. */
2677 throwToSingleThreaded(cap, tso,
2678 (StgClosure *)blockedIndefinitelyOnMVar_closure);
2680 case BlockedOnBlackHole:
2681 throwToSingleThreaded(cap, tso,
2682 (StgClosure *)nonTermination_closure);
2685 throwToSingleThreaded(cap, tso,
2686 (StgClosure *)blockedIndefinitelyOnSTM_closure);
2689 /* This might happen if the thread was blocked on a black hole
2690 * belonging to a thread that we've just woken up (raiseAsync
2691 * can wake up threads, remember...).
2694 case BlockedOnException:
2695 // throwTo should never block indefinitely: if the target
2696 // thread dies or completes, throwTo returns.
2697 barf("resurrectThreads: thread BlockedOnException");
2700 barf("resurrectThreads: thread blocked in a strange way");
2705 /* -----------------------------------------------------------------------------
2706 performPendingThrowTos is called after garbage collection, and
2707 passed a list of threads that were found to have pending throwTos
2708 (tso->blocked_exceptions was not empty), and were blocked.
2709 Normally this doesn't happen, because we would deliver the
2710 exception directly if the target thread is blocked, but there are
2711 small windows where it might occur on a multiprocessor (see
2714 NB. we must be holding all the capabilities at this point, just
2715 like resurrectThreads().
2716 -------------------------------------------------------------------------- */
2719 performPendingThrowTos (StgTSO *threads)
2723 Task *task, *saved_task;;
2729 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2730 next = tso->global_link;
2732 gen = Bdescr((P_)tso)->gen;
2733 tso->global_link = gen->threads;
2736 debugTrace(DEBUG_sched, "performing blocked throwTo to thread %lu", (unsigned long)tso->id);
2738 // We must pretend this Capability belongs to the current Task
2739 // for the time being, as invariants will be broken otherwise.
2740 // In fact the current Task has exclusive access to the systme
2741 // at this point, so this is just bookkeeping:
2742 task->cap = tso->cap;
2743 saved_task = tso->cap->running_task;
2744 tso->cap->running_task = task;
2745 maybePerformBlockedException(tso->cap, tso);
2746 tso->cap->running_task = saved_task;
2749 // Restore our original Capability: