1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2005
5 * The scheduler and thread-related functionality
7 * --------------------------------------------------------------------------*/
9 #include "PosixSource.h"
14 #include "BlockAlloc.h"
15 #include "OSThreads.h"
20 #include "StgMiscClosures.h"
21 #include "Interpreter.h"
22 #include "Exception.h"
24 #include "RtsSignals.h"
30 #include "ThreadLabels.h"
31 #include "LdvProfile.h"
34 #include "Proftimer.h"
37 #if defined(GRAN) || defined(PARALLEL_HASKELL)
38 # include "GranSimRts.h"
40 # include "ParallelRts.h"
41 # include "Parallel.h"
42 # include "ParallelDebug.h"
47 #include "Capability.h"
49 #include "AwaitEvent.h"
51 #ifdef HAVE_SYS_TYPES_H
52 #include <sys/types.h>
66 // Turn off inlining when debugging - it obfuscates things
69 # define STATIC_INLINE static
73 #define USED_WHEN_THREADED_RTS
74 #define USED_WHEN_NON_THREADED_RTS STG_UNUSED
76 #define USED_WHEN_THREADED_RTS STG_UNUSED
77 #define USED_WHEN_NON_THREADED_RTS
83 #define USED_WHEN_SMP STG_UNUSED
86 /* -----------------------------------------------------------------------------
88 * -------------------------------------------------------------------------- */
92 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
93 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
96 In GranSim we have a runnable and a blocked queue for each processor.
97 In order to minimise code changes new arrays run_queue_hds/tls
98 are created. run_queue_hd is then a short cut (macro) for
99 run_queue_hds[CurrentProc] (see GranSim.h).
102 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
103 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
104 StgTSO *ccalling_threadss[MAX_PROC];
105 /* We use the same global list of threads (all_threads) in GranSim as in
106 the std RTS (i.e. we are cheating). However, we don't use this list in
107 the GranSim specific code at the moment (so we are only potentially
112 #if !defined(THREADED_RTS)
113 // Blocked/sleeping thrads
114 StgTSO *blocked_queue_hd = NULL;
115 StgTSO *blocked_queue_tl = NULL;
116 StgTSO *sleeping_queue = NULL; // perhaps replace with a hash table?
119 /* Threads blocked on blackholes.
120 * LOCK: sched_mutex+capability, or all capabilities
122 StgTSO *blackhole_queue = NULL;
125 /* The blackhole_queue should be checked for threads to wake up. See
126 * Schedule.h for more thorough comment.
127 * LOCK: none (doesn't matter if we miss an update)
129 rtsBool blackholes_need_checking = rtsFalse;
131 /* Linked list of all threads.
132 * Used for detecting garbage collected threads.
133 * LOCK: sched_mutex+capability, or all capabilities
135 StgTSO *all_threads = NULL;
137 /* flag set by signal handler to precipitate a context switch
138 * LOCK: none (just an advisory flag)
140 int context_switch = 0;
142 /* flag that tracks whether we have done any execution in this time slice.
143 * LOCK: currently none, perhaps we should lock (but needs to be
144 * updated in the fast path of the scheduler).
146 nat recent_activity = ACTIVITY_YES;
148 /* if this flag is set as well, give up execution
149 * LOCK: none (changes once, from false->true)
151 rtsBool interrupted = rtsFalse;
153 /* Next thread ID to allocate.
156 static StgThreadID next_thread_id = 1;
158 /* The smallest stack size that makes any sense is:
159 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
160 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
161 * + 1 (the closure to enter)
163 * + 1 (spare slot req'd by stg_ap_v_ret)
165 * A thread with this stack will bomb immediately with a stack
166 * overflow, which will increase its stack size.
168 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 3)
174 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
175 * exists - earlier gccs apparently didn't.
181 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
182 * in an MT setting, needed to signal that a worker thread shouldn't hang around
183 * in the scheduler when it is out of work.
185 rtsBool shutting_down_scheduler = rtsFalse;
188 * This mutex protects most of the global scheduler data in
189 * the THREADED_RTS and (inc. SMP) runtime.
191 #if defined(THREADED_RTS)
192 Mutex sched_mutex = INIT_MUTEX_VAR;
195 #if defined(PARALLEL_HASKELL)
197 rtsTime TimeOfLastYield;
198 rtsBool emitSchedule = rtsTrue;
201 /* -----------------------------------------------------------------------------
202 * static function prototypes
203 * -------------------------------------------------------------------------- */
205 static Capability *schedule (Capability *initialCapability, Task *task);
208 // These function all encapsulate parts of the scheduler loop, and are
209 // abstracted only to make the structure and control flow of the
210 // scheduler clearer.
212 static void schedulePreLoop (void);
213 static void schedulePushWork(Capability *cap, Task *task);
214 static void scheduleStartSignalHandlers (void);
215 static void scheduleCheckBlockedThreads (Capability *cap);
216 static void scheduleCheckBlackHoles (Capability *cap);
217 static void scheduleDetectDeadlock (Capability *cap, Task *task);
219 static StgTSO *scheduleProcessEvent(rtsEvent *event);
221 #if defined(PARALLEL_HASKELL)
222 static StgTSO *scheduleSendPendingMessages(void);
223 static void scheduleActivateSpark(void);
224 static rtsBool scheduleGetRemoteWork(rtsBool *receivedFinish);
226 #if defined(PAR) || defined(GRAN)
227 static void scheduleGranParReport(void);
229 static void schedulePostRunThread(void);
230 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
231 static void scheduleHandleStackOverflow( Capability *cap, Task *task,
233 static rtsBool scheduleHandleYield( Capability *cap, StgTSO *t,
234 nat prev_what_next );
235 static void scheduleHandleThreadBlocked( StgTSO *t );
236 static rtsBool scheduleHandleThreadFinished( Capability *cap, Task *task,
238 static rtsBool scheduleDoHeapProfile(rtsBool ready_to_gc);
239 static void scheduleDoGC(Capability *cap, Task *task, rtsBool force_major);
241 static void unblockThread(Capability *cap, StgTSO *tso);
242 static rtsBool checkBlackHoles(Capability *cap);
243 static void AllRoots(evac_fn evac);
245 static StgTSO *threadStackOverflow(Capability *cap, StgTSO *tso);
247 static void raiseAsync_(Capability *cap, StgTSO *tso, StgClosure *exception,
248 rtsBool stop_at_atomically);
250 static void deleteThread (Capability *cap, StgTSO *tso);
251 static void deleteRunQueue (Capability *cap);
254 static void printThreadBlockage(StgTSO *tso);
255 static void printThreadStatus(StgTSO *tso);
256 void printThreadQueue(StgTSO *tso);
259 #if defined(PARALLEL_HASKELL)
260 StgTSO * createSparkThread(rtsSpark spark);
261 StgTSO * activateSpark (rtsSpark spark);
265 static char *whatNext_strs[] = {
275 /* -----------------------------------------------------------------------------
276 * Putting a thread on the run queue: different scheduling policies
277 * -------------------------------------------------------------------------- */
280 addToRunQueue( Capability *cap, StgTSO *t )
282 #if defined(PARALLEL_HASKELL)
283 if (RtsFlags.ParFlags.doFairScheduling) {
284 // this does round-robin scheduling; good for concurrency
285 appendToRunQueue(cap,t);
287 // this does unfair scheduling; good for parallelism
288 pushOnRunQueue(cap,t);
291 // this does round-robin scheduling; good for concurrency
292 appendToRunQueue(cap,t);
296 /* ---------------------------------------------------------------------------
297 Main scheduling loop.
299 We use round-robin scheduling, each thread returning to the
300 scheduler loop when one of these conditions is detected:
303 * timer expires (thread yields)
309 In a GranSim setup this loop iterates over the global event queue.
310 This revolves around the global event queue, which determines what
311 to do next. Therefore, it's more complicated than either the
312 concurrent or the parallel (GUM) setup.
315 GUM iterates over incoming messages.
316 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
317 and sends out a fish whenever it has nothing to do; in-between
318 doing the actual reductions (shared code below) it processes the
319 incoming messages and deals with delayed operations
320 (see PendingFetches).
321 This is not the ugliest code you could imagine, but it's bloody close.
323 ------------------------------------------------------------------------ */
326 schedule (Capability *initialCapability, Task *task)
330 StgThreadReturnCode ret;
333 #elif defined(PARALLEL_HASKELL)
336 rtsBool receivedFinish = rtsFalse;
338 nat tp_size, sp_size; // stats only
343 rtsBool first = rtsTrue;
345 cap = initialCapability;
347 // Pre-condition: this task owns initialCapability.
348 // The sched_mutex is *NOT* held
349 // NB. on return, we still hold a capability.
352 sched_belch("### NEW SCHEDULER LOOP (task: %p, cap: %p)",
353 task, initialCapability);
358 // -----------------------------------------------------------
359 // Scheduler loop starts here:
361 #if defined(PARALLEL_HASKELL)
362 #define TERMINATION_CONDITION (!receivedFinish)
364 #define TERMINATION_CONDITION ((event = get_next_event()) != (rtsEvent*)NULL)
366 #define TERMINATION_CONDITION rtsTrue
369 while (TERMINATION_CONDITION) {
372 /* Choose the processor with the next event */
373 CurrentProc = event->proc;
374 CurrentTSO = event->tso;
377 #if defined(THREADED_RTS)
379 // don't yield the first time, we want a chance to run this
380 // thread for a bit, even if there are others banging at the
383 ASSERT_CAPABILITY_INVARIANTS(cap,task);
385 // Yield the capability to higher-priority tasks if necessary.
386 yieldCapability(&cap, task);
391 schedulePushWork(cap,task);
394 // Check whether we have re-entered the RTS from Haskell without
395 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
397 if (cap->in_haskell) {
398 errorBelch("schedule: re-entered unsafely.\n"
399 " Perhaps a 'foreign import unsafe' should be 'safe'?");
400 stg_exit(EXIT_FAILURE);
404 // Test for interruption. If interrupted==rtsTrue, then either
405 // we received a keyboard interrupt (^C), or the scheduler is
406 // trying to shut down all the tasks (shutting_down_scheduler) in
411 if (shutting_down_scheduler) {
412 IF_DEBUG(scheduler, sched_belch("shutting down"));
413 // If we are a worker, just exit. If we're a bound thread
414 // then we will exit below when we've removed our TSO from
416 if (task->tso == NULL) {
420 IF_DEBUG(scheduler, sched_belch("interrupted"));
424 #if defined(not_yet) && defined(SMP)
426 // Top up the run queue from our spark pool. We try to make the
427 // number of threads in the run queue equal to the number of
428 // free capabilities.
432 if (emptyRunQueue()) {
433 spark = findSpark(rtsFalse);
435 break; /* no more sparks in the pool */
437 createSparkThread(spark);
439 sched_belch("==^^ turning spark of closure %p into a thread",
440 (StgClosure *)spark));
446 scheduleStartSignalHandlers();
448 // Only check the black holes here if we've nothing else to do.
449 // During normal execution, the black hole list only gets checked
450 // at GC time, to avoid repeatedly traversing this possibly long
451 // list each time around the scheduler.
452 if (emptyRunQueue(cap)) { scheduleCheckBlackHoles(cap); }
454 scheduleCheckBlockedThreads(cap);
456 scheduleDetectDeadlock(cap,task);
458 // Normally, the only way we can get here with no threads to
459 // run is if a keyboard interrupt received during
460 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
461 // Additionally, it is not fatal for the
462 // threaded RTS to reach here with no threads to run.
464 // win32: might be here due to awaitEvent() being abandoned
465 // as a result of a console event having been delivered.
466 if ( emptyRunQueue(cap) ) {
467 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
470 continue; // nothing to do
473 #if defined(PARALLEL_HASKELL)
474 scheduleSendPendingMessages();
475 if (emptyRunQueue(cap) && scheduleActivateSpark())
479 ASSERT(next_fish_to_send_at==0); // i.e. no delayed fishes left!
482 /* If we still have no work we need to send a FISH to get a spark
484 if (emptyRunQueue(cap)) {
485 if (!scheduleGetRemoteWork(&receivedFinish)) continue;
486 ASSERT(rtsFalse); // should not happen at the moment
488 // from here: non-empty run queue.
489 // TODO: merge above case with this, only one call processMessages() !
490 if (PacketsWaiting()) { /* process incoming messages, if
491 any pending... only in else
492 because getRemoteWork waits for
494 receivedFinish = processMessages();
499 scheduleProcessEvent(event);
503 // Get a thread to run
505 t = popRunQueue(cap);
507 #if defined(GRAN) || defined(PAR)
508 scheduleGranParReport(); // some kind of debuging output
510 // Sanity check the thread we're about to run. This can be
511 // expensive if there is lots of thread switching going on...
512 IF_DEBUG(sanity,checkTSO(t));
515 #if defined(THREADED_RTS)
516 // Check whether we can run this thread in the current task.
517 // If not, we have to pass our capability to the right task.
519 Task *bound = t->bound;
524 sched_belch("### Running thread %d in bound thread",
526 // yes, the Haskell thread is bound to the current native thread
529 sched_belch("### thread %d bound to another OS thread",
531 // no, bound to a different Haskell thread: pass to that thread
532 pushOnRunQueue(cap,t);
536 // The thread we want to run is unbound.
539 sched_belch("### this OS thread cannot run thread %d", t->id));
540 // no, the current native thread is bound to a different
541 // Haskell thread, so pass it to any worker thread
542 pushOnRunQueue(cap,t);
549 cap->r.rCurrentTSO = t;
551 /* context switches are initiated by the timer signal, unless
552 * the user specified "context switch as often as possible", with
555 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
556 && !emptyThreadQueues(cap)) {
562 IF_DEBUG(scheduler, sched_belch("-->> running thread %ld %s ...",
563 (long)t->id, whatNext_strs[t->what_next]));
565 #if defined(PROFILING)
566 startHeapProfTimer();
569 // ----------------------------------------------------------------------
570 // Run the current thread
572 prev_what_next = t->what_next;
574 errno = t->saved_errno;
575 cap->in_haskell = rtsTrue;
577 recent_activity = ACTIVITY_YES;
579 switch (prev_what_next) {
583 /* Thread already finished, return to scheduler. */
584 ret = ThreadFinished;
590 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
591 cap = regTableToCapability(r);
596 case ThreadInterpret:
597 cap = interpretBCO(cap);
602 barf("schedule: invalid what_next field");
605 cap->in_haskell = rtsFalse;
607 // The TSO might have moved, eg. if it re-entered the RTS and a GC
608 // happened. So find the new location:
609 t = cap->r.rCurrentTSO;
612 // If ret is ThreadBlocked, and this Task is bound to the TSO that
613 // blocked, we are in limbo - the TSO is now owned by whatever it
614 // is blocked on, and may in fact already have been woken up,
615 // perhaps even on a different Capability. It may be the case
616 // that task->cap != cap. We better yield this Capability
617 // immediately and return to normaility.
618 if (ret == ThreadBlocked) {
620 debugBelch("--<< thread %d (%s) stopped: blocked\n",
621 t->id, whatNext_strs[t->what_next]));
626 ASSERT_CAPABILITY_INVARIANTS(cap,task);
628 // And save the current errno in this thread.
629 t->saved_errno = errno;
631 // ----------------------------------------------------------------------
633 // Costs for the scheduler are assigned to CCS_SYSTEM
634 #if defined(PROFILING)
639 // We have run some Haskell code: there might be blackhole-blocked
640 // threads to wake up now.
641 // Lock-free test here should be ok, we're just setting a flag.
642 if ( blackhole_queue != END_TSO_QUEUE ) {
643 blackholes_need_checking = rtsTrue;
646 #if defined(THREADED_RTS)
647 IF_DEBUG(scheduler,debugBelch("sched (task %p): ", (void *)(unsigned long)(unsigned int)osThreadId()););
648 #elif !defined(GRAN) && !defined(PARALLEL_HASKELL)
649 IF_DEBUG(scheduler,debugBelch("sched: "););
652 schedulePostRunThread();
654 ready_to_gc = rtsFalse;
658 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
662 scheduleHandleStackOverflow(cap,task,t);
666 if (scheduleHandleYield(cap, t, prev_what_next)) {
667 // shortcut for switching between compiler/interpreter:
673 scheduleHandleThreadBlocked(t);
677 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
678 ASSERT_CAPABILITY_INVARIANTS(cap,task);
682 barf("schedule: invalid thread return code %d", (int)ret);
685 if (scheduleDoHeapProfile(ready_to_gc)) { ready_to_gc = rtsFalse; }
686 if (ready_to_gc) { scheduleDoGC(cap,task,rtsFalse); }
687 } /* end of while() */
689 IF_PAR_DEBUG(verbose,
690 debugBelch("== Leaving schedule() after having received Finish\n"));
693 /* ----------------------------------------------------------------------------
694 * Setting up the scheduler loop
695 * ------------------------------------------------------------------------- */
698 schedulePreLoop(void)
701 /* set up first event to get things going */
702 /* ToDo: assign costs for system setup and init MainTSO ! */
703 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
705 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
708 debugBelch("GRAN: Init CurrentTSO (in schedule) = %p\n",
710 G_TSO(CurrentTSO, 5));
712 if (RtsFlags.GranFlags.Light) {
713 /* Save current time; GranSim Light only */
714 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
719 /* -----------------------------------------------------------------------------
722 * Push work to other Capabilities if we have some.
723 * -------------------------------------------------------------------------- */
726 schedulePushWork(Capability *cap, Task *task)
729 Capability *free_caps[n_capabilities], *cap0;
732 // Check whether we have more threads on our run queue that we
733 // could hand to another Capability.
734 if (emptyRunQueue(cap) || cap->run_queue_hd->link == END_TSO_QUEUE) {
738 // First grab as many free Capabilities as we can.
739 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
740 cap0 = &capabilities[i];
741 if (cap != cap0 && tryGrabCapability(cap0,task)) {
742 if (!emptyRunQueue(cap0) || cap->returning_tasks_hd != NULL) {
743 // it already has some work, we just grabbed it at
744 // the wrong moment. Or maybe it's deadlocked!
745 releaseCapability(cap0);
747 free_caps[n_free_caps++] = cap0;
752 // we now have n_free_caps free capabilities stashed in
753 // free_caps[]. Share our run queue equally with them. This is
754 // probably the simplest thing we could do; improvements we might
755 // want to do include:
757 // - giving high priority to moving relatively new threads, on
758 // the gournds that they haven't had time to build up a
759 // working set in the cache on this CPU/Capability.
761 // - giving low priority to moving long-lived threads
763 if (n_free_caps > 0) {
764 StgTSO *prev, *t, *next;
765 IF_DEBUG(scheduler, sched_belch("excess threads on run queue and %d free capabilities, sharing...", n_free_caps));
767 prev = cap->run_queue_hd;
769 prev->link = END_TSO_QUEUE;
771 for (; t != END_TSO_QUEUE; t = next) {
773 t->link = END_TSO_QUEUE;
774 if (t->what_next == ThreadRelocated) {
777 } else if (i == n_free_caps) {
783 appendToRunQueue(free_caps[i],t);
784 if (t->bound) { t->bound->cap = free_caps[i]; }
788 cap->run_queue_tl = prev;
790 // release the capabilities
791 for (i = 0; i < n_free_caps; i++) {
792 task->cap = free_caps[i];
793 releaseCapability(free_caps[i]);
796 task->cap = cap; // reset to point to our Capability.
800 /* ----------------------------------------------------------------------------
801 * Start any pending signal handlers
802 * ------------------------------------------------------------------------- */
805 scheduleStartSignalHandlers(void)
807 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
808 if (signals_pending()) { // safe outside the lock
809 startSignalHandlers();
814 /* ----------------------------------------------------------------------------
815 * Check for blocked threads that can be woken up.
816 * ------------------------------------------------------------------------- */
819 scheduleCheckBlockedThreads(Capability *cap USED_WHEN_NON_THREADED_RTS)
821 #if !defined(THREADED_RTS)
823 // Check whether any waiting threads need to be woken up. If the
824 // run queue is empty, and there are no other tasks running, we
825 // can wait indefinitely for something to happen.
827 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
829 awaitEvent( emptyRunQueue(cap) && !blackholes_need_checking );
835 /* ----------------------------------------------------------------------------
836 * Check for threads blocked on BLACKHOLEs that can be woken up
837 * ------------------------------------------------------------------------- */
839 scheduleCheckBlackHoles (Capability *cap)
841 if ( blackholes_need_checking ) // check without the lock first
843 ACQUIRE_LOCK(&sched_mutex);
844 if ( blackholes_need_checking ) {
845 checkBlackHoles(cap);
846 blackholes_need_checking = rtsFalse;
848 RELEASE_LOCK(&sched_mutex);
852 /* ----------------------------------------------------------------------------
853 * Detect deadlock conditions and attempt to resolve them.
854 * ------------------------------------------------------------------------- */
857 scheduleDetectDeadlock (Capability *cap, Task *task)
860 #if defined(PARALLEL_HASKELL)
861 // ToDo: add deadlock detection in GUM (similar to SMP) -- HWL
866 * Detect deadlock: when we have no threads to run, there are no
867 * threads blocked, waiting for I/O, or sleeping, and all the
868 * other tasks are waiting for work, we must have a deadlock of
871 if ( emptyThreadQueues(cap) )
873 #if defined(THREADED_RTS)
875 * In the threaded RTS, we only check for deadlock if there
876 * has been no activity in a complete timeslice. This means
877 * we won't eagerly start a full GC just because we don't have
878 * any threads to run currently.
880 if (recent_activity != ACTIVITY_INACTIVE) return;
883 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
885 // Garbage collection can release some new threads due to
886 // either (a) finalizers or (b) threads resurrected because
887 // they are unreachable and will therefore be sent an
888 // exception. Any threads thus released will be immediately
890 scheduleDoGC( cap, task, rtsTrue/*force major GC*/ );
891 recent_activity = ACTIVITY_DONE_GC;
893 if ( !emptyRunQueue(cap) ) return;
895 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
896 /* If we have user-installed signal handlers, then wait
897 * for signals to arrive rather then bombing out with a
900 if ( anyUserHandlers() ) {
902 sched_belch("still deadlocked, waiting for signals..."));
906 if (signals_pending()) {
907 startSignalHandlers();
910 // either we have threads to run, or we were interrupted:
911 ASSERT(!emptyRunQueue(cap) || interrupted);
915 #if !defined(THREADED_RTS)
916 /* Probably a real deadlock. Send the current main thread the
917 * Deadlock exception.
920 switch (task->tso->why_blocked) {
922 case BlockedOnBlackHole:
923 case BlockedOnException:
925 raiseAsync(cap, task->tso, (StgClosure *)NonTermination_closure);
928 barf("deadlock: main thread blocked in a strange way");
936 /* ----------------------------------------------------------------------------
937 * Process an event (GRAN only)
938 * ------------------------------------------------------------------------- */
942 scheduleProcessEvent(rtsEvent *event)
946 if (RtsFlags.GranFlags.Light)
947 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
949 /* adjust time based on time-stamp */
950 if (event->time > CurrentTime[CurrentProc] &&
951 event->evttype != ContinueThread)
952 CurrentTime[CurrentProc] = event->time;
954 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
955 if (!RtsFlags.GranFlags.Light)
958 IF_DEBUG(gran, debugBelch("GRAN: switch by event-type\n"));
960 /* main event dispatcher in GranSim */
961 switch (event->evttype) {
962 /* Should just be continuing execution */
964 IF_DEBUG(gran, debugBelch("GRAN: doing ContinueThread\n"));
965 /* ToDo: check assertion
966 ASSERT(run_queue_hd != (StgTSO*)NULL &&
967 run_queue_hd != END_TSO_QUEUE);
969 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
970 if (!RtsFlags.GranFlags.DoAsyncFetch &&
971 procStatus[CurrentProc]==Fetching) {
972 debugBelch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]\n",
973 CurrentTSO->id, CurrentTSO, CurrentProc);
976 /* Ignore ContinueThreads for completed threads */
977 if (CurrentTSO->what_next == ThreadComplete) {
978 debugBelch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)\n",
979 CurrentTSO->id, CurrentTSO, CurrentProc);
982 /* Ignore ContinueThreads for threads that are being migrated */
983 if (PROCS(CurrentTSO)==Nowhere) {
984 debugBelch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)\n",
985 CurrentTSO->id, CurrentTSO, CurrentProc);
988 /* The thread should be at the beginning of the run queue */
989 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
990 debugBelch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread\n",
991 CurrentTSO->id, CurrentTSO, CurrentProc);
992 break; // run the thread anyway
995 new_event(proc, proc, CurrentTime[proc],
997 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
999 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
1000 break; // now actually run the thread; DaH Qu'vam yImuHbej
1003 do_the_fetchnode(event);
1004 goto next_thread; /* handle next event in event queue */
1007 do_the_globalblock(event);
1008 goto next_thread; /* handle next event in event queue */
1011 do_the_fetchreply(event);
1012 goto next_thread; /* handle next event in event queue */
1014 case UnblockThread: /* Move from the blocked queue to the tail of */
1015 do_the_unblock(event);
1016 goto next_thread; /* handle next event in event queue */
1018 case ResumeThread: /* Move from the blocked queue to the tail of */
1019 /* the runnable queue ( i.e. Qu' SImqa'lu') */
1020 event->tso->gran.blocktime +=
1021 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
1022 do_the_startthread(event);
1023 goto next_thread; /* handle next event in event queue */
1026 do_the_startthread(event);
1027 goto next_thread; /* handle next event in event queue */
1030 do_the_movethread(event);
1031 goto next_thread; /* handle next event in event queue */
1034 do_the_movespark(event);
1035 goto next_thread; /* handle next event in event queue */
1038 do_the_findwork(event);
1039 goto next_thread; /* handle next event in event queue */
1042 barf("Illegal event type %u\n", event->evttype);
1045 /* This point was scheduler_loop in the old RTS */
1047 IF_DEBUG(gran, debugBelch("GRAN: after main switch\n"));
1049 TimeOfLastEvent = CurrentTime[CurrentProc];
1050 TimeOfNextEvent = get_time_of_next_event();
1051 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
1052 // CurrentTSO = ThreadQueueHd;
1054 IF_DEBUG(gran, debugBelch("GRAN: time of next event is: %ld\n",
1057 if (RtsFlags.GranFlags.Light)
1058 GranSimLight_leave_system(event, &ActiveTSO);
1060 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
1063 debugBelch("GRAN: end of time-slice is %#lx\n", EndOfTimeSlice));
1065 /* in a GranSim setup the TSO stays on the run queue */
1067 /* Take a thread from the run queue. */
1068 POP_RUN_QUEUE(t); // take_off_run_queue(t);
1071 debugBelch("GRAN: About to run current thread, which is\n");
1074 context_switch = 0; // turned on via GranYield, checking events and time slice
1077 DumpGranEvent(GR_SCHEDULE, t));
1079 procStatus[CurrentProc] = Busy;
1083 /* ----------------------------------------------------------------------------
1084 * Send pending messages (PARALLEL_HASKELL only)
1085 * ------------------------------------------------------------------------- */
1087 #if defined(PARALLEL_HASKELL)
1089 scheduleSendPendingMessages(void)
1095 # if defined(PAR) // global Mem.Mgmt., omit for now
1096 if (PendingFetches != END_BF_QUEUE) {
1101 if (RtsFlags.ParFlags.BufferTime) {
1102 // if we use message buffering, we must send away all message
1103 // packets which have become too old...
1109 /* ----------------------------------------------------------------------------
1110 * Activate spark threads (PARALLEL_HASKELL only)
1111 * ------------------------------------------------------------------------- */
1113 #if defined(PARALLEL_HASKELL)
1115 scheduleActivateSpark(void)
1118 ASSERT(emptyRunQueue());
1119 /* We get here if the run queue is empty and want some work.
1120 We try to turn a spark into a thread, and add it to the run queue,
1121 from where it will be picked up in the next iteration of the scheduler
1125 /* :-[ no local threads => look out for local sparks */
1126 /* the spark pool for the current PE */
1127 pool = &(cap.r.rSparks); // JB: cap = (old) MainCap
1128 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
1129 pool->hd < pool->tl) {
1131 * ToDo: add GC code check that we really have enough heap afterwards!!
1133 * If we're here (no runnable threads) and we have pending
1134 * sparks, we must have a space problem. Get enough space
1135 * to turn one of those pending sparks into a
1139 spark = findSpark(rtsFalse); /* get a spark */
1140 if (spark != (rtsSpark) NULL) {
1141 tso = createThreadFromSpark(spark); /* turn the spark into a thread */
1142 IF_PAR_DEBUG(fish, // schedule,
1143 debugBelch("==== schedule: Created TSO %d (%p); %d threads active\n",
1144 tso->id, tso, advisory_thread_count));
1146 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
1147 IF_PAR_DEBUG(fish, // schedule,
1148 debugBelch("==^^ failed to create thread from spark @ %lx\n",
1150 return rtsFalse; /* failed to generate a thread */
1151 } /* otherwise fall through & pick-up new tso */
1153 IF_PAR_DEBUG(fish, // schedule,
1154 debugBelch("==^^ no local sparks (spark pool contains only NFs: %d)\n",
1155 spark_queue_len(pool)));
1156 return rtsFalse; /* failed to generate a thread */
1158 return rtsTrue; /* success in generating a thread */
1159 } else { /* no more threads permitted or pool empty */
1160 return rtsFalse; /* failed to generateThread */
1163 tso = NULL; // avoid compiler warning only
1164 return rtsFalse; /* dummy in non-PAR setup */
1167 #endif // PARALLEL_HASKELL
1169 /* ----------------------------------------------------------------------------
1170 * Get work from a remote node (PARALLEL_HASKELL only)
1171 * ------------------------------------------------------------------------- */
1173 #if defined(PARALLEL_HASKELL)
1175 scheduleGetRemoteWork(rtsBool *receivedFinish)
1177 ASSERT(emptyRunQueue());
1179 if (RtsFlags.ParFlags.BufferTime) {
1180 IF_PAR_DEBUG(verbose,
1181 debugBelch("...send all pending data,"));
1184 for (i=1; i<=nPEs; i++)
1185 sendImmediately(i); // send all messages away immediately
1189 //++EDEN++ idle() , i.e. send all buffers, wait for work
1190 // suppress fishing in EDEN... just look for incoming messages
1191 // (blocking receive)
1192 IF_PAR_DEBUG(verbose,
1193 debugBelch("...wait for incoming messages...\n"));
1194 *receivedFinish = processMessages(); // blocking receive...
1196 // and reenter scheduling loop after having received something
1197 // (return rtsFalse below)
1199 # else /* activate SPARKS machinery */
1200 /* We get here, if we have no work, tried to activate a local spark, but still
1201 have no work. We try to get a remote spark, by sending a FISH message.
1202 Thread migration should be added here, and triggered when a sequence of
1203 fishes returns without work. */
1204 delay = (RtsFlags.ParFlags.fishDelay!=0ll ? RtsFlags.ParFlags.fishDelay : 0ll);
1206 /* =8-[ no local sparks => look for work on other PEs */
1208 * We really have absolutely no work. Send out a fish
1209 * (there may be some out there already), and wait for
1210 * something to arrive. We clearly can't run any threads
1211 * until a SCHEDULE or RESUME arrives, and so that's what
1212 * we're hoping to see. (Of course, we still have to
1213 * respond to other types of messages.)
1215 rtsTime now = msTime() /*CURRENT_TIME*/;
1216 IF_PAR_DEBUG(verbose,
1217 debugBelch("-- now=%ld\n", now));
1218 IF_PAR_DEBUG(fish, // verbose,
1219 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
1220 (last_fish_arrived_at!=0 &&
1221 last_fish_arrived_at+delay > now)) {
1222 debugBelch("--$$ <%llu> delaying FISH until %llu (last fish %llu, delay %llu)\n",
1223 now, last_fish_arrived_at+delay,
1224 last_fish_arrived_at,
1228 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
1229 advisory_thread_count < RtsFlags.ParFlags.maxThreads) { // send a FISH, but when?
1230 if (last_fish_arrived_at==0 ||
1231 (last_fish_arrived_at+delay <= now)) { // send FISH now!
1232 /* outstandingFishes is set in sendFish, processFish;
1233 avoid flooding system with fishes via delay */
1234 next_fish_to_send_at = 0;
1236 /* ToDo: this should be done in the main scheduling loop to avoid the
1237 busy wait here; not so bad if fish delay is very small */
1238 int iq = 0; // DEBUGGING -- HWL
1239 next_fish_to_send_at = last_fish_arrived_at+delay; // remember when to send
1240 /* send a fish when ready, but process messages that arrive in the meantime */
1242 if (PacketsWaiting()) {
1244 *receivedFinish = processMessages();
1247 } while (!*receivedFinish || now<next_fish_to_send_at);
1248 // JB: This means the fish could become obsolete, if we receive
1249 // work. Better check for work again?
1250 // last line: while (!receivedFinish || !haveWork || now<...)
1251 // next line: if (receivedFinish || haveWork )
1253 if (*receivedFinish) // no need to send a FISH if we are finishing anyway
1254 return rtsFalse; // NB: this will leave scheduler loop
1255 // immediately after return!
1257 IF_PAR_DEBUG(fish, // verbose,
1258 debugBelch("--$$ <%llu> sent delayed fish (%d processMessages); active/total threads=%d/%d\n",now,iq,run_queue_len(),advisory_thread_count));
1262 // JB: IMHO, this should all be hidden inside sendFish(...)
1264 sendFish(pe, thisPE, NEW_FISH_AGE, NEW_FISH_HISTORY,
1267 // Global statistics: count no. of fishes
1268 if (RtsFlags.ParFlags.ParStats.Global &&
1269 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1270 globalParStats.tot_fish_mess++;
1274 /* delayed fishes must have been sent by now! */
1275 next_fish_to_send_at = 0;
1278 *receivedFinish = processMessages();
1279 # endif /* SPARKS */
1282 /* NB: this function always returns rtsFalse, meaning the scheduler
1283 loop continues with the next iteration;
1285 return code means success in finding work; we enter this function
1286 if there is no local work, thus have to send a fish which takes
1287 time until it arrives with work; in the meantime we should process
1288 messages in the main loop;
1291 #endif // PARALLEL_HASKELL
1293 /* ----------------------------------------------------------------------------
1294 * PAR/GRAN: Report stats & debugging info(?)
1295 * ------------------------------------------------------------------------- */
1297 #if defined(PAR) || defined(GRAN)
1299 scheduleGranParReport(void)
1301 ASSERT(run_queue_hd != END_TSO_QUEUE);
1303 /* Take a thread from the run queue, if we have work */
1304 POP_RUN_QUEUE(t); // take_off_run_queue(END_TSO_QUEUE);
1306 /* If this TSO has got its outport closed in the meantime,
1307 * it mustn't be run. Instead, we have to clean it up as if it was finished.
1308 * It has to be marked as TH_DEAD for this purpose.
1309 * If it is TH_TERM instead, it is supposed to have finished in the normal way.
1311 JB: TODO: investigate wether state change field could be nuked
1312 entirely and replaced by the normal tso state (whatnext
1313 field). All we want to do is to kill tsos from outside.
1316 /* ToDo: write something to the log-file
1317 if (RTSflags.ParFlags.granSimStats && !sameThread)
1318 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
1322 /* the spark pool for the current PE */
1323 pool = &(cap.r.rSparks); // cap = (old) MainCap
1326 debugBelch("--=^ %d threads, %d sparks on [%#x]\n",
1327 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
1330 debugBelch("--=^ %d threads, %d sparks on [%#x]\n",
1331 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
1333 if (RtsFlags.ParFlags.ParStats.Full &&
1334 (t->par.sparkname != (StgInt)0) && // only log spark generated threads
1335 (emitSchedule || // forced emit
1336 (t && LastTSO && t->id != LastTSO->id))) {
1338 we are running a different TSO, so write a schedule event to log file
1339 NB: If we use fair scheduling we also have to write a deschedule
1340 event for LastTSO; with unfair scheduling we know that the
1341 previous tso has blocked whenever we switch to another tso, so
1342 we don't need it in GUM for now
1344 IF_PAR_DEBUG(fish, // schedule,
1345 debugBelch("____ scheduling spark generated thread %d (%lx) (%lx) via a forced emit\n",t->id,t,t->par.sparkname));
1347 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1348 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
1349 emitSchedule = rtsFalse;
1354 /* ----------------------------------------------------------------------------
1355 * After running a thread...
1356 * ------------------------------------------------------------------------- */
1359 schedulePostRunThread(void)
1362 /* HACK 675: if the last thread didn't yield, make sure to print a
1363 SCHEDULE event to the log file when StgRunning the next thread, even
1364 if it is the same one as before */
1366 TimeOfLastYield = CURRENT_TIME;
1369 /* some statistics gathering in the parallel case */
1371 #if defined(GRAN) || defined(PAR) || defined(EDEN)
1375 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
1376 globalGranStats.tot_heapover++;
1378 globalParStats.tot_heapover++;
1385 DumpGranEvent(GR_DESCHEDULE, t));
1386 globalGranStats.tot_stackover++;
1389 // DumpGranEvent(GR_DESCHEDULE, t);
1390 globalParStats.tot_stackover++;
1394 case ThreadYielding:
1397 DumpGranEvent(GR_DESCHEDULE, t));
1398 globalGranStats.tot_yields++;
1401 // DumpGranEvent(GR_DESCHEDULE, t);
1402 globalParStats.tot_yields++;
1409 debugBelch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1410 t->id, t, whatNext_strs[t->what_next], t->block_info.closure,
1411 (t->block_info.closure==(StgClosure*)NULL ? 99 : where_is(t->block_info.closure)));
1412 if (t->block_info.closure!=(StgClosure*)NULL)
1413 print_bq(t->block_info.closure);
1416 // ??? needed; should emit block before
1418 DumpGranEvent(GR_DESCHEDULE, t));
1419 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1422 ASSERT(procStatus[CurrentProc]==Busy ||
1423 ((procStatus[CurrentProc]==Fetching) &&
1424 (t->block_info.closure!=(StgClosure*)NULL)));
1425 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1426 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1427 procStatus[CurrentProc]==Fetching))
1428 procStatus[CurrentProc] = Idle;
1431 //++PAR++ blockThread() writes the event (change?)
1435 case ThreadFinished:
1439 barf("parGlobalStats: unknown return code");
1445 /* -----------------------------------------------------------------------------
1446 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1447 * -------------------------------------------------------------------------- */
1450 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1452 // did the task ask for a large block?
1453 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1454 // if so, get one and push it on the front of the nursery.
1458 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1461 debugBelch("--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1462 (long)t->id, whatNext_strs[t->what_next], blocks));
1464 // don't do this if the nursery is (nearly) full, we'll GC first.
1465 if (cap->r.rCurrentNursery->link != NULL ||
1466 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1467 // if the nursery has only one block.
1470 bd = allocGroup( blocks );
1472 cap->r.rNursery->n_blocks += blocks;
1474 // link the new group into the list
1475 bd->link = cap->r.rCurrentNursery;
1476 bd->u.back = cap->r.rCurrentNursery->u.back;
1477 if (cap->r.rCurrentNursery->u.back != NULL) {
1478 cap->r.rCurrentNursery->u.back->link = bd;
1481 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1482 g0s0 == cap->r.rNursery);
1484 cap->r.rNursery->blocks = bd;
1486 cap->r.rCurrentNursery->u.back = bd;
1488 // initialise it as a nursery block. We initialise the
1489 // step, gen_no, and flags field of *every* sub-block in
1490 // this large block, because this is easier than making
1491 // sure that we always find the block head of a large
1492 // block whenever we call Bdescr() (eg. evacuate() and
1493 // isAlive() in the GC would both have to do this, at
1497 for (x = bd; x < bd + blocks; x++) {
1498 x->step = cap->r.rNursery;
1504 // This assert can be a killer if the app is doing lots
1505 // of large block allocations.
1506 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1508 // now update the nursery to point to the new block
1509 cap->r.rCurrentNursery = bd;
1511 // we might be unlucky and have another thread get on the
1512 // run queue before us and steal the large block, but in that
1513 // case the thread will just end up requesting another large
1515 pushOnRunQueue(cap,t);
1516 return rtsFalse; /* not actually GC'ing */
1521 debugBelch("--<< thread %ld (%s) stopped: HeapOverflow\n",
1522 (long)t->id, whatNext_strs[t->what_next]));
1524 ASSERT(!is_on_queue(t,CurrentProc));
1525 #elif defined(PARALLEL_HASKELL)
1526 /* Currently we emit a DESCHEDULE event before GC in GUM.
1527 ToDo: either add separate event to distinguish SYSTEM time from rest
1528 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1529 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1530 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1531 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1532 emitSchedule = rtsTrue;
1536 pushOnRunQueue(cap,t);
1538 /* actual GC is done at the end of the while loop in schedule() */
1541 /* -----------------------------------------------------------------------------
1542 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1543 * -------------------------------------------------------------------------- */
1546 scheduleHandleStackOverflow (Capability *cap, Task *task, StgTSO *t)
1548 IF_DEBUG(scheduler,debugBelch("--<< thread %ld (%s) stopped, StackOverflow\n",
1549 (long)t->id, whatNext_strs[t->what_next]));
1550 /* just adjust the stack for this thread, then pop it back
1554 /* enlarge the stack */
1555 StgTSO *new_t = threadStackOverflow(cap, t);
1557 /* This TSO has moved, so update any pointers to it from the
1558 * main thread stack. It better not be on any other queues...
1559 * (it shouldn't be).
1561 if (task->tso != NULL) {
1564 pushOnRunQueue(cap,new_t);
1568 /* -----------------------------------------------------------------------------
1569 * Handle a thread that returned to the scheduler with ThreadYielding
1570 * -------------------------------------------------------------------------- */
1573 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1575 // Reset the context switch flag. We don't do this just before
1576 // running the thread, because that would mean we would lose ticks
1577 // during GC, which can lead to unfair scheduling (a thread hogs
1578 // the CPU because the tick always arrives during GC). This way
1579 // penalises threads that do a lot of allocation, but that seems
1580 // better than the alternative.
1583 /* put the thread back on the run queue. Then, if we're ready to
1584 * GC, check whether this is the last task to stop. If so, wake
1585 * up the GC thread. getThread will block during a GC until the
1589 if (t->what_next != prev_what_next) {
1590 debugBelch("--<< thread %ld (%s) stopped to switch evaluators\n",
1591 (long)t->id, whatNext_strs[t->what_next]);
1593 debugBelch("--<< thread %ld (%s) stopped, yielding\n",
1594 (long)t->id, whatNext_strs[t->what_next]);
1599 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1601 ASSERT(t->link == END_TSO_QUEUE);
1603 // Shortcut if we're just switching evaluators: don't bother
1604 // doing stack squeezing (which can be expensive), just run the
1606 if (t->what_next != prev_what_next) {
1611 ASSERT(!is_on_queue(t,CurrentProc));
1614 //debugBelch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1615 checkThreadQsSanity(rtsTrue));
1619 addToRunQueue(cap,t);
1622 /* add a ContinueThread event to actually process the thread */
1623 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1625 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1627 debugBelch("GRAN: eventq and runnableq after adding yielded thread to queue again:\n");
1634 /* -----------------------------------------------------------------------------
1635 * Handle a thread that returned to the scheduler with ThreadBlocked
1636 * -------------------------------------------------------------------------- */
1639 scheduleHandleThreadBlocked( StgTSO *t
1640 #if !defined(GRAN) && !defined(DEBUG)
1647 debugBelch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: \n",
1648 t->id, t, whatNext_strs[t->what_next], t->block_info.closure, (t->block_info.closure==(StgClosure*)NULL ? 99 : where_is(t->block_info.closure)));
1649 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1651 // ??? needed; should emit block before
1653 DumpGranEvent(GR_DESCHEDULE, t));
1654 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1657 ASSERT(procStatus[CurrentProc]==Busy ||
1658 ((procStatus[CurrentProc]==Fetching) &&
1659 (t->block_info.closure!=(StgClosure*)NULL)));
1660 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1661 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1662 procStatus[CurrentProc]==Fetching))
1663 procStatus[CurrentProc] = Idle;
1667 debugBelch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: \n",
1668 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1671 if (t->block_info.closure!=(StgClosure*)NULL)
1672 print_bq(t->block_info.closure));
1674 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1677 /* whatever we schedule next, we must log that schedule */
1678 emitSchedule = rtsTrue;
1682 // We don't need to do anything. The thread is blocked, and it
1683 // has tidied up its stack and placed itself on whatever queue
1684 // it needs to be on.
1687 ASSERT(t->why_blocked != NotBlocked);
1688 // This might not be true under SMP: we don't have
1689 // exclusive access to this TSO, so someone might have
1690 // woken it up by now. This actually happens: try
1691 // conc023 +RTS -N2.
1695 debugBelch("--<< thread %d (%s) stopped: ",
1696 t->id, whatNext_strs[t->what_next]);
1697 printThreadBlockage(t);
1700 /* Only for dumping event to log file
1701 ToDo: do I need this in GranSim, too?
1707 /* -----------------------------------------------------------------------------
1708 * Handle a thread that returned to the scheduler with ThreadFinished
1709 * -------------------------------------------------------------------------- */
1712 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1714 /* Need to check whether this was a main thread, and if so,
1715 * return with the return value.
1717 * We also end up here if the thread kills itself with an
1718 * uncaught exception, see Exception.cmm.
1720 IF_DEBUG(scheduler,debugBelch("--++ thread %d (%s) finished\n",
1721 t->id, whatNext_strs[t->what_next]));
1724 endThread(t, CurrentProc); // clean-up the thread
1725 #elif defined(PARALLEL_HASKELL)
1726 /* For now all are advisory -- HWL */
1727 //if(t->priority==AdvisoryPriority) ??
1728 advisory_thread_count--; // JB: Caution with this counter, buggy!
1731 if(t->dist.priority==RevalPriority)
1735 # if defined(EDENOLD)
1736 // the thread could still have an outport... (BUG)
1737 if (t->eden.outport != -1) {
1738 // delete the outport for the tso which has finished...
1739 IF_PAR_DEBUG(eden_ports,
1740 debugBelch("WARNING: Scheduler removes outport %d for TSO %d.\n",
1741 t->eden.outport, t->id));
1744 // thread still in the process (HEAVY BUG! since outport has just been closed...)
1745 if (t->eden.epid != -1) {
1746 IF_PAR_DEBUG(eden_ports,
1747 debugBelch("WARNING: Scheduler removes TSO %d from process %d .\n",
1748 t->id, t->eden.epid));
1749 removeTSOfromProcess(t);
1754 if (RtsFlags.ParFlags.ParStats.Full &&
1755 !RtsFlags.ParFlags.ParStats.Suppressed)
1756 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1758 // t->par only contains statistics: left out for now...
1760 debugBelch("**** end thread: ended sparked thread %d (%lx); sparkname: %lx\n",
1761 t->id,t,t->par.sparkname));
1763 #endif // PARALLEL_HASKELL
1766 // Check whether the thread that just completed was a bound
1767 // thread, and if so return with the result.
1769 // There is an assumption here that all thread completion goes
1770 // through this point; we need to make sure that if a thread
1771 // ends up in the ThreadKilled state, that it stays on the run
1772 // queue so it can be dealt with here.
1777 if (t->bound != task) {
1778 #if !defined(THREADED_RTS)
1779 // Must be a bound thread that is not the topmost one. Leave
1780 // it on the run queue until the stack has unwound to the
1781 // point where we can deal with this. Leaving it on the run
1782 // queue also ensures that the garbage collector knows about
1783 // this thread and its return value (it gets dropped from the
1784 // all_threads list so there's no other way to find it).
1785 appendToRunQueue(cap,t);
1788 // this cannot happen in the threaded RTS, because a
1789 // bound thread can only be run by the appropriate Task.
1790 barf("finished bound thread that isn't mine");
1794 ASSERT(task->tso == t);
1796 if (t->what_next == ThreadComplete) {
1798 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1799 *(task->ret) = (StgClosure *)task->tso->sp[1];
1801 task->stat = Success;
1804 *(task->ret) = NULL;
1807 task->stat = Interrupted;
1809 task->stat = Killed;
1813 removeThreadLabel((StgWord)task->tso->id);
1815 return rtsTrue; // tells schedule() to return
1821 /* -----------------------------------------------------------------------------
1822 * Perform a heap census, if PROFILING
1823 * -------------------------------------------------------------------------- */
1826 scheduleDoHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1828 #if defined(PROFILING)
1829 // When we have +RTS -i0 and we're heap profiling, do a census at
1830 // every GC. This lets us get repeatable runs for debugging.
1831 if (performHeapProfile ||
1832 (RtsFlags.ProfFlags.profileInterval==0 &&
1833 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1834 GarbageCollect(GetRoots, rtsTrue);
1836 performHeapProfile = rtsFalse;
1837 return rtsTrue; // true <=> we already GC'd
1843 /* -----------------------------------------------------------------------------
1844 * Perform a garbage collection if necessary
1845 * -------------------------------------------------------------------------- */
1848 scheduleDoGC( Capability *cap, Task *task USED_WHEN_SMP, rtsBool force_major )
1852 static volatile StgWord waiting_for_gc;
1853 rtsBool was_waiting;
1858 // In order to GC, there must be no threads running Haskell code.
1859 // Therefore, the GC thread needs to hold *all* the capabilities,
1860 // and release them after the GC has completed.
1862 // This seems to be the simplest way: previous attempts involved
1863 // making all the threads with capabilities give up their
1864 // capabilities and sleep except for the *last* one, which
1865 // actually did the GC. But it's quite hard to arrange for all
1866 // the other tasks to sleep and stay asleep.
1869 was_waiting = cas(&waiting_for_gc, 0, 1);
1872 IF_DEBUG(scheduler, sched_belch("someone else is trying to GC..."));
1873 yieldCapability(&cap,task);
1874 } while (waiting_for_gc);
1878 for (i=0; i < n_capabilities; i++) {
1879 IF_DEBUG(scheduler, sched_belch("ready_to_gc, grabbing all the capabilies (%d/%d)", i, n_capabilities));
1880 if (cap != &capabilities[i]) {
1881 Capability *pcap = &capabilities[i];
1882 // we better hope this task doesn't get migrated to
1883 // another Capability while we're waiting for this one.
1884 // It won't, because load balancing happens while we have
1885 // all the Capabilities, but even so it's a slightly
1886 // unsavoury invariant.
1889 waitForReturnCapability(&pcap, task);
1890 if (pcap != &capabilities[i]) {
1891 barf("scheduleDoGC: got the wrong capability");
1896 waiting_for_gc = rtsFalse;
1899 /* Kick any transactions which are invalid back to their
1900 * atomically frames. When next scheduled they will try to
1901 * commit, this commit will fail and they will retry.
1906 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1907 if (t->what_next == ThreadRelocated) {
1910 next = t->global_link;
1911 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1912 if (!stmValidateNestOfTransactions (t -> trec)) {
1913 IF_DEBUG(stm, sched_belch("trec %p found wasting its time", t));
1915 // strip the stack back to the
1916 // ATOMICALLY_FRAME, aborting the (nested)
1917 // transaction, and saving the stack of any
1918 // partially-evaluated thunks on the heap.
1919 raiseAsync_(cap, t, NULL, rtsTrue);
1922 ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1930 // so this happens periodically:
1931 scheduleCheckBlackHoles(cap);
1933 IF_DEBUG(scheduler, printAllThreads());
1935 /* everybody back, start the GC.
1936 * Could do it in this thread, or signal a condition var
1937 * to do it in another thread. Either way, we need to
1938 * broadcast on gc_pending_cond afterward.
1940 #if defined(THREADED_RTS)
1941 IF_DEBUG(scheduler,sched_belch("doing GC"));
1943 GarbageCollect(GetRoots, force_major);
1946 // release our stash of capabilities.
1947 for (i = 0; i < n_capabilities; i++) {
1948 if (cap != &capabilities[i]) {
1949 task->cap = &capabilities[i];
1950 releaseCapability(&capabilities[i]);
1957 /* add a ContinueThread event to continue execution of current thread */
1958 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1960 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1962 debugBelch("GRAN: eventq and runnableq after Garbage collection:\n\n");
1968 /* ---------------------------------------------------------------------------
1969 * rtsSupportsBoundThreads(): is the RTS built to support bound threads?
1970 * used by Control.Concurrent for error checking.
1971 * ------------------------------------------------------------------------- */
1974 rtsSupportsBoundThreads(void)
1976 #if defined(THREADED_RTS)
1983 /* ---------------------------------------------------------------------------
1984 * isThreadBound(tso): check whether tso is bound to an OS thread.
1985 * ------------------------------------------------------------------------- */
1988 isThreadBound(StgTSO* tso USED_WHEN_THREADED_RTS)
1990 #if defined(THREADED_RTS)
1991 return (tso->bound != NULL);
1996 /* ---------------------------------------------------------------------------
1997 * Singleton fork(). Do not copy any running threads.
1998 * ------------------------------------------------------------------------- */
2000 #if !defined(mingw32_HOST_OS) && !defined(SMP)
2001 #define FORKPROCESS_PRIMOP_SUPPORTED
2004 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2006 deleteThreadImmediately(Capability *cap, StgTSO *tso);
2009 forkProcess(HsStablePtr *entry
2010 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
2015 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2021 IF_DEBUG(scheduler,sched_belch("forking!"));
2023 // ToDo: for SMP, we should probably acquire *all* the capabilities
2028 if (pid) { // parent
2030 // just return the pid
2036 // delete all threads
2037 cap->run_queue_hd = END_TSO_QUEUE;
2038 cap->run_queue_tl = END_TSO_QUEUE;
2040 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
2043 // don't allow threads to catch the ThreadKilled exception
2044 deleteThreadImmediately(cap,t);
2047 // wipe the main thread list
2048 while ((task = all_tasks) != NULL) {
2049 all_tasks = task->all_link;
2053 cap = rts_evalStableIO(cap, entry, NULL); // run the action
2054 rts_checkSchedStatus("forkProcess",cap);
2057 hs_exit(); // clean up and exit
2058 stg_exit(EXIT_SUCCESS);
2060 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
2061 barf("forkProcess#: primop not supported on this platform, sorry!\n");
2066 /* ---------------------------------------------------------------------------
2067 * Delete the threads on the run queue of the current capability.
2068 * ------------------------------------------------------------------------- */
2071 deleteRunQueue (Capability *cap)
2074 for (t = cap->run_queue_hd; t != END_TSO_QUEUE; t = next) {
2075 ASSERT(t->what_next != ThreadRelocated);
2077 deleteThread(cap, t);
2081 /* startThread and insertThread are now in GranSim.c -- HWL */
2084 /* -----------------------------------------------------------------------------
2085 Managing the suspended_ccalling_tasks list.
2086 Locks required: sched_mutex
2087 -------------------------------------------------------------------------- */
2090 suspendTask (Capability *cap, Task *task)
2092 ASSERT(task->next == NULL && task->prev == NULL);
2093 task->next = cap->suspended_ccalling_tasks;
2095 if (cap->suspended_ccalling_tasks) {
2096 cap->suspended_ccalling_tasks->prev = task;
2098 cap->suspended_ccalling_tasks = task;
2102 recoverSuspendedTask (Capability *cap, Task *task)
2105 task->prev->next = task->next;
2107 ASSERT(cap->suspended_ccalling_tasks == task);
2108 cap->suspended_ccalling_tasks = task->next;
2111 task->next->prev = task->prev;
2113 task->next = task->prev = NULL;
2116 /* ---------------------------------------------------------------------------
2117 * Suspending & resuming Haskell threads.
2119 * When making a "safe" call to C (aka _ccall_GC), the task gives back
2120 * its capability before calling the C function. This allows another
2121 * task to pick up the capability and carry on running Haskell
2122 * threads. It also means that if the C call blocks, it won't lock
2125 * The Haskell thread making the C call is put to sleep for the
2126 * duration of the call, on the susepended_ccalling_threads queue. We
2127 * give out a token to the task, which it can use to resume the thread
2128 * on return from the C function.
2129 * ------------------------------------------------------------------------- */
2132 suspendThread (StgRegTable *reg)
2135 int saved_errno = errno;
2139 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
2141 cap = regTableToCapability(reg);
2143 task = cap->running_task;
2144 tso = cap->r.rCurrentTSO;
2147 sched_belch("thread %d did a safe foreign call", cap->r.rCurrentTSO->id));
2149 // XXX this might not be necessary --SDM
2150 tso->what_next = ThreadRunGHC;
2154 if(tso->blocked_exceptions == NULL) {
2155 tso->why_blocked = BlockedOnCCall;
2156 tso->blocked_exceptions = END_TSO_QUEUE;
2158 tso->why_blocked = BlockedOnCCall_NoUnblockExc;
2161 // Hand back capability
2162 task->suspended_tso = tso;
2164 ACQUIRE_LOCK(&cap->lock);
2166 suspendTask(cap,task);
2167 cap->in_haskell = rtsFalse;
2168 releaseCapability_(cap);
2170 RELEASE_LOCK(&cap->lock);
2172 #if defined(THREADED_RTS)
2173 /* Preparing to leave the RTS, so ensure there's a native thread/task
2174 waiting to take over.
2176 IF_DEBUG(scheduler, sched_belch("thread %d: leaving RTS", tso->id));
2179 errno = saved_errno;
2184 resumeThread (void *task_)
2188 int saved_errno = errno;
2192 // Wait for permission to re-enter the RTS with the result.
2193 waitForReturnCapability(&cap,task);
2194 // we might be on a different capability now... but if so, our
2195 // entry on the suspended_ccalling_tasks list will also have been
2198 // Remove the thread from the suspended list
2199 recoverSuspendedTask(cap,task);
2201 tso = task->suspended_tso;
2202 task->suspended_tso = NULL;
2203 tso->link = END_TSO_QUEUE;
2204 IF_DEBUG(scheduler, sched_belch("thread %d: re-entering RTS", tso->id));
2206 if (tso->why_blocked == BlockedOnCCall) {
2207 awakenBlockedQueue(cap,tso->blocked_exceptions);
2208 tso->blocked_exceptions = NULL;
2211 /* Reset blocking status */
2212 tso->why_blocked = NotBlocked;
2214 cap->r.rCurrentTSO = tso;
2215 cap->in_haskell = rtsTrue;
2216 errno = saved_errno;
2221 /* ---------------------------------------------------------------------------
2222 * Comparing Thread ids.
2224 * This is used from STG land in the implementation of the
2225 * instances of Eq/Ord for ThreadIds.
2226 * ------------------------------------------------------------------------ */
2229 cmp_thread(StgPtr tso1, StgPtr tso2)
2231 StgThreadID id1 = ((StgTSO *)tso1)->id;
2232 StgThreadID id2 = ((StgTSO *)tso2)->id;
2234 if (id1 < id2) return (-1);
2235 if (id1 > id2) return 1;
2239 /* ---------------------------------------------------------------------------
2240 * Fetching the ThreadID from an StgTSO.
2242 * This is used in the implementation of Show for ThreadIds.
2243 * ------------------------------------------------------------------------ */
2245 rts_getThreadId(StgPtr tso)
2247 return ((StgTSO *)tso)->id;
2252 labelThread(StgPtr tso, char *label)
2257 /* Caveat: Once set, you can only set the thread name to "" */
2258 len = strlen(label)+1;
2259 buf = stgMallocBytes(len * sizeof(char), "Schedule.c:labelThread()");
2260 strncpy(buf,label,len);
2261 /* Update will free the old memory for us */
2262 updateThreadLabel(((StgTSO *)tso)->id,buf);
2266 /* ---------------------------------------------------------------------------
2267 Create a new thread.
2269 The new thread starts with the given stack size. Before the
2270 scheduler can run, however, this thread needs to have a closure
2271 (and possibly some arguments) pushed on its stack. See
2272 pushClosure() in Schedule.h.
2274 createGenThread() and createIOThread() (in SchedAPI.h) are
2275 convenient packaged versions of this function.
2277 currently pri (priority) is only used in a GRAN setup -- HWL
2278 ------------------------------------------------------------------------ */
2280 /* currently pri (priority) is only used in a GRAN setup -- HWL */
2282 createThread(nat size, StgInt pri)
2285 createThread(Capability *cap, nat size)
2291 /* sched_mutex is *not* required */
2293 /* First check whether we should create a thread at all */
2294 #if defined(PARALLEL_HASKELL)
2295 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
2296 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
2298 debugBelch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)\n",
2299 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
2300 return END_TSO_QUEUE;
2306 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
2309 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
2311 /* catch ridiculously small stack sizes */
2312 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
2313 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
2316 stack_size = size - TSO_STRUCT_SIZEW;
2318 tso = (StgTSO *)allocateLocal(cap, size);
2319 TICK_ALLOC_TSO(stack_size, 0);
2321 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
2323 SET_GRAN_HDR(tso, ThisPE);
2326 // Always start with the compiled code evaluator
2327 tso->what_next = ThreadRunGHC;
2329 tso->why_blocked = NotBlocked;
2330 tso->blocked_exceptions = NULL;
2332 tso->saved_errno = 0;
2335 tso->stack_size = stack_size;
2336 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
2338 tso->sp = (P_)&(tso->stack) + stack_size;
2340 tso->trec = NO_TREC;
2343 tso->prof.CCCS = CCS_MAIN;
2346 /* put a stop frame on the stack */
2347 tso->sp -= sizeofW(StgStopFrame);
2348 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
2349 tso->link = END_TSO_QUEUE;
2353 /* uses more flexible routine in GranSim */
2354 insertThread(tso, CurrentProc);
2356 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
2362 if (RtsFlags.GranFlags.GranSimStats.Full)
2363 DumpGranEvent(GR_START,tso);
2364 #elif defined(PARALLEL_HASKELL)
2365 if (RtsFlags.ParFlags.ParStats.Full)
2366 DumpGranEvent(GR_STARTQ,tso);
2367 /* HACk to avoid SCHEDULE
2371 /* Link the new thread on the global thread list.
2373 ACQUIRE_LOCK(&sched_mutex);
2374 tso->id = next_thread_id++; // while we have the mutex
2375 tso->global_link = all_threads;
2377 RELEASE_LOCK(&sched_mutex);
2380 tso->dist.priority = MandatoryPriority; //by default that is...
2384 tso->gran.pri = pri;
2386 tso->gran.magic = TSO_MAGIC; // debugging only
2388 tso->gran.sparkname = 0;
2389 tso->gran.startedat = CURRENT_TIME;
2390 tso->gran.exported = 0;
2391 tso->gran.basicblocks = 0;
2392 tso->gran.allocs = 0;
2393 tso->gran.exectime = 0;
2394 tso->gran.fetchtime = 0;
2395 tso->gran.fetchcount = 0;
2396 tso->gran.blocktime = 0;
2397 tso->gran.blockcount = 0;
2398 tso->gran.blockedat = 0;
2399 tso->gran.globalsparks = 0;
2400 tso->gran.localsparks = 0;
2401 if (RtsFlags.GranFlags.Light)
2402 tso->gran.clock = Now; /* local clock */
2404 tso->gran.clock = 0;
2406 IF_DEBUG(gran,printTSO(tso));
2407 #elif defined(PARALLEL_HASKELL)
2409 tso->par.magic = TSO_MAGIC; // debugging only
2411 tso->par.sparkname = 0;
2412 tso->par.startedat = CURRENT_TIME;
2413 tso->par.exported = 0;
2414 tso->par.basicblocks = 0;
2415 tso->par.allocs = 0;
2416 tso->par.exectime = 0;
2417 tso->par.fetchtime = 0;
2418 tso->par.fetchcount = 0;
2419 tso->par.blocktime = 0;
2420 tso->par.blockcount = 0;
2421 tso->par.blockedat = 0;
2422 tso->par.globalsparks = 0;
2423 tso->par.localsparks = 0;
2427 globalGranStats.tot_threads_created++;
2428 globalGranStats.threads_created_on_PE[CurrentProc]++;
2429 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
2430 globalGranStats.tot_sq_probes++;
2431 #elif defined(PARALLEL_HASKELL)
2432 // collect parallel global statistics (currently done together with GC stats)
2433 if (RtsFlags.ParFlags.ParStats.Global &&
2434 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
2435 //debugBelch("Creating thread %d @ %11.2f\n", tso->id, usertime());
2436 globalParStats.tot_threads_created++;
2442 sched_belch("==__ schedule: Created TSO %d (%p);",
2443 CurrentProc, tso, tso->id));
2444 #elif defined(PARALLEL_HASKELL)
2445 IF_PAR_DEBUG(verbose,
2446 sched_belch("==__ schedule: Created TSO %d (%p); %d threads active",
2447 (long)tso->id, tso, advisory_thread_count));
2449 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
2450 (long)tso->id, (long)tso->stack_size));
2457 all parallel thread creation calls should fall through the following routine.
2460 createThreadFromSpark(rtsSpark spark)
2462 ASSERT(spark != (rtsSpark)NULL);
2463 // JB: TAKE CARE OF THIS COUNTER! BUGGY
2464 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
2466 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
2467 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
2468 return END_TSO_QUEUE;
2472 tso = createThread(RtsFlags.GcFlags.initialStkSize);
2473 if (tso==END_TSO_QUEUE)
2474 barf("createSparkThread: Cannot create TSO");
2476 tso->priority = AdvisoryPriority;
2478 pushClosure(tso,spark);
2480 advisory_thread_count++; // JB: TAKE CARE OF THIS COUNTER! BUGGY
2487 Turn a spark into a thread.
2488 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
2492 activateSpark (rtsSpark spark)
2496 tso = createSparkThread(spark);
2497 if (RtsFlags.ParFlags.ParStats.Full) {
2498 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
2499 IF_PAR_DEBUG(verbose,
2500 debugBelch("==^^ activateSpark: turning spark of closure %p (%s) into a thread\n",
2501 (StgClosure *)spark, info_type((StgClosure *)spark)));
2503 // ToDo: fwd info on local/global spark to thread -- HWL
2504 // tso->gran.exported = spark->exported;
2505 // tso->gran.locked = !spark->global;
2506 // tso->gran.sparkname = spark->name;
2512 /* ---------------------------------------------------------------------------
2515 * scheduleThread puts a thread on the end of the runnable queue.
2516 * This will usually be done immediately after a thread is created.
2517 * The caller of scheduleThread must create the thread using e.g.
2518 * createThread and push an appropriate closure
2519 * on this thread's stack before the scheduler is invoked.
2520 * ------------------------------------------------------------------------ */
2523 scheduleThread(Capability *cap, StgTSO *tso)
2525 // The thread goes at the *end* of the run-queue, to avoid possible
2526 // starvation of any threads already on the queue.
2527 appendToRunQueue(cap,tso);
2531 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *cap)
2535 // We already created/initialised the Task
2536 task = cap->running_task;
2538 // This TSO is now a bound thread; make the Task and TSO
2539 // point to each other.
2544 task->stat = NoStatus;
2546 appendToRunQueue(cap,tso);
2548 IF_DEBUG(scheduler, sched_belch("new bound thread (%d)", tso->id));
2551 /* GranSim specific init */
2552 CurrentTSO = m->tso; // the TSO to run
2553 procStatus[MainProc] = Busy; // status of main PE
2554 CurrentProc = MainProc; // PE to run it on
2557 cap = schedule(cap,task);
2559 ASSERT(task->stat != NoStatus);
2560 ASSERT_CAPABILITY_INVARIANTS(cap,task);
2562 IF_DEBUG(scheduler, sched_belch("bound thread (%d) finished", task->tso->id));
2566 /* ----------------------------------------------------------------------------
2568 * ------------------------------------------------------------------------- */
2570 #if defined(THREADED_RTS)
2572 workerStart(Task *task)
2576 // See startWorkerTask().
2577 ACQUIRE_LOCK(&task->lock);
2579 RELEASE_LOCK(&task->lock);
2581 // set the thread-local pointer to the Task:
2584 // schedule() runs without a lock.
2585 cap = schedule(cap,task);
2587 // On exit from schedule(), we have a Capability.
2588 releaseCapability(cap);
2593 /* ---------------------------------------------------------------------------
2596 * Initialise the scheduler. This resets all the queues - if the
2597 * queues contained any threads, they'll be garbage collected at the
2600 * ------------------------------------------------------------------------ */
2607 for (i=0; i<=MAX_PROC; i++) {
2608 run_queue_hds[i] = END_TSO_QUEUE;
2609 run_queue_tls[i] = END_TSO_QUEUE;
2610 blocked_queue_hds[i] = END_TSO_QUEUE;
2611 blocked_queue_tls[i] = END_TSO_QUEUE;
2612 ccalling_threadss[i] = END_TSO_QUEUE;
2613 blackhole_queue[i] = END_TSO_QUEUE;
2614 sleeping_queue = END_TSO_QUEUE;
2616 #elif !defined(THREADED_RTS)
2617 blocked_queue_hd = END_TSO_QUEUE;
2618 blocked_queue_tl = END_TSO_QUEUE;
2619 sleeping_queue = END_TSO_QUEUE;
2622 blackhole_queue = END_TSO_QUEUE;
2623 all_threads = END_TSO_QUEUE;
2628 RtsFlags.ConcFlags.ctxtSwitchTicks =
2629 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
2631 #if defined(THREADED_RTS)
2632 /* Initialise the mutex and condition variables used by
2634 initMutex(&sched_mutex);
2637 ACQUIRE_LOCK(&sched_mutex);
2639 /* A capability holds the state a native thread needs in
2640 * order to execute STG code. At least one capability is
2641 * floating around (only SMP builds have more than one).
2649 * Eagerly start one worker to run each Capability, except for
2650 * Capability 0. The idea is that we're probably going to start a
2651 * bound thread on Capability 0 pretty soon, so we don't want a
2652 * worker task hogging it.
2657 for (i = 1; i < n_capabilities; i++) {
2658 cap = &capabilities[i];
2659 ACQUIRE_LOCK(&cap->lock);
2660 startWorkerTask(cap, workerStart);
2661 RELEASE_LOCK(&cap->lock);
2666 #if /* defined(SMP) ||*/ defined(PARALLEL_HASKELL)
2670 RELEASE_LOCK(&sched_mutex);
2674 exitScheduler( void )
2676 interrupted = rtsTrue;
2677 shutting_down_scheduler = rtsTrue;
2679 #if defined(THREADED_RTS)
2684 ACQUIRE_LOCK(&sched_mutex);
2685 task = newBoundTask();
2686 RELEASE_LOCK(&sched_mutex);
2688 for (i = 0; i < n_capabilities; i++) {
2689 shutdownCapability(&capabilities[i], task);
2691 boundTaskExiting(task);
2697 /* ---------------------------------------------------------------------------
2698 Where are the roots that we know about?
2700 - all the threads on the runnable queue
2701 - all the threads on the blocked queue
2702 - all the threads on the sleeping queue
2703 - all the thread currently executing a _ccall_GC
2704 - all the "main threads"
2706 ------------------------------------------------------------------------ */
2708 /* This has to be protected either by the scheduler monitor, or by the
2709 garbage collection monitor (probably the latter).
2714 GetRoots( evac_fn evac )
2721 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2722 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2723 evac((StgClosure **)&run_queue_hds[i]);
2724 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2725 evac((StgClosure **)&run_queue_tls[i]);
2727 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2728 evac((StgClosure **)&blocked_queue_hds[i]);
2729 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2730 evac((StgClosure **)&blocked_queue_tls[i]);
2731 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2732 evac((StgClosure **)&ccalling_threads[i]);
2739 for (i = 0; i < n_capabilities; i++) {
2740 cap = &capabilities[i];
2741 evac((StgClosure **)&cap->run_queue_hd);
2742 evac((StgClosure **)&cap->run_queue_tl);
2744 for (task = cap->suspended_ccalling_tasks; task != NULL;
2746 evac((StgClosure **)&task->suspended_tso);
2750 #if !defined(THREADED_RTS)
2751 evac((StgClosure **)&blocked_queue_hd);
2752 evac((StgClosure **)&blocked_queue_tl);
2753 evac((StgClosure **)&sleeping_queue);
2757 evac((StgClosure **)&blackhole_queue);
2759 #if defined(PARALLEL_HASKELL) || defined(GRAN)
2760 markSparkQueue(evac);
2763 #if defined(RTS_USER_SIGNALS)
2764 // mark the signal handlers (signals should be already blocked)
2765 markSignalHandlers(evac);
2769 /* -----------------------------------------------------------------------------
2772 This is the interface to the garbage collector from Haskell land.
2773 We provide this so that external C code can allocate and garbage
2774 collect when called from Haskell via _ccall_GC.
2776 It might be useful to provide an interface whereby the programmer
2777 can specify more roots (ToDo).
2779 This needs to be protected by the GC condition variable above. KH.
2780 -------------------------------------------------------------------------- */
2782 static void (*extra_roots)(evac_fn);
2788 // ToDo: we have to grab all the capabilities here.
2789 errorBelch("performGC not supported in threaded RTS (yet)");
2790 stg_exit(EXIT_FAILURE);
2792 /* Obligated to hold this lock upon entry */
2793 GarbageCollect(GetRoots,rtsFalse);
2797 performMajorGC(void)
2800 errorBelch("performMayjorGC not supported in threaded RTS (yet)");
2801 stg_exit(EXIT_FAILURE);
2803 GarbageCollect(GetRoots,rtsTrue);
2807 AllRoots(evac_fn evac)
2809 GetRoots(evac); // the scheduler's roots
2810 extra_roots(evac); // the user's roots
2814 performGCWithRoots(void (*get_roots)(evac_fn))
2817 errorBelch("performGCWithRoots not supported in threaded RTS (yet)");
2818 stg_exit(EXIT_FAILURE);
2820 extra_roots = get_roots;
2821 GarbageCollect(AllRoots,rtsFalse);
2824 /* -----------------------------------------------------------------------------
2827 If the thread has reached its maximum stack size, then raise the
2828 StackOverflow exception in the offending thread. Otherwise
2829 relocate the TSO into a larger chunk of memory and adjust its stack
2831 -------------------------------------------------------------------------- */
2834 threadStackOverflow(Capability *cap, StgTSO *tso)
2836 nat new_stack_size, stack_words;
2841 IF_DEBUG(sanity,checkTSO(tso));
2842 if (tso->stack_size >= tso->max_stack_size) {
2845 debugBelch("@@ threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)\n",
2846 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2847 /* If we're debugging, just print out the top of the stack */
2848 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2851 /* Send this thread the StackOverflow exception */
2852 raiseAsync(cap, tso, (StgClosure *)stackOverflow_closure);
2856 /* Try to double the current stack size. If that takes us over the
2857 * maximum stack size for this thread, then use the maximum instead.
2858 * Finally round up so the TSO ends up as a whole number of blocks.
2860 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2861 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2862 TSO_STRUCT_SIZE)/sizeof(W_);
2863 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2864 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2866 IF_DEBUG(scheduler, sched_belch("increasing stack size from %ld words to %d.\n", tso->stack_size, new_stack_size));
2868 dest = (StgTSO *)allocate(new_tso_size);
2869 TICK_ALLOC_TSO(new_stack_size,0);
2871 /* copy the TSO block and the old stack into the new area */
2872 memcpy(dest,tso,TSO_STRUCT_SIZE);
2873 stack_words = tso->stack + tso->stack_size - tso->sp;
2874 new_sp = (P_)dest + new_tso_size - stack_words;
2875 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2877 /* relocate the stack pointers... */
2879 dest->stack_size = new_stack_size;
2881 /* Mark the old TSO as relocated. We have to check for relocated
2882 * TSOs in the garbage collector and any primops that deal with TSOs.
2884 * It's important to set the sp value to just beyond the end
2885 * of the stack, so we don't attempt to scavenge any part of the
2888 tso->what_next = ThreadRelocated;
2890 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2891 tso->why_blocked = NotBlocked;
2893 IF_PAR_DEBUG(verbose,
2894 debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2895 tso->id, tso, tso->stack_size);
2896 /* If we're debugging, just print out the top of the stack */
2897 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2900 IF_DEBUG(sanity,checkTSO(tso));
2902 IF_DEBUG(scheduler,printTSO(dest));
2908 /* ---------------------------------------------------------------------------
2909 Wake up a queue that was blocked on some resource.
2910 ------------------------------------------------------------------------ */
2914 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2917 #elif defined(PARALLEL_HASKELL)
2919 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2921 /* write RESUME events to log file and
2922 update blocked and fetch time (depending on type of the orig closure) */
2923 if (RtsFlags.ParFlags.ParStats.Full) {
2924 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2925 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2926 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2927 if (emptyRunQueue())
2928 emitSchedule = rtsTrue;
2930 switch (get_itbl(node)->type) {
2932 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2937 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2944 barf("{unblockOne}Daq Qagh: unexpected closure in blocking queue");
2951 StgBlockingQueueElement *
2952 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2955 PEs node_loc, tso_loc;
2957 node_loc = where_is(node); // should be lifted out of loop
2958 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2959 tso_loc = where_is((StgClosure *)tso);
2960 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2961 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2962 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2963 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2964 // insertThread(tso, node_loc);
2965 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2967 tso, node, (rtsSpark*)NULL);
2968 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2971 } else { // TSO is remote (actually should be FMBQ)
2972 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2973 RtsFlags.GranFlags.Costs.gunblocktime +
2974 RtsFlags.GranFlags.Costs.latency;
2975 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2977 tso, node, (rtsSpark*)NULL);
2978 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2981 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2983 debugBelch(" %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2984 (node_loc==tso_loc ? "Local" : "Global"),
2985 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2986 tso->block_info.closure = NULL;
2987 IF_DEBUG(scheduler,debugBelch("-- Waking up thread %ld (%p)\n",
2990 #elif defined(PARALLEL_HASKELL)
2991 StgBlockingQueueElement *
2992 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2994 StgBlockingQueueElement *next;
2996 switch (get_itbl(bqe)->type) {
2998 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2999 /* if it's a TSO just push it onto the run_queue */
3001 ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
3002 APPEND_TO_RUN_QUEUE((StgTSO *)bqe);
3004 unblockCount(bqe, node);
3005 /* reset blocking status after dumping event */
3006 ((StgTSO *)bqe)->why_blocked = NotBlocked;
3010 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
3012 bqe->link = (StgBlockingQueueElement *)PendingFetches;
3013 PendingFetches = (StgBlockedFetch *)bqe;
3017 /* can ignore this case in a non-debugging setup;
3018 see comments on RBHSave closures above */
3020 /* check that the closure is an RBHSave closure */
3021 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
3022 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
3023 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
3027 barf("{unblockOne}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
3028 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
3032 IF_PAR_DEBUG(bq, debugBelch(", %p (%s)\n", bqe, info_type((StgClosure*)bqe)));
3038 unblockOne(Capability *cap, StgTSO *tso)
3042 ASSERT(get_itbl(tso)->type == TSO);
3043 ASSERT(tso->why_blocked != NotBlocked);
3044 tso->why_blocked = NotBlocked;
3046 tso->link = END_TSO_QUEUE;
3048 // We might have just migrated this TSO to our Capability:
3050 tso->bound->cap = cap;
3053 appendToRunQueue(cap,tso);
3055 // we're holding a newly woken thread, make sure we context switch
3056 // quickly so we can migrate it if necessary.
3058 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", (long)tso->id));
3065 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
3067 StgBlockingQueueElement *bqe;
3072 debugBelch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): \n", \
3073 node, CurrentProc, CurrentTime[CurrentProc],
3074 CurrentTSO->id, CurrentTSO));
3076 node_loc = where_is(node);
3078 ASSERT(q == END_BQ_QUEUE ||
3079 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
3080 get_itbl(q)->type == CONSTR); // closure (type constructor)
3081 ASSERT(is_unique(node));
3083 /* FAKE FETCH: magically copy the node to the tso's proc;
3084 no Fetch necessary because in reality the node should not have been
3085 moved to the other PE in the first place
3087 if (CurrentProc!=node_loc) {
3089 debugBelch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)\n",
3090 node, node_loc, CurrentProc, CurrentTSO->id,
3091 // CurrentTSO, where_is(CurrentTSO),
3092 node->header.gran.procs));
3093 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
3095 debugBelch("## new bitmask of node %p is %#x\n",
3096 node, node->header.gran.procs));
3097 if (RtsFlags.GranFlags.GranSimStats.Global) {
3098 globalGranStats.tot_fake_fetches++;
3103 // ToDo: check: ASSERT(CurrentProc==node_loc);
3104 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
3107 bqe points to the current element in the queue
3108 next points to the next element in the queue
3110 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
3111 //tso_loc = where_is(tso);
3113 bqe = unblockOne(bqe, node);
3116 /* if this is the BQ of an RBH, we have to put back the info ripped out of
3117 the closure to make room for the anchor of the BQ */
3118 if (bqe!=END_BQ_QUEUE) {
3119 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
3121 ASSERT((info_ptr==&RBH_Save_0_info) ||
3122 (info_ptr==&RBH_Save_1_info) ||
3123 (info_ptr==&RBH_Save_2_info));
3125 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
3126 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
3127 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
3130 debugBelch("## Filled in RBH_Save for %p (%s) at end of AwBQ\n",
3131 node, info_type(node)));
3134 /* statistics gathering */
3135 if (RtsFlags.GranFlags.GranSimStats.Global) {
3136 // globalGranStats.tot_bq_processing_time += bq_processing_time;
3137 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
3138 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
3139 globalGranStats.tot_awbq++; // total no. of bqs awakened
3142 debugBelch("## BQ Stats of %p: [%d entries] %s\n",
3143 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
3145 #elif defined(PARALLEL_HASKELL)
3147 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
3149 StgBlockingQueueElement *bqe;
3151 IF_PAR_DEBUG(verbose,
3152 debugBelch("##-_ AwBQ for node %p on [%x]: \n",
3156 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
3157 IF_PAR_DEBUG(verbose, debugBelch("## ... nothing to unblock so lets just return. RFP (BUG?)\n"));
3162 ASSERT(q == END_BQ_QUEUE ||
3163 get_itbl(q)->type == TSO ||
3164 get_itbl(q)->type == BLOCKED_FETCH ||
3165 get_itbl(q)->type == CONSTR);
3168 while (get_itbl(bqe)->type==TSO ||
3169 get_itbl(bqe)->type==BLOCKED_FETCH) {
3170 bqe = unblockOne(bqe, node);
3174 #else /* !GRAN && !PARALLEL_HASKELL */
3177 awakenBlockedQueue(Capability *cap, StgTSO *tso)
3179 if (tso == NULL) return; // hack; see bug #1235728, and comments in
3181 while (tso != END_TSO_QUEUE) {
3182 tso = unblockOne(cap,tso);
3187 /* ---------------------------------------------------------------------------
3189 - usually called inside a signal handler so it mustn't do anything fancy.
3190 ------------------------------------------------------------------------ */
3193 interruptStgRts(void)
3197 #if defined(THREADED_RTS)
3198 prodAllCapabilities();
3202 /* -----------------------------------------------------------------------------
3205 This is for use when we raise an exception in another thread, which
3207 This has nothing to do with the UnblockThread event in GranSim. -- HWL
3208 -------------------------------------------------------------------------- */
3210 #if defined(GRAN) || defined(PARALLEL_HASKELL)
3212 NB: only the type of the blocking queue is different in GranSim and GUM
3213 the operations on the queue-elements are the same
3214 long live polymorphism!
3216 Locks: sched_mutex is held upon entry and exit.
3220 unblockThread(Capability *cap, StgTSO *tso)
3222 StgBlockingQueueElement *t, **last;
3224 switch (tso->why_blocked) {
3227 return; /* not blocked */
3230 // Be careful: nothing to do here! We tell the scheduler that the thread
3231 // is runnable and we leave it to the stack-walking code to abort the
3232 // transaction while unwinding the stack. We should perhaps have a debugging
3233 // test to make sure that this really happens and that the 'zombie' transaction
3234 // does not get committed.
3238 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3240 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
3241 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3243 last = (StgBlockingQueueElement **)&mvar->head;
3244 for (t = (StgBlockingQueueElement *)mvar->head;
3246 last = &t->link, last_tso = t, t = t->link) {
3247 if (t == (StgBlockingQueueElement *)tso) {
3248 *last = (StgBlockingQueueElement *)tso->link;
3249 if (mvar->tail == tso) {
3250 mvar->tail = (StgTSO *)last_tso;
3255 barf("unblockThread (MVAR): TSO not found");
3258 case BlockedOnBlackHole:
3259 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3261 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3263 last = &bq->blocking_queue;
3264 for (t = bq->blocking_queue;
3266 last = &t->link, t = t->link) {
3267 if (t == (StgBlockingQueueElement *)tso) {
3268 *last = (StgBlockingQueueElement *)tso->link;
3272 barf("unblockThread (BLACKHOLE): TSO not found");
3275 case BlockedOnException:
3277 StgTSO *target = tso->block_info.tso;
3279 ASSERT(get_itbl(target)->type == TSO);
3281 if (target->what_next == ThreadRelocated) {
3282 target = target->link;
3283 ASSERT(get_itbl(target)->type == TSO);
3286 ASSERT(target->blocked_exceptions != NULL);
3288 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
3289 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
3291 last = &t->link, t = t->link) {
3292 ASSERT(get_itbl(t)->type == TSO);
3293 if (t == (StgBlockingQueueElement *)tso) {
3294 *last = (StgBlockingQueueElement *)tso->link;
3298 barf("unblockThread (Exception): TSO not found");
3302 case BlockedOnWrite:
3303 #if defined(mingw32_HOST_OS)
3304 case BlockedOnDoProc:
3307 /* take TSO off blocked_queue */
3308 StgBlockingQueueElement *prev = NULL;
3309 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
3310 prev = t, t = t->link) {
3311 if (t == (StgBlockingQueueElement *)tso) {
3313 blocked_queue_hd = (StgTSO *)t->link;
3314 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3315 blocked_queue_tl = END_TSO_QUEUE;
3318 prev->link = t->link;
3319 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3320 blocked_queue_tl = (StgTSO *)prev;
3323 #if defined(mingw32_HOST_OS)
3324 /* (Cooperatively) signal that the worker thread should abort
3327 abandonWorkRequest(tso->block_info.async_result->reqID);
3332 barf("unblockThread (I/O): TSO not found");
3335 case BlockedOnDelay:
3337 /* take TSO off sleeping_queue */
3338 StgBlockingQueueElement *prev = NULL;
3339 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
3340 prev = t, t = t->link) {
3341 if (t == (StgBlockingQueueElement *)tso) {
3343 sleeping_queue = (StgTSO *)t->link;
3345 prev->link = t->link;
3350 barf("unblockThread (delay): TSO not found");
3354 barf("unblockThread");
3358 tso->link = END_TSO_QUEUE;
3359 tso->why_blocked = NotBlocked;
3360 tso->block_info.closure = NULL;
3361 pushOnRunQueue(cap,tso);
3365 unblockThread(Capability *cap, StgTSO *tso)
3369 /* To avoid locking unnecessarily. */
3370 if (tso->why_blocked == NotBlocked) {
3374 switch (tso->why_blocked) {
3377 // Be careful: nothing to do here! We tell the scheduler that the thread
3378 // is runnable and we leave it to the stack-walking code to abort the
3379 // transaction while unwinding the stack. We should perhaps have a debugging
3380 // test to make sure that this really happens and that the 'zombie' transaction
3381 // does not get committed.
3385 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3387 StgTSO *last_tso = END_TSO_QUEUE;
3388 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3391 for (t = mvar->head; t != END_TSO_QUEUE;
3392 last = &t->link, last_tso = t, t = t->link) {
3395 if (mvar->tail == tso) {
3396 mvar->tail = last_tso;
3401 barf("unblockThread (MVAR): TSO not found");
3404 case BlockedOnBlackHole:
3406 last = &blackhole_queue;
3407 for (t = blackhole_queue; t != END_TSO_QUEUE;
3408 last = &t->link, t = t->link) {
3414 barf("unblockThread (BLACKHOLE): TSO not found");
3417 case BlockedOnException:
3419 StgTSO *target = tso->block_info.tso;
3421 ASSERT(get_itbl(target)->type == TSO);
3423 while (target->what_next == ThreadRelocated) {
3424 target = target->link;
3425 ASSERT(get_itbl(target)->type == TSO);
3428 ASSERT(target->blocked_exceptions != NULL);
3430 last = &target->blocked_exceptions;
3431 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
3432 last = &t->link, t = t->link) {
3433 ASSERT(get_itbl(t)->type == TSO);
3439 barf("unblockThread (Exception): TSO not found");
3442 #if !defined(THREADED_RTS)
3444 case BlockedOnWrite:
3445 #if defined(mingw32_HOST_OS)
3446 case BlockedOnDoProc:
3449 StgTSO *prev = NULL;
3450 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
3451 prev = t, t = t->link) {
3454 blocked_queue_hd = t->link;
3455 if (blocked_queue_tl == t) {
3456 blocked_queue_tl = END_TSO_QUEUE;
3459 prev->link = t->link;
3460 if (blocked_queue_tl == t) {
3461 blocked_queue_tl = prev;
3464 #if defined(mingw32_HOST_OS)
3465 /* (Cooperatively) signal that the worker thread should abort
3468 abandonWorkRequest(tso->block_info.async_result->reqID);
3473 barf("unblockThread (I/O): TSO not found");
3476 case BlockedOnDelay:
3478 StgTSO *prev = NULL;
3479 for (t = sleeping_queue; t != END_TSO_QUEUE;
3480 prev = t, t = t->link) {
3483 sleeping_queue = t->link;
3485 prev->link = t->link;
3490 barf("unblockThread (delay): TSO not found");
3495 barf("unblockThread");
3499 tso->link = END_TSO_QUEUE;
3500 tso->why_blocked = NotBlocked;
3501 tso->block_info.closure = NULL;
3502 appendToRunQueue(cap,tso);
3506 /* -----------------------------------------------------------------------------
3509 * Check the blackhole_queue for threads that can be woken up. We do
3510 * this periodically: before every GC, and whenever the run queue is
3513 * An elegant solution might be to just wake up all the blocked
3514 * threads with awakenBlockedQueue occasionally: they'll go back to
3515 * sleep again if the object is still a BLACKHOLE. Unfortunately this
3516 * doesn't give us a way to tell whether we've actually managed to
3517 * wake up any threads, so we would be busy-waiting.
3519 * -------------------------------------------------------------------------- */
3522 checkBlackHoles (Capability *cap)
3525 rtsBool any_woke_up = rtsFalse;
3528 // blackhole_queue is global:
3529 ASSERT_LOCK_HELD(&sched_mutex);
3531 IF_DEBUG(scheduler, sched_belch("checking threads blocked on black holes"));
3533 // ASSUMES: sched_mutex
3534 prev = &blackhole_queue;
3535 t = blackhole_queue;
3536 while (t != END_TSO_QUEUE) {
3537 ASSERT(t->why_blocked == BlockedOnBlackHole);
3538 type = get_itbl(t->block_info.closure)->type;
3539 if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
3540 IF_DEBUG(sanity,checkTSO(t));
3541 t = unblockOne(cap, t);
3542 // urk, the threads migrate to the current capability
3543 // here, but we'd like to keep them on the original one.
3545 any_woke_up = rtsTrue;
3555 /* -----------------------------------------------------------------------------
3558 * The following function implements the magic for raising an
3559 * asynchronous exception in an existing thread.
3561 * We first remove the thread from any queue on which it might be
3562 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
3564 * We strip the stack down to the innermost CATCH_FRAME, building
3565 * thunks in the heap for all the active computations, so they can
3566 * be restarted if necessary. When we reach a CATCH_FRAME, we build
3567 * an application of the handler to the exception, and push it on
3568 * the top of the stack.
3570 * How exactly do we save all the active computations? We create an
3571 * AP_STACK for every UpdateFrame on the stack. Entering one of these
3572 * AP_STACKs pushes everything from the corresponding update frame
3573 * upwards onto the stack. (Actually, it pushes everything up to the
3574 * next update frame plus a pointer to the next AP_STACK object.
3575 * Entering the next AP_STACK object pushes more onto the stack until we
3576 * reach the last AP_STACK object - at which point the stack should look
3577 * exactly as it did when we killed the TSO and we can continue
3578 * execution by entering the closure on top of the stack.
3580 * We can also kill a thread entirely - this happens if either (a) the
3581 * exception passed to raiseAsync is NULL, or (b) there's no
3582 * CATCH_FRAME on the stack. In either case, we strip the entire
3583 * stack and replace the thread with a zombie.
3585 * ToDo: in SMP mode, this function is only safe if either (a) we hold
3586 * all the Capabilities (eg. in GC), or (b) we own the Capability that
3587 * the TSO is currently blocked on or on the run queue of.
3589 * -------------------------------------------------------------------------- */
3592 raiseAsync(Capability *cap, StgTSO *tso, StgClosure *exception)
3594 raiseAsync_(cap, tso, exception, rtsFalse);
3598 raiseAsync_(Capability *cap, StgTSO *tso, StgClosure *exception,
3599 rtsBool stop_at_atomically)
3601 StgRetInfoTable *info;
3604 // Thread already dead?
3605 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3610 sched_belch("raising exception in thread %ld.", (long)tso->id));
3612 // Remove it from any blocking queues
3613 unblockThread(cap,tso);
3617 // The stack freezing code assumes there's a closure pointer on
3618 // the top of the stack, so we have to arrange that this is the case...
3620 if (sp[0] == (W_)&stg_enter_info) {
3624 sp[0] = (W_)&stg_dummy_ret_closure;
3630 // 1. Let the top of the stack be the "current closure"
3632 // 2. Walk up the stack until we find either an UPDATE_FRAME or a
3635 // 3. If it's an UPDATE_FRAME, then make an AP_STACK containing the
3636 // current closure applied to the chunk of stack up to (but not
3637 // including) the update frame. This closure becomes the "current
3638 // closure". Go back to step 2.
3640 // 4. If it's a CATCH_FRAME, then leave the exception handler on
3641 // top of the stack applied to the exception.
3643 // 5. If it's a STOP_FRAME, then kill the thread.
3645 // NB: if we pass an ATOMICALLY_FRAME then abort the associated
3652 info = get_ret_itbl((StgClosure *)frame);
3654 while (info->i.type != UPDATE_FRAME
3655 && (info->i.type != CATCH_FRAME || exception == NULL)
3656 && info->i.type != STOP_FRAME
3657 && (info->i.type != ATOMICALLY_FRAME || stop_at_atomically == rtsFalse))
3659 if (info->i.type == CATCH_RETRY_FRAME || info->i.type == ATOMICALLY_FRAME) {
3660 // IF we find an ATOMICALLY_FRAME then we abort the
3661 // current transaction and propagate the exception. In
3662 // this case (unlike ordinary exceptions) we do not care
3663 // whether the transaction is valid or not because its
3664 // possible validity cannot have caused the exception
3665 // and will not be visible after the abort.
3667 debugBelch("Found atomically block delivering async exception\n"));
3668 stmAbortTransaction(tso -> trec);
3669 tso -> trec = stmGetEnclosingTRec(tso -> trec);
3671 frame += stack_frame_sizeW((StgClosure *)frame);
3672 info = get_ret_itbl((StgClosure *)frame);
3675 switch (info->i.type) {
3677 case ATOMICALLY_FRAME:
3678 ASSERT(stop_at_atomically);
3679 ASSERT(stmGetEnclosingTRec(tso->trec) == NO_TREC);
3680 stmCondemnTransaction(tso -> trec);
3684 // R1 is not a register: the return convention for IO in
3685 // this case puts the return value on the stack, so we
3686 // need to set up the stack to return to the atomically
3687 // frame properly...
3688 tso->sp = frame - 2;
3689 tso->sp[1] = (StgWord) &stg_NO_FINALIZER_closure; // why not?
3690 tso->sp[0] = (StgWord) &stg_ut_1_0_unreg_info;
3692 tso->what_next = ThreadRunGHC;
3696 // If we find a CATCH_FRAME, and we've got an exception to raise,
3697 // then build the THUNK raise(exception), and leave it on
3698 // top of the CATCH_FRAME ready to enter.
3702 StgCatchFrame *cf = (StgCatchFrame *)frame;
3706 // we've got an exception to raise, so let's pass it to the
3707 // handler in this frame.
3709 raise = (StgThunk *)allocateLocal(cap,sizeofW(StgThunk)+MIN_UPD_SIZE);
3710 TICK_ALLOC_SE_THK(1,0);
3711 SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
3712 raise->payload[0] = exception;
3714 // throw away the stack from Sp up to the CATCH_FRAME.
3718 /* Ensure that async excpetions are blocked now, so we don't get
3719 * a surprise exception before we get around to executing the
3722 if (tso->blocked_exceptions == NULL) {
3723 tso->blocked_exceptions = END_TSO_QUEUE;
3726 /* Put the newly-built THUNK on top of the stack, ready to execute
3727 * when the thread restarts.
3730 sp[-1] = (W_)&stg_enter_info;
3732 tso->what_next = ThreadRunGHC;
3733 IF_DEBUG(sanity, checkTSO(tso));
3742 // First build an AP_STACK consisting of the stack chunk above the
3743 // current update frame, with the top word on the stack as the
3746 words = frame - sp - 1;
3747 ap = (StgAP_STACK *)allocateLocal(cap,AP_STACK_sizeW(words));
3750 ap->fun = (StgClosure *)sp[0];
3752 for(i=0; i < (nat)words; ++i) {
3753 ap->payload[i] = (StgClosure *)*sp++;
3756 SET_HDR(ap,&stg_AP_STACK_info,
3757 ((StgClosure *)frame)->header.prof.ccs /* ToDo */);
3758 TICK_ALLOC_UP_THK(words+1,0);
3761 debugBelch("sched: Updating ");
3762 printPtr((P_)((StgUpdateFrame *)frame)->updatee);
3763 debugBelch(" with ");
3764 printObj((StgClosure *)ap);
3767 // Replace the updatee with an indirection - happily
3768 // this will also wake up any threads currently
3769 // waiting on the result.
3771 // Warning: if we're in a loop, more than one update frame on
3772 // the stack may point to the same object. Be careful not to
3773 // overwrite an IND_OLDGEN in this case, because we'll screw
3774 // up the mutable lists. To be on the safe side, don't
3775 // overwrite any kind of indirection at all. See also
3776 // threadSqueezeStack in GC.c, where we have to make a similar
3779 if (!closure_IND(((StgUpdateFrame *)frame)->updatee)) {
3780 // revert the black hole
3781 UPD_IND_NOLOCK(((StgUpdateFrame *)frame)->updatee,
3784 sp += sizeofW(StgUpdateFrame) - 1;
3785 sp[0] = (W_)ap; // push onto stack
3790 // We've stripped the entire stack, the thread is now dead.
3791 sp += sizeofW(StgStopFrame);
3792 tso->what_next = ThreadKilled;
3803 /* -----------------------------------------------------------------------------
3806 This is used for interruption (^C) and forking, and corresponds to
3807 raising an exception but without letting the thread catch the
3809 -------------------------------------------------------------------------- */
3812 deleteThread (Capability *cap, StgTSO *tso)
3814 if (tso->why_blocked != BlockedOnCCall &&
3815 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
3816 raiseAsync(cap,tso,NULL);
3820 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
3822 deleteThreadImmediately(Capability *cap, StgTSO *tso)
3823 { // for forkProcess only:
3824 // delete thread without giving it a chance to catch the KillThread exception
3826 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3830 if (tso->why_blocked != BlockedOnCCall &&
3831 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
3832 unblockThread(cap,tso);
3835 tso->what_next = ThreadKilled;
3839 /* -----------------------------------------------------------------------------
3840 raiseExceptionHelper
3842 This function is called by the raise# primitve, just so that we can
3843 move some of the tricky bits of raising an exception from C-- into
3844 C. Who knows, it might be a useful re-useable thing here too.
3845 -------------------------------------------------------------------------- */
3848 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
3850 Capability *cap = regTableToCapability(reg);
3851 StgThunk *raise_closure = NULL;
3853 StgRetInfoTable *info;
3855 // This closure represents the expression 'raise# E' where E
3856 // is the exception raise. It is used to overwrite all the
3857 // thunks which are currently under evaluataion.
3861 // LDV profiling: stg_raise_info has THUNK as its closure
3862 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
3863 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
3864 // 1 does not cause any problem unless profiling is performed.
3865 // However, when LDV profiling goes on, we need to linearly scan
3866 // small object pool, where raise_closure is stored, so we should
3867 // use MIN_UPD_SIZE.
3869 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
3870 // sizeofW(StgClosure)+1);
3874 // Walk up the stack, looking for the catch frame. On the way,
3875 // we update any closures pointed to from update frames with the
3876 // raise closure that we just built.
3880 info = get_ret_itbl((StgClosure *)p);
3881 next = p + stack_frame_sizeW((StgClosure *)p);
3882 switch (info->i.type) {
3885 // Only create raise_closure if we need to.
3886 if (raise_closure == NULL) {
3888 (StgThunk *)allocateLocal(cap,sizeofW(StgThunk)+MIN_UPD_SIZE);
3889 SET_HDR(raise_closure, &stg_raise_info, CCCS);
3890 raise_closure->payload[0] = exception;
3892 UPD_IND(((StgUpdateFrame *)p)->updatee,(StgClosure *)raise_closure);
3896 case ATOMICALLY_FRAME:
3897 IF_DEBUG(stm, debugBelch("Found ATOMICALLY_FRAME at %p\n", p));
3899 return ATOMICALLY_FRAME;
3905 case CATCH_STM_FRAME:
3906 IF_DEBUG(stm, debugBelch("Found CATCH_STM_FRAME at %p\n", p));
3908 return CATCH_STM_FRAME;
3914 case CATCH_RETRY_FRAME:
3923 /* -----------------------------------------------------------------------------
3924 findRetryFrameHelper
3926 This function is called by the retry# primitive. It traverses the stack
3927 leaving tso->sp referring to the frame which should handle the retry.
3929 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
3930 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
3932 We skip CATCH_STM_FRAMEs because retries are not considered to be exceptions,
3933 despite the similar implementation.
3935 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
3936 not be created within memory transactions.
3937 -------------------------------------------------------------------------- */
3940 findRetryFrameHelper (StgTSO *tso)
3943 StgRetInfoTable *info;
3947 info = get_ret_itbl((StgClosure *)p);
3948 next = p + stack_frame_sizeW((StgClosure *)p);
3949 switch (info->i.type) {
3951 case ATOMICALLY_FRAME:
3952 IF_DEBUG(stm, debugBelch("Found ATOMICALLY_FRAME at %p during retrry\n", p));
3954 return ATOMICALLY_FRAME;
3956 case CATCH_RETRY_FRAME:
3957 IF_DEBUG(stm, debugBelch("Found CATCH_RETRY_FRAME at %p during retrry\n", p));
3959 return CATCH_RETRY_FRAME;
3961 case CATCH_STM_FRAME:
3963 ASSERT(info->i.type != CATCH_FRAME);
3964 ASSERT(info->i.type != STOP_FRAME);
3971 /* -----------------------------------------------------------------------------
3972 resurrectThreads is called after garbage collection on the list of
3973 threads found to be garbage. Each of these threads will be woken
3974 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3975 on an MVar, or NonTermination if the thread was blocked on a Black
3978 Locks: assumes we hold *all* the capabilities.
3979 -------------------------------------------------------------------------- */
3982 resurrectThreads (StgTSO *threads)
3987 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3988 next = tso->global_link;
3989 tso->global_link = all_threads;
3991 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3993 // Wake up the thread on the Capability it was last on for a
3994 // bound thread, or last_free_capability otherwise.
3996 cap = tso->bound->cap;
3998 cap = last_free_capability;
4001 switch (tso->why_blocked) {
4003 case BlockedOnException:
4004 /* Called by GC - sched_mutex lock is currently held. */
4005 raiseAsync(cap, tso,(StgClosure *)BlockedOnDeadMVar_closure);
4007 case BlockedOnBlackHole:
4008 raiseAsync(cap, tso,(StgClosure *)NonTermination_closure);
4011 raiseAsync(cap, tso,(StgClosure *)BlockedIndefinitely_closure);
4014 /* This might happen if the thread was blocked on a black hole
4015 * belonging to a thread that we've just woken up (raiseAsync
4016 * can wake up threads, remember...).
4020 barf("resurrectThreads: thread blocked in a strange way");
4025 /* ----------------------------------------------------------------------------
4026 * Debugging: why is a thread blocked
4027 * [Also provides useful information when debugging threaded programs
4028 * at the Haskell source code level, so enable outside of DEBUG. --sof 7/02]
4029 ------------------------------------------------------------------------- */
4033 printThreadBlockage(StgTSO *tso)
4035 switch (tso->why_blocked) {
4037 debugBelch("is blocked on read from fd %d", (int)(tso->block_info.fd));
4039 case BlockedOnWrite:
4040 debugBelch("is blocked on write to fd %d", (int)(tso->block_info.fd));
4042 #if defined(mingw32_HOST_OS)
4043 case BlockedOnDoProc:
4044 debugBelch("is blocked on proc (request: %ld)", tso->block_info.async_result->reqID);
4047 case BlockedOnDelay:
4048 debugBelch("is blocked until %ld", (long)(tso->block_info.target));
4051 debugBelch("is blocked on an MVar @ %p", tso->block_info.closure);
4053 case BlockedOnException:
4054 debugBelch("is blocked on delivering an exception to thread %d",
4055 tso->block_info.tso->id);
4057 case BlockedOnBlackHole:
4058 debugBelch("is blocked on a black hole");
4061 debugBelch("is not blocked");
4063 #if defined(PARALLEL_HASKELL)
4065 debugBelch("is blocked on global address; local FM_BQ is %p (%s)",
4066 tso->block_info.closure, info_type(tso->block_info.closure));
4068 case BlockedOnGA_NoSend:
4069 debugBelch("is blocked on global address (no send); local FM_BQ is %p (%s)",
4070 tso->block_info.closure, info_type(tso->block_info.closure));
4073 case BlockedOnCCall:
4074 debugBelch("is blocked on an external call");
4076 case BlockedOnCCall_NoUnblockExc:
4077 debugBelch("is blocked on an external call (exceptions were already blocked)");
4080 debugBelch("is blocked on an STM operation");
4083 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
4084 tso->why_blocked, tso->id, tso);
4089 printThreadStatus(StgTSO *t)
4091 debugBelch("\tthread %4d @ %p ", t->id, (void *)t);
4093 void *label = lookupThreadLabel(t->id);
4094 if (label) debugBelch("[\"%s\"] ",(char *)label);
4096 if (t->what_next == ThreadRelocated) {
4097 debugBelch("has been relocated...\n");
4099 switch (t->what_next) {
4101 debugBelch("has been killed");
4103 case ThreadComplete:
4104 debugBelch("has completed");
4107 printThreadBlockage(t);
4114 printAllThreads(void)
4121 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
4122 ullong_format_string(TIME_ON_PROC(CurrentProc),
4123 time_string, rtsFalse/*no commas!*/);
4125 debugBelch("all threads at [%s]:\n", time_string);
4126 # elif defined(PARALLEL_HASKELL)
4127 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
4128 ullong_format_string(CURRENT_TIME,
4129 time_string, rtsFalse/*no commas!*/);
4131 debugBelch("all threads at [%s]:\n", time_string);
4133 debugBelch("all threads:\n");
4136 for (i = 0; i < n_capabilities; i++) {
4137 cap = &capabilities[i];
4138 debugBelch("threads on capability %d:\n", cap->no);
4139 for (t = cap->run_queue_hd; t != END_TSO_QUEUE; t = t->link) {
4140 printThreadStatus(t);
4144 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
4145 if (t->why_blocked != NotBlocked) {
4146 printThreadStatus(t);
4148 if (t->what_next == ThreadRelocated) {
4151 next = t->global_link;
4158 printThreadQueue(StgTSO *t)
4161 for (; t != END_TSO_QUEUE; t = t->link) {
4162 printThreadStatus(t);
4165 debugBelch("%d threads on queue\n", i);
4169 Print a whole blocking queue attached to node (debugging only).
4171 # if defined(PARALLEL_HASKELL)
4173 print_bq (StgClosure *node)
4175 StgBlockingQueueElement *bqe;
4179 debugBelch("## BQ of closure %p (%s): ",
4180 node, info_type(node));
4182 /* should cover all closures that may have a blocking queue */
4183 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
4184 get_itbl(node)->type == FETCH_ME_BQ ||
4185 get_itbl(node)->type == RBH ||
4186 get_itbl(node)->type == MVAR);
4188 ASSERT(node!=(StgClosure*)NULL); // sanity check
4190 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
4194 Print a whole blocking queue starting with the element bqe.
4197 print_bqe (StgBlockingQueueElement *bqe)
4202 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
4204 for (end = (bqe==END_BQ_QUEUE);
4205 !end; // iterate until bqe points to a CONSTR
4206 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
4207 bqe = end ? END_BQ_QUEUE : bqe->link) {
4208 ASSERT(bqe != END_BQ_QUEUE); // sanity check
4209 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
4210 /* types of closures that may appear in a blocking queue */
4211 ASSERT(get_itbl(bqe)->type == TSO ||
4212 get_itbl(bqe)->type == BLOCKED_FETCH ||
4213 get_itbl(bqe)->type == CONSTR);
4214 /* only BQs of an RBH end with an RBH_Save closure */
4215 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
4217 switch (get_itbl(bqe)->type) {
4219 debugBelch(" TSO %u (%x),",
4220 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
4223 debugBelch(" BF (node=%p, ga=((%x, %d, %x)),",
4224 ((StgBlockedFetch *)bqe)->node,
4225 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
4226 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
4227 ((StgBlockedFetch *)bqe)->ga.weight);
4230 debugBelch(" %s (IP %p),",
4231 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
4232 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
4233 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
4234 "RBH_Save_?"), get_itbl(bqe));
4237 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
4238 info_type((StgClosure *)bqe)); // , node, info_type(node));
4244 # elif defined(GRAN)
4246 print_bq (StgClosure *node)
4248 StgBlockingQueueElement *bqe;
4249 PEs node_loc, tso_loc;
4252 /* should cover all closures that may have a blocking queue */
4253 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
4254 get_itbl(node)->type == FETCH_ME_BQ ||
4255 get_itbl(node)->type == RBH);
4257 ASSERT(node!=(StgClosure*)NULL); // sanity check
4258 node_loc = where_is(node);
4260 debugBelch("## BQ of closure %p (%s) on [PE %d]: ",
4261 node, info_type(node), node_loc);
4264 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
4266 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
4267 !end; // iterate until bqe points to a CONSTR
4268 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
4269 ASSERT(bqe != END_BQ_QUEUE); // sanity check
4270 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
4271 /* types of closures that may appear in a blocking queue */
4272 ASSERT(get_itbl(bqe)->type == TSO ||
4273 get_itbl(bqe)->type == CONSTR);
4274 /* only BQs of an RBH end with an RBH_Save closure */
4275 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
4277 tso_loc = where_is((StgClosure *)bqe);
4278 switch (get_itbl(bqe)->type) {
4280 debugBelch(" TSO %d (%p) on [PE %d],",
4281 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
4284 debugBelch(" %s (IP %p),",
4285 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
4286 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
4287 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
4288 "RBH_Save_?"), get_itbl(bqe));
4291 barf("Unexpected closure type %s in blocking queue of %p (%s)",
4292 info_type((StgClosure *)bqe), node, info_type(node));
4300 #if defined(PARALLEL_HASKELL)
4307 for (i=0, tso=run_queue_hd;
4308 tso != END_TSO_QUEUE;
4309 i++, tso=tso->link) {
4318 sched_belch(char *s, ...)
4323 debugBelch("sched (task %p): ", (void *)(unsigned long)(unsigned int)osThreadId());
4324 #elif defined(PARALLEL_HASKELL)
4327 debugBelch("sched: ");