1 /* ---------------------------------------------------------------------------
2 * $Id: Schedule.c,v 1.142 2002/05/11 00:16:11 sof Exp $
4 * (c) The GHC Team, 1998-2000
8 * Different GHC ways use this scheduler quite differently (see comments below)
9 * Here is the global picture:
11 * WAY Name CPP flag What's it for
12 * --------------------------------------
13 * mp GUM PAR Parallel execution on a distributed memory machine
14 * s SMP SMP Parallel execution on a shared memory machine
15 * mg GranSim GRAN Simulation of parallel execution
16 * md GUM/GdH DIST Distributed execution (based on GUM)
18 * --------------------------------------------------------------------------*/
20 //@node Main scheduling code, , ,
21 //@section Main scheduling code
24 * Version with scheduler monitor support for SMPs (WAY=s):
26 This design provides a high-level API to create and schedule threads etc.
27 as documented in the SMP design document.
29 It uses a monitor design controlled by a single mutex to exercise control
30 over accesses to shared data structures, and builds on the Posix threads
33 The majority of state is shared. In order to keep essential per-task state,
34 there is a Capability structure, which contains all the information
35 needed to run a thread: its STG registers, a pointer to its TSO, a
36 nursery etc. During STG execution, a pointer to the capability is
37 kept in a register (BaseReg).
39 In a non-SMP build, there is one global capability, namely MainRegTable.
43 * Version with support for distributed memory parallelism aka GUM (WAY=mp):
45 The main scheduling loop in GUM iterates until a finish message is received.
46 In that case a global flag @receivedFinish@ is set and this instance of
47 the RTS shuts down. See ghc/rts/parallel/HLComms.c:processMessages()
48 for the handling of incoming messages, such as PP_FINISH.
49 Note that in the parallel case we have a system manager that coordinates
50 different PEs, each of which are running one instance of the RTS.
51 See ghc/rts/parallel/SysMan.c for the main routine of the parallel program.
52 From this routine processes executing ghc/rts/Main.c are spawned. -- HWL
54 * Version with support for simulating parallel execution aka GranSim (WAY=mg):
56 The main scheduling code in GranSim is quite different from that in std
57 (concurrent) Haskell: while concurrent Haskell just iterates over the
58 threads in the runnable queue, GranSim is event driven, i.e. it iterates
59 over the events in the global event queue. -- HWL
64 //* Variables and Data structures::
65 //* Main scheduling loop::
66 //* Suspend and Resume::
68 //* Garbage Collextion Routines::
69 //* Blocking Queue Routines::
70 //* Exception Handling Routines::
71 //* Debugging Routines::
75 //@node Includes, Variables and Data structures, Main scheduling code, Main scheduling code
76 //@subsection Includes
78 #include "PosixSource.h"
85 #include "StgStartup.h"
88 #include "StgMiscClosures.h"
90 #include "Interpreter.h"
91 #include "Exception.h"
100 #include "Proftimer.h"
101 #include "ProfHeap.h"
103 #if defined(GRAN) || defined(PAR)
104 # include "GranSimRts.h"
105 # include "GranSim.h"
106 # include "ParallelRts.h"
107 # include "Parallel.h"
108 # include "ParallelDebug.h"
109 # include "FetchMe.h"
113 #include "Capability.h"
114 #include "OSThreads.h"
117 #ifdef HAVE_SYS_TYPES_H
118 #include <sys/types.h>
126 //@node Variables and Data structures, Prototypes, Includes, Main scheduling code
127 //@subsection Variables and Data structures
129 /* Main thread queue.
130 * Locks required: sched_mutex.
132 StgMainThread *main_threads;
135 * Locks required: sched_mutex.
139 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
140 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
143 In GranSim we have a runnable and a blocked queue for each processor.
144 In order to minimise code changes new arrays run_queue_hds/tls
145 are created. run_queue_hd is then a short cut (macro) for
146 run_queue_hds[CurrentProc] (see GranSim.h).
149 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
150 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
151 StgTSO *ccalling_threadss[MAX_PROC];
152 /* We use the same global list of threads (all_threads) in GranSim as in
153 the std RTS (i.e. we are cheating). However, we don't use this list in
154 the GranSim specific code at the moment (so we are only potentially
159 StgTSO *run_queue_hd, *run_queue_tl;
160 StgTSO *blocked_queue_hd, *blocked_queue_tl;
161 StgTSO *sleeping_queue; /* perhaps replace with a hash table? */
165 /* Linked list of all threads.
166 * Used for detecting garbage collected threads.
170 /* When a thread performs a safe C call (_ccall_GC, using old
171 * terminology), it gets put on the suspended_ccalling_threads
172 * list. Used by the garbage collector.
174 static StgTSO *suspended_ccalling_threads;
176 static StgTSO *threadStackOverflow(StgTSO *tso);
178 /* KH: The following two flags are shared memory locations. There is no need
179 to lock them, since they are only unset at the end of a scheduler
183 /* flag set by signal handler to precipitate a context switch */
184 //@cindex context_switch
187 /* if this flag is set as well, give up execution */
188 //@cindex interrupted
191 /* Next thread ID to allocate.
192 * Locks required: sched_mutex
194 //@cindex next_thread_id
195 StgThreadID next_thread_id = 1;
198 * Pointers to the state of the current thread.
199 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
200 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
203 /* The smallest stack size that makes any sense is:
204 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
205 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
206 * + 1 (the realworld token for an IO thread)
207 * + 1 (the closure to enter)
209 * A thread with this stack will bomb immediately with a stack
210 * overflow, which will increase its stack size.
213 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 2)
220 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
221 * exists - earlier gccs apparently didn't.
227 rtsBool shutting_down_scheduler = rtsFalse;
229 void addToBlockedQueue ( StgTSO *tso );
231 static void schedule ( void );
232 void interruptStgRts ( void );
234 static StgTSO * createThread_ ( nat size, rtsBool have_lock, StgInt pri );
236 static StgTSO * createThread_ ( nat size, rtsBool have_lock );
239 static void detectBlackHoles ( void );
242 static void sched_belch(char *s, ...);
245 #if defined(RTS_SUPPORTS_THREADS)
246 /* ToDo: carefully document the invariants that go together
247 * with these synchronisation objects.
249 Mutex sched_mutex = INIT_MUTEX_VAR;
250 Mutex term_mutex = INIT_MUTEX_VAR;
253 static Condition gc_pending_cond = INIT_COND_VAR;
257 #endif /* RTS_SUPPORTS_THREADS */
261 rtsTime TimeOfLastYield;
262 rtsBool emitSchedule = rtsTrue;
266 char *whatNext_strs[] = {
274 char *threadReturnCode_strs[] = {
275 "HeapOverflow", /* might also be StackOverflow */
284 StgTSO * createSparkThread(rtsSpark spark);
285 StgTSO * activateSpark (rtsSpark spark);
289 * The thread state for the main thread.
290 // ToDo: check whether not needed any more
294 #if defined(PAR) || defined(RTS_SUPPORTS_THREADS)
295 static void taskStart(void);
306 //@node Main scheduling loop, Suspend and Resume, Prototypes, Main scheduling code
307 //@subsection Main scheduling loop
309 /* ---------------------------------------------------------------------------
310 Main scheduling loop.
312 We use round-robin scheduling, each thread returning to the
313 scheduler loop when one of these conditions is detected:
316 * timer expires (thread yields)
321 Locking notes: we acquire the scheduler lock once at the beginning
322 of the scheduler loop, and release it when
324 * running a thread, or
325 * waiting for work, or
326 * waiting for a GC to complete.
329 In a GranSim setup this loop iterates over the global event queue.
330 This revolves around the global event queue, which determines what
331 to do next. Therefore, it's more complicated than either the
332 concurrent or the parallel (GUM) setup.
335 GUM iterates over incoming messages.
336 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
337 and sends out a fish whenever it has nothing to do; in-between
338 doing the actual reductions (shared code below) it processes the
339 incoming messages and deals with delayed operations
340 (see PendingFetches).
341 This is not the ugliest code you could imagine, but it's bloody close.
343 ------------------------------------------------------------------------ */
350 StgThreadReturnCode ret;
358 rtsBool receivedFinish = rtsFalse;
360 nat tp_size, sp_size; // stats only
363 rtsBool was_interrupted = rtsFalse;
365 ACQUIRE_LOCK(&sched_mutex);
367 #if defined(RTS_SUPPORTS_THREADS)
368 waitForWorkCapability(&sched_mutex, &cap, rtsFalse);
370 /* simply initialise it in the non-threaded case */
371 grabCapability(&cap);
375 /* set up first event to get things going */
376 /* ToDo: assign costs for system setup and init MainTSO ! */
377 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
379 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
382 fprintf(stderr, "GRAN: Init CurrentTSO (in schedule) = %p\n", CurrentTSO);
383 G_TSO(CurrentTSO, 5));
385 if (RtsFlags.GranFlags.Light) {
386 /* Save current time; GranSim Light only */
387 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
390 event = get_next_event();
392 while (event!=(rtsEvent*)NULL) {
393 /* Choose the processor with the next event */
394 CurrentProc = event->proc;
395 CurrentTSO = event->tso;
399 while (!receivedFinish) { /* set by processMessages */
400 /* when receiving PP_FINISH message */
407 IF_DEBUG(scheduler, printAllThreads());
409 #if defined(RTS_SUPPORTS_THREADS)
410 /* Check to see whether there are any worker threads
411 waiting to deposit external call results. If so,
412 yield our capability */
413 yieldToReturningWorker(&sched_mutex, &cap);
416 /* If we're interrupted (the user pressed ^C, or some other
417 * termination condition occurred), kill all the currently running
421 IF_DEBUG(scheduler, sched_belch("interrupted"));
423 interrupted = rtsFalse;
424 was_interrupted = rtsTrue;
427 /* Go through the list of main threads and wake up any
428 * clients whose computations have finished. ToDo: this
429 * should be done more efficiently without a linear scan
430 * of the main threads list, somehow...
432 #if defined(RTS_SUPPORTS_THREADS)
434 StgMainThread *m, **prev;
435 prev = &main_threads;
436 for (m = main_threads; m != NULL; m = m->link) {
437 switch (m->tso->what_next) {
440 *(m->ret) = (StgClosure *)m->tso->sp[0];
444 broadcastCondition(&m->wakeup);
447 m->tso->label = NULL;
451 if (m->ret) *(m->ret) = NULL;
453 if (was_interrupted) {
454 m->stat = Interrupted;
458 broadcastCondition(&m->wakeup);
461 m->tso->label = NULL;
470 #else /* not threaded */
473 /* in GUM do this only on the Main PE */
476 /* If our main thread has finished or been killed, return.
479 StgMainThread *m = main_threads;
480 if (m->tso->what_next == ThreadComplete
481 || m->tso->what_next == ThreadKilled) {
484 m->tso->label = NULL;
486 main_threads = main_threads->link;
487 if (m->tso->what_next == ThreadComplete) {
488 /* we finished successfully, fill in the return value */
489 if (m->ret) { *(m->ret) = (StgClosure *)m->tso->sp[0]; };
493 if (m->ret) { *(m->ret) = NULL; };
494 if (was_interrupted) {
495 m->stat = Interrupted;
505 /* Top up the run queue from our spark pool. We try to make the
506 * number of threads in the run queue equal to the number of
509 * Disable spark support in SMP for now, non-essential & requires
510 * a little bit of work to make it compile cleanly. -- sof 1/02.
512 #if 0 /* defined(SMP) */
514 nat n = getFreeCapabilities();
515 StgTSO *tso = run_queue_hd;
517 /* Count the run queue */
518 while (n > 0 && tso != END_TSO_QUEUE) {
525 spark = findSpark(rtsFalse);
527 break; /* no more sparks in the pool */
529 /* I'd prefer this to be done in activateSpark -- HWL */
530 /* tricky - it needs to hold the scheduler lock and
531 * not try to re-acquire it -- SDM */
532 createSparkThread(spark);
534 sched_belch("==^^ turning spark of closure %p into a thread",
535 (StgClosure *)spark));
538 /* We need to wake up the other tasks if we just created some
541 if (getFreeCapabilities() - n > 1) {
542 signalCondition( &thread_ready_cond );
547 /* check for signals each time around the scheduler */
548 #ifndef mingw32_TARGET_OS
549 if (signals_pending()) {
550 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
551 startSignalHandlers();
552 ACQUIRE_LOCK(&sched_mutex);
556 /* Check whether any waiting threads need to be woken up. If the
557 * run queue is empty, and there are no other tasks running, we
558 * can wait indefinitely for something to happen.
559 * ToDo: what if another client comes along & requests another
562 if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue) ) {
563 awaitEvent( EMPTY_RUN_QUEUE()
565 && allFreeCapabilities()
569 /* we can be interrupted while waiting for I/O... */
570 if (interrupted) continue;
573 * Detect deadlock: when we have no threads to run, there are no
574 * threads waiting on I/O or sleeping, and all the other tasks are
575 * waiting for work, we must have a deadlock of some description.
577 * We first try to find threads blocked on themselves (ie. black
578 * holes), and generate NonTermination exceptions where necessary.
580 * If no threads are black holed, we have a deadlock situation, so
581 * inform all the main threads.
584 if ( EMPTY_THREAD_QUEUES()
585 #if defined(RTS_SUPPORTS_THREADS)
586 && EMPTY_QUEUE(suspended_ccalling_threads)
589 && allFreeCapabilities()
593 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
594 #if defined(THREADED_RTS)
595 /* and SMP mode ..? */
596 releaseCapability(cap);
598 // Garbage collection can release some new threads due to
599 // either (a) finalizers or (b) threads resurrected because
600 // they are about to be send BlockedOnDeadMVar. Any threads
601 // thus released will be immediately runnable.
602 GarbageCollect(GetRoots,rtsTrue);
604 if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
607 sched_belch("still deadlocked, checking for black holes..."));
610 if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
612 #ifndef mingw32_TARGET_OS
613 /* If we have user-installed signal handlers, then wait
614 * for signals to arrive rather then bombing out with a
617 #if defined(RTS_SUPPORTS_THREADS)
618 if ( 0 ) { /* hmm..what to do? Simply stop waiting for
619 a signal with no runnable threads (or I/O
620 suspended ones) leads nowhere quick.
621 For now, simply shut down when we reach this
624 ToDo: define precisely under what conditions
625 the Scheduler should shut down in an MT setting.
628 if ( anyUserHandlers() ) {
631 sched_belch("still deadlocked, waiting for signals..."));
635 // we might be interrupted...
636 if (interrupted) { continue; }
638 if (signals_pending()) {
639 RELEASE_LOCK(&sched_mutex);
640 startSignalHandlers();
641 ACQUIRE_LOCK(&sched_mutex);
643 ASSERT(!EMPTY_RUN_QUEUE());
648 /* Probably a real deadlock. Send the current main thread the
649 * Deadlock exception (or in the SMP build, send *all* main
650 * threads the deadlock exception, since none of them can make
655 #if defined(RTS_SUPPORTS_THREADS)
656 for (m = main_threads; m != NULL; m = m->link) {
657 switch (m->tso->why_blocked) {
658 case BlockedOnBlackHole:
659 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
661 case BlockedOnException:
663 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
666 barf("deadlock: main thread blocked in a strange way");
671 switch (m->tso->why_blocked) {
672 case BlockedOnBlackHole:
673 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
675 case BlockedOnException:
677 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
680 barf("deadlock: main thread blocked in a strange way");
685 #if defined(RTS_SUPPORTS_THREADS)
686 /* ToDo: revisit conditions (and mechanism) for shutting
687 down a multi-threaded world */
688 IF_DEBUG(scheduler, sched_belch("all done, i think...shutting down."));
689 RELEASE_LOCK(&sched_mutex);
697 /* ToDo: add deadlock detection in GUM (similar to SMP) -- HWL */
701 /* If there's a GC pending, don't do anything until it has
705 IF_DEBUG(scheduler,sched_belch("waiting for GC"));
706 waitCondition( &gc_pending_cond, &sched_mutex );
710 #if defined(RTS_SUPPORTS_THREADS)
711 /* block until we've got a thread on the run queue and a free
715 if ( EMPTY_RUN_QUEUE() ) {
716 /* Give up our capability */
717 releaseCapability(cap);
719 /* If we're in the process of shutting down (& running the
720 * a batch of finalisers), don't wait around.
722 if ( shutting_down_scheduler ) {
723 RELEASE_LOCK(&sched_mutex);
726 IF_DEBUG(scheduler, sched_belch("thread %d: waiting for work", osThreadId()));
727 waitForWorkCapability(&sched_mutex, &cap, rtsTrue);
728 IF_DEBUG(scheduler, sched_belch("thread %d: work now available", osThreadId()));
733 if (RtsFlags.GranFlags.Light)
734 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
736 /* adjust time based on time-stamp */
737 if (event->time > CurrentTime[CurrentProc] &&
738 event->evttype != ContinueThread)
739 CurrentTime[CurrentProc] = event->time;
741 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
742 if (!RtsFlags.GranFlags.Light)
745 IF_DEBUG(gran, fprintf(stderr, "GRAN: switch by event-type\n"));
747 /* main event dispatcher in GranSim */
748 switch (event->evttype) {
749 /* Should just be continuing execution */
751 IF_DEBUG(gran, fprintf(stderr, "GRAN: doing ContinueThread\n"));
752 /* ToDo: check assertion
753 ASSERT(run_queue_hd != (StgTSO*)NULL &&
754 run_queue_hd != END_TSO_QUEUE);
756 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
757 if (!RtsFlags.GranFlags.DoAsyncFetch &&
758 procStatus[CurrentProc]==Fetching) {
759 belch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]",
760 CurrentTSO->id, CurrentTSO, CurrentProc);
763 /* Ignore ContinueThreads for completed threads */
764 if (CurrentTSO->what_next == ThreadComplete) {
765 belch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)",
766 CurrentTSO->id, CurrentTSO, CurrentProc);
769 /* Ignore ContinueThreads for threads that are being migrated */
770 if (PROCS(CurrentTSO)==Nowhere) {
771 belch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)",
772 CurrentTSO->id, CurrentTSO, CurrentProc);
775 /* The thread should be at the beginning of the run queue */
776 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
777 belch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread",
778 CurrentTSO->id, CurrentTSO, CurrentProc);
779 break; // run the thread anyway
782 new_event(proc, proc, CurrentTime[proc],
784 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
786 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
787 break; // now actually run the thread; DaH Qu'vam yImuHbej
790 do_the_fetchnode(event);
791 goto next_thread; /* handle next event in event queue */
794 do_the_globalblock(event);
795 goto next_thread; /* handle next event in event queue */
798 do_the_fetchreply(event);
799 goto next_thread; /* handle next event in event queue */
801 case UnblockThread: /* Move from the blocked queue to the tail of */
802 do_the_unblock(event);
803 goto next_thread; /* handle next event in event queue */
805 case ResumeThread: /* Move from the blocked queue to the tail of */
806 /* the runnable queue ( i.e. Qu' SImqa'lu') */
807 event->tso->gran.blocktime +=
808 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
809 do_the_startthread(event);
810 goto next_thread; /* handle next event in event queue */
813 do_the_startthread(event);
814 goto next_thread; /* handle next event in event queue */
817 do_the_movethread(event);
818 goto next_thread; /* handle next event in event queue */
821 do_the_movespark(event);
822 goto next_thread; /* handle next event in event queue */
825 do_the_findwork(event);
826 goto next_thread; /* handle next event in event queue */
829 barf("Illegal event type %u\n", event->evttype);
832 /* This point was scheduler_loop in the old RTS */
834 IF_DEBUG(gran, belch("GRAN: after main switch"));
836 TimeOfLastEvent = CurrentTime[CurrentProc];
837 TimeOfNextEvent = get_time_of_next_event();
838 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
839 // CurrentTSO = ThreadQueueHd;
841 IF_DEBUG(gran, belch("GRAN: time of next event is: %ld",
844 if (RtsFlags.GranFlags.Light)
845 GranSimLight_leave_system(event, &ActiveTSO);
847 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
850 belch("GRAN: end of time-slice is %#lx", EndOfTimeSlice));
852 /* in a GranSim setup the TSO stays on the run queue */
854 /* Take a thread from the run queue. */
855 t = POP_RUN_QUEUE(); // take_off_run_queue(t);
858 fprintf(stderr, "GRAN: About to run current thread, which is\n");
861 context_switch = 0; // turned on via GranYield, checking events and time slice
864 DumpGranEvent(GR_SCHEDULE, t));
866 procStatus[CurrentProc] = Busy;
869 if (PendingFetches != END_BF_QUEUE) {
873 /* ToDo: phps merge with spark activation above */
874 /* check whether we have local work and send requests if we have none */
875 if (EMPTY_RUN_QUEUE()) { /* no runnable threads */
876 /* :-[ no local threads => look out for local sparks */
877 /* the spark pool for the current PE */
878 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
879 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
880 pool->hd < pool->tl) {
882 * ToDo: add GC code check that we really have enough heap afterwards!!
884 * If we're here (no runnable threads) and we have pending
885 * sparks, we must have a space problem. Get enough space
886 * to turn one of those pending sparks into a
890 spark = findSpark(rtsFalse); /* get a spark */
891 if (spark != (rtsSpark) NULL) {
892 tso = activateSpark(spark); /* turn the spark into a thread */
893 IF_PAR_DEBUG(schedule,
894 belch("==== schedule: Created TSO %d (%p); %d threads active",
895 tso->id, tso, advisory_thread_count));
897 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
898 belch("==^^ failed to activate spark");
900 } /* otherwise fall through & pick-up new tso */
902 IF_PAR_DEBUG(verbose,
903 belch("==^^ no local sparks (spark pool contains only NFs: %d)",
904 spark_queue_len(pool)));
909 /* If we still have no work we need to send a FISH to get a spark
912 if (EMPTY_RUN_QUEUE()) {
913 /* =8-[ no local sparks => look for work on other PEs */
915 * We really have absolutely no work. Send out a fish
916 * (there may be some out there already), and wait for
917 * something to arrive. We clearly can't run any threads
918 * until a SCHEDULE or RESUME arrives, and so that's what
919 * we're hoping to see. (Of course, we still have to
920 * respond to other types of messages.)
922 TIME now = msTime() /*CURRENT_TIME*/;
923 IF_PAR_DEBUG(verbose,
924 belch("-- now=%ld", now));
925 IF_PAR_DEBUG(verbose,
926 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
927 (last_fish_arrived_at!=0 &&
928 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
929 belch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)",
930 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
931 last_fish_arrived_at,
932 RtsFlags.ParFlags.fishDelay, now);
935 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
936 (last_fish_arrived_at==0 ||
937 (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
938 /* outstandingFishes is set in sendFish, processFish;
939 avoid flooding system with fishes via delay */
941 sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY,
944 // Global statistics: count no. of fishes
945 if (RtsFlags.ParFlags.ParStats.Global &&
946 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
947 globalParStats.tot_fish_mess++;
951 receivedFinish = processMessages();
954 } else if (PacketsWaiting()) { /* Look for incoming messages */
955 receivedFinish = processMessages();
958 /* Now we are sure that we have some work available */
959 ASSERT(run_queue_hd != END_TSO_QUEUE);
961 /* Take a thread from the run queue, if we have work */
962 t = POP_RUN_QUEUE(); // take_off_run_queue(END_TSO_QUEUE);
963 IF_DEBUG(sanity,checkTSO(t));
965 /* ToDo: write something to the log-file
966 if (RTSflags.ParFlags.granSimStats && !sameThread)
967 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
971 /* the spark pool for the current PE */
972 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
975 belch("--=^ %d threads, %d sparks on [%#x]",
976 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
979 if (0 && RtsFlags.ParFlags.ParStats.Full &&
980 t && LastTSO && t->id != LastTSO->id &&
981 LastTSO->why_blocked == NotBlocked &&
982 LastTSO->what_next != ThreadComplete) {
983 // if previously scheduled TSO not blocked we have to record the context switch
984 DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
985 GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
988 if (RtsFlags.ParFlags.ParStats.Full &&
989 (emitSchedule /* forced emit */ ||
990 (t && LastTSO && t->id != LastTSO->id))) {
992 we are running a different TSO, so write a schedule event to log file
993 NB: If we use fair scheduling we also have to write a deschedule
994 event for LastTSO; with unfair scheduling we know that the
995 previous tso has blocked whenever we switch to another tso, so
996 we don't need it in GUM for now
998 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
999 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
1000 emitSchedule = rtsFalse;
1004 #else /* !GRAN && !PAR */
1006 /* grab a thread from the run queue */
1007 ASSERT(run_queue_hd != END_TSO_QUEUE);
1008 t = POP_RUN_QUEUE();
1009 // Sanity check the thread we're about to run. This can be
1010 // expensive if there is lots of thread switching going on...
1011 IF_DEBUG(sanity,checkTSO(t));
1014 cap->r.rCurrentTSO = t;
1016 /* context switches are now initiated by the timer signal, unless
1017 * the user specified "context switch as often as possible", with
1022 RtsFlags.ProfFlags.profileInterval == 0 ||
1024 (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
1025 && (run_queue_hd != END_TSO_QUEUE
1026 || blocked_queue_hd != END_TSO_QUEUE
1027 || sleeping_queue != END_TSO_QUEUE)))
1032 RELEASE_LOCK(&sched_mutex);
1034 IF_DEBUG(scheduler, sched_belch("-->> Running TSO %ld (%p) %s ...",
1035 t->id, t, whatNext_strs[t->what_next]));
1038 startHeapProfTimer();
1041 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1042 /* Run the current thread
1044 switch (cap->r.rCurrentTSO->what_next) {
1046 case ThreadComplete:
1047 /* Thread already finished, return to scheduler. */
1048 ret = ThreadFinished;
1050 case ThreadEnterGHC:
1051 ret = StgRun((StgFunPtr) stg_enterStackTop, &cap->r);
1054 ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
1056 case ThreadEnterInterp:
1057 ret = interpretBCO(cap);
1060 barf("schedule: invalid what_next field");
1062 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1064 /* Costs for the scheduler are assigned to CCS_SYSTEM */
1066 stopHeapProfTimer();
1070 ACQUIRE_LOCK(&sched_mutex);
1073 IF_DEBUG(scheduler,fprintf(stderr,"scheduler (task %ld): ", osThreadId()););
1074 #elif !defined(GRAN) && !defined(PAR)
1075 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: "););
1077 t = cap->r.rCurrentTSO;
1080 /* HACK 675: if the last thread didn't yield, make sure to print a
1081 SCHEDULE event to the log file when StgRunning the next thread, even
1082 if it is the same one as before */
1084 TimeOfLastYield = CURRENT_TIME;
1090 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
1091 globalGranStats.tot_heapover++;
1093 globalParStats.tot_heapover++;
1096 // did the task ask for a large block?
1097 if (cap->r.rHpAlloc > BLOCK_SIZE_W) {
1098 // if so, get one and push it on the front of the nursery.
1102 blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc * sizeof(W_)) / BLOCK_SIZE;
1104 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: requesting a large block (size %d)",
1106 whatNext_strs[t->what_next], blocks));
1108 // don't do this if it would push us over the
1109 // alloc_blocks_lim limit; we'll GC first.
1110 if (alloc_blocks + blocks < alloc_blocks_lim) {
1112 alloc_blocks += blocks;
1113 bd = allocGroup( blocks );
1115 // link the new group into the list
1116 bd->link = cap->r.rCurrentNursery;
1117 bd->u.back = cap->r.rCurrentNursery->u.back;
1118 if (cap->r.rCurrentNursery->u.back != NULL) {
1119 cap->r.rCurrentNursery->u.back->link = bd;
1121 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1122 g0s0->blocks == cap->r.rNursery);
1123 cap->r.rNursery = g0s0->blocks = bd;
1125 cap->r.rCurrentNursery->u.back = bd;
1127 // initialise it as a nursery block
1131 bd->free = bd->start;
1133 // don't forget to update the block count in g0s0.
1134 g0s0->n_blocks += blocks;
1135 ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1137 // now update the nursery to point to the new block
1138 cap->r.rCurrentNursery = bd;
1140 // we might be unlucky and have another thread get on the
1141 // run queue before us and steal the large block, but in that
1142 // case the thread will just end up requesting another large
1144 PUSH_ON_RUN_QUEUE(t);
1149 /* make all the running tasks block on a condition variable,
1150 * maybe set context_switch and wait till they all pile in,
1151 * then have them wait on a GC condition variable.
1153 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: HeapOverflow",
1154 t->id, t, whatNext_strs[t->what_next]));
1157 ASSERT(!is_on_queue(t,CurrentProc));
1159 /* Currently we emit a DESCHEDULE event before GC in GUM.
1160 ToDo: either add separate event to distinguish SYSTEM time from rest
1161 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1162 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1163 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1164 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1165 emitSchedule = rtsTrue;
1169 ready_to_gc = rtsTrue;
1170 context_switch = 1; /* stop other threads ASAP */
1171 PUSH_ON_RUN_QUEUE(t);
1172 /* actual GC is done at the end of the while loop */
1178 DumpGranEvent(GR_DESCHEDULE, t));
1179 globalGranStats.tot_stackover++;
1182 // DumpGranEvent(GR_DESCHEDULE, t);
1183 globalParStats.tot_stackover++;
1185 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped, StackOverflow",
1186 t->id, t, whatNext_strs[t->what_next]));
1187 /* just adjust the stack for this thread, then pop it back
1193 /* enlarge the stack */
1194 StgTSO *new_t = threadStackOverflow(t);
1196 /* This TSO has moved, so update any pointers to it from the
1197 * main thread stack. It better not be on any other queues...
1198 * (it shouldn't be).
1200 for (m = main_threads; m != NULL; m = m->link) {
1205 threadPaused(new_t);
1206 PUSH_ON_RUN_QUEUE(new_t);
1210 case ThreadYielding:
1213 DumpGranEvent(GR_DESCHEDULE, t));
1214 globalGranStats.tot_yields++;
1217 // DumpGranEvent(GR_DESCHEDULE, t);
1218 globalParStats.tot_yields++;
1220 /* put the thread back on the run queue. Then, if we're ready to
1221 * GC, check whether this is the last task to stop. If so, wake
1222 * up the GC thread. getThread will block during a GC until the
1226 if (t->what_next == ThreadEnterInterp) {
1227 /* ToDo: or maybe a timer expired when we were in Hugs?
1228 * or maybe someone hit ctrl-C
1230 belch("--<< thread %ld (%p; %s) stopped to switch to Hugs",
1231 t->id, t, whatNext_strs[t->what_next]);
1233 belch("--<< thread %ld (%p; %s) stopped, yielding",
1234 t->id, t, whatNext_strs[t->what_next]);
1241 //belch("&& Doing sanity check on yielding TSO %ld.", t->id);
1243 ASSERT(t->link == END_TSO_QUEUE);
1245 ASSERT(!is_on_queue(t,CurrentProc));
1248 //belch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1249 checkThreadQsSanity(rtsTrue));
1252 if (RtsFlags.ParFlags.doFairScheduling) {
1253 /* this does round-robin scheduling; good for concurrency */
1254 APPEND_TO_RUN_QUEUE(t);
1256 /* this does unfair scheduling; good for parallelism */
1257 PUSH_ON_RUN_QUEUE(t);
1260 /* this does round-robin scheduling; good for concurrency */
1261 APPEND_TO_RUN_QUEUE(t);
1264 /* add a ContinueThread event to actually process the thread */
1265 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1267 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1269 belch("GRAN: eventq and runnableq after adding yielded thread to queue again:");
1278 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1279 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)));
1280 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1282 // ??? needed; should emit block before
1284 DumpGranEvent(GR_DESCHEDULE, t));
1285 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1288 ASSERT(procStatus[CurrentProc]==Busy ||
1289 ((procStatus[CurrentProc]==Fetching) &&
1290 (t->block_info.closure!=(StgClosure*)NULL)));
1291 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1292 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1293 procStatus[CurrentProc]==Fetching))
1294 procStatus[CurrentProc] = Idle;
1298 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: ",
1299 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1302 if (t->block_info.closure!=(StgClosure*)NULL)
1303 print_bq(t->block_info.closure));
1305 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1308 /* whatever we schedule next, we must log that schedule */
1309 emitSchedule = rtsTrue;
1312 /* don't need to do anything. Either the thread is blocked on
1313 * I/O, in which case we'll have called addToBlockedQueue
1314 * previously, or it's blocked on an MVar or Blackhole, in which
1315 * case it'll be on the relevant queue already.
1318 fprintf(stderr, "--<< thread %d (%p) stopped: ", t->id, t);
1319 printThreadBlockage(t);
1320 fprintf(stderr, "\n"));
1322 /* Only for dumping event to log file
1323 ToDo: do I need this in GranSim, too?
1330 case ThreadFinished:
1331 /* Need to check whether this was a main thread, and if so, signal
1332 * the task that started it with the return value. If we have no
1333 * more main threads, we probably need to stop all the tasks until
1336 /* We also end up here if the thread kills itself with an
1337 * uncaught exception, see Exception.hc.
1339 IF_DEBUG(scheduler,belch("--++ thread %d (%p) finished", t->id, t));
1341 endThread(t, CurrentProc); // clean-up the thread
1343 /* For now all are advisory -- HWL */
1344 //if(t->priority==AdvisoryPriority) ??
1345 advisory_thread_count--;
1348 if(t->dist.priority==RevalPriority)
1352 if (RtsFlags.ParFlags.ParStats.Full &&
1353 !RtsFlags.ParFlags.ParStats.Suppressed)
1354 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1359 barf("schedule: invalid thread return code %d", (int)ret);
1363 if (RtsFlags.ProfFlags.profileInterval==0 || performHeapProfile) {
1364 GarbageCollect(GetRoots, rtsTrue);
1366 performHeapProfile = rtsFalse;
1367 ready_to_gc = rtsFalse; // we already GC'd
1373 && allFreeCapabilities()
1376 /* everybody back, start the GC.
1377 * Could do it in this thread, or signal a condition var
1378 * to do it in another thread. Either way, we need to
1379 * broadcast on gc_pending_cond afterward.
1381 #if defined(RTS_SUPPORTS_THREADS)
1382 IF_DEBUG(scheduler,sched_belch("doing GC"));
1384 GarbageCollect(GetRoots,rtsFalse);
1385 ready_to_gc = rtsFalse;
1387 broadcastCondition(&gc_pending_cond);
1390 /* add a ContinueThread event to continue execution of current thread */
1391 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1393 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1395 fprintf(stderr, "GRAN: eventq and runnableq after Garbage collection:\n");
1403 IF_GRAN_DEBUG(unused,
1404 print_eventq(EventHd));
1406 event = get_next_event();
1409 /* ToDo: wait for next message to arrive rather than busy wait */
1412 } /* end of while(1) */
1414 IF_PAR_DEBUG(verbose,
1415 belch("== Leaving schedule() after having received Finish"));
1418 /* ---------------------------------------------------------------------------
1419 * Singleton fork(). Do not copy any running threads.
1420 * ------------------------------------------------------------------------- */
1422 StgInt forkProcess(StgTSO* tso) {
1424 #ifndef mingw32_TARGET_OS
1428 IF_DEBUG(scheduler,sched_belch("forking!"));
1431 if (pid) { /* parent */
1433 /* just return the pid */
1435 } else { /* child */
1436 /* wipe all other threads */
1438 tso->link = END_TSO_QUEUE;
1440 /* DO NOT TOUCH THE QUEUES directly because most of the code around
1441 us is picky about finding the threat still in its queue when
1442 handling the deleteThread() */
1444 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1446 if (t->id != tso->id) {
1453 barf("forkProcess#: primop not implemented for mingw32, sorry! (%u)\n", tso->id);
1454 /* pointlessly printing out the TSOs 'id' to avoid CC unused warning. */
1456 #endif /* mingw32 */
1459 /* ---------------------------------------------------------------------------
1460 * deleteAllThreads(): kill all the live threads.
1462 * This is used when we catch a user interrupt (^C), before performing
1463 * any necessary cleanups and running finalizers.
1465 * Locks: sched_mutex held.
1466 * ------------------------------------------------------------------------- */
1468 void deleteAllThreads ( void )
1471 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
1472 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1473 next = t->global_link;
1476 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1477 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
1478 sleeping_queue = END_TSO_QUEUE;
1481 /* startThread and insertThread are now in GranSim.c -- HWL */
1484 //@node Suspend and Resume, Run queue code, Main scheduling loop, Main scheduling code
1485 //@subsection Suspend and Resume
1487 /* ---------------------------------------------------------------------------
1488 * Suspending & resuming Haskell threads.
1490 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1491 * its capability before calling the C function. This allows another
1492 * task to pick up the capability and carry on running Haskell
1493 * threads. It also means that if the C call blocks, it won't lock
1496 * The Haskell thread making the C call is put to sleep for the
1497 * duration of the call, on the susepended_ccalling_threads queue. We
1498 * give out a token to the task, which it can use to resume the thread
1499 * on return from the C function.
1500 * ------------------------------------------------------------------------- */
1503 suspendThread( StgRegTable *reg,
1505 #if !defined(RTS_SUPPORTS_THREADS) && !defined(DEBUG)
1513 /* assume that *reg is a pointer to the StgRegTable part
1516 cap = (Capability *)((void *)reg - sizeof(StgFunTable));
1518 ACQUIRE_LOCK(&sched_mutex);
1521 sched_belch("thread %d did a _ccall_gc (is_concurrent: %d)", cap->r.rCurrentTSO->id,concCall));
1523 threadPaused(cap->r.rCurrentTSO);
1524 cap->r.rCurrentTSO->link = suspended_ccalling_threads;
1525 suspended_ccalling_threads = cap->r.rCurrentTSO;
1527 #if defined(RTS_SUPPORTS_THREADS)
1528 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall;
1531 /* Use the thread ID as the token; it should be unique */
1532 tok = cap->r.rCurrentTSO->id;
1534 /* Hand back capability */
1535 releaseCapability(cap);
1537 #if defined(RTS_SUPPORTS_THREADS)
1538 /* Preparing to leave the RTS, so ensure there's a native thread/task
1539 waiting to take over.
1541 ToDo: optimise this and only create a new task if there's a need
1542 for one (i.e., if there's only one Concurrent Haskell thread alive,
1543 there's no need to create a new task).
1545 IF_DEBUG(scheduler, sched_belch("worker thread (%d): leaving RTS", tok));
1547 startTask(taskStart);
1551 /* Other threads _might_ be available for execution; signal this */
1553 RELEASE_LOCK(&sched_mutex);
1558 resumeThread( StgInt tok,
1560 #if !defined(RTS_SUPPORTS_THREADS)
1565 StgTSO *tso, **prev;
1568 #if defined(RTS_SUPPORTS_THREADS)
1569 /* Wait for permission to re-enter the RTS with the result. */
1571 ACQUIRE_LOCK(&sched_mutex);
1572 grabReturnCapability(&sched_mutex, &cap);
1574 grabCapability(&cap);
1577 grabCapability(&cap);
1580 /* Remove the thread off of the suspended list */
1581 prev = &suspended_ccalling_threads;
1582 for (tso = suspended_ccalling_threads;
1583 tso != END_TSO_QUEUE;
1584 prev = &tso->link, tso = tso->link) {
1585 if (tso->id == (StgThreadID)tok) {
1590 if (tso == END_TSO_QUEUE) {
1591 barf("resumeThread: thread not found");
1593 tso->link = END_TSO_QUEUE;
1594 /* Reset blocking status */
1595 tso->why_blocked = NotBlocked;
1597 cap->r.rCurrentTSO = tso;
1598 RELEASE_LOCK(&sched_mutex);
1603 /* ---------------------------------------------------------------------------
1605 * ------------------------------------------------------------------------ */
1606 static void unblockThread(StgTSO *tso);
1608 /* ---------------------------------------------------------------------------
1609 * Comparing Thread ids.
1611 * This is used from STG land in the implementation of the
1612 * instances of Eq/Ord for ThreadIds.
1613 * ------------------------------------------------------------------------ */
1615 int cmp_thread(const StgTSO *tso1, const StgTSO *tso2)
1617 StgThreadID id1 = tso1->id;
1618 StgThreadID id2 = tso2->id;
1620 if (id1 < id2) return (-1);
1621 if (id1 > id2) return 1;
1625 /* ---------------------------------------------------------------------------
1626 * Fetching the ThreadID from an StgTSO.
1628 * This is used in the implementation of Show for ThreadIds.
1629 * ------------------------------------------------------------------------ */
1630 int rts_getThreadId(const StgTSO *tso)
1636 void labelThread(StgTSO *tso, char *label)
1641 /* Caveat: Once set, you can only set the thread name to "" */
1642 len = strlen(label)+1;
1643 buf = realloc(tso->label,len);
1645 fprintf(stderr,"insufficient memory for labelThread!\n");
1649 strncpy(buf,label,len);
1654 /* ---------------------------------------------------------------------------
1655 Create a new thread.
1657 The new thread starts with the given stack size. Before the
1658 scheduler can run, however, this thread needs to have a closure
1659 (and possibly some arguments) pushed on its stack. See
1660 pushClosure() in Schedule.h.
1662 createGenThread() and createIOThread() (in SchedAPI.h) are
1663 convenient packaged versions of this function.
1665 currently pri (priority) is only used in a GRAN setup -- HWL
1666 ------------------------------------------------------------------------ */
1667 //@cindex createThread
1669 /* currently pri (priority) is only used in a GRAN setup -- HWL */
1671 createThread(nat stack_size, StgInt pri)
1673 return createThread_(stack_size, rtsFalse, pri);
1677 createThread_(nat size, rtsBool have_lock, StgInt pri)
1681 createThread(nat stack_size)
1683 return createThread_(stack_size, rtsFalse);
1687 createThread_(nat size, rtsBool have_lock)
1694 /* First check whether we should create a thread at all */
1696 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1697 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1699 belch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1700 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1701 return END_TSO_QUEUE;
1707 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
1710 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
1712 /* catch ridiculously small stack sizes */
1713 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
1714 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
1717 stack_size = size - TSO_STRUCT_SIZEW;
1719 tso = (StgTSO *)allocate(size);
1720 TICK_ALLOC_TSO(stack_size, 0);
1722 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
1724 SET_GRAN_HDR(tso, ThisPE);
1726 tso->what_next = ThreadEnterGHC;
1732 /* tso->id needs to be unique. For now we use a heavyweight mutex to
1733 * protect the increment operation on next_thread_id.
1734 * In future, we could use an atomic increment instead.
1737 if (!have_lock) { ACQUIRE_LOCK(&sched_mutex); }
1739 tso->id = next_thread_id++;
1741 if (!have_lock) { RELEASE_LOCK(&sched_mutex); }
1744 tso->why_blocked = NotBlocked;
1745 tso->blocked_exceptions = NULL;
1747 tso->stack_size = stack_size;
1748 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
1750 tso->sp = (P_)&(tso->stack) + stack_size;
1753 tso->prof.CCCS = CCS_MAIN;
1756 /* put a stop frame on the stack */
1757 tso->sp -= sizeofW(StgStopFrame);
1758 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
1759 tso->su = (StgUpdateFrame*)tso->sp;
1763 tso->link = END_TSO_QUEUE;
1764 /* uses more flexible routine in GranSim */
1765 insertThread(tso, CurrentProc);
1767 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
1773 if (RtsFlags.GranFlags.GranSimStats.Full)
1774 DumpGranEvent(GR_START,tso);
1776 if (RtsFlags.ParFlags.ParStats.Full)
1777 DumpGranEvent(GR_STARTQ,tso);
1778 /* HACk to avoid SCHEDULE
1782 /* Link the new thread on the global thread list.
1784 tso->global_link = all_threads;
1788 tso->dist.priority = MandatoryPriority; //by default that is...
1792 tso->gran.pri = pri;
1794 tso->gran.magic = TSO_MAGIC; // debugging only
1796 tso->gran.sparkname = 0;
1797 tso->gran.startedat = CURRENT_TIME;
1798 tso->gran.exported = 0;
1799 tso->gran.basicblocks = 0;
1800 tso->gran.allocs = 0;
1801 tso->gran.exectime = 0;
1802 tso->gran.fetchtime = 0;
1803 tso->gran.fetchcount = 0;
1804 tso->gran.blocktime = 0;
1805 tso->gran.blockcount = 0;
1806 tso->gran.blockedat = 0;
1807 tso->gran.globalsparks = 0;
1808 tso->gran.localsparks = 0;
1809 if (RtsFlags.GranFlags.Light)
1810 tso->gran.clock = Now; /* local clock */
1812 tso->gran.clock = 0;
1814 IF_DEBUG(gran,printTSO(tso));
1817 tso->par.magic = TSO_MAGIC; // debugging only
1819 tso->par.sparkname = 0;
1820 tso->par.startedat = CURRENT_TIME;
1821 tso->par.exported = 0;
1822 tso->par.basicblocks = 0;
1823 tso->par.allocs = 0;
1824 tso->par.exectime = 0;
1825 tso->par.fetchtime = 0;
1826 tso->par.fetchcount = 0;
1827 tso->par.blocktime = 0;
1828 tso->par.blockcount = 0;
1829 tso->par.blockedat = 0;
1830 tso->par.globalsparks = 0;
1831 tso->par.localsparks = 0;
1835 globalGranStats.tot_threads_created++;
1836 globalGranStats.threads_created_on_PE[CurrentProc]++;
1837 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
1838 globalGranStats.tot_sq_probes++;
1840 // collect parallel global statistics (currently done together with GC stats)
1841 if (RtsFlags.ParFlags.ParStats.Global &&
1842 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1843 //fprintf(stderr, "Creating thread %d @ %11.2f\n", tso->id, usertime());
1844 globalParStats.tot_threads_created++;
1850 belch("==__ schedule: Created TSO %d (%p);",
1851 CurrentProc, tso, tso->id));
1853 IF_PAR_DEBUG(verbose,
1854 belch("==__ schedule: Created TSO %d (%p); %d threads active",
1855 tso->id, tso, advisory_thread_count));
1857 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
1858 tso->id, tso->stack_size));
1865 all parallel thread creation calls should fall through the following routine.
1868 createSparkThread(rtsSpark spark)
1870 ASSERT(spark != (rtsSpark)NULL);
1871 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
1873 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1874 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1875 return END_TSO_QUEUE;
1879 tso = createThread_(RtsFlags.GcFlags.initialStkSize, rtsTrue);
1880 if (tso==END_TSO_QUEUE)
1881 barf("createSparkThread: Cannot create TSO");
1883 tso->priority = AdvisoryPriority;
1885 pushClosure(tso,spark);
1886 PUSH_ON_RUN_QUEUE(tso);
1887 advisory_thread_count++;
1894 Turn a spark into a thread.
1895 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
1898 //@cindex activateSpark
1900 activateSpark (rtsSpark spark)
1904 tso = createSparkThread(spark);
1905 if (RtsFlags.ParFlags.ParStats.Full) {
1906 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
1907 IF_PAR_DEBUG(verbose,
1908 belch("==^^ activateSpark: turning spark of closure %p (%s) into a thread",
1909 (StgClosure *)spark, info_type((StgClosure *)spark)));
1911 // ToDo: fwd info on local/global spark to thread -- HWL
1912 // tso->gran.exported = spark->exported;
1913 // tso->gran.locked = !spark->global;
1914 // tso->gran.sparkname = spark->name;
1920 /* ---------------------------------------------------------------------------
1923 * scheduleThread puts a thread on the head of the runnable queue.
1924 * This will usually be done immediately after a thread is created.
1925 * The caller of scheduleThread must create the thread using e.g.
1926 * createThread and push an appropriate closure
1927 * on this thread's stack before the scheduler is invoked.
1928 * ------------------------------------------------------------------------ */
1930 static void scheduleThread_ (StgTSO* tso, rtsBool createTask);
1933 scheduleThread_(StgTSO *tso
1934 , rtsBool createTask
1935 #if !defined(THREADED_RTS)
1940 ACQUIRE_LOCK(&sched_mutex);
1942 /* Put the new thread on the head of the runnable queue. The caller
1943 * better push an appropriate closure on this thread's stack
1944 * beforehand. In the SMP case, the thread may start running as
1945 * soon as we release the scheduler lock below.
1947 PUSH_ON_RUN_QUEUE(tso);
1948 #if defined(THREADED_RTS)
1949 /* If main() is scheduling a thread, don't bother creating a
1953 startTask(taskStart);
1959 IF_DEBUG(scheduler,printTSO(tso));
1961 RELEASE_LOCK(&sched_mutex);
1964 void scheduleThread(StgTSO* tso)
1966 return scheduleThread_(tso, rtsFalse);
1969 void scheduleExtThread(StgTSO* tso)
1971 return scheduleThread_(tso, rtsTrue);
1974 /* ---------------------------------------------------------------------------
1977 * Initialise the scheduler. This resets all the queues - if the
1978 * queues contained any threads, they'll be garbage collected at the
1981 * ------------------------------------------------------------------------ */
1985 term_handler(int sig STG_UNUSED)
1988 ACQUIRE_LOCK(&term_mutex);
1990 RELEASE_LOCK(&term_mutex);
2001 for (i=0; i<=MAX_PROC; i++) {
2002 run_queue_hds[i] = END_TSO_QUEUE;
2003 run_queue_tls[i] = END_TSO_QUEUE;
2004 blocked_queue_hds[i] = END_TSO_QUEUE;
2005 blocked_queue_tls[i] = END_TSO_QUEUE;
2006 ccalling_threadss[i] = END_TSO_QUEUE;
2007 sleeping_queue = END_TSO_QUEUE;
2010 run_queue_hd = END_TSO_QUEUE;
2011 run_queue_tl = END_TSO_QUEUE;
2012 blocked_queue_hd = END_TSO_QUEUE;
2013 blocked_queue_tl = END_TSO_QUEUE;
2014 sleeping_queue = END_TSO_QUEUE;
2017 suspended_ccalling_threads = END_TSO_QUEUE;
2019 main_threads = NULL;
2020 all_threads = END_TSO_QUEUE;
2025 RtsFlags.ConcFlags.ctxtSwitchTicks =
2026 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
2028 #if defined(RTS_SUPPORTS_THREADS)
2029 /* Initialise the mutex and condition variables used by
2031 initMutex(&sched_mutex);
2032 initMutex(&term_mutex);
2034 initCondition(&thread_ready_cond);
2038 initCondition(&gc_pending_cond);
2041 #if defined(RTS_SUPPORTS_THREADS)
2042 ACQUIRE_LOCK(&sched_mutex);
2045 /* Install the SIGHUP handler */
2048 struct sigaction action,oact;
2050 action.sa_handler = term_handler;
2051 sigemptyset(&action.sa_mask);
2052 action.sa_flags = 0;
2053 if (sigaction(SIGTERM, &action, &oact) != 0) {
2054 barf("can't install TERM handler");
2059 /* A capability holds the state a native thread needs in
2060 * order to execute STG code. At least one capability is
2061 * floating around (only SMP builds have more than one).
2065 #if defined(RTS_SUPPORTS_THREADS)
2066 /* start our haskell execution tasks */
2068 startTaskManager(RtsFlags.ParFlags.nNodes, taskStart);
2070 startTaskManager(0,taskStart);
2074 #if /* defined(SMP) ||*/ defined(PAR)
2078 #if defined(RTS_SUPPORTS_THREADS)
2079 RELEASE_LOCK(&sched_mutex);
2085 exitScheduler( void )
2087 #if defined(RTS_SUPPORTS_THREADS)
2090 shutting_down_scheduler = rtsTrue;
2093 /* -----------------------------------------------------------------------------
2094 Managing the per-task allocation areas.
2096 Each capability comes with an allocation area. These are
2097 fixed-length block lists into which allocation can be done.
2099 ToDo: no support for two-space collection at the moment???
2100 -------------------------------------------------------------------------- */
2102 /* -----------------------------------------------------------------------------
2103 * waitThread is the external interface for running a new computation
2104 * and waiting for the result.
2106 * In the non-SMP case, we create a new main thread, push it on the
2107 * main-thread stack, and invoke the scheduler to run it. The
2108 * scheduler will return when the top main thread on the stack has
2109 * completed or died, and fill in the necessary fields of the
2110 * main_thread structure.
2112 * In the SMP case, we create a main thread as before, but we then
2113 * create a new condition variable and sleep on it. When our new
2114 * main thread has completed, we'll be woken up and the status/result
2115 * will be in the main_thread struct.
2116 * -------------------------------------------------------------------------- */
2119 howManyThreadsAvail ( void )
2123 for (q = run_queue_hd; q != END_TSO_QUEUE; q = q->link)
2125 for (q = blocked_queue_hd; q != END_TSO_QUEUE; q = q->link)
2127 for (q = sleeping_queue; q != END_TSO_QUEUE; q = q->link)
2133 finishAllThreads ( void )
2136 while (run_queue_hd != END_TSO_QUEUE) {
2137 waitThread ( run_queue_hd, NULL);
2139 while (blocked_queue_hd != END_TSO_QUEUE) {
2140 waitThread ( blocked_queue_hd, NULL);
2142 while (sleeping_queue != END_TSO_QUEUE) {
2143 waitThread ( blocked_queue_hd, NULL);
2146 (blocked_queue_hd != END_TSO_QUEUE ||
2147 run_queue_hd != END_TSO_QUEUE ||
2148 sleeping_queue != END_TSO_QUEUE);
2152 waitThread(StgTSO *tso, /*out*/StgClosure **ret)
2154 IF_DEBUG(scheduler, sched_belch("== scheduler: waiting for thread (%d)\n", tso->id));
2155 #if defined(THREADED_RTS)
2156 return waitThread_(tso,ret, rtsFalse);
2158 return waitThread_(tso,ret);
2163 waitThread_(StgTSO *tso,
2164 /*out*/StgClosure **ret
2165 #if defined(THREADED_RTS)
2166 , rtsBool blockWaiting
2171 SchedulerStatus stat;
2173 ACQUIRE_LOCK(&sched_mutex);
2174 IF_DEBUG(scheduler, sched_belch("== scheduler: waiting for thread (%d)\n", tso->id));
2176 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2181 #if defined(RTS_SUPPORTS_THREADS)
2182 initCondition(&m->wakeup);
2185 m->link = main_threads;
2188 IF_DEBUG(scheduler, sched_belch("== scheduler: new main thread (%d)\n", m->tso->id));
2190 #if defined(RTS_SUPPORTS_THREADS)
2192 # if defined(THREADED_RTS)
2193 if (!blockWaiting) {
2194 /* In the threaded case, the OS thread that called main()
2195 * gets to enter the RTS directly without going via another
2198 RELEASE_LOCK(&sched_mutex);
2200 ASSERT(m->stat != NoStatus);
2205 waitCondition(&m->wakeup, &sched_mutex);
2206 } while (m->stat == NoStatus);
2209 /* GranSim specific init */
2210 CurrentTSO = m->tso; // the TSO to run
2211 procStatus[MainProc] = Busy; // status of main PE
2212 CurrentProc = MainProc; // PE to run it on
2216 RELEASE_LOCK(&sched_mutex);
2218 ASSERT(m->stat != NoStatus);
2223 #if defined(RTS_SUPPORTS_THREADS)
2224 closeCondition(&m->wakeup);
2227 IF_DEBUG(scheduler, fprintf(stderr, "== scheduler: main thread (%d) finished\n",
2231 #if defined(THREADED_RTS)
2234 RELEASE_LOCK(&sched_mutex);
2239 //@node Run queue code, Garbage Collextion Routines, Suspend and Resume, Main scheduling code
2240 //@subsection Run queue code
2244 NB: In GranSim we have many run queues; run_queue_hd is actually a macro
2245 unfolding to run_queue_hds[CurrentProc], thus CurrentProc is an
2246 implicit global variable that has to be correct when calling these
2250 /* Put the new thread on the head of the runnable queue.
2251 * The caller of createThread better push an appropriate closure
2252 * on this thread's stack before the scheduler is invoked.
2254 static /* inline */ void
2255 add_to_run_queue(tso)
2258 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2259 tso->link = run_queue_hd;
2261 if (run_queue_tl == END_TSO_QUEUE) {
2266 /* Put the new thread at the end of the runnable queue. */
2267 static /* inline */ void
2268 push_on_run_queue(tso)
2271 ASSERT(get_itbl((StgClosure *)tso)->type == TSO);
2272 ASSERT(run_queue_hd!=NULL && run_queue_tl!=NULL);
2273 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2274 if (run_queue_hd == END_TSO_QUEUE) {
2277 run_queue_tl->link = tso;
2283 Should be inlined because it's used very often in schedule. The tso
2284 argument is actually only needed in GranSim, where we want to have the
2285 possibility to schedule *any* TSO on the run queue, irrespective of the
2286 actual ordering. Therefore, if tso is not the nil TSO then we traverse
2287 the run queue and dequeue the tso, adjusting the links in the queue.
2289 //@cindex take_off_run_queue
2290 static /* inline */ StgTSO*
2291 take_off_run_queue(StgTSO *tso) {
2295 qetlaHbogh Qu' ngaSbogh ghomDaQ {tso} yIteq!
2297 if tso is specified, unlink that tso from the run_queue (doesn't have
2298 to be at the beginning of the queue); GranSim only
2300 if (tso!=END_TSO_QUEUE) {
2301 /* find tso in queue */
2302 for (t=run_queue_hd, prev=END_TSO_QUEUE;
2303 t!=END_TSO_QUEUE && t!=tso;
2307 /* now actually dequeue the tso */
2308 if (prev!=END_TSO_QUEUE) {
2309 ASSERT(run_queue_hd!=t);
2310 prev->link = t->link;
2312 /* t is at beginning of thread queue */
2313 ASSERT(run_queue_hd==t);
2314 run_queue_hd = t->link;
2316 /* t is at end of thread queue */
2317 if (t->link==END_TSO_QUEUE) {
2318 ASSERT(t==run_queue_tl);
2319 run_queue_tl = prev;
2321 ASSERT(run_queue_tl!=t);
2323 t->link = END_TSO_QUEUE;
2325 /* take tso from the beginning of the queue; std concurrent code */
2327 if (t != END_TSO_QUEUE) {
2328 run_queue_hd = t->link;
2329 t->link = END_TSO_QUEUE;
2330 if (run_queue_hd == END_TSO_QUEUE) {
2331 run_queue_tl = END_TSO_QUEUE;
2340 //@node Garbage Collextion Routines, Blocking Queue Routines, Run queue code, Main scheduling code
2341 //@subsection Garbage Collextion Routines
2343 /* ---------------------------------------------------------------------------
2344 Where are the roots that we know about?
2346 - all the threads on the runnable queue
2347 - all the threads on the blocked queue
2348 - all the threads on the sleeping queue
2349 - all the thread currently executing a _ccall_GC
2350 - all the "main threads"
2352 ------------------------------------------------------------------------ */
2354 /* This has to be protected either by the scheduler monitor, or by the
2355 garbage collection monitor (probably the latter).
2360 GetRoots(evac_fn evac)
2365 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2366 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2367 evac((StgClosure **)&run_queue_hds[i]);
2368 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2369 evac((StgClosure **)&run_queue_tls[i]);
2371 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2372 evac((StgClosure **)&blocked_queue_hds[i]);
2373 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2374 evac((StgClosure **)&blocked_queue_tls[i]);
2375 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2376 evac((StgClosure **)&ccalling_threads[i]);
2383 if (run_queue_hd != END_TSO_QUEUE) {
2384 ASSERT(run_queue_tl != END_TSO_QUEUE);
2385 evac((StgClosure **)&run_queue_hd);
2386 evac((StgClosure **)&run_queue_tl);
2389 if (blocked_queue_hd != END_TSO_QUEUE) {
2390 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2391 evac((StgClosure **)&blocked_queue_hd);
2392 evac((StgClosure **)&blocked_queue_tl);
2395 if (sleeping_queue != END_TSO_QUEUE) {
2396 evac((StgClosure **)&sleeping_queue);
2400 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2401 evac((StgClosure **)&suspended_ccalling_threads);
2404 #if defined(PAR) || defined(GRAN)
2405 markSparkQueue(evac);
2409 /* -----------------------------------------------------------------------------
2412 This is the interface to the garbage collector from Haskell land.
2413 We provide this so that external C code can allocate and garbage
2414 collect when called from Haskell via _ccall_GC.
2416 It might be useful to provide an interface whereby the programmer
2417 can specify more roots (ToDo).
2419 This needs to be protected by the GC condition variable above. KH.
2420 -------------------------------------------------------------------------- */
2422 void (*extra_roots)(evac_fn);
2427 /* Obligated to hold this lock upon entry */
2428 ACQUIRE_LOCK(&sched_mutex);
2429 GarbageCollect(GetRoots,rtsFalse);
2430 RELEASE_LOCK(&sched_mutex);
2434 performMajorGC(void)
2436 ACQUIRE_LOCK(&sched_mutex);
2437 GarbageCollect(GetRoots,rtsTrue);
2438 RELEASE_LOCK(&sched_mutex);
2442 AllRoots(evac_fn evac)
2444 GetRoots(evac); // the scheduler's roots
2445 extra_roots(evac); // the user's roots
2449 performGCWithRoots(void (*get_roots)(evac_fn))
2451 ACQUIRE_LOCK(&sched_mutex);
2452 extra_roots = get_roots;
2453 GarbageCollect(AllRoots,rtsFalse);
2454 RELEASE_LOCK(&sched_mutex);
2457 /* -----------------------------------------------------------------------------
2460 If the thread has reached its maximum stack size, then raise the
2461 StackOverflow exception in the offending thread. Otherwise
2462 relocate the TSO into a larger chunk of memory and adjust its stack
2464 -------------------------------------------------------------------------- */
2467 threadStackOverflow(StgTSO *tso)
2469 nat new_stack_size, new_tso_size, diff, stack_words;
2473 IF_DEBUG(sanity,checkTSO(tso));
2474 if (tso->stack_size >= tso->max_stack_size) {
2477 belch("@@ threadStackOverflow of TSO %d (%p): stack too large (now %ld; max is %ld",
2478 tso->id, tso, tso->stack_size, tso->max_stack_size);
2479 /* If we're debugging, just print out the top of the stack */
2480 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2483 /* Send this thread the StackOverflow exception */
2484 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2488 /* Try to double the current stack size. If that takes us over the
2489 * maximum stack size for this thread, then use the maximum instead.
2490 * Finally round up so the TSO ends up as a whole number of blocks.
2492 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2493 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2494 TSO_STRUCT_SIZE)/sizeof(W_);
2495 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2496 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2498 IF_DEBUG(scheduler, fprintf(stderr,"== scheduler: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2500 dest = (StgTSO *)allocate(new_tso_size);
2501 TICK_ALLOC_TSO(new_stack_size,0);
2503 /* copy the TSO block and the old stack into the new area */
2504 memcpy(dest,tso,TSO_STRUCT_SIZE);
2505 stack_words = tso->stack + tso->stack_size - tso->sp;
2506 new_sp = (P_)dest + new_tso_size - stack_words;
2507 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2509 /* relocate the stack pointers... */
2510 diff = (P_)new_sp - (P_)tso->sp; /* In *words* */
2511 dest->su = (StgUpdateFrame *) ((P_)dest->su + diff);
2513 dest->stack_size = new_stack_size;
2515 /* and relocate the update frame list */
2516 relocate_stack(dest, diff);
2518 /* Mark the old TSO as relocated. We have to check for relocated
2519 * TSOs in the garbage collector and any primops that deal with TSOs.
2521 * It's important to set the sp and su values to just beyond the end
2522 * of the stack, so we don't attempt to scavenge any part of the
2525 tso->what_next = ThreadRelocated;
2527 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2528 tso->su = (StgUpdateFrame *)tso->sp;
2529 tso->why_blocked = NotBlocked;
2530 dest->mut_link = NULL;
2532 IF_PAR_DEBUG(verbose,
2533 belch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld",
2534 tso->id, tso, tso->stack_size);
2535 /* If we're debugging, just print out the top of the stack */
2536 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2539 IF_DEBUG(sanity,checkTSO(tso));
2541 IF_DEBUG(scheduler,printTSO(dest));
2547 //@node Blocking Queue Routines, Exception Handling Routines, Garbage Collextion Routines, Main scheduling code
2548 //@subsection Blocking Queue Routines
2550 /* ---------------------------------------------------------------------------
2551 Wake up a queue that was blocked on some resource.
2552 ------------------------------------------------------------------------ */
2556 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2561 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2563 /* write RESUME events to log file and
2564 update blocked and fetch time (depending on type of the orig closure) */
2565 if (RtsFlags.ParFlags.ParStats.Full) {
2566 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2567 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2568 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2569 if (EMPTY_RUN_QUEUE())
2570 emitSchedule = rtsTrue;
2572 switch (get_itbl(node)->type) {
2574 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2579 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2586 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2593 static StgBlockingQueueElement *
2594 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2597 PEs node_loc, tso_loc;
2599 node_loc = where_is(node); // should be lifted out of loop
2600 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2601 tso_loc = where_is((StgClosure *)tso);
2602 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2603 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2604 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2605 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2606 // insertThread(tso, node_loc);
2607 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2609 tso, node, (rtsSpark*)NULL);
2610 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2613 } else { // TSO is remote (actually should be FMBQ)
2614 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2615 RtsFlags.GranFlags.Costs.gunblocktime +
2616 RtsFlags.GranFlags.Costs.latency;
2617 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2619 tso, node, (rtsSpark*)NULL);
2620 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2623 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2625 fprintf(stderr," %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2626 (node_loc==tso_loc ? "Local" : "Global"),
2627 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2628 tso->block_info.closure = NULL;
2629 IF_DEBUG(scheduler,belch("-- Waking up thread %ld (%p)",
2633 static StgBlockingQueueElement *
2634 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2636 StgBlockingQueueElement *next;
2638 switch (get_itbl(bqe)->type) {
2640 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2641 /* if it's a TSO just push it onto the run_queue */
2643 // ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2644 PUSH_ON_RUN_QUEUE((StgTSO *)bqe);
2646 unblockCount(bqe, node);
2647 /* reset blocking status after dumping event */
2648 ((StgTSO *)bqe)->why_blocked = NotBlocked;
2652 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2654 bqe->link = (StgBlockingQueueElement *)PendingFetches;
2655 PendingFetches = (StgBlockedFetch *)bqe;
2659 /* can ignore this case in a non-debugging setup;
2660 see comments on RBHSave closures above */
2662 /* check that the closure is an RBHSave closure */
2663 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2664 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2665 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2669 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2670 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
2674 IF_PAR_DEBUG(bq, fprintf(stderr, ", %p (%s)", bqe, info_type((StgClosure*)bqe)));
2678 #else /* !GRAN && !PAR */
2680 unblockOneLocked(StgTSO *tso)
2684 ASSERT(get_itbl(tso)->type == TSO);
2685 ASSERT(tso->why_blocked != NotBlocked);
2686 tso->why_blocked = NotBlocked;
2688 PUSH_ON_RUN_QUEUE(tso);
2690 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
2695 #if defined(GRAN) || defined(PAR)
2696 inline StgBlockingQueueElement *
2697 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2699 ACQUIRE_LOCK(&sched_mutex);
2700 bqe = unblockOneLocked(bqe, node);
2701 RELEASE_LOCK(&sched_mutex);
2706 unblockOne(StgTSO *tso)
2708 ACQUIRE_LOCK(&sched_mutex);
2709 tso = unblockOneLocked(tso);
2710 RELEASE_LOCK(&sched_mutex);
2717 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2719 StgBlockingQueueElement *bqe;
2724 belch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): ", \
2725 node, CurrentProc, CurrentTime[CurrentProc],
2726 CurrentTSO->id, CurrentTSO));
2728 node_loc = where_is(node);
2730 ASSERT(q == END_BQ_QUEUE ||
2731 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
2732 get_itbl(q)->type == CONSTR); // closure (type constructor)
2733 ASSERT(is_unique(node));
2735 /* FAKE FETCH: magically copy the node to the tso's proc;
2736 no Fetch necessary because in reality the node should not have been
2737 moved to the other PE in the first place
2739 if (CurrentProc!=node_loc) {
2741 belch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)",
2742 node, node_loc, CurrentProc, CurrentTSO->id,
2743 // CurrentTSO, where_is(CurrentTSO),
2744 node->header.gran.procs));
2745 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
2747 belch("## new bitmask of node %p is %#x",
2748 node, node->header.gran.procs));
2749 if (RtsFlags.GranFlags.GranSimStats.Global) {
2750 globalGranStats.tot_fake_fetches++;
2755 // ToDo: check: ASSERT(CurrentProc==node_loc);
2756 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
2759 bqe points to the current element in the queue
2760 next points to the next element in the queue
2762 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2763 //tso_loc = where_is(tso);
2765 bqe = unblockOneLocked(bqe, node);
2768 /* if this is the BQ of an RBH, we have to put back the info ripped out of
2769 the closure to make room for the anchor of the BQ */
2770 if (bqe!=END_BQ_QUEUE) {
2771 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
2773 ASSERT((info_ptr==&RBH_Save_0_info) ||
2774 (info_ptr==&RBH_Save_1_info) ||
2775 (info_ptr==&RBH_Save_2_info));
2777 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
2778 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
2779 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
2782 belch("## Filled in RBH_Save for %p (%s) at end of AwBQ",
2783 node, info_type(node)));
2786 /* statistics gathering */
2787 if (RtsFlags.GranFlags.GranSimStats.Global) {
2788 // globalGranStats.tot_bq_processing_time += bq_processing_time;
2789 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
2790 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
2791 globalGranStats.tot_awbq++; // total no. of bqs awakened
2794 fprintf(stderr,"## BQ Stats of %p: [%d entries] %s\n",
2795 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
2799 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2801 StgBlockingQueueElement *bqe;
2803 ACQUIRE_LOCK(&sched_mutex);
2805 IF_PAR_DEBUG(verbose,
2806 belch("##-_ AwBQ for node %p on [%x]: ",
2810 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
2811 IF_PAR_DEBUG(verbose, belch("## ... nothing to unblock so lets just return. RFP (BUG?)"));
2816 ASSERT(q == END_BQ_QUEUE ||
2817 get_itbl(q)->type == TSO ||
2818 get_itbl(q)->type == BLOCKED_FETCH ||
2819 get_itbl(q)->type == CONSTR);
2822 while (get_itbl(bqe)->type==TSO ||
2823 get_itbl(bqe)->type==BLOCKED_FETCH) {
2824 bqe = unblockOneLocked(bqe, node);
2826 RELEASE_LOCK(&sched_mutex);
2829 #else /* !GRAN && !PAR */
2831 awakenBlockedQueue(StgTSO *tso)
2833 ACQUIRE_LOCK(&sched_mutex);
2834 while (tso != END_TSO_QUEUE) {
2835 tso = unblockOneLocked(tso);
2837 RELEASE_LOCK(&sched_mutex);
2841 //@node Exception Handling Routines, Debugging Routines, Blocking Queue Routines, Main scheduling code
2842 //@subsection Exception Handling Routines
2844 /* ---------------------------------------------------------------------------
2846 - usually called inside a signal handler so it mustn't do anything fancy.
2847 ------------------------------------------------------------------------ */
2850 interruptStgRts(void)
2856 /* -----------------------------------------------------------------------------
2859 This is for use when we raise an exception in another thread, which
2861 This has nothing to do with the UnblockThread event in GranSim. -- HWL
2862 -------------------------------------------------------------------------- */
2864 #if defined(GRAN) || defined(PAR)
2866 NB: only the type of the blocking queue is different in GranSim and GUM
2867 the operations on the queue-elements are the same
2868 long live polymorphism!
2870 Locks: sched_mutex is held upon entry and exit.
2874 unblockThread(StgTSO *tso)
2876 StgBlockingQueueElement *t, **last;
2878 switch (tso->why_blocked) {
2881 return; /* not blocked */
2884 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2886 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
2887 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2889 last = (StgBlockingQueueElement **)&mvar->head;
2890 for (t = (StgBlockingQueueElement *)mvar->head;
2892 last = &t->link, last_tso = t, t = t->link) {
2893 if (t == (StgBlockingQueueElement *)tso) {
2894 *last = (StgBlockingQueueElement *)tso->link;
2895 if (mvar->tail == tso) {
2896 mvar->tail = (StgTSO *)last_tso;
2901 barf("unblockThread (MVAR): TSO not found");
2904 case BlockedOnBlackHole:
2905 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2907 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2909 last = &bq->blocking_queue;
2910 for (t = bq->blocking_queue;
2912 last = &t->link, t = t->link) {
2913 if (t == (StgBlockingQueueElement *)tso) {
2914 *last = (StgBlockingQueueElement *)tso->link;
2918 barf("unblockThread (BLACKHOLE): TSO not found");
2921 case BlockedOnException:
2923 StgTSO *target = tso->block_info.tso;
2925 ASSERT(get_itbl(target)->type == TSO);
2927 if (target->what_next == ThreadRelocated) {
2928 target = target->link;
2929 ASSERT(get_itbl(target)->type == TSO);
2932 ASSERT(target->blocked_exceptions != NULL);
2934 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
2935 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
2937 last = &t->link, t = t->link) {
2938 ASSERT(get_itbl(t)->type == TSO);
2939 if (t == (StgBlockingQueueElement *)tso) {
2940 *last = (StgBlockingQueueElement *)tso->link;
2944 barf("unblockThread (Exception): TSO not found");
2948 case BlockedOnWrite:
2950 /* take TSO off blocked_queue */
2951 StgBlockingQueueElement *prev = NULL;
2952 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
2953 prev = t, t = t->link) {
2954 if (t == (StgBlockingQueueElement *)tso) {
2956 blocked_queue_hd = (StgTSO *)t->link;
2957 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2958 blocked_queue_tl = END_TSO_QUEUE;
2961 prev->link = t->link;
2962 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2963 blocked_queue_tl = (StgTSO *)prev;
2969 barf("unblockThread (I/O): TSO not found");
2972 case BlockedOnDelay:
2974 /* take TSO off sleeping_queue */
2975 StgBlockingQueueElement *prev = NULL;
2976 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
2977 prev = t, t = t->link) {
2978 if (t == (StgBlockingQueueElement *)tso) {
2980 sleeping_queue = (StgTSO *)t->link;
2982 prev->link = t->link;
2987 barf("unblockThread (I/O): TSO not found");
2991 barf("unblockThread");
2995 tso->link = END_TSO_QUEUE;
2996 tso->why_blocked = NotBlocked;
2997 tso->block_info.closure = NULL;
2998 PUSH_ON_RUN_QUEUE(tso);
3002 unblockThread(StgTSO *tso)
3006 /* To avoid locking unnecessarily. */
3007 if (tso->why_blocked == NotBlocked) {
3011 switch (tso->why_blocked) {
3014 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3016 StgTSO *last_tso = END_TSO_QUEUE;
3017 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3020 for (t = mvar->head; t != END_TSO_QUEUE;
3021 last = &t->link, last_tso = t, t = t->link) {
3024 if (mvar->tail == tso) {
3025 mvar->tail = last_tso;
3030 barf("unblockThread (MVAR): TSO not found");
3033 case BlockedOnBlackHole:
3034 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3036 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3038 last = &bq->blocking_queue;
3039 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
3040 last = &t->link, t = t->link) {
3046 barf("unblockThread (BLACKHOLE): TSO not found");
3049 case BlockedOnException:
3051 StgTSO *target = tso->block_info.tso;
3053 ASSERT(get_itbl(target)->type == TSO);
3055 while (target->what_next == ThreadRelocated) {
3056 target = target->link;
3057 ASSERT(get_itbl(target)->type == TSO);
3060 ASSERT(target->blocked_exceptions != NULL);
3062 last = &target->blocked_exceptions;
3063 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
3064 last = &t->link, t = t->link) {
3065 ASSERT(get_itbl(t)->type == TSO);
3071 barf("unblockThread (Exception): TSO not found");
3075 case BlockedOnWrite:
3077 StgTSO *prev = NULL;
3078 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
3079 prev = t, t = t->link) {
3082 blocked_queue_hd = t->link;
3083 if (blocked_queue_tl == t) {
3084 blocked_queue_tl = END_TSO_QUEUE;
3087 prev->link = t->link;
3088 if (blocked_queue_tl == t) {
3089 blocked_queue_tl = prev;
3095 barf("unblockThread (I/O): TSO not found");
3098 case BlockedOnDelay:
3100 StgTSO *prev = NULL;
3101 for (t = sleeping_queue; t != END_TSO_QUEUE;
3102 prev = t, t = t->link) {
3105 sleeping_queue = t->link;
3107 prev->link = t->link;
3112 barf("unblockThread (I/O): TSO not found");
3116 barf("unblockThread");
3120 tso->link = END_TSO_QUEUE;
3121 tso->why_blocked = NotBlocked;
3122 tso->block_info.closure = NULL;
3123 PUSH_ON_RUN_QUEUE(tso);
3127 /* -----------------------------------------------------------------------------
3130 * The following function implements the magic for raising an
3131 * asynchronous exception in an existing thread.
3133 * We first remove the thread from any queue on which it might be
3134 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
3136 * We strip the stack down to the innermost CATCH_FRAME, building
3137 * thunks in the heap for all the active computations, so they can
3138 * be restarted if necessary. When we reach a CATCH_FRAME, we build
3139 * an application of the handler to the exception, and push it on
3140 * the top of the stack.
3142 * How exactly do we save all the active computations? We create an
3143 * AP_UPD for every UpdateFrame on the stack. Entering one of these
3144 * AP_UPDs pushes everything from the corresponding update frame
3145 * upwards onto the stack. (Actually, it pushes everything up to the
3146 * next update frame plus a pointer to the next AP_UPD object.
3147 * Entering the next AP_UPD object pushes more onto the stack until we
3148 * reach the last AP_UPD object - at which point the stack should look
3149 * exactly as it did when we killed the TSO and we can continue
3150 * execution by entering the closure on top of the stack.
3152 * We can also kill a thread entirely - this happens if either (a) the
3153 * exception passed to raiseAsync is NULL, or (b) there's no
3154 * CATCH_FRAME on the stack. In either case, we strip the entire
3155 * stack and replace the thread with a zombie.
3157 * Locks: sched_mutex held upon entry nor exit.
3159 * -------------------------------------------------------------------------- */
3162 deleteThread(StgTSO *tso)
3164 raiseAsync(tso,NULL);
3168 raiseAsyncWithLock(StgTSO *tso, StgClosure *exception)
3170 /* When raising async exs from contexts where sched_mutex isn't held;
3171 use raiseAsyncWithLock(). */
3172 ACQUIRE_LOCK(&sched_mutex);
3173 raiseAsync(tso,exception);
3174 RELEASE_LOCK(&sched_mutex);
3178 raiseAsync(StgTSO *tso, StgClosure *exception)
3180 StgUpdateFrame* su = tso->su;
3181 StgPtr sp = tso->sp;
3183 /* Thread already dead? */
3184 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3188 IF_DEBUG(scheduler, sched_belch("raising exception in thread %ld.", tso->id));
3190 /* Remove it from any blocking queues */
3193 IF_DEBUG(scheduler, sched_belch("raising exception in thread %ld.", tso->id));
3194 /* The stack freezing code assumes there's a closure pointer on
3195 * the top of the stack. This isn't always the case with compiled
3196 * code, so we have to push a dummy closure on the top which just
3197 * returns to the next return address on the stack.
3199 if ( LOOKS_LIKE_GHC_INFO((void*)*sp) ) {
3200 *(--sp) = (W_)&stg_dummy_ret_closure;
3204 nat words = ((P_)su - (P_)sp) - 1;
3208 /* If we find a CATCH_FRAME, and we've got an exception to raise,
3209 * then build the THUNK raise(exception), and leave it on
3210 * top of the CATCH_FRAME ready to enter.
3212 if (get_itbl(su)->type == CATCH_FRAME && exception != NULL) {
3214 StgCatchFrame *cf = (StgCatchFrame *)su;
3218 /* we've got an exception to raise, so let's pass it to the
3219 * handler in this frame.
3221 raise = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3222 TICK_ALLOC_SE_THK(1,0);
3223 SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
3224 raise->payload[0] = exception;
3226 /* throw away the stack from Sp up to the CATCH_FRAME.
3230 /* Ensure that async excpetions are blocked now, so we don't get
3231 * a surprise exception before we get around to executing the
3234 if (tso->blocked_exceptions == NULL) {
3235 tso->blocked_exceptions = END_TSO_QUEUE;
3238 /* Put the newly-built THUNK on top of the stack, ready to execute
3239 * when the thread restarts.
3244 tso->what_next = ThreadEnterGHC;
3245 IF_DEBUG(sanity, checkTSO(tso));
3249 /* First build an AP_UPD consisting of the stack chunk above the
3250 * current update frame, with the top word on the stack as the
3253 ap = (StgAP_UPD *)allocate(AP_sizeW(words));
3258 ap->fun = (StgClosure *)sp[0];
3260 for(i=0; i < (nat)words; ++i) {
3261 ap->payload[i] = (StgClosure *)*sp++;
3264 switch (get_itbl(su)->type) {
3268 SET_HDR(ap,&stg_AP_UPD_info,su->header.prof.ccs /* ToDo */);
3269 TICK_ALLOC_UP_THK(words+1,0);
3272 fprintf(stderr, "scheduler: Updating ");
3273 printPtr((P_)su->updatee);
3274 fprintf(stderr, " with ");
3275 printObj((StgClosure *)ap);
3278 /* Replace the updatee with an indirection - happily
3279 * this will also wake up any threads currently
3280 * waiting on the result.
3282 * Warning: if we're in a loop, more than one update frame on
3283 * the stack may point to the same object. Be careful not to
3284 * overwrite an IND_OLDGEN in this case, because we'll screw
3285 * up the mutable lists. To be on the safe side, don't
3286 * overwrite any kind of indirection at all. See also
3287 * threadSqueezeStack in GC.c, where we have to make a similar
3290 if (!closure_IND(su->updatee)) {
3291 UPD_IND_NOLOCK(su->updatee,ap); /* revert the black hole */
3294 sp += sizeofW(StgUpdateFrame) -1;
3295 sp[0] = (W_)ap; /* push onto stack */
3301 StgCatchFrame *cf = (StgCatchFrame *)su;
3304 /* We want a PAP, not an AP_UPD. Fortunately, the
3305 * layout's the same.
3307 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3308 TICK_ALLOC_UPD_PAP(words+1,0);
3310 /* now build o = FUN(catch,ap,handler) */
3311 o = (StgClosure *)allocate(sizeofW(StgClosure)+2);
3312 TICK_ALLOC_FUN(2,0);
3313 SET_HDR(o,&stg_catch_info,su->header.prof.ccs /* ToDo */);
3314 o->payload[0] = (StgClosure *)ap;
3315 o->payload[1] = cf->handler;
3318 fprintf(stderr, "scheduler: Built ");
3319 printObj((StgClosure *)o);
3322 /* pop the old handler and put o on the stack */
3324 sp += sizeofW(StgCatchFrame) - 1;
3331 StgSeqFrame *sf = (StgSeqFrame *)su;
3334 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3335 TICK_ALLOC_UPD_PAP(words+1,0);
3337 /* now build o = FUN(seq,ap) */
3338 o = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3339 TICK_ALLOC_SE_THK(1,0);
3340 SET_HDR(o,&stg_seq_info,su->header.prof.ccs /* ToDo */);
3341 o->payload[0] = (StgClosure *)ap;
3344 fprintf(stderr, "scheduler: Built ");
3345 printObj((StgClosure *)o);
3348 /* pop the old handler and put o on the stack */
3350 sp += sizeofW(StgSeqFrame) - 1;
3356 /* We've stripped the entire stack, the thread is now dead. */
3357 sp += sizeofW(StgStopFrame) - 1;
3358 sp[0] = (W_)exception; /* save the exception */
3359 tso->what_next = ThreadKilled;
3360 tso->su = (StgUpdateFrame *)(sp+1);
3371 /* -----------------------------------------------------------------------------
3372 resurrectThreads is called after garbage collection on the list of
3373 threads found to be garbage. Each of these threads will be woken
3374 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3375 on an MVar, or NonTermination if the thread was blocked on a Black
3378 Locks: sched_mutex isn't held upon entry nor exit.
3379 -------------------------------------------------------------------------- */
3382 resurrectThreads( StgTSO *threads )
3386 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3387 next = tso->global_link;
3388 tso->global_link = all_threads;
3390 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3392 switch (tso->why_blocked) {
3394 case BlockedOnException:
3395 /* Called by GC - sched_mutex lock is currently held. */
3396 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3398 case BlockedOnBlackHole:
3399 raiseAsync(tso,(StgClosure *)NonTermination_closure);
3402 /* This might happen if the thread was blocked on a black hole
3403 * belonging to a thread that we've just woken up (raiseAsync
3404 * can wake up threads, remember...).
3408 barf("resurrectThreads: thread blocked in a strange way");
3413 /* -----------------------------------------------------------------------------
3414 * Blackhole detection: if we reach a deadlock, test whether any
3415 * threads are blocked on themselves. Any threads which are found to
3416 * be self-blocked get sent a NonTermination exception.
3418 * This is only done in a deadlock situation in order to avoid
3419 * performance overhead in the normal case.
3421 * Locks: sched_mutex is held upon entry and exit.
3422 * -------------------------------------------------------------------------- */
3425 detectBlackHoles( void )
3427 StgTSO *t = all_threads;
3428 StgUpdateFrame *frame;
3429 StgClosure *blocked_on;
3431 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3433 while (t->what_next == ThreadRelocated) {
3435 ASSERT(get_itbl(t)->type == TSO);
3438 if (t->why_blocked != BlockedOnBlackHole) {
3442 blocked_on = t->block_info.closure;
3444 for (frame = t->su; ; frame = frame->link) {
3445 switch (get_itbl(frame)->type) {
3448 if (frame->updatee == blocked_on) {
3449 /* We are blocking on one of our own computations, so
3450 * send this thread the NonTermination exception.
3453 sched_belch("thread %d is blocked on itself", t->id));
3454 raiseAsync(t, (StgClosure *)NonTermination_closure);
3475 //@node Debugging Routines, Index, Exception Handling Routines, Main scheduling code
3476 //@subsection Debugging Routines
3478 /* -----------------------------------------------------------------------------
3479 Debugging: why is a thread blocked
3480 -------------------------------------------------------------------------- */
3485 printThreadBlockage(StgTSO *tso)
3487 switch (tso->why_blocked) {
3489 fprintf(stderr,"is blocked on read from fd %d", tso->block_info.fd);
3491 case BlockedOnWrite:
3492 fprintf(stderr,"is blocked on write to fd %d", tso->block_info.fd);
3494 case BlockedOnDelay:
3495 fprintf(stderr,"is blocked until %d", tso->block_info.target);
3498 fprintf(stderr,"is blocked on an MVar");
3500 case BlockedOnException:
3501 fprintf(stderr,"is blocked on delivering an exception to thread %d",
3502 tso->block_info.tso->id);
3504 case BlockedOnBlackHole:
3505 fprintf(stderr,"is blocked on a black hole");
3508 fprintf(stderr,"is not blocked");
3512 fprintf(stderr,"is blocked on global address; local FM_BQ is %p (%s)",
3513 tso->block_info.closure, info_type(tso->block_info.closure));
3515 case BlockedOnGA_NoSend:
3516 fprintf(stderr,"is blocked on global address (no send); local FM_BQ is %p (%s)",
3517 tso->block_info.closure, info_type(tso->block_info.closure));
3520 #if defined(RTS_SUPPORTS_THREADS)
3521 case BlockedOnCCall:
3522 fprintf(stderr,"is blocked on an external call");
3526 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3527 tso->why_blocked, tso->id, tso);
3532 printThreadStatus(StgTSO *tso)
3534 switch (tso->what_next) {
3536 fprintf(stderr,"has been killed");
3538 case ThreadComplete:
3539 fprintf(stderr,"has completed");
3542 printThreadBlockage(tso);
3547 printAllThreads(void)
3552 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3553 ullong_format_string(TIME_ON_PROC(CurrentProc),
3554 time_string, rtsFalse/*no commas!*/);
3556 sched_belch("all threads at [%s]:", time_string);
3558 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3559 ullong_format_string(CURRENT_TIME,
3560 time_string, rtsFalse/*no commas!*/);
3562 sched_belch("all threads at [%s]:", time_string);
3564 sched_belch("all threads:");
3567 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3568 fprintf(stderr, "\tthread %d ", t->id);
3569 if (t->label) fprintf(stderr,"[\"%s\"] ",t->label);
3570 printThreadStatus(t);
3571 fprintf(stderr,"\n");
3576 Print a whole blocking queue attached to node (debugging only).
3581 print_bq (StgClosure *node)
3583 StgBlockingQueueElement *bqe;
3587 fprintf(stderr,"## BQ of closure %p (%s): ",
3588 node, info_type(node));
3590 /* should cover all closures that may have a blocking queue */
3591 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3592 get_itbl(node)->type == FETCH_ME_BQ ||
3593 get_itbl(node)->type == RBH ||
3594 get_itbl(node)->type == MVAR);
3596 ASSERT(node!=(StgClosure*)NULL); // sanity check
3598 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
3602 Print a whole blocking queue starting with the element bqe.
3605 print_bqe (StgBlockingQueueElement *bqe)
3610 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3612 for (end = (bqe==END_BQ_QUEUE);
3613 !end; // iterate until bqe points to a CONSTR
3614 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
3615 bqe = end ? END_BQ_QUEUE : bqe->link) {
3616 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3617 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3618 /* types of closures that may appear in a blocking queue */
3619 ASSERT(get_itbl(bqe)->type == TSO ||
3620 get_itbl(bqe)->type == BLOCKED_FETCH ||
3621 get_itbl(bqe)->type == CONSTR);
3622 /* only BQs of an RBH end with an RBH_Save closure */
3623 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3625 switch (get_itbl(bqe)->type) {
3627 fprintf(stderr," TSO %u (%x),",
3628 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
3631 fprintf(stderr," BF (node=%p, ga=((%x, %d, %x)),",
3632 ((StgBlockedFetch *)bqe)->node,
3633 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
3634 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
3635 ((StgBlockedFetch *)bqe)->ga.weight);
3638 fprintf(stderr," %s (IP %p),",
3639 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3640 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3641 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3642 "RBH_Save_?"), get_itbl(bqe));
3645 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
3646 info_type((StgClosure *)bqe)); // , node, info_type(node));
3650 fputc('\n', stderr);
3652 # elif defined(GRAN)
3654 print_bq (StgClosure *node)
3656 StgBlockingQueueElement *bqe;
3657 PEs node_loc, tso_loc;
3660 /* should cover all closures that may have a blocking queue */
3661 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3662 get_itbl(node)->type == FETCH_ME_BQ ||
3663 get_itbl(node)->type == RBH);
3665 ASSERT(node!=(StgClosure*)NULL); // sanity check
3666 node_loc = where_is(node);
3668 fprintf(stderr,"## BQ of closure %p (%s) on [PE %d]: ",
3669 node, info_type(node), node_loc);
3672 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3674 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
3675 !end; // iterate until bqe points to a CONSTR
3676 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
3677 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3678 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3679 /* types of closures that may appear in a blocking queue */
3680 ASSERT(get_itbl(bqe)->type == TSO ||
3681 get_itbl(bqe)->type == CONSTR);
3682 /* only BQs of an RBH end with an RBH_Save closure */
3683 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3685 tso_loc = where_is((StgClosure *)bqe);
3686 switch (get_itbl(bqe)->type) {
3688 fprintf(stderr," TSO %d (%p) on [PE %d],",
3689 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
3692 fprintf(stderr," %s (IP %p),",
3693 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3694 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3695 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3696 "RBH_Save_?"), get_itbl(bqe));
3699 barf("Unexpected closure type %s in blocking queue of %p (%s)",
3700 info_type((StgClosure *)bqe), node, info_type(node));
3704 fputc('\n', stderr);
3708 Nice and easy: only TSOs on the blocking queue
3711 print_bq (StgClosure *node)
3715 ASSERT(node!=(StgClosure*)NULL); // sanity check
3716 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
3717 tso != END_TSO_QUEUE;
3719 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
3720 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
3721 fprintf(stderr," TSO %d (%p),", tso->id, tso);
3723 fputc('\n', stderr);
3734 for (i=0, tso=run_queue_hd;
3735 tso != END_TSO_QUEUE;
3744 sched_belch(char *s, ...)
3749 fprintf(stderr, "scheduler (task %ld): ", osThreadId());
3751 fprintf(stderr, "== ");
3753 fprintf(stderr, "scheduler: ");
3755 vfprintf(stderr, s, ap);
3756 fprintf(stderr, "\n");
3762 //@node Index, , Debugging Routines, Main scheduling code
3766 //* StgMainThread:: @cindex\s-+StgMainThread
3767 //* awaken_blocked_queue:: @cindex\s-+awaken_blocked_queue
3768 //* blocked_queue_hd:: @cindex\s-+blocked_queue_hd
3769 //* blocked_queue_tl:: @cindex\s-+blocked_queue_tl
3770 //* context_switch:: @cindex\s-+context_switch
3771 //* createThread:: @cindex\s-+createThread
3772 //* gc_pending_cond:: @cindex\s-+gc_pending_cond
3773 //* initScheduler:: @cindex\s-+initScheduler
3774 //* interrupted:: @cindex\s-+interrupted
3775 //* next_thread_id:: @cindex\s-+next_thread_id
3776 //* print_bq:: @cindex\s-+print_bq
3777 //* run_queue_hd:: @cindex\s-+run_queue_hd
3778 //* run_queue_tl:: @cindex\s-+run_queue_tl
3779 //* sched_mutex:: @cindex\s-+sched_mutex
3780 //* schedule:: @cindex\s-+schedule
3781 //* take_off_run_queue:: @cindex\s-+take_off_run_queue
3782 //* term_mutex:: @cindex\s-+term_mutex