1 /* ---------------------------------------------------------------------------
2 * $Id: Schedule.c,v 1.153 2002/08/28 13:02:51 simonmar 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"
87 #define COMPILING_SCHEDULER
89 #include "StgMiscClosures.h"
91 #include "Interpreter.h"
92 #include "Exception.h"
100 #include "ThreadLabels.h"
102 #include "Proftimer.h"
103 #include "ProfHeap.h"
105 #if defined(GRAN) || defined(PAR)
106 # include "GranSimRts.h"
107 # include "GranSim.h"
108 # include "ParallelRts.h"
109 # include "Parallel.h"
110 # include "ParallelDebug.h"
111 # include "FetchMe.h"
115 #include "Capability.h"
116 #include "OSThreads.h"
119 #ifdef HAVE_SYS_TYPES_H
120 #include <sys/types.h>
130 //@node Variables and Data structures, Prototypes, Includes, Main scheduling code
131 //@subsection Variables and Data structures
133 /* Main thread queue.
134 * Locks required: sched_mutex.
136 StgMainThread *main_threads = NULL;
139 * Locks required: sched_mutex.
143 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
144 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
147 In GranSim we have a runnable and a blocked queue for each processor.
148 In order to minimise code changes new arrays run_queue_hds/tls
149 are created. run_queue_hd is then a short cut (macro) for
150 run_queue_hds[CurrentProc] (see GranSim.h).
153 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
154 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
155 StgTSO *ccalling_threadss[MAX_PROC];
156 /* We use the same global list of threads (all_threads) in GranSim as in
157 the std RTS (i.e. we are cheating). However, we don't use this list in
158 the GranSim specific code at the moment (so we are only potentially
163 StgTSO *run_queue_hd = NULL;
164 StgTSO *run_queue_tl = NULL;
165 StgTSO *blocked_queue_hd = NULL;
166 StgTSO *blocked_queue_tl = NULL;
167 StgTSO *sleeping_queue = NULL; /* perhaps replace with a hash table? */
171 /* Linked list of all threads.
172 * Used for detecting garbage collected threads.
174 StgTSO *all_threads = NULL;
176 /* When a thread performs a safe C call (_ccall_GC, using old
177 * terminology), it gets put on the suspended_ccalling_threads
178 * list. Used by the garbage collector.
180 static StgTSO *suspended_ccalling_threads;
182 static StgTSO *threadStackOverflow(StgTSO *tso);
184 /* KH: The following two flags are shared memory locations. There is no need
185 to lock them, since they are only unset at the end of a scheduler
189 /* flag set by signal handler to precipitate a context switch */
190 //@cindex context_switch
191 nat context_switch = 0;
193 /* if this flag is set as well, give up execution */
194 //@cindex interrupted
195 rtsBool interrupted = rtsFalse;
197 /* Next thread ID to allocate.
198 * Locks required: thread_id_mutex
200 //@cindex next_thread_id
201 static StgThreadID next_thread_id = 1;
204 * Pointers to the state of the current thread.
205 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
206 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
209 /* The smallest stack size that makes any sense is:
210 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
211 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
212 * + 1 (the realworld token for an IO thread)
213 * + 1 (the closure to enter)
215 * A thread with this stack will bomb immediately with a stack
216 * overflow, which will increase its stack size.
219 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 2)
226 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
227 * exists - earlier gccs apparently didn't.
232 static rtsBool ready_to_gc;
235 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
236 * in an MT setting, needed to signal that a worker thread shouldn't hang around
237 * in the scheduler when it is out of work.
239 static rtsBool shutting_down_scheduler = rtsFalse;
241 void addToBlockedQueue ( StgTSO *tso );
243 static void schedule ( void );
244 void interruptStgRts ( void );
246 static void detectBlackHoles ( void );
249 static void sched_belch(char *s, ...);
252 #if defined(RTS_SUPPORTS_THREADS)
253 /* ToDo: carefully document the invariants that go together
254 * with these synchronisation objects.
256 Mutex sched_mutex = INIT_MUTEX_VAR;
257 Mutex term_mutex = INIT_MUTEX_VAR;
260 * A heavyweight solution to the problem of protecting
261 * the thread_id from concurrent update.
263 Mutex thread_id_mutex = INIT_MUTEX_VAR;
267 static Condition gc_pending_cond = INIT_COND_VAR;
271 #endif /* RTS_SUPPORTS_THREADS */
275 rtsTime TimeOfLastYield;
276 rtsBool emitSchedule = rtsTrue;
280 static char *whatNext_strs[] = {
290 StgTSO * createSparkThread(rtsSpark spark);
291 StgTSO * activateSpark (rtsSpark spark);
295 * The thread state for the main thread.
296 // ToDo: check whether not needed any more
300 #if defined(PAR) || defined(RTS_SUPPORTS_THREADS)
301 static void taskStart(void);
312 //@node Main scheduling loop, Suspend and Resume, Prototypes, Main scheduling code
313 //@subsection Main scheduling loop
315 /* ---------------------------------------------------------------------------
316 Main scheduling loop.
318 We use round-robin scheduling, each thread returning to the
319 scheduler loop when one of these conditions is detected:
322 * timer expires (thread yields)
327 Locking notes: we acquire the scheduler lock once at the beginning
328 of the scheduler loop, and release it when
330 * running a thread, or
331 * waiting for work, or
332 * waiting for a GC to complete.
335 In a GranSim setup this loop iterates over the global event queue.
336 This revolves around the global event queue, which determines what
337 to do next. Therefore, it's more complicated than either the
338 concurrent or the parallel (GUM) setup.
341 GUM iterates over incoming messages.
342 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
343 and sends out a fish whenever it has nothing to do; in-between
344 doing the actual reductions (shared code below) it processes the
345 incoming messages and deals with delayed operations
346 (see PendingFetches).
347 This is not the ugliest code you could imagine, but it's bloody close.
349 ------------------------------------------------------------------------ */
356 StgThreadReturnCode ret;
364 rtsBool receivedFinish = rtsFalse;
366 nat tp_size, sp_size; // stats only
369 rtsBool was_interrupted = rtsFalse;
371 ACQUIRE_LOCK(&sched_mutex);
373 #if defined(RTS_SUPPORTS_THREADS)
374 waitForWorkCapability(&sched_mutex, &cap, rtsFalse);
376 /* simply initialise it in the non-threaded case */
377 grabCapability(&cap);
381 /* set up first event to get things going */
382 /* ToDo: assign costs for system setup and init MainTSO ! */
383 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
385 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
388 fprintf(stderr, "GRAN: Init CurrentTSO (in schedule) = %p\n", CurrentTSO);
389 G_TSO(CurrentTSO, 5));
391 if (RtsFlags.GranFlags.Light) {
392 /* Save current time; GranSim Light only */
393 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
396 event = get_next_event();
398 while (event!=(rtsEvent*)NULL) {
399 /* Choose the processor with the next event */
400 CurrentProc = event->proc;
401 CurrentTSO = event->tso;
405 while (!receivedFinish) { /* set by processMessages */
406 /* when receiving PP_FINISH message */
413 IF_DEBUG(scheduler, printAllThreads());
415 #if defined(RTS_SUPPORTS_THREADS)
416 /* Check to see whether there are any worker threads
417 waiting to deposit external call results. If so,
418 yield our capability */
419 yieldToReturningWorker(&sched_mutex, &cap);
422 /* If we're interrupted (the user pressed ^C, or some other
423 * termination condition occurred), kill all the currently running
427 IF_DEBUG(scheduler, sched_belch("interrupted"));
429 interrupted = rtsFalse;
430 was_interrupted = rtsTrue;
433 /* Go through the list of main threads and wake up any
434 * clients whose computations have finished. ToDo: this
435 * should be done more efficiently without a linear scan
436 * of the main threads list, somehow...
438 #if defined(RTS_SUPPORTS_THREADS)
440 StgMainThread *m, **prev;
441 prev = &main_threads;
442 for (m = main_threads; m != NULL; m = m->link) {
443 switch (m->tso->what_next) {
446 *(m->ret) = (StgClosure *)m->tso->sp[0];
450 broadcastCondition(&m->wakeup);
452 removeThreadLabel((StgWord)m->tso);
456 if (m->ret) *(m->ret) = NULL;
458 if (was_interrupted) {
459 m->stat = Interrupted;
463 broadcastCondition(&m->wakeup);
465 removeThreadLabel((StgWord)m->tso);
474 #else /* not threaded */
477 /* in GUM do this only on the Main PE */
480 /* If our main thread has finished or been killed, return.
483 StgMainThread *m = main_threads;
484 if (m->tso->what_next == ThreadComplete
485 || m->tso->what_next == ThreadKilled) {
487 removeThreadLabel((StgWord)m->tso);
489 main_threads = main_threads->link;
490 if (m->tso->what_next == ThreadComplete) {
491 /* we finished successfully, fill in the return value */
492 if (m->ret) { *(m->ret) = (StgClosure *)m->tso->sp[0]; };
496 if (m->ret) { *(m->ret) = NULL; };
497 if (was_interrupted) {
498 m->stat = Interrupted;
508 /* Top up the run queue from our spark pool. We try to make the
509 * number of threads in the run queue equal to the number of
512 * Disable spark support in SMP for now, non-essential & requires
513 * a little bit of work to make it compile cleanly. -- sof 1/02.
515 #if 0 /* defined(SMP) */
517 nat n = getFreeCapabilities();
518 StgTSO *tso = run_queue_hd;
520 /* Count the run queue */
521 while (n > 0 && tso != END_TSO_QUEUE) {
528 spark = findSpark(rtsFalse);
530 break; /* no more sparks in the pool */
532 /* I'd prefer this to be done in activateSpark -- HWL */
533 /* tricky - it needs to hold the scheduler lock and
534 * not try to re-acquire it -- SDM */
535 createSparkThread(spark);
537 sched_belch("==^^ turning spark of closure %p into a thread",
538 (StgClosure *)spark));
541 /* We need to wake up the other tasks if we just created some
544 if (getFreeCapabilities() - n > 1) {
545 signalCondition( &thread_ready_cond );
550 /* check for signals each time around the scheduler */
551 #ifndef mingw32_TARGET_OS
552 if (signals_pending()) {
553 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
554 startSignalHandlers();
555 ACQUIRE_LOCK(&sched_mutex);
559 /* Check whether any waiting threads need to be woken up. If the
560 * run queue is empty, and there are no other tasks running, we
561 * can wait indefinitely for something to happen.
562 * ToDo: what if another client comes along & requests another
565 if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue) ) {
566 awaitEvent( EMPTY_RUN_QUEUE()
568 && allFreeCapabilities()
572 /* we can be interrupted while waiting for I/O... */
573 if (interrupted) continue;
576 * Detect deadlock: when we have no threads to run, there are no
577 * threads waiting on I/O or sleeping, and all the other tasks are
578 * waiting for work, we must have a deadlock of some description.
580 * We first try to find threads blocked on themselves (ie. black
581 * holes), and generate NonTermination exceptions where necessary.
583 * If no threads are black holed, we have a deadlock situation, so
584 * inform all the main threads.
587 if ( EMPTY_THREAD_QUEUES()
588 #if defined(RTS_SUPPORTS_THREADS)
589 && EMPTY_QUEUE(suspended_ccalling_threads)
592 && allFreeCapabilities()
596 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
597 #if defined(THREADED_RTS)
598 /* and SMP mode ..? */
599 releaseCapability(cap);
601 // Garbage collection can release some new threads due to
602 // either (a) finalizers or (b) threads resurrected because
603 // they are about to be send BlockedOnDeadMVar. Any threads
604 // thus released will be immediately runnable.
605 GarbageCollect(GetRoots,rtsTrue);
607 if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
610 sched_belch("still deadlocked, checking for black holes..."));
613 if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
615 #ifndef mingw32_TARGET_OS
616 /* If we have user-installed signal handlers, then wait
617 * for signals to arrive rather then bombing out with a
620 #if defined(RTS_SUPPORTS_THREADS)
621 if ( 0 ) { /* hmm..what to do? Simply stop waiting for
622 a signal with no runnable threads (or I/O
623 suspended ones) leads nowhere quick.
624 For now, simply shut down when we reach this
627 ToDo: define precisely under what conditions
628 the Scheduler should shut down in an MT setting.
631 if ( anyUserHandlers() ) {
634 sched_belch("still deadlocked, waiting for signals..."));
638 // we might be interrupted...
639 if (interrupted) { continue; }
641 if (signals_pending()) {
642 RELEASE_LOCK(&sched_mutex);
643 startSignalHandlers();
644 ACQUIRE_LOCK(&sched_mutex);
646 ASSERT(!EMPTY_RUN_QUEUE());
651 /* Probably a real deadlock. Send the current main thread the
652 * Deadlock exception (or in the SMP build, send *all* main
653 * threads the deadlock exception, since none of them can make
658 #if defined(RTS_SUPPORTS_THREADS)
659 for (m = main_threads; m != NULL; m = m->link) {
660 switch (m->tso->why_blocked) {
661 case BlockedOnBlackHole:
662 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
664 case BlockedOnException:
666 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
669 barf("deadlock: main thread blocked in a strange way");
674 switch (m->tso->why_blocked) {
675 case BlockedOnBlackHole:
676 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
678 case BlockedOnException:
680 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
683 barf("deadlock: main thread blocked in a strange way");
688 #if defined(RTS_SUPPORTS_THREADS)
689 /* ToDo: revisit conditions (and mechanism) for shutting
690 down a multi-threaded world */
691 IF_DEBUG(scheduler, sched_belch("all done, i think...shutting down."));
692 RELEASE_LOCK(&sched_mutex);
700 /* ToDo: add deadlock detection in GUM (similar to SMP) -- HWL */
704 /* If there's a GC pending, don't do anything until it has
708 IF_DEBUG(scheduler,sched_belch("waiting for GC"));
709 waitCondition( &gc_pending_cond, &sched_mutex );
713 #if defined(RTS_SUPPORTS_THREADS)
714 /* block until we've got a thread on the run queue and a free
718 if ( EMPTY_RUN_QUEUE() ) {
719 /* Give up our capability */
720 releaseCapability(cap);
722 /* If we're in the process of shutting down (& running the
723 * a batch of finalisers), don't wait around.
725 if ( shutting_down_scheduler ) {
726 RELEASE_LOCK(&sched_mutex);
729 IF_DEBUG(scheduler, sched_belch("thread %d: waiting for work", osThreadId()));
730 waitForWorkCapability(&sched_mutex, &cap, rtsTrue);
731 IF_DEBUG(scheduler, sched_belch("thread %d: work now available", osThreadId()));
736 if (RtsFlags.GranFlags.Light)
737 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
739 /* adjust time based on time-stamp */
740 if (event->time > CurrentTime[CurrentProc] &&
741 event->evttype != ContinueThread)
742 CurrentTime[CurrentProc] = event->time;
744 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
745 if (!RtsFlags.GranFlags.Light)
748 IF_DEBUG(gran, fprintf(stderr, "GRAN: switch by event-type\n"));
750 /* main event dispatcher in GranSim */
751 switch (event->evttype) {
752 /* Should just be continuing execution */
754 IF_DEBUG(gran, fprintf(stderr, "GRAN: doing ContinueThread\n"));
755 /* ToDo: check assertion
756 ASSERT(run_queue_hd != (StgTSO*)NULL &&
757 run_queue_hd != END_TSO_QUEUE);
759 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
760 if (!RtsFlags.GranFlags.DoAsyncFetch &&
761 procStatus[CurrentProc]==Fetching) {
762 belch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]",
763 CurrentTSO->id, CurrentTSO, CurrentProc);
766 /* Ignore ContinueThreads for completed threads */
767 if (CurrentTSO->what_next == ThreadComplete) {
768 belch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)",
769 CurrentTSO->id, CurrentTSO, CurrentProc);
772 /* Ignore ContinueThreads for threads that are being migrated */
773 if (PROCS(CurrentTSO)==Nowhere) {
774 belch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)",
775 CurrentTSO->id, CurrentTSO, CurrentProc);
778 /* The thread should be at the beginning of the run queue */
779 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
780 belch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread",
781 CurrentTSO->id, CurrentTSO, CurrentProc);
782 break; // run the thread anyway
785 new_event(proc, proc, CurrentTime[proc],
787 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
789 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
790 break; // now actually run the thread; DaH Qu'vam yImuHbej
793 do_the_fetchnode(event);
794 goto next_thread; /* handle next event in event queue */
797 do_the_globalblock(event);
798 goto next_thread; /* handle next event in event queue */
801 do_the_fetchreply(event);
802 goto next_thread; /* handle next event in event queue */
804 case UnblockThread: /* Move from the blocked queue to the tail of */
805 do_the_unblock(event);
806 goto next_thread; /* handle next event in event queue */
808 case ResumeThread: /* Move from the blocked queue to the tail of */
809 /* the runnable queue ( i.e. Qu' SImqa'lu') */
810 event->tso->gran.blocktime +=
811 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
812 do_the_startthread(event);
813 goto next_thread; /* handle next event in event queue */
816 do_the_startthread(event);
817 goto next_thread; /* handle next event in event queue */
820 do_the_movethread(event);
821 goto next_thread; /* handle next event in event queue */
824 do_the_movespark(event);
825 goto next_thread; /* handle next event in event queue */
828 do_the_findwork(event);
829 goto next_thread; /* handle next event in event queue */
832 barf("Illegal event type %u\n", event->evttype);
835 /* This point was scheduler_loop in the old RTS */
837 IF_DEBUG(gran, belch("GRAN: after main switch"));
839 TimeOfLastEvent = CurrentTime[CurrentProc];
840 TimeOfNextEvent = get_time_of_next_event();
841 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
842 // CurrentTSO = ThreadQueueHd;
844 IF_DEBUG(gran, belch("GRAN: time of next event is: %ld",
847 if (RtsFlags.GranFlags.Light)
848 GranSimLight_leave_system(event, &ActiveTSO);
850 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
853 belch("GRAN: end of time-slice is %#lx", EndOfTimeSlice));
855 /* in a GranSim setup the TSO stays on the run queue */
857 /* Take a thread from the run queue. */
858 t = POP_RUN_QUEUE(); // take_off_run_queue(t);
861 fprintf(stderr, "GRAN: About to run current thread, which is\n");
864 context_switch = 0; // turned on via GranYield, checking events and time slice
867 DumpGranEvent(GR_SCHEDULE, t));
869 procStatus[CurrentProc] = Busy;
872 if (PendingFetches != END_BF_QUEUE) {
876 /* ToDo: phps merge with spark activation above */
877 /* check whether we have local work and send requests if we have none */
878 if (EMPTY_RUN_QUEUE()) { /* no runnable threads */
879 /* :-[ no local threads => look out for local sparks */
880 /* the spark pool for the current PE */
881 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
882 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
883 pool->hd < pool->tl) {
885 * ToDo: add GC code check that we really have enough heap afterwards!!
887 * If we're here (no runnable threads) and we have pending
888 * sparks, we must have a space problem. Get enough space
889 * to turn one of those pending sparks into a
893 spark = findSpark(rtsFalse); /* get a spark */
894 if (spark != (rtsSpark) NULL) {
895 tso = activateSpark(spark); /* turn the spark into a thread */
896 IF_PAR_DEBUG(schedule,
897 belch("==== schedule: Created TSO %d (%p); %d threads active",
898 tso->id, tso, advisory_thread_count));
900 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
901 belch("==^^ failed to activate spark");
903 } /* otherwise fall through & pick-up new tso */
905 IF_PAR_DEBUG(verbose,
906 belch("==^^ no local sparks (spark pool contains only NFs: %d)",
907 spark_queue_len(pool)));
912 /* If we still have no work we need to send a FISH to get a spark
915 if (EMPTY_RUN_QUEUE()) {
916 /* =8-[ no local sparks => look for work on other PEs */
918 * We really have absolutely no work. Send out a fish
919 * (there may be some out there already), and wait for
920 * something to arrive. We clearly can't run any threads
921 * until a SCHEDULE or RESUME arrives, and so that's what
922 * we're hoping to see. (Of course, we still have to
923 * respond to other types of messages.)
925 TIME now = msTime() /*CURRENT_TIME*/;
926 IF_PAR_DEBUG(verbose,
927 belch("-- now=%ld", now));
928 IF_PAR_DEBUG(verbose,
929 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
930 (last_fish_arrived_at!=0 &&
931 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
932 belch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)",
933 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
934 last_fish_arrived_at,
935 RtsFlags.ParFlags.fishDelay, now);
938 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
939 (last_fish_arrived_at==0 ||
940 (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
941 /* outstandingFishes is set in sendFish, processFish;
942 avoid flooding system with fishes via delay */
944 sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY,
947 // Global statistics: count no. of fishes
948 if (RtsFlags.ParFlags.ParStats.Global &&
949 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
950 globalParStats.tot_fish_mess++;
954 receivedFinish = processMessages();
957 } else if (PacketsWaiting()) { /* Look for incoming messages */
958 receivedFinish = processMessages();
961 /* Now we are sure that we have some work available */
962 ASSERT(run_queue_hd != END_TSO_QUEUE);
964 /* Take a thread from the run queue, if we have work */
965 t = POP_RUN_QUEUE(); // take_off_run_queue(END_TSO_QUEUE);
966 IF_DEBUG(sanity,checkTSO(t));
968 /* ToDo: write something to the log-file
969 if (RTSflags.ParFlags.granSimStats && !sameThread)
970 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
974 /* the spark pool for the current PE */
975 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
978 belch("--=^ %d threads, %d sparks on [%#x]",
979 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
982 if (0 && RtsFlags.ParFlags.ParStats.Full &&
983 t && LastTSO && t->id != LastTSO->id &&
984 LastTSO->why_blocked == NotBlocked &&
985 LastTSO->what_next != ThreadComplete) {
986 // if previously scheduled TSO not blocked we have to record the context switch
987 DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
988 GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
991 if (RtsFlags.ParFlags.ParStats.Full &&
992 (emitSchedule /* forced emit */ ||
993 (t && LastTSO && t->id != LastTSO->id))) {
995 we are running a different TSO, so write a schedule event to log file
996 NB: If we use fair scheduling we also have to write a deschedule
997 event for LastTSO; with unfair scheduling we know that the
998 previous tso has blocked whenever we switch to another tso, so
999 we don't need it in GUM for now
1001 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1002 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
1003 emitSchedule = rtsFalse;
1007 #else /* !GRAN && !PAR */
1009 /* grab a thread from the run queue */
1010 ASSERT(run_queue_hd != END_TSO_QUEUE);
1011 t = POP_RUN_QUEUE();
1012 // Sanity check the thread we're about to run. This can be
1013 // expensive if there is lots of thread switching going on...
1014 IF_DEBUG(sanity,checkTSO(t));
1017 cap->r.rCurrentTSO = t;
1019 /* context switches are now initiated by the timer signal, unless
1020 * the user specified "context switch as often as possible", with
1025 RtsFlags.ProfFlags.profileInterval == 0 ||
1027 (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
1028 && (run_queue_hd != END_TSO_QUEUE
1029 || blocked_queue_hd != END_TSO_QUEUE
1030 || sleeping_queue != END_TSO_QUEUE)))
1035 RELEASE_LOCK(&sched_mutex);
1037 IF_DEBUG(scheduler, sched_belch("-->> Running TSO %ld (%p) %s ...",
1038 t->id, t, whatNext_strs[t->what_next]));
1041 startHeapProfTimer();
1044 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1045 /* Run the current thread
1047 switch (cap->r.rCurrentTSO->what_next) {
1049 case ThreadComplete:
1050 /* Thread already finished, return to scheduler. */
1051 ret = ThreadFinished;
1053 case ThreadEnterGHC:
1054 ret = StgRun((StgFunPtr) stg_enterStackTop, &cap->r);
1057 ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
1059 case ThreadEnterInterp:
1060 ret = interpretBCO(cap);
1063 barf("schedule: invalid what_next field");
1065 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1067 /* Costs for the scheduler are assigned to CCS_SYSTEM */
1069 stopHeapProfTimer();
1073 ACQUIRE_LOCK(&sched_mutex);
1076 IF_DEBUG(scheduler,fprintf(stderr,"scheduler (task %ld): ", osThreadId()););
1077 #elif !defined(GRAN) && !defined(PAR)
1078 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: "););
1080 t = cap->r.rCurrentTSO;
1083 /* HACK 675: if the last thread didn't yield, make sure to print a
1084 SCHEDULE event to the log file when StgRunning the next thread, even
1085 if it is the same one as before */
1087 TimeOfLastYield = CURRENT_TIME;
1093 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
1094 globalGranStats.tot_heapover++;
1096 globalParStats.tot_heapover++;
1099 // did the task ask for a large block?
1100 if (cap->r.rHpAlloc > BLOCK_SIZE_W) {
1101 // if so, get one and push it on the front of the nursery.
1105 blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc * sizeof(W_)) / BLOCK_SIZE;
1107 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: requesting a large block (size %d)",
1109 whatNext_strs[t->what_next], blocks));
1111 // don't do this if it would push us over the
1112 // alloc_blocks_lim limit; we'll GC first.
1113 if (alloc_blocks + blocks < alloc_blocks_lim) {
1115 alloc_blocks += blocks;
1116 bd = allocGroup( blocks );
1118 // link the new group into the list
1119 bd->link = cap->r.rCurrentNursery;
1120 bd->u.back = cap->r.rCurrentNursery->u.back;
1121 if (cap->r.rCurrentNursery->u.back != NULL) {
1122 cap->r.rCurrentNursery->u.back->link = bd;
1124 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1125 g0s0->blocks == cap->r.rNursery);
1126 cap->r.rNursery = g0s0->blocks = bd;
1128 cap->r.rCurrentNursery->u.back = bd;
1130 // initialise it as a nursery block. We initialise the
1131 // step, gen_no, and flags field of *every* sub-block in
1132 // this large block, because this is easier than making
1133 // sure that we always find the block head of a large
1134 // block whenever we call Bdescr() (eg. evacuate() and
1135 // isAlive() in the GC would both have to do this, at
1139 for (x = bd; x < bd + blocks; x++) {
1147 // don't forget to update the block count in g0s0.
1148 g0s0->n_blocks += blocks;
1149 ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1151 // now update the nursery to point to the new block
1152 cap->r.rCurrentNursery = bd;
1154 // we might be unlucky and have another thread get on the
1155 // run queue before us and steal the large block, but in that
1156 // case the thread will just end up requesting another large
1158 PUSH_ON_RUN_QUEUE(t);
1163 /* make all the running tasks block on a condition variable,
1164 * maybe set context_switch and wait till they all pile in,
1165 * then have them wait on a GC condition variable.
1167 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: HeapOverflow",
1168 t->id, t, whatNext_strs[t->what_next]));
1171 ASSERT(!is_on_queue(t,CurrentProc));
1173 /* Currently we emit a DESCHEDULE event before GC in GUM.
1174 ToDo: either add separate event to distinguish SYSTEM time from rest
1175 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1176 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1177 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1178 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1179 emitSchedule = rtsTrue;
1183 ready_to_gc = rtsTrue;
1184 context_switch = 1; /* stop other threads ASAP */
1185 PUSH_ON_RUN_QUEUE(t);
1186 /* actual GC is done at the end of the while loop */
1192 DumpGranEvent(GR_DESCHEDULE, t));
1193 globalGranStats.tot_stackover++;
1196 // DumpGranEvent(GR_DESCHEDULE, t);
1197 globalParStats.tot_stackover++;
1199 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped, StackOverflow",
1200 t->id, t, whatNext_strs[t->what_next]));
1201 /* just adjust the stack for this thread, then pop it back
1207 /* enlarge the stack */
1208 StgTSO *new_t = threadStackOverflow(t);
1210 /* This TSO has moved, so update any pointers to it from the
1211 * main thread stack. It better not be on any other queues...
1212 * (it shouldn't be).
1214 for (m = main_threads; m != NULL; m = m->link) {
1219 threadPaused(new_t);
1220 PUSH_ON_RUN_QUEUE(new_t);
1224 case ThreadYielding:
1227 DumpGranEvent(GR_DESCHEDULE, t));
1228 globalGranStats.tot_yields++;
1231 // DumpGranEvent(GR_DESCHEDULE, t);
1232 globalParStats.tot_yields++;
1234 /* put the thread back on the run queue. Then, if we're ready to
1235 * GC, check whether this is the last task to stop. If so, wake
1236 * up the GC thread. getThread will block during a GC until the
1240 if (t->what_next == ThreadEnterInterp) {
1241 /* ToDo: or maybe a timer expired when we were in Hugs?
1242 * or maybe someone hit ctrl-C
1244 belch("--<< thread %ld (%p; %s) stopped to switch to Hugs",
1245 t->id, t, whatNext_strs[t->what_next]);
1247 belch("--<< thread %ld (%p; %s) stopped, yielding",
1248 t->id, t, whatNext_strs[t->what_next]);
1255 //belch("&& Doing sanity check on yielding TSO %ld.", t->id);
1257 ASSERT(t->link == END_TSO_QUEUE);
1259 ASSERT(!is_on_queue(t,CurrentProc));
1262 //belch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1263 checkThreadQsSanity(rtsTrue));
1266 if (RtsFlags.ParFlags.doFairScheduling) {
1267 /* this does round-robin scheduling; good for concurrency */
1268 APPEND_TO_RUN_QUEUE(t);
1270 /* this does unfair scheduling; good for parallelism */
1271 PUSH_ON_RUN_QUEUE(t);
1274 /* this does round-robin scheduling; good for concurrency */
1275 APPEND_TO_RUN_QUEUE(t);
1278 /* add a ContinueThread event to actually process the thread */
1279 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1281 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1283 belch("GRAN: eventq and runnableq after adding yielded thread to queue again:");
1292 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1293 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)));
1294 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1296 // ??? needed; should emit block before
1298 DumpGranEvent(GR_DESCHEDULE, t));
1299 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1302 ASSERT(procStatus[CurrentProc]==Busy ||
1303 ((procStatus[CurrentProc]==Fetching) &&
1304 (t->block_info.closure!=(StgClosure*)NULL)));
1305 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1306 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1307 procStatus[CurrentProc]==Fetching))
1308 procStatus[CurrentProc] = Idle;
1312 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: ",
1313 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1316 if (t->block_info.closure!=(StgClosure*)NULL)
1317 print_bq(t->block_info.closure));
1319 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1322 /* whatever we schedule next, we must log that schedule */
1323 emitSchedule = rtsTrue;
1326 /* don't need to do anything. Either the thread is blocked on
1327 * I/O, in which case we'll have called addToBlockedQueue
1328 * previously, or it's blocked on an MVar or Blackhole, in which
1329 * case it'll be on the relevant queue already.
1332 fprintf(stderr, "--<< thread %d (%p) stopped: ", t->id, t);
1333 printThreadBlockage(t);
1334 fprintf(stderr, "\n"));
1336 /* Only for dumping event to log file
1337 ToDo: do I need this in GranSim, too?
1344 case ThreadFinished:
1345 /* Need to check whether this was a main thread, and if so, signal
1346 * the task that started it with the return value. If we have no
1347 * more main threads, we probably need to stop all the tasks until
1350 /* We also end up here if the thread kills itself with an
1351 * uncaught exception, see Exception.hc.
1353 IF_DEBUG(scheduler,belch("--++ thread %d (%p) finished", t->id, t));
1355 endThread(t, CurrentProc); // clean-up the thread
1357 /* For now all are advisory -- HWL */
1358 //if(t->priority==AdvisoryPriority) ??
1359 advisory_thread_count--;
1362 if(t->dist.priority==RevalPriority)
1366 if (RtsFlags.ParFlags.ParStats.Full &&
1367 !RtsFlags.ParFlags.ParStats.Suppressed)
1368 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1373 barf("schedule: invalid thread return code %d", (int)ret);
1377 if (RtsFlags.ProfFlags.profileInterval==0 || performHeapProfile) {
1378 GarbageCollect(GetRoots, rtsTrue);
1380 performHeapProfile = rtsFalse;
1381 ready_to_gc = rtsFalse; // we already GC'd
1387 && allFreeCapabilities()
1390 /* everybody back, start the GC.
1391 * Could do it in this thread, or signal a condition var
1392 * to do it in another thread. Either way, we need to
1393 * broadcast on gc_pending_cond afterward.
1395 #if defined(RTS_SUPPORTS_THREADS)
1396 IF_DEBUG(scheduler,sched_belch("doing GC"));
1398 GarbageCollect(GetRoots,rtsFalse);
1399 ready_to_gc = rtsFalse;
1401 broadcastCondition(&gc_pending_cond);
1404 /* add a ContinueThread event to continue execution of current thread */
1405 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1407 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1409 fprintf(stderr, "GRAN: eventq and runnableq after Garbage collection:\n");
1417 IF_GRAN_DEBUG(unused,
1418 print_eventq(EventHd));
1420 event = get_next_event();
1423 /* ToDo: wait for next message to arrive rather than busy wait */
1426 } /* end of while(1) */
1428 IF_PAR_DEBUG(verbose,
1429 belch("== Leaving schedule() after having received Finish"));
1432 /* ---------------------------------------------------------------------------
1433 * Singleton fork(). Do not copy any running threads.
1434 * ------------------------------------------------------------------------- */
1436 StgInt forkProcess(StgTSO* tso) {
1438 #ifndef mingw32_TARGET_OS
1444 IF_DEBUG(scheduler,sched_belch("forking!"));
1447 if (pid) { /* parent */
1449 /* just return the pid */
1451 } else { /* child */
1452 /* wipe all other threads */
1453 run_queue_hd = run_queue_tl = tso;
1454 tso->link = END_TSO_QUEUE;
1456 /* When clearing out the threads, we need to ensure
1457 that a 'main thread' is left behind; if there isn't,
1458 the Scheduler will shutdown next time it is entered.
1460 ==> we don't kill a thread that's on the main_threads
1461 list (nor the current thread.)
1463 [ Attempts at implementing the more ambitious scheme of
1464 killing the main_threads also, and then adding the
1465 current thread onto the main_threads list if it wasn't
1466 there already, failed -- waitThread() (for one) wasn't
1467 up to it. If it proves to be desirable to also kill
1468 the main threads, then this scheme will have to be
1469 revisited (and fully debugged!)
1474 /* DO NOT TOUCH THE QUEUES directly because most of the code around
1475 us is picky about finding the thread still in its queue when
1476 handling the deleteThread() */
1478 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1481 /* Don't kill the current thread.. */
1482 if (t->id == tso->id) continue;
1484 /* ..or a main thread */
1485 for (m = main_threads; m != NULL; m = m->link) {
1486 if (m->tso->id == t->id) {
1498 barf("forkProcess#: primop not implemented for mingw32, sorry! (%u)\n", tso->id);
1499 /* pointlessly printing out the TSOs 'id' to avoid CC unused warning. */
1501 #endif /* mingw32 */
1504 /* ---------------------------------------------------------------------------
1505 * deleteAllThreads(): kill all the live threads.
1507 * This is used when we catch a user interrupt (^C), before performing
1508 * any necessary cleanups and running finalizers.
1510 * Locks: sched_mutex held.
1511 * ------------------------------------------------------------------------- */
1513 void deleteAllThreads ( void )
1516 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
1517 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1518 next = t->global_link;
1521 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1522 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
1523 sleeping_queue = END_TSO_QUEUE;
1526 /* startThread and insertThread are now in GranSim.c -- HWL */
1529 //@node Suspend and Resume, Run queue code, Main scheduling loop, Main scheduling code
1530 //@subsection Suspend and Resume
1532 /* ---------------------------------------------------------------------------
1533 * Suspending & resuming Haskell threads.
1535 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1536 * its capability before calling the C function. This allows another
1537 * task to pick up the capability and carry on running Haskell
1538 * threads. It also means that if the C call blocks, it won't lock
1541 * The Haskell thread making the C call is put to sleep for the
1542 * duration of the call, on the susepended_ccalling_threads queue. We
1543 * give out a token to the task, which it can use to resume the thread
1544 * on return from the C function.
1545 * ------------------------------------------------------------------------- */
1548 suspendThread( StgRegTable *reg,
1550 #if !defined(RTS_SUPPORTS_THREADS) && !defined(DEBUG)
1558 /* assume that *reg is a pointer to the StgRegTable part
1561 cap = (Capability *)((void *)reg - sizeof(StgFunTable));
1563 ACQUIRE_LOCK(&sched_mutex);
1566 sched_belch("thread %d did a _ccall_gc (is_concurrent: %d)", cap->r.rCurrentTSO->id,concCall));
1568 threadPaused(cap->r.rCurrentTSO);
1569 cap->r.rCurrentTSO->link = suspended_ccalling_threads;
1570 suspended_ccalling_threads = cap->r.rCurrentTSO;
1572 #if defined(RTS_SUPPORTS_THREADS)
1573 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall;
1576 /* Use the thread ID as the token; it should be unique */
1577 tok = cap->r.rCurrentTSO->id;
1579 /* Hand back capability */
1580 releaseCapability(cap);
1582 #if defined(RTS_SUPPORTS_THREADS)
1583 /* Preparing to leave the RTS, so ensure there's a native thread/task
1584 waiting to take over.
1586 ToDo: optimise this and only create a new task if there's a need
1587 for one (i.e., if there's only one Concurrent Haskell thread alive,
1588 there's no need to create a new task).
1590 IF_DEBUG(scheduler, sched_belch("worker thread (%d): leaving RTS", tok));
1592 startTask(taskStart);
1596 /* Other threads _might_ be available for execution; signal this */
1598 RELEASE_LOCK(&sched_mutex);
1603 resumeThread( StgInt tok,
1605 #if !defined(RTS_SUPPORTS_THREADS)
1610 StgTSO *tso, **prev;
1613 #if defined(RTS_SUPPORTS_THREADS)
1614 /* Wait for permission to re-enter the RTS with the result. */
1616 ACQUIRE_LOCK(&sched_mutex);
1617 grabReturnCapability(&sched_mutex, &cap);
1619 grabCapability(&cap);
1622 grabCapability(&cap);
1625 /* Remove the thread off of the suspended list */
1626 prev = &suspended_ccalling_threads;
1627 for (tso = suspended_ccalling_threads;
1628 tso != END_TSO_QUEUE;
1629 prev = &tso->link, tso = tso->link) {
1630 if (tso->id == (StgThreadID)tok) {
1635 if (tso == END_TSO_QUEUE) {
1636 barf("resumeThread: thread not found");
1638 tso->link = END_TSO_QUEUE;
1639 /* Reset blocking status */
1640 tso->why_blocked = NotBlocked;
1642 cap->r.rCurrentTSO = tso;
1643 RELEASE_LOCK(&sched_mutex);
1648 /* ---------------------------------------------------------------------------
1650 * ------------------------------------------------------------------------ */
1651 static void unblockThread(StgTSO *tso);
1653 /* ---------------------------------------------------------------------------
1654 * Comparing Thread ids.
1656 * This is used from STG land in the implementation of the
1657 * instances of Eq/Ord for ThreadIds.
1658 * ------------------------------------------------------------------------ */
1660 int cmp_thread(const StgTSO *tso1, const StgTSO *tso2)
1662 StgThreadID id1 = tso1->id;
1663 StgThreadID id2 = tso2->id;
1665 if (id1 < id2) return (-1);
1666 if (id1 > id2) return 1;
1670 /* ---------------------------------------------------------------------------
1671 * Fetching the ThreadID from an StgTSO.
1673 * This is used in the implementation of Show for ThreadIds.
1674 * ------------------------------------------------------------------------ */
1675 int rts_getThreadId(const StgTSO *tso)
1681 void labelThread(StgTSO *tso, char *label)
1686 /* Caveat: Once set, you can only set the thread name to "" */
1687 len = strlen(label)+1;
1690 fprintf(stderr,"insufficient memory for labelThread!\n");
1692 strncpy(buf,label,len);
1693 /* Update will free the old memory for us */
1694 updateThreadLabel((StgWord)tso,buf);
1698 /* ---------------------------------------------------------------------------
1699 Create a new thread.
1701 The new thread starts with the given stack size. Before the
1702 scheduler can run, however, this thread needs to have a closure
1703 (and possibly some arguments) pushed on its stack. See
1704 pushClosure() in Schedule.h.
1706 createGenThread() and createIOThread() (in SchedAPI.h) are
1707 convenient packaged versions of this function.
1709 currently pri (priority) is only used in a GRAN setup -- HWL
1710 ------------------------------------------------------------------------ */
1711 //@cindex createThread
1713 /* currently pri (priority) is only used in a GRAN setup -- HWL */
1715 createThread(nat size, StgInt pri)
1718 createThread(nat size)
1725 /* First check whether we should create a thread at all */
1727 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1728 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1730 belch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1731 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1732 return END_TSO_QUEUE;
1738 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
1741 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
1743 /* catch ridiculously small stack sizes */
1744 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
1745 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
1748 stack_size = size - TSO_STRUCT_SIZEW;
1750 tso = (StgTSO *)allocate(size);
1751 TICK_ALLOC_TSO(stack_size, 0);
1753 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
1755 SET_GRAN_HDR(tso, ThisPE);
1757 tso->what_next = ThreadEnterGHC;
1759 /* tso->id needs to be unique. For now we use a heavyweight mutex to
1760 * protect the increment operation on next_thread_id.
1761 * In future, we could use an atomic increment instead.
1763 ACQUIRE_LOCK(&thread_id_mutex);
1764 tso->id = next_thread_id++;
1765 RELEASE_LOCK(&thread_id_mutex);
1767 tso->why_blocked = NotBlocked;
1768 tso->blocked_exceptions = NULL;
1770 tso->stack_size = stack_size;
1771 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
1773 tso->sp = (P_)&(tso->stack) + stack_size;
1776 tso->prof.CCCS = CCS_MAIN;
1779 /* put a stop frame on the stack */
1780 tso->sp -= sizeofW(StgStopFrame);
1781 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
1782 tso->su = (StgUpdateFrame*)tso->sp;
1786 tso->link = END_TSO_QUEUE;
1787 /* uses more flexible routine in GranSim */
1788 insertThread(tso, CurrentProc);
1790 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
1796 if (RtsFlags.GranFlags.GranSimStats.Full)
1797 DumpGranEvent(GR_START,tso);
1799 if (RtsFlags.ParFlags.ParStats.Full)
1800 DumpGranEvent(GR_STARTQ,tso);
1801 /* HACk to avoid SCHEDULE
1805 /* Link the new thread on the global thread list.
1807 tso->global_link = all_threads;
1811 tso->dist.priority = MandatoryPriority; //by default that is...
1815 tso->gran.pri = pri;
1817 tso->gran.magic = TSO_MAGIC; // debugging only
1819 tso->gran.sparkname = 0;
1820 tso->gran.startedat = CURRENT_TIME;
1821 tso->gran.exported = 0;
1822 tso->gran.basicblocks = 0;
1823 tso->gran.allocs = 0;
1824 tso->gran.exectime = 0;
1825 tso->gran.fetchtime = 0;
1826 tso->gran.fetchcount = 0;
1827 tso->gran.blocktime = 0;
1828 tso->gran.blockcount = 0;
1829 tso->gran.blockedat = 0;
1830 tso->gran.globalsparks = 0;
1831 tso->gran.localsparks = 0;
1832 if (RtsFlags.GranFlags.Light)
1833 tso->gran.clock = Now; /* local clock */
1835 tso->gran.clock = 0;
1837 IF_DEBUG(gran,printTSO(tso));
1840 tso->par.magic = TSO_MAGIC; // debugging only
1842 tso->par.sparkname = 0;
1843 tso->par.startedat = CURRENT_TIME;
1844 tso->par.exported = 0;
1845 tso->par.basicblocks = 0;
1846 tso->par.allocs = 0;
1847 tso->par.exectime = 0;
1848 tso->par.fetchtime = 0;
1849 tso->par.fetchcount = 0;
1850 tso->par.blocktime = 0;
1851 tso->par.blockcount = 0;
1852 tso->par.blockedat = 0;
1853 tso->par.globalsparks = 0;
1854 tso->par.localsparks = 0;
1858 globalGranStats.tot_threads_created++;
1859 globalGranStats.threads_created_on_PE[CurrentProc]++;
1860 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
1861 globalGranStats.tot_sq_probes++;
1863 // collect parallel global statistics (currently done together with GC stats)
1864 if (RtsFlags.ParFlags.ParStats.Global &&
1865 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1866 //fprintf(stderr, "Creating thread %d @ %11.2f\n", tso->id, usertime());
1867 globalParStats.tot_threads_created++;
1873 belch("==__ schedule: Created TSO %d (%p);",
1874 CurrentProc, tso, tso->id));
1876 IF_PAR_DEBUG(verbose,
1877 belch("==__ schedule: Created TSO %d (%p); %d threads active",
1878 tso->id, tso, advisory_thread_count));
1880 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
1881 tso->id, tso->stack_size));
1888 all parallel thread creation calls should fall through the following routine.
1891 createSparkThread(rtsSpark spark)
1893 ASSERT(spark != (rtsSpark)NULL);
1894 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
1896 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1897 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1898 return END_TSO_QUEUE;
1902 tso = createThread(RtsFlags.GcFlags.initialStkSize);
1903 if (tso==END_TSO_QUEUE)
1904 barf("createSparkThread: Cannot create TSO");
1906 tso->priority = AdvisoryPriority;
1908 pushClosure(tso,spark);
1909 PUSH_ON_RUN_QUEUE(tso);
1910 advisory_thread_count++;
1917 Turn a spark into a thread.
1918 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
1921 //@cindex activateSpark
1923 activateSpark (rtsSpark spark)
1927 tso = createSparkThread(spark);
1928 if (RtsFlags.ParFlags.ParStats.Full) {
1929 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
1930 IF_PAR_DEBUG(verbose,
1931 belch("==^^ activateSpark: turning spark of closure %p (%s) into a thread",
1932 (StgClosure *)spark, info_type((StgClosure *)spark)));
1934 // ToDo: fwd info on local/global spark to thread -- HWL
1935 // tso->gran.exported = spark->exported;
1936 // tso->gran.locked = !spark->global;
1937 // tso->gran.sparkname = spark->name;
1943 static SchedulerStatus waitThread_(/*out*/StgMainThread* m
1944 #if defined(THREADED_RTS)
1945 , rtsBool blockWaiting
1950 /* ---------------------------------------------------------------------------
1953 * scheduleThread puts a thread on the head of the runnable queue.
1954 * This will usually be done immediately after a thread is created.
1955 * The caller of scheduleThread must create the thread using e.g.
1956 * createThread and push an appropriate closure
1957 * on this thread's stack before the scheduler is invoked.
1958 * ------------------------------------------------------------------------ */
1960 static void scheduleThread_ (StgTSO* tso, rtsBool createTask);
1963 scheduleThread_(StgTSO *tso
1964 , rtsBool createTask
1965 #if !defined(THREADED_RTS)
1970 ACQUIRE_LOCK(&sched_mutex);
1972 /* Put the new thread on the head of the runnable queue. The caller
1973 * better push an appropriate closure on this thread's stack
1974 * beforehand. In the SMP case, the thread may start running as
1975 * soon as we release the scheduler lock below.
1977 PUSH_ON_RUN_QUEUE(tso);
1978 #if defined(THREADED_RTS)
1979 /* If main() is scheduling a thread, don't bother creating a
1983 startTask(taskStart);
1989 IF_DEBUG(scheduler,printTSO(tso));
1991 RELEASE_LOCK(&sched_mutex);
1994 void scheduleThread(StgTSO* tso)
1996 scheduleThread_(tso, rtsFalse);
2000 scheduleWaitThread(StgTSO* tso, /*[out]*/HaskellObj* ret)
2004 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2008 #if defined(RTS_SUPPORTS_THREADS)
2009 initCondition(&m->wakeup);
2012 /* Put the thread on the main-threads list prior to scheduling the TSO.
2013 Failure to do so introduces a race condition in the MT case (as
2014 identified by Wolfgang Thaller), whereby the new task/OS thread
2015 created by scheduleThread_() would complete prior to the thread
2016 that spawned it managed to put 'itself' on the main-threads list.
2017 The upshot of it all being that the worker thread wouldn't get to
2018 signal the completion of the its work item for the main thread to
2019 see (==> it got stuck waiting.) -- sof 6/02.
2021 ACQUIRE_LOCK(&sched_mutex);
2022 IF_DEBUG(scheduler, sched_belch("== scheduler: waiting for thread (%d)\n", tso->id));
2024 m->link = main_threads;
2027 /* Inefficient (scheduleThread_() acquires it again right away),
2028 * but obviously correct.
2030 RELEASE_LOCK(&sched_mutex);
2032 scheduleThread_(tso, rtsTrue);
2033 #if defined(THREADED_RTS)
2034 return waitThread_(m, rtsTrue);
2036 return waitThread_(m);
2040 /* ---------------------------------------------------------------------------
2043 * Initialise the scheduler. This resets all the queues - if the
2044 * queues contained any threads, they'll be garbage collected at the
2047 * ------------------------------------------------------------------------ */
2051 term_handler(int sig STG_UNUSED)
2054 ACQUIRE_LOCK(&term_mutex);
2056 RELEASE_LOCK(&term_mutex);
2067 for (i=0; i<=MAX_PROC; i++) {
2068 run_queue_hds[i] = END_TSO_QUEUE;
2069 run_queue_tls[i] = END_TSO_QUEUE;
2070 blocked_queue_hds[i] = END_TSO_QUEUE;
2071 blocked_queue_tls[i] = END_TSO_QUEUE;
2072 ccalling_threadss[i] = END_TSO_QUEUE;
2073 sleeping_queue = END_TSO_QUEUE;
2076 run_queue_hd = END_TSO_QUEUE;
2077 run_queue_tl = END_TSO_QUEUE;
2078 blocked_queue_hd = END_TSO_QUEUE;
2079 blocked_queue_tl = END_TSO_QUEUE;
2080 sleeping_queue = END_TSO_QUEUE;
2083 suspended_ccalling_threads = END_TSO_QUEUE;
2085 main_threads = NULL;
2086 all_threads = END_TSO_QUEUE;
2091 RtsFlags.ConcFlags.ctxtSwitchTicks =
2092 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
2094 #if defined(RTS_SUPPORTS_THREADS)
2095 /* Initialise the mutex and condition variables used by
2097 initMutex(&sched_mutex);
2098 initMutex(&term_mutex);
2099 initMutex(&thread_id_mutex);
2101 initCondition(&thread_ready_cond);
2105 initCondition(&gc_pending_cond);
2108 #if defined(RTS_SUPPORTS_THREADS)
2109 ACQUIRE_LOCK(&sched_mutex);
2112 /* Install the SIGHUP handler */
2115 struct sigaction action,oact;
2117 action.sa_handler = term_handler;
2118 sigemptyset(&action.sa_mask);
2119 action.sa_flags = 0;
2120 if (sigaction(SIGTERM, &action, &oact) != 0) {
2121 barf("can't install TERM handler");
2126 /* A capability holds the state a native thread needs in
2127 * order to execute STG code. At least one capability is
2128 * floating around (only SMP builds have more than one).
2132 #if defined(RTS_SUPPORTS_THREADS)
2133 /* start our haskell execution tasks */
2135 startTaskManager(RtsFlags.ParFlags.nNodes, taskStart);
2137 startTaskManager(0,taskStart);
2141 #if /* defined(SMP) ||*/ defined(PAR)
2145 #if defined(RTS_SUPPORTS_THREADS)
2146 RELEASE_LOCK(&sched_mutex);
2152 exitScheduler( void )
2154 #if defined(RTS_SUPPORTS_THREADS)
2157 shutting_down_scheduler = rtsTrue;
2160 /* -----------------------------------------------------------------------------
2161 Managing the per-task allocation areas.
2163 Each capability comes with an allocation area. These are
2164 fixed-length block lists into which allocation can be done.
2166 ToDo: no support for two-space collection at the moment???
2167 -------------------------------------------------------------------------- */
2169 /* -----------------------------------------------------------------------------
2170 * waitThread is the external interface for running a new computation
2171 * and waiting for the result.
2173 * In the non-SMP case, we create a new main thread, push it on the
2174 * main-thread stack, and invoke the scheduler to run it. The
2175 * scheduler will return when the top main thread on the stack has
2176 * completed or died, and fill in the necessary fields of the
2177 * main_thread structure.
2179 * In the SMP case, we create a main thread as before, but we then
2180 * create a new condition variable and sleep on it. When our new
2181 * main thread has completed, we'll be woken up and the status/result
2182 * will be in the main_thread struct.
2183 * -------------------------------------------------------------------------- */
2186 howManyThreadsAvail ( void )
2190 for (q = run_queue_hd; q != END_TSO_QUEUE; q = q->link)
2192 for (q = blocked_queue_hd; q != END_TSO_QUEUE; q = q->link)
2194 for (q = sleeping_queue; q != END_TSO_QUEUE; q = q->link)
2200 finishAllThreads ( void )
2203 while (run_queue_hd != END_TSO_QUEUE) {
2204 waitThread ( run_queue_hd, NULL);
2206 while (blocked_queue_hd != END_TSO_QUEUE) {
2207 waitThread ( blocked_queue_hd, NULL);
2209 while (sleeping_queue != END_TSO_QUEUE) {
2210 waitThread ( blocked_queue_hd, NULL);
2213 (blocked_queue_hd != END_TSO_QUEUE ||
2214 run_queue_hd != END_TSO_QUEUE ||
2215 sleeping_queue != END_TSO_QUEUE);
2219 waitThread(StgTSO *tso, /*out*/StgClosure **ret)
2223 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2227 #if defined(RTS_SUPPORTS_THREADS)
2228 initCondition(&m->wakeup);
2231 /* see scheduleWaitThread() comment */
2232 ACQUIRE_LOCK(&sched_mutex);
2233 IF_DEBUG(scheduler, sched_belch("== scheduler: waiting for thread (%d)\n", tso->id));
2234 m->link = main_threads;
2236 RELEASE_LOCK(&sched_mutex);
2238 IF_DEBUG(scheduler, sched_belch("== scheduler: waiting for thread (%d)\n", tso->id));
2239 #if defined(THREADED_RTS)
2240 return waitThread_(m, rtsFalse);
2242 return waitThread_(m);
2248 waitThread_(StgMainThread* m
2249 #if defined(THREADED_RTS)
2250 , rtsBool blockWaiting
2254 SchedulerStatus stat;
2256 IF_DEBUG(scheduler, sched_belch("== scheduler: new main thread (%d)\n", m->tso->id));
2258 #if defined(RTS_SUPPORTS_THREADS)
2260 # if defined(THREADED_RTS)
2261 if (!blockWaiting) {
2262 /* In the threaded case, the OS thread that called main()
2263 * gets to enter the RTS directly without going via another
2267 ASSERT(m->stat != NoStatus);
2271 ACQUIRE_LOCK(&sched_mutex);
2273 waitCondition(&m->wakeup, &sched_mutex);
2274 } while (m->stat == NoStatus);
2277 /* GranSim specific init */
2278 CurrentTSO = m->tso; // the TSO to run
2279 procStatus[MainProc] = Busy; // status of main PE
2280 CurrentProc = MainProc; // PE to run it on
2284 RELEASE_LOCK(&sched_mutex);
2286 ASSERT(m->stat != NoStatus);
2291 #if defined(RTS_SUPPORTS_THREADS)
2292 closeCondition(&m->wakeup);
2295 IF_DEBUG(scheduler, fprintf(stderr, "== scheduler: main thread (%d) finished\n",
2299 #if defined(THREADED_RTS)
2302 RELEASE_LOCK(&sched_mutex);
2307 //@node Run queue code, Garbage Collextion Routines, Suspend and Resume, Main scheduling code
2308 //@subsection Run queue code
2312 NB: In GranSim we have many run queues; run_queue_hd is actually a macro
2313 unfolding to run_queue_hds[CurrentProc], thus CurrentProc is an
2314 implicit global variable that has to be correct when calling these
2318 /* Put the new thread on the head of the runnable queue.
2319 * The caller of createThread better push an appropriate closure
2320 * on this thread's stack before the scheduler is invoked.
2322 static /* inline */ void
2323 add_to_run_queue(tso)
2326 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2327 tso->link = run_queue_hd;
2329 if (run_queue_tl == END_TSO_QUEUE) {
2334 /* Put the new thread at the end of the runnable queue. */
2335 static /* inline */ void
2336 push_on_run_queue(tso)
2339 ASSERT(get_itbl((StgClosure *)tso)->type == TSO);
2340 ASSERT(run_queue_hd!=NULL && run_queue_tl!=NULL);
2341 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2342 if (run_queue_hd == END_TSO_QUEUE) {
2345 run_queue_tl->link = tso;
2351 Should be inlined because it's used very often in schedule. The tso
2352 argument is actually only needed in GranSim, where we want to have the
2353 possibility to schedule *any* TSO on the run queue, irrespective of the
2354 actual ordering. Therefore, if tso is not the nil TSO then we traverse
2355 the run queue and dequeue the tso, adjusting the links in the queue.
2357 //@cindex take_off_run_queue
2358 static /* inline */ StgTSO*
2359 take_off_run_queue(StgTSO *tso) {
2363 qetlaHbogh Qu' ngaSbogh ghomDaQ {tso} yIteq!
2365 if tso is specified, unlink that tso from the run_queue (doesn't have
2366 to be at the beginning of the queue); GranSim only
2368 if (tso!=END_TSO_QUEUE) {
2369 /* find tso in queue */
2370 for (t=run_queue_hd, prev=END_TSO_QUEUE;
2371 t!=END_TSO_QUEUE && t!=tso;
2375 /* now actually dequeue the tso */
2376 if (prev!=END_TSO_QUEUE) {
2377 ASSERT(run_queue_hd!=t);
2378 prev->link = t->link;
2380 /* t is at beginning of thread queue */
2381 ASSERT(run_queue_hd==t);
2382 run_queue_hd = t->link;
2384 /* t is at end of thread queue */
2385 if (t->link==END_TSO_QUEUE) {
2386 ASSERT(t==run_queue_tl);
2387 run_queue_tl = prev;
2389 ASSERT(run_queue_tl!=t);
2391 t->link = END_TSO_QUEUE;
2393 /* take tso from the beginning of the queue; std concurrent code */
2395 if (t != END_TSO_QUEUE) {
2396 run_queue_hd = t->link;
2397 t->link = END_TSO_QUEUE;
2398 if (run_queue_hd == END_TSO_QUEUE) {
2399 run_queue_tl = END_TSO_QUEUE;
2408 //@node Garbage Collextion Routines, Blocking Queue Routines, Run queue code, Main scheduling code
2409 //@subsection Garbage Collextion Routines
2411 /* ---------------------------------------------------------------------------
2412 Where are the roots that we know about?
2414 - all the threads on the runnable queue
2415 - all the threads on the blocked queue
2416 - all the threads on the sleeping queue
2417 - all the thread currently executing a _ccall_GC
2418 - all the "main threads"
2420 ------------------------------------------------------------------------ */
2422 /* This has to be protected either by the scheduler monitor, or by the
2423 garbage collection monitor (probably the latter).
2428 GetRoots(evac_fn evac)
2433 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2434 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2435 evac((StgClosure **)&run_queue_hds[i]);
2436 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2437 evac((StgClosure **)&run_queue_tls[i]);
2439 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2440 evac((StgClosure **)&blocked_queue_hds[i]);
2441 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2442 evac((StgClosure **)&blocked_queue_tls[i]);
2443 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2444 evac((StgClosure **)&ccalling_threads[i]);
2451 if (run_queue_hd != END_TSO_QUEUE) {
2452 ASSERT(run_queue_tl != END_TSO_QUEUE);
2453 evac((StgClosure **)&run_queue_hd);
2454 evac((StgClosure **)&run_queue_tl);
2457 if (blocked_queue_hd != END_TSO_QUEUE) {
2458 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2459 evac((StgClosure **)&blocked_queue_hd);
2460 evac((StgClosure **)&blocked_queue_tl);
2463 if (sleeping_queue != END_TSO_QUEUE) {
2464 evac((StgClosure **)&sleeping_queue);
2468 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2469 evac((StgClosure **)&suspended_ccalling_threads);
2472 #if defined(PAR) || defined(GRAN)
2473 markSparkQueue(evac);
2477 /* -----------------------------------------------------------------------------
2480 This is the interface to the garbage collector from Haskell land.
2481 We provide this so that external C code can allocate and garbage
2482 collect when called from Haskell via _ccall_GC.
2484 It might be useful to provide an interface whereby the programmer
2485 can specify more roots (ToDo).
2487 This needs to be protected by the GC condition variable above. KH.
2488 -------------------------------------------------------------------------- */
2490 static void (*extra_roots)(evac_fn);
2495 /* Obligated to hold this lock upon entry */
2496 ACQUIRE_LOCK(&sched_mutex);
2497 GarbageCollect(GetRoots,rtsFalse);
2498 RELEASE_LOCK(&sched_mutex);
2502 performMajorGC(void)
2504 ACQUIRE_LOCK(&sched_mutex);
2505 GarbageCollect(GetRoots,rtsTrue);
2506 RELEASE_LOCK(&sched_mutex);
2510 AllRoots(evac_fn evac)
2512 GetRoots(evac); // the scheduler's roots
2513 extra_roots(evac); // the user's roots
2517 performGCWithRoots(void (*get_roots)(evac_fn))
2519 ACQUIRE_LOCK(&sched_mutex);
2520 extra_roots = get_roots;
2521 GarbageCollect(AllRoots,rtsFalse);
2522 RELEASE_LOCK(&sched_mutex);
2525 /* -----------------------------------------------------------------------------
2528 If the thread has reached its maximum stack size, then raise the
2529 StackOverflow exception in the offending thread. Otherwise
2530 relocate the TSO into a larger chunk of memory and adjust its stack
2532 -------------------------------------------------------------------------- */
2535 threadStackOverflow(StgTSO *tso)
2537 nat new_stack_size, new_tso_size, diff, stack_words;
2541 IF_DEBUG(sanity,checkTSO(tso));
2542 if (tso->stack_size >= tso->max_stack_size) {
2545 belch("@@ threadStackOverflow of TSO %d (%p): stack too large (now %ld; max is %ld",
2546 tso->id, tso, tso->stack_size, tso->max_stack_size);
2547 /* If we're debugging, just print out the top of the stack */
2548 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2551 /* Send this thread the StackOverflow exception */
2552 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2556 /* Try to double the current stack size. If that takes us over the
2557 * maximum stack size for this thread, then use the maximum instead.
2558 * Finally round up so the TSO ends up as a whole number of blocks.
2560 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2561 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2562 TSO_STRUCT_SIZE)/sizeof(W_);
2563 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2564 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2566 IF_DEBUG(scheduler, fprintf(stderr,"== scheduler: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2568 dest = (StgTSO *)allocate(new_tso_size);
2569 TICK_ALLOC_TSO(new_stack_size,0);
2571 /* copy the TSO block and the old stack into the new area */
2572 memcpy(dest,tso,TSO_STRUCT_SIZE);
2573 stack_words = tso->stack + tso->stack_size - tso->sp;
2574 new_sp = (P_)dest + new_tso_size - stack_words;
2575 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2577 /* relocate the stack pointers... */
2578 diff = (P_)new_sp - (P_)tso->sp; /* In *words* */
2579 dest->su = (StgUpdateFrame *) ((P_)dest->su + diff);
2581 dest->stack_size = new_stack_size;
2583 /* and relocate the update frame list */
2584 relocate_stack(dest, diff);
2586 /* Mark the old TSO as relocated. We have to check for relocated
2587 * TSOs in the garbage collector and any primops that deal with TSOs.
2589 * It's important to set the sp and su values to just beyond the end
2590 * of the stack, so we don't attempt to scavenge any part of the
2593 tso->what_next = ThreadRelocated;
2595 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2596 tso->su = (StgUpdateFrame *)tso->sp;
2597 tso->why_blocked = NotBlocked;
2598 dest->mut_link = NULL;
2600 IF_PAR_DEBUG(verbose,
2601 belch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld",
2602 tso->id, tso, tso->stack_size);
2603 /* If we're debugging, just print out the top of the stack */
2604 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2607 IF_DEBUG(sanity,checkTSO(tso));
2609 IF_DEBUG(scheduler,printTSO(dest));
2615 //@node Blocking Queue Routines, Exception Handling Routines, Garbage Collextion Routines, Main scheduling code
2616 //@subsection Blocking Queue Routines
2618 /* ---------------------------------------------------------------------------
2619 Wake up a queue that was blocked on some resource.
2620 ------------------------------------------------------------------------ */
2624 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2629 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2631 /* write RESUME events to log file and
2632 update blocked and fetch time (depending on type of the orig closure) */
2633 if (RtsFlags.ParFlags.ParStats.Full) {
2634 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2635 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2636 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2637 if (EMPTY_RUN_QUEUE())
2638 emitSchedule = rtsTrue;
2640 switch (get_itbl(node)->type) {
2642 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2647 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2654 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2661 static StgBlockingQueueElement *
2662 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2665 PEs node_loc, tso_loc;
2667 node_loc = where_is(node); // should be lifted out of loop
2668 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2669 tso_loc = where_is((StgClosure *)tso);
2670 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2671 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2672 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2673 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2674 // insertThread(tso, node_loc);
2675 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2677 tso, node, (rtsSpark*)NULL);
2678 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2681 } else { // TSO is remote (actually should be FMBQ)
2682 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2683 RtsFlags.GranFlags.Costs.gunblocktime +
2684 RtsFlags.GranFlags.Costs.latency;
2685 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2687 tso, node, (rtsSpark*)NULL);
2688 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2691 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2693 fprintf(stderr," %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2694 (node_loc==tso_loc ? "Local" : "Global"),
2695 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2696 tso->block_info.closure = NULL;
2697 IF_DEBUG(scheduler,belch("-- Waking up thread %ld (%p)",
2701 static StgBlockingQueueElement *
2702 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2704 StgBlockingQueueElement *next;
2706 switch (get_itbl(bqe)->type) {
2708 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2709 /* if it's a TSO just push it onto the run_queue */
2711 // ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2712 PUSH_ON_RUN_QUEUE((StgTSO *)bqe);
2714 unblockCount(bqe, node);
2715 /* reset blocking status after dumping event */
2716 ((StgTSO *)bqe)->why_blocked = NotBlocked;
2720 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2722 bqe->link = (StgBlockingQueueElement *)PendingFetches;
2723 PendingFetches = (StgBlockedFetch *)bqe;
2727 /* can ignore this case in a non-debugging setup;
2728 see comments on RBHSave closures above */
2730 /* check that the closure is an RBHSave closure */
2731 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2732 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2733 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2737 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2738 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
2742 IF_PAR_DEBUG(bq, fprintf(stderr, ", %p (%s)", bqe, info_type((StgClosure*)bqe)));
2746 #else /* !GRAN && !PAR */
2748 unblockOneLocked(StgTSO *tso)
2752 ASSERT(get_itbl(tso)->type == TSO);
2753 ASSERT(tso->why_blocked != NotBlocked);
2754 tso->why_blocked = NotBlocked;
2756 PUSH_ON_RUN_QUEUE(tso);
2758 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
2763 #if defined(GRAN) || defined(PAR)
2764 inline StgBlockingQueueElement *
2765 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2767 ACQUIRE_LOCK(&sched_mutex);
2768 bqe = unblockOneLocked(bqe, node);
2769 RELEASE_LOCK(&sched_mutex);
2774 unblockOne(StgTSO *tso)
2776 ACQUIRE_LOCK(&sched_mutex);
2777 tso = unblockOneLocked(tso);
2778 RELEASE_LOCK(&sched_mutex);
2785 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2787 StgBlockingQueueElement *bqe;
2792 belch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): ", \
2793 node, CurrentProc, CurrentTime[CurrentProc],
2794 CurrentTSO->id, CurrentTSO));
2796 node_loc = where_is(node);
2798 ASSERT(q == END_BQ_QUEUE ||
2799 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
2800 get_itbl(q)->type == CONSTR); // closure (type constructor)
2801 ASSERT(is_unique(node));
2803 /* FAKE FETCH: magically copy the node to the tso's proc;
2804 no Fetch necessary because in reality the node should not have been
2805 moved to the other PE in the first place
2807 if (CurrentProc!=node_loc) {
2809 belch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)",
2810 node, node_loc, CurrentProc, CurrentTSO->id,
2811 // CurrentTSO, where_is(CurrentTSO),
2812 node->header.gran.procs));
2813 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
2815 belch("## new bitmask of node %p is %#x",
2816 node, node->header.gran.procs));
2817 if (RtsFlags.GranFlags.GranSimStats.Global) {
2818 globalGranStats.tot_fake_fetches++;
2823 // ToDo: check: ASSERT(CurrentProc==node_loc);
2824 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
2827 bqe points to the current element in the queue
2828 next points to the next element in the queue
2830 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2831 //tso_loc = where_is(tso);
2833 bqe = unblockOneLocked(bqe, node);
2836 /* if this is the BQ of an RBH, we have to put back the info ripped out of
2837 the closure to make room for the anchor of the BQ */
2838 if (bqe!=END_BQ_QUEUE) {
2839 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
2841 ASSERT((info_ptr==&RBH_Save_0_info) ||
2842 (info_ptr==&RBH_Save_1_info) ||
2843 (info_ptr==&RBH_Save_2_info));
2845 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
2846 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
2847 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
2850 belch("## Filled in RBH_Save for %p (%s) at end of AwBQ",
2851 node, info_type(node)));
2854 /* statistics gathering */
2855 if (RtsFlags.GranFlags.GranSimStats.Global) {
2856 // globalGranStats.tot_bq_processing_time += bq_processing_time;
2857 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
2858 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
2859 globalGranStats.tot_awbq++; // total no. of bqs awakened
2862 fprintf(stderr,"## BQ Stats of %p: [%d entries] %s\n",
2863 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
2867 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2869 StgBlockingQueueElement *bqe;
2871 ACQUIRE_LOCK(&sched_mutex);
2873 IF_PAR_DEBUG(verbose,
2874 belch("##-_ AwBQ for node %p on [%x]: ",
2878 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
2879 IF_PAR_DEBUG(verbose, belch("## ... nothing to unblock so lets just return. RFP (BUG?)"));
2884 ASSERT(q == END_BQ_QUEUE ||
2885 get_itbl(q)->type == TSO ||
2886 get_itbl(q)->type == BLOCKED_FETCH ||
2887 get_itbl(q)->type == CONSTR);
2890 while (get_itbl(bqe)->type==TSO ||
2891 get_itbl(bqe)->type==BLOCKED_FETCH) {
2892 bqe = unblockOneLocked(bqe, node);
2894 RELEASE_LOCK(&sched_mutex);
2897 #else /* !GRAN && !PAR */
2899 awakenBlockedQueue(StgTSO *tso)
2901 ACQUIRE_LOCK(&sched_mutex);
2902 while (tso != END_TSO_QUEUE) {
2903 tso = unblockOneLocked(tso);
2905 RELEASE_LOCK(&sched_mutex);
2909 //@node Exception Handling Routines, Debugging Routines, Blocking Queue Routines, Main scheduling code
2910 //@subsection Exception Handling Routines
2912 /* ---------------------------------------------------------------------------
2914 - usually called inside a signal handler so it mustn't do anything fancy.
2915 ------------------------------------------------------------------------ */
2918 interruptStgRts(void)
2924 /* -----------------------------------------------------------------------------
2927 This is for use when we raise an exception in another thread, which
2929 This has nothing to do with the UnblockThread event in GranSim. -- HWL
2930 -------------------------------------------------------------------------- */
2932 #if defined(GRAN) || defined(PAR)
2934 NB: only the type of the blocking queue is different in GranSim and GUM
2935 the operations on the queue-elements are the same
2936 long live polymorphism!
2938 Locks: sched_mutex is held upon entry and exit.
2942 unblockThread(StgTSO *tso)
2944 StgBlockingQueueElement *t, **last;
2946 switch (tso->why_blocked) {
2949 return; /* not blocked */
2952 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2954 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
2955 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2957 last = (StgBlockingQueueElement **)&mvar->head;
2958 for (t = (StgBlockingQueueElement *)mvar->head;
2960 last = &t->link, last_tso = t, t = t->link) {
2961 if (t == (StgBlockingQueueElement *)tso) {
2962 *last = (StgBlockingQueueElement *)tso->link;
2963 if (mvar->tail == tso) {
2964 mvar->tail = (StgTSO *)last_tso;
2969 barf("unblockThread (MVAR): TSO not found");
2972 case BlockedOnBlackHole:
2973 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2975 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2977 last = &bq->blocking_queue;
2978 for (t = bq->blocking_queue;
2980 last = &t->link, t = t->link) {
2981 if (t == (StgBlockingQueueElement *)tso) {
2982 *last = (StgBlockingQueueElement *)tso->link;
2986 barf("unblockThread (BLACKHOLE): TSO not found");
2989 case BlockedOnException:
2991 StgTSO *target = tso->block_info.tso;
2993 ASSERT(get_itbl(target)->type == TSO);
2995 if (target->what_next == ThreadRelocated) {
2996 target = target->link;
2997 ASSERT(get_itbl(target)->type == TSO);
3000 ASSERT(target->blocked_exceptions != NULL);
3002 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
3003 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
3005 last = &t->link, t = t->link) {
3006 ASSERT(get_itbl(t)->type == TSO);
3007 if (t == (StgBlockingQueueElement *)tso) {
3008 *last = (StgBlockingQueueElement *)tso->link;
3012 barf("unblockThread (Exception): TSO not found");
3016 case BlockedOnWrite:
3018 /* take TSO off blocked_queue */
3019 StgBlockingQueueElement *prev = NULL;
3020 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
3021 prev = t, t = t->link) {
3022 if (t == (StgBlockingQueueElement *)tso) {
3024 blocked_queue_hd = (StgTSO *)t->link;
3025 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3026 blocked_queue_tl = END_TSO_QUEUE;
3029 prev->link = t->link;
3030 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3031 blocked_queue_tl = (StgTSO *)prev;
3037 barf("unblockThread (I/O): TSO not found");
3040 case BlockedOnDelay:
3042 /* take TSO off sleeping_queue */
3043 StgBlockingQueueElement *prev = NULL;
3044 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
3045 prev = t, t = t->link) {
3046 if (t == (StgBlockingQueueElement *)tso) {
3048 sleeping_queue = (StgTSO *)t->link;
3050 prev->link = t->link;
3055 barf("unblockThread (I/O): TSO not found");
3059 barf("unblockThread");
3063 tso->link = END_TSO_QUEUE;
3064 tso->why_blocked = NotBlocked;
3065 tso->block_info.closure = NULL;
3066 PUSH_ON_RUN_QUEUE(tso);
3070 unblockThread(StgTSO *tso)
3074 /* To avoid locking unnecessarily. */
3075 if (tso->why_blocked == NotBlocked) {
3079 switch (tso->why_blocked) {
3082 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3084 StgTSO *last_tso = END_TSO_QUEUE;
3085 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3088 for (t = mvar->head; t != END_TSO_QUEUE;
3089 last = &t->link, last_tso = t, t = t->link) {
3092 if (mvar->tail == tso) {
3093 mvar->tail = last_tso;
3098 barf("unblockThread (MVAR): TSO not found");
3101 case BlockedOnBlackHole:
3102 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3104 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3106 last = &bq->blocking_queue;
3107 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
3108 last = &t->link, t = t->link) {
3114 barf("unblockThread (BLACKHOLE): TSO not found");
3117 case BlockedOnException:
3119 StgTSO *target = tso->block_info.tso;
3121 ASSERT(get_itbl(target)->type == TSO);
3123 while (target->what_next == ThreadRelocated) {
3124 target = target->link;
3125 ASSERT(get_itbl(target)->type == TSO);
3128 ASSERT(target->blocked_exceptions != NULL);
3130 last = &target->blocked_exceptions;
3131 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
3132 last = &t->link, t = t->link) {
3133 ASSERT(get_itbl(t)->type == TSO);
3139 barf("unblockThread (Exception): TSO not found");
3143 case BlockedOnWrite:
3145 StgTSO *prev = NULL;
3146 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
3147 prev = t, t = t->link) {
3150 blocked_queue_hd = t->link;
3151 if (blocked_queue_tl == t) {
3152 blocked_queue_tl = END_TSO_QUEUE;
3155 prev->link = t->link;
3156 if (blocked_queue_tl == t) {
3157 blocked_queue_tl = prev;
3163 barf("unblockThread (I/O): TSO not found");
3166 case BlockedOnDelay:
3168 StgTSO *prev = NULL;
3169 for (t = sleeping_queue; t != END_TSO_QUEUE;
3170 prev = t, t = t->link) {
3173 sleeping_queue = t->link;
3175 prev->link = t->link;
3180 barf("unblockThread (I/O): TSO not found");
3184 barf("unblockThread");
3188 tso->link = END_TSO_QUEUE;
3189 tso->why_blocked = NotBlocked;
3190 tso->block_info.closure = NULL;
3191 PUSH_ON_RUN_QUEUE(tso);
3195 /* -----------------------------------------------------------------------------
3198 * The following function implements the magic for raising an
3199 * asynchronous exception in an existing thread.
3201 * We first remove the thread from any queue on which it might be
3202 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
3204 * We strip the stack down to the innermost CATCH_FRAME, building
3205 * thunks in the heap for all the active computations, so they can
3206 * be restarted if necessary. When we reach a CATCH_FRAME, we build
3207 * an application of the handler to the exception, and push it on
3208 * the top of the stack.
3210 * How exactly do we save all the active computations? We create an
3211 * AP_UPD for every UpdateFrame on the stack. Entering one of these
3212 * AP_UPDs pushes everything from the corresponding update frame
3213 * upwards onto the stack. (Actually, it pushes everything up to the
3214 * next update frame plus a pointer to the next AP_UPD object.
3215 * Entering the next AP_UPD object pushes more onto the stack until we
3216 * reach the last AP_UPD object - at which point the stack should look
3217 * exactly as it did when we killed the TSO and we can continue
3218 * execution by entering the closure on top of the stack.
3220 * We can also kill a thread entirely - this happens if either (a) the
3221 * exception passed to raiseAsync is NULL, or (b) there's no
3222 * CATCH_FRAME on the stack. In either case, we strip the entire
3223 * stack and replace the thread with a zombie.
3225 * Locks: sched_mutex held upon entry nor exit.
3227 * -------------------------------------------------------------------------- */
3230 deleteThread(StgTSO *tso)
3232 raiseAsync(tso,NULL);
3236 raiseAsyncWithLock(StgTSO *tso, StgClosure *exception)
3238 /* When raising async exs from contexts where sched_mutex isn't held;
3239 use raiseAsyncWithLock(). */
3240 ACQUIRE_LOCK(&sched_mutex);
3241 raiseAsync(tso,exception);
3242 RELEASE_LOCK(&sched_mutex);
3246 raiseAsync(StgTSO *tso, StgClosure *exception)
3248 StgUpdateFrame* su = tso->su;
3249 StgPtr sp = tso->sp;
3251 /* Thread already dead? */
3252 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3256 IF_DEBUG(scheduler, sched_belch("raising exception in thread %ld.", tso->id));
3258 /* Remove it from any blocking queues */
3261 /* The stack freezing code assumes there's a closure pointer on
3262 * the top of the stack. This isn't always the case with compiled
3263 * code, so we have to push a dummy closure on the top which just
3264 * returns to the next return address on the stack.
3266 if ( LOOKS_LIKE_GHC_INFO((void*)*sp) ) {
3267 *(--sp) = (W_)&stg_dummy_ret_closure;
3271 nat words = ((P_)su - (P_)sp) - 1;
3275 ASSERT((P_)su > (P_)sp);
3277 /* If we find a CATCH_FRAME, and we've got an exception to raise,
3278 * then build the THUNK raise(exception), and leave it on
3279 * top of the CATCH_FRAME ready to enter.
3281 if (get_itbl(su)->type == CATCH_FRAME && exception != NULL) {
3283 StgCatchFrame *cf = (StgCatchFrame *)su;
3287 /* we've got an exception to raise, so let's pass it to the
3288 * handler in this frame.
3290 raise = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3291 TICK_ALLOC_SE_THK(1,0);
3292 SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
3293 raise->payload[0] = exception;
3295 /* throw away the stack from Sp up to the CATCH_FRAME.
3299 /* Ensure that async excpetions are blocked now, so we don't get
3300 * a surprise exception before we get around to executing the
3303 if (tso->blocked_exceptions == NULL) {
3304 tso->blocked_exceptions = END_TSO_QUEUE;
3307 /* Put the newly-built THUNK on top of the stack, ready to execute
3308 * when the thread restarts.
3313 tso->what_next = ThreadEnterGHC;
3314 IF_DEBUG(sanity, checkTSO(tso));
3318 /* First build an AP_UPD consisting of the stack chunk above the
3319 * current update frame, with the top word on the stack as the
3322 ap = (StgAP_UPD *)allocate(AP_sizeW(words));
3325 ap->fun = (StgClosure *)sp[0];
3327 for(i=0; i < (nat)words; ++i) {
3328 ap->payload[i] = (StgClosure *)*sp++;
3331 switch (get_itbl(su)->type) {
3335 SET_HDR(ap,&stg_AP_UPD_info,su->header.prof.ccs /* ToDo */);
3336 TICK_ALLOC_UP_THK(words+1,0);
3339 fprintf(stderr, "scheduler: Updating ");
3340 printPtr((P_)su->updatee);
3341 fprintf(stderr, " with ");
3342 printObj((StgClosure *)ap);
3345 /* Replace the updatee with an indirection - happily
3346 * this will also wake up any threads currently
3347 * waiting on the result.
3349 * Warning: if we're in a loop, more than one update frame on
3350 * the stack may point to the same object. Be careful not to
3351 * overwrite an IND_OLDGEN in this case, because we'll screw
3352 * up the mutable lists. To be on the safe side, don't
3353 * overwrite any kind of indirection at all. See also
3354 * threadSqueezeStack in GC.c, where we have to make a similar
3357 if (!closure_IND(su->updatee)) {
3358 UPD_IND_NOLOCK(su->updatee,ap); /* revert the black hole */
3361 sp += sizeofW(StgUpdateFrame) -1;
3362 sp[0] = (W_)ap; /* push onto stack */
3368 StgCatchFrame *cf = (StgCatchFrame *)su;
3371 /* We want a PAP, not an AP_UPD. Fortunately, the
3372 * layout's the same.
3374 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3375 TICK_ALLOC_UPD_PAP(words+1,0);
3377 /* now build o = FUN(catch,ap,handler) */
3378 o = (StgClosure *)allocate(sizeofW(StgClosure)+2);
3379 TICK_ALLOC_FUN(2,0);
3380 SET_HDR(o,&stg_catch_info,su->header.prof.ccs /* ToDo */);
3381 o->payload[0] = (StgClosure *)ap;
3382 o->payload[1] = cf->handler;
3385 fprintf(stderr, "scheduler: Built ");
3386 printObj((StgClosure *)o);
3389 /* pop the old handler and put o on the stack */
3391 sp += sizeofW(StgCatchFrame) - 1;
3398 StgSeqFrame *sf = (StgSeqFrame *)su;
3401 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3402 TICK_ALLOC_UPD_PAP(words+1,0);
3404 /* now build o = FUN(seq,ap) */
3405 o = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3406 TICK_ALLOC_SE_THK(1,0);
3407 SET_HDR(o,&stg_seq_info,su->header.prof.ccs /* ToDo */);
3408 o->payload[0] = (StgClosure *)ap;
3411 fprintf(stderr, "scheduler: Built ");
3412 printObj((StgClosure *)o);
3415 /* pop the old handler and put o on the stack */
3417 sp += sizeofW(StgSeqFrame) - 1;
3423 /* We've stripped the entire stack, the thread is now dead. */
3424 sp += sizeofW(StgStopFrame) - 1;
3425 sp[0] = (W_)exception; /* save the exception */
3426 tso->what_next = ThreadKilled;
3427 tso->su = (StgUpdateFrame *)(sp+1);
3438 /* -----------------------------------------------------------------------------
3439 resurrectThreads is called after garbage collection on the list of
3440 threads found to be garbage. Each of these threads will be woken
3441 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3442 on an MVar, or NonTermination if the thread was blocked on a Black
3445 Locks: sched_mutex isn't held upon entry nor exit.
3446 -------------------------------------------------------------------------- */
3449 resurrectThreads( StgTSO *threads )
3453 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3454 next = tso->global_link;
3455 tso->global_link = all_threads;
3457 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3459 switch (tso->why_blocked) {
3461 case BlockedOnException:
3462 /* Called by GC - sched_mutex lock is currently held. */
3463 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3465 case BlockedOnBlackHole:
3466 raiseAsync(tso,(StgClosure *)NonTermination_closure);
3469 /* This might happen if the thread was blocked on a black hole
3470 * belonging to a thread that we've just woken up (raiseAsync
3471 * can wake up threads, remember...).
3475 barf("resurrectThreads: thread blocked in a strange way");
3480 /* -----------------------------------------------------------------------------
3481 * Blackhole detection: if we reach a deadlock, test whether any
3482 * threads are blocked on themselves. Any threads which are found to
3483 * be self-blocked get sent a NonTermination exception.
3485 * This is only done in a deadlock situation in order to avoid
3486 * performance overhead in the normal case.
3488 * Locks: sched_mutex is held upon entry and exit.
3489 * -------------------------------------------------------------------------- */
3492 detectBlackHoles( void )
3494 StgTSO *t = all_threads;
3495 StgUpdateFrame *frame;
3496 StgClosure *blocked_on;
3498 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3500 while (t->what_next == ThreadRelocated) {
3502 ASSERT(get_itbl(t)->type == TSO);
3505 if (t->why_blocked != BlockedOnBlackHole) {
3509 blocked_on = t->block_info.closure;
3511 for (frame = t->su; ; frame = frame->link) {
3512 switch (get_itbl(frame)->type) {
3515 if (frame->updatee == blocked_on) {
3516 /* We are blocking on one of our own computations, so
3517 * send this thread the NonTermination exception.
3520 sched_belch("thread %d is blocked on itself", t->id));
3521 raiseAsync(t, (StgClosure *)NonTermination_closure);
3542 //@node Debugging Routines, Index, Exception Handling Routines, Main scheduling code
3543 //@subsection Debugging Routines
3545 /* -----------------------------------------------------------------------------
3546 * Debugging: why is a thread blocked
3547 * [Also provides useful information when debugging threaded programs
3548 * at the Haskell source code level, so enable outside of DEBUG. --sof 7/02]
3549 -------------------------------------------------------------------------- */
3553 printThreadBlockage(StgTSO *tso)
3555 switch (tso->why_blocked) {
3557 fprintf(stderr,"is blocked on read from fd %d", tso->block_info.fd);
3559 case BlockedOnWrite:
3560 fprintf(stderr,"is blocked on write to fd %d", tso->block_info.fd);
3562 case BlockedOnDelay:
3563 fprintf(stderr,"is blocked until %d", tso->block_info.target);
3566 fprintf(stderr,"is blocked on an MVar");
3568 case BlockedOnException:
3569 fprintf(stderr,"is blocked on delivering an exception to thread %d",
3570 tso->block_info.tso->id);
3572 case BlockedOnBlackHole:
3573 fprintf(stderr,"is blocked on a black hole");
3576 fprintf(stderr,"is not blocked");
3580 fprintf(stderr,"is blocked on global address; local FM_BQ is %p (%s)",
3581 tso->block_info.closure, info_type(tso->block_info.closure));
3583 case BlockedOnGA_NoSend:
3584 fprintf(stderr,"is blocked on global address (no send); local FM_BQ is %p (%s)",
3585 tso->block_info.closure, info_type(tso->block_info.closure));
3588 #if defined(RTS_SUPPORTS_THREADS)
3589 case BlockedOnCCall:
3590 fprintf(stderr,"is blocked on an external call");
3594 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3595 tso->why_blocked, tso->id, tso);
3601 printThreadStatus(StgTSO *tso)
3603 switch (tso->what_next) {
3605 fprintf(stderr,"has been killed");
3607 case ThreadComplete:
3608 fprintf(stderr,"has completed");
3611 printThreadBlockage(tso);
3616 printAllThreads(void)
3622 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3623 ullong_format_string(TIME_ON_PROC(CurrentProc),
3624 time_string, rtsFalse/*no commas!*/);
3626 fprintf(stderr, "all threads at [%s]:\n", time_string);
3628 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3629 ullong_format_string(CURRENT_TIME,
3630 time_string, rtsFalse/*no commas!*/);
3632 fprintf(stderr,"all threads at [%s]:\n", time_string);
3634 fprintf(stderr,"all threads:\n");
3637 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3638 fprintf(stderr, "\tthread %d @ %p ", t->id, (void *)t);
3639 label = lookupThreadLabel((StgWord)t);
3640 if (label) fprintf(stderr,"[\"%s\"] ",(char *)label);
3641 printThreadStatus(t);
3642 fprintf(stderr,"\n");
3649 Print a whole blocking queue attached to node (debugging only).
3654 print_bq (StgClosure *node)
3656 StgBlockingQueueElement *bqe;
3660 fprintf(stderr,"## BQ of closure %p (%s): ",
3661 node, info_type(node));
3663 /* should cover all closures that may have a blocking queue */
3664 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3665 get_itbl(node)->type == FETCH_ME_BQ ||
3666 get_itbl(node)->type == RBH ||
3667 get_itbl(node)->type == MVAR);
3669 ASSERT(node!=(StgClosure*)NULL); // sanity check
3671 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
3675 Print a whole blocking queue starting with the element bqe.
3678 print_bqe (StgBlockingQueueElement *bqe)
3683 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3685 for (end = (bqe==END_BQ_QUEUE);
3686 !end; // iterate until bqe points to a CONSTR
3687 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
3688 bqe = end ? END_BQ_QUEUE : bqe->link) {
3689 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3690 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3691 /* types of closures that may appear in a blocking queue */
3692 ASSERT(get_itbl(bqe)->type == TSO ||
3693 get_itbl(bqe)->type == BLOCKED_FETCH ||
3694 get_itbl(bqe)->type == CONSTR);
3695 /* only BQs of an RBH end with an RBH_Save closure */
3696 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3698 switch (get_itbl(bqe)->type) {
3700 fprintf(stderr," TSO %u (%x),",
3701 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
3704 fprintf(stderr," BF (node=%p, ga=((%x, %d, %x)),",
3705 ((StgBlockedFetch *)bqe)->node,
3706 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
3707 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
3708 ((StgBlockedFetch *)bqe)->ga.weight);
3711 fprintf(stderr," %s (IP %p),",
3712 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3713 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3714 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3715 "RBH_Save_?"), get_itbl(bqe));
3718 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
3719 info_type((StgClosure *)bqe)); // , node, info_type(node));
3723 fputc('\n', stderr);
3725 # elif defined(GRAN)
3727 print_bq (StgClosure *node)
3729 StgBlockingQueueElement *bqe;
3730 PEs node_loc, tso_loc;
3733 /* should cover all closures that may have a blocking queue */
3734 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3735 get_itbl(node)->type == FETCH_ME_BQ ||
3736 get_itbl(node)->type == RBH);
3738 ASSERT(node!=(StgClosure*)NULL); // sanity check
3739 node_loc = where_is(node);
3741 fprintf(stderr,"## BQ of closure %p (%s) on [PE %d]: ",
3742 node, info_type(node), node_loc);
3745 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3747 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
3748 !end; // iterate until bqe points to a CONSTR
3749 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
3750 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3751 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3752 /* types of closures that may appear in a blocking queue */
3753 ASSERT(get_itbl(bqe)->type == TSO ||
3754 get_itbl(bqe)->type == CONSTR);
3755 /* only BQs of an RBH end with an RBH_Save closure */
3756 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3758 tso_loc = where_is((StgClosure *)bqe);
3759 switch (get_itbl(bqe)->type) {
3761 fprintf(stderr," TSO %d (%p) on [PE %d],",
3762 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
3765 fprintf(stderr," %s (IP %p),",
3766 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3767 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3768 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3769 "RBH_Save_?"), get_itbl(bqe));
3772 barf("Unexpected closure type %s in blocking queue of %p (%s)",
3773 info_type((StgClosure *)bqe), node, info_type(node));
3777 fputc('\n', stderr);
3781 Nice and easy: only TSOs on the blocking queue
3784 print_bq (StgClosure *node)
3788 ASSERT(node!=(StgClosure*)NULL); // sanity check
3789 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
3790 tso != END_TSO_QUEUE;
3792 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
3793 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
3794 fprintf(stderr," TSO %d (%p),", tso->id, tso);
3796 fputc('\n', stderr);
3807 for (i=0, tso=run_queue_hd;
3808 tso != END_TSO_QUEUE;
3817 sched_belch(char *s, ...)
3822 fprintf(stderr, "scheduler (task %ld): ", osThreadId());
3824 fprintf(stderr, "== ");
3826 fprintf(stderr, "scheduler: ");
3828 vfprintf(stderr, s, ap);
3829 fprintf(stderr, "\n");
3836 //@node Index, , Debugging Routines, Main scheduling code
3840 //* StgMainThread:: @cindex\s-+StgMainThread
3841 //* awaken_blocked_queue:: @cindex\s-+awaken_blocked_queue
3842 //* blocked_queue_hd:: @cindex\s-+blocked_queue_hd
3843 //* blocked_queue_tl:: @cindex\s-+blocked_queue_tl
3844 //* context_switch:: @cindex\s-+context_switch
3845 //* createThread:: @cindex\s-+createThread
3846 //* gc_pending_cond:: @cindex\s-+gc_pending_cond
3847 //* initScheduler:: @cindex\s-+initScheduler
3848 //* interrupted:: @cindex\s-+interrupted
3849 //* next_thread_id:: @cindex\s-+next_thread_id
3850 //* print_bq:: @cindex\s-+print_bq
3851 //* run_queue_hd:: @cindex\s-+run_queue_hd
3852 //* run_queue_tl:: @cindex\s-+run_queue_tl
3853 //* sched_mutex:: @cindex\s-+sched_mutex
3854 //* schedule:: @cindex\s-+schedule
3855 //* take_off_run_queue:: @cindex\s-+take_off_run_queue
3856 //* term_mutex:: @cindex\s-+term_mutex