1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2004
7 * Different GHC ways use this scheduler quite differently (see comments below)
8 * Here is the global picture:
10 * WAY Name CPP flag What's it for
11 * --------------------------------------
12 * mp GUM PARALLEL_HASKELL Parallel execution on a distrib. memory machine
13 * s SMP SMP Parallel execution on a shared memory machine
14 * mg GranSim GRAN Simulation of parallel execution
15 * md GUM/GdH DIST Distributed execution (based on GUM)
17 * --------------------------------------------------------------------------*/
20 * Version with support for distributed memory parallelism aka GUM (WAY=mp):
22 The main scheduling loop in GUM iterates until a finish message is received.
23 In that case a global flag @receivedFinish@ is set and this instance of
24 the RTS shuts down. See ghc/rts/parallel/HLComms.c:processMessages()
25 for the handling of incoming messages, such as PP_FINISH.
26 Note that in the parallel case we have a system manager that coordinates
27 different PEs, each of which are running one instance of the RTS.
28 See ghc/rts/parallel/SysMan.c for the main routine of the parallel program.
29 From this routine processes executing ghc/rts/Main.c are spawned. -- HWL
31 * Version with support for simulating parallel execution aka GranSim (WAY=mg):
33 The main scheduling code in GranSim is quite different from that in std
34 (concurrent) Haskell: while concurrent Haskell just iterates over the
35 threads in the runnable queue, GranSim is event driven, i.e. it iterates
36 over the events in the global event queue. -- HWL
39 #include "PosixSource.h"
44 #include "BlockAlloc.h"
45 #include "OSThreads.h"
49 #define COMPILING_SCHEDULER
51 #include "StgMiscClosures.h"
52 #include "Interpreter.h"
53 #include "Exception.h"
61 #include "ThreadLabels.h"
62 #include "LdvProfile.h"
65 #include "Proftimer.h"
68 #if defined(GRAN) || defined(PARALLEL_HASKELL)
69 # include "GranSimRts.h"
71 # include "ParallelRts.h"
72 # include "Parallel.h"
73 # include "ParallelDebug.h"
78 #include "Capability.h"
81 #ifdef HAVE_SYS_TYPES_H
82 #include <sys/types.h>
96 // Turn off inlining when debugging - it obfuscates things
99 # define STATIC_INLINE static
103 #define USED_IN_THREADED_RTS
105 #define USED_IN_THREADED_RTS STG_UNUSED
108 #ifdef RTS_SUPPORTS_THREADS
109 #define USED_WHEN_RTS_SUPPORTS_THREADS
111 #define USED_WHEN_RTS_SUPPORTS_THREADS STG_UNUSED
114 /* Main thread queue.
115 * Locks required: sched_mutex.
117 StgMainThread *main_threads = NULL;
121 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
122 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
125 In GranSim we have a runnable and a blocked queue for each processor.
126 In order to minimise code changes new arrays run_queue_hds/tls
127 are created. run_queue_hd is then a short cut (macro) for
128 run_queue_hds[CurrentProc] (see GranSim.h).
131 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
132 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
133 StgTSO *ccalling_threadss[MAX_PROC];
134 /* We use the same global list of threads (all_threads) in GranSim as in
135 the std RTS (i.e. we are cheating). However, we don't use this list in
136 the GranSim specific code at the moment (so we are only potentially
142 * Locks required: sched_mutex.
144 StgTSO *run_queue_hd = NULL;
145 StgTSO *run_queue_tl = NULL;
146 StgTSO *blocked_queue_hd = NULL;
147 StgTSO *blocked_queue_tl = NULL;
148 StgTSO *sleeping_queue = NULL; /* perhaps replace with a hash table? */
152 /* Linked list of all threads.
153 * Used for detecting garbage collected threads.
155 StgTSO *all_threads = NULL;
157 /* When a thread performs a safe C call (_ccall_GC, using old
158 * terminology), it gets put on the suspended_ccalling_threads
159 * list. Used by the garbage collector.
161 static StgTSO *suspended_ccalling_threads;
163 /* KH: The following two flags are shared memory locations. There is no need
164 to lock them, since they are only unset at the end of a scheduler
168 /* flag set by signal handler to precipitate a context switch */
169 int context_switch = 0;
171 /* if this flag is set as well, give up execution */
172 rtsBool interrupted = rtsFalse;
174 /* If this flag is set, we are running Haskell code. Used to detect
175 * uses of 'foreign import unsafe' that should be 'safe'.
177 static rtsBool in_haskell = rtsFalse;
179 /* Next thread ID to allocate.
180 * Locks required: thread_id_mutex
182 static StgThreadID next_thread_id = 1;
185 * Pointers to the state of the current thread.
186 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
187 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
190 /* The smallest stack size that makes any sense is:
191 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
192 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
193 * + 1 (the closure to enter)
195 * + 1 (spare slot req'd by stg_ap_v_ret)
197 * A thread with this stack will bomb immediately with a stack
198 * overflow, which will increase its stack size.
201 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 3)
208 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
209 * exists - earlier gccs apparently didn't.
215 static Condition gc_pending_cond = INIT_COND_VAR;
218 static rtsBool ready_to_gc;
221 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
222 * in an MT setting, needed to signal that a worker thread shouldn't hang around
223 * in the scheduler when it is out of work.
225 static rtsBool shutting_down_scheduler = rtsFalse;
227 #if defined(RTS_SUPPORTS_THREADS)
228 /* ToDo: carefully document the invariants that go together
229 * with these synchronisation objects.
231 Mutex sched_mutex = INIT_MUTEX_VAR;
232 Mutex term_mutex = INIT_MUTEX_VAR;
234 #endif /* RTS_SUPPORTS_THREADS */
236 #if defined(PARALLEL_HASKELL)
238 rtsTime TimeOfLastYield;
239 rtsBool emitSchedule = rtsTrue;
243 static char *whatNext_strs[] = {
253 /* -----------------------------------------------------------------------------
254 * static function prototypes
255 * -------------------------------------------------------------------------- */
257 #if defined(RTS_SUPPORTS_THREADS)
258 static void taskStart(void);
261 static void schedule( StgMainThread *mainThread USED_WHEN_RTS_SUPPORTS_THREADS,
262 Capability *initialCapability );
265 // These function all encapsulate parts of the scheduler loop, and are
266 // abstracted only to make the structure and control flow of the
267 // scheduler clearer.
269 static void schedulePreLoop(void);
270 static void scheduleHandleInterrupt(void);
271 static void scheduleStartSignalHandlers(void);
272 static void scheduleCheckBlockedThreads(void);
273 static void scheduleDetectDeadlock(void);
275 static StgTSO *scheduleProcessEvent(rtsEvent *event);
277 #if defined(PARALLEL_HASKELL)
278 static StgTSO *scheduleSendPendingMessages(void);
279 static void scheduleActivateSpark(void);
280 static rtsBool scheduleGetRemoteWork(rtsBool *receivedFinish);
282 #if defined(PAR) || defined(GRAN)
283 static void scheduleGranParReport(void);
285 static void schedulePostRunThread(void);
286 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
287 static void scheduleHandleStackOverflow( StgTSO *t);
288 static rtsBool scheduleHandleYield( StgTSO *t, nat prev_what_next );
289 static void scheduleHandleThreadBlocked( StgTSO *t );
290 static rtsBool scheduleHandleThreadFinished( StgMainThread *mainThread,
291 Capability *cap, StgTSO *t );
292 static void scheduleDoHeapProfile(void);
293 static void scheduleDoGC(void);
295 static void unblockThread(StgTSO *tso);
296 static SchedulerStatus waitThread_(/*out*/StgMainThread* m,
297 Capability *initialCapability
299 static void scheduleThread_ (StgTSO* tso);
300 static void AllRoots(evac_fn evac);
302 static StgTSO *threadStackOverflow(StgTSO *tso);
304 static void raiseAsync_(StgTSO *tso, StgClosure *exception,
305 rtsBool stop_at_atomically);
307 static void printThreadBlockage(StgTSO *tso);
308 static void printThreadStatus(StgTSO *tso);
310 #if defined(PARALLEL_HASKELL)
311 StgTSO * createSparkThread(rtsSpark spark);
312 StgTSO * activateSpark (rtsSpark spark);
315 /* ----------------------------------------------------------------------------
317 * ------------------------------------------------------------------------- */
319 #if defined(RTS_SUPPORTS_THREADS)
320 static rtsBool startingWorkerThread = rtsFalse;
325 ACQUIRE_LOCK(&sched_mutex);
326 startingWorkerThread = rtsFalse;
328 RELEASE_LOCK(&sched_mutex);
332 startSchedulerTaskIfNecessary(void)
334 if(run_queue_hd != END_TSO_QUEUE
335 || blocked_queue_hd != END_TSO_QUEUE
336 || sleeping_queue != END_TSO_QUEUE)
338 if(!startingWorkerThread)
339 { // we don't want to start another worker thread
340 // just because the last one hasn't yet reached the
341 // "waiting for capability" state
342 startingWorkerThread = rtsTrue;
343 if (!startTask(taskStart)) {
344 startingWorkerThread = rtsFalse;
351 /* -----------------------------------------------------------------------------
352 * Putting a thread on the run queue: different scheduling policies
353 * -------------------------------------------------------------------------- */
356 addToRunQueue( StgTSO *t )
358 #if defined(PARALLEL_HASKELL)
359 if (RtsFlags.ParFlags.doFairScheduling) {
360 // this does round-robin scheduling; good for concurrency
361 APPEND_TO_RUN_QUEUE(t);
363 // this does unfair scheduling; good for parallelism
364 PUSH_ON_RUN_QUEUE(t);
367 // this does round-robin scheduling; good for concurrency
368 APPEND_TO_RUN_QUEUE(t);
372 /* ---------------------------------------------------------------------------
373 Main scheduling loop.
375 We use round-robin scheduling, each thread returning to the
376 scheduler loop when one of these conditions is detected:
379 * timer expires (thread yields)
384 Locking notes: we acquire the scheduler lock once at the beginning
385 of the scheduler loop, and release it when
387 * running a thread, or
388 * waiting for work, or
389 * waiting for a GC to complete.
392 In a GranSim setup this loop iterates over the global event queue.
393 This revolves around the global event queue, which determines what
394 to do next. Therefore, it's more complicated than either the
395 concurrent or the parallel (GUM) setup.
398 GUM iterates over incoming messages.
399 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
400 and sends out a fish whenever it has nothing to do; in-between
401 doing the actual reductions (shared code below) it processes the
402 incoming messages and deals with delayed operations
403 (see PendingFetches).
404 This is not the ugliest code you could imagine, but it's bloody close.
406 ------------------------------------------------------------------------ */
409 schedule( StgMainThread *mainThread USED_WHEN_RTS_SUPPORTS_THREADS,
410 Capability *initialCapability )
414 StgThreadReturnCode ret;
417 #elif defined(PARALLEL_HASKELL)
420 rtsBool receivedFinish = rtsFalse;
422 nat tp_size, sp_size; // stats only
427 // Pre-condition: sched_mutex is held.
428 // We might have a capability, passed in as initialCapability.
429 cap = initialCapability;
431 #if !defined(RTS_SUPPORTS_THREADS)
432 // simply initialise it in the non-threaded case
433 grabCapability(&cap);
437 sched_belch("### NEW SCHEDULER LOOP (main thr: %p, cap: %p)",
438 mainThread, initialCapability);
443 // -----------------------------------------------------------
444 // Scheduler loop starts here:
446 #if defined(PARALLEL_HASKELL)
447 #define TERMINATION_CONDITION (!receivedFinish)
449 #define TERMINATION_CONDITION ((event = get_next_event()) != (rtsEvent*)NULL)
451 #define TERMINATION_CONDITION rtsTrue
454 while (TERMINATION_CONDITION) {
457 /* Choose the processor with the next event */
458 CurrentProc = event->proc;
459 CurrentTSO = event->tso;
462 IF_DEBUG(scheduler, printAllThreads());
466 // Wait until GC has completed, if necessary.
470 releaseCapability(cap);
471 IF_DEBUG(scheduler,sched_belch("waiting for GC"));
472 waitCondition( &gc_pending_cond, &sched_mutex );
477 #if defined(RTS_SUPPORTS_THREADS)
478 // Yield the capability to higher-priority tasks if necessary.
481 yieldCapability(&cap);
484 // If we do not currently hold a capability, we wait for one
487 waitForCapability(&sched_mutex, &cap,
488 mainThread ? &mainThread->bound_thread_cond : NULL);
491 // We now have a capability...
494 // Check whether we have re-entered the RTS from Haskell without
495 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
498 errorBelch("schedule: re-entered unsafely.\n"
499 " Perhaps a 'foreign import unsafe' should be 'safe'?");
503 scheduleHandleInterrupt();
505 #if defined(not_yet) && defined(SMP)
507 // Top up the run queue from our spark pool. We try to make the
508 // number of threads in the run queue equal to the number of
509 // free capabilities.
513 if (EMPTY_RUN_QUEUE()) {
514 spark = findSpark(rtsFalse);
516 break; /* no more sparks in the pool */
518 createSparkThread(spark);
520 sched_belch("==^^ turning spark of closure %p into a thread",
521 (StgClosure *)spark));
527 scheduleStartSignalHandlers();
529 scheduleCheckBlockedThreads();
531 scheduleDetectDeadlock();
533 // Normally, the only way we can get here with no threads to
534 // run is if a keyboard interrupt received during
535 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
536 // Additionally, it is not fatal for the
537 // threaded RTS to reach here with no threads to run.
539 // win32: might be here due to awaitEvent() being abandoned
540 // as a result of a console event having been delivered.
541 if ( EMPTY_RUN_QUEUE() ) {
542 #if !defined(RTS_SUPPORTS_THREADS) && !defined(mingw32_HOST_OS)
545 continue; // nothing to do
548 #if defined(PARALLEL_HASKELL)
549 scheduleSendPendingMessages();
550 if (EMPTY_RUN_QUEUE() && scheduleActivateSpark())
554 ASSERT(next_fish_to_send_at==0); // i.e. no delayed fishes left!
557 /* If we still have no work we need to send a FISH to get a spark
559 if (EMPTY_RUN_QUEUE()) {
560 if (!scheduleGetRemoteWork(&receivedFinish)) continue;
561 ASSERT(rtsFalse); // should not happen at the moment
563 // from here: non-empty run queue.
564 // TODO: merge above case with this, only one call processMessages() !
565 if (PacketsWaiting()) { /* process incoming messages, if
566 any pending... only in else
567 because getRemoteWork waits for
569 receivedFinish = processMessages();
574 scheduleProcessEvent(event);
578 // Get a thread to run
580 ASSERT(run_queue_hd != END_TSO_QUEUE);
583 #if defined(GRAN) || defined(PAR)
584 scheduleGranParReport(); // some kind of debuging output
586 // Sanity check the thread we're about to run. This can be
587 // expensive if there is lots of thread switching going on...
588 IF_DEBUG(sanity,checkTSO(t));
591 #if defined(RTS_SUPPORTS_THREADS)
592 // Check whether we can run this thread in the current task.
593 // If not, we have to pass our capability to the right task.
595 StgMainThread *m = t->main;
602 sched_belch("### Running thread %d in bound thread", t->id));
603 // yes, the Haskell thread is bound to the current native thread
608 sched_belch("### thread %d bound to another OS thread", t->id));
609 // no, bound to a different Haskell thread: pass to that thread
610 PUSH_ON_RUN_QUEUE(t);
611 passCapability(&m->bound_thread_cond);
617 if(mainThread != NULL)
618 // The thread we want to run is bound.
621 sched_belch("### this OS thread cannot run thread %d", t->id));
622 // no, the current native thread is bound to a different
623 // Haskell thread, so pass it to any worker thread
624 PUSH_ON_RUN_QUEUE(t);
625 passCapabilityToWorker();
632 cap->r.rCurrentTSO = t;
634 /* context switches are now initiated by the timer signal, unless
635 * the user specified "context switch as often as possible", with
638 if ((RtsFlags.ConcFlags.ctxtSwitchTicks == 0
639 && (run_queue_hd != END_TSO_QUEUE
640 || blocked_queue_hd != END_TSO_QUEUE
641 || sleeping_queue != END_TSO_QUEUE)))
646 RELEASE_LOCK(&sched_mutex);
648 IF_DEBUG(scheduler, sched_belch("-->> running thread %ld %s ...",
649 (long)t->id, whatNext_strs[t->what_next]));
651 #if defined(PROFILING)
652 startHeapProfTimer();
655 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
656 /* Run the current thread
658 prev_what_next = t->what_next;
660 errno = t->saved_errno;
661 in_haskell = rtsTrue;
663 switch (prev_what_next) {
667 /* Thread already finished, return to scheduler. */
668 ret = ThreadFinished;
672 ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
675 case ThreadInterpret:
676 ret = interpretBCO(cap);
680 barf("schedule: invalid what_next field");
683 in_haskell = rtsFalse;
685 // The TSO might have moved, eg. if it re-entered the RTS and a GC
686 // happened. So find the new location:
687 t = cap->r.rCurrentTSO;
689 // And save the current errno in this thread.
690 t->saved_errno = errno;
692 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
694 /* Costs for the scheduler are assigned to CCS_SYSTEM */
695 #if defined(PROFILING)
700 ACQUIRE_LOCK(&sched_mutex);
702 #if defined(RTS_SUPPORTS_THREADS)
703 IF_DEBUG(scheduler,debugBelch("sched (task %p): ", osThreadId()););
704 #elif !defined(GRAN) && !defined(PARALLEL_HASKELL)
705 IF_DEBUG(scheduler,debugBelch("sched: "););
708 schedulePostRunThread();
712 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
716 scheduleHandleStackOverflow(t);
720 if (scheduleHandleYield(t, prev_what_next)) {
721 // shortcut for switching between compiler/interpreter:
727 scheduleHandleThreadBlocked(t);
732 if (scheduleHandleThreadFinished(mainThread, cap, t)) return;;
736 barf("schedule: invalid thread return code %d", (int)ret);
739 scheduleDoHeapProfile();
741 } /* end of while() */
743 IF_PAR_DEBUG(verbose,
744 debugBelch("== Leaving schedule() after having received Finish\n"));
747 /* ----------------------------------------------------------------------------
748 * Setting up the scheduler loop
749 * ASSUMES: sched_mutex
750 * ------------------------------------------------------------------------- */
753 schedulePreLoop(void)
756 /* set up first event to get things going */
757 /* ToDo: assign costs for system setup and init MainTSO ! */
758 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
760 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
763 debugBelch("GRAN: Init CurrentTSO (in schedule) = %p\n",
765 G_TSO(CurrentTSO, 5));
767 if (RtsFlags.GranFlags.Light) {
768 /* Save current time; GranSim Light only */
769 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
774 /* ----------------------------------------------------------------------------
775 * Deal with the interrupt flag
776 * ASSUMES: sched_mutex
777 * ------------------------------------------------------------------------- */
780 void scheduleHandleInterrupt(void)
783 // Test for interruption. If interrupted==rtsTrue, then either
784 // we received a keyboard interrupt (^C), or the scheduler is
785 // trying to shut down all the tasks (shutting_down_scheduler) in
789 if (shutting_down_scheduler) {
790 IF_DEBUG(scheduler, sched_belch("shutting down"));
791 #if defined(RTS_SUPPORTS_THREADS)
795 IF_DEBUG(scheduler, sched_belch("interrupted"));
801 /* ----------------------------------------------------------------------------
802 * Start any pending signal handlers
803 * ASSUMES: sched_mutex
804 * ------------------------------------------------------------------------- */
807 scheduleStartSignalHandlers(void)
809 #if defined(RTS_USER_SIGNALS)
810 if (signals_pending()) {
811 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
812 startSignalHandlers();
813 ACQUIRE_LOCK(&sched_mutex);
818 /* ----------------------------------------------------------------------------
819 * Check for blocked threads that can be woken up.
820 * ASSUMES: sched_mutex
821 * ------------------------------------------------------------------------- */
824 scheduleCheckBlockedThreads(void)
827 // Check whether any waiting threads need to be woken up. If the
828 // run queue is empty, and there are no other tasks running, we
829 // can wait indefinitely for something to happen.
831 if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue) )
833 #if defined(RTS_SUPPORTS_THREADS)
834 // We shouldn't be here...
835 barf("schedule: awaitEvent() in threaded RTS");
837 awaitEvent( EMPTY_RUN_QUEUE() );
841 /* ----------------------------------------------------------------------------
842 * Detect deadlock conditions and attempt to resolve them.
843 * ASSUMES: sched_mutex
844 * ------------------------------------------------------------------------- */
847 scheduleDetectDeadlock(void)
850 * Detect deadlock: when we have no threads to run, there are no
851 * threads waiting on I/O or sleeping, and all the other tasks are
852 * waiting for work, we must have a deadlock of some description.
854 * We first try to find threads blocked on themselves (ie. black
855 * holes), and generate NonTermination exceptions where necessary.
857 * If no threads are black holed, we have a deadlock situation, so
858 * inform all the main threads.
860 #if !defined(PARALLEL_HASKELL) && !defined(RTS_SUPPORTS_THREADS)
861 if ( EMPTY_THREAD_QUEUES() )
863 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
865 // Garbage collection can release some new threads due to
866 // either (a) finalizers or (b) threads resurrected because
867 // they are unreachable and will therefore be sent an
868 // exception. Any threads thus released will be immediately
870 GarbageCollect(GetRoots,rtsTrue);
871 if ( !EMPTY_RUN_QUEUE() ) return;
873 #if defined(RTS_USER_SIGNALS)
874 /* If we have user-installed signal handlers, then wait
875 * for signals to arrive rather then bombing out with a
878 if ( anyUserHandlers() ) {
880 sched_belch("still deadlocked, waiting for signals..."));
884 if (signals_pending()) {
885 RELEASE_LOCK(&sched_mutex);
886 startSignalHandlers();
887 ACQUIRE_LOCK(&sched_mutex);
890 // either we have threads to run, or we were interrupted:
891 ASSERT(!EMPTY_RUN_QUEUE() || interrupted);
895 /* Probably a real deadlock. Send the current main thread the
896 * Deadlock exception (or in the SMP build, send *all* main
897 * threads the deadlock exception, since none of them can make
903 switch (m->tso->why_blocked) {
904 case BlockedOnBlackHole:
905 case BlockedOnException:
907 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
910 barf("deadlock: main thread blocked in a strange way");
915 #elif defined(RTS_SUPPORTS_THREADS)
916 // ToDo: add deadlock detection in threaded RTS
917 #elif defined(PARALLEL_HASKELL)
918 // ToDo: add deadlock detection in GUM (similar to SMP) -- HWL
922 /* ----------------------------------------------------------------------------
923 * Process an event (GRAN only)
924 * ------------------------------------------------------------------------- */
928 scheduleProcessEvent(rtsEvent *event)
932 if (RtsFlags.GranFlags.Light)
933 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
935 /* adjust time based on time-stamp */
936 if (event->time > CurrentTime[CurrentProc] &&
937 event->evttype != ContinueThread)
938 CurrentTime[CurrentProc] = event->time;
940 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
941 if (!RtsFlags.GranFlags.Light)
944 IF_DEBUG(gran, debugBelch("GRAN: switch by event-type\n"));
946 /* main event dispatcher in GranSim */
947 switch (event->evttype) {
948 /* Should just be continuing execution */
950 IF_DEBUG(gran, debugBelch("GRAN: doing ContinueThread\n"));
951 /* ToDo: check assertion
952 ASSERT(run_queue_hd != (StgTSO*)NULL &&
953 run_queue_hd != END_TSO_QUEUE);
955 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
956 if (!RtsFlags.GranFlags.DoAsyncFetch &&
957 procStatus[CurrentProc]==Fetching) {
958 debugBelch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]\n",
959 CurrentTSO->id, CurrentTSO, CurrentProc);
962 /* Ignore ContinueThreads for completed threads */
963 if (CurrentTSO->what_next == ThreadComplete) {
964 debugBelch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)\n",
965 CurrentTSO->id, CurrentTSO, CurrentProc);
968 /* Ignore ContinueThreads for threads that are being migrated */
969 if (PROCS(CurrentTSO)==Nowhere) {
970 debugBelch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)\n",
971 CurrentTSO->id, CurrentTSO, CurrentProc);
974 /* The thread should be at the beginning of the run queue */
975 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
976 debugBelch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread\n",
977 CurrentTSO->id, CurrentTSO, CurrentProc);
978 break; // run the thread anyway
981 new_event(proc, proc, CurrentTime[proc],
983 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
985 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
986 break; // now actually run the thread; DaH Qu'vam yImuHbej
989 do_the_fetchnode(event);
990 goto next_thread; /* handle next event in event queue */
993 do_the_globalblock(event);
994 goto next_thread; /* handle next event in event queue */
997 do_the_fetchreply(event);
998 goto next_thread; /* handle next event in event queue */
1000 case UnblockThread: /* Move from the blocked queue to the tail of */
1001 do_the_unblock(event);
1002 goto next_thread; /* handle next event in event queue */
1004 case ResumeThread: /* Move from the blocked queue to the tail of */
1005 /* the runnable queue ( i.e. Qu' SImqa'lu') */
1006 event->tso->gran.blocktime +=
1007 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
1008 do_the_startthread(event);
1009 goto next_thread; /* handle next event in event queue */
1012 do_the_startthread(event);
1013 goto next_thread; /* handle next event in event queue */
1016 do_the_movethread(event);
1017 goto next_thread; /* handle next event in event queue */
1020 do_the_movespark(event);
1021 goto next_thread; /* handle next event in event queue */
1024 do_the_findwork(event);
1025 goto next_thread; /* handle next event in event queue */
1028 barf("Illegal event type %u\n", event->evttype);
1031 /* This point was scheduler_loop in the old RTS */
1033 IF_DEBUG(gran, debugBelch("GRAN: after main switch\n"));
1035 TimeOfLastEvent = CurrentTime[CurrentProc];
1036 TimeOfNextEvent = get_time_of_next_event();
1037 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
1038 // CurrentTSO = ThreadQueueHd;
1040 IF_DEBUG(gran, debugBelch("GRAN: time of next event is: %ld\n",
1043 if (RtsFlags.GranFlags.Light)
1044 GranSimLight_leave_system(event, &ActiveTSO);
1046 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
1049 debugBelch("GRAN: end of time-slice is %#lx\n", EndOfTimeSlice));
1051 /* in a GranSim setup the TSO stays on the run queue */
1053 /* Take a thread from the run queue. */
1054 POP_RUN_QUEUE(t); // take_off_run_queue(t);
1057 debugBelch("GRAN: About to run current thread, which is\n");
1060 context_switch = 0; // turned on via GranYield, checking events and time slice
1063 DumpGranEvent(GR_SCHEDULE, t));
1065 procStatus[CurrentProc] = Busy;
1069 /* ----------------------------------------------------------------------------
1070 * Send pending messages (PARALLEL_HASKELL only)
1071 * ------------------------------------------------------------------------- */
1073 #if defined(PARALLEL_HASKELL)
1075 scheduleSendPendingMessages(void)
1081 # if defined(PAR) // global Mem.Mgmt., omit for now
1082 if (PendingFetches != END_BF_QUEUE) {
1087 if (RtsFlags.ParFlags.BufferTime) {
1088 // if we use message buffering, we must send away all message
1089 // packets which have become too old...
1095 /* ----------------------------------------------------------------------------
1096 * Activate spark threads (PARALLEL_HASKELL only)
1097 * ------------------------------------------------------------------------- */
1099 #if defined(PARALLEL_HASKELL)
1101 scheduleActivateSpark(void)
1104 ASSERT(EMPTY_RUN_QUEUE());
1105 /* We get here if the run queue is empty and want some work.
1106 We try to turn a spark into a thread, and add it to the run queue,
1107 from where it will be picked up in the next iteration of the scheduler
1111 /* :-[ no local threads => look out for local sparks */
1112 /* the spark pool for the current PE */
1113 pool = &(cap.r.rSparks); // JB: cap = (old) MainCap
1114 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
1115 pool->hd < pool->tl) {
1117 * ToDo: add GC code check that we really have enough heap afterwards!!
1119 * If we're here (no runnable threads) and we have pending
1120 * sparks, we must have a space problem. Get enough space
1121 * to turn one of those pending sparks into a
1125 spark = findSpark(rtsFalse); /* get a spark */
1126 if (spark != (rtsSpark) NULL) {
1127 tso = createThreadFromSpark(spark); /* turn the spark into a thread */
1128 IF_PAR_DEBUG(fish, // schedule,
1129 debugBelch("==== schedule: Created TSO %d (%p); %d threads active\n",
1130 tso->id, tso, advisory_thread_count));
1132 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
1133 IF_PAR_DEBUG(fish, // schedule,
1134 debugBelch("==^^ failed to create thread from spark @ %lx\n",
1136 return rtsFalse; /* failed to generate a thread */
1137 } /* otherwise fall through & pick-up new tso */
1139 IF_PAR_DEBUG(fish, // schedule,
1140 debugBelch("==^^ no local sparks (spark pool contains only NFs: %d)\n",
1141 spark_queue_len(pool)));
1142 return rtsFalse; /* failed to generate a thread */
1144 return rtsTrue; /* success in generating a thread */
1145 } else { /* no more threads permitted or pool empty */
1146 return rtsFalse; /* failed to generateThread */
1149 tso = NULL; // avoid compiler warning only
1150 return rtsFalse; /* dummy in non-PAR setup */
1153 #endif // PARALLEL_HASKELL
1155 /* ----------------------------------------------------------------------------
1156 * Get work from a remote node (PARALLEL_HASKELL only)
1157 * ------------------------------------------------------------------------- */
1159 #if defined(PARALLEL_HASKELL)
1161 scheduleGetRemoteWork(rtsBool *receivedFinish)
1163 ASSERT(EMPTY_RUN_QUEUE());
1165 if (RtsFlags.ParFlags.BufferTime) {
1166 IF_PAR_DEBUG(verbose,
1167 debugBelch("...send all pending data,"));
1170 for (i=1; i<=nPEs; i++)
1171 sendImmediately(i); // send all messages away immediately
1175 //++EDEN++ idle() , i.e. send all buffers, wait for work
1176 // suppress fishing in EDEN... just look for incoming messages
1177 // (blocking receive)
1178 IF_PAR_DEBUG(verbose,
1179 debugBelch("...wait for incoming messages...\n"));
1180 *receivedFinish = processMessages(); // blocking receive...
1182 // and reenter scheduling loop after having received something
1183 // (return rtsFalse below)
1185 # else /* activate SPARKS machinery */
1186 /* We get here, if we have no work, tried to activate a local spark, but still
1187 have no work. We try to get a remote spark, by sending a FISH message.
1188 Thread migration should be added here, and triggered when a sequence of
1189 fishes returns without work. */
1190 delay = (RtsFlags.ParFlags.fishDelay!=0ll ? RtsFlags.ParFlags.fishDelay : 0ll);
1192 /* =8-[ no local sparks => look for work on other PEs */
1194 * We really have absolutely no work. Send out a fish
1195 * (there may be some out there already), and wait for
1196 * something to arrive. We clearly can't run any threads
1197 * until a SCHEDULE or RESUME arrives, and so that's what
1198 * we're hoping to see. (Of course, we still have to
1199 * respond to other types of messages.)
1201 rtsTime now = msTime() /*CURRENT_TIME*/;
1202 IF_PAR_DEBUG(verbose,
1203 debugBelch("-- now=%ld\n", now));
1204 IF_PAR_DEBUG(fish, // verbose,
1205 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
1206 (last_fish_arrived_at!=0 &&
1207 last_fish_arrived_at+delay > now)) {
1208 debugBelch("--$$ <%llu> delaying FISH until %llu (last fish %llu, delay %llu)\n",
1209 now, last_fish_arrived_at+delay,
1210 last_fish_arrived_at,
1214 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
1215 advisory_thread_count < RtsFlags.ParFlags.maxThreads) { // send a FISH, but when?
1216 if (last_fish_arrived_at==0 ||
1217 (last_fish_arrived_at+delay <= now)) { // send FISH now!
1218 /* outstandingFishes is set in sendFish, processFish;
1219 avoid flooding system with fishes via delay */
1220 next_fish_to_send_at = 0;
1222 /* ToDo: this should be done in the main scheduling loop to avoid the
1223 busy wait here; not so bad if fish delay is very small */
1224 int iq = 0; // DEBUGGING -- HWL
1225 next_fish_to_send_at = last_fish_arrived_at+delay; // remember when to send
1226 /* send a fish when ready, but process messages that arrive in the meantime */
1228 if (PacketsWaiting()) {
1230 *receivedFinish = processMessages();
1233 } while (!*receivedFinish || now<next_fish_to_send_at);
1234 // JB: This means the fish could become obsolete, if we receive
1235 // work. Better check for work again?
1236 // last line: while (!receivedFinish || !haveWork || now<...)
1237 // next line: if (receivedFinish || haveWork )
1239 if (*receivedFinish) // no need to send a FISH if we are finishing anyway
1240 return rtsFalse; // NB: this will leave scheduler loop
1241 // immediately after return!
1243 IF_PAR_DEBUG(fish, // verbose,
1244 debugBelch("--$$ <%llu> sent delayed fish (%d processMessages); active/total threads=%d/%d\n",now,iq,run_queue_len(),advisory_thread_count));
1248 // JB: IMHO, this should all be hidden inside sendFish(...)
1250 sendFish(pe, thisPE, NEW_FISH_AGE, NEW_FISH_HISTORY,
1253 // Global statistics: count no. of fishes
1254 if (RtsFlags.ParFlags.ParStats.Global &&
1255 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1256 globalParStats.tot_fish_mess++;
1260 /* delayed fishes must have been sent by now! */
1261 next_fish_to_send_at = 0;
1264 *receivedFinish = processMessages();
1265 # endif /* SPARKS */
1268 /* NB: this function always returns rtsFalse, meaning the scheduler
1269 loop continues with the next iteration;
1271 return code means success in finding work; we enter this function
1272 if there is no local work, thus have to send a fish which takes
1273 time until it arrives with work; in the meantime we should process
1274 messages in the main loop;
1277 #endif // PARALLEL_HASKELL
1279 /* ----------------------------------------------------------------------------
1280 * PAR/GRAN: Report stats & debugging info(?)
1281 * ------------------------------------------------------------------------- */
1283 #if defined(PAR) || defined(GRAN)
1285 scheduleGranParReport(void)
1287 ASSERT(run_queue_hd != END_TSO_QUEUE);
1289 /* Take a thread from the run queue, if we have work */
1290 POP_RUN_QUEUE(t); // take_off_run_queue(END_TSO_QUEUE);
1292 /* If this TSO has got its outport closed in the meantime,
1293 * it mustn't be run. Instead, we have to clean it up as if it was finished.
1294 * It has to be marked as TH_DEAD for this purpose.
1295 * If it is TH_TERM instead, it is supposed to have finished in the normal way.
1297 JB: TODO: investigate wether state change field could be nuked
1298 entirely and replaced by the normal tso state (whatnext
1299 field). All we want to do is to kill tsos from outside.
1302 /* ToDo: write something to the log-file
1303 if (RTSflags.ParFlags.granSimStats && !sameThread)
1304 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
1308 /* the spark pool for the current PE */
1309 pool = &(cap.r.rSparks); // cap = (old) MainCap
1312 debugBelch("--=^ %d threads, %d sparks on [%#x]\n",
1313 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
1316 debugBelch("--=^ %d threads, %d sparks on [%#x]\n",
1317 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
1319 if (RtsFlags.ParFlags.ParStats.Full &&
1320 (t->par.sparkname != (StgInt)0) && // only log spark generated threads
1321 (emitSchedule || // forced emit
1322 (t && LastTSO && t->id != LastTSO->id))) {
1324 we are running a different TSO, so write a schedule event to log file
1325 NB: If we use fair scheduling we also have to write a deschedule
1326 event for LastTSO; with unfair scheduling we know that the
1327 previous tso has blocked whenever we switch to another tso, so
1328 we don't need it in GUM for now
1330 IF_PAR_DEBUG(fish, // schedule,
1331 debugBelch("____ scheduling spark generated thread %d (%lx) (%lx) via a forced emit\n",t->id,t,t->par.sparkname));
1333 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1334 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
1335 emitSchedule = rtsFalse;
1340 /* ----------------------------------------------------------------------------
1341 * After running a thread...
1342 * ASSUMES: sched_mutex
1343 * ------------------------------------------------------------------------- */
1346 schedulePostRunThread(void)
1349 /* HACK 675: if the last thread didn't yield, make sure to print a
1350 SCHEDULE event to the log file when StgRunning the next thread, even
1351 if it is the same one as before */
1353 TimeOfLastYield = CURRENT_TIME;
1356 /* some statistics gathering in the parallel case */
1358 #if defined(GRAN) || defined(PAR) || defined(EDEN)
1362 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
1363 globalGranStats.tot_heapover++;
1365 globalParStats.tot_heapover++;
1372 DumpGranEvent(GR_DESCHEDULE, t));
1373 globalGranStats.tot_stackover++;
1376 // DumpGranEvent(GR_DESCHEDULE, t);
1377 globalParStats.tot_stackover++;
1381 case ThreadYielding:
1384 DumpGranEvent(GR_DESCHEDULE, t));
1385 globalGranStats.tot_yields++;
1388 // DumpGranEvent(GR_DESCHEDULE, t);
1389 globalParStats.tot_yields++;
1396 debugBelch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1397 t->id, t, whatNext_strs[t->what_next], t->block_info.closure,
1398 (t->block_info.closure==(StgClosure*)NULL ? 99 : where_is(t->block_info.closure)));
1399 if (t->block_info.closure!=(StgClosure*)NULL)
1400 print_bq(t->block_info.closure);
1403 // ??? needed; should emit block before
1405 DumpGranEvent(GR_DESCHEDULE, t));
1406 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1409 ASSERT(procStatus[CurrentProc]==Busy ||
1410 ((procStatus[CurrentProc]==Fetching) &&
1411 (t->block_info.closure!=(StgClosure*)NULL)));
1412 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1413 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1414 procStatus[CurrentProc]==Fetching))
1415 procStatus[CurrentProc] = Idle;
1418 //++PAR++ blockThread() writes the event (change?)
1422 case ThreadFinished:
1426 barf("parGlobalStats: unknown return code");
1432 /* -----------------------------------------------------------------------------
1433 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1434 * ASSUMES: sched_mutex
1435 * -------------------------------------------------------------------------- */
1438 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1440 // did the task ask for a large block?
1441 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1442 // if so, get one and push it on the front of the nursery.
1446 blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1449 debugBelch("--<< thread %ld (%s) stopped: requesting a large block (size %d)\n",
1450 (long)t->id, whatNext_strs[t->what_next], blocks));
1452 // don't do this if it would push us over the
1453 // alloc_blocks_lim limit; we'll GC first.
1454 if (alloc_blocks + blocks < alloc_blocks_lim) {
1456 alloc_blocks += blocks;
1457 bd = allocGroup( blocks );
1459 // link the new group into the list
1460 bd->link = cap->r.rCurrentNursery;
1461 bd->u.back = cap->r.rCurrentNursery->u.back;
1462 if (cap->r.rCurrentNursery->u.back != NULL) {
1463 cap->r.rCurrentNursery->u.back->link = bd;
1465 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1466 g0s0->blocks == cap->r.rNursery);
1467 cap->r.rNursery = g0s0->blocks = bd;
1469 cap->r.rCurrentNursery->u.back = bd;
1471 // initialise it as a nursery block. We initialise the
1472 // step, gen_no, and flags field of *every* sub-block in
1473 // this large block, because this is easier than making
1474 // sure that we always find the block head of a large
1475 // block whenever we call Bdescr() (eg. evacuate() and
1476 // isAlive() in the GC would both have to do this, at
1480 for (x = bd; x < bd + blocks; x++) {
1487 // don't forget to update the block count in g0s0.
1488 g0s0->n_blocks += blocks;
1489 // This assert can be a killer if the app is doing lots
1490 // of large block allocations.
1491 ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1493 // now update the nursery to point to the new block
1494 cap->r.rCurrentNursery = bd;
1496 // we might be unlucky and have another thread get on the
1497 // run queue before us and steal the large block, but in that
1498 // case the thread will just end up requesting another large
1500 PUSH_ON_RUN_QUEUE(t);
1501 return rtsFalse; /* not actually GC'ing */
1505 /* make all the running tasks block on a condition variable,
1506 * maybe set context_switch and wait till they all pile in,
1507 * then have them wait on a GC condition variable.
1510 debugBelch("--<< thread %ld (%s) stopped: HeapOverflow\n",
1511 (long)t->id, whatNext_strs[t->what_next]));
1514 ASSERT(!is_on_queue(t,CurrentProc));
1515 #elif defined(PARALLEL_HASKELL)
1516 /* Currently we emit a DESCHEDULE event before GC in GUM.
1517 ToDo: either add separate event to distinguish SYSTEM time from rest
1518 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1519 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1520 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1521 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1522 emitSchedule = rtsTrue;
1526 PUSH_ON_RUN_QUEUE(t);
1528 /* actual GC is done at the end of the while loop in schedule() */
1531 /* -----------------------------------------------------------------------------
1532 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1533 * ASSUMES: sched_mutex
1534 * -------------------------------------------------------------------------- */
1537 scheduleHandleStackOverflow( StgTSO *t)
1539 IF_DEBUG(scheduler,debugBelch("--<< thread %ld (%s) stopped, StackOverflow\n",
1540 (long)t->id, whatNext_strs[t->what_next]));
1541 /* just adjust the stack for this thread, then pop it back
1546 /* enlarge the stack */
1547 StgTSO *new_t = threadStackOverflow(t);
1549 /* This TSO has moved, so update any pointers to it from the
1550 * main thread stack. It better not be on any other queues...
1551 * (it shouldn't be).
1553 if (t->main != NULL) {
1554 t->main->tso = new_t;
1556 PUSH_ON_RUN_QUEUE(new_t);
1560 /* -----------------------------------------------------------------------------
1561 * Handle a thread that returned to the scheduler with ThreadYielding
1562 * ASSUMES: sched_mutex
1563 * -------------------------------------------------------------------------- */
1566 scheduleHandleYield( StgTSO *t, nat prev_what_next )
1568 // Reset the context switch flag. We don't do this just before
1569 // running the thread, because that would mean we would lose ticks
1570 // during GC, which can lead to unfair scheduling (a thread hogs
1571 // the CPU because the tick always arrives during GC). This way
1572 // penalises threads that do a lot of allocation, but that seems
1573 // better than the alternative.
1576 /* put the thread back on the run queue. Then, if we're ready to
1577 * GC, check whether this is the last task to stop. If so, wake
1578 * up the GC thread. getThread will block during a GC until the
1582 if (t->what_next != prev_what_next) {
1583 debugBelch("--<< thread %ld (%s) stopped to switch evaluators\n",
1584 (long)t->id, whatNext_strs[t->what_next]);
1586 debugBelch("--<< thread %ld (%s) stopped, yielding\n",
1587 (long)t->id, whatNext_strs[t->what_next]);
1592 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1594 ASSERT(t->link == END_TSO_QUEUE);
1596 // Shortcut if we're just switching evaluators: don't bother
1597 // doing stack squeezing (which can be expensive), just run the
1599 if (t->what_next != prev_what_next) {
1606 ASSERT(!is_on_queue(t,CurrentProc));
1609 //debugBelch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1610 checkThreadQsSanity(rtsTrue));
1617 /* add a ContinueThread event to actually process the thread */
1618 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1620 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1622 debugBelch("GRAN: eventq and runnableq after adding yielded thread to queue again:\n");
1629 /* -----------------------------------------------------------------------------
1630 * Handle a thread that returned to the scheduler with ThreadBlocked
1631 * ASSUMES: sched_mutex
1632 * -------------------------------------------------------------------------- */
1635 scheduleHandleThreadBlocked( StgTSO *t
1636 #if !defined(GRAN) && !defined(DEBUG)
1643 debugBelch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: \n",
1644 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)));
1645 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1647 // ??? needed; should emit block before
1649 DumpGranEvent(GR_DESCHEDULE, t));
1650 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1653 ASSERT(procStatus[CurrentProc]==Busy ||
1654 ((procStatus[CurrentProc]==Fetching) &&
1655 (t->block_info.closure!=(StgClosure*)NULL)));
1656 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1657 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1658 procStatus[CurrentProc]==Fetching))
1659 procStatus[CurrentProc] = Idle;
1663 debugBelch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: \n",
1664 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1667 if (t->block_info.closure!=(StgClosure*)NULL)
1668 print_bq(t->block_info.closure));
1670 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1673 /* whatever we schedule next, we must log that schedule */
1674 emitSchedule = rtsTrue;
1677 /* don't need to do anything. Either the thread is blocked on
1678 * I/O, in which case we'll have called addToBlockedQueue
1679 * previously, or it's blocked on an MVar or Blackhole, in which
1680 * case it'll be on the relevant queue already.
1682 ASSERT(t->why_blocked != NotBlocked);
1684 debugBelch("--<< thread %d (%s) stopped: ",
1685 t->id, whatNext_strs[t->what_next]);
1686 printThreadBlockage(t);
1689 /* Only for dumping event to log file
1690 ToDo: do I need this in GranSim, too?
1696 /* -----------------------------------------------------------------------------
1697 * Handle a thread that returned to the scheduler with ThreadFinished
1698 * ASSUMES: sched_mutex
1699 * -------------------------------------------------------------------------- */
1702 scheduleHandleThreadFinished( StgMainThread *mainThread
1703 USED_WHEN_RTS_SUPPORTS_THREADS,
1707 /* Need to check whether this was a main thread, and if so,
1708 * return with the return value.
1710 * We also end up here if the thread kills itself with an
1711 * uncaught exception, see Exception.cmm.
1713 IF_DEBUG(scheduler,debugBelch("--++ thread %d (%s) finished\n",
1714 t->id, whatNext_strs[t->what_next]));
1717 endThread(t, CurrentProc); // clean-up the thread
1718 #elif defined(PARALLEL_HASKELL)
1719 /* For now all are advisory -- HWL */
1720 //if(t->priority==AdvisoryPriority) ??
1721 advisory_thread_count--; // JB: Caution with this counter, buggy!
1724 if(t->dist.priority==RevalPriority)
1728 # if defined(EDENOLD)
1729 // the thread could still have an outport... (BUG)
1730 if (t->eden.outport != -1) {
1731 // delete the outport for the tso which has finished...
1732 IF_PAR_DEBUG(eden_ports,
1733 debugBelch("WARNING: Scheduler removes outport %d for TSO %d.\n",
1734 t->eden.outport, t->id));
1737 // thread still in the process (HEAVY BUG! since outport has just been closed...)
1738 if (t->eden.epid != -1) {
1739 IF_PAR_DEBUG(eden_ports,
1740 debugBelch("WARNING: Scheduler removes TSO %d from process %d .\n",
1741 t->id, t->eden.epid));
1742 removeTSOfromProcess(t);
1747 if (RtsFlags.ParFlags.ParStats.Full &&
1748 !RtsFlags.ParFlags.ParStats.Suppressed)
1749 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1751 // t->par only contains statistics: left out for now...
1753 debugBelch("**** end thread: ended sparked thread %d (%lx); sparkname: %lx\n",
1754 t->id,t,t->par.sparkname));
1756 #endif // PARALLEL_HASKELL
1759 // Check whether the thread that just completed was a main
1760 // thread, and if so return with the result.
1762 // There is an assumption here that all thread completion goes
1763 // through this point; we need to make sure that if a thread
1764 // ends up in the ThreadKilled state, that it stays on the run
1765 // queue so it can be dealt with here.
1768 #if defined(RTS_SUPPORTS_THREADS)
1771 mainThread->tso == t
1775 // We are a bound thread: this must be our thread that just
1777 ASSERT(mainThread->tso == t);
1779 if (t->what_next == ThreadComplete) {
1780 if (mainThread->ret) {
1781 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1782 *(mainThread->ret) = (StgClosure *)mainThread->tso->sp[1];
1784 mainThread->stat = Success;
1786 if (mainThread->ret) {
1787 *(mainThread->ret) = NULL;
1790 mainThread->stat = Interrupted;
1792 mainThread->stat = Killed;
1796 removeThreadLabel((StgWord)mainThread->tso->id);
1798 if (mainThread->prev == NULL) {
1799 main_threads = mainThread->link;
1801 mainThread->prev->link = mainThread->link;
1803 if (mainThread->link != NULL) {
1804 mainThread->link->prev = NULL;
1806 releaseCapability(cap);
1807 return rtsTrue; // tells schedule() to return
1810 #ifdef RTS_SUPPORTS_THREADS
1811 ASSERT(t->main == NULL);
1813 if (t->main != NULL) {
1814 // Must be a main thread that is not the topmost one. Leave
1815 // it on the run queue until the stack has unwound to the
1816 // point where we can deal with this. Leaving it on the run
1817 // queue also ensures that the garbage collector knows about
1818 // this thread and its return value (it gets dropped from the
1819 // all_threads list so there's no other way to find it).
1820 APPEND_TO_RUN_QUEUE(t);
1826 /* -----------------------------------------------------------------------------
1827 * Perform a heap census, if PROFILING
1828 * -------------------------------------------------------------------------- */
1831 scheduleDoHeapProfile(void)
1834 // When we have +RTS -i0 and we're heap profiling, do a census at
1835 // every GC. This lets us get repeatable runs for debugging.
1836 if (performHeapProfile ||
1837 (RtsFlags.ProfFlags.profileInterval==0 &&
1838 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1839 GarbageCollect(GetRoots, rtsTrue);
1841 performHeapProfile = rtsFalse;
1842 ready_to_gc = rtsFalse; // we already GC'd
1847 /* -----------------------------------------------------------------------------
1848 * Perform a garbage collection if necessary
1849 * ASSUMES: sched_mutex
1850 * -------------------------------------------------------------------------- */
1858 // The last task to stop actually gets to do the GC. The rest
1859 // of the tasks release their capabilities and wait gc_pending_cond.
1860 if (ready_to_gc && allFreeCapabilities())
1865 /* Kick any transactions which are invalid back to their
1866 * atomically frames. When next scheduled they will try to
1867 * commit, this commit will fail and they will retry.
1869 for (t = all_threads; t != END_TSO_QUEUE; t = t -> link) {
1870 if (t -> what_next != ThreadRelocated && t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1871 if (!stmValidateTransaction (t -> trec)) {
1872 IF_DEBUG(stm, sched_belch("trec %p found wasting its time", t));
1874 // strip the stack back to the ATOMICALLY_FRAME, aborting
1875 // the (nested) transaction, and saving the stack of any
1876 // partially-evaluated thunks on the heap.
1877 raiseAsync_(t, NULL, rtsTrue);
1880 ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1886 /* everybody back, start the GC.
1887 * Could do it in this thread, or signal a condition var
1888 * to do it in another thread. Either way, we need to
1889 * broadcast on gc_pending_cond afterward.
1891 #if defined(RTS_SUPPORTS_THREADS)
1892 IF_DEBUG(scheduler,sched_belch("doing GC"));
1894 GarbageCollect(GetRoots,rtsFalse);
1895 ready_to_gc = rtsFalse;
1897 broadcastCondition(&gc_pending_cond);
1900 /* add a ContinueThread event to continue execution of current thread */
1901 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1903 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1905 debugBelch("GRAN: eventq and runnableq after Garbage collection:\n\n");
1912 /* ---------------------------------------------------------------------------
1913 * rtsSupportsBoundThreads(): is the RTS built to support bound threads?
1914 * used by Control.Concurrent for error checking.
1915 * ------------------------------------------------------------------------- */
1918 rtsSupportsBoundThreads(void)
1927 /* ---------------------------------------------------------------------------
1928 * isThreadBound(tso): check whether tso is bound to an OS thread.
1929 * ------------------------------------------------------------------------- */
1932 isThreadBound(StgTSO* tso USED_IN_THREADED_RTS)
1935 return (tso->main != NULL);
1940 /* ---------------------------------------------------------------------------
1941 * Singleton fork(). Do not copy any running threads.
1942 * ------------------------------------------------------------------------- */
1944 #ifndef mingw32_HOST_OS
1945 #define FORKPROCESS_PRIMOP_SUPPORTED
1948 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1950 deleteThreadImmediately(StgTSO *tso);
1953 forkProcess(HsStablePtr *entry
1954 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1959 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1965 IF_DEBUG(scheduler,sched_belch("forking!"));
1966 rts_lock(); // This not only acquires sched_mutex, it also
1967 // makes sure that no other threads are running
1971 if (pid) { /* parent */
1973 /* just return the pid */
1977 } else { /* child */
1980 // delete all threads
1981 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1983 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1986 // don't allow threads to catch the ThreadKilled exception
1987 deleteThreadImmediately(t);
1990 // wipe the main thread list
1991 while((m = main_threads) != NULL) {
1992 main_threads = m->link;
1993 # ifdef THREADED_RTS
1994 closeCondition(&m->bound_thread_cond);
1999 rc = rts_evalStableIO(entry, NULL); // run the action
2000 rts_checkSchedStatus("forkProcess",rc);
2004 hs_exit(); // clean up and exit
2007 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
2008 barf("forkProcess#: primop not supported, sorry!\n");
2013 /* ---------------------------------------------------------------------------
2014 * deleteAllThreads(): kill all the live threads.
2016 * This is used when we catch a user interrupt (^C), before performing
2017 * any necessary cleanups and running finalizers.
2019 * Locks: sched_mutex held.
2020 * ------------------------------------------------------------------------- */
2023 deleteAllThreads ( void )
2026 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
2027 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
2028 next = t->global_link;
2032 // The run queue now contains a bunch of ThreadKilled threads. We
2033 // must not throw these away: the main thread(s) will be in there
2034 // somewhere, and the main scheduler loop has to deal with it.
2035 // Also, the run queue is the only thing keeping these threads from
2036 // being GC'd, and we don't want the "main thread has been GC'd" panic.
2038 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
2039 ASSERT(sleeping_queue == END_TSO_QUEUE);
2042 /* startThread and insertThread are now in GranSim.c -- HWL */
2045 /* ---------------------------------------------------------------------------
2046 * Suspending & resuming Haskell threads.
2048 * When making a "safe" call to C (aka _ccall_GC), the task gives back
2049 * its capability before calling the C function. This allows another
2050 * task to pick up the capability and carry on running Haskell
2051 * threads. It also means that if the C call blocks, it won't lock
2054 * The Haskell thread making the C call is put to sleep for the
2055 * duration of the call, on the susepended_ccalling_threads queue. We
2056 * give out a token to the task, which it can use to resume the thread
2057 * on return from the C function.
2058 * ------------------------------------------------------------------------- */
2061 suspendThread( StgRegTable *reg )
2065 int saved_errno = errno;
2067 /* assume that *reg is a pointer to the StgRegTable part
2070 cap = (Capability *)((void *)((unsigned char*)reg - sizeof(StgFunTable)));
2072 ACQUIRE_LOCK(&sched_mutex);
2075 sched_belch("thread %d did a _ccall_gc", cap->r.rCurrentTSO->id));
2077 // XXX this might not be necessary --SDM
2078 cap->r.rCurrentTSO->what_next = ThreadRunGHC;
2080 threadPaused(cap->r.rCurrentTSO);
2081 cap->r.rCurrentTSO->link = suspended_ccalling_threads;
2082 suspended_ccalling_threads = cap->r.rCurrentTSO;
2084 if(cap->r.rCurrentTSO->blocked_exceptions == NULL) {
2085 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall;
2086 cap->r.rCurrentTSO->blocked_exceptions = END_TSO_QUEUE;
2088 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall_NoUnblockExc;
2091 /* Use the thread ID as the token; it should be unique */
2092 tok = cap->r.rCurrentTSO->id;
2094 /* Hand back capability */
2095 releaseCapability(cap);
2097 #if defined(RTS_SUPPORTS_THREADS)
2098 /* Preparing to leave the RTS, so ensure there's a native thread/task
2099 waiting to take over.
2101 IF_DEBUG(scheduler, sched_belch("worker (token %d): leaving RTS", tok));
2104 in_haskell = rtsFalse;
2105 RELEASE_LOCK(&sched_mutex);
2107 errno = saved_errno;
2112 resumeThread( StgInt tok )
2114 StgTSO *tso, **prev;
2116 int saved_errno = errno;
2118 #if defined(RTS_SUPPORTS_THREADS)
2119 /* Wait for permission to re-enter the RTS with the result. */
2120 ACQUIRE_LOCK(&sched_mutex);
2121 waitForReturnCapability(&sched_mutex, &cap);
2123 IF_DEBUG(scheduler, sched_belch("worker (token %d): re-entering RTS", tok));
2125 grabCapability(&cap);
2128 /* Remove the thread off of the suspended list */
2129 prev = &suspended_ccalling_threads;
2130 for (tso = suspended_ccalling_threads;
2131 tso != END_TSO_QUEUE;
2132 prev = &tso->link, tso = tso->link) {
2133 if (tso->id == (StgThreadID)tok) {
2138 if (tso == END_TSO_QUEUE) {
2139 barf("resumeThread: thread not found");
2141 tso->link = END_TSO_QUEUE;
2143 if(tso->why_blocked == BlockedOnCCall) {
2144 awakenBlockedQueueNoLock(tso->blocked_exceptions);
2145 tso->blocked_exceptions = NULL;
2148 /* Reset blocking status */
2149 tso->why_blocked = NotBlocked;
2151 cap->r.rCurrentTSO = tso;
2152 in_haskell = rtsTrue;
2153 RELEASE_LOCK(&sched_mutex);
2154 errno = saved_errno;
2158 /* ---------------------------------------------------------------------------
2159 * Comparing Thread ids.
2161 * This is used from STG land in the implementation of the
2162 * instances of Eq/Ord for ThreadIds.
2163 * ------------------------------------------------------------------------ */
2166 cmp_thread(StgPtr tso1, StgPtr tso2)
2168 StgThreadID id1 = ((StgTSO *)tso1)->id;
2169 StgThreadID id2 = ((StgTSO *)tso2)->id;
2171 if (id1 < id2) return (-1);
2172 if (id1 > id2) return 1;
2176 /* ---------------------------------------------------------------------------
2177 * Fetching the ThreadID from an StgTSO.
2179 * This is used in the implementation of Show for ThreadIds.
2180 * ------------------------------------------------------------------------ */
2182 rts_getThreadId(StgPtr tso)
2184 return ((StgTSO *)tso)->id;
2189 labelThread(StgPtr tso, char *label)
2194 /* Caveat: Once set, you can only set the thread name to "" */
2195 len = strlen(label)+1;
2196 buf = stgMallocBytes(len * sizeof(char), "Schedule.c:labelThread()");
2197 strncpy(buf,label,len);
2198 /* Update will free the old memory for us */
2199 updateThreadLabel(((StgTSO *)tso)->id,buf);
2203 /* ---------------------------------------------------------------------------
2204 Create a new thread.
2206 The new thread starts with the given stack size. Before the
2207 scheduler can run, however, this thread needs to have a closure
2208 (and possibly some arguments) pushed on its stack. See
2209 pushClosure() in Schedule.h.
2211 createGenThread() and createIOThread() (in SchedAPI.h) are
2212 convenient packaged versions of this function.
2214 currently pri (priority) is only used in a GRAN setup -- HWL
2215 ------------------------------------------------------------------------ */
2217 /* currently pri (priority) is only used in a GRAN setup -- HWL */
2219 createThread(nat size, StgInt pri)
2222 createThread(nat size)
2229 /* First check whether we should create a thread at all */
2230 #if defined(PARALLEL_HASKELL)
2231 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
2232 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
2234 debugBelch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)\n",
2235 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
2236 return END_TSO_QUEUE;
2242 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
2245 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
2247 /* catch ridiculously small stack sizes */
2248 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
2249 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
2252 stack_size = size - TSO_STRUCT_SIZEW;
2254 tso = (StgTSO *)allocate(size);
2255 TICK_ALLOC_TSO(stack_size, 0);
2257 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
2259 SET_GRAN_HDR(tso, ThisPE);
2262 // Always start with the compiled code evaluator
2263 tso->what_next = ThreadRunGHC;
2265 tso->id = next_thread_id++;
2266 tso->why_blocked = NotBlocked;
2267 tso->blocked_exceptions = NULL;
2269 tso->saved_errno = 0;
2272 tso->stack_size = stack_size;
2273 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
2275 tso->sp = (P_)&(tso->stack) + stack_size;
2277 tso->trec = NO_TREC;
2280 tso->prof.CCCS = CCS_MAIN;
2283 /* put a stop frame on the stack */
2284 tso->sp -= sizeofW(StgStopFrame);
2285 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
2286 tso->link = END_TSO_QUEUE;
2290 /* uses more flexible routine in GranSim */
2291 insertThread(tso, CurrentProc);
2293 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
2299 if (RtsFlags.GranFlags.GranSimStats.Full)
2300 DumpGranEvent(GR_START,tso);
2301 #elif defined(PARALLEL_HASKELL)
2302 if (RtsFlags.ParFlags.ParStats.Full)
2303 DumpGranEvent(GR_STARTQ,tso);
2304 /* HACk to avoid SCHEDULE
2308 /* Link the new thread on the global thread list.
2310 tso->global_link = all_threads;
2314 tso->dist.priority = MandatoryPriority; //by default that is...
2318 tso->gran.pri = pri;
2320 tso->gran.magic = TSO_MAGIC; // debugging only
2322 tso->gran.sparkname = 0;
2323 tso->gran.startedat = CURRENT_TIME;
2324 tso->gran.exported = 0;
2325 tso->gran.basicblocks = 0;
2326 tso->gran.allocs = 0;
2327 tso->gran.exectime = 0;
2328 tso->gran.fetchtime = 0;
2329 tso->gran.fetchcount = 0;
2330 tso->gran.blocktime = 0;
2331 tso->gran.blockcount = 0;
2332 tso->gran.blockedat = 0;
2333 tso->gran.globalsparks = 0;
2334 tso->gran.localsparks = 0;
2335 if (RtsFlags.GranFlags.Light)
2336 tso->gran.clock = Now; /* local clock */
2338 tso->gran.clock = 0;
2340 IF_DEBUG(gran,printTSO(tso));
2341 #elif defined(PARALLEL_HASKELL)
2343 tso->par.magic = TSO_MAGIC; // debugging only
2345 tso->par.sparkname = 0;
2346 tso->par.startedat = CURRENT_TIME;
2347 tso->par.exported = 0;
2348 tso->par.basicblocks = 0;
2349 tso->par.allocs = 0;
2350 tso->par.exectime = 0;
2351 tso->par.fetchtime = 0;
2352 tso->par.fetchcount = 0;
2353 tso->par.blocktime = 0;
2354 tso->par.blockcount = 0;
2355 tso->par.blockedat = 0;
2356 tso->par.globalsparks = 0;
2357 tso->par.localsparks = 0;
2361 globalGranStats.tot_threads_created++;
2362 globalGranStats.threads_created_on_PE[CurrentProc]++;
2363 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
2364 globalGranStats.tot_sq_probes++;
2365 #elif defined(PARALLEL_HASKELL)
2366 // collect parallel global statistics (currently done together with GC stats)
2367 if (RtsFlags.ParFlags.ParStats.Global &&
2368 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
2369 //debugBelch("Creating thread %d @ %11.2f\n", tso->id, usertime());
2370 globalParStats.tot_threads_created++;
2376 sched_belch("==__ schedule: Created TSO %d (%p);",
2377 CurrentProc, tso, tso->id));
2378 #elif defined(PARALLEL_HASKELL)
2379 IF_PAR_DEBUG(verbose,
2380 sched_belch("==__ schedule: Created TSO %d (%p); %d threads active",
2381 (long)tso->id, tso, advisory_thread_count));
2383 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
2384 (long)tso->id, (long)tso->stack_size));
2391 all parallel thread creation calls should fall through the following routine.
2394 createThreadFromSpark(rtsSpark spark)
2396 ASSERT(spark != (rtsSpark)NULL);
2397 // JB: TAKE CARE OF THIS COUNTER! BUGGY
2398 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
2400 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
2401 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
2402 return END_TSO_QUEUE;
2406 tso = createThread(RtsFlags.GcFlags.initialStkSize);
2407 if (tso==END_TSO_QUEUE)
2408 barf("createSparkThread: Cannot create TSO");
2410 tso->priority = AdvisoryPriority;
2412 pushClosure(tso,spark);
2414 advisory_thread_count++; // JB: TAKE CARE OF THIS COUNTER! BUGGY
2421 Turn a spark into a thread.
2422 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
2426 activateSpark (rtsSpark spark)
2430 tso = createSparkThread(spark);
2431 if (RtsFlags.ParFlags.ParStats.Full) {
2432 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
2433 IF_PAR_DEBUG(verbose,
2434 debugBelch("==^^ activateSpark: turning spark of closure %p (%s) into a thread\n",
2435 (StgClosure *)spark, info_type((StgClosure *)spark)));
2437 // ToDo: fwd info on local/global spark to thread -- HWL
2438 // tso->gran.exported = spark->exported;
2439 // tso->gran.locked = !spark->global;
2440 // tso->gran.sparkname = spark->name;
2446 /* ---------------------------------------------------------------------------
2449 * scheduleThread puts a thread on the head of the runnable queue.
2450 * This will usually be done immediately after a thread is created.
2451 * The caller of scheduleThread must create the thread using e.g.
2452 * createThread and push an appropriate closure
2453 * on this thread's stack before the scheduler is invoked.
2454 * ------------------------------------------------------------------------ */
2457 scheduleThread_(StgTSO *tso)
2459 // The thread goes at the *end* of the run-queue, to avoid possible
2460 // starvation of any threads already on the queue.
2461 APPEND_TO_RUN_QUEUE(tso);
2466 scheduleThread(StgTSO* tso)
2468 ACQUIRE_LOCK(&sched_mutex);
2469 scheduleThread_(tso);
2470 RELEASE_LOCK(&sched_mutex);
2473 #if defined(RTS_SUPPORTS_THREADS)
2474 static Condition bound_cond_cache;
2475 static int bound_cond_cache_full = 0;
2480 scheduleWaitThread(StgTSO* tso, /*[out]*/HaskellObj* ret,
2481 Capability *initialCapability)
2483 // Precondition: sched_mutex must be held
2486 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2491 m->link = main_threads;
2493 if (main_threads != NULL) {
2494 main_threads->prev = m;
2498 #if defined(RTS_SUPPORTS_THREADS)
2499 // Allocating a new condition for each thread is expensive, so we
2500 // cache one. This is a pretty feeble hack, but it helps speed up
2501 // consecutive call-ins quite a bit.
2502 if (bound_cond_cache_full) {
2503 m->bound_thread_cond = bound_cond_cache;
2504 bound_cond_cache_full = 0;
2506 initCondition(&m->bound_thread_cond);
2510 /* Put the thread on the main-threads list prior to scheduling the TSO.
2511 Failure to do so introduces a race condition in the MT case (as
2512 identified by Wolfgang Thaller), whereby the new task/OS thread
2513 created by scheduleThread_() would complete prior to the thread
2514 that spawned it managed to put 'itself' on the main-threads list.
2515 The upshot of it all being that the worker thread wouldn't get to
2516 signal the completion of the its work item for the main thread to
2517 see (==> it got stuck waiting.) -- sof 6/02.
2519 IF_DEBUG(scheduler, sched_belch("waiting for thread (%d)", tso->id));
2521 APPEND_TO_RUN_QUEUE(tso);
2522 // NB. Don't call threadRunnable() here, because the thread is
2523 // bound and only runnable by *this* OS thread, so waking up other
2524 // workers will just slow things down.
2526 return waitThread_(m, initialCapability);
2529 /* ---------------------------------------------------------------------------
2532 * Initialise the scheduler. This resets all the queues - if the
2533 * queues contained any threads, they'll be garbage collected at the
2536 * ------------------------------------------------------------------------ */
2544 for (i=0; i<=MAX_PROC; i++) {
2545 run_queue_hds[i] = END_TSO_QUEUE;
2546 run_queue_tls[i] = END_TSO_QUEUE;
2547 blocked_queue_hds[i] = END_TSO_QUEUE;
2548 blocked_queue_tls[i] = END_TSO_QUEUE;
2549 ccalling_threadss[i] = END_TSO_QUEUE;
2550 sleeping_queue = END_TSO_QUEUE;
2553 run_queue_hd = END_TSO_QUEUE;
2554 run_queue_tl = END_TSO_QUEUE;
2555 blocked_queue_hd = END_TSO_QUEUE;
2556 blocked_queue_tl = END_TSO_QUEUE;
2557 sleeping_queue = END_TSO_QUEUE;
2560 suspended_ccalling_threads = END_TSO_QUEUE;
2562 main_threads = NULL;
2563 all_threads = END_TSO_QUEUE;
2568 RtsFlags.ConcFlags.ctxtSwitchTicks =
2569 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
2571 #if defined(RTS_SUPPORTS_THREADS)
2572 /* Initialise the mutex and condition variables used by
2574 initMutex(&sched_mutex);
2575 initMutex(&term_mutex);
2578 ACQUIRE_LOCK(&sched_mutex);
2580 /* A capability holds the state a native thread needs in
2581 * order to execute STG code. At least one capability is
2582 * floating around (only SMP builds have more than one).
2586 #if defined(RTS_SUPPORTS_THREADS)
2587 /* start our haskell execution tasks */
2588 startTaskManager(0,taskStart);
2591 #if /* defined(SMP) ||*/ defined(PARALLEL_HASKELL)
2595 RELEASE_LOCK(&sched_mutex);
2599 exitScheduler( void )
2601 #if defined(RTS_SUPPORTS_THREADS)
2604 interrupted = rtsTrue;
2605 shutting_down_scheduler = rtsTrue;
2608 /* ----------------------------------------------------------------------------
2609 Managing the per-task allocation areas.
2611 Each capability comes with an allocation area. These are
2612 fixed-length block lists into which allocation can be done.
2614 ToDo: no support for two-space collection at the moment???
2615 ------------------------------------------------------------------------- */
2617 static SchedulerStatus
2618 waitThread_(StgMainThread* m, Capability *initialCapability)
2620 SchedulerStatus stat;
2622 // Precondition: sched_mutex must be held.
2623 IF_DEBUG(scheduler, sched_belch("new main thread (%d)", m->tso->id));
2626 /* GranSim specific init */
2627 CurrentTSO = m->tso; // the TSO to run
2628 procStatus[MainProc] = Busy; // status of main PE
2629 CurrentProc = MainProc; // PE to run it on
2630 schedule(m,initialCapability);
2632 schedule(m,initialCapability);
2633 ASSERT(m->stat != NoStatus);
2638 #if defined(RTS_SUPPORTS_THREADS)
2639 // Free the condition variable, returning it to the cache if possible.
2640 if (!bound_cond_cache_full) {
2641 bound_cond_cache = m->bound_thread_cond;
2642 bound_cond_cache_full = 1;
2644 closeCondition(&m->bound_thread_cond);
2648 IF_DEBUG(scheduler, sched_belch("main thread (%d) finished", m->tso->id));
2651 // Postcondition: sched_mutex still held
2655 /* ---------------------------------------------------------------------------
2656 Where are the roots that we know about?
2658 - all the threads on the runnable queue
2659 - all the threads on the blocked queue
2660 - all the threads on the sleeping queue
2661 - all the thread currently executing a _ccall_GC
2662 - all the "main threads"
2664 ------------------------------------------------------------------------ */
2666 /* This has to be protected either by the scheduler monitor, or by the
2667 garbage collection monitor (probably the latter).
2672 GetRoots( evac_fn evac )
2677 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2678 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2679 evac((StgClosure **)&run_queue_hds[i]);
2680 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2681 evac((StgClosure **)&run_queue_tls[i]);
2683 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2684 evac((StgClosure **)&blocked_queue_hds[i]);
2685 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2686 evac((StgClosure **)&blocked_queue_tls[i]);
2687 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2688 evac((StgClosure **)&ccalling_threads[i]);
2695 if (run_queue_hd != END_TSO_QUEUE) {
2696 ASSERT(run_queue_tl != END_TSO_QUEUE);
2697 evac((StgClosure **)&run_queue_hd);
2698 evac((StgClosure **)&run_queue_tl);
2701 if (blocked_queue_hd != END_TSO_QUEUE) {
2702 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2703 evac((StgClosure **)&blocked_queue_hd);
2704 evac((StgClosure **)&blocked_queue_tl);
2707 if (sleeping_queue != END_TSO_QUEUE) {
2708 evac((StgClosure **)&sleeping_queue);
2712 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2713 evac((StgClosure **)&suspended_ccalling_threads);
2716 #if defined(PARALLEL_HASKELL) || defined(GRAN)
2717 markSparkQueue(evac);
2720 #if defined(RTS_USER_SIGNALS)
2721 // mark the signal handlers (signals should be already blocked)
2722 markSignalHandlers(evac);
2726 /* -----------------------------------------------------------------------------
2729 This is the interface to the garbage collector from Haskell land.
2730 We provide this so that external C code can allocate and garbage
2731 collect when called from Haskell via _ccall_GC.
2733 It might be useful to provide an interface whereby the programmer
2734 can specify more roots (ToDo).
2736 This needs to be protected by the GC condition variable above. KH.
2737 -------------------------------------------------------------------------- */
2739 static void (*extra_roots)(evac_fn);
2744 /* Obligated to hold this lock upon entry */
2745 ACQUIRE_LOCK(&sched_mutex);
2746 GarbageCollect(GetRoots,rtsFalse);
2747 RELEASE_LOCK(&sched_mutex);
2751 performMajorGC(void)
2753 ACQUIRE_LOCK(&sched_mutex);
2754 GarbageCollect(GetRoots,rtsTrue);
2755 RELEASE_LOCK(&sched_mutex);
2759 AllRoots(evac_fn evac)
2761 GetRoots(evac); // the scheduler's roots
2762 extra_roots(evac); // the user's roots
2766 performGCWithRoots(void (*get_roots)(evac_fn))
2768 ACQUIRE_LOCK(&sched_mutex);
2769 extra_roots = get_roots;
2770 GarbageCollect(AllRoots,rtsFalse);
2771 RELEASE_LOCK(&sched_mutex);
2774 /* -----------------------------------------------------------------------------
2777 If the thread has reached its maximum stack size, then raise the
2778 StackOverflow exception in the offending thread. Otherwise
2779 relocate the TSO into a larger chunk of memory and adjust its stack
2781 -------------------------------------------------------------------------- */
2784 threadStackOverflow(StgTSO *tso)
2786 nat new_stack_size, new_tso_size, stack_words;
2790 IF_DEBUG(sanity,checkTSO(tso));
2791 if (tso->stack_size >= tso->max_stack_size) {
2794 debugBelch("@@ threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)\n",
2795 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2796 /* If we're debugging, just print out the top of the stack */
2797 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2800 /* Send this thread the StackOverflow exception */
2801 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2805 /* Try to double the current stack size. If that takes us over the
2806 * maximum stack size for this thread, then use the maximum instead.
2807 * Finally round up so the TSO ends up as a whole number of blocks.
2809 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2810 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2811 TSO_STRUCT_SIZE)/sizeof(W_);
2812 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2813 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2815 IF_DEBUG(scheduler, debugBelch("== sched: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2817 dest = (StgTSO *)allocate(new_tso_size);
2818 TICK_ALLOC_TSO(new_stack_size,0);
2820 /* copy the TSO block and the old stack into the new area */
2821 memcpy(dest,tso,TSO_STRUCT_SIZE);
2822 stack_words = tso->stack + tso->stack_size - tso->sp;
2823 new_sp = (P_)dest + new_tso_size - stack_words;
2824 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2826 /* relocate the stack pointers... */
2828 dest->stack_size = new_stack_size;
2830 /* Mark the old TSO as relocated. We have to check for relocated
2831 * TSOs in the garbage collector and any primops that deal with TSOs.
2833 * It's important to set the sp value to just beyond the end
2834 * of the stack, so we don't attempt to scavenge any part of the
2837 tso->what_next = ThreadRelocated;
2839 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2840 tso->why_blocked = NotBlocked;
2842 IF_PAR_DEBUG(verbose,
2843 debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2844 tso->id, tso, tso->stack_size);
2845 /* If we're debugging, just print out the top of the stack */
2846 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2849 IF_DEBUG(sanity,checkTSO(tso));
2851 IF_DEBUG(scheduler,printTSO(dest));
2857 /* ---------------------------------------------------------------------------
2858 Wake up a queue that was blocked on some resource.
2859 ------------------------------------------------------------------------ */
2863 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2866 #elif defined(PARALLEL_HASKELL)
2868 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2870 /* write RESUME events to log file and
2871 update blocked and fetch time (depending on type of the orig closure) */
2872 if (RtsFlags.ParFlags.ParStats.Full) {
2873 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2874 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2875 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2876 if (EMPTY_RUN_QUEUE())
2877 emitSchedule = rtsTrue;
2879 switch (get_itbl(node)->type) {
2881 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2886 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2893 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2900 static StgBlockingQueueElement *
2901 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2904 PEs node_loc, tso_loc;
2906 node_loc = where_is(node); // should be lifted out of loop
2907 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2908 tso_loc = where_is((StgClosure *)tso);
2909 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2910 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2911 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2912 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2913 // insertThread(tso, node_loc);
2914 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2916 tso, node, (rtsSpark*)NULL);
2917 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2920 } else { // TSO is remote (actually should be FMBQ)
2921 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2922 RtsFlags.GranFlags.Costs.gunblocktime +
2923 RtsFlags.GranFlags.Costs.latency;
2924 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2926 tso, node, (rtsSpark*)NULL);
2927 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2930 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2932 debugBelch(" %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2933 (node_loc==tso_loc ? "Local" : "Global"),
2934 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2935 tso->block_info.closure = NULL;
2936 IF_DEBUG(scheduler,debugBelch("-- Waking up thread %ld (%p)\n",
2939 #elif defined(PARALLEL_HASKELL)
2940 static StgBlockingQueueElement *
2941 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2943 StgBlockingQueueElement *next;
2945 switch (get_itbl(bqe)->type) {
2947 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2948 /* if it's a TSO just push it onto the run_queue */
2950 ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2951 APPEND_TO_RUN_QUEUE((StgTSO *)bqe);
2953 unblockCount(bqe, node);
2954 /* reset blocking status after dumping event */
2955 ((StgTSO *)bqe)->why_blocked = NotBlocked;
2959 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2961 bqe->link = (StgBlockingQueueElement *)PendingFetches;
2962 PendingFetches = (StgBlockedFetch *)bqe;
2966 /* can ignore this case in a non-debugging setup;
2967 see comments on RBHSave closures above */
2969 /* check that the closure is an RBHSave closure */
2970 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2971 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2972 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2976 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2977 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
2981 IF_PAR_DEBUG(bq, debugBelch(", %p (%s)\n", bqe, info_type((StgClosure*)bqe)));
2985 #else /* !GRAN && !PARALLEL_HASKELL */
2987 unblockOneLocked(StgTSO *tso)
2991 ASSERT(get_itbl(tso)->type == TSO);
2992 ASSERT(tso->why_blocked != NotBlocked);
2993 tso->why_blocked = NotBlocked;
2995 tso->link = END_TSO_QUEUE;
2996 APPEND_TO_RUN_QUEUE(tso);
2998 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", (long)tso->id));
3003 #if defined(GRAN) || defined(PARALLEL_HASKELL)
3004 INLINE_ME StgBlockingQueueElement *
3005 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
3007 ACQUIRE_LOCK(&sched_mutex);
3008 bqe = unblockOneLocked(bqe, node);
3009 RELEASE_LOCK(&sched_mutex);
3014 unblockOne(StgTSO *tso)
3016 ACQUIRE_LOCK(&sched_mutex);
3017 tso = unblockOneLocked(tso);
3018 RELEASE_LOCK(&sched_mutex);
3025 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
3027 StgBlockingQueueElement *bqe;
3032 debugBelch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): \n", \
3033 node, CurrentProc, CurrentTime[CurrentProc],
3034 CurrentTSO->id, CurrentTSO));
3036 node_loc = where_is(node);
3038 ASSERT(q == END_BQ_QUEUE ||
3039 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
3040 get_itbl(q)->type == CONSTR); // closure (type constructor)
3041 ASSERT(is_unique(node));
3043 /* FAKE FETCH: magically copy the node to the tso's proc;
3044 no Fetch necessary because in reality the node should not have been
3045 moved to the other PE in the first place
3047 if (CurrentProc!=node_loc) {
3049 debugBelch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)\n",
3050 node, node_loc, CurrentProc, CurrentTSO->id,
3051 // CurrentTSO, where_is(CurrentTSO),
3052 node->header.gran.procs));
3053 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
3055 debugBelch("## new bitmask of node %p is %#x\n",
3056 node, node->header.gran.procs));
3057 if (RtsFlags.GranFlags.GranSimStats.Global) {
3058 globalGranStats.tot_fake_fetches++;
3063 // ToDo: check: ASSERT(CurrentProc==node_loc);
3064 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
3067 bqe points to the current element in the queue
3068 next points to the next element in the queue
3070 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
3071 //tso_loc = where_is(tso);
3073 bqe = unblockOneLocked(bqe, node);
3076 /* if this is the BQ of an RBH, we have to put back the info ripped out of
3077 the closure to make room for the anchor of the BQ */
3078 if (bqe!=END_BQ_QUEUE) {
3079 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
3081 ASSERT((info_ptr==&RBH_Save_0_info) ||
3082 (info_ptr==&RBH_Save_1_info) ||
3083 (info_ptr==&RBH_Save_2_info));
3085 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
3086 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
3087 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
3090 debugBelch("## Filled in RBH_Save for %p (%s) at end of AwBQ\n",
3091 node, info_type(node)));
3094 /* statistics gathering */
3095 if (RtsFlags.GranFlags.GranSimStats.Global) {
3096 // globalGranStats.tot_bq_processing_time += bq_processing_time;
3097 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
3098 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
3099 globalGranStats.tot_awbq++; // total no. of bqs awakened
3102 debugBelch("## BQ Stats of %p: [%d entries] %s\n",
3103 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
3105 #elif defined(PARALLEL_HASKELL)
3107 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
3109 StgBlockingQueueElement *bqe;
3111 ACQUIRE_LOCK(&sched_mutex);
3113 IF_PAR_DEBUG(verbose,
3114 debugBelch("##-_ AwBQ for node %p on [%x]: \n",
3118 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
3119 IF_PAR_DEBUG(verbose, debugBelch("## ... nothing to unblock so lets just return. RFP (BUG?)\n"));
3124 ASSERT(q == END_BQ_QUEUE ||
3125 get_itbl(q)->type == TSO ||
3126 get_itbl(q)->type == BLOCKED_FETCH ||
3127 get_itbl(q)->type == CONSTR);
3130 while (get_itbl(bqe)->type==TSO ||
3131 get_itbl(bqe)->type==BLOCKED_FETCH) {
3132 bqe = unblockOneLocked(bqe, node);
3134 RELEASE_LOCK(&sched_mutex);
3137 #else /* !GRAN && !PARALLEL_HASKELL */
3140 awakenBlockedQueueNoLock(StgTSO *tso)
3142 while (tso != END_TSO_QUEUE) {
3143 tso = unblockOneLocked(tso);
3148 awakenBlockedQueue(StgTSO *tso)
3150 ACQUIRE_LOCK(&sched_mutex);
3151 while (tso != END_TSO_QUEUE) {
3152 tso = unblockOneLocked(tso);
3154 RELEASE_LOCK(&sched_mutex);
3158 /* ---------------------------------------------------------------------------
3160 - usually called inside a signal handler so it mustn't do anything fancy.
3161 ------------------------------------------------------------------------ */
3164 interruptStgRts(void)
3170 /* -----------------------------------------------------------------------------
3173 This is for use when we raise an exception in another thread, which
3175 This has nothing to do with the UnblockThread event in GranSim. -- HWL
3176 -------------------------------------------------------------------------- */
3178 #if defined(GRAN) || defined(PARALLEL_HASKELL)
3180 NB: only the type of the blocking queue is different in GranSim and GUM
3181 the operations on the queue-elements are the same
3182 long live polymorphism!
3184 Locks: sched_mutex is held upon entry and exit.
3188 unblockThread(StgTSO *tso)
3190 StgBlockingQueueElement *t, **last;
3192 switch (tso->why_blocked) {
3195 return; /* not blocked */
3198 // Be careful: nothing to do here! We tell the scheduler that the thread
3199 // is runnable and we leave it to the stack-walking code to abort the
3200 // transaction while unwinding the stack. We should perhaps have a debugging
3201 // test to make sure that this really happens and that the 'zombie' transaction
3202 // does not get committed.
3206 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3208 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
3209 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3211 last = (StgBlockingQueueElement **)&mvar->head;
3212 for (t = (StgBlockingQueueElement *)mvar->head;
3214 last = &t->link, last_tso = t, t = t->link) {
3215 if (t == (StgBlockingQueueElement *)tso) {
3216 *last = (StgBlockingQueueElement *)tso->link;
3217 if (mvar->tail == tso) {
3218 mvar->tail = (StgTSO *)last_tso;
3223 barf("unblockThread (MVAR): TSO not found");
3226 case BlockedOnBlackHole:
3227 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3229 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3231 last = &bq->blocking_queue;
3232 for (t = bq->blocking_queue;
3234 last = &t->link, t = t->link) {
3235 if (t == (StgBlockingQueueElement *)tso) {
3236 *last = (StgBlockingQueueElement *)tso->link;
3240 barf("unblockThread (BLACKHOLE): TSO not found");
3243 case BlockedOnException:
3245 StgTSO *target = tso->block_info.tso;
3247 ASSERT(get_itbl(target)->type == TSO);
3249 if (target->what_next == ThreadRelocated) {
3250 target = target->link;
3251 ASSERT(get_itbl(target)->type == TSO);
3254 ASSERT(target->blocked_exceptions != NULL);
3256 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
3257 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
3259 last = &t->link, t = t->link) {
3260 ASSERT(get_itbl(t)->type == TSO);
3261 if (t == (StgBlockingQueueElement *)tso) {
3262 *last = (StgBlockingQueueElement *)tso->link;
3266 barf("unblockThread (Exception): TSO not found");
3270 case BlockedOnWrite:
3271 #if defined(mingw32_HOST_OS)
3272 case BlockedOnDoProc:
3275 /* take TSO off blocked_queue */
3276 StgBlockingQueueElement *prev = NULL;
3277 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
3278 prev = t, t = t->link) {
3279 if (t == (StgBlockingQueueElement *)tso) {
3281 blocked_queue_hd = (StgTSO *)t->link;
3282 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3283 blocked_queue_tl = END_TSO_QUEUE;
3286 prev->link = t->link;
3287 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3288 blocked_queue_tl = (StgTSO *)prev;
3294 barf("unblockThread (I/O): TSO not found");
3297 case BlockedOnDelay:
3299 /* take TSO off sleeping_queue */
3300 StgBlockingQueueElement *prev = NULL;
3301 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
3302 prev = t, t = t->link) {
3303 if (t == (StgBlockingQueueElement *)tso) {
3305 sleeping_queue = (StgTSO *)t->link;
3307 prev->link = t->link;
3312 barf("unblockThread (delay): TSO not found");
3316 barf("unblockThread");
3320 tso->link = END_TSO_QUEUE;
3321 tso->why_blocked = NotBlocked;
3322 tso->block_info.closure = NULL;
3323 PUSH_ON_RUN_QUEUE(tso);
3327 unblockThread(StgTSO *tso)
3331 /* To avoid locking unnecessarily. */
3332 if (tso->why_blocked == NotBlocked) {
3336 switch (tso->why_blocked) {
3339 // Be careful: nothing to do here! We tell the scheduler that the thread
3340 // is runnable and we leave it to the stack-walking code to abort the
3341 // transaction while unwinding the stack. We should perhaps have a debugging
3342 // test to make sure that this really happens and that the 'zombie' transaction
3343 // does not get committed.
3347 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3349 StgTSO *last_tso = END_TSO_QUEUE;
3350 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3353 for (t = mvar->head; t != END_TSO_QUEUE;
3354 last = &t->link, last_tso = t, t = t->link) {
3357 if (mvar->tail == tso) {
3358 mvar->tail = last_tso;
3363 barf("unblockThread (MVAR): TSO not found");
3366 case BlockedOnBlackHole:
3367 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3369 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3371 last = &bq->blocking_queue;
3372 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
3373 last = &t->link, t = t->link) {
3379 barf("unblockThread (BLACKHOLE): TSO not found");
3382 case BlockedOnException:
3384 StgTSO *target = tso->block_info.tso;
3386 ASSERT(get_itbl(target)->type == TSO);
3388 while (target->what_next == ThreadRelocated) {
3389 target = target->link;
3390 ASSERT(get_itbl(target)->type == TSO);
3393 ASSERT(target->blocked_exceptions != NULL);
3395 last = &target->blocked_exceptions;
3396 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
3397 last = &t->link, t = t->link) {
3398 ASSERT(get_itbl(t)->type == TSO);
3404 barf("unblockThread (Exception): TSO not found");
3408 case BlockedOnWrite:
3409 #if defined(mingw32_HOST_OS)
3410 case BlockedOnDoProc:
3413 StgTSO *prev = NULL;
3414 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
3415 prev = t, t = t->link) {
3418 blocked_queue_hd = t->link;
3419 if (blocked_queue_tl == t) {
3420 blocked_queue_tl = END_TSO_QUEUE;
3423 prev->link = t->link;
3424 if (blocked_queue_tl == t) {
3425 blocked_queue_tl = prev;
3431 barf("unblockThread (I/O): TSO not found");
3434 case BlockedOnDelay:
3436 StgTSO *prev = NULL;
3437 for (t = sleeping_queue; t != END_TSO_QUEUE;
3438 prev = t, t = t->link) {
3441 sleeping_queue = t->link;
3443 prev->link = t->link;
3448 barf("unblockThread (delay): TSO not found");
3452 barf("unblockThread");
3456 tso->link = END_TSO_QUEUE;
3457 tso->why_blocked = NotBlocked;
3458 tso->block_info.closure = NULL;
3459 APPEND_TO_RUN_QUEUE(tso);
3463 /* -----------------------------------------------------------------------------
3466 * The following function implements the magic for raising an
3467 * asynchronous exception in an existing thread.
3469 * We first remove the thread from any queue on which it might be
3470 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
3472 * We strip the stack down to the innermost CATCH_FRAME, building
3473 * thunks in the heap for all the active computations, so they can
3474 * be restarted if necessary. When we reach a CATCH_FRAME, we build
3475 * an application of the handler to the exception, and push it on
3476 * the top of the stack.
3478 * How exactly do we save all the active computations? We create an
3479 * AP_STACK for every UpdateFrame on the stack. Entering one of these
3480 * AP_STACKs pushes everything from the corresponding update frame
3481 * upwards onto the stack. (Actually, it pushes everything up to the
3482 * next update frame plus a pointer to the next AP_STACK object.
3483 * Entering the next AP_STACK object pushes more onto the stack until we
3484 * reach the last AP_STACK object - at which point the stack should look
3485 * exactly as it did when we killed the TSO and we can continue
3486 * execution by entering the closure on top of the stack.
3488 * We can also kill a thread entirely - this happens if either (a) the
3489 * exception passed to raiseAsync is NULL, or (b) there's no
3490 * CATCH_FRAME on the stack. In either case, we strip the entire
3491 * stack and replace the thread with a zombie.
3493 * Locks: sched_mutex held upon entry nor exit.
3495 * -------------------------------------------------------------------------- */
3498 deleteThread(StgTSO *tso)
3500 if (tso->why_blocked != BlockedOnCCall &&
3501 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
3502 raiseAsync(tso,NULL);
3506 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
3508 deleteThreadImmediately(StgTSO *tso)
3509 { // for forkProcess only:
3510 // delete thread without giving it a chance to catch the KillThread exception
3512 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3516 if (tso->why_blocked != BlockedOnCCall &&
3517 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
3521 tso->what_next = ThreadKilled;
3526 raiseAsyncWithLock(StgTSO *tso, StgClosure *exception)
3528 /* When raising async exs from contexts where sched_mutex isn't held;
3529 use raiseAsyncWithLock(). */
3530 ACQUIRE_LOCK(&sched_mutex);
3531 raiseAsync(tso,exception);
3532 RELEASE_LOCK(&sched_mutex);
3536 raiseAsync(StgTSO *tso, StgClosure *exception)
3538 raiseAsync_(tso, exception, rtsFalse);
3542 raiseAsync_(StgTSO *tso, StgClosure *exception, rtsBool stop_at_atomically)
3544 StgRetInfoTable *info;
3547 // Thread already dead?
3548 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3553 sched_belch("raising exception in thread %ld.", (long)tso->id));
3555 // Remove it from any blocking queues
3560 // The stack freezing code assumes there's a closure pointer on
3561 // the top of the stack, so we have to arrange that this is the case...
3563 if (sp[0] == (W_)&stg_enter_info) {
3567 sp[0] = (W_)&stg_dummy_ret_closure;
3573 // 1. Let the top of the stack be the "current closure"
3575 // 2. Walk up the stack until we find either an UPDATE_FRAME or a
3578 // 3. If it's an UPDATE_FRAME, then make an AP_STACK containing the
3579 // current closure applied to the chunk of stack up to (but not
3580 // including) the update frame. This closure becomes the "current
3581 // closure". Go back to step 2.
3583 // 4. If it's a CATCH_FRAME, then leave the exception handler on
3584 // top of the stack applied to the exception.
3586 // 5. If it's a STOP_FRAME, then kill the thread.
3588 // NB: if we pass an ATOMICALLY_FRAME then abort the associated
3595 info = get_ret_itbl((StgClosure *)frame);
3597 while (info->i.type != UPDATE_FRAME
3598 && (info->i.type != CATCH_FRAME || exception == NULL)
3599 && info->i.type != STOP_FRAME
3600 && (info->i.type != ATOMICALLY_FRAME || stop_at_atomically == rtsFalse))
3602 if (info->i.type == CATCH_RETRY_FRAME || info->i.type == ATOMICALLY_FRAME) {
3603 // IF we find an ATOMICALLY_FRAME then we abort the
3604 // current transaction and propagate the exception. In
3605 // this case (unlike ordinary exceptions) we do not care
3606 // whether the transaction is valid or not because its
3607 // possible validity cannot have caused the exception
3608 // and will not be visible after the abort.
3610 debugBelch("Found atomically block delivering async exception\n"));
3611 stmAbortTransaction(tso -> trec);
3612 tso -> trec = stmGetEnclosingTRec(tso -> trec);
3614 frame += stack_frame_sizeW((StgClosure *)frame);
3615 info = get_ret_itbl((StgClosure *)frame);
3618 switch (info->i.type) {
3620 case ATOMICALLY_FRAME:
3621 ASSERT(stop_at_atomically);
3622 ASSERT(stmGetEnclosingTRec(tso->trec) == NO_TREC);
3623 stmCondemnTransaction(tso -> trec);
3627 // R1 is not a register: the return convention for IO in
3628 // this case puts the return value on the stack, so we
3629 // need to set up the stack to return to the atomically
3630 // frame properly...
3631 tso->sp = frame - 2;
3632 tso->sp[1] = (StgWord) &stg_NO_FINALIZER_closure; // why not?
3633 tso->sp[0] = (StgWord) &stg_ut_1_0_unreg_info;
3635 tso->what_next = ThreadRunGHC;
3639 // If we find a CATCH_FRAME, and we've got an exception to raise,
3640 // then build the THUNK raise(exception), and leave it on
3641 // top of the CATCH_FRAME ready to enter.
3645 StgCatchFrame *cf = (StgCatchFrame *)frame;
3649 // we've got an exception to raise, so let's pass it to the
3650 // handler in this frame.
3652 raise = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3653 TICK_ALLOC_SE_THK(1,0);
3654 SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
3655 raise->payload[0] = exception;
3657 // throw away the stack from Sp up to the CATCH_FRAME.
3661 /* Ensure that async excpetions are blocked now, so we don't get
3662 * a surprise exception before we get around to executing the
3665 if (tso->blocked_exceptions == NULL) {
3666 tso->blocked_exceptions = END_TSO_QUEUE;
3669 /* Put the newly-built THUNK on top of the stack, ready to execute
3670 * when the thread restarts.
3673 sp[-1] = (W_)&stg_enter_info;
3675 tso->what_next = ThreadRunGHC;
3676 IF_DEBUG(sanity, checkTSO(tso));
3685 // First build an AP_STACK consisting of the stack chunk above the
3686 // current update frame, with the top word on the stack as the
3689 words = frame - sp - 1;
3690 ap = (StgAP_STACK *)allocate(PAP_sizeW(words));
3693 ap->fun = (StgClosure *)sp[0];
3695 for(i=0; i < (nat)words; ++i) {
3696 ap->payload[i] = (StgClosure *)*sp++;
3699 SET_HDR(ap,&stg_AP_STACK_info,
3700 ((StgClosure *)frame)->header.prof.ccs /* ToDo */);
3701 TICK_ALLOC_UP_THK(words+1,0);
3704 debugBelch("sched: Updating ");
3705 printPtr((P_)((StgUpdateFrame *)frame)->updatee);
3706 debugBelch(" with ");
3707 printObj((StgClosure *)ap);
3710 // Replace the updatee with an indirection - happily
3711 // this will also wake up any threads currently
3712 // waiting on the result.
3714 // Warning: if we're in a loop, more than one update frame on
3715 // the stack may point to the same object. Be careful not to
3716 // overwrite an IND_OLDGEN in this case, because we'll screw
3717 // up the mutable lists. To be on the safe side, don't
3718 // overwrite any kind of indirection at all. See also
3719 // threadSqueezeStack in GC.c, where we have to make a similar
3722 if (!closure_IND(((StgUpdateFrame *)frame)->updatee)) {
3723 // revert the black hole
3724 UPD_IND_NOLOCK(((StgUpdateFrame *)frame)->updatee,
3727 sp += sizeofW(StgUpdateFrame) - 1;
3728 sp[0] = (W_)ap; // push onto stack
3733 // We've stripped the entire stack, the thread is now dead.
3734 sp += sizeofW(StgStopFrame);
3735 tso->what_next = ThreadKilled;
3746 /* -----------------------------------------------------------------------------
3747 raiseExceptionHelper
3749 This function is called by the raise# primitve, just so that we can
3750 move some of the tricky bits of raising an exception from C-- into
3751 C. Who knows, it might be a useful re-useable thing here too.
3752 -------------------------------------------------------------------------- */
3755 raiseExceptionHelper (StgTSO *tso, StgClosure *exception)
3757 StgClosure *raise_closure = NULL;
3759 StgRetInfoTable *info;
3761 // This closure represents the expression 'raise# E' where E
3762 // is the exception raise. It is used to overwrite all the
3763 // thunks which are currently under evaluataion.
3767 // LDV profiling: stg_raise_info has THUNK as its closure
3768 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
3769 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
3770 // 1 does not cause any problem unless profiling is performed.
3771 // However, when LDV profiling goes on, we need to linearly scan
3772 // small object pool, where raise_closure is stored, so we should
3773 // use MIN_UPD_SIZE.
3775 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
3776 // sizeofW(StgClosure)+1);
3780 // Walk up the stack, looking for the catch frame. On the way,
3781 // we update any closures pointed to from update frames with the
3782 // raise closure that we just built.
3786 info = get_ret_itbl((StgClosure *)p);
3787 next = p + stack_frame_sizeW((StgClosure *)p);
3788 switch (info->i.type) {
3791 // Only create raise_closure if we need to.
3792 if (raise_closure == NULL) {
3794 (StgClosure *)allocate(sizeofW(StgClosure)+MIN_UPD_SIZE);
3795 SET_HDR(raise_closure, &stg_raise_info, CCCS);
3796 raise_closure->payload[0] = exception;
3798 UPD_IND(((StgUpdateFrame *)p)->updatee,raise_closure);
3802 case ATOMICALLY_FRAME:
3803 IF_DEBUG(stm, debugBelch("Found ATOMICALLY_FRAME at %p\n", p));
3805 return ATOMICALLY_FRAME;
3811 case CATCH_STM_FRAME:
3812 IF_DEBUG(stm, debugBelch("Found CATCH_STM_FRAME at %p\n", p));
3814 return CATCH_STM_FRAME;
3820 case CATCH_RETRY_FRAME:
3829 /* -----------------------------------------------------------------------------
3830 findRetryFrameHelper
3832 This function is called by the retry# primitive. It traverses the stack
3833 leaving tso->sp referring to the frame which should handle the retry.
3835 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
3836 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
3838 We skip CATCH_STM_FRAMEs because retries are not considered to be exceptions,
3839 despite the similar implementation.
3841 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
3842 not be created within memory transactions.
3843 -------------------------------------------------------------------------- */
3846 findRetryFrameHelper (StgTSO *tso)
3849 StgRetInfoTable *info;
3853 info = get_ret_itbl((StgClosure *)p);
3854 next = p + stack_frame_sizeW((StgClosure *)p);
3855 switch (info->i.type) {
3857 case ATOMICALLY_FRAME:
3858 IF_DEBUG(stm, debugBelch("Found ATOMICALLY_FRAME at %p during retrry\n", p));
3860 return ATOMICALLY_FRAME;
3862 case CATCH_RETRY_FRAME:
3863 IF_DEBUG(stm, debugBelch("Found CATCH_RETRY_FRAME at %p during retrry\n", p));
3865 return CATCH_RETRY_FRAME;
3867 case CATCH_STM_FRAME:
3869 ASSERT(info->i.type != CATCH_FRAME);
3870 ASSERT(info->i.type != STOP_FRAME);
3877 /* -----------------------------------------------------------------------------
3878 resurrectThreads is called after garbage collection on the list of
3879 threads found to be garbage. Each of these threads will be woken
3880 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3881 on an MVar, or NonTermination if the thread was blocked on a Black
3884 Locks: sched_mutex isn't held upon entry nor exit.
3885 -------------------------------------------------------------------------- */
3888 resurrectThreads( StgTSO *threads )
3892 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3893 next = tso->global_link;
3894 tso->global_link = all_threads;
3896 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3898 switch (tso->why_blocked) {
3900 case BlockedOnException:
3901 /* Called by GC - sched_mutex lock is currently held. */
3902 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3904 case BlockedOnBlackHole:
3905 raiseAsync(tso,(StgClosure *)NonTermination_closure);
3908 raiseAsync(tso,(StgClosure *)BlockedIndefinitely_closure);
3911 /* This might happen if the thread was blocked on a black hole
3912 * belonging to a thread that we've just woken up (raiseAsync
3913 * can wake up threads, remember...).
3917 barf("resurrectThreads: thread blocked in a strange way");
3922 /* ----------------------------------------------------------------------------
3923 * Debugging: why is a thread blocked
3924 * [Also provides useful information when debugging threaded programs
3925 * at the Haskell source code level, so enable outside of DEBUG. --sof 7/02]
3926 ------------------------------------------------------------------------- */
3929 printThreadBlockage(StgTSO *tso)
3931 switch (tso->why_blocked) {
3933 debugBelch("is blocked on read from fd %d", tso->block_info.fd);
3935 case BlockedOnWrite:
3936 debugBelch("is blocked on write to fd %d", tso->block_info.fd);
3938 #if defined(mingw32_HOST_OS)
3939 case BlockedOnDoProc:
3940 debugBelch("is blocked on proc (request: %d)", tso->block_info.async_result->reqID);
3943 case BlockedOnDelay:
3944 debugBelch("is blocked until %d", tso->block_info.target);
3947 debugBelch("is blocked on an MVar");
3949 case BlockedOnException:
3950 debugBelch("is blocked on delivering an exception to thread %d",
3951 tso->block_info.tso->id);
3953 case BlockedOnBlackHole:
3954 debugBelch("is blocked on a black hole");
3957 debugBelch("is not blocked");
3959 #if defined(PARALLEL_HASKELL)
3961 debugBelch("is blocked on global address; local FM_BQ is %p (%s)",
3962 tso->block_info.closure, info_type(tso->block_info.closure));
3964 case BlockedOnGA_NoSend:
3965 debugBelch("is blocked on global address (no send); local FM_BQ is %p (%s)",
3966 tso->block_info.closure, info_type(tso->block_info.closure));
3969 case BlockedOnCCall:
3970 debugBelch("is blocked on an external call");
3972 case BlockedOnCCall_NoUnblockExc:
3973 debugBelch("is blocked on an external call (exceptions were already blocked)");
3976 debugBelch("is blocked on an STM operation");
3979 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3980 tso->why_blocked, tso->id, tso);
3985 printThreadStatus(StgTSO *tso)
3987 switch (tso->what_next) {
3989 debugBelch("has been killed");
3991 case ThreadComplete:
3992 debugBelch("has completed");
3995 printThreadBlockage(tso);
4000 printAllThreads(void)
4005 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
4006 ullong_format_string(TIME_ON_PROC(CurrentProc),
4007 time_string, rtsFalse/*no commas!*/);
4009 debugBelch("all threads at [%s]:\n", time_string);
4010 # elif defined(PARALLEL_HASKELL)
4011 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
4012 ullong_format_string(CURRENT_TIME,
4013 time_string, rtsFalse/*no commas!*/);
4015 debugBelch("all threads at [%s]:\n", time_string);
4017 debugBelch("all threads:\n");
4020 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
4021 debugBelch("\tthread %d @ %p ", t->id, (void *)t);
4024 void *label = lookupThreadLabel(t->id);
4025 if (label) debugBelch("[\"%s\"] ",(char *)label);
4028 printThreadStatus(t);
4036 Print a whole blocking queue attached to node (debugging only).
4038 # if defined(PARALLEL_HASKELL)
4040 print_bq (StgClosure *node)
4042 StgBlockingQueueElement *bqe;
4046 debugBelch("## BQ of closure %p (%s): ",
4047 node, info_type(node));
4049 /* should cover all closures that may have a blocking queue */
4050 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
4051 get_itbl(node)->type == FETCH_ME_BQ ||
4052 get_itbl(node)->type == RBH ||
4053 get_itbl(node)->type == MVAR);
4055 ASSERT(node!=(StgClosure*)NULL); // sanity check
4057 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
4061 Print a whole blocking queue starting with the element bqe.
4064 print_bqe (StgBlockingQueueElement *bqe)
4069 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
4071 for (end = (bqe==END_BQ_QUEUE);
4072 !end; // iterate until bqe points to a CONSTR
4073 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
4074 bqe = end ? END_BQ_QUEUE : bqe->link) {
4075 ASSERT(bqe != END_BQ_QUEUE); // sanity check
4076 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
4077 /* types of closures that may appear in a blocking queue */
4078 ASSERT(get_itbl(bqe)->type == TSO ||
4079 get_itbl(bqe)->type == BLOCKED_FETCH ||
4080 get_itbl(bqe)->type == CONSTR);
4081 /* only BQs of an RBH end with an RBH_Save closure */
4082 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
4084 switch (get_itbl(bqe)->type) {
4086 debugBelch(" TSO %u (%x),",
4087 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
4090 debugBelch(" BF (node=%p, ga=((%x, %d, %x)),",
4091 ((StgBlockedFetch *)bqe)->node,
4092 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
4093 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
4094 ((StgBlockedFetch *)bqe)->ga.weight);
4097 debugBelch(" %s (IP %p),",
4098 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
4099 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
4100 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
4101 "RBH_Save_?"), get_itbl(bqe));
4104 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
4105 info_type((StgClosure *)bqe)); // , node, info_type(node));
4111 # elif defined(GRAN)
4113 print_bq (StgClosure *node)
4115 StgBlockingQueueElement *bqe;
4116 PEs node_loc, tso_loc;
4119 /* should cover all closures that may have a blocking queue */
4120 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
4121 get_itbl(node)->type == FETCH_ME_BQ ||
4122 get_itbl(node)->type == RBH);
4124 ASSERT(node!=(StgClosure*)NULL); // sanity check
4125 node_loc = where_is(node);
4127 debugBelch("## BQ of closure %p (%s) on [PE %d]: ",
4128 node, info_type(node), node_loc);
4131 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
4133 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
4134 !end; // iterate until bqe points to a CONSTR
4135 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
4136 ASSERT(bqe != END_BQ_QUEUE); // sanity check
4137 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
4138 /* types of closures that may appear in a blocking queue */
4139 ASSERT(get_itbl(bqe)->type == TSO ||
4140 get_itbl(bqe)->type == CONSTR);
4141 /* only BQs of an RBH end with an RBH_Save closure */
4142 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
4144 tso_loc = where_is((StgClosure *)bqe);
4145 switch (get_itbl(bqe)->type) {
4147 debugBelch(" TSO %d (%p) on [PE %d],",
4148 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
4151 debugBelch(" %s (IP %p),",
4152 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
4153 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
4154 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
4155 "RBH_Save_?"), get_itbl(bqe));
4158 barf("Unexpected closure type %s in blocking queue of %p (%s)",
4159 info_type((StgClosure *)bqe), node, info_type(node));
4167 Nice and easy: only TSOs on the blocking queue
4170 print_bq (StgClosure *node)
4174 ASSERT(node!=(StgClosure*)NULL); // sanity check
4175 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
4176 tso != END_TSO_QUEUE;
4178 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
4179 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
4180 debugBelch(" TSO %d (%p),", tso->id, tso);
4186 #if defined(PARALLEL_HASKELL)
4193 for (i=0, tso=run_queue_hd;
4194 tso != END_TSO_QUEUE;
4203 sched_belch(char *s, ...)
4207 #ifdef RTS_SUPPORTS_THREADS
4208 debugBelch("sched (task %p): ", osThreadId());
4209 #elif defined(PARALLEL_HASKELL)
4212 debugBelch("sched: ");