1 /* ---------------------------------------------------------------------------
2 * $Id: Schedule.c,v 1.101 2001/10/23 10:54:14 simonmar Exp $
4 * (c) The GHC Team, 1998-2000
8 * Different GHC ways use this scheduler quite differently (see comments below)
9 * Here is the global picture:
11 * WAY Name CPP flag What's it for
12 * --------------------------------------
13 * mp GUM PAR Parallel execution on a distributed memory machine
14 * s SMP SMP Parallel execution on a shared memory machine
15 * mg GranSim GRAN Simulation of parallel execution
16 * md GUM/GdH DIST Distributed execution (based on GUM)
17 * --------------------------------------------------------------------------*/
19 //@node Main scheduling code, , ,
20 //@section Main scheduling code
23 * Version with scheduler monitor support for SMPs (WAY=s):
25 This design provides a high-level API to create and schedule threads etc.
26 as documented in the SMP design document.
28 It uses a monitor design controlled by a single mutex to exercise control
29 over accesses to shared data structures, and builds on the Posix threads
32 The majority of state is shared. In order to keep essential per-task state,
33 there is a Capability structure, which contains all the information
34 needed to run a thread: its STG registers, a pointer to its TSO, a
35 nursery etc. During STG execution, a pointer to the capability is
36 kept in a register (BaseReg).
38 In a non-SMP build, there is one global capability, namely MainRegTable.
42 * Version with support for distributed memory parallelism aka GUM (WAY=mp):
44 The main scheduling loop in GUM iterates until a finish message is received.
45 In that case a global flag @receivedFinish@ is set and this instance of
46 the RTS shuts down. See ghc/rts/parallel/HLComms.c:processMessages()
47 for the handling of incoming messages, such as PP_FINISH.
48 Note that in the parallel case we have a system manager that coordinates
49 different PEs, each of which are running one instance of the RTS.
50 See ghc/rts/parallel/SysMan.c for the main routine of the parallel program.
51 From this routine processes executing ghc/rts/Main.c are spawned. -- HWL
53 * Version with support for simulating parallel execution aka GranSim (WAY=mg):
55 The main scheduling code in GranSim is quite different from that in std
56 (concurrent) Haskell: while concurrent Haskell just iterates over the
57 threads in the runnable queue, GranSim is event driven, i.e. it iterates
58 over the events in the global event queue. -- HWL
63 //* Variables and Data structures::
64 //* Main scheduling loop::
65 //* Suspend and Resume::
67 //* Garbage Collextion Routines::
68 //* Blocking Queue Routines::
69 //* Exception Handling Routines::
70 //* Debugging Routines::
74 //@node Includes, Variables and Data structures, Main scheduling code, Main scheduling code
75 //@subsection Includes
77 #include "PosixSource.h"
84 #include "StgStartup.h"
87 #include "StgMiscClosures.h"
89 #include "Interpreter.h"
90 #include "Exception.h"
98 #if defined(GRAN) || defined(PAR)
99 # include "GranSimRts.h"
100 # include "GranSim.h"
101 # include "ParallelRts.h"
102 # include "Parallel.h"
103 # include "ParallelDebug.h"
104 # include "FetchMe.h"
111 //@node Variables and Data structures, Prototypes, Includes, Main scheduling code
112 //@subsection Variables and Data structures
116 * These are the threads which clients have requested that we run.
118 * In an SMP build, we might have several concurrent clients all
119 * waiting for results, and each one will wait on a condition variable
120 * until the result is available.
122 * In non-SMP, clients are strictly nested: the first client calls
123 * into the RTS, which might call out again to C with a _ccall_GC, and
124 * eventually re-enter the RTS.
126 * Main threads information is kept in a linked list:
128 //@cindex StgMainThread
129 typedef struct StgMainThread_ {
131 SchedulerStatus stat;
134 pthread_cond_t wakeup;
136 struct StgMainThread_ *link;
139 /* Main thread queue.
140 * Locks required: sched_mutex.
142 static StgMainThread *main_threads;
145 * Locks required: sched_mutex.
149 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
150 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
153 In GranSim we have a runable and a blocked queue for each processor.
154 In order to minimise code changes new arrays run_queue_hds/tls
155 are created. run_queue_hd is then a short cut (macro) for
156 run_queue_hds[CurrentProc] (see GranSim.h).
159 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
160 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
161 StgTSO *ccalling_threadss[MAX_PROC];
162 /* We use the same global list of threads (all_threads) in GranSim as in
163 the std RTS (i.e. we are cheating). However, we don't use this list in
164 the GranSim specific code at the moment (so we are only potentially
169 StgTSO *run_queue_hd, *run_queue_tl;
170 StgTSO *blocked_queue_hd, *blocked_queue_tl;
171 StgTSO *sleeping_queue; /* perhaps replace with a hash table? */
175 /* Linked list of all threads.
176 * Used for detecting garbage collected threads.
180 /* Threads suspended in _ccall_GC.
182 static StgTSO *suspended_ccalling_threads;
184 static void GetRoots(evac_fn);
185 static StgTSO *threadStackOverflow(StgTSO *tso);
187 /* KH: The following two flags are shared memory locations. There is no need
188 to lock them, since they are only unset at the end of a scheduler
192 /* flag set by signal handler to precipitate a context switch */
193 //@cindex context_switch
196 /* if this flag is set as well, give up execution */
197 //@cindex interrupted
200 /* Next thread ID to allocate.
201 * Locks required: sched_mutex
203 //@cindex next_thread_id
204 StgThreadID next_thread_id = 1;
207 * Pointers to the state of the current thread.
208 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
209 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
212 /* The smallest stack size that makes any sense is:
213 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
214 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
215 * + 1 (the realworld token for an IO thread)
216 * + 1 (the closure to enter)
218 * A thread with this stack will bomb immediately with a stack
219 * overflow, which will increase its stack size.
222 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 2)
224 /* Free capability list.
225 * Locks required: sched_mutex.
228 //@cindex free_capabilities
229 //@cindex n_free_capabilities
230 Capability *free_capabilities; /* Available capabilities for running threads */
231 nat n_free_capabilities; /* total number of available capabilities */
233 //@cindex MainRegTable
234 Capability MainRegTable; /* for non-SMP, we have one global capability */
241 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
242 * exists - earlier gccs apparently didn't.
249 /* All our current task ids, saved in case we need to kill them later.
256 void addToBlockedQueue ( StgTSO *tso );
258 static void schedule ( void );
259 void interruptStgRts ( void );
261 static StgTSO * createThread_ ( nat size, rtsBool have_lock, StgInt pri );
263 static StgTSO * createThread_ ( nat size, rtsBool have_lock );
266 static void detectBlackHoles ( void );
269 static void sched_belch(char *s, ...);
273 //@cindex sched_mutex
275 //@cindex thread_ready_cond
276 //@cindex gc_pending_cond
277 pthread_mutex_t sched_mutex = PTHREAD_MUTEX_INITIALIZER;
278 pthread_mutex_t term_mutex = PTHREAD_MUTEX_INITIALIZER;
279 pthread_cond_t thread_ready_cond = PTHREAD_COND_INITIALIZER;
280 pthread_cond_t gc_pending_cond = PTHREAD_COND_INITIALIZER;
287 rtsTime TimeOfLastYield;
288 rtsBool emitSchedule = rtsTrue;
292 char *whatNext_strs[] = {
300 char *threadReturnCode_strs[] = {
301 "HeapOverflow", /* might also be StackOverflow */
310 StgTSO * createSparkThread(rtsSpark spark);
311 StgTSO * activateSpark (rtsSpark spark);
315 * The thread state for the main thread.
316 // ToDo: check whether not needed any more
320 //@node Main scheduling loop, Suspend and Resume, Prototypes, Main scheduling code
321 //@subsection Main scheduling loop
323 /* ---------------------------------------------------------------------------
324 Main scheduling loop.
326 We use round-robin scheduling, each thread returning to the
327 scheduler loop when one of these conditions is detected:
330 * timer expires (thread yields)
335 Locking notes: we acquire the scheduler lock once at the beginning
336 of the scheduler loop, and release it when
338 * running a thread, or
339 * waiting for work, or
340 * waiting for a GC to complete.
343 In a GranSim setup this loop iterates over the global event queue.
344 This revolves around the global event queue, which determines what
345 to do next. Therefore, it's more complicated than either the
346 concurrent or the parallel (GUM) setup.
349 GUM iterates over incoming messages.
350 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
351 and sends out a fish whenever it has nothing to do; in-between
352 doing the actual reductions (shared code below) it processes the
353 incoming messages and deals with delayed operations
354 (see PendingFetches).
355 This is not the ugliest code you could imagine, but it's bloody close.
357 ------------------------------------------------------------------------ */
364 StgThreadReturnCode ret;
372 rtsBool receivedFinish = rtsFalse;
374 nat tp_size, sp_size; // stats only
377 rtsBool was_interrupted = rtsFalse;
379 ACQUIRE_LOCK(&sched_mutex);
383 /* set up first event to get things going */
384 /* ToDo: assign costs for system setup and init MainTSO ! */
385 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
387 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
390 fprintf(stderr, "GRAN: Init CurrentTSO (in schedule) = %p\n", CurrentTSO);
391 G_TSO(CurrentTSO, 5));
393 if (RtsFlags.GranFlags.Light) {
394 /* Save current time; GranSim Light only */
395 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
398 event = get_next_event();
400 while (event!=(rtsEvent*)NULL) {
401 /* Choose the processor with the next event */
402 CurrentProc = event->proc;
403 CurrentTSO = event->tso;
407 while (!receivedFinish) { /* set by processMessages */
408 /* when receiving PP_FINISH message */
415 IF_DEBUG(scheduler, printAllThreads());
417 /* If we're interrupted (the user pressed ^C, or some other
418 * termination condition occurred), kill all the currently running
422 IF_DEBUG(scheduler, sched_belch("interrupted"));
424 interrupted = rtsFalse;
425 was_interrupted = rtsTrue;
428 /* Go through the list of main threads and wake up any
429 * clients whose computations have finished. ToDo: this
430 * should be done more efficiently without a linear scan
431 * of the main threads list, somehow...
435 StgMainThread *m, **prev;
436 prev = &main_threads;
437 for (m = main_threads; m != NULL; m = m->link) {
438 switch (m->tso->what_next) {
441 *(m->ret) = (StgClosure *)m->tso->sp[0];
445 pthread_cond_broadcast(&m->wakeup);
449 if (was_interrupted) {
450 m->stat = Interrupted;
454 pthread_cond_broadcast(&m->wakeup);
464 /* in GUM do this only on the Main PE */
467 /* If our main thread has finished or been killed, return.
470 StgMainThread *m = main_threads;
471 if (m->tso->what_next == ThreadComplete
472 || m->tso->what_next == ThreadKilled) {
473 main_threads = main_threads->link;
474 if (m->tso->what_next == ThreadComplete) {
475 /* we finished successfully, fill in the return value */
476 if (m->ret) { *(m->ret) = (StgClosure *)m->tso->sp[0]; };
480 if (was_interrupted) {
481 m->stat = Interrupted;
491 /* Top up the run queue from our spark pool. We try to make the
492 * number of threads in the run queue equal to the number of
497 nat n = n_free_capabilities;
498 StgTSO *tso = run_queue_hd;
500 /* Count the run queue */
501 while (n > 0 && tso != END_TSO_QUEUE) {
508 spark = findSpark(rtsFalse);
510 break; /* no more sparks in the pool */
512 /* I'd prefer this to be done in activateSpark -- HWL */
513 /* tricky - it needs to hold the scheduler lock and
514 * not try to re-acquire it -- SDM */
515 createSparkThread(spark);
517 sched_belch("==^^ turning spark of closure %p into a thread",
518 (StgClosure *)spark));
521 /* We need to wake up the other tasks if we just created some
524 if (n_free_capabilities - n > 1) {
525 pthread_cond_signal(&thread_ready_cond);
530 /* Check whether any waiting threads need to be woken up. If the
531 * run queue is empty, and there are no other tasks running, we
532 * can wait indefinitely for something to happen.
533 * ToDo: what if another client comes along & requests another
536 if (blocked_queue_hd != END_TSO_QUEUE || sleeping_queue != END_TSO_QUEUE) {
538 (run_queue_hd == END_TSO_QUEUE)
540 && (n_free_capabilities == RtsFlags.ParFlags.nNodes)
544 /* we can be interrupted while waiting for I/O... */
545 if (interrupted) continue;
547 /* check for signals each time around the scheduler */
548 #ifndef mingw32_TARGET_OS
549 if (signals_pending()) {
550 start_signal_handlers();
555 * Detect deadlock: when we have no threads to run, there are no
556 * threads waiting on I/O or sleeping, and all the other tasks are
557 * waiting for work, we must have a deadlock of some description.
559 * We first try to find threads blocked on themselves (ie. black
560 * holes), and generate NonTermination exceptions where necessary.
562 * If no threads are black holed, we have a deadlock situation, so
563 * inform all the main threads.
566 if (blocked_queue_hd == END_TSO_QUEUE
567 && run_queue_hd == END_TSO_QUEUE
568 && sleeping_queue == END_TSO_QUEUE
570 && (n_free_capabilities == RtsFlags.ParFlags.nNodes)
574 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
575 GarbageCollect(GetRoots,rtsTrue);
576 if (blocked_queue_hd == END_TSO_QUEUE
577 && run_queue_hd == END_TSO_QUEUE
578 && sleeping_queue == END_TSO_QUEUE) {
579 IF_DEBUG(scheduler, sched_belch("still deadlocked, checking for black holes..."));
581 if (run_queue_hd == END_TSO_QUEUE) {
582 StgMainThread *m = main_threads;
584 for (; m != NULL; m = m->link) {
585 deleteThread(m->tso);
588 pthread_cond_broadcast(&m->wakeup);
592 deleteThread(m->tso);
595 main_threads = m->link;
602 /* ToDo: add deadlock detection in GUM (similar to SMP) -- HWL */
606 /* If there's a GC pending, don't do anything until it has
610 IF_DEBUG(scheduler,sched_belch("waiting for GC"));
611 pthread_cond_wait(&gc_pending_cond, &sched_mutex);
614 /* block until we've got a thread on the run queue and a free
617 while (run_queue_hd == END_TSO_QUEUE || free_capabilities == NULL) {
618 IF_DEBUG(scheduler, sched_belch("waiting for work"));
619 pthread_cond_wait(&thread_ready_cond, &sched_mutex);
620 IF_DEBUG(scheduler, sched_belch("work now available"));
626 if (RtsFlags.GranFlags.Light)
627 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
629 /* adjust time based on time-stamp */
630 if (event->time > CurrentTime[CurrentProc] &&
631 event->evttype != ContinueThread)
632 CurrentTime[CurrentProc] = event->time;
634 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
635 if (!RtsFlags.GranFlags.Light)
638 IF_DEBUG(gran, fprintf(stderr, "GRAN: switch by event-type\n"));
640 /* main event dispatcher in GranSim */
641 switch (event->evttype) {
642 /* Should just be continuing execution */
644 IF_DEBUG(gran, fprintf(stderr, "GRAN: doing ContinueThread\n"));
645 /* ToDo: check assertion
646 ASSERT(run_queue_hd != (StgTSO*)NULL &&
647 run_queue_hd != END_TSO_QUEUE);
649 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
650 if (!RtsFlags.GranFlags.DoAsyncFetch &&
651 procStatus[CurrentProc]==Fetching) {
652 belch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]",
653 CurrentTSO->id, CurrentTSO, CurrentProc);
656 /* Ignore ContinueThreads for completed threads */
657 if (CurrentTSO->what_next == ThreadComplete) {
658 belch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)",
659 CurrentTSO->id, CurrentTSO, CurrentProc);
662 /* Ignore ContinueThreads for threads that are being migrated */
663 if (PROCS(CurrentTSO)==Nowhere) {
664 belch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)",
665 CurrentTSO->id, CurrentTSO, CurrentProc);
668 /* The thread should be at the beginning of the run queue */
669 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
670 belch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread",
671 CurrentTSO->id, CurrentTSO, CurrentProc);
672 break; // run the thread anyway
675 new_event(proc, proc, CurrentTime[proc],
677 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
679 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
680 break; // now actually run the thread; DaH Qu'vam yImuHbej
683 do_the_fetchnode(event);
684 goto next_thread; /* handle next event in event queue */
687 do_the_globalblock(event);
688 goto next_thread; /* handle next event in event queue */
691 do_the_fetchreply(event);
692 goto next_thread; /* handle next event in event queue */
694 case UnblockThread: /* Move from the blocked queue to the tail of */
695 do_the_unblock(event);
696 goto next_thread; /* handle next event in event queue */
698 case ResumeThread: /* Move from the blocked queue to the tail of */
699 /* the runnable queue ( i.e. Qu' SImqa'lu') */
700 event->tso->gran.blocktime +=
701 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
702 do_the_startthread(event);
703 goto next_thread; /* handle next event in event queue */
706 do_the_startthread(event);
707 goto next_thread; /* handle next event in event queue */
710 do_the_movethread(event);
711 goto next_thread; /* handle next event in event queue */
714 do_the_movespark(event);
715 goto next_thread; /* handle next event in event queue */
718 do_the_findwork(event);
719 goto next_thread; /* handle next event in event queue */
722 barf("Illegal event type %u\n", event->evttype);
725 /* This point was scheduler_loop in the old RTS */
727 IF_DEBUG(gran, belch("GRAN: after main switch"));
729 TimeOfLastEvent = CurrentTime[CurrentProc];
730 TimeOfNextEvent = get_time_of_next_event();
731 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
732 // CurrentTSO = ThreadQueueHd;
734 IF_DEBUG(gran, belch("GRAN: time of next event is: %ld",
737 if (RtsFlags.GranFlags.Light)
738 GranSimLight_leave_system(event, &ActiveTSO);
740 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
743 belch("GRAN: end of time-slice is %#lx", EndOfTimeSlice));
745 /* in a GranSim setup the TSO stays on the run queue */
747 /* Take a thread from the run queue. */
748 t = POP_RUN_QUEUE(); // take_off_run_queue(t);
751 fprintf(stderr, "GRAN: About to run current thread, which is\n");
754 context_switch = 0; // turned on via GranYield, checking events and time slice
757 DumpGranEvent(GR_SCHEDULE, t));
759 procStatus[CurrentProc] = Busy;
762 if (PendingFetches != END_BF_QUEUE) {
766 /* ToDo: phps merge with spark activation above */
767 /* check whether we have local work and send requests if we have none */
768 if (EMPTY_RUN_QUEUE()) { /* no runnable threads */
769 /* :-[ no local threads => look out for local sparks */
770 /* the spark pool for the current PE */
771 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
772 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
773 pool->hd < pool->tl) {
775 * ToDo: add GC code check that we really have enough heap afterwards!!
777 * If we're here (no runnable threads) and we have pending
778 * sparks, we must have a space problem. Get enough space
779 * to turn one of those pending sparks into a
783 spark = findSpark(rtsFalse); /* get a spark */
784 if (spark != (rtsSpark) NULL) {
785 tso = activateSpark(spark); /* turn the spark into a thread */
786 IF_PAR_DEBUG(schedule,
787 belch("==== schedule: Created TSO %d (%p); %d threads active",
788 tso->id, tso, advisory_thread_count));
790 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
791 belch("==^^ failed to activate spark");
793 } /* otherwise fall through & pick-up new tso */
795 IF_PAR_DEBUG(verbose,
796 belch("==^^ no local sparks (spark pool contains only NFs: %d)",
797 spark_queue_len(pool)));
802 /* If we still have no work we need to send a FISH to get a spark
805 if (EMPTY_RUN_QUEUE()) {
806 /* =8-[ no local sparks => look for work on other PEs */
808 * We really have absolutely no work. Send out a fish
809 * (there may be some out there already), and wait for
810 * something to arrive. We clearly can't run any threads
811 * until a SCHEDULE or RESUME arrives, and so that's what
812 * we're hoping to see. (Of course, we still have to
813 * respond to other types of messages.)
815 TIME now = msTime() /*CURRENT_TIME*/;
816 IF_PAR_DEBUG(verbose,
817 belch("-- now=%ld", now));
818 IF_PAR_DEBUG(verbose,
819 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
820 (last_fish_arrived_at!=0 &&
821 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
822 belch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)",
823 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
824 last_fish_arrived_at,
825 RtsFlags.ParFlags.fishDelay, now);
828 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
829 (last_fish_arrived_at==0 ||
830 (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
831 /* outstandingFishes is set in sendFish, processFish;
832 avoid flooding system with fishes via delay */
834 sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY,
837 // Global statistics: count no. of fishes
838 if (RtsFlags.ParFlags.ParStats.Global &&
839 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
840 globalParStats.tot_fish_mess++;
844 receivedFinish = processMessages();
847 } else if (PacketsWaiting()) { /* Look for incoming messages */
848 receivedFinish = processMessages();
851 /* Now we are sure that we have some work available */
852 ASSERT(run_queue_hd != END_TSO_QUEUE);
854 /* Take a thread from the run queue, if we have work */
855 t = POP_RUN_QUEUE(); // take_off_run_queue(END_TSO_QUEUE);
856 IF_DEBUG(sanity,checkTSO(t));
858 /* ToDo: write something to the log-file
859 if (RTSflags.ParFlags.granSimStats && !sameThread)
860 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
864 /* the spark pool for the current PE */
865 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
868 belch("--=^ %d threads, %d sparks on [%#x]",
869 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
872 if (0 && RtsFlags.ParFlags.ParStats.Full &&
873 t && LastTSO && t->id != LastTSO->id &&
874 LastTSO->why_blocked == NotBlocked &&
875 LastTSO->what_next != ThreadComplete) {
876 // if previously scheduled TSO not blocked we have to record the context switch
877 DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
878 GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
881 if (RtsFlags.ParFlags.ParStats.Full &&
882 (emitSchedule /* forced emit */ ||
883 (t && LastTSO && t->id != LastTSO->id))) {
885 we are running a different TSO, so write a schedule event to log file
886 NB: If we use fair scheduling we also have to write a deschedule
887 event for LastTSO; with unfair scheduling we know that the
888 previous tso has blocked whenever we switch to another tso, so
889 we don't need it in GUM for now
891 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
892 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
893 emitSchedule = rtsFalse;
897 #else /* !GRAN && !PAR */
899 /* grab a thread from the run queue
901 ASSERT(run_queue_hd != END_TSO_QUEUE);
903 IF_DEBUG(sanity,checkTSO(t));
910 cap = free_capabilities;
911 free_capabilities = cap->link;
912 n_free_capabilities--;
917 cap->rCurrentTSO = t;
919 /* context switches are now initiated by the timer signal, unless
920 * the user specified "context switch as often as possible", with
923 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
924 && (run_queue_hd != END_TSO_QUEUE
925 || blocked_queue_hd != END_TSO_QUEUE
926 || sleeping_queue != END_TSO_QUEUE))
931 RELEASE_LOCK(&sched_mutex);
933 IF_DEBUG(scheduler, sched_belch("-->> Running TSO %ld (%p) %s ...",
934 t->id, t, whatNext_strs[t->what_next]));
936 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
937 /* Run the current thread
939 switch (cap->rCurrentTSO->what_next) {
942 /* Thread already finished, return to scheduler. */
943 ret = ThreadFinished;
946 ret = StgRun((StgFunPtr) stg_enterStackTop, cap);
949 ret = StgRun((StgFunPtr) stg_returnToStackTop, cap);
951 case ThreadEnterInterp:
952 ret = interpretBCO(cap);
955 barf("schedule: invalid what_next field");
957 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
959 /* Costs for the scheduler are assigned to CCS_SYSTEM */
964 ACQUIRE_LOCK(&sched_mutex);
967 IF_DEBUG(scheduler,fprintf(stderr,"scheduler (task %ld): ", pthread_self()););
968 #elif !defined(GRAN) && !defined(PAR)
969 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: "););
971 t = cap->rCurrentTSO;
974 /* HACK 675: if the last thread didn't yield, make sure to print a
975 SCHEDULE event to the log file when StgRunning the next thread, even
976 if it is the same one as before */
978 TimeOfLastYield = CURRENT_TIME;
985 DumpGranEvent(GR_DESCHEDULE, t));
986 globalGranStats.tot_heapover++;
989 //DumpGranEvent(GR_DESCHEDULE, t);
990 globalParStats.tot_heapover++;
992 /* make all the running tasks block on a condition variable,
993 * maybe set context_switch and wait till they all pile in,
994 * then have them wait on a GC condition variable.
996 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: HeapOverflow",
997 t->id, t, whatNext_strs[t->what_next]));
1000 ASSERT(!is_on_queue(t,CurrentProc));
1002 /* Currently we emit a DESCHEDULE event before GC in GUM.
1003 ToDo: either add separate event to distinguish SYSTEM time from rest
1004 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1005 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1006 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1007 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1008 emitSchedule = rtsTrue;
1012 ready_to_gc = rtsTrue;
1013 context_switch = 1; /* stop other threads ASAP */
1014 PUSH_ON_RUN_QUEUE(t);
1015 /* actual GC is done at the end of the while loop */
1021 DumpGranEvent(GR_DESCHEDULE, t));
1022 globalGranStats.tot_stackover++;
1025 // DumpGranEvent(GR_DESCHEDULE, t);
1026 globalParStats.tot_stackover++;
1028 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped, StackOverflow",
1029 t->id, t, whatNext_strs[t->what_next]));
1030 /* just adjust the stack for this thread, then pop it back
1036 /* enlarge the stack */
1037 StgTSO *new_t = threadStackOverflow(t);
1039 /* This TSO has moved, so update any pointers to it from the
1040 * main thread stack. It better not be on any other queues...
1041 * (it shouldn't be).
1043 for (m = main_threads; m != NULL; m = m->link) {
1048 threadPaused(new_t);
1049 PUSH_ON_RUN_QUEUE(new_t);
1053 case ThreadYielding:
1056 DumpGranEvent(GR_DESCHEDULE, t));
1057 globalGranStats.tot_yields++;
1060 // DumpGranEvent(GR_DESCHEDULE, t);
1061 globalParStats.tot_yields++;
1063 /* put the thread back on the run queue. Then, if we're ready to
1064 * GC, check whether this is the last task to stop. If so, wake
1065 * up the GC thread. getThread will block during a GC until the
1069 if (t->what_next == ThreadEnterInterp) {
1070 /* ToDo: or maybe a timer expired when we were in Hugs?
1071 * or maybe someone hit ctrl-C
1073 belch("--<< thread %ld (%p; %s) stopped to switch to Hugs",
1074 t->id, t, whatNext_strs[t->what_next]);
1076 belch("--<< thread %ld (%p; %s) stopped, yielding",
1077 t->id, t, whatNext_strs[t->what_next]);
1084 //belch("&& Doing sanity check on yielding TSO %ld.", t->id);
1086 ASSERT(t->link == END_TSO_QUEUE);
1088 ASSERT(!is_on_queue(t,CurrentProc));
1091 //belch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1092 checkThreadQsSanity(rtsTrue));
1095 if (RtsFlags.ParFlags.doFairScheduling) {
1096 /* this does round-robin scheduling; good for concurrency */
1097 APPEND_TO_RUN_QUEUE(t);
1099 /* this does unfair scheduling; good for parallelism */
1100 PUSH_ON_RUN_QUEUE(t);
1103 /* this does round-robin scheduling; good for concurrency */
1104 APPEND_TO_RUN_QUEUE(t);
1107 /* add a ContinueThread event to actually process the thread */
1108 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1110 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1112 belch("GRAN: eventq and runnableq after adding yielded thread to queue again:");
1121 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1122 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)));
1123 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1125 // ??? needed; should emit block before
1127 DumpGranEvent(GR_DESCHEDULE, t));
1128 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1131 ASSERT(procStatus[CurrentProc]==Busy ||
1132 ((procStatus[CurrentProc]==Fetching) &&
1133 (t->block_info.closure!=(StgClosure*)NULL)));
1134 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1135 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1136 procStatus[CurrentProc]==Fetching))
1137 procStatus[CurrentProc] = Idle;
1141 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: ",
1142 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1145 if (t->block_info.closure!=(StgClosure*)NULL)
1146 print_bq(t->block_info.closure));
1148 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1151 /* whatever we schedule next, we must log that schedule */
1152 emitSchedule = rtsTrue;
1155 /* don't need to do anything. Either the thread is blocked on
1156 * I/O, in which case we'll have called addToBlockedQueue
1157 * previously, or it's blocked on an MVar or Blackhole, in which
1158 * case it'll be on the relevant queue already.
1161 fprintf(stderr, "--<< thread %d (%p) stopped: ", t->id, t);
1162 printThreadBlockage(t);
1163 fprintf(stderr, "\n"));
1165 /* Only for dumping event to log file
1166 ToDo: do I need this in GranSim, too?
1173 case ThreadFinished:
1174 /* Need to check whether this was a main thread, and if so, signal
1175 * the task that started it with the return value. If we have no
1176 * more main threads, we probably need to stop all the tasks until
1179 /* We also end up here if the thread kills itself with an
1180 * uncaught exception, see Exception.hc.
1182 IF_DEBUG(scheduler,belch("--++ thread %d (%p) finished", t->id, t));
1184 endThread(t, CurrentProc); // clean-up the thread
1186 /* For now all are advisory -- HWL */
1187 //if(t->priority==AdvisoryPriority) ??
1188 advisory_thread_count--;
1191 if(t->dist.priority==RevalPriority)
1195 if (RtsFlags.ParFlags.ParStats.Full &&
1196 !RtsFlags.ParFlags.ParStats.Suppressed)
1197 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1202 barf("schedule: invalid thread return code %d", (int)ret);
1206 cap->link = free_capabilities;
1207 free_capabilities = cap;
1208 n_free_capabilities++;
1212 if (ready_to_gc && n_free_capabilities == RtsFlags.ParFlags.nNodes)
1217 /* everybody back, start the GC.
1218 * Could do it in this thread, or signal a condition var
1219 * to do it in another thread. Either way, we need to
1220 * broadcast on gc_pending_cond afterward.
1223 IF_DEBUG(scheduler,sched_belch("doing GC"));
1225 GarbageCollect(GetRoots,rtsFalse);
1226 ready_to_gc = rtsFalse;
1228 pthread_cond_broadcast(&gc_pending_cond);
1231 /* add a ContinueThread event to continue execution of current thread */
1232 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1234 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1236 fprintf(stderr, "GRAN: eventq and runnableq after Garbage collection:\n");
1243 IF_GRAN_DEBUG(unused,
1244 print_eventq(EventHd));
1246 event = get_next_event();
1250 /* ToDo: wait for next message to arrive rather than busy wait */
1255 t = take_off_run_queue(END_TSO_QUEUE);
1258 } /* end of while(1) */
1259 IF_PAR_DEBUG(verbose,
1260 belch("== Leaving schedule() after having received Finish"));
1263 /* ---------------------------------------------------------------------------
1264 * deleteAllThreads(): kill all the live threads.
1266 * This is used when we catch a user interrupt (^C), before performing
1267 * any necessary cleanups and running finalizers.
1268 * ------------------------------------------------------------------------- */
1270 void deleteAllThreads ( void )
1273 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
1274 for (t = run_queue_hd; t != END_TSO_QUEUE; t = t->link) {
1277 for (t = blocked_queue_hd; t != END_TSO_QUEUE; t = t->link) {
1280 for (t = sleeping_queue; t != END_TSO_QUEUE; t = t->link) {
1283 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1284 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
1285 sleeping_queue = END_TSO_QUEUE;
1288 /* startThread and insertThread are now in GranSim.c -- HWL */
1290 //@node Suspend and Resume, Run queue code, Main scheduling loop, Main scheduling code
1291 //@subsection Suspend and Resume
1293 /* ---------------------------------------------------------------------------
1294 * Suspending & resuming Haskell threads.
1296 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1297 * its capability before calling the C function. This allows another
1298 * task to pick up the capability and carry on running Haskell
1299 * threads. It also means that if the C call blocks, it won't lock
1302 * The Haskell thread making the C call is put to sleep for the
1303 * duration of the call, on the susepended_ccalling_threads queue. We
1304 * give out a token to the task, which it can use to resume the thread
1305 * on return from the C function.
1306 * ------------------------------------------------------------------------- */
1309 suspendThread( Capability *cap )
1313 ACQUIRE_LOCK(&sched_mutex);
1316 sched_belch("thread %d did a _ccall_gc", cap->rCurrentTSO->id));
1318 threadPaused(cap->rCurrentTSO);
1319 cap->rCurrentTSO->link = suspended_ccalling_threads;
1320 suspended_ccalling_threads = cap->rCurrentTSO;
1322 /* Use the thread ID as the token; it should be unique */
1323 tok = cap->rCurrentTSO->id;
1326 cap->link = free_capabilities;
1327 free_capabilities = cap;
1328 n_free_capabilities++;
1331 RELEASE_LOCK(&sched_mutex);
1336 resumeThread( StgInt tok )
1338 StgTSO *tso, **prev;
1341 ACQUIRE_LOCK(&sched_mutex);
1343 prev = &suspended_ccalling_threads;
1344 for (tso = suspended_ccalling_threads;
1345 tso != END_TSO_QUEUE;
1346 prev = &tso->link, tso = tso->link) {
1347 if (tso->id == (StgThreadID)tok) {
1352 if (tso == END_TSO_QUEUE) {
1353 barf("resumeThread: thread not found");
1355 tso->link = END_TSO_QUEUE;
1358 while (free_capabilities == NULL) {
1359 IF_DEBUG(scheduler, sched_belch("waiting to resume"));
1360 pthread_cond_wait(&thread_ready_cond, &sched_mutex);
1361 IF_DEBUG(scheduler, sched_belch("resuming thread %d", tso->id));
1363 cap = free_capabilities;
1364 free_capabilities = cap->link;
1365 n_free_capabilities--;
1367 cap = &MainRegTable;
1370 cap->rCurrentTSO = tso;
1372 RELEASE_LOCK(&sched_mutex);
1377 /* ---------------------------------------------------------------------------
1379 * ------------------------------------------------------------------------ */
1380 static void unblockThread(StgTSO *tso);
1382 /* ---------------------------------------------------------------------------
1383 * Comparing Thread ids.
1385 * This is used from STG land in the implementation of the
1386 * instances of Eq/Ord for ThreadIds.
1387 * ------------------------------------------------------------------------ */
1389 int cmp_thread(const StgTSO *tso1, const StgTSO *tso2)
1391 StgThreadID id1 = tso1->id;
1392 StgThreadID id2 = tso2->id;
1394 if (id1 < id2) return (-1);
1395 if (id1 > id2) return 1;
1399 /* ---------------------------------------------------------------------------
1400 Create a new thread.
1402 The new thread starts with the given stack size. Before the
1403 scheduler can run, however, this thread needs to have a closure
1404 (and possibly some arguments) pushed on its stack. See
1405 pushClosure() in Schedule.h.
1407 createGenThread() and createIOThread() (in SchedAPI.h) are
1408 convenient packaged versions of this function.
1410 currently pri (priority) is only used in a GRAN setup -- HWL
1411 ------------------------------------------------------------------------ */
1412 //@cindex createThread
1414 /* currently pri (priority) is only used in a GRAN setup -- HWL */
1416 createThread(nat stack_size, StgInt pri)
1418 return createThread_(stack_size, rtsFalse, pri);
1422 createThread_(nat size, rtsBool have_lock, StgInt pri)
1426 createThread(nat stack_size)
1428 return createThread_(stack_size, rtsFalse);
1432 createThread_(nat size, rtsBool have_lock)
1439 /* First check whether we should create a thread at all */
1441 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1442 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1444 belch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1445 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1446 return END_TSO_QUEUE;
1452 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
1455 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
1457 /* catch ridiculously small stack sizes */
1458 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
1459 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
1462 stack_size = size - TSO_STRUCT_SIZEW;
1464 tso = (StgTSO *)allocate(size);
1465 TICK_ALLOC_TSO(size-TSO_STRUCT_SIZEW, 0);
1467 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
1469 SET_GRAN_HDR(tso, ThisPE);
1471 tso->what_next = ThreadEnterGHC;
1473 /* tso->id needs to be unique. For now we use a heavyweight mutex to
1474 * protect the increment operation on next_thread_id.
1475 * In future, we could use an atomic increment instead.
1477 if (!have_lock) { ACQUIRE_LOCK(&sched_mutex); }
1478 tso->id = next_thread_id++;
1479 if (!have_lock) { RELEASE_LOCK(&sched_mutex); }
1481 tso->why_blocked = NotBlocked;
1482 tso->blocked_exceptions = NULL;
1484 tso->stack_size = stack_size;
1485 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
1487 tso->sp = (P_)&(tso->stack) + stack_size;
1490 tso->prof.CCCS = CCS_MAIN;
1493 /* put a stop frame on the stack */
1494 tso->sp -= sizeofW(StgStopFrame);
1495 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
1496 tso->su = (StgUpdateFrame*)tso->sp;
1500 tso->link = END_TSO_QUEUE;
1501 /* uses more flexible routine in GranSim */
1502 insertThread(tso, CurrentProc);
1504 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
1510 if (RtsFlags.GranFlags.GranSimStats.Full)
1511 DumpGranEvent(GR_START,tso);
1513 if (RtsFlags.ParFlags.ParStats.Full)
1514 DumpGranEvent(GR_STARTQ,tso);
1515 /* HACk to avoid SCHEDULE
1519 /* Link the new thread on the global thread list.
1521 tso->global_link = all_threads;
1525 tso->dist.priority = MandatoryPriority; //by default that is...
1529 tso->gran.pri = pri;
1531 tso->gran.magic = TSO_MAGIC; // debugging only
1533 tso->gran.sparkname = 0;
1534 tso->gran.startedat = CURRENT_TIME;
1535 tso->gran.exported = 0;
1536 tso->gran.basicblocks = 0;
1537 tso->gran.allocs = 0;
1538 tso->gran.exectime = 0;
1539 tso->gran.fetchtime = 0;
1540 tso->gran.fetchcount = 0;
1541 tso->gran.blocktime = 0;
1542 tso->gran.blockcount = 0;
1543 tso->gran.blockedat = 0;
1544 tso->gran.globalsparks = 0;
1545 tso->gran.localsparks = 0;
1546 if (RtsFlags.GranFlags.Light)
1547 tso->gran.clock = Now; /* local clock */
1549 tso->gran.clock = 0;
1551 IF_DEBUG(gran,printTSO(tso));
1554 tso->par.magic = TSO_MAGIC; // debugging only
1556 tso->par.sparkname = 0;
1557 tso->par.startedat = CURRENT_TIME;
1558 tso->par.exported = 0;
1559 tso->par.basicblocks = 0;
1560 tso->par.allocs = 0;
1561 tso->par.exectime = 0;
1562 tso->par.fetchtime = 0;
1563 tso->par.fetchcount = 0;
1564 tso->par.blocktime = 0;
1565 tso->par.blockcount = 0;
1566 tso->par.blockedat = 0;
1567 tso->par.globalsparks = 0;
1568 tso->par.localsparks = 0;
1572 globalGranStats.tot_threads_created++;
1573 globalGranStats.threads_created_on_PE[CurrentProc]++;
1574 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
1575 globalGranStats.tot_sq_probes++;
1577 // collect parallel global statistics (currently done together with GC stats)
1578 if (RtsFlags.ParFlags.ParStats.Global &&
1579 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1580 //fprintf(stderr, "Creating thread %d @ %11.2f\n", tso->id, usertime());
1581 globalParStats.tot_threads_created++;
1587 belch("==__ schedule: Created TSO %d (%p);",
1588 CurrentProc, tso, tso->id));
1590 IF_PAR_DEBUG(verbose,
1591 belch("==__ schedule: Created TSO %d (%p); %d threads active",
1592 tso->id, tso, advisory_thread_count));
1594 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
1595 tso->id, tso->stack_size));
1602 all parallel thread creation calls should fall through the following routine.
1605 createSparkThread(rtsSpark spark)
1607 ASSERT(spark != (rtsSpark)NULL);
1608 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
1610 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1611 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1612 return END_TSO_QUEUE;
1616 tso = createThread_(RtsFlags.GcFlags.initialStkSize, rtsTrue);
1617 if (tso==END_TSO_QUEUE)
1618 barf("createSparkThread: Cannot create TSO");
1620 tso->priority = AdvisoryPriority;
1622 pushClosure(tso,spark);
1623 PUSH_ON_RUN_QUEUE(tso);
1624 advisory_thread_count++;
1631 Turn a spark into a thread.
1632 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
1635 //@cindex activateSpark
1637 activateSpark (rtsSpark spark)
1641 tso = createSparkThread(spark);
1642 if (RtsFlags.ParFlags.ParStats.Full) {
1643 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
1644 IF_PAR_DEBUG(verbose,
1645 belch("==^^ activateSpark: turning spark of closure %p (%s) into a thread",
1646 (StgClosure *)spark, info_type((StgClosure *)spark)));
1648 // ToDo: fwd info on local/global spark to thread -- HWL
1649 // tso->gran.exported = spark->exported;
1650 // tso->gran.locked = !spark->global;
1651 // tso->gran.sparkname = spark->name;
1657 /* ---------------------------------------------------------------------------
1660 * scheduleThread puts a thread on the head of the runnable queue.
1661 * This will usually be done immediately after a thread is created.
1662 * The caller of scheduleThread must create the thread using e.g.
1663 * createThread and push an appropriate closure
1664 * on this thread's stack before the scheduler is invoked.
1665 * ------------------------------------------------------------------------ */
1668 scheduleThread(StgTSO *tso)
1670 if (tso==END_TSO_QUEUE){
1675 ACQUIRE_LOCK(&sched_mutex);
1677 /* Put the new thread on the head of the runnable queue. The caller
1678 * better push an appropriate closure on this thread's stack
1679 * beforehand. In the SMP case, the thread may start running as
1680 * soon as we release the scheduler lock below.
1682 PUSH_ON_RUN_QUEUE(tso);
1686 IF_DEBUG(scheduler,printTSO(tso));
1688 RELEASE_LOCK(&sched_mutex);
1691 /* ---------------------------------------------------------------------------
1694 * Start up Posix threads to run each of the scheduler tasks.
1695 * I believe the task ids are not needed in the system as defined.
1697 * ------------------------------------------------------------------------ */
1699 #if defined(PAR) || defined(SMP)
1701 taskStart(void) /* ( void *arg STG_UNUSED) */
1703 scheduleThread(END_TSO_QUEUE);
1707 /* ---------------------------------------------------------------------------
1710 * Initialise the scheduler. This resets all the queues - if the
1711 * queues contained any threads, they'll be garbage collected at the
1714 * This now calls startTasks(), so should only be called once! KH @ 25/10/99
1715 * ------------------------------------------------------------------------ */
1719 term_handler(int sig STG_UNUSED)
1722 ACQUIRE_LOCK(&term_mutex);
1724 RELEASE_LOCK(&term_mutex);
1729 //@cindex initScheduler
1736 for (i=0; i<=MAX_PROC; i++) {
1737 run_queue_hds[i] = END_TSO_QUEUE;
1738 run_queue_tls[i] = END_TSO_QUEUE;
1739 blocked_queue_hds[i] = END_TSO_QUEUE;
1740 blocked_queue_tls[i] = END_TSO_QUEUE;
1741 ccalling_threadss[i] = END_TSO_QUEUE;
1742 sleeping_queue = END_TSO_QUEUE;
1745 run_queue_hd = END_TSO_QUEUE;
1746 run_queue_tl = END_TSO_QUEUE;
1747 blocked_queue_hd = END_TSO_QUEUE;
1748 blocked_queue_tl = END_TSO_QUEUE;
1749 sleeping_queue = END_TSO_QUEUE;
1752 suspended_ccalling_threads = END_TSO_QUEUE;
1754 main_threads = NULL;
1755 all_threads = END_TSO_QUEUE;
1760 RtsFlags.ConcFlags.ctxtSwitchTicks =
1761 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
1763 /* Install the SIGHUP handler */
1766 struct sigaction action,oact;
1768 action.sa_handler = term_handler;
1769 sigemptyset(&action.sa_mask);
1770 action.sa_flags = 0;
1771 if (sigaction(SIGTERM, &action, &oact) != 0) {
1772 barf("can't install TERM handler");
1778 /* Allocate N Capabilities */
1781 Capability *cap, *prev;
1784 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1785 cap = stgMallocBytes(sizeof(Capability), "initScheduler:capabilities");
1789 free_capabilities = cap;
1790 n_free_capabilities = RtsFlags.ParFlags.nNodes;
1792 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Allocated %d capabilities\n",
1793 n_free_capabilities););
1796 #if defined(SMP) || defined(PAR)
1809 /* make some space for saving all the thread ids */
1810 task_ids = stgMallocBytes(RtsFlags.ParFlags.nNodes * sizeof(task_info),
1811 "initScheduler:task_ids");
1813 /* and create all the threads */
1814 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1815 r = pthread_create(&tid,NULL,taskStart,NULL);
1817 barf("startTasks: Can't create new Posix thread");
1819 task_ids[i].id = tid;
1820 task_ids[i].mut_time = 0.0;
1821 task_ids[i].mut_etime = 0.0;
1822 task_ids[i].gc_time = 0.0;
1823 task_ids[i].gc_etime = 0.0;
1824 task_ids[i].elapsedtimestart = elapsedtime();
1825 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Started task: %ld\n",tid););
1831 exitScheduler( void )
1836 /* Don't want to use pthread_cancel, since we'd have to install
1837 * these silly exception handlers (pthread_cleanup_{push,pop}) around
1841 /* Cancel all our tasks */
1842 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1843 pthread_cancel(task_ids[i].id);
1846 /* Wait for all the tasks to terminate */
1847 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1848 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: waiting for task %ld\n",
1850 pthread_join(task_ids[i].id, NULL);
1854 /* Send 'em all a SIGHUP. That should shut 'em up.
1856 await_death = RtsFlags.ParFlags.nNodes;
1857 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1858 pthread_kill(task_ids[i].id,SIGTERM);
1860 while (await_death > 0) {
1866 /* -----------------------------------------------------------------------------
1867 Managing the per-task allocation areas.
1869 Each capability comes with an allocation area. These are
1870 fixed-length block lists into which allocation can be done.
1872 ToDo: no support for two-space collection at the moment???
1873 -------------------------------------------------------------------------- */
1875 /* -----------------------------------------------------------------------------
1876 * waitThread is the external interface for running a new computation
1877 * and waiting for the result.
1879 * In the non-SMP case, we create a new main thread, push it on the
1880 * main-thread stack, and invoke the scheduler to run it. The
1881 * scheduler will return when the top main thread on the stack has
1882 * completed or died, and fill in the necessary fields of the
1883 * main_thread structure.
1885 * In the SMP case, we create a main thread as before, but we then
1886 * create a new condition variable and sleep on it. When our new
1887 * main thread has completed, we'll be woken up and the status/result
1888 * will be in the main_thread struct.
1889 * -------------------------------------------------------------------------- */
1892 howManyThreadsAvail ( void )
1896 for (q = run_queue_hd; q != END_TSO_QUEUE; q = q->link)
1898 for (q = blocked_queue_hd; q != END_TSO_QUEUE; q = q->link)
1900 for (q = sleeping_queue; q != END_TSO_QUEUE; q = q->link)
1906 finishAllThreads ( void )
1909 while (run_queue_hd != END_TSO_QUEUE) {
1910 waitThread ( run_queue_hd, NULL );
1912 while (blocked_queue_hd != END_TSO_QUEUE) {
1913 waitThread ( blocked_queue_hd, NULL );
1915 while (sleeping_queue != END_TSO_QUEUE) {
1916 waitThread ( blocked_queue_hd, NULL );
1919 (blocked_queue_hd != END_TSO_QUEUE ||
1920 run_queue_hd != END_TSO_QUEUE ||
1921 sleeping_queue != END_TSO_QUEUE);
1925 waitThread(StgTSO *tso, /*out*/StgClosure **ret)
1928 SchedulerStatus stat;
1930 ACQUIRE_LOCK(&sched_mutex);
1932 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
1938 pthread_cond_init(&m->wakeup, NULL);
1941 m->link = main_threads;
1944 IF_DEBUG(scheduler, fprintf(stderr, "== scheduler: new main thread (%d)\n",
1949 pthread_cond_wait(&m->wakeup, &sched_mutex);
1950 } while (m->stat == NoStatus);
1952 /* GranSim specific init */
1953 CurrentTSO = m->tso; // the TSO to run
1954 procStatus[MainProc] = Busy; // status of main PE
1955 CurrentProc = MainProc; // PE to run it on
1960 ASSERT(m->stat != NoStatus);
1966 pthread_cond_destroy(&m->wakeup);
1969 IF_DEBUG(scheduler, fprintf(stderr, "== scheduler: main thread (%d) finished\n",
1973 RELEASE_LOCK(&sched_mutex);
1978 //@node Run queue code, Garbage Collextion Routines, Suspend and Resume, Main scheduling code
1979 //@subsection Run queue code
1983 NB: In GranSim we have many run queues; run_queue_hd is actually a macro
1984 unfolding to run_queue_hds[CurrentProc], thus CurrentProc is an
1985 implicit global variable that has to be correct when calling these
1989 /* Put the new thread on the head of the runnable queue.
1990 * The caller of createThread better push an appropriate closure
1991 * on this thread's stack before the scheduler is invoked.
1993 static /* inline */ void
1994 add_to_run_queue(tso)
1997 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
1998 tso->link = run_queue_hd;
2000 if (run_queue_tl == END_TSO_QUEUE) {
2005 /* Put the new thread at the end of the runnable queue. */
2006 static /* inline */ void
2007 push_on_run_queue(tso)
2010 ASSERT(get_itbl((StgClosure *)tso)->type == TSO);
2011 ASSERT(run_queue_hd!=NULL && run_queue_tl!=NULL);
2012 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2013 if (run_queue_hd == END_TSO_QUEUE) {
2016 run_queue_tl->link = tso;
2022 Should be inlined because it's used very often in schedule. The tso
2023 argument is actually only needed in GranSim, where we want to have the
2024 possibility to schedule *any* TSO on the run queue, irrespective of the
2025 actual ordering. Therefore, if tso is not the nil TSO then we traverse
2026 the run queue and dequeue the tso, adjusting the links in the queue.
2028 //@cindex take_off_run_queue
2029 static /* inline */ StgTSO*
2030 take_off_run_queue(StgTSO *tso) {
2034 qetlaHbogh Qu' ngaSbogh ghomDaQ {tso} yIteq!
2036 if tso is specified, unlink that tso from the run_queue (doesn't have
2037 to be at the beginning of the queue); GranSim only
2039 if (tso!=END_TSO_QUEUE) {
2040 /* find tso in queue */
2041 for (t=run_queue_hd, prev=END_TSO_QUEUE;
2042 t!=END_TSO_QUEUE && t!=tso;
2046 /* now actually dequeue the tso */
2047 if (prev!=END_TSO_QUEUE) {
2048 ASSERT(run_queue_hd!=t);
2049 prev->link = t->link;
2051 /* t is at beginning of thread queue */
2052 ASSERT(run_queue_hd==t);
2053 run_queue_hd = t->link;
2055 /* t is at end of thread queue */
2056 if (t->link==END_TSO_QUEUE) {
2057 ASSERT(t==run_queue_tl);
2058 run_queue_tl = prev;
2060 ASSERT(run_queue_tl!=t);
2062 t->link = END_TSO_QUEUE;
2064 /* take tso from the beginning of the queue; std concurrent code */
2066 if (t != END_TSO_QUEUE) {
2067 run_queue_hd = t->link;
2068 t->link = END_TSO_QUEUE;
2069 if (run_queue_hd == END_TSO_QUEUE) {
2070 run_queue_tl = END_TSO_QUEUE;
2079 //@node Garbage Collextion Routines, Blocking Queue Routines, Run queue code, Main scheduling code
2080 //@subsection Garbage Collextion Routines
2082 /* ---------------------------------------------------------------------------
2083 Where are the roots that we know about?
2085 - all the threads on the runnable queue
2086 - all the threads on the blocked queue
2087 - all the threads on the sleeping queue
2088 - all the thread currently executing a _ccall_GC
2089 - all the "main threads"
2091 ------------------------------------------------------------------------ */
2093 /* This has to be protected either by the scheduler monitor, or by the
2094 garbage collection monitor (probably the latter).
2099 GetRoots(evac_fn evac)
2106 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2107 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2108 evac((StgClosure **)&run_queue_hds[i]);
2109 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2110 evac((StgClosure **)&run_queue_tls[i]);
2112 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2113 evac((StgClosure **)&blocked_queue_hds[i]);
2114 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2115 evac((StgClosure **)&blocked_queue_tls[i]);
2116 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2117 evac((StgClosure **)&ccalling_threads[i]);
2124 if (run_queue_hd != END_TSO_QUEUE) {
2125 ASSERT(run_queue_tl != END_TSO_QUEUE);
2126 evac((StgClosure **)&run_queue_hd);
2127 evac((StgClosure **)&run_queue_tl);
2130 if (blocked_queue_hd != END_TSO_QUEUE) {
2131 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2132 evac((StgClosure **)&blocked_queue_hd);
2133 evac((StgClosure **)&blocked_queue_tl);
2136 if (sleeping_queue != END_TSO_QUEUE) {
2137 evac((StgClosure **)&sleeping_queue);
2141 for (m = main_threads; m != NULL; m = m->link) {
2142 evac((StgClosure **)&m->tso);
2144 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2145 evac((StgClosure **)&suspended_ccalling_threads);
2148 #if defined(SMP) || defined(PAR) || defined(GRAN)
2149 markSparkQueue(evac);
2153 /* -----------------------------------------------------------------------------
2156 This is the interface to the garbage collector from Haskell land.
2157 We provide this so that external C code can allocate and garbage
2158 collect when called from Haskell via _ccall_GC.
2160 It might be useful to provide an interface whereby the programmer
2161 can specify more roots (ToDo).
2163 This needs to be protected by the GC condition variable above. KH.
2164 -------------------------------------------------------------------------- */
2166 void (*extra_roots)(evac_fn);
2171 GarbageCollect(GetRoots,rtsFalse);
2175 performMajorGC(void)
2177 GarbageCollect(GetRoots,rtsTrue);
2181 AllRoots(evac_fn evac)
2183 GetRoots(evac); // the scheduler's roots
2184 extra_roots(evac); // the user's roots
2188 performGCWithRoots(void (*get_roots)(evac_fn))
2190 extra_roots = get_roots;
2191 GarbageCollect(AllRoots,rtsFalse);
2194 /* -----------------------------------------------------------------------------
2197 If the thread has reached its maximum stack size, then raise the
2198 StackOverflow exception in the offending thread. Otherwise
2199 relocate the TSO into a larger chunk of memory and adjust its stack
2201 -------------------------------------------------------------------------- */
2204 threadStackOverflow(StgTSO *tso)
2206 nat new_stack_size, new_tso_size, diff, stack_words;
2210 IF_DEBUG(sanity,checkTSO(tso));
2211 if (tso->stack_size >= tso->max_stack_size) {
2214 belch("@@ threadStackOverflow of TSO %d (%p): stack too large (now %ld; max is %ld",
2215 tso->id, tso, tso->stack_size, tso->max_stack_size);
2216 /* If we're debugging, just print out the top of the stack */
2217 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2220 /* Send this thread the StackOverflow exception */
2221 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2225 /* Try to double the current stack size. If that takes us over the
2226 * maximum stack size for this thread, then use the maximum instead.
2227 * Finally round up so the TSO ends up as a whole number of blocks.
2229 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2230 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2231 TSO_STRUCT_SIZE)/sizeof(W_);
2232 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2233 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2235 IF_DEBUG(scheduler, fprintf(stderr,"== scheduler: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2237 dest = (StgTSO *)allocate(new_tso_size);
2238 TICK_ALLOC_TSO(new_tso_size-sizeofW(StgTSO),0);
2240 /* copy the TSO block and the old stack into the new area */
2241 memcpy(dest,tso,TSO_STRUCT_SIZE);
2242 stack_words = tso->stack + tso->stack_size - tso->sp;
2243 new_sp = (P_)dest + new_tso_size - stack_words;
2244 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2246 /* relocate the stack pointers... */
2247 diff = (P_)new_sp - (P_)tso->sp; /* In *words* */
2248 dest->su = (StgUpdateFrame *) ((P_)dest->su + diff);
2250 dest->stack_size = new_stack_size;
2252 /* and relocate the update frame list */
2253 relocate_stack(dest, diff);
2255 /* Mark the old TSO as relocated. We have to check for relocated
2256 * TSOs in the garbage collector and any primops that deal with TSOs.
2258 * It's important to set the sp and su values to just beyond the end
2259 * of the stack, so we don't attempt to scavenge any part of the
2262 tso->what_next = ThreadRelocated;
2264 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2265 tso->su = (StgUpdateFrame *)tso->sp;
2266 tso->why_blocked = NotBlocked;
2267 dest->mut_link = NULL;
2269 IF_PAR_DEBUG(verbose,
2270 belch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld",
2271 tso->id, tso, tso->stack_size);
2272 /* If we're debugging, just print out the top of the stack */
2273 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2276 IF_DEBUG(sanity,checkTSO(tso));
2278 IF_DEBUG(scheduler,printTSO(dest));
2284 //@node Blocking Queue Routines, Exception Handling Routines, Garbage Collextion Routines, Main scheduling code
2285 //@subsection Blocking Queue Routines
2287 /* ---------------------------------------------------------------------------
2288 Wake up a queue that was blocked on some resource.
2289 ------------------------------------------------------------------------ */
2293 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2298 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2300 /* write RESUME events to log file and
2301 update blocked and fetch time (depending on type of the orig closure) */
2302 if (RtsFlags.ParFlags.ParStats.Full) {
2303 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2304 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2305 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2306 if (EMPTY_RUN_QUEUE())
2307 emitSchedule = rtsTrue;
2309 switch (get_itbl(node)->type) {
2311 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2316 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2323 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2330 static StgBlockingQueueElement *
2331 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2334 PEs node_loc, tso_loc;
2336 node_loc = where_is(node); // should be lifted out of loop
2337 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2338 tso_loc = where_is((StgClosure *)tso);
2339 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2340 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2341 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2342 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2343 // insertThread(tso, node_loc);
2344 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2346 tso, node, (rtsSpark*)NULL);
2347 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2350 } else { // TSO is remote (actually should be FMBQ)
2351 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2352 RtsFlags.GranFlags.Costs.gunblocktime +
2353 RtsFlags.GranFlags.Costs.latency;
2354 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2356 tso, node, (rtsSpark*)NULL);
2357 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2360 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2362 fprintf(stderr," %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2363 (node_loc==tso_loc ? "Local" : "Global"),
2364 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2365 tso->block_info.closure = NULL;
2366 IF_DEBUG(scheduler,belch("-- Waking up thread %ld (%p)",
2370 static StgBlockingQueueElement *
2371 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2373 StgBlockingQueueElement *next;
2375 switch (get_itbl(bqe)->type) {
2377 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2378 /* if it's a TSO just push it onto the run_queue */
2380 // ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2381 PUSH_ON_RUN_QUEUE((StgTSO *)bqe);
2383 unblockCount(bqe, node);
2384 /* reset blocking status after dumping event */
2385 ((StgTSO *)bqe)->why_blocked = NotBlocked;
2389 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2391 bqe->link = (StgBlockingQueueElement *)PendingFetches;
2392 PendingFetches = (StgBlockedFetch *)bqe;
2396 /* can ignore this case in a non-debugging setup;
2397 see comments on RBHSave closures above */
2399 /* check that the closure is an RBHSave closure */
2400 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2401 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2402 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2406 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2407 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
2411 IF_PAR_DEBUG(bq, fprintf(stderr, ", %p (%s)", bqe, info_type((StgClosure*)bqe)));
2415 #else /* !GRAN && !PAR */
2417 unblockOneLocked(StgTSO *tso)
2421 ASSERT(get_itbl(tso)->type == TSO);
2422 ASSERT(tso->why_blocked != NotBlocked);
2423 tso->why_blocked = NotBlocked;
2425 PUSH_ON_RUN_QUEUE(tso);
2427 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
2432 #if defined(GRAN) || defined(PAR)
2433 inline StgBlockingQueueElement *
2434 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2436 ACQUIRE_LOCK(&sched_mutex);
2437 bqe = unblockOneLocked(bqe, node);
2438 RELEASE_LOCK(&sched_mutex);
2443 unblockOne(StgTSO *tso)
2445 ACQUIRE_LOCK(&sched_mutex);
2446 tso = unblockOneLocked(tso);
2447 RELEASE_LOCK(&sched_mutex);
2454 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2456 StgBlockingQueueElement *bqe;
2461 belch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): ", \
2462 node, CurrentProc, CurrentTime[CurrentProc],
2463 CurrentTSO->id, CurrentTSO));
2465 node_loc = where_is(node);
2467 ASSERT(q == END_BQ_QUEUE ||
2468 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
2469 get_itbl(q)->type == CONSTR); // closure (type constructor)
2470 ASSERT(is_unique(node));
2472 /* FAKE FETCH: magically copy the node to the tso's proc;
2473 no Fetch necessary because in reality the node should not have been
2474 moved to the other PE in the first place
2476 if (CurrentProc!=node_loc) {
2478 belch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)",
2479 node, node_loc, CurrentProc, CurrentTSO->id,
2480 // CurrentTSO, where_is(CurrentTSO),
2481 node->header.gran.procs));
2482 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
2484 belch("## new bitmask of node %p is %#x",
2485 node, node->header.gran.procs));
2486 if (RtsFlags.GranFlags.GranSimStats.Global) {
2487 globalGranStats.tot_fake_fetches++;
2492 // ToDo: check: ASSERT(CurrentProc==node_loc);
2493 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
2496 bqe points to the current element in the queue
2497 next points to the next element in the queue
2499 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2500 //tso_loc = where_is(tso);
2502 bqe = unblockOneLocked(bqe, node);
2505 /* if this is the BQ of an RBH, we have to put back the info ripped out of
2506 the closure to make room for the anchor of the BQ */
2507 if (bqe!=END_BQ_QUEUE) {
2508 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
2510 ASSERT((info_ptr==&RBH_Save_0_info) ||
2511 (info_ptr==&RBH_Save_1_info) ||
2512 (info_ptr==&RBH_Save_2_info));
2514 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
2515 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
2516 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
2519 belch("## Filled in RBH_Save for %p (%s) at end of AwBQ",
2520 node, info_type(node)));
2523 /* statistics gathering */
2524 if (RtsFlags.GranFlags.GranSimStats.Global) {
2525 // globalGranStats.tot_bq_processing_time += bq_processing_time;
2526 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
2527 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
2528 globalGranStats.tot_awbq++; // total no. of bqs awakened
2531 fprintf(stderr,"## BQ Stats of %p: [%d entries] %s\n",
2532 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
2536 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2538 StgBlockingQueueElement *bqe;
2540 ACQUIRE_LOCK(&sched_mutex);
2542 IF_PAR_DEBUG(verbose,
2543 belch("##-_ AwBQ for node %p on [%x]: ",
2547 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
2548 IF_PAR_DEBUG(verbose, belch("## ... nothing to unblock so lets just return. RFP (BUG?)"));
2553 ASSERT(q == END_BQ_QUEUE ||
2554 get_itbl(q)->type == TSO ||
2555 get_itbl(q)->type == BLOCKED_FETCH ||
2556 get_itbl(q)->type == CONSTR);
2559 while (get_itbl(bqe)->type==TSO ||
2560 get_itbl(bqe)->type==BLOCKED_FETCH) {
2561 bqe = unblockOneLocked(bqe, node);
2563 RELEASE_LOCK(&sched_mutex);
2566 #else /* !GRAN && !PAR */
2568 awakenBlockedQueue(StgTSO *tso)
2570 ACQUIRE_LOCK(&sched_mutex);
2571 while (tso != END_TSO_QUEUE) {
2572 tso = unblockOneLocked(tso);
2574 RELEASE_LOCK(&sched_mutex);
2578 //@node Exception Handling Routines, Debugging Routines, Blocking Queue Routines, Main scheduling code
2579 //@subsection Exception Handling Routines
2581 /* ---------------------------------------------------------------------------
2583 - usually called inside a signal handler so it mustn't do anything fancy.
2584 ------------------------------------------------------------------------ */
2587 interruptStgRts(void)
2593 /* -----------------------------------------------------------------------------
2596 This is for use when we raise an exception in another thread, which
2598 This has nothing to do with the UnblockThread event in GranSim. -- HWL
2599 -------------------------------------------------------------------------- */
2601 #if defined(GRAN) || defined(PAR)
2603 NB: only the type of the blocking queue is different in GranSim and GUM
2604 the operations on the queue-elements are the same
2605 long live polymorphism!
2608 unblockThread(StgTSO *tso)
2610 StgBlockingQueueElement *t, **last;
2612 ACQUIRE_LOCK(&sched_mutex);
2613 switch (tso->why_blocked) {
2616 return; /* not blocked */
2619 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2621 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
2622 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2624 last = (StgBlockingQueueElement **)&mvar->head;
2625 for (t = (StgBlockingQueueElement *)mvar->head;
2627 last = &t->link, last_tso = t, t = t->link) {
2628 if (t == (StgBlockingQueueElement *)tso) {
2629 *last = (StgBlockingQueueElement *)tso->link;
2630 if (mvar->tail == tso) {
2631 mvar->tail = (StgTSO *)last_tso;
2636 barf("unblockThread (MVAR): TSO not found");
2639 case BlockedOnBlackHole:
2640 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2642 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2644 last = &bq->blocking_queue;
2645 for (t = bq->blocking_queue;
2647 last = &t->link, t = t->link) {
2648 if (t == (StgBlockingQueueElement *)tso) {
2649 *last = (StgBlockingQueueElement *)tso->link;
2653 barf("unblockThread (BLACKHOLE): TSO not found");
2656 case BlockedOnException:
2658 StgTSO *target = tso->block_info.tso;
2660 ASSERT(get_itbl(target)->type == TSO);
2662 if (target->what_next == ThreadRelocated) {
2663 target = target->link;
2664 ASSERT(get_itbl(target)->type == TSO);
2667 ASSERT(target->blocked_exceptions != NULL);
2669 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
2670 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
2672 last = &t->link, t = t->link) {
2673 ASSERT(get_itbl(t)->type == TSO);
2674 if (t == (StgBlockingQueueElement *)tso) {
2675 *last = (StgBlockingQueueElement *)tso->link;
2679 barf("unblockThread (Exception): TSO not found");
2683 case BlockedOnWrite:
2685 /* take TSO off blocked_queue */
2686 StgBlockingQueueElement *prev = NULL;
2687 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
2688 prev = t, t = t->link) {
2689 if (t == (StgBlockingQueueElement *)tso) {
2691 blocked_queue_hd = (StgTSO *)t->link;
2692 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2693 blocked_queue_tl = END_TSO_QUEUE;
2696 prev->link = t->link;
2697 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2698 blocked_queue_tl = (StgTSO *)prev;
2704 barf("unblockThread (I/O): TSO not found");
2707 case BlockedOnDelay:
2709 /* take TSO off sleeping_queue */
2710 StgBlockingQueueElement *prev = NULL;
2711 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
2712 prev = t, t = t->link) {
2713 if (t == (StgBlockingQueueElement *)tso) {
2715 sleeping_queue = (StgTSO *)t->link;
2717 prev->link = t->link;
2722 barf("unblockThread (I/O): TSO not found");
2726 barf("unblockThread");
2730 tso->link = END_TSO_QUEUE;
2731 tso->why_blocked = NotBlocked;
2732 tso->block_info.closure = NULL;
2733 PUSH_ON_RUN_QUEUE(tso);
2734 RELEASE_LOCK(&sched_mutex);
2738 unblockThread(StgTSO *tso)
2742 ACQUIRE_LOCK(&sched_mutex);
2743 switch (tso->why_blocked) {
2746 return; /* not blocked */
2749 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2751 StgTSO *last_tso = END_TSO_QUEUE;
2752 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2755 for (t = mvar->head; t != END_TSO_QUEUE;
2756 last = &t->link, last_tso = t, t = t->link) {
2759 if (mvar->tail == tso) {
2760 mvar->tail = last_tso;
2765 barf("unblockThread (MVAR): TSO not found");
2768 case BlockedOnBlackHole:
2769 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2771 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2773 last = &bq->blocking_queue;
2774 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
2775 last = &t->link, t = t->link) {
2781 barf("unblockThread (BLACKHOLE): TSO not found");
2784 case BlockedOnException:
2786 StgTSO *target = tso->block_info.tso;
2788 ASSERT(get_itbl(target)->type == TSO);
2790 while (target->what_next == ThreadRelocated) {
2791 target = target->link;
2792 ASSERT(get_itbl(target)->type == TSO);
2795 ASSERT(target->blocked_exceptions != NULL);
2797 last = &target->blocked_exceptions;
2798 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
2799 last = &t->link, t = t->link) {
2800 ASSERT(get_itbl(t)->type == TSO);
2806 barf("unblockThread (Exception): TSO not found");
2810 case BlockedOnWrite:
2812 StgTSO *prev = NULL;
2813 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
2814 prev = t, t = t->link) {
2817 blocked_queue_hd = t->link;
2818 if (blocked_queue_tl == t) {
2819 blocked_queue_tl = END_TSO_QUEUE;
2822 prev->link = t->link;
2823 if (blocked_queue_tl == t) {
2824 blocked_queue_tl = prev;
2830 barf("unblockThread (I/O): TSO not found");
2833 case BlockedOnDelay:
2835 StgTSO *prev = NULL;
2836 for (t = sleeping_queue; t != END_TSO_QUEUE;
2837 prev = t, t = t->link) {
2840 sleeping_queue = t->link;
2842 prev->link = t->link;
2847 barf("unblockThread (I/O): TSO not found");
2851 barf("unblockThread");
2855 tso->link = END_TSO_QUEUE;
2856 tso->why_blocked = NotBlocked;
2857 tso->block_info.closure = NULL;
2858 PUSH_ON_RUN_QUEUE(tso);
2859 RELEASE_LOCK(&sched_mutex);
2863 /* -----------------------------------------------------------------------------
2866 * The following function implements the magic for raising an
2867 * asynchronous exception in an existing thread.
2869 * We first remove the thread from any queue on which it might be
2870 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
2872 * We strip the stack down to the innermost CATCH_FRAME, building
2873 * thunks in the heap for all the active computations, so they can
2874 * be restarted if necessary. When we reach a CATCH_FRAME, we build
2875 * an application of the handler to the exception, and push it on
2876 * the top of the stack.
2878 * How exactly do we save all the active computations? We create an
2879 * AP_UPD for every UpdateFrame on the stack. Entering one of these
2880 * AP_UPDs pushes everything from the corresponding update frame
2881 * upwards onto the stack. (Actually, it pushes everything up to the
2882 * next update frame plus a pointer to the next AP_UPD object.
2883 * Entering the next AP_UPD object pushes more onto the stack until we
2884 * reach the last AP_UPD object - at which point the stack should look
2885 * exactly as it did when we killed the TSO and we can continue
2886 * execution by entering the closure on top of the stack.
2888 * We can also kill a thread entirely - this happens if either (a) the
2889 * exception passed to raiseAsync is NULL, or (b) there's no
2890 * CATCH_FRAME on the stack. In either case, we strip the entire
2891 * stack and replace the thread with a zombie.
2893 * -------------------------------------------------------------------------- */
2896 deleteThread(StgTSO *tso)
2898 raiseAsync(tso,NULL);
2902 raiseAsync(StgTSO *tso, StgClosure *exception)
2904 StgUpdateFrame* su = tso->su;
2905 StgPtr sp = tso->sp;
2907 /* Thread already dead? */
2908 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
2912 IF_DEBUG(scheduler, sched_belch("raising exception in thread %ld.", tso->id));
2914 /* Remove it from any blocking queues */
2917 /* The stack freezing code assumes there's a closure pointer on
2918 * the top of the stack. This isn't always the case with compiled
2919 * code, so we have to push a dummy closure on the top which just
2920 * returns to the next return address on the stack.
2922 if ( LOOKS_LIKE_GHC_INFO((void*)*sp) ) {
2923 *(--sp) = (W_)&stg_dummy_ret_closure;
2927 nat words = ((P_)su - (P_)sp) - 1;
2931 /* If we find a CATCH_FRAME, and we've got an exception to raise,
2932 * then build PAP(handler,exception,realworld#), and leave it on
2933 * top of the stack ready to enter.
2935 if (get_itbl(su)->type == CATCH_FRAME && exception != NULL) {
2936 StgCatchFrame *cf = (StgCatchFrame *)su;
2937 /* we've got an exception to raise, so let's pass it to the
2938 * handler in this frame.
2940 ap = (StgAP_UPD *)allocate(sizeofW(StgPAP) + 2);
2941 TICK_ALLOC_UPD_PAP(3,0);
2942 SET_HDR(ap,&stg_PAP_info,cf->header.prof.ccs);
2945 ap->fun = cf->handler; /* :: Exception -> IO a */
2946 ap->payload[0] = exception;
2947 ap->payload[1] = ARG_TAG(0); /* realworld token */
2949 /* throw away the stack from Sp up to and including the
2952 sp = (P_)su + sizeofW(StgCatchFrame) - 1;
2955 /* Restore the blocked/unblocked state for asynchronous exceptions
2956 * at the CATCH_FRAME.
2958 * If exceptions were unblocked at the catch, arrange that they
2959 * are unblocked again after executing the handler by pushing an
2960 * unblockAsyncExceptions_ret stack frame.
2962 if (!cf->exceptions_blocked) {
2963 *(sp--) = (W_)&stg_unblockAsyncExceptionszh_ret_info;
2966 /* Ensure that async exceptions are blocked when running the handler.
2968 if (tso->blocked_exceptions == NULL) {
2969 tso->blocked_exceptions = END_TSO_QUEUE;
2972 /* Put the newly-built PAP on top of the stack, ready to execute
2973 * when the thread restarts.
2977 tso->what_next = ThreadEnterGHC;
2978 IF_DEBUG(sanity, checkTSO(tso));
2982 /* First build an AP_UPD consisting of the stack chunk above the
2983 * current update frame, with the top word on the stack as the
2986 ap = (StgAP_UPD *)allocate(AP_sizeW(words));
2991 ap->fun = (StgClosure *)sp[0];
2993 for(i=0; i < (nat)words; ++i) {
2994 ap->payload[i] = (StgClosure *)*sp++;
2997 switch (get_itbl(su)->type) {
3001 SET_HDR(ap,&stg_AP_UPD_info,su->header.prof.ccs /* ToDo */);
3002 TICK_ALLOC_UP_THK(words+1,0);
3005 fprintf(stderr, "scheduler: Updating ");
3006 printPtr((P_)su->updatee);
3007 fprintf(stderr, " with ");
3008 printObj((StgClosure *)ap);
3011 /* Replace the updatee with an indirection - happily
3012 * this will also wake up any threads currently
3013 * waiting on the result.
3015 * Warning: if we're in a loop, more than one update frame on
3016 * the stack may point to the same object. Be careful not to
3017 * overwrite an IND_OLDGEN in this case, because we'll screw
3018 * up the mutable lists. To be on the safe side, don't
3019 * overwrite any kind of indirection at all. See also
3020 * threadSqueezeStack in GC.c, where we have to make a similar
3023 if (!closure_IND(su->updatee)) {
3024 UPD_IND_NOLOCK(su->updatee,ap); /* revert the black hole */
3027 sp += sizeofW(StgUpdateFrame) -1;
3028 sp[0] = (W_)ap; /* push onto stack */
3034 StgCatchFrame *cf = (StgCatchFrame *)su;
3037 /* We want a PAP, not an AP_UPD. Fortunately, the
3038 * layout's the same.
3040 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3041 TICK_ALLOC_UPD_PAP(words+1,0);
3043 /* now build o = FUN(catch,ap,handler) */
3044 o = (StgClosure *)allocate(sizeofW(StgClosure)+2);
3045 TICK_ALLOC_FUN(2,0);
3046 SET_HDR(o,&stg_catch_info,su->header.prof.ccs /* ToDo */);
3047 o->payload[0] = (StgClosure *)ap;
3048 o->payload[1] = cf->handler;
3051 fprintf(stderr, "scheduler: Built ");
3052 printObj((StgClosure *)o);
3055 /* pop the old handler and put o on the stack */
3057 sp += sizeofW(StgCatchFrame) - 1;
3064 StgSeqFrame *sf = (StgSeqFrame *)su;
3067 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3068 TICK_ALLOC_UPD_PAP(words+1,0);
3070 /* now build o = FUN(seq,ap) */
3071 o = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3072 TICK_ALLOC_SE_THK(1,0);
3073 SET_HDR(o,&stg_seq_info,su->header.prof.ccs /* ToDo */);
3074 o->payload[0] = (StgClosure *)ap;
3077 fprintf(stderr, "scheduler: Built ");
3078 printObj((StgClosure *)o);
3081 /* pop the old handler and put o on the stack */
3083 sp += sizeofW(StgSeqFrame) - 1;
3089 /* We've stripped the entire stack, the thread is now dead. */
3090 sp += sizeofW(StgStopFrame) - 1;
3091 sp[0] = (W_)exception; /* save the exception */
3092 tso->what_next = ThreadKilled;
3093 tso->su = (StgUpdateFrame *)(sp+1);
3104 /* -----------------------------------------------------------------------------
3105 resurrectThreads is called after garbage collection on the list of
3106 threads found to be garbage. Each of these threads will be woken
3107 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3108 on an MVar, or NonTermination if the thread was blocked on a Black
3110 -------------------------------------------------------------------------- */
3113 resurrectThreads( StgTSO *threads )
3117 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3118 next = tso->global_link;
3119 tso->global_link = all_threads;
3121 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3123 switch (tso->why_blocked) {
3125 case BlockedOnException:
3126 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3128 case BlockedOnBlackHole:
3129 raiseAsync(tso,(StgClosure *)NonTermination_closure);
3132 /* This might happen if the thread was blocked on a black hole
3133 * belonging to a thread that we've just woken up (raiseAsync
3134 * can wake up threads, remember...).
3138 barf("resurrectThreads: thread blocked in a strange way");
3143 /* -----------------------------------------------------------------------------
3144 * Blackhole detection: if we reach a deadlock, test whether any
3145 * threads are blocked on themselves. Any threads which are found to
3146 * be self-blocked get sent a NonTermination exception.
3148 * This is only done in a deadlock situation in order to avoid
3149 * performance overhead in the normal case.
3150 * -------------------------------------------------------------------------- */
3153 detectBlackHoles( void )
3155 StgTSO *t = all_threads;
3156 StgUpdateFrame *frame;
3157 StgClosure *blocked_on;
3159 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3161 while (t->what_next == ThreadRelocated) {
3163 ASSERT(get_itbl(t)->type == TSO);
3166 if (t->why_blocked != BlockedOnBlackHole) {
3170 blocked_on = t->block_info.closure;
3172 for (frame = t->su; ; frame = frame->link) {
3173 switch (get_itbl(frame)->type) {
3176 if (frame->updatee == blocked_on) {
3177 /* We are blocking on one of our own computations, so
3178 * send this thread the NonTermination exception.
3181 sched_belch("thread %d is blocked on itself", t->id));
3182 raiseAsync(t, (StgClosure *)NonTermination_closure);
3203 //@node Debugging Routines, Index, Exception Handling Routines, Main scheduling code
3204 //@subsection Debugging Routines
3206 /* -----------------------------------------------------------------------------
3207 Debugging: why is a thread blocked
3208 -------------------------------------------------------------------------- */
3213 printThreadBlockage(StgTSO *tso)
3215 switch (tso->why_blocked) {
3217 fprintf(stderr,"is blocked on read from fd %d", tso->block_info.fd);
3219 case BlockedOnWrite:
3220 fprintf(stderr,"is blocked on write to fd %d", tso->block_info.fd);
3222 case BlockedOnDelay:
3223 fprintf(stderr,"is blocked until %d", tso->block_info.target);
3226 fprintf(stderr,"is blocked on an MVar");
3228 case BlockedOnException:
3229 fprintf(stderr,"is blocked on delivering an exception to thread %d",
3230 tso->block_info.tso->id);
3232 case BlockedOnBlackHole:
3233 fprintf(stderr,"is blocked on a black hole");
3236 fprintf(stderr,"is not blocked");
3240 fprintf(stderr,"is blocked on global address; local FM_BQ is %p (%s)",
3241 tso->block_info.closure, info_type(tso->block_info.closure));
3243 case BlockedOnGA_NoSend:
3244 fprintf(stderr,"is blocked on global address (no send); local FM_BQ is %p (%s)",
3245 tso->block_info.closure, info_type(tso->block_info.closure));
3249 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3250 tso->why_blocked, tso->id, tso);
3255 printThreadStatus(StgTSO *tso)
3257 switch (tso->what_next) {
3259 fprintf(stderr,"has been killed");
3261 case ThreadComplete:
3262 fprintf(stderr,"has completed");
3265 printThreadBlockage(tso);
3270 printAllThreads(void)
3275 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3276 ullong_format_string(TIME_ON_PROC(CurrentProc),
3277 time_string, rtsFalse/*no commas!*/);
3279 sched_belch("all threads at [%s]:", time_string);
3281 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3282 ullong_format_string(CURRENT_TIME,
3283 time_string, rtsFalse/*no commas!*/);
3285 sched_belch("all threads at [%s]:", time_string);
3287 sched_belch("all threads:");
3290 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3291 fprintf(stderr, "\tthread %d ", t->id);
3292 printThreadStatus(t);
3293 fprintf(stderr,"\n");
3298 Print a whole blocking queue attached to node (debugging only).
3303 print_bq (StgClosure *node)
3305 StgBlockingQueueElement *bqe;
3309 fprintf(stderr,"## BQ of closure %p (%s): ",
3310 node, info_type(node));
3312 /* should cover all closures that may have a blocking queue */
3313 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3314 get_itbl(node)->type == FETCH_ME_BQ ||
3315 get_itbl(node)->type == RBH ||
3316 get_itbl(node)->type == MVAR);
3318 ASSERT(node!=(StgClosure*)NULL); // sanity check
3320 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
3324 Print a whole blocking queue starting with the element bqe.
3327 print_bqe (StgBlockingQueueElement *bqe)
3332 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3334 for (end = (bqe==END_BQ_QUEUE);
3335 !end; // iterate until bqe points to a CONSTR
3336 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
3337 bqe = end ? END_BQ_QUEUE : bqe->link) {
3338 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3339 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3340 /* types of closures that may appear in a blocking queue */
3341 ASSERT(get_itbl(bqe)->type == TSO ||
3342 get_itbl(bqe)->type == BLOCKED_FETCH ||
3343 get_itbl(bqe)->type == CONSTR);
3344 /* only BQs of an RBH end with an RBH_Save closure */
3345 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3347 switch (get_itbl(bqe)->type) {
3349 fprintf(stderr," TSO %u (%x),",
3350 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
3353 fprintf(stderr," BF (node=%p, ga=((%x, %d, %x)),",
3354 ((StgBlockedFetch *)bqe)->node,
3355 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
3356 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
3357 ((StgBlockedFetch *)bqe)->ga.weight);
3360 fprintf(stderr," %s (IP %p),",
3361 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3362 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3363 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3364 "RBH_Save_?"), get_itbl(bqe));
3367 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
3368 info_type((StgClosure *)bqe)); // , node, info_type(node));
3372 fputc('\n', stderr);
3374 # elif defined(GRAN)
3376 print_bq (StgClosure *node)
3378 StgBlockingQueueElement *bqe;
3379 PEs node_loc, tso_loc;
3382 /* should cover all closures that may have a blocking queue */
3383 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3384 get_itbl(node)->type == FETCH_ME_BQ ||
3385 get_itbl(node)->type == RBH);
3387 ASSERT(node!=(StgClosure*)NULL); // sanity check
3388 node_loc = where_is(node);
3390 fprintf(stderr,"## BQ of closure %p (%s) on [PE %d]: ",
3391 node, info_type(node), node_loc);
3394 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3396 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
3397 !end; // iterate until bqe points to a CONSTR
3398 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
3399 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3400 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3401 /* types of closures that may appear in a blocking queue */
3402 ASSERT(get_itbl(bqe)->type == TSO ||
3403 get_itbl(bqe)->type == CONSTR);
3404 /* only BQs of an RBH end with an RBH_Save closure */
3405 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3407 tso_loc = where_is((StgClosure *)bqe);
3408 switch (get_itbl(bqe)->type) {
3410 fprintf(stderr," TSO %d (%p) on [PE %d],",
3411 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
3414 fprintf(stderr," %s (IP %p),",
3415 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3416 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3417 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3418 "RBH_Save_?"), get_itbl(bqe));
3421 barf("Unexpected closure type %s in blocking queue of %p (%s)",
3422 info_type((StgClosure *)bqe), node, info_type(node));
3426 fputc('\n', stderr);
3430 Nice and easy: only TSOs on the blocking queue
3433 print_bq (StgClosure *node)
3437 ASSERT(node!=(StgClosure*)NULL); // sanity check
3438 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
3439 tso != END_TSO_QUEUE;
3441 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
3442 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
3443 fprintf(stderr," TSO %d (%p),", tso->id, tso);
3445 fputc('\n', stderr);
3456 for (i=0, tso=run_queue_hd;
3457 tso != END_TSO_QUEUE;
3466 sched_belch(char *s, ...)
3471 fprintf(stderr, "scheduler (task %ld): ", pthread_self());
3473 fprintf(stderr, "== ");
3475 fprintf(stderr, "scheduler: ");
3477 vfprintf(stderr, s, ap);
3478 fprintf(stderr, "\n");
3484 //@node Index, , Debugging Routines, Main scheduling code
3488 //* MainRegTable:: @cindex\s-+MainRegTable
3489 //* StgMainThread:: @cindex\s-+StgMainThread
3490 //* awaken_blocked_queue:: @cindex\s-+awaken_blocked_queue
3491 //* blocked_queue_hd:: @cindex\s-+blocked_queue_hd
3492 //* blocked_queue_tl:: @cindex\s-+blocked_queue_tl
3493 //* context_switch:: @cindex\s-+context_switch
3494 //* createThread:: @cindex\s-+createThread
3495 //* free_capabilities:: @cindex\s-+free_capabilities
3496 //* gc_pending_cond:: @cindex\s-+gc_pending_cond
3497 //* initScheduler:: @cindex\s-+initScheduler
3498 //* interrupted:: @cindex\s-+interrupted
3499 //* n_free_capabilities:: @cindex\s-+n_free_capabilities
3500 //* next_thread_id:: @cindex\s-+next_thread_id
3501 //* print_bq:: @cindex\s-+print_bq
3502 //* run_queue_hd:: @cindex\s-+run_queue_hd
3503 //* run_queue_tl:: @cindex\s-+run_queue_tl
3504 //* sched_mutex:: @cindex\s-+sched_mutex
3505 //* schedule:: @cindex\s-+schedule
3506 //* take_off_run_queue:: @cindex\s-+take_off_run_queue
3507 //* task_ids:: @cindex\s-+task_ids
3508 //* term_mutex:: @cindex\s-+term_mutex
3509 //* thread_ready_cond:: @cindex\s-+thread_ready_cond