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 *blackhole_queue = NULL;
149 StgTSO *sleeping_queue = NULL; /* perhaps replace with a hash table? */
153 /* The blackhole_queue should be checked for threads to wake up. See
154 * Schedule.h for more thorough comment.
156 rtsBool blackholes_need_checking = rtsFalse;
158 /* Linked list of all threads.
159 * Used for detecting garbage collected threads.
161 StgTSO *all_threads = NULL;
163 /* When a thread performs a safe C call (_ccall_GC, using old
164 * terminology), it gets put on the suspended_ccalling_threads
165 * list. Used by the garbage collector.
167 static StgTSO *suspended_ccalling_threads;
169 /* KH: The following two flags are shared memory locations. There is no need
170 to lock them, since they are only unset at the end of a scheduler
174 /* flag set by signal handler to precipitate a context switch */
175 int context_switch = 0;
177 /* flag that tracks whether we have done any execution in this time slice. */
178 nat recent_activity = ACTIVITY_YES;
180 /* if this flag is set as well, give up execution */
181 rtsBool interrupted = rtsFalse;
183 /* Next thread ID to allocate.
184 * Locks required: thread_id_mutex
186 static StgThreadID next_thread_id = 1;
189 * Pointers to the state of the current thread.
190 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
191 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
194 /* The smallest stack size that makes any sense is:
195 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
196 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
197 * + 1 (the closure to enter)
199 * + 1 (spare slot req'd by stg_ap_v_ret)
201 * A thread with this stack will bomb immediately with a stack
202 * overflow, which will increase its stack size.
205 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 3)
212 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
213 * exists - earlier gccs apparently didn't.
219 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
220 * in an MT setting, needed to signal that a worker thread shouldn't hang around
221 * in the scheduler when it is out of work.
223 static rtsBool shutting_down_scheduler = rtsFalse;
225 #if defined(RTS_SUPPORTS_THREADS)
226 /* ToDo: carefully document the invariants that go together
227 * with these synchronisation objects.
229 Mutex sched_mutex = INIT_MUTEX_VAR;
230 Mutex term_mutex = INIT_MUTEX_VAR;
232 #endif /* RTS_SUPPORTS_THREADS */
234 #if defined(PARALLEL_HASKELL)
236 rtsTime TimeOfLastYield;
237 rtsBool emitSchedule = rtsTrue;
241 static char *whatNext_strs[] = {
251 /* -----------------------------------------------------------------------------
252 * static function prototypes
253 * -------------------------------------------------------------------------- */
255 #if defined(RTS_SUPPORTS_THREADS)
256 static void taskStart(void);
259 static void schedule( StgMainThread *mainThread USED_WHEN_RTS_SUPPORTS_THREADS,
260 Capability *initialCapability );
263 // These function all encapsulate parts of the scheduler loop, and are
264 // abstracted only to make the structure and control flow of the
265 // scheduler clearer.
267 static void schedulePreLoop(void);
268 static void scheduleStartSignalHandlers(void);
269 static void scheduleCheckBlockedThreads(void);
270 static void scheduleCheckBlackHoles(void);
271 static void scheduleDetectDeadlock(void);
273 static StgTSO *scheduleProcessEvent(rtsEvent *event);
275 #if defined(PARALLEL_HASKELL)
276 static StgTSO *scheduleSendPendingMessages(void);
277 static void scheduleActivateSpark(void);
278 static rtsBool scheduleGetRemoteWork(rtsBool *receivedFinish);
280 #if defined(PAR) || defined(GRAN)
281 static void scheduleGranParReport(void);
283 static void schedulePostRunThread(void);
284 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
285 static void scheduleHandleStackOverflow( StgTSO *t);
286 static rtsBool scheduleHandleYield( StgTSO *t, nat prev_what_next );
287 static void scheduleHandleThreadBlocked( StgTSO *t );
288 static rtsBool scheduleHandleThreadFinished( StgMainThread *mainThread,
289 Capability *cap, StgTSO *t );
290 static rtsBool scheduleDoHeapProfile(rtsBool ready_to_gc);
291 static void scheduleDoGC(Capability *cap);
293 static void unblockThread(StgTSO *tso);
294 static rtsBool checkBlackHoles(void);
295 static SchedulerStatus waitThread_(/*out*/StgMainThread* m,
296 Capability *initialCapability
298 static void scheduleThread_ (StgTSO* tso);
299 static void AllRoots(evac_fn evac);
301 static StgTSO *threadStackOverflow(StgTSO *tso);
303 static void raiseAsync_(StgTSO *tso, StgClosure *exception,
304 rtsBool stop_at_atomically);
306 static void printThreadBlockage(StgTSO *tso);
307 static void printThreadStatus(StgTSO *tso);
309 #if defined(PARALLEL_HASKELL)
310 StgTSO * createSparkThread(rtsSpark spark);
311 StgTSO * activateSpark (rtsSpark spark);
314 /* ----------------------------------------------------------------------------
316 * ------------------------------------------------------------------------- */
318 #if defined(RTS_SUPPORTS_THREADS)
319 static nat startingWorkerThread = 0;
324 ACQUIRE_LOCK(&sched_mutex);
325 startingWorkerThread--;
328 RELEASE_LOCK(&sched_mutex);
332 startSchedulerTaskIfNecessary(void)
334 if ( !EMPTY_RUN_QUEUE()
335 && !shutting_down_scheduler // not if we're shutting down
336 && startingWorkerThread==0)
338 // we don't want to start another worker thread
339 // just because the last one hasn't yet reached the
340 // "waiting for capability" state
341 startingWorkerThread++;
342 if (!maybeStartNewWorker(taskStart)) {
343 startingWorkerThread--;
349 /* -----------------------------------------------------------------------------
350 * Putting a thread on the run queue: different scheduling policies
351 * -------------------------------------------------------------------------- */
354 addToRunQueue( StgTSO *t )
356 #if defined(PARALLEL_HASKELL)
357 if (RtsFlags.ParFlags.doFairScheduling) {
358 // this does round-robin scheduling; good for concurrency
359 APPEND_TO_RUN_QUEUE(t);
361 // this does unfair scheduling; good for parallelism
362 PUSH_ON_RUN_QUEUE(t);
365 // this does round-robin scheduling; good for concurrency
366 APPEND_TO_RUN_QUEUE(t);
370 /* ---------------------------------------------------------------------------
371 Main scheduling loop.
373 We use round-robin scheduling, each thread returning to the
374 scheduler loop when one of these conditions is detected:
377 * timer expires (thread yields)
382 Locking notes: we acquire the scheduler lock once at the beginning
383 of the scheduler loop, and release it when
385 * running a thread, or
386 * waiting for work, or
387 * waiting for a GC to complete.
390 In a GranSim setup this loop iterates over the global event queue.
391 This revolves around the global event queue, which determines what
392 to do next. Therefore, it's more complicated than either the
393 concurrent or the parallel (GUM) setup.
396 GUM iterates over incoming messages.
397 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
398 and sends out a fish whenever it has nothing to do; in-between
399 doing the actual reductions (shared code below) it processes the
400 incoming messages and deals with delayed operations
401 (see PendingFetches).
402 This is not the ugliest code you could imagine, but it's bloody close.
404 ------------------------------------------------------------------------ */
407 schedule( StgMainThread *mainThread USED_WHEN_RTS_SUPPORTS_THREADS,
408 Capability *initialCapability )
412 StgThreadReturnCode ret;
415 #elif defined(PARALLEL_HASKELL)
418 rtsBool receivedFinish = rtsFalse;
420 nat tp_size, sp_size; // stats only
426 // Pre-condition: sched_mutex is held.
427 // We might have a capability, passed in as initialCapability.
428 cap = initialCapability;
430 #if !defined(RTS_SUPPORTS_THREADS)
431 // simply initialise it in the non-threaded case
432 grabCapability(&cap);
436 sched_belch("### NEW SCHEDULER LOOP (main thr: %p, cap: %p)",
437 mainThread, initialCapability);
442 // -----------------------------------------------------------
443 // Scheduler loop starts here:
445 #if defined(PARALLEL_HASKELL)
446 #define TERMINATION_CONDITION (!receivedFinish)
448 #define TERMINATION_CONDITION ((event = get_next_event()) != (rtsEvent*)NULL)
450 #define TERMINATION_CONDITION rtsTrue
453 while (TERMINATION_CONDITION) {
456 /* Choose the processor with the next event */
457 CurrentProc = event->proc;
458 CurrentTSO = event->tso;
461 IF_DEBUG(scheduler, printAllThreads());
463 #if defined(RTS_SUPPORTS_THREADS)
464 // Yield the capability to higher-priority tasks if necessary.
467 yieldCapability(&cap);
470 // If we do not currently hold a capability, we wait for one
473 waitForCapability(&sched_mutex, &cap,
474 mainThread ? &mainThread->bound_thread_cond : NULL);
477 // We now have a capability...
480 #if 0 /* extra sanity checking */
483 for (m = main_threads; m != NULL; m = m->link) {
484 ASSERT(get_itbl(m->tso)->type == TSO);
489 // Check whether we have re-entered the RTS from Haskell without
490 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
492 if (cap->r.rInHaskell) {
493 errorBelch("schedule: re-entered unsafely.\n"
494 " Perhaps a 'foreign import unsafe' should be 'safe'?");
499 // Test for interruption. If interrupted==rtsTrue, then either
500 // we received a keyboard interrupt (^C), or the scheduler is
501 // trying to shut down all the tasks (shutting_down_scheduler) in
505 if (shutting_down_scheduler) {
506 IF_DEBUG(scheduler, sched_belch("shutting down"));
507 releaseCapability(cap);
509 mainThread->stat = Interrupted;
510 mainThread->ret = NULL;
514 IF_DEBUG(scheduler, sched_belch("interrupted"));
519 #if defined(not_yet) && defined(SMP)
521 // Top up the run queue from our spark pool. We try to make the
522 // number of threads in the run queue equal to the number of
523 // free capabilities.
527 if (EMPTY_RUN_QUEUE()) {
528 spark = findSpark(rtsFalse);
530 break; /* no more sparks in the pool */
532 createSparkThread(spark);
534 sched_belch("==^^ turning spark of closure %p into a thread",
535 (StgClosure *)spark));
541 scheduleStartSignalHandlers();
543 // Only check the black holes here if we've nothing else to do.
544 // During normal execution, the black hole list only gets checked
545 // at GC time, to avoid repeatedly traversing this possibly long
546 // list each time around the scheduler.
547 if (EMPTY_RUN_QUEUE()) { scheduleCheckBlackHoles(); }
549 scheduleCheckBlockedThreads();
551 scheduleDetectDeadlock();
553 // Normally, the only way we can get here with no threads to
554 // run is if a keyboard interrupt received during
555 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
556 // Additionally, it is not fatal for the
557 // threaded RTS to reach here with no threads to run.
559 // win32: might be here due to awaitEvent() being abandoned
560 // as a result of a console event having been delivered.
561 if ( EMPTY_RUN_QUEUE() ) {
562 #if !defined(RTS_SUPPORTS_THREADS) && !defined(mingw32_HOST_OS)
565 continue; // nothing to do
568 #if defined(PARALLEL_HASKELL)
569 scheduleSendPendingMessages();
570 if (EMPTY_RUN_QUEUE() && scheduleActivateSpark())
574 ASSERT(next_fish_to_send_at==0); // i.e. no delayed fishes left!
577 /* If we still have no work we need to send a FISH to get a spark
579 if (EMPTY_RUN_QUEUE()) {
580 if (!scheduleGetRemoteWork(&receivedFinish)) continue;
581 ASSERT(rtsFalse); // should not happen at the moment
583 // from here: non-empty run queue.
584 // TODO: merge above case with this, only one call processMessages() !
585 if (PacketsWaiting()) { /* process incoming messages, if
586 any pending... only in else
587 because getRemoteWork waits for
589 receivedFinish = processMessages();
594 scheduleProcessEvent(event);
598 // Get a thread to run
600 ASSERT(run_queue_hd != END_TSO_QUEUE);
603 #if defined(GRAN) || defined(PAR)
604 scheduleGranParReport(); // some kind of debuging output
606 // Sanity check the thread we're about to run. This can be
607 // expensive if there is lots of thread switching going on...
608 IF_DEBUG(sanity,checkTSO(t));
611 #if defined(RTS_SUPPORTS_THREADS)
612 // Check whether we can run this thread in the current task.
613 // If not, we have to pass our capability to the right task.
615 StgMainThread *m = t->main;
622 sched_belch("### Running thread %d in bound thread", t->id));
623 // yes, the Haskell thread is bound to the current native thread
628 sched_belch("### thread %d bound to another OS thread", t->id));
629 // no, bound to a different Haskell thread: pass to that thread
630 PUSH_ON_RUN_QUEUE(t);
631 passCapability(&m->bound_thread_cond);
637 if(mainThread != NULL)
638 // The thread we want to run is bound.
641 sched_belch("### this OS thread cannot run thread %d", t->id));
642 // no, the current native thread is bound to a different
643 // Haskell thread, so pass it to any worker thread
644 PUSH_ON_RUN_QUEUE(t);
645 passCapabilityToWorker();
652 cap->r.rCurrentTSO = t;
654 /* context switches are now initiated by the timer signal, unless
655 * the user specified "context switch as often as possible", with
658 if ((RtsFlags.ConcFlags.ctxtSwitchTicks == 0
659 && (run_queue_hd != END_TSO_QUEUE
660 || blocked_queue_hd != END_TSO_QUEUE
661 || sleeping_queue != END_TSO_QUEUE)))
666 RELEASE_LOCK(&sched_mutex);
668 IF_DEBUG(scheduler, sched_belch("-->> running thread %ld %s ...",
669 (long)t->id, whatNext_strs[t->what_next]));
671 #if defined(PROFILING)
672 startHeapProfTimer();
675 // ----------------------------------------------------------------------
676 // Run the current thread
678 prev_what_next = t->what_next;
680 errno = t->saved_errno;
681 cap->r.rInHaskell = rtsTrue;
683 recent_activity = ACTIVITY_YES;
685 switch (prev_what_next) {
689 /* Thread already finished, return to scheduler. */
690 ret = ThreadFinished;
694 ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
697 case ThreadInterpret:
698 ret = interpretBCO(cap);
702 barf("schedule: invalid what_next field");
705 // We have run some Haskell code: there might be blackhole-blocked
706 // threads to wake up now.
707 if ( blackhole_queue != END_TSO_QUEUE ) {
708 blackholes_need_checking = rtsTrue;
711 cap->r.rInHaskell = rtsFalse;
713 // The TSO might have moved, eg. if it re-entered the RTS and a GC
714 // happened. So find the new location:
715 t = cap->r.rCurrentTSO;
717 // And save the current errno in this thread.
718 t->saved_errno = errno;
720 // ----------------------------------------------------------------------
722 /* Costs for the scheduler are assigned to CCS_SYSTEM */
723 #if defined(PROFILING)
728 ACQUIRE_LOCK(&sched_mutex);
730 #if defined(RTS_SUPPORTS_THREADS)
731 IF_DEBUG(scheduler,debugBelch("sched (task %p): ", osThreadId()););
732 #elif !defined(GRAN) && !defined(PARALLEL_HASKELL)
733 IF_DEBUG(scheduler,debugBelch("sched: "););
736 schedulePostRunThread();
738 ready_to_gc = rtsFalse;
742 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
746 scheduleHandleStackOverflow(t);
750 if (scheduleHandleYield(t, prev_what_next)) {
751 // shortcut for switching between compiler/interpreter:
757 scheduleHandleThreadBlocked(t);
762 if (scheduleHandleThreadFinished(mainThread, cap, t)) return;;
766 barf("schedule: invalid thread return code %d", (int)ret);
769 if (scheduleDoHeapProfile(ready_to_gc)) { ready_to_gc = rtsFalse; }
770 if (ready_to_gc) { scheduleDoGC(cap); }
771 } /* end of while() */
773 IF_PAR_DEBUG(verbose,
774 debugBelch("== Leaving schedule() after having received Finish\n"));
777 /* ----------------------------------------------------------------------------
778 * Setting up the scheduler loop
779 * ASSUMES: sched_mutex
780 * ------------------------------------------------------------------------- */
783 schedulePreLoop(void)
786 /* set up first event to get things going */
787 /* ToDo: assign costs for system setup and init MainTSO ! */
788 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
790 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
793 debugBelch("GRAN: Init CurrentTSO (in schedule) = %p\n",
795 G_TSO(CurrentTSO, 5));
797 if (RtsFlags.GranFlags.Light) {
798 /* Save current time; GranSim Light only */
799 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
804 /* ----------------------------------------------------------------------------
805 * Start any pending signal handlers
806 * ASSUMES: sched_mutex
807 * ------------------------------------------------------------------------- */
810 scheduleStartSignalHandlers(void)
812 #if defined(RTS_USER_SIGNALS) && !defined(RTS_SUPPORTS_THREADS)
813 if (signals_pending()) {
814 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
815 startSignalHandlers();
816 ACQUIRE_LOCK(&sched_mutex);
821 /* ----------------------------------------------------------------------------
822 * Check for blocked threads that can be woken up.
823 * ASSUMES: sched_mutex
824 * ------------------------------------------------------------------------- */
827 scheduleCheckBlockedThreads(void)
830 // Check whether any waiting threads need to be woken up. If the
831 // run queue is empty, and there are no other tasks running, we
832 // can wait indefinitely for something to happen.
834 if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue) )
836 #if defined(RTS_SUPPORTS_THREADS)
837 // We shouldn't be here...
838 barf("schedule: awaitEvent() in threaded RTS");
840 awaitEvent( EMPTY_RUN_QUEUE() && !blackholes_need_checking );
845 /* ----------------------------------------------------------------------------
846 * Check for threads blocked on BLACKHOLEs that can be woken up
847 * ASSUMES: sched_mutex
848 * ------------------------------------------------------------------------- */
850 scheduleCheckBlackHoles( void )
852 if ( blackholes_need_checking )
855 blackholes_need_checking = rtsFalse;
859 /* ----------------------------------------------------------------------------
860 * Detect deadlock conditions and attempt to resolve them.
861 * ASSUMES: sched_mutex
862 * ------------------------------------------------------------------------- */
865 scheduleDetectDeadlock(void)
868 #if defined(PARALLEL_HASKELL)
869 // ToDo: add deadlock detection in GUM (similar to SMP) -- HWL
874 * Detect deadlock: when we have no threads to run, there are no
875 * threads blocked, waiting for I/O, or sleeping, and all the
876 * other tasks are waiting for work, we must have a deadlock of
879 if ( EMPTY_THREAD_QUEUES() )
881 #if defined(RTS_SUPPORTS_THREADS)
883 * In the threaded RTS, we only check for deadlock if there
884 * has been no activity in a complete timeslice. This means
885 * we won't eagerly start a full GC just because we don't have
886 * any threads to run currently.
888 if (recent_activity != ACTIVITY_INACTIVE) return;
891 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
893 // Garbage collection can release some new threads due to
894 // either (a) finalizers or (b) threads resurrected because
895 // they are unreachable and will therefore be sent an
896 // exception. Any threads thus released will be immediately
898 GarbageCollect(GetRoots,rtsTrue);
899 recent_activity = ACTIVITY_DONE_GC;
900 if ( !EMPTY_RUN_QUEUE() ) return;
902 #if defined(RTS_USER_SIGNALS) && !defined(RTS_SUPPORTS_THREADS)
903 /* If we have user-installed signal handlers, then wait
904 * for signals to arrive rather then bombing out with a
907 if ( anyUserHandlers() ) {
909 sched_belch("still deadlocked, waiting for signals..."));
913 if (signals_pending()) {
914 RELEASE_LOCK(&sched_mutex);
915 startSignalHandlers();
916 ACQUIRE_LOCK(&sched_mutex);
919 // either we have threads to run, or we were interrupted:
920 ASSERT(!EMPTY_RUN_QUEUE() || interrupted);
924 #if !defined(RTS_SUPPORTS_THREADS)
925 /* Probably a real deadlock. Send the current main thread the
926 * Deadlock exception (or in the SMP build, send *all* main
927 * threads the deadlock exception, since none of them can make
933 switch (m->tso->why_blocked) {
935 case BlockedOnBlackHole:
936 case BlockedOnException:
938 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
941 barf("deadlock: main thread blocked in a strange way");
948 /* ----------------------------------------------------------------------------
949 * Process an event (GRAN only)
950 * ------------------------------------------------------------------------- */
954 scheduleProcessEvent(rtsEvent *event)
958 if (RtsFlags.GranFlags.Light)
959 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
961 /* adjust time based on time-stamp */
962 if (event->time > CurrentTime[CurrentProc] &&
963 event->evttype != ContinueThread)
964 CurrentTime[CurrentProc] = event->time;
966 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
967 if (!RtsFlags.GranFlags.Light)
970 IF_DEBUG(gran, debugBelch("GRAN: switch by event-type\n"));
972 /* main event dispatcher in GranSim */
973 switch (event->evttype) {
974 /* Should just be continuing execution */
976 IF_DEBUG(gran, debugBelch("GRAN: doing ContinueThread\n"));
977 /* ToDo: check assertion
978 ASSERT(run_queue_hd != (StgTSO*)NULL &&
979 run_queue_hd != END_TSO_QUEUE);
981 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
982 if (!RtsFlags.GranFlags.DoAsyncFetch &&
983 procStatus[CurrentProc]==Fetching) {
984 debugBelch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]\n",
985 CurrentTSO->id, CurrentTSO, CurrentProc);
988 /* Ignore ContinueThreads for completed threads */
989 if (CurrentTSO->what_next == ThreadComplete) {
990 debugBelch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)\n",
991 CurrentTSO->id, CurrentTSO, CurrentProc);
994 /* Ignore ContinueThreads for threads that are being migrated */
995 if (PROCS(CurrentTSO)==Nowhere) {
996 debugBelch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)\n",
997 CurrentTSO->id, CurrentTSO, CurrentProc);
1000 /* The thread should be at the beginning of the run queue */
1001 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
1002 debugBelch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread\n",
1003 CurrentTSO->id, CurrentTSO, CurrentProc);
1004 break; // run the thread anyway
1007 new_event(proc, proc, CurrentTime[proc],
1009 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
1011 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
1012 break; // now actually run the thread; DaH Qu'vam yImuHbej
1015 do_the_fetchnode(event);
1016 goto next_thread; /* handle next event in event queue */
1019 do_the_globalblock(event);
1020 goto next_thread; /* handle next event in event queue */
1023 do_the_fetchreply(event);
1024 goto next_thread; /* handle next event in event queue */
1026 case UnblockThread: /* Move from the blocked queue to the tail of */
1027 do_the_unblock(event);
1028 goto next_thread; /* handle next event in event queue */
1030 case ResumeThread: /* Move from the blocked queue to the tail of */
1031 /* the runnable queue ( i.e. Qu' SImqa'lu') */
1032 event->tso->gran.blocktime +=
1033 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
1034 do_the_startthread(event);
1035 goto next_thread; /* handle next event in event queue */
1038 do_the_startthread(event);
1039 goto next_thread; /* handle next event in event queue */
1042 do_the_movethread(event);
1043 goto next_thread; /* handle next event in event queue */
1046 do_the_movespark(event);
1047 goto next_thread; /* handle next event in event queue */
1050 do_the_findwork(event);
1051 goto next_thread; /* handle next event in event queue */
1054 barf("Illegal event type %u\n", event->evttype);
1057 /* This point was scheduler_loop in the old RTS */
1059 IF_DEBUG(gran, debugBelch("GRAN: after main switch\n"));
1061 TimeOfLastEvent = CurrentTime[CurrentProc];
1062 TimeOfNextEvent = get_time_of_next_event();
1063 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
1064 // CurrentTSO = ThreadQueueHd;
1066 IF_DEBUG(gran, debugBelch("GRAN: time of next event is: %ld\n",
1069 if (RtsFlags.GranFlags.Light)
1070 GranSimLight_leave_system(event, &ActiveTSO);
1072 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
1075 debugBelch("GRAN: end of time-slice is %#lx\n", EndOfTimeSlice));
1077 /* in a GranSim setup the TSO stays on the run queue */
1079 /* Take a thread from the run queue. */
1080 POP_RUN_QUEUE(t); // take_off_run_queue(t);
1083 debugBelch("GRAN: About to run current thread, which is\n");
1086 context_switch = 0; // turned on via GranYield, checking events and time slice
1089 DumpGranEvent(GR_SCHEDULE, t));
1091 procStatus[CurrentProc] = Busy;
1095 /* ----------------------------------------------------------------------------
1096 * Send pending messages (PARALLEL_HASKELL only)
1097 * ------------------------------------------------------------------------- */
1099 #if defined(PARALLEL_HASKELL)
1101 scheduleSendPendingMessages(void)
1107 # if defined(PAR) // global Mem.Mgmt., omit for now
1108 if (PendingFetches != END_BF_QUEUE) {
1113 if (RtsFlags.ParFlags.BufferTime) {
1114 // if we use message buffering, we must send away all message
1115 // packets which have become too old...
1121 /* ----------------------------------------------------------------------------
1122 * Activate spark threads (PARALLEL_HASKELL only)
1123 * ------------------------------------------------------------------------- */
1125 #if defined(PARALLEL_HASKELL)
1127 scheduleActivateSpark(void)
1130 ASSERT(EMPTY_RUN_QUEUE());
1131 /* We get here if the run queue is empty and want some work.
1132 We try to turn a spark into a thread, and add it to the run queue,
1133 from where it will be picked up in the next iteration of the scheduler
1137 /* :-[ no local threads => look out for local sparks */
1138 /* the spark pool for the current PE */
1139 pool = &(cap.r.rSparks); // JB: cap = (old) MainCap
1140 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
1141 pool->hd < pool->tl) {
1143 * ToDo: add GC code check that we really have enough heap afterwards!!
1145 * If we're here (no runnable threads) and we have pending
1146 * sparks, we must have a space problem. Get enough space
1147 * to turn one of those pending sparks into a
1151 spark = findSpark(rtsFalse); /* get a spark */
1152 if (spark != (rtsSpark) NULL) {
1153 tso = createThreadFromSpark(spark); /* turn the spark into a thread */
1154 IF_PAR_DEBUG(fish, // schedule,
1155 debugBelch("==== schedule: Created TSO %d (%p); %d threads active\n",
1156 tso->id, tso, advisory_thread_count));
1158 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
1159 IF_PAR_DEBUG(fish, // schedule,
1160 debugBelch("==^^ failed to create thread from spark @ %lx\n",
1162 return rtsFalse; /* failed to generate a thread */
1163 } /* otherwise fall through & pick-up new tso */
1165 IF_PAR_DEBUG(fish, // schedule,
1166 debugBelch("==^^ no local sparks (spark pool contains only NFs: %d)\n",
1167 spark_queue_len(pool)));
1168 return rtsFalse; /* failed to generate a thread */
1170 return rtsTrue; /* success in generating a thread */
1171 } else { /* no more threads permitted or pool empty */
1172 return rtsFalse; /* failed to generateThread */
1175 tso = NULL; // avoid compiler warning only
1176 return rtsFalse; /* dummy in non-PAR setup */
1179 #endif // PARALLEL_HASKELL
1181 /* ----------------------------------------------------------------------------
1182 * Get work from a remote node (PARALLEL_HASKELL only)
1183 * ------------------------------------------------------------------------- */
1185 #if defined(PARALLEL_HASKELL)
1187 scheduleGetRemoteWork(rtsBool *receivedFinish)
1189 ASSERT(EMPTY_RUN_QUEUE());
1191 if (RtsFlags.ParFlags.BufferTime) {
1192 IF_PAR_DEBUG(verbose,
1193 debugBelch("...send all pending data,"));
1196 for (i=1; i<=nPEs; i++)
1197 sendImmediately(i); // send all messages away immediately
1201 //++EDEN++ idle() , i.e. send all buffers, wait for work
1202 // suppress fishing in EDEN... just look for incoming messages
1203 // (blocking receive)
1204 IF_PAR_DEBUG(verbose,
1205 debugBelch("...wait for incoming messages...\n"));
1206 *receivedFinish = processMessages(); // blocking receive...
1208 // and reenter scheduling loop after having received something
1209 // (return rtsFalse below)
1211 # else /* activate SPARKS machinery */
1212 /* We get here, if we have no work, tried to activate a local spark, but still
1213 have no work. We try to get a remote spark, by sending a FISH message.
1214 Thread migration should be added here, and triggered when a sequence of
1215 fishes returns without work. */
1216 delay = (RtsFlags.ParFlags.fishDelay!=0ll ? RtsFlags.ParFlags.fishDelay : 0ll);
1218 /* =8-[ no local sparks => look for work on other PEs */
1220 * We really have absolutely no work. Send out a fish
1221 * (there may be some out there already), and wait for
1222 * something to arrive. We clearly can't run any threads
1223 * until a SCHEDULE or RESUME arrives, and so that's what
1224 * we're hoping to see. (Of course, we still have to
1225 * respond to other types of messages.)
1227 rtsTime now = msTime() /*CURRENT_TIME*/;
1228 IF_PAR_DEBUG(verbose,
1229 debugBelch("-- now=%ld\n", now));
1230 IF_PAR_DEBUG(fish, // verbose,
1231 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
1232 (last_fish_arrived_at!=0 &&
1233 last_fish_arrived_at+delay > now)) {
1234 debugBelch("--$$ <%llu> delaying FISH until %llu (last fish %llu, delay %llu)\n",
1235 now, last_fish_arrived_at+delay,
1236 last_fish_arrived_at,
1240 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
1241 advisory_thread_count < RtsFlags.ParFlags.maxThreads) { // send a FISH, but when?
1242 if (last_fish_arrived_at==0 ||
1243 (last_fish_arrived_at+delay <= now)) { // send FISH now!
1244 /* outstandingFishes is set in sendFish, processFish;
1245 avoid flooding system with fishes via delay */
1246 next_fish_to_send_at = 0;
1248 /* ToDo: this should be done in the main scheduling loop to avoid the
1249 busy wait here; not so bad if fish delay is very small */
1250 int iq = 0; // DEBUGGING -- HWL
1251 next_fish_to_send_at = last_fish_arrived_at+delay; // remember when to send
1252 /* send a fish when ready, but process messages that arrive in the meantime */
1254 if (PacketsWaiting()) {
1256 *receivedFinish = processMessages();
1259 } while (!*receivedFinish || now<next_fish_to_send_at);
1260 // JB: This means the fish could become obsolete, if we receive
1261 // work. Better check for work again?
1262 // last line: while (!receivedFinish || !haveWork || now<...)
1263 // next line: if (receivedFinish || haveWork )
1265 if (*receivedFinish) // no need to send a FISH if we are finishing anyway
1266 return rtsFalse; // NB: this will leave scheduler loop
1267 // immediately after return!
1269 IF_PAR_DEBUG(fish, // verbose,
1270 debugBelch("--$$ <%llu> sent delayed fish (%d processMessages); active/total threads=%d/%d\n",now,iq,run_queue_len(),advisory_thread_count));
1274 // JB: IMHO, this should all be hidden inside sendFish(...)
1276 sendFish(pe, thisPE, NEW_FISH_AGE, NEW_FISH_HISTORY,
1279 // Global statistics: count no. of fishes
1280 if (RtsFlags.ParFlags.ParStats.Global &&
1281 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1282 globalParStats.tot_fish_mess++;
1286 /* delayed fishes must have been sent by now! */
1287 next_fish_to_send_at = 0;
1290 *receivedFinish = processMessages();
1291 # endif /* SPARKS */
1294 /* NB: this function always returns rtsFalse, meaning the scheduler
1295 loop continues with the next iteration;
1297 return code means success in finding work; we enter this function
1298 if there is no local work, thus have to send a fish which takes
1299 time until it arrives with work; in the meantime we should process
1300 messages in the main loop;
1303 #endif // PARALLEL_HASKELL
1305 /* ----------------------------------------------------------------------------
1306 * PAR/GRAN: Report stats & debugging info(?)
1307 * ------------------------------------------------------------------------- */
1309 #if defined(PAR) || defined(GRAN)
1311 scheduleGranParReport(void)
1313 ASSERT(run_queue_hd != END_TSO_QUEUE);
1315 /* Take a thread from the run queue, if we have work */
1316 POP_RUN_QUEUE(t); // take_off_run_queue(END_TSO_QUEUE);
1318 /* If this TSO has got its outport closed in the meantime,
1319 * it mustn't be run. Instead, we have to clean it up as if it was finished.
1320 * It has to be marked as TH_DEAD for this purpose.
1321 * If it is TH_TERM instead, it is supposed to have finished in the normal way.
1323 JB: TODO: investigate wether state change field could be nuked
1324 entirely and replaced by the normal tso state (whatnext
1325 field). All we want to do is to kill tsos from outside.
1328 /* ToDo: write something to the log-file
1329 if (RTSflags.ParFlags.granSimStats && !sameThread)
1330 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
1334 /* the spark pool for the current PE */
1335 pool = &(cap.r.rSparks); // cap = (old) MainCap
1338 debugBelch("--=^ %d threads, %d sparks on [%#x]\n",
1339 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
1342 debugBelch("--=^ %d threads, %d sparks on [%#x]\n",
1343 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
1345 if (RtsFlags.ParFlags.ParStats.Full &&
1346 (t->par.sparkname != (StgInt)0) && // only log spark generated threads
1347 (emitSchedule || // forced emit
1348 (t && LastTSO && t->id != LastTSO->id))) {
1350 we are running a different TSO, so write a schedule event to log file
1351 NB: If we use fair scheduling we also have to write a deschedule
1352 event for LastTSO; with unfair scheduling we know that the
1353 previous tso has blocked whenever we switch to another tso, so
1354 we don't need it in GUM for now
1356 IF_PAR_DEBUG(fish, // schedule,
1357 debugBelch("____ scheduling spark generated thread %d (%lx) (%lx) via a forced emit\n",t->id,t,t->par.sparkname));
1359 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1360 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
1361 emitSchedule = rtsFalse;
1366 /* ----------------------------------------------------------------------------
1367 * After running a thread...
1368 * ASSUMES: sched_mutex
1369 * ------------------------------------------------------------------------- */
1372 schedulePostRunThread(void)
1375 /* HACK 675: if the last thread didn't yield, make sure to print a
1376 SCHEDULE event to the log file when StgRunning the next thread, even
1377 if it is the same one as before */
1379 TimeOfLastYield = CURRENT_TIME;
1382 /* some statistics gathering in the parallel case */
1384 #if defined(GRAN) || defined(PAR) || defined(EDEN)
1388 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
1389 globalGranStats.tot_heapover++;
1391 globalParStats.tot_heapover++;
1398 DumpGranEvent(GR_DESCHEDULE, t));
1399 globalGranStats.tot_stackover++;
1402 // DumpGranEvent(GR_DESCHEDULE, t);
1403 globalParStats.tot_stackover++;
1407 case ThreadYielding:
1410 DumpGranEvent(GR_DESCHEDULE, t));
1411 globalGranStats.tot_yields++;
1414 // DumpGranEvent(GR_DESCHEDULE, t);
1415 globalParStats.tot_yields++;
1422 debugBelch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1423 t->id, t, whatNext_strs[t->what_next], t->block_info.closure,
1424 (t->block_info.closure==(StgClosure*)NULL ? 99 : where_is(t->block_info.closure)));
1425 if (t->block_info.closure!=(StgClosure*)NULL)
1426 print_bq(t->block_info.closure);
1429 // ??? needed; should emit block before
1431 DumpGranEvent(GR_DESCHEDULE, t));
1432 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1435 ASSERT(procStatus[CurrentProc]==Busy ||
1436 ((procStatus[CurrentProc]==Fetching) &&
1437 (t->block_info.closure!=(StgClosure*)NULL)));
1438 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1439 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1440 procStatus[CurrentProc]==Fetching))
1441 procStatus[CurrentProc] = Idle;
1444 //++PAR++ blockThread() writes the event (change?)
1448 case ThreadFinished:
1452 barf("parGlobalStats: unknown return code");
1458 /* -----------------------------------------------------------------------------
1459 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1460 * ASSUMES: sched_mutex
1461 * -------------------------------------------------------------------------- */
1464 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1466 // did the task ask for a large block?
1467 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1468 // if so, get one and push it on the front of the nursery.
1472 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1475 debugBelch("--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1476 (long)t->id, whatNext_strs[t->what_next], blocks));
1478 // don't do this if it would push us over the
1479 // alloc_blocks_lim limit; we'll GC first.
1480 if (alloc_blocks + blocks < alloc_blocks_lim) {
1482 alloc_blocks += blocks;
1483 bd = allocGroup( blocks );
1485 // link the new group into the list
1486 bd->link = cap->r.rCurrentNursery;
1487 bd->u.back = cap->r.rCurrentNursery->u.back;
1488 if (cap->r.rCurrentNursery->u.back != NULL) {
1489 cap->r.rCurrentNursery->u.back->link = bd;
1492 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1493 g0s0 == cap->r.rNursery);
1496 cap->r.rNursery->blocks = bd;
1498 cap->r.rCurrentNursery->u.back = bd;
1500 // initialise it as a nursery block. We initialise the
1501 // step, gen_no, and flags field of *every* sub-block in
1502 // this large block, because this is easier than making
1503 // sure that we always find the block head of a large
1504 // block whenever we call Bdescr() (eg. evacuate() and
1505 // isAlive() in the GC would both have to do this, at
1509 for (x = bd; x < bd + blocks; x++) {
1517 // don't forget to update the block count in g0s0.
1518 g0s0->n_blocks += blocks;
1520 // This assert can be a killer if the app is doing lots
1521 // of large block allocations.
1522 ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1525 // now update the nursery to point to the new block
1526 cap->r.rCurrentNursery = bd;
1528 // we might be unlucky and have another thread get on the
1529 // run queue before us and steal the large block, but in that
1530 // case the thread will just end up requesting another large
1532 PUSH_ON_RUN_QUEUE(t);
1533 return rtsFalse; /* not actually GC'ing */
1537 /* make all the running tasks block on a condition variable,
1538 * maybe set context_switch and wait till they all pile in,
1539 * then have them wait on a GC condition variable.
1542 debugBelch("--<< thread %ld (%s) stopped: HeapOverflow\n",
1543 (long)t->id, whatNext_strs[t->what_next]));
1546 ASSERT(!is_on_queue(t,CurrentProc));
1547 #elif defined(PARALLEL_HASKELL)
1548 /* Currently we emit a DESCHEDULE event before GC in GUM.
1549 ToDo: either add separate event to distinguish SYSTEM time from rest
1550 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1551 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1552 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1553 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1554 emitSchedule = rtsTrue;
1558 PUSH_ON_RUN_QUEUE(t);
1560 /* actual GC is done at the end of the while loop in schedule() */
1563 /* -----------------------------------------------------------------------------
1564 * Handle a thread that returned to the scheduler with ThreadStackOverflow
1565 * ASSUMES: sched_mutex
1566 * -------------------------------------------------------------------------- */
1569 scheduleHandleStackOverflow( StgTSO *t)
1571 IF_DEBUG(scheduler,debugBelch("--<< thread %ld (%s) stopped, StackOverflow\n",
1572 (long)t->id, whatNext_strs[t->what_next]));
1573 /* just adjust the stack for this thread, then pop it back
1578 /* enlarge the stack */
1579 StgTSO *new_t = threadStackOverflow(t);
1581 /* This TSO has moved, so update any pointers to it from the
1582 * main thread stack. It better not be on any other queues...
1583 * (it shouldn't be).
1585 if (t->main != NULL) {
1586 t->main->tso = new_t;
1588 PUSH_ON_RUN_QUEUE(new_t);
1592 /* -----------------------------------------------------------------------------
1593 * Handle a thread that returned to the scheduler with ThreadYielding
1594 * ASSUMES: sched_mutex
1595 * -------------------------------------------------------------------------- */
1598 scheduleHandleYield( StgTSO *t, nat prev_what_next )
1600 // Reset the context switch flag. We don't do this just before
1601 // running the thread, because that would mean we would lose ticks
1602 // during GC, which can lead to unfair scheduling (a thread hogs
1603 // the CPU because the tick always arrives during GC). This way
1604 // penalises threads that do a lot of allocation, but that seems
1605 // better than the alternative.
1608 /* put the thread back on the run queue. Then, if we're ready to
1609 * GC, check whether this is the last task to stop. If so, wake
1610 * up the GC thread. getThread will block during a GC until the
1614 if (t->what_next != prev_what_next) {
1615 debugBelch("--<< thread %ld (%s) stopped to switch evaluators\n",
1616 (long)t->id, whatNext_strs[t->what_next]);
1618 debugBelch("--<< thread %ld (%s) stopped, yielding\n",
1619 (long)t->id, whatNext_strs[t->what_next]);
1624 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1626 ASSERT(t->link == END_TSO_QUEUE);
1628 // Shortcut if we're just switching evaluators: don't bother
1629 // doing stack squeezing (which can be expensive), just run the
1631 if (t->what_next != prev_what_next) {
1638 ASSERT(!is_on_queue(t,CurrentProc));
1641 //debugBelch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1642 checkThreadQsSanity(rtsTrue));
1649 /* add a ContinueThread event to actually process the thread */
1650 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1652 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1654 debugBelch("GRAN: eventq and runnableq after adding yielded thread to queue again:\n");
1661 /* -----------------------------------------------------------------------------
1662 * Handle a thread that returned to the scheduler with ThreadBlocked
1663 * ASSUMES: sched_mutex
1664 * -------------------------------------------------------------------------- */
1667 scheduleHandleThreadBlocked( StgTSO *t
1668 #if !defined(GRAN) && !defined(DEBUG)
1675 debugBelch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: \n",
1676 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)));
1677 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1679 // ??? needed; should emit block before
1681 DumpGranEvent(GR_DESCHEDULE, t));
1682 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1685 ASSERT(procStatus[CurrentProc]==Busy ||
1686 ((procStatus[CurrentProc]==Fetching) &&
1687 (t->block_info.closure!=(StgClosure*)NULL)));
1688 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1689 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1690 procStatus[CurrentProc]==Fetching))
1691 procStatus[CurrentProc] = Idle;
1695 debugBelch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: \n",
1696 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1699 if (t->block_info.closure!=(StgClosure*)NULL)
1700 print_bq(t->block_info.closure));
1702 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1705 /* whatever we schedule next, we must log that schedule */
1706 emitSchedule = rtsTrue;
1709 /* don't need to do anything. Either the thread is blocked on
1710 * I/O, in which case we'll have called addToBlockedQueue
1711 * previously, or it's blocked on an MVar or Blackhole, in which
1712 * case it'll be on the relevant queue already.
1714 ASSERT(t->why_blocked != NotBlocked);
1716 debugBelch("--<< thread %d (%s) stopped: ",
1717 t->id, whatNext_strs[t->what_next]);
1718 printThreadBlockage(t);
1721 /* Only for dumping event to log file
1722 ToDo: do I need this in GranSim, too?
1728 /* -----------------------------------------------------------------------------
1729 * Handle a thread that returned to the scheduler with ThreadFinished
1730 * ASSUMES: sched_mutex
1731 * -------------------------------------------------------------------------- */
1734 scheduleHandleThreadFinished( StgMainThread *mainThread
1735 USED_WHEN_RTS_SUPPORTS_THREADS,
1739 /* Need to check whether this was a main thread, and if so,
1740 * return with the return value.
1742 * We also end up here if the thread kills itself with an
1743 * uncaught exception, see Exception.cmm.
1745 IF_DEBUG(scheduler,debugBelch("--++ thread %d (%s) finished\n",
1746 t->id, whatNext_strs[t->what_next]));
1749 endThread(t, CurrentProc); // clean-up the thread
1750 #elif defined(PARALLEL_HASKELL)
1751 /* For now all are advisory -- HWL */
1752 //if(t->priority==AdvisoryPriority) ??
1753 advisory_thread_count--; // JB: Caution with this counter, buggy!
1756 if(t->dist.priority==RevalPriority)
1760 # if defined(EDENOLD)
1761 // the thread could still have an outport... (BUG)
1762 if (t->eden.outport != -1) {
1763 // delete the outport for the tso which has finished...
1764 IF_PAR_DEBUG(eden_ports,
1765 debugBelch("WARNING: Scheduler removes outport %d for TSO %d.\n",
1766 t->eden.outport, t->id));
1769 // thread still in the process (HEAVY BUG! since outport has just been closed...)
1770 if (t->eden.epid != -1) {
1771 IF_PAR_DEBUG(eden_ports,
1772 debugBelch("WARNING: Scheduler removes TSO %d from process %d .\n",
1773 t->id, t->eden.epid));
1774 removeTSOfromProcess(t);
1779 if (RtsFlags.ParFlags.ParStats.Full &&
1780 !RtsFlags.ParFlags.ParStats.Suppressed)
1781 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1783 // t->par only contains statistics: left out for now...
1785 debugBelch("**** end thread: ended sparked thread %d (%lx); sparkname: %lx\n",
1786 t->id,t,t->par.sparkname));
1788 #endif // PARALLEL_HASKELL
1791 // Check whether the thread that just completed was a main
1792 // thread, and if so return with the result.
1794 // There is an assumption here that all thread completion goes
1795 // through this point; we need to make sure that if a thread
1796 // ends up in the ThreadKilled state, that it stays on the run
1797 // queue so it can be dealt with here.
1800 #if defined(RTS_SUPPORTS_THREADS)
1803 mainThread->tso == t
1807 // We are a bound thread: this must be our thread that just
1809 ASSERT(mainThread->tso == t);
1811 if (t->what_next == ThreadComplete) {
1812 if (mainThread->ret) {
1813 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1814 *(mainThread->ret) = (StgClosure *)mainThread->tso->sp[1];
1816 mainThread->stat = Success;
1818 if (mainThread->ret) {
1819 *(mainThread->ret) = NULL;
1822 mainThread->stat = Interrupted;
1824 mainThread->stat = Killed;
1828 removeThreadLabel((StgWord)mainThread->tso->id);
1830 if (mainThread->prev == NULL) {
1831 ASSERT(mainThread == main_threads);
1832 main_threads = mainThread->link;
1834 mainThread->prev->link = mainThread->link;
1836 if (mainThread->link != NULL) {
1837 mainThread->link->prev = mainThread->prev;
1839 releaseCapability(cap);
1840 return rtsTrue; // tells schedule() to return
1843 #ifdef RTS_SUPPORTS_THREADS
1844 ASSERT(t->main == NULL);
1846 if (t->main != NULL) {
1847 // Must be a main thread that is not the topmost one. Leave
1848 // it on the run queue until the stack has unwound to the
1849 // point where we can deal with this. Leaving it on the run
1850 // queue also ensures that the garbage collector knows about
1851 // this thread and its return value (it gets dropped from the
1852 // all_threads list so there's no other way to find it).
1853 APPEND_TO_RUN_QUEUE(t);
1859 /* -----------------------------------------------------------------------------
1860 * Perform a heap census, if PROFILING
1861 * -------------------------------------------------------------------------- */
1864 scheduleDoHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1866 #if defined(PROFILING)
1867 // When we have +RTS -i0 and we're heap profiling, do a census at
1868 // every GC. This lets us get repeatable runs for debugging.
1869 if (performHeapProfile ||
1870 (RtsFlags.ProfFlags.profileInterval==0 &&
1871 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1872 GarbageCollect(GetRoots, rtsTrue);
1874 performHeapProfile = rtsFalse;
1875 return rtsTrue; // true <=> we already GC'd
1881 /* -----------------------------------------------------------------------------
1882 * Perform a garbage collection if necessary
1883 * ASSUMES: sched_mutex
1884 * -------------------------------------------------------------------------- */
1887 scheduleDoGC( Capability *cap STG_UNUSED )
1891 static rtsBool waiting_for_gc;
1892 int n_capabilities = RtsFlags.ParFlags.nNodes - 1;
1893 // subtract one because we're already holding one.
1894 Capability *caps[n_capabilities];
1898 // In order to GC, there must be no threads running Haskell code.
1899 // Therefore, the GC thread needs to hold *all* the capabilities,
1900 // and release them after the GC has completed.
1902 // This seems to be the simplest way: previous attempts involved
1903 // making all the threads with capabilities give up their
1904 // capabilities and sleep except for the *last* one, which
1905 // actually did the GC. But it's quite hard to arrange for all
1906 // the other tasks to sleep and stay asleep.
1909 // Someone else is already trying to GC
1910 if (waiting_for_gc) return;
1911 waiting_for_gc = rtsTrue;
1913 caps[n_capabilities] = cap;
1914 while (n_capabilities > 0) {
1915 IF_DEBUG(scheduler, sched_belch("ready_to_gc, grabbing all the capabilies (%d left)", n_capabilities));
1916 waitForReturnCapability(&sched_mutex, &cap);
1918 caps[n_capabilities] = cap;
1921 waiting_for_gc = rtsFalse;
1924 /* Kick any transactions which are invalid back to their
1925 * atomically frames. When next scheduled they will try to
1926 * commit, this commit will fail and they will retry.
1928 for (t = all_threads; t != END_TSO_QUEUE; t = t -> link) {
1929 if (t -> what_next != ThreadRelocated && t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1930 if (!stmValidateTransaction (t -> trec)) {
1931 IF_DEBUG(stm, sched_belch("trec %p found wasting its time", t));
1933 // strip the stack back to the ATOMICALLY_FRAME, aborting
1934 // the (nested) transaction, and saving the stack of any
1935 // partially-evaluated thunks on the heap.
1936 raiseAsync_(t, NULL, rtsTrue);
1939 ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1945 // so this happens periodically:
1946 scheduleCheckBlackHoles();
1948 /* everybody back, start the GC.
1949 * Could do it in this thread, or signal a condition var
1950 * to do it in another thread. Either way, we need to
1951 * broadcast on gc_pending_cond afterward.
1953 #if defined(RTS_SUPPORTS_THREADS)
1954 IF_DEBUG(scheduler,sched_belch("doing GC"));
1956 GarbageCollect(GetRoots,rtsFalse);
1960 // release our stash of capabilities.
1962 for (i = 0; i < RtsFlags.ParFlags.nNodes-1; i++) {
1963 releaseCapability(caps[i]);
1969 /* add a ContinueThread event to continue execution of current thread */
1970 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1972 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1974 debugBelch("GRAN: eventq and runnableq after Garbage collection:\n\n");
1980 /* ---------------------------------------------------------------------------
1981 * rtsSupportsBoundThreads(): is the RTS built to support bound threads?
1982 * used by Control.Concurrent for error checking.
1983 * ------------------------------------------------------------------------- */
1986 rtsSupportsBoundThreads(void)
1988 #if defined(RTS_SUPPORTS_THREADS)
1995 /* ---------------------------------------------------------------------------
1996 * isThreadBound(tso): check whether tso is bound to an OS thread.
1997 * ------------------------------------------------------------------------- */
2000 isThreadBound(StgTSO* tso USED_IN_THREADED_RTS)
2002 #if defined(RTS_SUPPORTS_THREADS)
2003 return (tso->main != NULL);
2008 /* ---------------------------------------------------------------------------
2009 * Singleton fork(). Do not copy any running threads.
2010 * ------------------------------------------------------------------------- */
2012 #ifndef mingw32_HOST_OS
2013 #define FORKPROCESS_PRIMOP_SUPPORTED
2016 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2018 deleteThreadImmediately(StgTSO *tso);
2021 forkProcess(HsStablePtr *entry
2022 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
2027 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2033 IF_DEBUG(scheduler,sched_belch("forking!"));
2034 rts_lock(); // This not only acquires sched_mutex, it also
2035 // makes sure that no other threads are running
2039 if (pid) { /* parent */
2041 /* just return the pid */
2045 } else { /* child */
2048 // delete all threads
2049 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
2051 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
2054 // don't allow threads to catch the ThreadKilled exception
2055 deleteThreadImmediately(t);
2058 // wipe the main thread list
2059 while((m = main_threads) != NULL) {
2060 main_threads = m->link;
2061 # ifdef THREADED_RTS
2062 closeCondition(&m->bound_thread_cond);
2067 rc = rts_evalStableIO(entry, NULL); // run the action
2068 rts_checkSchedStatus("forkProcess",rc);
2072 hs_exit(); // clean up and exit
2075 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
2076 barf("forkProcess#: primop not supported, sorry!\n");
2081 /* ---------------------------------------------------------------------------
2082 * deleteAllThreads(): kill all the live threads.
2084 * This is used when we catch a user interrupt (^C), before performing
2085 * any necessary cleanups and running finalizers.
2087 * Locks: sched_mutex held.
2088 * ------------------------------------------------------------------------- */
2091 deleteAllThreads ( void )
2094 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
2095 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
2096 if (t->what_next == ThreadRelocated) {
2099 next = t->global_link;
2104 // The run queue now contains a bunch of ThreadKilled threads. We
2105 // must not throw these away: the main thread(s) will be in there
2106 // somewhere, and the main scheduler loop has to deal with it.
2107 // Also, the run queue is the only thing keeping these threads from
2108 // being GC'd, and we don't want the "main thread has been GC'd" panic.
2110 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
2111 ASSERT(blackhole_queue == END_TSO_QUEUE);
2112 ASSERT(sleeping_queue == END_TSO_QUEUE);
2115 /* startThread and insertThread are now in GranSim.c -- HWL */
2118 /* ---------------------------------------------------------------------------
2119 * Suspending & resuming Haskell threads.
2121 * When making a "safe" call to C (aka _ccall_GC), the task gives back
2122 * its capability before calling the C function. This allows another
2123 * task to pick up the capability and carry on running Haskell
2124 * threads. It also means that if the C call blocks, it won't lock
2127 * The Haskell thread making the C call is put to sleep for the
2128 * duration of the call, on the susepended_ccalling_threads queue. We
2129 * give out a token to the task, which it can use to resume the thread
2130 * on return from the C function.
2131 * ------------------------------------------------------------------------- */
2134 suspendThread( StgRegTable *reg )
2138 int saved_errno = errno;
2140 /* assume that *reg is a pointer to the StgRegTable part
2143 cap = (Capability *)((void *)((unsigned char*)reg - sizeof(StgFunTable)));
2145 ACQUIRE_LOCK(&sched_mutex);
2148 sched_belch("thread %d did a _ccall_gc", cap->r.rCurrentTSO->id));
2150 // XXX this might not be necessary --SDM
2151 cap->r.rCurrentTSO->what_next = ThreadRunGHC;
2153 threadPaused(cap->r.rCurrentTSO);
2154 cap->r.rCurrentTSO->link = suspended_ccalling_threads;
2155 suspended_ccalling_threads = cap->r.rCurrentTSO;
2157 if(cap->r.rCurrentTSO->blocked_exceptions == NULL) {
2158 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall;
2159 cap->r.rCurrentTSO->blocked_exceptions = END_TSO_QUEUE;
2161 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall_NoUnblockExc;
2164 /* Use the thread ID as the token; it should be unique */
2165 tok = cap->r.rCurrentTSO->id;
2167 /* Hand back capability */
2168 cap->r.rInHaskell = rtsFalse;
2169 releaseCapability(cap);
2171 #if defined(RTS_SUPPORTS_THREADS)
2172 /* Preparing to leave the RTS, so ensure there's a native thread/task
2173 waiting to take over.
2175 IF_DEBUG(scheduler, sched_belch("worker (token %d): leaving RTS", tok));
2178 RELEASE_LOCK(&sched_mutex);
2180 errno = saved_errno;
2185 resumeThread( StgInt tok )
2187 StgTSO *tso, **prev;
2189 int saved_errno = errno;
2191 #if defined(RTS_SUPPORTS_THREADS)
2192 /* Wait for permission to re-enter the RTS with the result. */
2193 ACQUIRE_LOCK(&sched_mutex);
2194 waitForReturnCapability(&sched_mutex, &cap);
2196 IF_DEBUG(scheduler, sched_belch("worker (token %d): re-entering RTS", tok));
2198 grabCapability(&cap);
2201 /* Remove the thread off of the suspended list */
2202 prev = &suspended_ccalling_threads;
2203 for (tso = suspended_ccalling_threads;
2204 tso != END_TSO_QUEUE;
2205 prev = &tso->link, tso = tso->link) {
2206 if (tso->id == (StgThreadID)tok) {
2211 if (tso == END_TSO_QUEUE) {
2212 barf("resumeThread: thread not found");
2214 tso->link = END_TSO_QUEUE;
2216 if(tso->why_blocked == BlockedOnCCall) {
2217 awakenBlockedQueueNoLock(tso->blocked_exceptions);
2218 tso->blocked_exceptions = NULL;
2221 /* Reset blocking status */
2222 tso->why_blocked = NotBlocked;
2224 cap->r.rCurrentTSO = tso;
2225 cap->r.rInHaskell = rtsTrue;
2226 RELEASE_LOCK(&sched_mutex);
2227 errno = saved_errno;
2231 /* ---------------------------------------------------------------------------
2232 * Comparing Thread ids.
2234 * This is used from STG land in the implementation of the
2235 * instances of Eq/Ord for ThreadIds.
2236 * ------------------------------------------------------------------------ */
2239 cmp_thread(StgPtr tso1, StgPtr tso2)
2241 StgThreadID id1 = ((StgTSO *)tso1)->id;
2242 StgThreadID id2 = ((StgTSO *)tso2)->id;
2244 if (id1 < id2) return (-1);
2245 if (id1 > id2) return 1;
2249 /* ---------------------------------------------------------------------------
2250 * Fetching the ThreadID from an StgTSO.
2252 * This is used in the implementation of Show for ThreadIds.
2253 * ------------------------------------------------------------------------ */
2255 rts_getThreadId(StgPtr tso)
2257 return ((StgTSO *)tso)->id;
2262 labelThread(StgPtr tso, char *label)
2267 /* Caveat: Once set, you can only set the thread name to "" */
2268 len = strlen(label)+1;
2269 buf = stgMallocBytes(len * sizeof(char), "Schedule.c:labelThread()");
2270 strncpy(buf,label,len);
2271 /* Update will free the old memory for us */
2272 updateThreadLabel(((StgTSO *)tso)->id,buf);
2276 /* ---------------------------------------------------------------------------
2277 Create a new thread.
2279 The new thread starts with the given stack size. Before the
2280 scheduler can run, however, this thread needs to have a closure
2281 (and possibly some arguments) pushed on its stack. See
2282 pushClosure() in Schedule.h.
2284 createGenThread() and createIOThread() (in SchedAPI.h) are
2285 convenient packaged versions of this function.
2287 currently pri (priority) is only used in a GRAN setup -- HWL
2288 ------------------------------------------------------------------------ */
2290 /* currently pri (priority) is only used in a GRAN setup -- HWL */
2292 createThread(nat size, StgInt pri)
2295 createThread(nat size)
2302 /* First check whether we should create a thread at all */
2303 #if defined(PARALLEL_HASKELL)
2304 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
2305 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
2307 debugBelch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)\n",
2308 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
2309 return END_TSO_QUEUE;
2315 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
2318 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
2320 /* catch ridiculously small stack sizes */
2321 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
2322 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
2325 stack_size = size - TSO_STRUCT_SIZEW;
2327 tso = (StgTSO *)allocate(size);
2328 TICK_ALLOC_TSO(stack_size, 0);
2330 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
2332 SET_GRAN_HDR(tso, ThisPE);
2335 // Always start with the compiled code evaluator
2336 tso->what_next = ThreadRunGHC;
2338 tso->id = next_thread_id++;
2339 tso->why_blocked = NotBlocked;
2340 tso->blocked_exceptions = NULL;
2342 tso->saved_errno = 0;
2345 tso->stack_size = stack_size;
2346 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
2348 tso->sp = (P_)&(tso->stack) + stack_size;
2350 tso->trec = NO_TREC;
2353 tso->prof.CCCS = CCS_MAIN;
2356 /* put a stop frame on the stack */
2357 tso->sp -= sizeofW(StgStopFrame);
2358 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
2359 tso->link = END_TSO_QUEUE;
2363 /* uses more flexible routine in GranSim */
2364 insertThread(tso, CurrentProc);
2366 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
2372 if (RtsFlags.GranFlags.GranSimStats.Full)
2373 DumpGranEvent(GR_START,tso);
2374 #elif defined(PARALLEL_HASKELL)
2375 if (RtsFlags.ParFlags.ParStats.Full)
2376 DumpGranEvent(GR_STARTQ,tso);
2377 /* HACk to avoid SCHEDULE
2381 /* Link the new thread on the global thread list.
2383 tso->global_link = all_threads;
2387 tso->dist.priority = MandatoryPriority; //by default that is...
2391 tso->gran.pri = pri;
2393 tso->gran.magic = TSO_MAGIC; // debugging only
2395 tso->gran.sparkname = 0;
2396 tso->gran.startedat = CURRENT_TIME;
2397 tso->gran.exported = 0;
2398 tso->gran.basicblocks = 0;
2399 tso->gran.allocs = 0;
2400 tso->gran.exectime = 0;
2401 tso->gran.fetchtime = 0;
2402 tso->gran.fetchcount = 0;
2403 tso->gran.blocktime = 0;
2404 tso->gran.blockcount = 0;
2405 tso->gran.blockedat = 0;
2406 tso->gran.globalsparks = 0;
2407 tso->gran.localsparks = 0;
2408 if (RtsFlags.GranFlags.Light)
2409 tso->gran.clock = Now; /* local clock */
2411 tso->gran.clock = 0;
2413 IF_DEBUG(gran,printTSO(tso));
2414 #elif defined(PARALLEL_HASKELL)
2416 tso->par.magic = TSO_MAGIC; // debugging only
2418 tso->par.sparkname = 0;
2419 tso->par.startedat = CURRENT_TIME;
2420 tso->par.exported = 0;
2421 tso->par.basicblocks = 0;
2422 tso->par.allocs = 0;
2423 tso->par.exectime = 0;
2424 tso->par.fetchtime = 0;
2425 tso->par.fetchcount = 0;
2426 tso->par.blocktime = 0;
2427 tso->par.blockcount = 0;
2428 tso->par.blockedat = 0;
2429 tso->par.globalsparks = 0;
2430 tso->par.localsparks = 0;
2434 globalGranStats.tot_threads_created++;
2435 globalGranStats.threads_created_on_PE[CurrentProc]++;
2436 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
2437 globalGranStats.tot_sq_probes++;
2438 #elif defined(PARALLEL_HASKELL)
2439 // collect parallel global statistics (currently done together with GC stats)
2440 if (RtsFlags.ParFlags.ParStats.Global &&
2441 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
2442 //debugBelch("Creating thread %d @ %11.2f\n", tso->id, usertime());
2443 globalParStats.tot_threads_created++;
2449 sched_belch("==__ schedule: Created TSO %d (%p);",
2450 CurrentProc, tso, tso->id));
2451 #elif defined(PARALLEL_HASKELL)
2452 IF_PAR_DEBUG(verbose,
2453 sched_belch("==__ schedule: Created TSO %d (%p); %d threads active",
2454 (long)tso->id, tso, advisory_thread_count));
2456 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
2457 (long)tso->id, (long)tso->stack_size));
2464 all parallel thread creation calls should fall through the following routine.
2467 createThreadFromSpark(rtsSpark spark)
2469 ASSERT(spark != (rtsSpark)NULL);
2470 // JB: TAKE CARE OF THIS COUNTER! BUGGY
2471 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
2473 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
2474 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
2475 return END_TSO_QUEUE;
2479 tso = createThread(RtsFlags.GcFlags.initialStkSize);
2480 if (tso==END_TSO_QUEUE)
2481 barf("createSparkThread: Cannot create TSO");
2483 tso->priority = AdvisoryPriority;
2485 pushClosure(tso,spark);
2487 advisory_thread_count++; // JB: TAKE CARE OF THIS COUNTER! BUGGY
2494 Turn a spark into a thread.
2495 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
2499 activateSpark (rtsSpark spark)
2503 tso = createSparkThread(spark);
2504 if (RtsFlags.ParFlags.ParStats.Full) {
2505 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
2506 IF_PAR_DEBUG(verbose,
2507 debugBelch("==^^ activateSpark: turning spark of closure %p (%s) into a thread\n",
2508 (StgClosure *)spark, info_type((StgClosure *)spark)));
2510 // ToDo: fwd info on local/global spark to thread -- HWL
2511 // tso->gran.exported = spark->exported;
2512 // tso->gran.locked = !spark->global;
2513 // tso->gran.sparkname = spark->name;
2519 /* ---------------------------------------------------------------------------
2522 * scheduleThread puts a thread on the head of the runnable queue.
2523 * This will usually be done immediately after a thread is created.
2524 * The caller of scheduleThread must create the thread using e.g.
2525 * createThread and push an appropriate closure
2526 * on this thread's stack before the scheduler is invoked.
2527 * ------------------------------------------------------------------------ */
2530 scheduleThread_(StgTSO *tso)
2532 // The thread goes at the *end* of the run-queue, to avoid possible
2533 // starvation of any threads already on the queue.
2534 APPEND_TO_RUN_QUEUE(tso);
2539 scheduleThread(StgTSO* tso)
2541 ACQUIRE_LOCK(&sched_mutex);
2542 scheduleThread_(tso);
2543 RELEASE_LOCK(&sched_mutex);
2546 #if defined(RTS_SUPPORTS_THREADS)
2547 static Condition bound_cond_cache;
2548 static int bound_cond_cache_full = 0;
2553 scheduleWaitThread(StgTSO* tso, /*[out]*/HaskellObj* ret,
2554 Capability *initialCapability)
2556 // Precondition: sched_mutex must be held
2559 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2564 m->link = main_threads;
2566 if (main_threads != NULL) {
2567 main_threads->prev = m;
2571 #if defined(RTS_SUPPORTS_THREADS)
2572 // Allocating a new condition for each thread is expensive, so we
2573 // cache one. This is a pretty feeble hack, but it helps speed up
2574 // consecutive call-ins quite a bit.
2575 if (bound_cond_cache_full) {
2576 m->bound_thread_cond = bound_cond_cache;
2577 bound_cond_cache_full = 0;
2579 initCondition(&m->bound_thread_cond);
2583 /* Put the thread on the main-threads list prior to scheduling the TSO.
2584 Failure to do so introduces a race condition in the MT case (as
2585 identified by Wolfgang Thaller), whereby the new task/OS thread
2586 created by scheduleThread_() would complete prior to the thread
2587 that spawned it managed to put 'itself' on the main-threads list.
2588 The upshot of it all being that the worker thread wouldn't get to
2589 signal the completion of the its work item for the main thread to
2590 see (==> it got stuck waiting.) -- sof 6/02.
2592 IF_DEBUG(scheduler, sched_belch("waiting for thread (%d)", tso->id));
2594 APPEND_TO_RUN_QUEUE(tso);
2595 // NB. Don't call threadRunnable() here, because the thread is
2596 // bound and only runnable by *this* OS thread, so waking up other
2597 // workers will just slow things down.
2599 return waitThread_(m, initialCapability);
2602 /* ---------------------------------------------------------------------------
2605 * Initialise the scheduler. This resets all the queues - if the
2606 * queues contained any threads, they'll be garbage collected at the
2609 * ------------------------------------------------------------------------ */
2617 for (i=0; i<=MAX_PROC; i++) {
2618 run_queue_hds[i] = END_TSO_QUEUE;
2619 run_queue_tls[i] = END_TSO_QUEUE;
2620 blocked_queue_hds[i] = END_TSO_QUEUE;
2621 blocked_queue_tls[i] = END_TSO_QUEUE;
2622 ccalling_threadss[i] = END_TSO_QUEUE;
2623 blackhole_queue[i] = END_TSO_QUEUE;
2624 sleeping_queue = END_TSO_QUEUE;
2627 run_queue_hd = END_TSO_QUEUE;
2628 run_queue_tl = END_TSO_QUEUE;
2629 blocked_queue_hd = END_TSO_QUEUE;
2630 blocked_queue_tl = END_TSO_QUEUE;
2631 blackhole_queue = END_TSO_QUEUE;
2632 sleeping_queue = END_TSO_QUEUE;
2635 suspended_ccalling_threads = END_TSO_QUEUE;
2637 main_threads = NULL;
2638 all_threads = END_TSO_QUEUE;
2643 RtsFlags.ConcFlags.ctxtSwitchTicks =
2644 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
2646 #if defined(RTS_SUPPORTS_THREADS)
2647 /* Initialise the mutex and condition variables used by
2649 initMutex(&sched_mutex);
2650 initMutex(&term_mutex);
2653 ACQUIRE_LOCK(&sched_mutex);
2655 /* A capability holds the state a native thread needs in
2656 * order to execute STG code. At least one capability is
2657 * floating around (only SMP builds have more than one).
2661 #if defined(RTS_SUPPORTS_THREADS)
2666 /* eagerly start some extra workers */
2667 startingWorkerThread = RtsFlags.ParFlags.nNodes;
2668 startTasks(RtsFlags.ParFlags.nNodes, taskStart);
2671 #if /* defined(SMP) ||*/ defined(PARALLEL_HASKELL)
2675 RELEASE_LOCK(&sched_mutex);
2679 exitScheduler( void )
2681 interrupted = rtsTrue;
2682 shutting_down_scheduler = rtsTrue;
2683 #if defined(RTS_SUPPORTS_THREADS)
2684 if (threadIsTask(osThreadId())) { taskStop(); }
2689 /* ----------------------------------------------------------------------------
2690 Managing the per-task allocation areas.
2692 Each capability comes with an allocation area. These are
2693 fixed-length block lists into which allocation can be done.
2695 ToDo: no support for two-space collection at the moment???
2696 ------------------------------------------------------------------------- */
2698 static SchedulerStatus
2699 waitThread_(StgMainThread* m, Capability *initialCapability)
2701 SchedulerStatus stat;
2703 // Precondition: sched_mutex must be held.
2704 IF_DEBUG(scheduler, sched_belch("new main thread (%d)", m->tso->id));
2707 /* GranSim specific init */
2708 CurrentTSO = m->tso; // the TSO to run
2709 procStatus[MainProc] = Busy; // status of main PE
2710 CurrentProc = MainProc; // PE to run it on
2711 schedule(m,initialCapability);
2713 schedule(m,initialCapability);
2714 ASSERT(m->stat != NoStatus);
2719 #if defined(RTS_SUPPORTS_THREADS)
2720 // Free the condition variable, returning it to the cache if possible.
2721 if (!bound_cond_cache_full) {
2722 bound_cond_cache = m->bound_thread_cond;
2723 bound_cond_cache_full = 1;
2725 closeCondition(&m->bound_thread_cond);
2729 IF_DEBUG(scheduler, sched_belch("main thread (%d) finished", m->tso->id));
2732 // Postcondition: sched_mutex still held
2736 /* ---------------------------------------------------------------------------
2737 Where are the roots that we know about?
2739 - all the threads on the runnable queue
2740 - all the threads on the blocked queue
2741 - all the threads on the sleeping queue
2742 - all the thread currently executing a _ccall_GC
2743 - all the "main threads"
2745 ------------------------------------------------------------------------ */
2747 /* This has to be protected either by the scheduler monitor, or by the
2748 garbage collection monitor (probably the latter).
2753 GetRoots( evac_fn evac )
2758 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2759 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2760 evac((StgClosure **)&run_queue_hds[i]);
2761 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2762 evac((StgClosure **)&run_queue_tls[i]);
2764 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2765 evac((StgClosure **)&blocked_queue_hds[i]);
2766 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2767 evac((StgClosure **)&blocked_queue_tls[i]);
2768 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2769 evac((StgClosure **)&ccalling_threads[i]);
2776 if (run_queue_hd != END_TSO_QUEUE) {
2777 ASSERT(run_queue_tl != END_TSO_QUEUE);
2778 evac((StgClosure **)&run_queue_hd);
2779 evac((StgClosure **)&run_queue_tl);
2782 if (blocked_queue_hd != END_TSO_QUEUE) {
2783 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2784 evac((StgClosure **)&blocked_queue_hd);
2785 evac((StgClosure **)&blocked_queue_tl);
2788 if (sleeping_queue != END_TSO_QUEUE) {
2789 evac((StgClosure **)&sleeping_queue);
2793 if (blackhole_queue != END_TSO_QUEUE) {
2794 evac((StgClosure **)&blackhole_queue);
2797 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2798 evac((StgClosure **)&suspended_ccalling_threads);
2801 #if defined(PARALLEL_HASKELL) || defined(GRAN)
2802 markSparkQueue(evac);
2805 #if defined(RTS_USER_SIGNALS)
2806 // mark the signal handlers (signals should be already blocked)
2807 markSignalHandlers(evac);
2811 /* -----------------------------------------------------------------------------
2814 This is the interface to the garbage collector from Haskell land.
2815 We provide this so that external C code can allocate and garbage
2816 collect when called from Haskell via _ccall_GC.
2818 It might be useful to provide an interface whereby the programmer
2819 can specify more roots (ToDo).
2821 This needs to be protected by the GC condition variable above. KH.
2822 -------------------------------------------------------------------------- */
2824 static void (*extra_roots)(evac_fn);
2829 /* Obligated to hold this lock upon entry */
2830 ACQUIRE_LOCK(&sched_mutex);
2831 GarbageCollect(GetRoots,rtsFalse);
2832 RELEASE_LOCK(&sched_mutex);
2836 performMajorGC(void)
2838 ACQUIRE_LOCK(&sched_mutex);
2839 GarbageCollect(GetRoots,rtsTrue);
2840 RELEASE_LOCK(&sched_mutex);
2844 AllRoots(evac_fn evac)
2846 GetRoots(evac); // the scheduler's roots
2847 extra_roots(evac); // the user's roots
2851 performGCWithRoots(void (*get_roots)(evac_fn))
2853 ACQUIRE_LOCK(&sched_mutex);
2854 extra_roots = get_roots;
2855 GarbageCollect(AllRoots,rtsFalse);
2856 RELEASE_LOCK(&sched_mutex);
2859 /* -----------------------------------------------------------------------------
2862 If the thread has reached its maximum stack size, then raise the
2863 StackOverflow exception in the offending thread. Otherwise
2864 relocate the TSO into a larger chunk of memory and adjust its stack
2866 -------------------------------------------------------------------------- */
2869 threadStackOverflow(StgTSO *tso)
2871 nat new_stack_size, stack_words;
2876 IF_DEBUG(sanity,checkTSO(tso));
2877 if (tso->stack_size >= tso->max_stack_size) {
2880 debugBelch("@@ threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)\n",
2881 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2882 /* If we're debugging, just print out the top of the stack */
2883 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2886 /* Send this thread the StackOverflow exception */
2887 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2891 /* Try to double the current stack size. If that takes us over the
2892 * maximum stack size for this thread, then use the maximum instead.
2893 * Finally round up so the TSO ends up as a whole number of blocks.
2895 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2896 new_tso_size = (lnat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2897 TSO_STRUCT_SIZE)/sizeof(W_);
2898 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2899 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2901 IF_DEBUG(scheduler, debugBelch("== sched: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2903 dest = (StgTSO *)allocate(new_tso_size);
2904 TICK_ALLOC_TSO(new_stack_size,0);
2906 /* copy the TSO block and the old stack into the new area */
2907 memcpy(dest,tso,TSO_STRUCT_SIZE);
2908 stack_words = tso->stack + tso->stack_size - tso->sp;
2909 new_sp = (P_)dest + new_tso_size - stack_words;
2910 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2912 /* relocate the stack pointers... */
2914 dest->stack_size = new_stack_size;
2916 /* Mark the old TSO as relocated. We have to check for relocated
2917 * TSOs in the garbage collector and any primops that deal with TSOs.
2919 * It's important to set the sp value to just beyond the end
2920 * of the stack, so we don't attempt to scavenge any part of the
2923 tso->what_next = ThreadRelocated;
2925 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2926 tso->why_blocked = NotBlocked;
2928 IF_PAR_DEBUG(verbose,
2929 debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2930 tso->id, tso, tso->stack_size);
2931 /* If we're debugging, just print out the top of the stack */
2932 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2935 IF_DEBUG(sanity,checkTSO(tso));
2937 IF_DEBUG(scheduler,printTSO(dest));
2943 /* ---------------------------------------------------------------------------
2944 Wake up a queue that was blocked on some resource.
2945 ------------------------------------------------------------------------ */
2949 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2952 #elif defined(PARALLEL_HASKELL)
2954 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2956 /* write RESUME events to log file and
2957 update blocked and fetch time (depending on type of the orig closure) */
2958 if (RtsFlags.ParFlags.ParStats.Full) {
2959 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2960 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2961 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2962 if (EMPTY_RUN_QUEUE())
2963 emitSchedule = rtsTrue;
2965 switch (get_itbl(node)->type) {
2967 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2972 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2979 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2986 static StgBlockingQueueElement *
2987 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2990 PEs node_loc, tso_loc;
2992 node_loc = where_is(node); // should be lifted out of loop
2993 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2994 tso_loc = where_is((StgClosure *)tso);
2995 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2996 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2997 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2998 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2999 // insertThread(tso, node_loc);
3000 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
3002 tso, node, (rtsSpark*)NULL);
3003 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
3006 } else { // TSO is remote (actually should be FMBQ)
3007 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
3008 RtsFlags.GranFlags.Costs.gunblocktime +
3009 RtsFlags.GranFlags.Costs.latency;
3010 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
3012 tso, node, (rtsSpark*)NULL);
3013 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
3016 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
3018 debugBelch(" %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
3019 (node_loc==tso_loc ? "Local" : "Global"),
3020 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
3021 tso->block_info.closure = NULL;
3022 IF_DEBUG(scheduler,debugBelch("-- Waking up thread %ld (%p)\n",
3025 #elif defined(PARALLEL_HASKELL)
3026 static StgBlockingQueueElement *
3027 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
3029 StgBlockingQueueElement *next;
3031 switch (get_itbl(bqe)->type) {
3033 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
3034 /* if it's a TSO just push it onto the run_queue */
3036 ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
3037 APPEND_TO_RUN_QUEUE((StgTSO *)bqe);
3039 unblockCount(bqe, node);
3040 /* reset blocking status after dumping event */
3041 ((StgTSO *)bqe)->why_blocked = NotBlocked;
3045 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
3047 bqe->link = (StgBlockingQueueElement *)PendingFetches;
3048 PendingFetches = (StgBlockedFetch *)bqe;
3052 /* can ignore this case in a non-debugging setup;
3053 see comments on RBHSave closures above */
3055 /* check that the closure is an RBHSave closure */
3056 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
3057 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
3058 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
3062 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
3063 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
3067 IF_PAR_DEBUG(bq, debugBelch(", %p (%s)\n", bqe, info_type((StgClosure*)bqe)));
3071 #else /* !GRAN && !PARALLEL_HASKELL */
3073 unblockOneLocked(StgTSO *tso)
3077 ASSERT(get_itbl(tso)->type == TSO);
3078 ASSERT(tso->why_blocked != NotBlocked);
3079 tso->why_blocked = NotBlocked;
3081 tso->link = END_TSO_QUEUE;
3082 APPEND_TO_RUN_QUEUE(tso);
3084 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", (long)tso->id));
3089 #if defined(GRAN) || defined(PARALLEL_HASKELL)
3090 INLINE_ME StgBlockingQueueElement *
3091 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
3093 ACQUIRE_LOCK(&sched_mutex);
3094 bqe = unblockOneLocked(bqe, node);
3095 RELEASE_LOCK(&sched_mutex);
3100 unblockOne(StgTSO *tso)
3102 ACQUIRE_LOCK(&sched_mutex);
3103 tso = unblockOneLocked(tso);
3104 RELEASE_LOCK(&sched_mutex);
3111 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
3113 StgBlockingQueueElement *bqe;
3118 debugBelch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): \n", \
3119 node, CurrentProc, CurrentTime[CurrentProc],
3120 CurrentTSO->id, CurrentTSO));
3122 node_loc = where_is(node);
3124 ASSERT(q == END_BQ_QUEUE ||
3125 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
3126 get_itbl(q)->type == CONSTR); // closure (type constructor)
3127 ASSERT(is_unique(node));
3129 /* FAKE FETCH: magically copy the node to the tso's proc;
3130 no Fetch necessary because in reality the node should not have been
3131 moved to the other PE in the first place
3133 if (CurrentProc!=node_loc) {
3135 debugBelch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)\n",
3136 node, node_loc, CurrentProc, CurrentTSO->id,
3137 // CurrentTSO, where_is(CurrentTSO),
3138 node->header.gran.procs));
3139 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
3141 debugBelch("## new bitmask of node %p is %#x\n",
3142 node, node->header.gran.procs));
3143 if (RtsFlags.GranFlags.GranSimStats.Global) {
3144 globalGranStats.tot_fake_fetches++;
3149 // ToDo: check: ASSERT(CurrentProc==node_loc);
3150 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
3153 bqe points to the current element in the queue
3154 next points to the next element in the queue
3156 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
3157 //tso_loc = where_is(tso);
3159 bqe = unblockOneLocked(bqe, node);
3162 /* if this is the BQ of an RBH, we have to put back the info ripped out of
3163 the closure to make room for the anchor of the BQ */
3164 if (bqe!=END_BQ_QUEUE) {
3165 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
3167 ASSERT((info_ptr==&RBH_Save_0_info) ||
3168 (info_ptr==&RBH_Save_1_info) ||
3169 (info_ptr==&RBH_Save_2_info));
3171 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
3172 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
3173 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
3176 debugBelch("## Filled in RBH_Save for %p (%s) at end of AwBQ\n",
3177 node, info_type(node)));
3180 /* statistics gathering */
3181 if (RtsFlags.GranFlags.GranSimStats.Global) {
3182 // globalGranStats.tot_bq_processing_time += bq_processing_time;
3183 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
3184 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
3185 globalGranStats.tot_awbq++; // total no. of bqs awakened
3188 debugBelch("## BQ Stats of %p: [%d entries] %s\n",
3189 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
3191 #elif defined(PARALLEL_HASKELL)
3193 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
3195 StgBlockingQueueElement *bqe;
3197 ACQUIRE_LOCK(&sched_mutex);
3199 IF_PAR_DEBUG(verbose,
3200 debugBelch("##-_ AwBQ for node %p on [%x]: \n",
3204 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
3205 IF_PAR_DEBUG(verbose, debugBelch("## ... nothing to unblock so lets just return. RFP (BUG?)\n"));
3210 ASSERT(q == END_BQ_QUEUE ||
3211 get_itbl(q)->type == TSO ||
3212 get_itbl(q)->type == BLOCKED_FETCH ||
3213 get_itbl(q)->type == CONSTR);
3216 while (get_itbl(bqe)->type==TSO ||
3217 get_itbl(bqe)->type==BLOCKED_FETCH) {
3218 bqe = unblockOneLocked(bqe, node);
3220 RELEASE_LOCK(&sched_mutex);
3223 #else /* !GRAN && !PARALLEL_HASKELL */
3226 awakenBlockedQueueNoLock(StgTSO *tso)
3228 while (tso != END_TSO_QUEUE) {
3229 tso = unblockOneLocked(tso);
3234 awakenBlockedQueue(StgTSO *tso)
3236 ACQUIRE_LOCK(&sched_mutex);
3237 while (tso != END_TSO_QUEUE) {
3238 tso = unblockOneLocked(tso);
3240 RELEASE_LOCK(&sched_mutex);
3244 /* ---------------------------------------------------------------------------
3246 - usually called inside a signal handler so it mustn't do anything fancy.
3247 ------------------------------------------------------------------------ */
3250 interruptStgRts(void)
3255 /* ToDo: if invoked from a signal handler, this threadRunnable
3256 * only works if there's another thread (not this one) waiting to
3261 /* -----------------------------------------------------------------------------
3264 This is for use when we raise an exception in another thread, which
3266 This has nothing to do with the UnblockThread event in GranSim. -- HWL
3267 -------------------------------------------------------------------------- */
3269 #if defined(GRAN) || defined(PARALLEL_HASKELL)
3271 NB: only the type of the blocking queue is different in GranSim and GUM
3272 the operations on the queue-elements are the same
3273 long live polymorphism!
3275 Locks: sched_mutex is held upon entry and exit.
3279 unblockThread(StgTSO *tso)
3281 StgBlockingQueueElement *t, **last;
3283 switch (tso->why_blocked) {
3286 return; /* not blocked */
3289 // Be careful: nothing to do here! We tell the scheduler that the thread
3290 // is runnable and we leave it to the stack-walking code to abort the
3291 // transaction while unwinding the stack. We should perhaps have a debugging
3292 // test to make sure that this really happens and that the 'zombie' transaction
3293 // does not get committed.
3297 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3299 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
3300 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3302 last = (StgBlockingQueueElement **)&mvar->head;
3303 for (t = (StgBlockingQueueElement *)mvar->head;
3305 last = &t->link, last_tso = t, t = t->link) {
3306 if (t == (StgBlockingQueueElement *)tso) {
3307 *last = (StgBlockingQueueElement *)tso->link;
3308 if (mvar->tail == tso) {
3309 mvar->tail = (StgTSO *)last_tso;
3314 barf("unblockThread (MVAR): TSO not found");
3317 case BlockedOnBlackHole:
3318 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3320 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3322 last = &bq->blocking_queue;
3323 for (t = bq->blocking_queue;
3325 last = &t->link, t = t->link) {
3326 if (t == (StgBlockingQueueElement *)tso) {
3327 *last = (StgBlockingQueueElement *)tso->link;
3331 barf("unblockThread (BLACKHOLE): TSO not found");
3334 case BlockedOnException:
3336 StgTSO *target = tso->block_info.tso;
3338 ASSERT(get_itbl(target)->type == TSO);
3340 if (target->what_next == ThreadRelocated) {
3341 target = target->link;
3342 ASSERT(get_itbl(target)->type == TSO);
3345 ASSERT(target->blocked_exceptions != NULL);
3347 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
3348 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
3350 last = &t->link, t = t->link) {
3351 ASSERT(get_itbl(t)->type == TSO);
3352 if (t == (StgBlockingQueueElement *)tso) {
3353 *last = (StgBlockingQueueElement *)tso->link;
3357 barf("unblockThread (Exception): TSO not found");
3361 case BlockedOnWrite:
3362 #if defined(mingw32_HOST_OS)
3363 case BlockedOnDoProc:
3366 /* take TSO off blocked_queue */
3367 StgBlockingQueueElement *prev = NULL;
3368 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
3369 prev = t, t = t->link) {
3370 if (t == (StgBlockingQueueElement *)tso) {
3372 blocked_queue_hd = (StgTSO *)t->link;
3373 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3374 blocked_queue_tl = END_TSO_QUEUE;
3377 prev->link = t->link;
3378 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3379 blocked_queue_tl = (StgTSO *)prev;
3382 #if defined(mingw32_HOST_OS)
3383 /* (Cooperatively) signal that the worker thread should abort
3386 abandonWorkRequest(tso->block_info.async_result->reqID);
3391 barf("unblockThread (I/O): TSO not found");
3394 case BlockedOnDelay:
3396 /* take TSO off sleeping_queue */
3397 StgBlockingQueueElement *prev = NULL;
3398 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
3399 prev = t, t = t->link) {
3400 if (t == (StgBlockingQueueElement *)tso) {
3402 sleeping_queue = (StgTSO *)t->link;
3404 prev->link = t->link;
3409 barf("unblockThread (delay): TSO not found");
3413 barf("unblockThread");
3417 tso->link = END_TSO_QUEUE;
3418 tso->why_blocked = NotBlocked;
3419 tso->block_info.closure = NULL;
3420 PUSH_ON_RUN_QUEUE(tso);
3424 unblockThread(StgTSO *tso)
3428 /* To avoid locking unnecessarily. */
3429 if (tso->why_blocked == NotBlocked) {
3433 switch (tso->why_blocked) {
3436 // Be careful: nothing to do here! We tell the scheduler that the thread
3437 // is runnable and we leave it to the stack-walking code to abort the
3438 // transaction while unwinding the stack. We should perhaps have a debugging
3439 // test to make sure that this really happens and that the 'zombie' transaction
3440 // does not get committed.
3444 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3446 StgTSO *last_tso = END_TSO_QUEUE;
3447 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3450 for (t = mvar->head; t != END_TSO_QUEUE;
3451 last = &t->link, last_tso = t, t = t->link) {
3454 if (mvar->tail == tso) {
3455 mvar->tail = last_tso;
3460 barf("unblockThread (MVAR): TSO not found");
3463 case BlockedOnBlackHole:
3465 last = &blackhole_queue;
3466 for (t = blackhole_queue; t != END_TSO_QUEUE;
3467 last = &t->link, t = t->link) {
3473 barf("unblockThread (BLACKHOLE): TSO not found");
3476 case BlockedOnException:
3478 StgTSO *target = tso->block_info.tso;
3480 ASSERT(get_itbl(target)->type == TSO);
3482 while (target->what_next == ThreadRelocated) {
3483 target = target->link;
3484 ASSERT(get_itbl(target)->type == TSO);
3487 ASSERT(target->blocked_exceptions != NULL);
3489 last = &target->blocked_exceptions;
3490 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
3491 last = &t->link, t = t->link) {
3492 ASSERT(get_itbl(t)->type == TSO);
3498 barf("unblockThread (Exception): TSO not found");
3502 case BlockedOnWrite:
3503 #if defined(mingw32_HOST_OS)
3504 case BlockedOnDoProc:
3507 StgTSO *prev = NULL;
3508 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
3509 prev = t, t = t->link) {
3512 blocked_queue_hd = t->link;
3513 if (blocked_queue_tl == t) {
3514 blocked_queue_tl = END_TSO_QUEUE;
3517 prev->link = t->link;
3518 if (blocked_queue_tl == t) {
3519 blocked_queue_tl = prev;
3522 #if defined(mingw32_HOST_OS)
3523 /* (Cooperatively) signal that the worker thread should abort
3526 abandonWorkRequest(tso->block_info.async_result->reqID);
3531 barf("unblockThread (I/O): TSO not found");
3534 case BlockedOnDelay:
3536 StgTSO *prev = NULL;
3537 for (t = sleeping_queue; t != END_TSO_QUEUE;
3538 prev = t, t = t->link) {
3541 sleeping_queue = t->link;
3543 prev->link = t->link;
3548 barf("unblockThread (delay): TSO not found");
3552 barf("unblockThread");
3556 tso->link = END_TSO_QUEUE;
3557 tso->why_blocked = NotBlocked;
3558 tso->block_info.closure = NULL;
3559 APPEND_TO_RUN_QUEUE(tso);
3563 /* -----------------------------------------------------------------------------
3566 * Check the blackhole_queue for threads that can be woken up. We do
3567 * this periodically: before every GC, and whenever the run queue is
3570 * An elegant solution might be to just wake up all the blocked
3571 * threads with awakenBlockedQueue occasionally: they'll go back to
3572 * sleep again if the object is still a BLACKHOLE. Unfortunately this
3573 * doesn't give us a way to tell whether we've actually managed to
3574 * wake up any threads, so we would be busy-waiting.
3576 * -------------------------------------------------------------------------- */
3579 checkBlackHoles( void )
3582 rtsBool any_woke_up = rtsFalse;
3585 IF_DEBUG(scheduler, sched_belch("checking threads blocked on black holes"));
3587 // ASSUMES: sched_mutex
3588 prev = &blackhole_queue;
3589 t = blackhole_queue;
3590 while (t != END_TSO_QUEUE) {
3591 ASSERT(t->why_blocked == BlockedOnBlackHole);
3592 type = get_itbl(t->block_info.closure)->type;
3593 if (type != BLACKHOLE && type != CAF_BLACKHOLE) {
3594 t = unblockOneLocked(t);
3596 any_woke_up = rtsTrue;
3606 /* -----------------------------------------------------------------------------
3609 * The following function implements the magic for raising an
3610 * asynchronous exception in an existing thread.
3612 * We first remove the thread from any queue on which it might be
3613 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
3615 * We strip the stack down to the innermost CATCH_FRAME, building
3616 * thunks in the heap for all the active computations, so they can
3617 * be restarted if necessary. When we reach a CATCH_FRAME, we build
3618 * an application of the handler to the exception, and push it on
3619 * the top of the stack.
3621 * How exactly do we save all the active computations? We create an
3622 * AP_STACK for every UpdateFrame on the stack. Entering one of these
3623 * AP_STACKs pushes everything from the corresponding update frame
3624 * upwards onto the stack. (Actually, it pushes everything up to the
3625 * next update frame plus a pointer to the next AP_STACK object.
3626 * Entering the next AP_STACK object pushes more onto the stack until we
3627 * reach the last AP_STACK object - at which point the stack should look
3628 * exactly as it did when we killed the TSO and we can continue
3629 * execution by entering the closure on top of the stack.
3631 * We can also kill a thread entirely - this happens if either (a) the
3632 * exception passed to raiseAsync is NULL, or (b) there's no
3633 * CATCH_FRAME on the stack. In either case, we strip the entire
3634 * stack and replace the thread with a zombie.
3636 * Locks: sched_mutex held upon entry nor exit.
3638 * -------------------------------------------------------------------------- */
3641 deleteThread(StgTSO *tso)
3643 if (tso->why_blocked != BlockedOnCCall &&
3644 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
3645 raiseAsync(tso,NULL);
3649 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
3651 deleteThreadImmediately(StgTSO *tso)
3652 { // for forkProcess only:
3653 // delete thread without giving it a chance to catch the KillThread exception
3655 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3659 if (tso->why_blocked != BlockedOnCCall &&
3660 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
3664 tso->what_next = ThreadKilled;
3669 raiseAsyncWithLock(StgTSO *tso, StgClosure *exception)
3671 /* When raising async exs from contexts where sched_mutex isn't held;
3672 use raiseAsyncWithLock(). */
3673 ACQUIRE_LOCK(&sched_mutex);
3674 raiseAsync(tso,exception);
3675 RELEASE_LOCK(&sched_mutex);
3679 raiseAsync(StgTSO *tso, StgClosure *exception)
3681 raiseAsync_(tso, exception, rtsFalse);
3685 raiseAsync_(StgTSO *tso, StgClosure *exception, rtsBool stop_at_atomically)
3687 StgRetInfoTable *info;
3690 // Thread already dead?
3691 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3696 sched_belch("raising exception in thread %ld.", (long)tso->id));
3698 // Remove it from any blocking queues
3703 // The stack freezing code assumes there's a closure pointer on
3704 // the top of the stack, so we have to arrange that this is the case...
3706 if (sp[0] == (W_)&stg_enter_info) {
3710 sp[0] = (W_)&stg_dummy_ret_closure;
3716 // 1. Let the top of the stack be the "current closure"
3718 // 2. Walk up the stack until we find either an UPDATE_FRAME or a
3721 // 3. If it's an UPDATE_FRAME, then make an AP_STACK containing the
3722 // current closure applied to the chunk of stack up to (but not
3723 // including) the update frame. This closure becomes the "current
3724 // closure". Go back to step 2.
3726 // 4. If it's a CATCH_FRAME, then leave the exception handler on
3727 // top of the stack applied to the exception.
3729 // 5. If it's a STOP_FRAME, then kill the thread.
3731 // NB: if we pass an ATOMICALLY_FRAME then abort the associated
3738 info = get_ret_itbl((StgClosure *)frame);
3740 while (info->i.type != UPDATE_FRAME
3741 && (info->i.type != CATCH_FRAME || exception == NULL)
3742 && info->i.type != STOP_FRAME
3743 && (info->i.type != ATOMICALLY_FRAME || stop_at_atomically == rtsFalse))
3745 if (info->i.type == CATCH_RETRY_FRAME || info->i.type == ATOMICALLY_FRAME) {
3746 // IF we find an ATOMICALLY_FRAME then we abort the
3747 // current transaction and propagate the exception. In
3748 // this case (unlike ordinary exceptions) we do not care
3749 // whether the transaction is valid or not because its
3750 // possible validity cannot have caused the exception
3751 // and will not be visible after the abort.
3753 debugBelch("Found atomically block delivering async exception\n"));
3754 stmAbortTransaction(tso -> trec);
3755 tso -> trec = stmGetEnclosingTRec(tso -> trec);
3757 frame += stack_frame_sizeW((StgClosure *)frame);
3758 info = get_ret_itbl((StgClosure *)frame);
3761 switch (info->i.type) {
3763 case ATOMICALLY_FRAME:
3764 ASSERT(stop_at_atomically);
3765 ASSERT(stmGetEnclosingTRec(tso->trec) == NO_TREC);
3766 stmCondemnTransaction(tso -> trec);
3770 // R1 is not a register: the return convention for IO in
3771 // this case puts the return value on the stack, so we
3772 // need to set up the stack to return to the atomically
3773 // frame properly...
3774 tso->sp = frame - 2;
3775 tso->sp[1] = (StgWord) &stg_NO_FINALIZER_closure; // why not?
3776 tso->sp[0] = (StgWord) &stg_ut_1_0_unreg_info;
3778 tso->what_next = ThreadRunGHC;
3782 // If we find a CATCH_FRAME, and we've got an exception to raise,
3783 // then build the THUNK raise(exception), and leave it on
3784 // top of the CATCH_FRAME ready to enter.
3788 StgCatchFrame *cf = (StgCatchFrame *)frame;
3792 // we've got an exception to raise, so let's pass it to the
3793 // handler in this frame.
3795 raise = (StgThunk *)allocate(sizeofW(StgThunk)+1);
3796 TICK_ALLOC_SE_THK(1,0);
3797 SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
3798 raise->payload[0] = exception;
3800 // throw away the stack from Sp up to the CATCH_FRAME.
3804 /* Ensure that async excpetions are blocked now, so we don't get
3805 * a surprise exception before we get around to executing the
3808 if (tso->blocked_exceptions == NULL) {
3809 tso->blocked_exceptions = END_TSO_QUEUE;
3812 /* Put the newly-built THUNK on top of the stack, ready to execute
3813 * when the thread restarts.
3816 sp[-1] = (W_)&stg_enter_info;
3818 tso->what_next = ThreadRunGHC;
3819 IF_DEBUG(sanity, checkTSO(tso));
3828 // First build an AP_STACK consisting of the stack chunk above the
3829 // current update frame, with the top word on the stack as the
3832 words = frame - sp - 1;
3833 ap = (StgAP_STACK *)allocate(AP_STACK_sizeW(words));
3836 ap->fun = (StgClosure *)sp[0];
3838 for(i=0; i < (nat)words; ++i) {
3839 ap->payload[i] = (StgClosure *)*sp++;
3842 SET_HDR(ap,&stg_AP_STACK_info,
3843 ((StgClosure *)frame)->header.prof.ccs /* ToDo */);
3844 TICK_ALLOC_UP_THK(words+1,0);
3847 debugBelch("sched: Updating ");
3848 printPtr((P_)((StgUpdateFrame *)frame)->updatee);
3849 debugBelch(" with ");
3850 printObj((StgClosure *)ap);
3853 // Replace the updatee with an indirection - happily
3854 // this will also wake up any threads currently
3855 // waiting on the result.
3857 // Warning: if we're in a loop, more than one update frame on
3858 // the stack may point to the same object. Be careful not to
3859 // overwrite an IND_OLDGEN in this case, because we'll screw
3860 // up the mutable lists. To be on the safe side, don't
3861 // overwrite any kind of indirection at all. See also
3862 // threadSqueezeStack in GC.c, where we have to make a similar
3865 if (!closure_IND(((StgUpdateFrame *)frame)->updatee)) {
3866 // revert the black hole
3867 UPD_IND_NOLOCK(((StgUpdateFrame *)frame)->updatee,
3870 sp += sizeofW(StgUpdateFrame) - 1;
3871 sp[0] = (W_)ap; // push onto stack
3876 // We've stripped the entire stack, the thread is now dead.
3877 sp += sizeofW(StgStopFrame);
3878 tso->what_next = ThreadKilled;
3889 /* -----------------------------------------------------------------------------
3890 raiseExceptionHelper
3892 This function is called by the raise# primitve, just so that we can
3893 move some of the tricky bits of raising an exception from C-- into
3894 C. Who knows, it might be a useful re-useable thing here too.
3895 -------------------------------------------------------------------------- */
3898 raiseExceptionHelper (StgTSO *tso, StgClosure *exception)
3900 StgThunk *raise_closure = NULL;
3902 StgRetInfoTable *info;
3904 // This closure represents the expression 'raise# E' where E
3905 // is the exception raise. It is used to overwrite all the
3906 // thunks which are currently under evaluataion.
3910 // LDV profiling: stg_raise_info has THUNK as its closure
3911 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
3912 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
3913 // 1 does not cause any problem unless profiling is performed.
3914 // However, when LDV profiling goes on, we need to linearly scan
3915 // small object pool, where raise_closure is stored, so we should
3916 // use MIN_UPD_SIZE.
3918 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
3919 // sizeofW(StgClosure)+1);
3923 // Walk up the stack, looking for the catch frame. On the way,
3924 // we update any closures pointed to from update frames with the
3925 // raise closure that we just built.
3929 info = get_ret_itbl((StgClosure *)p);
3930 next = p + stack_frame_sizeW((StgClosure *)p);
3931 switch (info->i.type) {
3934 // Only create raise_closure if we need to.
3935 if (raise_closure == NULL) {
3937 (StgThunk *)allocate(sizeofW(StgThunk)+MIN_UPD_SIZE);
3938 SET_HDR(raise_closure, &stg_raise_info, CCCS);
3939 raise_closure->payload[0] = exception;
3941 UPD_IND(((StgUpdateFrame *)p)->updatee,(StgClosure *)raise_closure);
3945 case ATOMICALLY_FRAME:
3946 IF_DEBUG(stm, debugBelch("Found ATOMICALLY_FRAME at %p\n", p));
3948 return ATOMICALLY_FRAME;
3954 case CATCH_STM_FRAME:
3955 IF_DEBUG(stm, debugBelch("Found CATCH_STM_FRAME at %p\n", p));
3957 return CATCH_STM_FRAME;
3963 case CATCH_RETRY_FRAME:
3972 /* -----------------------------------------------------------------------------
3973 findRetryFrameHelper
3975 This function is called by the retry# primitive. It traverses the stack
3976 leaving tso->sp referring to the frame which should handle the retry.
3978 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
3979 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
3981 We skip CATCH_STM_FRAMEs because retries are not considered to be exceptions,
3982 despite the similar implementation.
3984 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
3985 not be created within memory transactions.
3986 -------------------------------------------------------------------------- */
3989 findRetryFrameHelper (StgTSO *tso)
3992 StgRetInfoTable *info;
3996 info = get_ret_itbl((StgClosure *)p);
3997 next = p + stack_frame_sizeW((StgClosure *)p);
3998 switch (info->i.type) {
4000 case ATOMICALLY_FRAME:
4001 IF_DEBUG(stm, debugBelch("Found ATOMICALLY_FRAME at %p during retrry\n", p));
4003 return ATOMICALLY_FRAME;
4005 case CATCH_RETRY_FRAME:
4006 IF_DEBUG(stm, debugBelch("Found CATCH_RETRY_FRAME at %p during retrry\n", p));
4008 return CATCH_RETRY_FRAME;
4010 case CATCH_STM_FRAME:
4012 ASSERT(info->i.type != CATCH_FRAME);
4013 ASSERT(info->i.type != STOP_FRAME);
4020 /* -----------------------------------------------------------------------------
4021 resurrectThreads is called after garbage collection on the list of
4022 threads found to be garbage. Each of these threads will be woken
4023 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
4024 on an MVar, or NonTermination if the thread was blocked on a Black
4027 Locks: sched_mutex isn't held upon entry nor exit.
4028 -------------------------------------------------------------------------- */
4031 resurrectThreads( StgTSO *threads )
4035 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
4036 next = tso->global_link;
4037 tso->global_link = all_threads;
4039 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
4041 switch (tso->why_blocked) {
4043 case BlockedOnException:
4044 /* Called by GC - sched_mutex lock is currently held. */
4045 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
4047 case BlockedOnBlackHole:
4048 raiseAsync(tso,(StgClosure *)NonTermination_closure);
4051 raiseAsync(tso,(StgClosure *)BlockedIndefinitely_closure);
4054 /* This might happen if the thread was blocked on a black hole
4055 * belonging to a thread that we've just woken up (raiseAsync
4056 * can wake up threads, remember...).
4060 barf("resurrectThreads: thread blocked in a strange way");
4065 /* ----------------------------------------------------------------------------
4066 * Debugging: why is a thread blocked
4067 * [Also provides useful information when debugging threaded programs
4068 * at the Haskell source code level, so enable outside of DEBUG. --sof 7/02]
4069 ------------------------------------------------------------------------- */
4072 printThreadBlockage(StgTSO *tso)
4074 switch (tso->why_blocked) {
4076 debugBelch("is blocked on read from fd %ld", tso->block_info.fd);
4078 case BlockedOnWrite:
4079 debugBelch("is blocked on write to fd %ld", tso->block_info.fd);
4081 #if defined(mingw32_HOST_OS)
4082 case BlockedOnDoProc:
4083 debugBelch("is blocked on proc (request: %ld)", tso->block_info.async_result->reqID);
4086 case BlockedOnDelay:
4087 debugBelch("is blocked until %ld", tso->block_info.target);
4090 debugBelch("is blocked on an MVar");
4092 case BlockedOnException:
4093 debugBelch("is blocked on delivering an exception to thread %d",
4094 tso->block_info.tso->id);
4096 case BlockedOnBlackHole:
4097 debugBelch("is blocked on a black hole");
4100 debugBelch("is not blocked");
4102 #if defined(PARALLEL_HASKELL)
4104 debugBelch("is blocked on global address; local FM_BQ is %p (%s)",
4105 tso->block_info.closure, info_type(tso->block_info.closure));
4107 case BlockedOnGA_NoSend:
4108 debugBelch("is blocked on global address (no send); local FM_BQ is %p (%s)",
4109 tso->block_info.closure, info_type(tso->block_info.closure));
4112 case BlockedOnCCall:
4113 debugBelch("is blocked on an external call");
4115 case BlockedOnCCall_NoUnblockExc:
4116 debugBelch("is blocked on an external call (exceptions were already blocked)");
4119 debugBelch("is blocked on an STM operation");
4122 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
4123 tso->why_blocked, tso->id, tso);
4128 printThreadStatus(StgTSO *tso)
4130 switch (tso->what_next) {
4132 debugBelch("has been killed");
4134 case ThreadComplete:
4135 debugBelch("has completed");
4138 printThreadBlockage(tso);
4143 printAllThreads(void)
4148 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
4149 ullong_format_string(TIME_ON_PROC(CurrentProc),
4150 time_string, rtsFalse/*no commas!*/);
4152 debugBelch("all threads at [%s]:\n", time_string);
4153 # elif defined(PARALLEL_HASKELL)
4154 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
4155 ullong_format_string(CURRENT_TIME,
4156 time_string, rtsFalse/*no commas!*/);
4158 debugBelch("all threads at [%s]:\n", time_string);
4160 debugBelch("all threads:\n");
4163 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
4164 debugBelch("\tthread %d @ %p ", t->id, (void *)t);
4167 void *label = lookupThreadLabel(t->id);
4168 if (label) debugBelch("[\"%s\"] ",(char *)label);
4171 printThreadStatus(t);
4179 Print a whole blocking queue attached to node (debugging only).
4181 # if defined(PARALLEL_HASKELL)
4183 print_bq (StgClosure *node)
4185 StgBlockingQueueElement *bqe;
4189 debugBelch("## BQ of closure %p (%s): ",
4190 node, info_type(node));
4192 /* should cover all closures that may have a blocking queue */
4193 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
4194 get_itbl(node)->type == FETCH_ME_BQ ||
4195 get_itbl(node)->type == RBH ||
4196 get_itbl(node)->type == MVAR);
4198 ASSERT(node!=(StgClosure*)NULL); // sanity check
4200 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
4204 Print a whole blocking queue starting with the element bqe.
4207 print_bqe (StgBlockingQueueElement *bqe)
4212 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
4214 for (end = (bqe==END_BQ_QUEUE);
4215 !end; // iterate until bqe points to a CONSTR
4216 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
4217 bqe = end ? END_BQ_QUEUE : bqe->link) {
4218 ASSERT(bqe != END_BQ_QUEUE); // sanity check
4219 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
4220 /* types of closures that may appear in a blocking queue */
4221 ASSERT(get_itbl(bqe)->type == TSO ||
4222 get_itbl(bqe)->type == BLOCKED_FETCH ||
4223 get_itbl(bqe)->type == CONSTR);
4224 /* only BQs of an RBH end with an RBH_Save closure */
4225 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
4227 switch (get_itbl(bqe)->type) {
4229 debugBelch(" TSO %u (%x),",
4230 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
4233 debugBelch(" BF (node=%p, ga=((%x, %d, %x)),",
4234 ((StgBlockedFetch *)bqe)->node,
4235 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
4236 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
4237 ((StgBlockedFetch *)bqe)->ga.weight);
4240 debugBelch(" %s (IP %p),",
4241 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
4242 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
4243 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
4244 "RBH_Save_?"), get_itbl(bqe));
4247 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
4248 info_type((StgClosure *)bqe)); // , node, info_type(node));
4254 # elif defined(GRAN)
4256 print_bq (StgClosure *node)
4258 StgBlockingQueueElement *bqe;
4259 PEs node_loc, tso_loc;
4262 /* should cover all closures that may have a blocking queue */
4263 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
4264 get_itbl(node)->type == FETCH_ME_BQ ||
4265 get_itbl(node)->type == RBH);
4267 ASSERT(node!=(StgClosure*)NULL); // sanity check
4268 node_loc = where_is(node);
4270 debugBelch("## BQ of closure %p (%s) on [PE %d]: ",
4271 node, info_type(node), node_loc);
4274 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
4276 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
4277 !end; // iterate until bqe points to a CONSTR
4278 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
4279 ASSERT(bqe != END_BQ_QUEUE); // sanity check
4280 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
4281 /* types of closures that may appear in a blocking queue */
4282 ASSERT(get_itbl(bqe)->type == TSO ||
4283 get_itbl(bqe)->type == CONSTR);
4284 /* only BQs of an RBH end with an RBH_Save closure */
4285 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
4287 tso_loc = where_is((StgClosure *)bqe);
4288 switch (get_itbl(bqe)->type) {
4290 debugBelch(" TSO %d (%p) on [PE %d],",
4291 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
4294 debugBelch(" %s (IP %p),",
4295 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
4296 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
4297 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
4298 "RBH_Save_?"), get_itbl(bqe));
4301 barf("Unexpected closure type %s in blocking queue of %p (%s)",
4302 info_type((StgClosure *)bqe), node, info_type(node));
4310 #if defined(PARALLEL_HASKELL)
4317 for (i=0, tso=run_queue_hd;
4318 tso != END_TSO_QUEUE;
4327 sched_belch(char *s, ...)
4331 #ifdef RTS_SUPPORTS_THREADS
4332 debugBelch("sched (task %p): ", osThreadId());
4333 #elif defined(PARALLEL_HASKELL)
4336 debugBelch("sched: ");