1 /* ---------------------------------------------------------------------------
2 * $Id: Schedule.c,v 1.150 2002/07/19 18:45:21 sof Exp $
4 * (c) The GHC Team, 1998-2000
8 * Different GHC ways use this scheduler quite differently (see comments below)
9 * Here is the global picture:
11 * WAY Name CPP flag What's it for
12 * --------------------------------------
13 * mp GUM PAR Parallel execution on a distributed memory machine
14 * s SMP SMP Parallel execution on a shared memory machine
15 * mg GranSim GRAN Simulation of parallel execution
16 * md GUM/GdH DIST Distributed execution (based on GUM)
18 * --------------------------------------------------------------------------*/
20 //@node Main scheduling code, , ,
21 //@section Main scheduling code
24 * Version with scheduler monitor support for SMPs (WAY=s):
26 This design provides a high-level API to create and schedule threads etc.
27 as documented in the SMP design document.
29 It uses a monitor design controlled by a single mutex to exercise control
30 over accesses to shared data structures, and builds on the Posix threads
33 The majority of state is shared. In order to keep essential per-task state,
34 there is a Capability structure, which contains all the information
35 needed to run a thread: its STG registers, a pointer to its TSO, a
36 nursery etc. During STG execution, a pointer to the capability is
37 kept in a register (BaseReg).
39 In a non-SMP build, there is one global capability, namely MainRegTable.
43 * Version with support for distributed memory parallelism aka GUM (WAY=mp):
45 The main scheduling loop in GUM iterates until a finish message is received.
46 In that case a global flag @receivedFinish@ is set and this instance of
47 the RTS shuts down. See ghc/rts/parallel/HLComms.c:processMessages()
48 for the handling of incoming messages, such as PP_FINISH.
49 Note that in the parallel case we have a system manager that coordinates
50 different PEs, each of which are running one instance of the RTS.
51 See ghc/rts/parallel/SysMan.c for the main routine of the parallel program.
52 From this routine processes executing ghc/rts/Main.c are spawned. -- HWL
54 * Version with support for simulating parallel execution aka GranSim (WAY=mg):
56 The main scheduling code in GranSim is quite different from that in std
57 (concurrent) Haskell: while concurrent Haskell just iterates over the
58 threads in the runnable queue, GranSim is event driven, i.e. it iterates
59 over the events in the global event queue. -- HWL
64 //* Variables and Data structures::
65 //* Main scheduling loop::
66 //* Suspend and Resume::
68 //* Garbage Collextion Routines::
69 //* Blocking Queue Routines::
70 //* Exception Handling Routines::
71 //* Debugging Routines::
75 //@node Includes, Variables and Data structures, Main scheduling code, Main scheduling code
76 //@subsection Includes
78 #include "PosixSource.h"
85 #include "StgStartup.h"
88 #include "StgMiscClosures.h"
90 #include "Interpreter.h"
91 #include "Exception.h"
99 #include "ThreadLabels.h"
101 #include "Proftimer.h"
102 #include "ProfHeap.h"
104 #if defined(GRAN) || defined(PAR)
105 # include "GranSimRts.h"
106 # include "GranSim.h"
107 # include "ParallelRts.h"
108 # include "Parallel.h"
109 # include "ParallelDebug.h"
110 # include "FetchMe.h"
114 #include "Capability.h"
115 #include "OSThreads.h"
118 #ifdef HAVE_SYS_TYPES_H
119 #include <sys/types.h>
129 //@node Variables and Data structures, Prototypes, Includes, Main scheduling code
130 //@subsection Variables and Data structures
132 /* Main thread queue.
133 * Locks required: sched_mutex.
135 StgMainThread *main_threads;
138 * Locks required: sched_mutex.
142 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
143 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
146 In GranSim we have a runnable and a blocked queue for each processor.
147 In order to minimise code changes new arrays run_queue_hds/tls
148 are created. run_queue_hd is then a short cut (macro) for
149 run_queue_hds[CurrentProc] (see GranSim.h).
152 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
153 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
154 StgTSO *ccalling_threadss[MAX_PROC];
155 /* We use the same global list of threads (all_threads) in GranSim as in
156 the std RTS (i.e. we are cheating). However, we don't use this list in
157 the GranSim specific code at the moment (so we are only potentially
162 StgTSO *run_queue_hd, *run_queue_tl;
163 StgTSO *blocked_queue_hd, *blocked_queue_tl;
164 StgTSO *sleeping_queue; /* perhaps replace with a hash table? */
168 /* Linked list of all threads.
169 * Used for detecting garbage collected threads.
173 /* When a thread performs a safe C call (_ccall_GC, using old
174 * terminology), it gets put on the suspended_ccalling_threads
175 * list. Used by the garbage collector.
177 static StgTSO *suspended_ccalling_threads;
179 static StgTSO *threadStackOverflow(StgTSO *tso);
181 /* KH: The following two flags are shared memory locations. There is no need
182 to lock them, since they are only unset at the end of a scheduler
186 /* flag set by signal handler to precipitate a context switch */
187 //@cindex context_switch
190 /* if this flag is set as well, give up execution */
191 //@cindex interrupted
194 /* Next thread ID to allocate.
195 * Locks required: thread_id_mutex
197 //@cindex next_thread_id
198 StgThreadID next_thread_id = 1;
201 * Pointers to the state of the current thread.
202 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
203 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
206 /* The smallest stack size that makes any sense is:
207 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
208 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
209 * + 1 (the realworld token for an IO thread)
210 * + 1 (the closure to enter)
212 * A thread with this stack will bomb immediately with a stack
213 * overflow, which will increase its stack size.
216 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 2)
223 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
224 * exists - earlier gccs apparently didn't.
232 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
233 * in an MT setting, needed to signal that a worker thread shouldn't hang around
234 * in the scheduler when it is out of work.
236 static rtsBool shutting_down_scheduler = rtsFalse;
238 void addToBlockedQueue ( StgTSO *tso );
240 static void schedule ( void );
241 void interruptStgRts ( void );
243 static void detectBlackHoles ( void );
246 static void sched_belch(char *s, ...);
249 #if defined(RTS_SUPPORTS_THREADS)
250 /* ToDo: carefully document the invariants that go together
251 * with these synchronisation objects.
253 Mutex sched_mutex = INIT_MUTEX_VAR;
254 Mutex term_mutex = INIT_MUTEX_VAR;
257 * A heavyweight solution to the problem of protecting
258 * the thread_id from concurrent update.
260 Mutex thread_id_mutex = INIT_MUTEX_VAR;
264 static Condition gc_pending_cond = INIT_COND_VAR;
268 #endif /* RTS_SUPPORTS_THREADS */
272 rtsTime TimeOfLastYield;
273 rtsBool emitSchedule = rtsTrue;
277 char *whatNext_strs[] = {
285 char *threadReturnCode_strs[] = {
286 "HeapOverflow", /* might also be StackOverflow */
295 StgTSO * createSparkThread(rtsSpark spark);
296 StgTSO * activateSpark (rtsSpark spark);
300 * The thread state for the main thread.
301 // ToDo: check whether not needed any more
305 #if defined(PAR) || defined(RTS_SUPPORTS_THREADS)
306 static void taskStart(void);
317 //@node Main scheduling loop, Suspend and Resume, Prototypes, Main scheduling code
318 //@subsection Main scheduling loop
320 /* ---------------------------------------------------------------------------
321 Main scheduling loop.
323 We use round-robin scheduling, each thread returning to the
324 scheduler loop when one of these conditions is detected:
327 * timer expires (thread yields)
332 Locking notes: we acquire the scheduler lock once at the beginning
333 of the scheduler loop, and release it when
335 * running a thread, or
336 * waiting for work, or
337 * waiting for a GC to complete.
340 In a GranSim setup this loop iterates over the global event queue.
341 This revolves around the global event queue, which determines what
342 to do next. Therefore, it's more complicated than either the
343 concurrent or the parallel (GUM) setup.
346 GUM iterates over incoming messages.
347 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
348 and sends out a fish whenever it has nothing to do; in-between
349 doing the actual reductions (shared code below) it processes the
350 incoming messages and deals with delayed operations
351 (see PendingFetches).
352 This is not the ugliest code you could imagine, but it's bloody close.
354 ------------------------------------------------------------------------ */
361 StgThreadReturnCode ret;
369 rtsBool receivedFinish = rtsFalse;
371 nat tp_size, sp_size; // stats only
374 rtsBool was_interrupted = rtsFalse;
376 ACQUIRE_LOCK(&sched_mutex);
378 #if defined(RTS_SUPPORTS_THREADS)
379 waitForWorkCapability(&sched_mutex, &cap, rtsFalse);
381 /* simply initialise it in the non-threaded case */
382 grabCapability(&cap);
386 /* set up first event to get things going */
387 /* ToDo: assign costs for system setup and init MainTSO ! */
388 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
390 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
393 fprintf(stderr, "GRAN: Init CurrentTSO (in schedule) = %p\n", CurrentTSO);
394 G_TSO(CurrentTSO, 5));
396 if (RtsFlags.GranFlags.Light) {
397 /* Save current time; GranSim Light only */
398 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
401 event = get_next_event();
403 while (event!=(rtsEvent*)NULL) {
404 /* Choose the processor with the next event */
405 CurrentProc = event->proc;
406 CurrentTSO = event->tso;
410 while (!receivedFinish) { /* set by processMessages */
411 /* when receiving PP_FINISH message */
418 IF_DEBUG(scheduler, printAllThreads());
420 #if defined(RTS_SUPPORTS_THREADS)
421 /* Check to see whether there are any worker threads
422 waiting to deposit external call results. If so,
423 yield our capability */
424 yieldToReturningWorker(&sched_mutex, &cap);
427 /* If we're interrupted (the user pressed ^C, or some other
428 * termination condition occurred), kill all the currently running
432 IF_DEBUG(scheduler, sched_belch("interrupted"));
434 interrupted = rtsFalse;
435 was_interrupted = rtsTrue;
438 /* Go through the list of main threads and wake up any
439 * clients whose computations have finished. ToDo: this
440 * should be done more efficiently without a linear scan
441 * of the main threads list, somehow...
443 #if defined(RTS_SUPPORTS_THREADS)
445 StgMainThread *m, **prev;
446 prev = &main_threads;
447 for (m = main_threads; m != NULL; m = m->link) {
448 switch (m->tso->what_next) {
451 *(m->ret) = (StgClosure *)m->tso->sp[0];
455 broadcastCondition(&m->wakeup);
457 removeThreadLabel((StgWord)m->tso);
461 if (m->ret) *(m->ret) = NULL;
463 if (was_interrupted) {
464 m->stat = Interrupted;
468 broadcastCondition(&m->wakeup);
470 removeThreadLabel((StgWord)m->tso);
479 #else /* not threaded */
482 /* in GUM do this only on the Main PE */
485 /* If our main thread has finished or been killed, return.
488 StgMainThread *m = main_threads;
489 if (m->tso->what_next == ThreadComplete
490 || m->tso->what_next == ThreadKilled) {
492 removeThreadLabel((StgWord)m->tso);
494 main_threads = main_threads->link;
495 if (m->tso->what_next == ThreadComplete) {
496 /* we finished successfully, fill in the return value */
497 if (m->ret) { *(m->ret) = (StgClosure *)m->tso->sp[0]; };
501 if (m->ret) { *(m->ret) = NULL; };
502 if (was_interrupted) {
503 m->stat = Interrupted;
513 /* Top up the run queue from our spark pool. We try to make the
514 * number of threads in the run queue equal to the number of
517 * Disable spark support in SMP for now, non-essential & requires
518 * a little bit of work to make it compile cleanly. -- sof 1/02.
520 #if 0 /* defined(SMP) */
522 nat n = getFreeCapabilities();
523 StgTSO *tso = run_queue_hd;
525 /* Count the run queue */
526 while (n > 0 && tso != END_TSO_QUEUE) {
533 spark = findSpark(rtsFalse);
535 break; /* no more sparks in the pool */
537 /* I'd prefer this to be done in activateSpark -- HWL */
538 /* tricky - it needs to hold the scheduler lock and
539 * not try to re-acquire it -- SDM */
540 createSparkThread(spark);
542 sched_belch("==^^ turning spark of closure %p into a thread",
543 (StgClosure *)spark));
546 /* We need to wake up the other tasks if we just created some
549 if (getFreeCapabilities() - n > 1) {
550 signalCondition( &thread_ready_cond );
555 /* check for signals each time around the scheduler */
556 #ifndef mingw32_TARGET_OS
557 if (signals_pending()) {
558 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
559 startSignalHandlers();
560 ACQUIRE_LOCK(&sched_mutex);
564 /* Check whether any waiting threads need to be woken up. If the
565 * run queue is empty, and there are no other tasks running, we
566 * can wait indefinitely for something to happen.
567 * ToDo: what if another client comes along & requests another
570 if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue) ) {
571 awaitEvent( EMPTY_RUN_QUEUE()
573 && allFreeCapabilities()
577 /* we can be interrupted while waiting for I/O... */
578 if (interrupted) continue;
581 * Detect deadlock: when we have no threads to run, there are no
582 * threads waiting on I/O or sleeping, and all the other tasks are
583 * waiting for work, we must have a deadlock of some description.
585 * We first try to find threads blocked on themselves (ie. black
586 * holes), and generate NonTermination exceptions where necessary.
588 * If no threads are black holed, we have a deadlock situation, so
589 * inform all the main threads.
592 if ( EMPTY_THREAD_QUEUES()
593 #if defined(RTS_SUPPORTS_THREADS)
594 && EMPTY_QUEUE(suspended_ccalling_threads)
597 && allFreeCapabilities()
601 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
602 #if defined(THREADED_RTS)
603 /* and SMP mode ..? */
604 releaseCapability(cap);
606 // Garbage collection can release some new threads due to
607 // either (a) finalizers or (b) threads resurrected because
608 // they are about to be send BlockedOnDeadMVar. Any threads
609 // thus released will be immediately runnable.
610 GarbageCollect(GetRoots,rtsTrue);
612 if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
615 sched_belch("still deadlocked, checking for black holes..."));
618 if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
620 #ifndef mingw32_TARGET_OS
621 /* If we have user-installed signal handlers, then wait
622 * for signals to arrive rather then bombing out with a
625 #if defined(RTS_SUPPORTS_THREADS)
626 if ( 0 ) { /* hmm..what to do? Simply stop waiting for
627 a signal with no runnable threads (or I/O
628 suspended ones) leads nowhere quick.
629 For now, simply shut down when we reach this
632 ToDo: define precisely under what conditions
633 the Scheduler should shut down in an MT setting.
636 if ( anyUserHandlers() ) {
639 sched_belch("still deadlocked, waiting for signals..."));
643 // we might be interrupted...
644 if (interrupted) { continue; }
646 if (signals_pending()) {
647 RELEASE_LOCK(&sched_mutex);
648 startSignalHandlers();
649 ACQUIRE_LOCK(&sched_mutex);
651 ASSERT(!EMPTY_RUN_QUEUE());
656 /* Probably a real deadlock. Send the current main thread the
657 * Deadlock exception (or in the SMP build, send *all* main
658 * threads the deadlock exception, since none of them can make
663 #if defined(RTS_SUPPORTS_THREADS)
664 for (m = main_threads; m != NULL; m = m->link) {
665 switch (m->tso->why_blocked) {
666 case BlockedOnBlackHole:
667 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
669 case BlockedOnException:
671 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
674 barf("deadlock: main thread blocked in a strange way");
679 switch (m->tso->why_blocked) {
680 case BlockedOnBlackHole:
681 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
683 case BlockedOnException:
685 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
688 barf("deadlock: main thread blocked in a strange way");
693 #if defined(RTS_SUPPORTS_THREADS)
694 /* ToDo: revisit conditions (and mechanism) for shutting
695 down a multi-threaded world */
696 IF_DEBUG(scheduler, sched_belch("all done, i think...shutting down."));
697 RELEASE_LOCK(&sched_mutex);
705 /* ToDo: add deadlock detection in GUM (similar to SMP) -- HWL */
709 /* If there's a GC pending, don't do anything until it has
713 IF_DEBUG(scheduler,sched_belch("waiting for GC"));
714 waitCondition( &gc_pending_cond, &sched_mutex );
718 #if defined(RTS_SUPPORTS_THREADS)
719 /* block until we've got a thread on the run queue and a free
723 if ( EMPTY_RUN_QUEUE() ) {
724 /* Give up our capability */
725 releaseCapability(cap);
727 /* If we're in the process of shutting down (& running the
728 * a batch of finalisers), don't wait around.
730 if ( shutting_down_scheduler ) {
731 RELEASE_LOCK(&sched_mutex);
734 IF_DEBUG(scheduler, sched_belch("thread %d: waiting for work", osThreadId()));
735 waitForWorkCapability(&sched_mutex, &cap, rtsTrue);
736 IF_DEBUG(scheduler, sched_belch("thread %d: work now available", osThreadId()));
741 if (RtsFlags.GranFlags.Light)
742 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
744 /* adjust time based on time-stamp */
745 if (event->time > CurrentTime[CurrentProc] &&
746 event->evttype != ContinueThread)
747 CurrentTime[CurrentProc] = event->time;
749 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
750 if (!RtsFlags.GranFlags.Light)
753 IF_DEBUG(gran, fprintf(stderr, "GRAN: switch by event-type\n"));
755 /* main event dispatcher in GranSim */
756 switch (event->evttype) {
757 /* Should just be continuing execution */
759 IF_DEBUG(gran, fprintf(stderr, "GRAN: doing ContinueThread\n"));
760 /* ToDo: check assertion
761 ASSERT(run_queue_hd != (StgTSO*)NULL &&
762 run_queue_hd != END_TSO_QUEUE);
764 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
765 if (!RtsFlags.GranFlags.DoAsyncFetch &&
766 procStatus[CurrentProc]==Fetching) {
767 belch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]",
768 CurrentTSO->id, CurrentTSO, CurrentProc);
771 /* Ignore ContinueThreads for completed threads */
772 if (CurrentTSO->what_next == ThreadComplete) {
773 belch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)",
774 CurrentTSO->id, CurrentTSO, CurrentProc);
777 /* Ignore ContinueThreads for threads that are being migrated */
778 if (PROCS(CurrentTSO)==Nowhere) {
779 belch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)",
780 CurrentTSO->id, CurrentTSO, CurrentProc);
783 /* The thread should be at the beginning of the run queue */
784 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
785 belch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread",
786 CurrentTSO->id, CurrentTSO, CurrentProc);
787 break; // run the thread anyway
790 new_event(proc, proc, CurrentTime[proc],
792 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
794 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
795 break; // now actually run the thread; DaH Qu'vam yImuHbej
798 do_the_fetchnode(event);
799 goto next_thread; /* handle next event in event queue */
802 do_the_globalblock(event);
803 goto next_thread; /* handle next event in event queue */
806 do_the_fetchreply(event);
807 goto next_thread; /* handle next event in event queue */
809 case UnblockThread: /* Move from the blocked queue to the tail of */
810 do_the_unblock(event);
811 goto next_thread; /* handle next event in event queue */
813 case ResumeThread: /* Move from the blocked queue to the tail of */
814 /* the runnable queue ( i.e. Qu' SImqa'lu') */
815 event->tso->gran.blocktime +=
816 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
817 do_the_startthread(event);
818 goto next_thread; /* handle next event in event queue */
821 do_the_startthread(event);
822 goto next_thread; /* handle next event in event queue */
825 do_the_movethread(event);
826 goto next_thread; /* handle next event in event queue */
829 do_the_movespark(event);
830 goto next_thread; /* handle next event in event queue */
833 do_the_findwork(event);
834 goto next_thread; /* handle next event in event queue */
837 barf("Illegal event type %u\n", event->evttype);
840 /* This point was scheduler_loop in the old RTS */
842 IF_DEBUG(gran, belch("GRAN: after main switch"));
844 TimeOfLastEvent = CurrentTime[CurrentProc];
845 TimeOfNextEvent = get_time_of_next_event();
846 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
847 // CurrentTSO = ThreadQueueHd;
849 IF_DEBUG(gran, belch("GRAN: time of next event is: %ld",
852 if (RtsFlags.GranFlags.Light)
853 GranSimLight_leave_system(event, &ActiveTSO);
855 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
858 belch("GRAN: end of time-slice is %#lx", EndOfTimeSlice));
860 /* in a GranSim setup the TSO stays on the run queue */
862 /* Take a thread from the run queue. */
863 t = POP_RUN_QUEUE(); // take_off_run_queue(t);
866 fprintf(stderr, "GRAN: About to run current thread, which is\n");
869 context_switch = 0; // turned on via GranYield, checking events and time slice
872 DumpGranEvent(GR_SCHEDULE, t));
874 procStatus[CurrentProc] = Busy;
877 if (PendingFetches != END_BF_QUEUE) {
881 /* ToDo: phps merge with spark activation above */
882 /* check whether we have local work and send requests if we have none */
883 if (EMPTY_RUN_QUEUE()) { /* no runnable threads */
884 /* :-[ no local threads => look out for local sparks */
885 /* the spark pool for the current PE */
886 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
887 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
888 pool->hd < pool->tl) {
890 * ToDo: add GC code check that we really have enough heap afterwards!!
892 * If we're here (no runnable threads) and we have pending
893 * sparks, we must have a space problem. Get enough space
894 * to turn one of those pending sparks into a
898 spark = findSpark(rtsFalse); /* get a spark */
899 if (spark != (rtsSpark) NULL) {
900 tso = activateSpark(spark); /* turn the spark into a thread */
901 IF_PAR_DEBUG(schedule,
902 belch("==== schedule: Created TSO %d (%p); %d threads active",
903 tso->id, tso, advisory_thread_count));
905 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
906 belch("==^^ failed to activate spark");
908 } /* otherwise fall through & pick-up new tso */
910 IF_PAR_DEBUG(verbose,
911 belch("==^^ no local sparks (spark pool contains only NFs: %d)",
912 spark_queue_len(pool)));
917 /* If we still have no work we need to send a FISH to get a spark
920 if (EMPTY_RUN_QUEUE()) {
921 /* =8-[ no local sparks => look for work on other PEs */
923 * We really have absolutely no work. Send out a fish
924 * (there may be some out there already), and wait for
925 * something to arrive. We clearly can't run any threads
926 * until a SCHEDULE or RESUME arrives, and so that's what
927 * we're hoping to see. (Of course, we still have to
928 * respond to other types of messages.)
930 TIME now = msTime() /*CURRENT_TIME*/;
931 IF_PAR_DEBUG(verbose,
932 belch("-- now=%ld", now));
933 IF_PAR_DEBUG(verbose,
934 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
935 (last_fish_arrived_at!=0 &&
936 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
937 belch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)",
938 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
939 last_fish_arrived_at,
940 RtsFlags.ParFlags.fishDelay, now);
943 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
944 (last_fish_arrived_at==0 ||
945 (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
946 /* outstandingFishes is set in sendFish, processFish;
947 avoid flooding system with fishes via delay */
949 sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY,
952 // Global statistics: count no. of fishes
953 if (RtsFlags.ParFlags.ParStats.Global &&
954 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
955 globalParStats.tot_fish_mess++;
959 receivedFinish = processMessages();
962 } else if (PacketsWaiting()) { /* Look for incoming messages */
963 receivedFinish = processMessages();
966 /* Now we are sure that we have some work available */
967 ASSERT(run_queue_hd != END_TSO_QUEUE);
969 /* Take a thread from the run queue, if we have work */
970 t = POP_RUN_QUEUE(); // take_off_run_queue(END_TSO_QUEUE);
971 IF_DEBUG(sanity,checkTSO(t));
973 /* ToDo: write something to the log-file
974 if (RTSflags.ParFlags.granSimStats && !sameThread)
975 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
979 /* the spark pool for the current PE */
980 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
983 belch("--=^ %d threads, %d sparks on [%#x]",
984 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
987 if (0 && RtsFlags.ParFlags.ParStats.Full &&
988 t && LastTSO && t->id != LastTSO->id &&
989 LastTSO->why_blocked == NotBlocked &&
990 LastTSO->what_next != ThreadComplete) {
991 // if previously scheduled TSO not blocked we have to record the context switch
992 DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
993 GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
996 if (RtsFlags.ParFlags.ParStats.Full &&
997 (emitSchedule /* forced emit */ ||
998 (t && LastTSO && t->id != LastTSO->id))) {
1000 we are running a different TSO, so write a schedule event to log file
1001 NB: If we use fair scheduling we also have to write a deschedule
1002 event for LastTSO; with unfair scheduling we know that the
1003 previous tso has blocked whenever we switch to another tso, so
1004 we don't need it in GUM for now
1006 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1007 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
1008 emitSchedule = rtsFalse;
1012 #else /* !GRAN && !PAR */
1014 /* grab a thread from the run queue */
1015 ASSERT(run_queue_hd != END_TSO_QUEUE);
1016 t = POP_RUN_QUEUE();
1017 // Sanity check the thread we're about to run. This can be
1018 // expensive if there is lots of thread switching going on...
1019 IF_DEBUG(sanity,checkTSO(t));
1022 cap->r.rCurrentTSO = t;
1024 /* context switches are now initiated by the timer signal, unless
1025 * the user specified "context switch as often as possible", with
1030 RtsFlags.ProfFlags.profileInterval == 0 ||
1032 (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
1033 && (run_queue_hd != END_TSO_QUEUE
1034 || blocked_queue_hd != END_TSO_QUEUE
1035 || sleeping_queue != END_TSO_QUEUE)))
1040 RELEASE_LOCK(&sched_mutex);
1042 IF_DEBUG(scheduler, sched_belch("-->> Running TSO %ld (%p) %s ...",
1043 t->id, t, whatNext_strs[t->what_next]));
1046 startHeapProfTimer();
1049 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1050 /* Run the current thread
1052 switch (cap->r.rCurrentTSO->what_next) {
1054 case ThreadComplete:
1055 /* Thread already finished, return to scheduler. */
1056 ret = ThreadFinished;
1058 case ThreadEnterGHC:
1059 ret = StgRun((StgFunPtr) stg_enterStackTop, &cap->r);
1062 ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
1064 case ThreadEnterInterp:
1065 ret = interpretBCO(cap);
1068 barf("schedule: invalid what_next field");
1070 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1072 /* Costs for the scheduler are assigned to CCS_SYSTEM */
1074 stopHeapProfTimer();
1078 ACQUIRE_LOCK(&sched_mutex);
1081 IF_DEBUG(scheduler,fprintf(stderr,"scheduler (task %ld): ", osThreadId()););
1082 #elif !defined(GRAN) && !defined(PAR)
1083 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: "););
1085 t = cap->r.rCurrentTSO;
1088 /* HACK 675: if the last thread didn't yield, make sure to print a
1089 SCHEDULE event to the log file when StgRunning the next thread, even
1090 if it is the same one as before */
1092 TimeOfLastYield = CURRENT_TIME;
1098 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
1099 globalGranStats.tot_heapover++;
1101 globalParStats.tot_heapover++;
1104 // did the task ask for a large block?
1105 if (cap->r.rHpAlloc > BLOCK_SIZE_W) {
1106 // if so, get one and push it on the front of the nursery.
1110 blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc * sizeof(W_)) / BLOCK_SIZE;
1112 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: requesting a large block (size %d)",
1114 whatNext_strs[t->what_next], blocks));
1116 // don't do this if it would push us over the
1117 // alloc_blocks_lim limit; we'll GC first.
1118 if (alloc_blocks + blocks < alloc_blocks_lim) {
1120 alloc_blocks += blocks;
1121 bd = allocGroup( blocks );
1123 // link the new group into the list
1124 bd->link = cap->r.rCurrentNursery;
1125 bd->u.back = cap->r.rCurrentNursery->u.back;
1126 if (cap->r.rCurrentNursery->u.back != NULL) {
1127 cap->r.rCurrentNursery->u.back->link = bd;
1129 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1130 g0s0->blocks == cap->r.rNursery);
1131 cap->r.rNursery = g0s0->blocks = bd;
1133 cap->r.rCurrentNursery->u.back = bd;
1135 // initialise it as a nursery block. We initialise the
1136 // step, gen_no, and flags field of *every* sub-block in
1137 // this large block, because this is easier than making
1138 // sure that we always find the block head of a large
1139 // block whenever we call Bdescr() (eg. evacuate() and
1140 // isAlive() in the GC would both have to do this, at
1144 for (x = bd; x < bd + blocks; x++) {
1152 // don't forget to update the block count in g0s0.
1153 g0s0->n_blocks += blocks;
1154 ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1156 // now update the nursery to point to the new block
1157 cap->r.rCurrentNursery = bd;
1159 // we might be unlucky and have another thread get on the
1160 // run queue before us and steal the large block, but in that
1161 // case the thread will just end up requesting another large
1163 PUSH_ON_RUN_QUEUE(t);
1168 /* make all the running tasks block on a condition variable,
1169 * maybe set context_switch and wait till they all pile in,
1170 * then have them wait on a GC condition variable.
1172 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: HeapOverflow",
1173 t->id, t, whatNext_strs[t->what_next]));
1176 ASSERT(!is_on_queue(t,CurrentProc));
1178 /* Currently we emit a DESCHEDULE event before GC in GUM.
1179 ToDo: either add separate event to distinguish SYSTEM time from rest
1180 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1181 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1182 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1183 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1184 emitSchedule = rtsTrue;
1188 ready_to_gc = rtsTrue;
1189 context_switch = 1; /* stop other threads ASAP */
1190 PUSH_ON_RUN_QUEUE(t);
1191 /* actual GC is done at the end of the while loop */
1197 DumpGranEvent(GR_DESCHEDULE, t));
1198 globalGranStats.tot_stackover++;
1201 // DumpGranEvent(GR_DESCHEDULE, t);
1202 globalParStats.tot_stackover++;
1204 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped, StackOverflow",
1205 t->id, t, whatNext_strs[t->what_next]));
1206 /* just adjust the stack for this thread, then pop it back
1212 /* enlarge the stack */
1213 StgTSO *new_t = threadStackOverflow(t);
1215 /* This TSO has moved, so update any pointers to it from the
1216 * main thread stack. It better not be on any other queues...
1217 * (it shouldn't be).
1219 for (m = main_threads; m != NULL; m = m->link) {
1224 threadPaused(new_t);
1225 PUSH_ON_RUN_QUEUE(new_t);
1229 case ThreadYielding:
1232 DumpGranEvent(GR_DESCHEDULE, t));
1233 globalGranStats.tot_yields++;
1236 // DumpGranEvent(GR_DESCHEDULE, t);
1237 globalParStats.tot_yields++;
1239 /* put the thread back on the run queue. Then, if we're ready to
1240 * GC, check whether this is the last task to stop. If so, wake
1241 * up the GC thread. getThread will block during a GC until the
1245 if (t->what_next == ThreadEnterInterp) {
1246 /* ToDo: or maybe a timer expired when we were in Hugs?
1247 * or maybe someone hit ctrl-C
1249 belch("--<< thread %ld (%p; %s) stopped to switch to Hugs",
1250 t->id, t, whatNext_strs[t->what_next]);
1252 belch("--<< thread %ld (%p; %s) stopped, yielding",
1253 t->id, t, whatNext_strs[t->what_next]);
1260 //belch("&& Doing sanity check on yielding TSO %ld.", t->id);
1262 ASSERT(t->link == END_TSO_QUEUE);
1264 ASSERT(!is_on_queue(t,CurrentProc));
1267 //belch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1268 checkThreadQsSanity(rtsTrue));
1271 if (RtsFlags.ParFlags.doFairScheduling) {
1272 /* this does round-robin scheduling; good for concurrency */
1273 APPEND_TO_RUN_QUEUE(t);
1275 /* this does unfair scheduling; good for parallelism */
1276 PUSH_ON_RUN_QUEUE(t);
1279 /* this does round-robin scheduling; good for concurrency */
1280 APPEND_TO_RUN_QUEUE(t);
1283 /* add a ContinueThread event to actually process the thread */
1284 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1286 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1288 belch("GRAN: eventq and runnableq after adding yielded thread to queue again:");
1297 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1298 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)));
1299 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1301 // ??? needed; should emit block before
1303 DumpGranEvent(GR_DESCHEDULE, t));
1304 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1307 ASSERT(procStatus[CurrentProc]==Busy ||
1308 ((procStatus[CurrentProc]==Fetching) &&
1309 (t->block_info.closure!=(StgClosure*)NULL)));
1310 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1311 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1312 procStatus[CurrentProc]==Fetching))
1313 procStatus[CurrentProc] = Idle;
1317 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: ",
1318 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1321 if (t->block_info.closure!=(StgClosure*)NULL)
1322 print_bq(t->block_info.closure));
1324 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1327 /* whatever we schedule next, we must log that schedule */
1328 emitSchedule = rtsTrue;
1331 /* don't need to do anything. Either the thread is blocked on
1332 * I/O, in which case we'll have called addToBlockedQueue
1333 * previously, or it's blocked on an MVar or Blackhole, in which
1334 * case it'll be on the relevant queue already.
1337 fprintf(stderr, "--<< thread %d (%p) stopped: ", t->id, t);
1338 printThreadBlockage(t);
1339 fprintf(stderr, "\n"));
1341 /* Only for dumping event to log file
1342 ToDo: do I need this in GranSim, too?
1349 case ThreadFinished:
1350 /* Need to check whether this was a main thread, and if so, signal
1351 * the task that started it with the return value. If we have no
1352 * more main threads, we probably need to stop all the tasks until
1355 /* We also end up here if the thread kills itself with an
1356 * uncaught exception, see Exception.hc.
1358 IF_DEBUG(scheduler,belch("--++ thread %d (%p) finished", t->id, t));
1360 endThread(t, CurrentProc); // clean-up the thread
1362 /* For now all are advisory -- HWL */
1363 //if(t->priority==AdvisoryPriority) ??
1364 advisory_thread_count--;
1367 if(t->dist.priority==RevalPriority)
1371 if (RtsFlags.ParFlags.ParStats.Full &&
1372 !RtsFlags.ParFlags.ParStats.Suppressed)
1373 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1378 barf("schedule: invalid thread return code %d", (int)ret);
1382 if (RtsFlags.ProfFlags.profileInterval==0 || performHeapProfile) {
1383 GarbageCollect(GetRoots, rtsTrue);
1385 performHeapProfile = rtsFalse;
1386 ready_to_gc = rtsFalse; // we already GC'd
1392 && allFreeCapabilities()
1395 /* everybody back, start the GC.
1396 * Could do it in this thread, or signal a condition var
1397 * to do it in another thread. Either way, we need to
1398 * broadcast on gc_pending_cond afterward.
1400 #if defined(RTS_SUPPORTS_THREADS)
1401 IF_DEBUG(scheduler,sched_belch("doing GC"));
1403 GarbageCollect(GetRoots,rtsFalse);
1404 ready_to_gc = rtsFalse;
1406 broadcastCondition(&gc_pending_cond);
1409 /* add a ContinueThread event to continue execution of current thread */
1410 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1412 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1414 fprintf(stderr, "GRAN: eventq and runnableq after Garbage collection:\n");
1422 IF_GRAN_DEBUG(unused,
1423 print_eventq(EventHd));
1425 event = get_next_event();
1428 /* ToDo: wait for next message to arrive rather than busy wait */
1431 } /* end of while(1) */
1433 IF_PAR_DEBUG(verbose,
1434 belch("== Leaving schedule() after having received Finish"));
1437 /* ---------------------------------------------------------------------------
1438 * Singleton fork(). Do not copy any running threads.
1439 * ------------------------------------------------------------------------- */
1441 StgInt forkProcess(StgTSO* tso) {
1443 #ifndef mingw32_TARGET_OS
1449 IF_DEBUG(scheduler,sched_belch("forking!"));
1452 if (pid) { /* parent */
1454 /* just return the pid */
1456 } else { /* child */
1457 /* wipe all other threads */
1458 run_queue_hd = run_queue_tl = tso;
1459 tso->link = END_TSO_QUEUE;
1461 /* When clearing out the threads, we need to ensure
1462 that a 'main thread' is left behind; if there isn't,
1463 the Scheduler will shutdown next time it is entered.
1465 ==> we don't kill a thread that's on the main_threads
1466 list (nor the current thread.)
1468 [ Attempts at implementing the more ambitious scheme of
1469 killing the main_threads also, and then adding the
1470 current thread onto the main_threads list if it wasn't
1471 there already, failed -- waitThread() (for one) wasn't
1472 up to it. If it proves to be desirable to also kill
1473 the main threads, then this scheme will have to be
1474 revisited (and fully debugged!)
1479 /* DO NOT TOUCH THE QUEUES directly because most of the code around
1480 us is picky about finding the thread still in its queue when
1481 handling the deleteThread() */
1483 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1486 /* Don't kill the current thread.. */
1487 if (t->id == tso->id) continue;
1489 /* ..or a main thread */
1490 for (m = main_threads; m != NULL; m = m->link) {
1491 if (m->tso->id == t->id) {
1503 barf("forkProcess#: primop not implemented for mingw32, sorry! (%u)\n", tso->id);
1504 /* pointlessly printing out the TSOs 'id' to avoid CC unused warning. */
1506 #endif /* mingw32 */
1509 /* ---------------------------------------------------------------------------
1510 * deleteAllThreads(): kill all the live threads.
1512 * This is used when we catch a user interrupt (^C), before performing
1513 * any necessary cleanups and running finalizers.
1515 * Locks: sched_mutex held.
1516 * ------------------------------------------------------------------------- */
1518 void deleteAllThreads ( void )
1521 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
1522 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1523 next = t->global_link;
1526 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1527 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
1528 sleeping_queue = END_TSO_QUEUE;
1531 /* startThread and insertThread are now in GranSim.c -- HWL */
1534 //@node Suspend and Resume, Run queue code, Main scheduling loop, Main scheduling code
1535 //@subsection Suspend and Resume
1537 /* ---------------------------------------------------------------------------
1538 * Suspending & resuming Haskell threads.
1540 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1541 * its capability before calling the C function. This allows another
1542 * task to pick up the capability and carry on running Haskell
1543 * threads. It also means that if the C call blocks, it won't lock
1546 * The Haskell thread making the C call is put to sleep for the
1547 * duration of the call, on the susepended_ccalling_threads queue. We
1548 * give out a token to the task, which it can use to resume the thread
1549 * on return from the C function.
1550 * ------------------------------------------------------------------------- */
1553 suspendThread( StgRegTable *reg,
1555 #if !defined(RTS_SUPPORTS_THREADS) && !defined(DEBUG)
1563 /* assume that *reg is a pointer to the StgRegTable part
1566 cap = (Capability *)((void *)reg - sizeof(StgFunTable));
1568 ACQUIRE_LOCK(&sched_mutex);
1571 sched_belch("thread %d did a _ccall_gc (is_concurrent: %d)", cap->r.rCurrentTSO->id,concCall));
1573 threadPaused(cap->r.rCurrentTSO);
1574 cap->r.rCurrentTSO->link = suspended_ccalling_threads;
1575 suspended_ccalling_threads = cap->r.rCurrentTSO;
1577 #if defined(RTS_SUPPORTS_THREADS)
1578 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall;
1581 /* Use the thread ID as the token; it should be unique */
1582 tok = cap->r.rCurrentTSO->id;
1584 /* Hand back capability */
1585 releaseCapability(cap);
1587 #if defined(RTS_SUPPORTS_THREADS)
1588 /* Preparing to leave the RTS, so ensure there's a native thread/task
1589 waiting to take over.
1591 ToDo: optimise this and only create a new task if there's a need
1592 for one (i.e., if there's only one Concurrent Haskell thread alive,
1593 there's no need to create a new task).
1595 IF_DEBUG(scheduler, sched_belch("worker thread (%d): leaving RTS", tok));
1597 startTask(taskStart);
1601 /* Other threads _might_ be available for execution; signal this */
1603 RELEASE_LOCK(&sched_mutex);
1608 resumeThread( StgInt tok,
1610 #if !defined(RTS_SUPPORTS_THREADS)
1615 StgTSO *tso, **prev;
1618 #if defined(RTS_SUPPORTS_THREADS)
1619 /* Wait for permission to re-enter the RTS with the result. */
1621 ACQUIRE_LOCK(&sched_mutex);
1622 grabReturnCapability(&sched_mutex, &cap);
1624 grabCapability(&cap);
1627 grabCapability(&cap);
1630 /* Remove the thread off of the suspended list */
1631 prev = &suspended_ccalling_threads;
1632 for (tso = suspended_ccalling_threads;
1633 tso != END_TSO_QUEUE;
1634 prev = &tso->link, tso = tso->link) {
1635 if (tso->id == (StgThreadID)tok) {
1640 if (tso == END_TSO_QUEUE) {
1641 barf("resumeThread: thread not found");
1643 tso->link = END_TSO_QUEUE;
1644 /* Reset blocking status */
1645 tso->why_blocked = NotBlocked;
1647 cap->r.rCurrentTSO = tso;
1648 RELEASE_LOCK(&sched_mutex);
1653 /* ---------------------------------------------------------------------------
1655 * ------------------------------------------------------------------------ */
1656 static void unblockThread(StgTSO *tso);
1658 /* ---------------------------------------------------------------------------
1659 * Comparing Thread ids.
1661 * This is used from STG land in the implementation of the
1662 * instances of Eq/Ord for ThreadIds.
1663 * ------------------------------------------------------------------------ */
1665 int cmp_thread(const StgTSO *tso1, const StgTSO *tso2)
1667 StgThreadID id1 = tso1->id;
1668 StgThreadID id2 = tso2->id;
1670 if (id1 < id2) return (-1);
1671 if (id1 > id2) return 1;
1675 /* ---------------------------------------------------------------------------
1676 * Fetching the ThreadID from an StgTSO.
1678 * This is used in the implementation of Show for ThreadIds.
1679 * ------------------------------------------------------------------------ */
1680 int rts_getThreadId(const StgTSO *tso)
1686 void labelThread(StgTSO *tso, char *label)
1691 /* Caveat: Once set, you can only set the thread name to "" */
1692 len = strlen(label)+1;
1695 fprintf(stderr,"insufficient memory for labelThread!\n");
1697 strncpy(buf,label,len);
1698 /* Update will free the old memory for us */
1699 updateThreadLabel((StgWord)tso,buf);
1703 /* ---------------------------------------------------------------------------
1704 Create a new thread.
1706 The new thread starts with the given stack size. Before the
1707 scheduler can run, however, this thread needs to have a closure
1708 (and possibly some arguments) pushed on its stack. See
1709 pushClosure() in Schedule.h.
1711 createGenThread() and createIOThread() (in SchedAPI.h) are
1712 convenient packaged versions of this function.
1714 currently pri (priority) is only used in a GRAN setup -- HWL
1715 ------------------------------------------------------------------------ */
1716 //@cindex createThread
1718 /* currently pri (priority) is only used in a GRAN setup -- HWL */
1720 createThread(nat size, StgInt pri)
1723 createThread(nat size)
1730 /* First check whether we should create a thread at all */
1732 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1733 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1735 belch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1736 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1737 return END_TSO_QUEUE;
1743 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
1746 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
1748 /* catch ridiculously small stack sizes */
1749 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
1750 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
1753 stack_size = size - TSO_STRUCT_SIZEW;
1755 tso = (StgTSO *)allocate(size);
1756 TICK_ALLOC_TSO(stack_size, 0);
1758 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
1760 SET_GRAN_HDR(tso, ThisPE);
1762 tso->what_next = ThreadEnterGHC;
1764 /* tso->id needs to be unique. For now we use a heavyweight mutex to
1765 * protect the increment operation on next_thread_id.
1766 * In future, we could use an atomic increment instead.
1768 ACQUIRE_LOCK(&thread_id_mutex);
1769 tso->id = next_thread_id++;
1770 RELEASE_LOCK(&thread_id_mutex);
1772 tso->why_blocked = NotBlocked;
1773 tso->blocked_exceptions = NULL;
1775 tso->stack_size = stack_size;
1776 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
1778 tso->sp = (P_)&(tso->stack) + stack_size;
1781 tso->prof.CCCS = CCS_MAIN;
1784 /* put a stop frame on the stack */
1785 tso->sp -= sizeofW(StgStopFrame);
1786 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
1787 tso->su = (StgUpdateFrame*)tso->sp;
1791 tso->link = END_TSO_QUEUE;
1792 /* uses more flexible routine in GranSim */
1793 insertThread(tso, CurrentProc);
1795 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
1801 if (RtsFlags.GranFlags.GranSimStats.Full)
1802 DumpGranEvent(GR_START,tso);
1804 if (RtsFlags.ParFlags.ParStats.Full)
1805 DumpGranEvent(GR_STARTQ,tso);
1806 /* HACk to avoid SCHEDULE
1810 /* Link the new thread on the global thread list.
1812 tso->global_link = all_threads;
1816 tso->dist.priority = MandatoryPriority; //by default that is...
1820 tso->gran.pri = pri;
1822 tso->gran.magic = TSO_MAGIC; // debugging only
1824 tso->gran.sparkname = 0;
1825 tso->gran.startedat = CURRENT_TIME;
1826 tso->gran.exported = 0;
1827 tso->gran.basicblocks = 0;
1828 tso->gran.allocs = 0;
1829 tso->gran.exectime = 0;
1830 tso->gran.fetchtime = 0;
1831 tso->gran.fetchcount = 0;
1832 tso->gran.blocktime = 0;
1833 tso->gran.blockcount = 0;
1834 tso->gran.blockedat = 0;
1835 tso->gran.globalsparks = 0;
1836 tso->gran.localsparks = 0;
1837 if (RtsFlags.GranFlags.Light)
1838 tso->gran.clock = Now; /* local clock */
1840 tso->gran.clock = 0;
1842 IF_DEBUG(gran,printTSO(tso));
1845 tso->par.magic = TSO_MAGIC; // debugging only
1847 tso->par.sparkname = 0;
1848 tso->par.startedat = CURRENT_TIME;
1849 tso->par.exported = 0;
1850 tso->par.basicblocks = 0;
1851 tso->par.allocs = 0;
1852 tso->par.exectime = 0;
1853 tso->par.fetchtime = 0;
1854 tso->par.fetchcount = 0;
1855 tso->par.blocktime = 0;
1856 tso->par.blockcount = 0;
1857 tso->par.blockedat = 0;
1858 tso->par.globalsparks = 0;
1859 tso->par.localsparks = 0;
1863 globalGranStats.tot_threads_created++;
1864 globalGranStats.threads_created_on_PE[CurrentProc]++;
1865 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
1866 globalGranStats.tot_sq_probes++;
1868 // collect parallel global statistics (currently done together with GC stats)
1869 if (RtsFlags.ParFlags.ParStats.Global &&
1870 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1871 //fprintf(stderr, "Creating thread %d @ %11.2f\n", tso->id, usertime());
1872 globalParStats.tot_threads_created++;
1878 belch("==__ schedule: Created TSO %d (%p);",
1879 CurrentProc, tso, tso->id));
1881 IF_PAR_DEBUG(verbose,
1882 belch("==__ schedule: Created TSO %d (%p); %d threads active",
1883 tso->id, tso, advisory_thread_count));
1885 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
1886 tso->id, tso->stack_size));
1893 all parallel thread creation calls should fall through the following routine.
1896 createSparkThread(rtsSpark spark)
1898 ASSERT(spark != (rtsSpark)NULL);
1899 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
1901 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1902 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1903 return END_TSO_QUEUE;
1907 tso = createThread(RtsFlags.GcFlags.initialStkSize);
1908 if (tso==END_TSO_QUEUE)
1909 barf("createSparkThread: Cannot create TSO");
1911 tso->priority = AdvisoryPriority;
1913 pushClosure(tso,spark);
1914 PUSH_ON_RUN_QUEUE(tso);
1915 advisory_thread_count++;
1922 Turn a spark into a thread.
1923 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
1926 //@cindex activateSpark
1928 activateSpark (rtsSpark spark)
1932 tso = createSparkThread(spark);
1933 if (RtsFlags.ParFlags.ParStats.Full) {
1934 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
1935 IF_PAR_DEBUG(verbose,
1936 belch("==^^ activateSpark: turning spark of closure %p (%s) into a thread",
1937 (StgClosure *)spark, info_type((StgClosure *)spark)));
1939 // ToDo: fwd info on local/global spark to thread -- HWL
1940 // tso->gran.exported = spark->exported;
1941 // tso->gran.locked = !spark->global;
1942 // tso->gran.sparkname = spark->name;
1948 static SchedulerStatus waitThread_(/*out*/StgMainThread* m
1949 #if defined(THREADED_RTS)
1950 , rtsBool blockWaiting
1955 /* ---------------------------------------------------------------------------
1958 * scheduleThread puts a thread on the head of the runnable queue.
1959 * This will usually be done immediately after a thread is created.
1960 * The caller of scheduleThread must create the thread using e.g.
1961 * createThread and push an appropriate closure
1962 * on this thread's stack before the scheduler is invoked.
1963 * ------------------------------------------------------------------------ */
1965 static void scheduleThread_ (StgTSO* tso, rtsBool createTask);
1968 scheduleThread_(StgTSO *tso
1969 , rtsBool createTask
1970 #if !defined(THREADED_RTS)
1975 ACQUIRE_LOCK(&sched_mutex);
1977 /* Put the new thread on the head of the runnable queue. The caller
1978 * better push an appropriate closure on this thread's stack
1979 * beforehand. In the SMP case, the thread may start running as
1980 * soon as we release the scheduler lock below.
1982 PUSH_ON_RUN_QUEUE(tso);
1983 #if defined(THREADED_RTS)
1984 /* If main() is scheduling a thread, don't bother creating a
1988 startTask(taskStart);
1994 IF_DEBUG(scheduler,printTSO(tso));
1996 RELEASE_LOCK(&sched_mutex);
1999 void scheduleThread(StgTSO* tso)
2001 scheduleThread_(tso, rtsFalse);
2005 scheduleWaitThread(StgTSO* tso, /*[out]*/HaskellObj* ret)
2009 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2013 #if defined(RTS_SUPPORTS_THREADS)
2014 initCondition(&m->wakeup);
2017 /* Put the thread on the main-threads list prior to scheduling the TSO.
2018 Failure to do so introduces a race condition in the MT case (as
2019 identified by Wolfgang Thaller), whereby the new task/OS thread
2020 created by scheduleThread_() would complete prior to the thread
2021 that spawned it managed to put 'itself' on the main-threads list.
2022 The upshot of it all being that the worker thread wouldn't get to
2023 signal the completion of the its work item for the main thread to
2024 see (==> it got stuck waiting.) -- sof 6/02.
2026 ACQUIRE_LOCK(&sched_mutex);
2027 IF_DEBUG(scheduler, sched_belch("== scheduler: waiting for thread (%d)\n", tso->id));
2029 m->link = main_threads;
2032 /* Inefficient (scheduleThread_() acquires it again right away),
2033 * but obviously correct.
2035 RELEASE_LOCK(&sched_mutex);
2037 scheduleThread_(tso, rtsTrue);
2038 #if defined(THREADED_RTS)
2039 return waitThread_(m, rtsTrue);
2041 return waitThread_(m);
2045 /* ---------------------------------------------------------------------------
2048 * Initialise the scheduler. This resets all the queues - if the
2049 * queues contained any threads, they'll be garbage collected at the
2052 * ------------------------------------------------------------------------ */
2056 term_handler(int sig STG_UNUSED)
2059 ACQUIRE_LOCK(&term_mutex);
2061 RELEASE_LOCK(&term_mutex);
2072 for (i=0; i<=MAX_PROC; i++) {
2073 run_queue_hds[i] = END_TSO_QUEUE;
2074 run_queue_tls[i] = END_TSO_QUEUE;
2075 blocked_queue_hds[i] = END_TSO_QUEUE;
2076 blocked_queue_tls[i] = END_TSO_QUEUE;
2077 ccalling_threadss[i] = END_TSO_QUEUE;
2078 sleeping_queue = END_TSO_QUEUE;
2081 run_queue_hd = END_TSO_QUEUE;
2082 run_queue_tl = END_TSO_QUEUE;
2083 blocked_queue_hd = END_TSO_QUEUE;
2084 blocked_queue_tl = END_TSO_QUEUE;
2085 sleeping_queue = END_TSO_QUEUE;
2088 suspended_ccalling_threads = END_TSO_QUEUE;
2090 main_threads = NULL;
2091 all_threads = END_TSO_QUEUE;
2096 RtsFlags.ConcFlags.ctxtSwitchTicks =
2097 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
2099 #if defined(RTS_SUPPORTS_THREADS)
2100 /* Initialise the mutex and condition variables used by
2102 initMutex(&sched_mutex);
2103 initMutex(&term_mutex);
2104 initMutex(&thread_id_mutex);
2106 initCondition(&thread_ready_cond);
2110 initCondition(&gc_pending_cond);
2113 #if defined(RTS_SUPPORTS_THREADS)
2114 ACQUIRE_LOCK(&sched_mutex);
2117 /* Install the SIGHUP handler */
2120 struct sigaction action,oact;
2122 action.sa_handler = term_handler;
2123 sigemptyset(&action.sa_mask);
2124 action.sa_flags = 0;
2125 if (sigaction(SIGTERM, &action, &oact) != 0) {
2126 barf("can't install TERM handler");
2131 /* A capability holds the state a native thread needs in
2132 * order to execute STG code. At least one capability is
2133 * floating around (only SMP builds have more than one).
2137 #if defined(RTS_SUPPORTS_THREADS)
2138 /* start our haskell execution tasks */
2140 startTaskManager(RtsFlags.ParFlags.nNodes, taskStart);
2142 startTaskManager(0,taskStart);
2146 #if /* defined(SMP) ||*/ defined(PAR)
2150 #if defined(RTS_SUPPORTS_THREADS)
2151 RELEASE_LOCK(&sched_mutex);
2157 exitScheduler( void )
2159 #if defined(RTS_SUPPORTS_THREADS)
2162 shutting_down_scheduler = rtsTrue;
2165 /* -----------------------------------------------------------------------------
2166 Managing the per-task allocation areas.
2168 Each capability comes with an allocation area. These are
2169 fixed-length block lists into which allocation can be done.
2171 ToDo: no support for two-space collection at the moment???
2172 -------------------------------------------------------------------------- */
2174 /* -----------------------------------------------------------------------------
2175 * waitThread is the external interface for running a new computation
2176 * and waiting for the result.
2178 * In the non-SMP case, we create a new main thread, push it on the
2179 * main-thread stack, and invoke the scheduler to run it. The
2180 * scheduler will return when the top main thread on the stack has
2181 * completed or died, and fill in the necessary fields of the
2182 * main_thread structure.
2184 * In the SMP case, we create a main thread as before, but we then
2185 * create a new condition variable and sleep on it. When our new
2186 * main thread has completed, we'll be woken up and the status/result
2187 * will be in the main_thread struct.
2188 * -------------------------------------------------------------------------- */
2191 howManyThreadsAvail ( void )
2195 for (q = run_queue_hd; q != END_TSO_QUEUE; q = q->link)
2197 for (q = blocked_queue_hd; q != END_TSO_QUEUE; q = q->link)
2199 for (q = sleeping_queue; q != END_TSO_QUEUE; q = q->link)
2205 finishAllThreads ( void )
2208 while (run_queue_hd != END_TSO_QUEUE) {
2209 waitThread ( run_queue_hd, NULL);
2211 while (blocked_queue_hd != END_TSO_QUEUE) {
2212 waitThread ( blocked_queue_hd, NULL);
2214 while (sleeping_queue != END_TSO_QUEUE) {
2215 waitThread ( blocked_queue_hd, NULL);
2218 (blocked_queue_hd != END_TSO_QUEUE ||
2219 run_queue_hd != END_TSO_QUEUE ||
2220 sleeping_queue != END_TSO_QUEUE);
2224 waitThread(StgTSO *tso, /*out*/StgClosure **ret)
2228 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2232 #if defined(RTS_SUPPORTS_THREADS)
2233 initCondition(&m->wakeup);
2236 /* see scheduleWaitThread() comment */
2237 ACQUIRE_LOCK(&sched_mutex);
2238 IF_DEBUG(scheduler, sched_belch("== scheduler: waiting for thread (%d)\n", tso->id));
2239 m->link = main_threads;
2241 RELEASE_LOCK(&sched_mutex);
2243 IF_DEBUG(scheduler, sched_belch("== scheduler: waiting for thread (%d)\n", tso->id));
2244 #if defined(THREADED_RTS)
2245 return waitThread_(m, rtsFalse);
2247 return waitThread_(m);
2253 waitThread_(StgMainThread* m
2254 #if defined(THREADED_RTS)
2255 , rtsBool blockWaiting
2259 SchedulerStatus stat;
2261 IF_DEBUG(scheduler, sched_belch("== scheduler: new main thread (%d)\n", m->tso->id));
2263 #if defined(RTS_SUPPORTS_THREADS)
2265 # if defined(THREADED_RTS)
2266 if (!blockWaiting) {
2267 /* In the threaded case, the OS thread that called main()
2268 * gets to enter the RTS directly without going via another
2272 ASSERT(m->stat != NoStatus);
2276 ACQUIRE_LOCK(&sched_mutex);
2278 waitCondition(&m->wakeup, &sched_mutex);
2279 } while (m->stat == NoStatus);
2282 /* GranSim specific init */
2283 CurrentTSO = m->tso; // the TSO to run
2284 procStatus[MainProc] = Busy; // status of main PE
2285 CurrentProc = MainProc; // PE to run it on
2289 RELEASE_LOCK(&sched_mutex);
2291 ASSERT(m->stat != NoStatus);
2296 #if defined(RTS_SUPPORTS_THREADS)
2297 closeCondition(&m->wakeup);
2300 IF_DEBUG(scheduler, fprintf(stderr, "== scheduler: main thread (%d) finished\n",
2304 #if defined(THREADED_RTS)
2307 RELEASE_LOCK(&sched_mutex);
2312 //@node Run queue code, Garbage Collextion Routines, Suspend and Resume, Main scheduling code
2313 //@subsection Run queue code
2317 NB: In GranSim we have many run queues; run_queue_hd is actually a macro
2318 unfolding to run_queue_hds[CurrentProc], thus CurrentProc is an
2319 implicit global variable that has to be correct when calling these
2323 /* Put the new thread on the head of the runnable queue.
2324 * The caller of createThread better push an appropriate closure
2325 * on this thread's stack before the scheduler is invoked.
2327 static /* inline */ void
2328 add_to_run_queue(tso)
2331 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2332 tso->link = run_queue_hd;
2334 if (run_queue_tl == END_TSO_QUEUE) {
2339 /* Put the new thread at the end of the runnable queue. */
2340 static /* inline */ void
2341 push_on_run_queue(tso)
2344 ASSERT(get_itbl((StgClosure *)tso)->type == TSO);
2345 ASSERT(run_queue_hd!=NULL && run_queue_tl!=NULL);
2346 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2347 if (run_queue_hd == END_TSO_QUEUE) {
2350 run_queue_tl->link = tso;
2356 Should be inlined because it's used very often in schedule. The tso
2357 argument is actually only needed in GranSim, where we want to have the
2358 possibility to schedule *any* TSO on the run queue, irrespective of the
2359 actual ordering. Therefore, if tso is not the nil TSO then we traverse
2360 the run queue and dequeue the tso, adjusting the links in the queue.
2362 //@cindex take_off_run_queue
2363 static /* inline */ StgTSO*
2364 take_off_run_queue(StgTSO *tso) {
2368 qetlaHbogh Qu' ngaSbogh ghomDaQ {tso} yIteq!
2370 if tso is specified, unlink that tso from the run_queue (doesn't have
2371 to be at the beginning of the queue); GranSim only
2373 if (tso!=END_TSO_QUEUE) {
2374 /* find tso in queue */
2375 for (t=run_queue_hd, prev=END_TSO_QUEUE;
2376 t!=END_TSO_QUEUE && t!=tso;
2380 /* now actually dequeue the tso */
2381 if (prev!=END_TSO_QUEUE) {
2382 ASSERT(run_queue_hd!=t);
2383 prev->link = t->link;
2385 /* t is at beginning of thread queue */
2386 ASSERT(run_queue_hd==t);
2387 run_queue_hd = t->link;
2389 /* t is at end of thread queue */
2390 if (t->link==END_TSO_QUEUE) {
2391 ASSERT(t==run_queue_tl);
2392 run_queue_tl = prev;
2394 ASSERT(run_queue_tl!=t);
2396 t->link = END_TSO_QUEUE;
2398 /* take tso from the beginning of the queue; std concurrent code */
2400 if (t != END_TSO_QUEUE) {
2401 run_queue_hd = t->link;
2402 t->link = END_TSO_QUEUE;
2403 if (run_queue_hd == END_TSO_QUEUE) {
2404 run_queue_tl = END_TSO_QUEUE;
2413 //@node Garbage Collextion Routines, Blocking Queue Routines, Run queue code, Main scheduling code
2414 //@subsection Garbage Collextion Routines
2416 /* ---------------------------------------------------------------------------
2417 Where are the roots that we know about?
2419 - all the threads on the runnable queue
2420 - all the threads on the blocked queue
2421 - all the threads on the sleeping queue
2422 - all the thread currently executing a _ccall_GC
2423 - all the "main threads"
2425 ------------------------------------------------------------------------ */
2427 /* This has to be protected either by the scheduler monitor, or by the
2428 garbage collection monitor (probably the latter).
2433 GetRoots(evac_fn evac)
2438 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2439 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2440 evac((StgClosure **)&run_queue_hds[i]);
2441 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2442 evac((StgClosure **)&run_queue_tls[i]);
2444 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2445 evac((StgClosure **)&blocked_queue_hds[i]);
2446 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2447 evac((StgClosure **)&blocked_queue_tls[i]);
2448 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2449 evac((StgClosure **)&ccalling_threads[i]);
2456 if (run_queue_hd != END_TSO_QUEUE) {
2457 ASSERT(run_queue_tl != END_TSO_QUEUE);
2458 evac((StgClosure **)&run_queue_hd);
2459 evac((StgClosure **)&run_queue_tl);
2462 if (blocked_queue_hd != END_TSO_QUEUE) {
2463 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2464 evac((StgClosure **)&blocked_queue_hd);
2465 evac((StgClosure **)&blocked_queue_tl);
2468 if (sleeping_queue != END_TSO_QUEUE) {
2469 evac((StgClosure **)&sleeping_queue);
2473 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2474 evac((StgClosure **)&suspended_ccalling_threads);
2477 #if defined(PAR) || defined(GRAN)
2478 markSparkQueue(evac);
2482 /* -----------------------------------------------------------------------------
2485 This is the interface to the garbage collector from Haskell land.
2486 We provide this so that external C code can allocate and garbage
2487 collect when called from Haskell via _ccall_GC.
2489 It might be useful to provide an interface whereby the programmer
2490 can specify more roots (ToDo).
2492 This needs to be protected by the GC condition variable above. KH.
2493 -------------------------------------------------------------------------- */
2495 void (*extra_roots)(evac_fn);
2500 /* Obligated to hold this lock upon entry */
2501 ACQUIRE_LOCK(&sched_mutex);
2502 GarbageCollect(GetRoots,rtsFalse);
2503 RELEASE_LOCK(&sched_mutex);
2507 performMajorGC(void)
2509 ACQUIRE_LOCK(&sched_mutex);
2510 GarbageCollect(GetRoots,rtsTrue);
2511 RELEASE_LOCK(&sched_mutex);
2515 AllRoots(evac_fn evac)
2517 GetRoots(evac); // the scheduler's roots
2518 extra_roots(evac); // the user's roots
2522 performGCWithRoots(void (*get_roots)(evac_fn))
2524 ACQUIRE_LOCK(&sched_mutex);
2525 extra_roots = get_roots;
2526 GarbageCollect(AllRoots,rtsFalse);
2527 RELEASE_LOCK(&sched_mutex);
2530 /* -----------------------------------------------------------------------------
2533 If the thread has reached its maximum stack size, then raise the
2534 StackOverflow exception in the offending thread. Otherwise
2535 relocate the TSO into a larger chunk of memory and adjust its stack
2537 -------------------------------------------------------------------------- */
2540 threadStackOverflow(StgTSO *tso)
2542 nat new_stack_size, new_tso_size, diff, stack_words;
2546 IF_DEBUG(sanity,checkTSO(tso));
2547 if (tso->stack_size >= tso->max_stack_size) {
2550 belch("@@ threadStackOverflow of TSO %d (%p): stack too large (now %ld; max is %ld",
2551 tso->id, tso, tso->stack_size, tso->max_stack_size);
2552 /* If we're debugging, just print out the top of the stack */
2553 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2556 /* Send this thread the StackOverflow exception */
2557 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2561 /* Try to double the current stack size. If that takes us over the
2562 * maximum stack size for this thread, then use the maximum instead.
2563 * Finally round up so the TSO ends up as a whole number of blocks.
2565 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2566 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2567 TSO_STRUCT_SIZE)/sizeof(W_);
2568 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2569 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2571 IF_DEBUG(scheduler, fprintf(stderr,"== scheduler: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2573 dest = (StgTSO *)allocate(new_tso_size);
2574 TICK_ALLOC_TSO(new_stack_size,0);
2576 /* copy the TSO block and the old stack into the new area */
2577 memcpy(dest,tso,TSO_STRUCT_SIZE);
2578 stack_words = tso->stack + tso->stack_size - tso->sp;
2579 new_sp = (P_)dest + new_tso_size - stack_words;
2580 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2582 /* relocate the stack pointers... */
2583 diff = (P_)new_sp - (P_)tso->sp; /* In *words* */
2584 dest->su = (StgUpdateFrame *) ((P_)dest->su + diff);
2586 dest->stack_size = new_stack_size;
2588 /* and relocate the update frame list */
2589 relocate_stack(dest, diff);
2591 /* Mark the old TSO as relocated. We have to check for relocated
2592 * TSOs in the garbage collector and any primops that deal with TSOs.
2594 * It's important to set the sp and su values to just beyond the end
2595 * of the stack, so we don't attempt to scavenge any part of the
2598 tso->what_next = ThreadRelocated;
2600 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2601 tso->su = (StgUpdateFrame *)tso->sp;
2602 tso->why_blocked = NotBlocked;
2603 dest->mut_link = NULL;
2605 IF_PAR_DEBUG(verbose,
2606 belch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld",
2607 tso->id, tso, tso->stack_size);
2608 /* If we're debugging, just print out the top of the stack */
2609 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2612 IF_DEBUG(sanity,checkTSO(tso));
2614 IF_DEBUG(scheduler,printTSO(dest));
2620 //@node Blocking Queue Routines, Exception Handling Routines, Garbage Collextion Routines, Main scheduling code
2621 //@subsection Blocking Queue Routines
2623 /* ---------------------------------------------------------------------------
2624 Wake up a queue that was blocked on some resource.
2625 ------------------------------------------------------------------------ */
2629 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2634 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2636 /* write RESUME events to log file and
2637 update blocked and fetch time (depending on type of the orig closure) */
2638 if (RtsFlags.ParFlags.ParStats.Full) {
2639 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2640 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2641 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2642 if (EMPTY_RUN_QUEUE())
2643 emitSchedule = rtsTrue;
2645 switch (get_itbl(node)->type) {
2647 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2652 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2659 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2666 static StgBlockingQueueElement *
2667 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2670 PEs node_loc, tso_loc;
2672 node_loc = where_is(node); // should be lifted out of loop
2673 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2674 tso_loc = where_is((StgClosure *)tso);
2675 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2676 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2677 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2678 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2679 // insertThread(tso, node_loc);
2680 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2682 tso, node, (rtsSpark*)NULL);
2683 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2686 } else { // TSO is remote (actually should be FMBQ)
2687 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2688 RtsFlags.GranFlags.Costs.gunblocktime +
2689 RtsFlags.GranFlags.Costs.latency;
2690 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2692 tso, node, (rtsSpark*)NULL);
2693 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2696 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2698 fprintf(stderr," %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2699 (node_loc==tso_loc ? "Local" : "Global"),
2700 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2701 tso->block_info.closure = NULL;
2702 IF_DEBUG(scheduler,belch("-- Waking up thread %ld (%p)",
2706 static StgBlockingQueueElement *
2707 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2709 StgBlockingQueueElement *next;
2711 switch (get_itbl(bqe)->type) {
2713 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2714 /* if it's a TSO just push it onto the run_queue */
2716 // ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2717 PUSH_ON_RUN_QUEUE((StgTSO *)bqe);
2719 unblockCount(bqe, node);
2720 /* reset blocking status after dumping event */
2721 ((StgTSO *)bqe)->why_blocked = NotBlocked;
2725 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2727 bqe->link = (StgBlockingQueueElement *)PendingFetches;
2728 PendingFetches = (StgBlockedFetch *)bqe;
2732 /* can ignore this case in a non-debugging setup;
2733 see comments on RBHSave closures above */
2735 /* check that the closure is an RBHSave closure */
2736 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2737 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2738 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2742 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2743 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
2747 IF_PAR_DEBUG(bq, fprintf(stderr, ", %p (%s)", bqe, info_type((StgClosure*)bqe)));
2751 #else /* !GRAN && !PAR */
2753 unblockOneLocked(StgTSO *tso)
2757 ASSERT(get_itbl(tso)->type == TSO);
2758 ASSERT(tso->why_blocked != NotBlocked);
2759 tso->why_blocked = NotBlocked;
2761 PUSH_ON_RUN_QUEUE(tso);
2763 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
2768 #if defined(GRAN) || defined(PAR)
2769 inline StgBlockingQueueElement *
2770 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2772 ACQUIRE_LOCK(&sched_mutex);
2773 bqe = unblockOneLocked(bqe, node);
2774 RELEASE_LOCK(&sched_mutex);
2779 unblockOne(StgTSO *tso)
2781 ACQUIRE_LOCK(&sched_mutex);
2782 tso = unblockOneLocked(tso);
2783 RELEASE_LOCK(&sched_mutex);
2790 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2792 StgBlockingQueueElement *bqe;
2797 belch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): ", \
2798 node, CurrentProc, CurrentTime[CurrentProc],
2799 CurrentTSO->id, CurrentTSO));
2801 node_loc = where_is(node);
2803 ASSERT(q == END_BQ_QUEUE ||
2804 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
2805 get_itbl(q)->type == CONSTR); // closure (type constructor)
2806 ASSERT(is_unique(node));
2808 /* FAKE FETCH: magically copy the node to the tso's proc;
2809 no Fetch necessary because in reality the node should not have been
2810 moved to the other PE in the first place
2812 if (CurrentProc!=node_loc) {
2814 belch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)",
2815 node, node_loc, CurrentProc, CurrentTSO->id,
2816 // CurrentTSO, where_is(CurrentTSO),
2817 node->header.gran.procs));
2818 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
2820 belch("## new bitmask of node %p is %#x",
2821 node, node->header.gran.procs));
2822 if (RtsFlags.GranFlags.GranSimStats.Global) {
2823 globalGranStats.tot_fake_fetches++;
2828 // ToDo: check: ASSERT(CurrentProc==node_loc);
2829 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
2832 bqe points to the current element in the queue
2833 next points to the next element in the queue
2835 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2836 //tso_loc = where_is(tso);
2838 bqe = unblockOneLocked(bqe, node);
2841 /* if this is the BQ of an RBH, we have to put back the info ripped out of
2842 the closure to make room for the anchor of the BQ */
2843 if (bqe!=END_BQ_QUEUE) {
2844 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
2846 ASSERT((info_ptr==&RBH_Save_0_info) ||
2847 (info_ptr==&RBH_Save_1_info) ||
2848 (info_ptr==&RBH_Save_2_info));
2850 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
2851 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
2852 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
2855 belch("## Filled in RBH_Save for %p (%s) at end of AwBQ",
2856 node, info_type(node)));
2859 /* statistics gathering */
2860 if (RtsFlags.GranFlags.GranSimStats.Global) {
2861 // globalGranStats.tot_bq_processing_time += bq_processing_time;
2862 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
2863 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
2864 globalGranStats.tot_awbq++; // total no. of bqs awakened
2867 fprintf(stderr,"## BQ Stats of %p: [%d entries] %s\n",
2868 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
2872 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2874 StgBlockingQueueElement *bqe;
2876 ACQUIRE_LOCK(&sched_mutex);
2878 IF_PAR_DEBUG(verbose,
2879 belch("##-_ AwBQ for node %p on [%x]: ",
2883 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
2884 IF_PAR_DEBUG(verbose, belch("## ... nothing to unblock so lets just return. RFP (BUG?)"));
2889 ASSERT(q == END_BQ_QUEUE ||
2890 get_itbl(q)->type == TSO ||
2891 get_itbl(q)->type == BLOCKED_FETCH ||
2892 get_itbl(q)->type == CONSTR);
2895 while (get_itbl(bqe)->type==TSO ||
2896 get_itbl(bqe)->type==BLOCKED_FETCH) {
2897 bqe = unblockOneLocked(bqe, node);
2899 RELEASE_LOCK(&sched_mutex);
2902 #else /* !GRAN && !PAR */
2904 awakenBlockedQueue(StgTSO *tso)
2906 ACQUIRE_LOCK(&sched_mutex);
2907 while (tso != END_TSO_QUEUE) {
2908 tso = unblockOneLocked(tso);
2910 RELEASE_LOCK(&sched_mutex);
2914 //@node Exception Handling Routines, Debugging Routines, Blocking Queue Routines, Main scheduling code
2915 //@subsection Exception Handling Routines
2917 /* ---------------------------------------------------------------------------
2919 - usually called inside a signal handler so it mustn't do anything fancy.
2920 ------------------------------------------------------------------------ */
2923 interruptStgRts(void)
2929 /* -----------------------------------------------------------------------------
2932 This is for use when we raise an exception in another thread, which
2934 This has nothing to do with the UnblockThread event in GranSim. -- HWL
2935 -------------------------------------------------------------------------- */
2937 #if defined(GRAN) || defined(PAR)
2939 NB: only the type of the blocking queue is different in GranSim and GUM
2940 the operations on the queue-elements are the same
2941 long live polymorphism!
2943 Locks: sched_mutex is held upon entry and exit.
2947 unblockThread(StgTSO *tso)
2949 StgBlockingQueueElement *t, **last;
2951 switch (tso->why_blocked) {
2954 return; /* not blocked */
2957 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2959 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
2960 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2962 last = (StgBlockingQueueElement **)&mvar->head;
2963 for (t = (StgBlockingQueueElement *)mvar->head;
2965 last = &t->link, last_tso = t, t = t->link) {
2966 if (t == (StgBlockingQueueElement *)tso) {
2967 *last = (StgBlockingQueueElement *)tso->link;
2968 if (mvar->tail == tso) {
2969 mvar->tail = (StgTSO *)last_tso;
2974 barf("unblockThread (MVAR): TSO not found");
2977 case BlockedOnBlackHole:
2978 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2980 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2982 last = &bq->blocking_queue;
2983 for (t = bq->blocking_queue;
2985 last = &t->link, t = t->link) {
2986 if (t == (StgBlockingQueueElement *)tso) {
2987 *last = (StgBlockingQueueElement *)tso->link;
2991 barf("unblockThread (BLACKHOLE): TSO not found");
2994 case BlockedOnException:
2996 StgTSO *target = tso->block_info.tso;
2998 ASSERT(get_itbl(target)->type == TSO);
3000 if (target->what_next == ThreadRelocated) {
3001 target = target->link;
3002 ASSERT(get_itbl(target)->type == TSO);
3005 ASSERT(target->blocked_exceptions != NULL);
3007 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
3008 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
3010 last = &t->link, t = t->link) {
3011 ASSERT(get_itbl(t)->type == TSO);
3012 if (t == (StgBlockingQueueElement *)tso) {
3013 *last = (StgBlockingQueueElement *)tso->link;
3017 barf("unblockThread (Exception): TSO not found");
3021 case BlockedOnWrite:
3023 /* take TSO off blocked_queue */
3024 StgBlockingQueueElement *prev = NULL;
3025 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
3026 prev = t, t = t->link) {
3027 if (t == (StgBlockingQueueElement *)tso) {
3029 blocked_queue_hd = (StgTSO *)t->link;
3030 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3031 blocked_queue_tl = END_TSO_QUEUE;
3034 prev->link = t->link;
3035 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3036 blocked_queue_tl = (StgTSO *)prev;
3042 barf("unblockThread (I/O): TSO not found");
3045 case BlockedOnDelay:
3047 /* take TSO off sleeping_queue */
3048 StgBlockingQueueElement *prev = NULL;
3049 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
3050 prev = t, t = t->link) {
3051 if (t == (StgBlockingQueueElement *)tso) {
3053 sleeping_queue = (StgTSO *)t->link;
3055 prev->link = t->link;
3060 barf("unblockThread (I/O): TSO not found");
3064 barf("unblockThread");
3068 tso->link = END_TSO_QUEUE;
3069 tso->why_blocked = NotBlocked;
3070 tso->block_info.closure = NULL;
3071 PUSH_ON_RUN_QUEUE(tso);
3075 unblockThread(StgTSO *tso)
3079 /* To avoid locking unnecessarily. */
3080 if (tso->why_blocked == NotBlocked) {
3084 switch (tso->why_blocked) {
3087 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3089 StgTSO *last_tso = END_TSO_QUEUE;
3090 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3093 for (t = mvar->head; t != END_TSO_QUEUE;
3094 last = &t->link, last_tso = t, t = t->link) {
3097 if (mvar->tail == tso) {
3098 mvar->tail = last_tso;
3103 barf("unblockThread (MVAR): TSO not found");
3106 case BlockedOnBlackHole:
3107 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3109 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3111 last = &bq->blocking_queue;
3112 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
3113 last = &t->link, t = t->link) {
3119 barf("unblockThread (BLACKHOLE): TSO not found");
3122 case BlockedOnException:
3124 StgTSO *target = tso->block_info.tso;
3126 ASSERT(get_itbl(target)->type == TSO);
3128 while (target->what_next == ThreadRelocated) {
3129 target = target->link;
3130 ASSERT(get_itbl(target)->type == TSO);
3133 ASSERT(target->blocked_exceptions != NULL);
3135 last = &target->blocked_exceptions;
3136 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
3137 last = &t->link, t = t->link) {
3138 ASSERT(get_itbl(t)->type == TSO);
3144 barf("unblockThread (Exception): TSO not found");
3148 case BlockedOnWrite:
3150 StgTSO *prev = NULL;
3151 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
3152 prev = t, t = t->link) {
3155 blocked_queue_hd = t->link;
3156 if (blocked_queue_tl == t) {
3157 blocked_queue_tl = END_TSO_QUEUE;
3160 prev->link = t->link;
3161 if (blocked_queue_tl == t) {
3162 blocked_queue_tl = prev;
3168 barf("unblockThread (I/O): TSO not found");
3171 case BlockedOnDelay:
3173 StgTSO *prev = NULL;
3174 for (t = sleeping_queue; t != END_TSO_QUEUE;
3175 prev = t, t = t->link) {
3178 sleeping_queue = t->link;
3180 prev->link = t->link;
3185 barf("unblockThread (I/O): TSO not found");
3189 barf("unblockThread");
3193 tso->link = END_TSO_QUEUE;
3194 tso->why_blocked = NotBlocked;
3195 tso->block_info.closure = NULL;
3196 PUSH_ON_RUN_QUEUE(tso);
3200 /* -----------------------------------------------------------------------------
3203 * The following function implements the magic for raising an
3204 * asynchronous exception in an existing thread.
3206 * We first remove the thread from any queue on which it might be
3207 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
3209 * We strip the stack down to the innermost CATCH_FRAME, building
3210 * thunks in the heap for all the active computations, so they can
3211 * be restarted if necessary. When we reach a CATCH_FRAME, we build
3212 * an application of the handler to the exception, and push it on
3213 * the top of the stack.
3215 * How exactly do we save all the active computations? We create an
3216 * AP_UPD for every UpdateFrame on the stack. Entering one of these
3217 * AP_UPDs pushes everything from the corresponding update frame
3218 * upwards onto the stack. (Actually, it pushes everything up to the
3219 * next update frame plus a pointer to the next AP_UPD object.
3220 * Entering the next AP_UPD object pushes more onto the stack until we
3221 * reach the last AP_UPD object - at which point the stack should look
3222 * exactly as it did when we killed the TSO and we can continue
3223 * execution by entering the closure on top of the stack.
3225 * We can also kill a thread entirely - this happens if either (a) the
3226 * exception passed to raiseAsync is NULL, or (b) there's no
3227 * CATCH_FRAME on the stack. In either case, we strip the entire
3228 * stack and replace the thread with a zombie.
3230 * Locks: sched_mutex held upon entry nor exit.
3232 * -------------------------------------------------------------------------- */
3235 deleteThread(StgTSO *tso)
3237 raiseAsync(tso,NULL);
3241 raiseAsyncWithLock(StgTSO *tso, StgClosure *exception)
3243 /* When raising async exs from contexts where sched_mutex isn't held;
3244 use raiseAsyncWithLock(). */
3245 ACQUIRE_LOCK(&sched_mutex);
3246 raiseAsync(tso,exception);
3247 RELEASE_LOCK(&sched_mutex);
3251 raiseAsync(StgTSO *tso, StgClosure *exception)
3253 StgUpdateFrame* su = tso->su;
3254 StgPtr sp = tso->sp;
3256 /* Thread already dead? */
3257 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3261 IF_DEBUG(scheduler, sched_belch("raising exception in thread %ld.", tso->id));
3263 /* Remove it from any blocking queues */
3266 IF_DEBUG(scheduler, sched_belch("raising exception in thread %ld.", tso->id));
3267 /* The stack freezing code assumes there's a closure pointer on
3268 * the top of the stack. This isn't always the case with compiled
3269 * code, so we have to push a dummy closure on the top which just
3270 * returns to the next return address on the stack.
3272 if ( LOOKS_LIKE_GHC_INFO((void*)*sp) ) {
3273 *(--sp) = (W_)&stg_dummy_ret_closure;
3277 nat words = ((P_)su - (P_)sp) - 1;
3281 /* If we find a CATCH_FRAME, and we've got an exception to raise,
3282 * then build the THUNK raise(exception), and leave it on
3283 * top of the CATCH_FRAME ready to enter.
3285 if (get_itbl(su)->type == CATCH_FRAME && exception != NULL) {
3287 StgCatchFrame *cf = (StgCatchFrame *)su;
3291 /* we've got an exception to raise, so let's pass it to the
3292 * handler in this frame.
3294 raise = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3295 TICK_ALLOC_SE_THK(1,0);
3296 SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
3297 raise->payload[0] = exception;
3299 /* throw away the stack from Sp up to the CATCH_FRAME.
3303 /* Ensure that async excpetions are blocked now, so we don't get
3304 * a surprise exception before we get around to executing the
3307 if (tso->blocked_exceptions == NULL) {
3308 tso->blocked_exceptions = END_TSO_QUEUE;
3311 /* Put the newly-built THUNK on top of the stack, ready to execute
3312 * when the thread restarts.
3317 tso->what_next = ThreadEnterGHC;
3318 IF_DEBUG(sanity, checkTSO(tso));
3322 /* First build an AP_UPD consisting of the stack chunk above the
3323 * current update frame, with the top word on the stack as the
3326 ap = (StgAP_UPD *)allocate(AP_sizeW(words));
3331 ap->fun = (StgClosure *)sp[0];
3333 for(i=0; i < (nat)words; ++i) {
3334 ap->payload[i] = (StgClosure *)*sp++;
3337 switch (get_itbl(su)->type) {
3341 SET_HDR(ap,&stg_AP_UPD_info,su->header.prof.ccs /* ToDo */);
3342 TICK_ALLOC_UP_THK(words+1,0);
3345 fprintf(stderr, "scheduler: Updating ");
3346 printPtr((P_)su->updatee);
3347 fprintf(stderr, " with ");
3348 printObj((StgClosure *)ap);
3351 /* Replace the updatee with an indirection - happily
3352 * this will also wake up any threads currently
3353 * waiting on the result.
3355 * Warning: if we're in a loop, more than one update frame on
3356 * the stack may point to the same object. Be careful not to
3357 * overwrite an IND_OLDGEN in this case, because we'll screw
3358 * up the mutable lists. To be on the safe side, don't
3359 * overwrite any kind of indirection at all. See also
3360 * threadSqueezeStack in GC.c, where we have to make a similar
3363 if (!closure_IND(su->updatee)) {
3364 UPD_IND_NOLOCK(su->updatee,ap); /* revert the black hole */
3367 sp += sizeofW(StgUpdateFrame) -1;
3368 sp[0] = (W_)ap; /* push onto stack */
3374 StgCatchFrame *cf = (StgCatchFrame *)su;
3377 /* We want a PAP, not an AP_UPD. Fortunately, the
3378 * layout's the same.
3380 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3381 TICK_ALLOC_UPD_PAP(words+1,0);
3383 /* now build o = FUN(catch,ap,handler) */
3384 o = (StgClosure *)allocate(sizeofW(StgClosure)+2);
3385 TICK_ALLOC_FUN(2,0);
3386 SET_HDR(o,&stg_catch_info,su->header.prof.ccs /* ToDo */);
3387 o->payload[0] = (StgClosure *)ap;
3388 o->payload[1] = cf->handler;
3391 fprintf(stderr, "scheduler: Built ");
3392 printObj((StgClosure *)o);
3395 /* pop the old handler and put o on the stack */
3397 sp += sizeofW(StgCatchFrame) - 1;
3404 StgSeqFrame *sf = (StgSeqFrame *)su;
3407 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3408 TICK_ALLOC_UPD_PAP(words+1,0);
3410 /* now build o = FUN(seq,ap) */
3411 o = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3412 TICK_ALLOC_SE_THK(1,0);
3413 SET_HDR(o,&stg_seq_info,su->header.prof.ccs /* ToDo */);
3414 o->payload[0] = (StgClosure *)ap;
3417 fprintf(stderr, "scheduler: Built ");
3418 printObj((StgClosure *)o);
3421 /* pop the old handler and put o on the stack */
3423 sp += sizeofW(StgSeqFrame) - 1;
3429 /* We've stripped the entire stack, the thread is now dead. */
3430 sp += sizeofW(StgStopFrame) - 1;
3431 sp[0] = (W_)exception; /* save the exception */
3432 tso->what_next = ThreadKilled;
3433 tso->su = (StgUpdateFrame *)(sp+1);
3444 /* -----------------------------------------------------------------------------
3445 resurrectThreads is called after garbage collection on the list of
3446 threads found to be garbage. Each of these threads will be woken
3447 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3448 on an MVar, or NonTermination if the thread was blocked on a Black
3451 Locks: sched_mutex isn't held upon entry nor exit.
3452 -------------------------------------------------------------------------- */
3455 resurrectThreads( StgTSO *threads )
3459 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3460 next = tso->global_link;
3461 tso->global_link = all_threads;
3463 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3465 switch (tso->why_blocked) {
3467 case BlockedOnException:
3468 /* Called by GC - sched_mutex lock is currently held. */
3469 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3471 case BlockedOnBlackHole:
3472 raiseAsync(tso,(StgClosure *)NonTermination_closure);
3475 /* This might happen if the thread was blocked on a black hole
3476 * belonging to a thread that we've just woken up (raiseAsync
3477 * can wake up threads, remember...).
3481 barf("resurrectThreads: thread blocked in a strange way");
3486 /* -----------------------------------------------------------------------------
3487 * Blackhole detection: if we reach a deadlock, test whether any
3488 * threads are blocked on themselves. Any threads which are found to
3489 * be self-blocked get sent a NonTermination exception.
3491 * This is only done in a deadlock situation in order to avoid
3492 * performance overhead in the normal case.
3494 * Locks: sched_mutex is held upon entry and exit.
3495 * -------------------------------------------------------------------------- */
3498 detectBlackHoles( void )
3500 StgTSO *t = all_threads;
3501 StgUpdateFrame *frame;
3502 StgClosure *blocked_on;
3504 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3506 while (t->what_next == ThreadRelocated) {
3508 ASSERT(get_itbl(t)->type == TSO);
3511 if (t->why_blocked != BlockedOnBlackHole) {
3515 blocked_on = t->block_info.closure;
3517 for (frame = t->su; ; frame = frame->link) {
3518 switch (get_itbl(frame)->type) {
3521 if (frame->updatee == blocked_on) {
3522 /* We are blocking on one of our own computations, so
3523 * send this thread the NonTermination exception.
3526 sched_belch("thread %d is blocked on itself", t->id));
3527 raiseAsync(t, (StgClosure *)NonTermination_closure);
3548 //@node Debugging Routines, Index, Exception Handling Routines, Main scheduling code
3549 //@subsection Debugging Routines
3551 /* -----------------------------------------------------------------------------
3552 Debugging: why is a thread blocked
3553 -------------------------------------------------------------------------- */
3558 printThreadBlockage(StgTSO *tso)
3560 switch (tso->why_blocked) {
3562 fprintf(stderr,"is blocked on read from fd %d", tso->block_info.fd);
3564 case BlockedOnWrite:
3565 fprintf(stderr,"is blocked on write to fd %d", tso->block_info.fd);
3567 case BlockedOnDelay:
3568 fprintf(stderr,"is blocked until %d", tso->block_info.target);
3571 fprintf(stderr,"is blocked on an MVar");
3573 case BlockedOnException:
3574 fprintf(stderr,"is blocked on delivering an exception to thread %d",
3575 tso->block_info.tso->id);
3577 case BlockedOnBlackHole:
3578 fprintf(stderr,"is blocked on a black hole");
3581 fprintf(stderr,"is not blocked");
3585 fprintf(stderr,"is blocked on global address; local FM_BQ is %p (%s)",
3586 tso->block_info.closure, info_type(tso->block_info.closure));
3588 case BlockedOnGA_NoSend:
3589 fprintf(stderr,"is blocked on global address (no send); local FM_BQ is %p (%s)",
3590 tso->block_info.closure, info_type(tso->block_info.closure));
3593 #if defined(RTS_SUPPORTS_THREADS)
3594 case BlockedOnCCall:
3595 fprintf(stderr,"is blocked on an external call");
3599 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3600 tso->why_blocked, tso->id, tso);
3605 printThreadStatus(StgTSO *tso)
3607 switch (tso->what_next) {
3609 fprintf(stderr,"has been killed");
3611 case ThreadComplete:
3612 fprintf(stderr,"has completed");
3615 printThreadBlockage(tso);
3620 printAllThreads(void)
3626 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3627 ullong_format_string(TIME_ON_PROC(CurrentProc),
3628 time_string, rtsFalse/*no commas!*/);
3630 sched_belch("all threads at [%s]:", time_string);
3632 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3633 ullong_format_string(CURRENT_TIME,
3634 time_string, rtsFalse/*no commas!*/);
3636 sched_belch("all threads at [%s]:", time_string);
3638 sched_belch("all threads:");
3641 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3642 fprintf(stderr, "\tthread %d @ %p ", t->id, (void *)t);
3643 label = lookupThreadLabel((StgWord)t);
3644 if (label) fprintf(stderr,"[\"%s\"] ",(char *)label);
3645 printThreadStatus(t);
3646 fprintf(stderr,"\n");
3651 Print a whole blocking queue attached to node (debugging only).
3656 print_bq (StgClosure *node)
3658 StgBlockingQueueElement *bqe;
3662 fprintf(stderr,"## BQ of closure %p (%s): ",
3663 node, info_type(node));
3665 /* should cover all closures that may have a blocking queue */
3666 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3667 get_itbl(node)->type == FETCH_ME_BQ ||
3668 get_itbl(node)->type == RBH ||
3669 get_itbl(node)->type == MVAR);
3671 ASSERT(node!=(StgClosure*)NULL); // sanity check
3673 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
3677 Print a whole blocking queue starting with the element bqe.
3680 print_bqe (StgBlockingQueueElement *bqe)
3685 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3687 for (end = (bqe==END_BQ_QUEUE);
3688 !end; // iterate until bqe points to a CONSTR
3689 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
3690 bqe = end ? END_BQ_QUEUE : bqe->link) {
3691 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3692 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3693 /* types of closures that may appear in a blocking queue */
3694 ASSERT(get_itbl(bqe)->type == TSO ||
3695 get_itbl(bqe)->type == BLOCKED_FETCH ||
3696 get_itbl(bqe)->type == CONSTR);
3697 /* only BQs of an RBH end with an RBH_Save closure */
3698 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3700 switch (get_itbl(bqe)->type) {
3702 fprintf(stderr," TSO %u (%x),",
3703 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
3706 fprintf(stderr," BF (node=%p, ga=((%x, %d, %x)),",
3707 ((StgBlockedFetch *)bqe)->node,
3708 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
3709 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
3710 ((StgBlockedFetch *)bqe)->ga.weight);
3713 fprintf(stderr," %s (IP %p),",
3714 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3715 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3716 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3717 "RBH_Save_?"), get_itbl(bqe));
3720 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
3721 info_type((StgClosure *)bqe)); // , node, info_type(node));
3725 fputc('\n', stderr);
3727 # elif defined(GRAN)
3729 print_bq (StgClosure *node)
3731 StgBlockingQueueElement *bqe;
3732 PEs node_loc, tso_loc;
3735 /* should cover all closures that may have a blocking queue */
3736 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3737 get_itbl(node)->type == FETCH_ME_BQ ||
3738 get_itbl(node)->type == RBH);
3740 ASSERT(node!=(StgClosure*)NULL); // sanity check
3741 node_loc = where_is(node);
3743 fprintf(stderr,"## BQ of closure %p (%s) on [PE %d]: ",
3744 node, info_type(node), node_loc);
3747 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3749 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
3750 !end; // iterate until bqe points to a CONSTR
3751 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
3752 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3753 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3754 /* types of closures that may appear in a blocking queue */
3755 ASSERT(get_itbl(bqe)->type == TSO ||
3756 get_itbl(bqe)->type == CONSTR);
3757 /* only BQs of an RBH end with an RBH_Save closure */
3758 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3760 tso_loc = where_is((StgClosure *)bqe);
3761 switch (get_itbl(bqe)->type) {
3763 fprintf(stderr," TSO %d (%p) on [PE %d],",
3764 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
3767 fprintf(stderr," %s (IP %p),",
3768 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3769 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3770 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3771 "RBH_Save_?"), get_itbl(bqe));
3774 barf("Unexpected closure type %s in blocking queue of %p (%s)",
3775 info_type((StgClosure *)bqe), node, info_type(node));
3779 fputc('\n', stderr);
3783 Nice and easy: only TSOs on the blocking queue
3786 print_bq (StgClosure *node)
3790 ASSERT(node!=(StgClosure*)NULL); // sanity check
3791 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
3792 tso != END_TSO_QUEUE;
3794 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
3795 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
3796 fprintf(stderr," TSO %d (%p),", tso->id, tso);
3798 fputc('\n', stderr);
3809 for (i=0, tso=run_queue_hd;
3810 tso != END_TSO_QUEUE;
3819 sched_belch(char *s, ...)
3824 fprintf(stderr, "scheduler (task %ld): ", osThreadId());
3826 fprintf(stderr, "== ");
3828 fprintf(stderr, "scheduler: ");
3830 vfprintf(stderr, s, ap);
3831 fprintf(stderr, "\n");
3838 //@node Index, , Debugging Routines, Main scheduling code
3842 //* StgMainThread:: @cindex\s-+StgMainThread
3843 //* awaken_blocked_queue:: @cindex\s-+awaken_blocked_queue
3844 //* blocked_queue_hd:: @cindex\s-+blocked_queue_hd
3845 //* blocked_queue_tl:: @cindex\s-+blocked_queue_tl
3846 //* context_switch:: @cindex\s-+context_switch
3847 //* createThread:: @cindex\s-+createThread
3848 //* gc_pending_cond:: @cindex\s-+gc_pending_cond
3849 //* initScheduler:: @cindex\s-+initScheduler
3850 //* interrupted:: @cindex\s-+interrupted
3851 //* next_thread_id:: @cindex\s-+next_thread_id
3852 //* print_bq:: @cindex\s-+print_bq
3853 //* run_queue_hd:: @cindex\s-+run_queue_hd
3854 //* run_queue_tl:: @cindex\s-+run_queue_tl
3855 //* sched_mutex:: @cindex\s-+sched_mutex
3856 //* schedule:: @cindex\s-+schedule
3857 //* take_off_run_queue:: @cindex\s-+take_off_run_queue
3858 //* term_mutex:: @cindex\s-+term_mutex