1 /* ---------------------------------------------------------------------------
2 * $Id: Schedule.c,v 1.107 2001/11/22 14:25:12 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"
99 #include "Proftimer.h"
100 #include "ProfHeap.h"
101 #include "RetainerProfile.h"
102 #include "LdvProfile.h"
104 #if defined(GRAN) || defined(PAR)
105 # include "GranSimRts.h"
106 # include "GranSim.h"
107 # include "ParallelRts.h"
108 # include "Parallel.h"
109 # include "ParallelDebug.h"
110 # include "FetchMe.h"
117 //@node Variables and Data structures, Prototypes, Includes, Main scheduling code
118 //@subsection Variables and Data structures
122 * These are the threads which clients have requested that we run.
124 * In an SMP build, we might have several concurrent clients all
125 * waiting for results, and each one will wait on a condition variable
126 * until the result is available.
128 * In non-SMP, clients are strictly nested: the first client calls
129 * into the RTS, which might call out again to C with a _ccall_GC, and
130 * eventually re-enter the RTS.
132 * Main threads information is kept in a linked list:
134 //@cindex StgMainThread
135 typedef struct StgMainThread_ {
137 SchedulerStatus stat;
140 pthread_cond_t wakeup;
142 struct StgMainThread_ *link;
145 /* Main thread queue.
146 * Locks required: sched_mutex.
148 static StgMainThread *main_threads;
151 * Locks required: sched_mutex.
155 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
156 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
159 In GranSim we have a runable and a blocked queue for each processor.
160 In order to minimise code changes new arrays run_queue_hds/tls
161 are created. run_queue_hd is then a short cut (macro) for
162 run_queue_hds[CurrentProc] (see GranSim.h).
165 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
166 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
167 StgTSO *ccalling_threadss[MAX_PROC];
168 /* We use the same global list of threads (all_threads) in GranSim as in
169 the std RTS (i.e. we are cheating). However, we don't use this list in
170 the GranSim specific code at the moment (so we are only potentially
175 StgTSO *run_queue_hd, *run_queue_tl;
176 StgTSO *blocked_queue_hd, *blocked_queue_tl;
177 StgTSO *sleeping_queue; /* perhaps replace with a hash table? */
181 /* Linked list of all threads.
182 * Used for detecting garbage collected threads.
186 /* Threads suspended in _ccall_GC.
188 static StgTSO *suspended_ccalling_threads;
190 static StgTSO *threadStackOverflow(StgTSO *tso);
192 /* KH: The following two flags are shared memory locations. There is no need
193 to lock them, since they are only unset at the end of a scheduler
197 /* flag set by signal handler to precipitate a context switch */
198 //@cindex context_switch
201 /* if this flag is set as well, give up execution */
202 //@cindex interrupted
205 /* Next thread ID to allocate.
206 * Locks required: sched_mutex
208 //@cindex next_thread_id
209 StgThreadID next_thread_id = 1;
212 * Pointers to the state of the current thread.
213 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
214 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
217 /* The smallest stack size that makes any sense is:
218 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
219 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
220 * + 1 (the realworld token for an IO thread)
221 * + 1 (the closure to enter)
223 * A thread with this stack will bomb immediately with a stack
224 * overflow, which will increase its stack size.
227 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 2)
229 /* Free capability list.
230 * Locks required: sched_mutex.
233 Capability *free_capabilities; /* Available capabilities for running threads */
234 nat n_free_capabilities; /* total number of available capabilities */
236 Capability MainCapability; /* for non-SMP, we have one global capability */
243 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
244 * exists - earlier gccs apparently didn't.
251 /* All our current task ids, saved in case we need to kill them later.
258 void addToBlockedQueue ( StgTSO *tso );
260 static void schedule ( void );
261 void interruptStgRts ( void );
263 static StgTSO * createThread_ ( nat size, rtsBool have_lock, StgInt pri );
265 static StgTSO * createThread_ ( nat size, rtsBool have_lock );
268 static void detectBlackHoles ( void );
271 static void sched_belch(char *s, ...);
275 //@cindex sched_mutex
277 //@cindex thread_ready_cond
278 //@cindex gc_pending_cond
279 pthread_mutex_t sched_mutex = PTHREAD_MUTEX_INITIALIZER;
280 pthread_mutex_t term_mutex = PTHREAD_MUTEX_INITIALIZER;
281 pthread_cond_t thread_ready_cond = PTHREAD_COND_INITIALIZER;
282 pthread_cond_t gc_pending_cond = PTHREAD_COND_INITIALIZER;
289 rtsTime TimeOfLastYield;
290 rtsBool emitSchedule = rtsTrue;
294 char *whatNext_strs[] = {
302 char *threadReturnCode_strs[] = {
303 "HeapOverflow", /* might also be StackOverflow */
312 StgTSO * createSparkThread(rtsSpark spark);
313 StgTSO * activateSpark (rtsSpark spark);
317 * The thread state for the main thread.
318 // ToDo: check whether not needed any more
322 //@node Main scheduling loop, Suspend and Resume, Prototypes, Main scheduling code
323 //@subsection Main scheduling loop
325 /* ---------------------------------------------------------------------------
326 Main scheduling loop.
328 We use round-robin scheduling, each thread returning to the
329 scheduler loop when one of these conditions is detected:
332 * timer expires (thread yields)
337 Locking notes: we acquire the scheduler lock once at the beginning
338 of the scheduler loop, and release it when
340 * running a thread, or
341 * waiting for work, or
342 * waiting for a GC to complete.
345 In a GranSim setup this loop iterates over the global event queue.
346 This revolves around the global event queue, which determines what
347 to do next. Therefore, it's more complicated than either the
348 concurrent or the parallel (GUM) setup.
351 GUM iterates over incoming messages.
352 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
353 and sends out a fish whenever it has nothing to do; in-between
354 doing the actual reductions (shared code below) it processes the
355 incoming messages and deals with delayed operations
356 (see PendingFetches).
357 This is not the ugliest code you could imagine, but it's bloody close.
359 ------------------------------------------------------------------------ */
366 StgThreadReturnCode ret;
374 rtsBool receivedFinish = rtsFalse;
376 nat tp_size, sp_size; // stats only
379 rtsBool was_interrupted = rtsFalse;
381 ACQUIRE_LOCK(&sched_mutex);
385 /* set up first event to get things going */
386 /* ToDo: assign costs for system setup and init MainTSO ! */
387 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
389 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
392 fprintf(stderr, "GRAN: Init CurrentTSO (in schedule) = %p\n", CurrentTSO);
393 G_TSO(CurrentTSO, 5));
395 if (RtsFlags.GranFlags.Light) {
396 /* Save current time; GranSim Light only */
397 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
400 event = get_next_event();
402 while (event!=(rtsEvent*)NULL) {
403 /* Choose the processor with the next event */
404 CurrentProc = event->proc;
405 CurrentTSO = event->tso;
409 while (!receivedFinish) { /* set by processMessages */
410 /* when receiving PP_FINISH message */
417 IF_DEBUG(scheduler, printAllThreads());
419 /* If we're interrupted (the user pressed ^C, or some other
420 * termination condition occurred), kill all the currently running
424 IF_DEBUG(scheduler, sched_belch("interrupted"));
426 interrupted = rtsFalse;
427 was_interrupted = rtsTrue;
430 /* Go through the list of main threads and wake up any
431 * clients whose computations have finished. ToDo: this
432 * should be done more efficiently without a linear scan
433 * of the main threads list, somehow...
437 StgMainThread *m, **prev;
438 prev = &main_threads;
439 for (m = main_threads; m != NULL; m = m->link) {
440 switch (m->tso->what_next) {
443 *(m->ret) = (StgClosure *)m->tso->sp[0];
447 pthread_cond_broadcast(&m->wakeup);
450 if (m->ret) *(m->ret) = NULL;
452 if (was_interrupted) {
453 m->stat = Interrupted;
457 pthread_cond_broadcast(&m->wakeup);
468 /* in GUM do this only on the Main PE */
471 /* If our main thread has finished or been killed, return.
474 StgMainThread *m = main_threads;
475 if (m->tso->what_next == ThreadComplete
476 || m->tso->what_next == ThreadKilled) {
477 main_threads = main_threads->link;
478 if (m->tso->what_next == ThreadComplete) {
479 /* we finished successfully, fill in the return value */
480 if (m->ret) { *(m->ret) = (StgClosure *)m->tso->sp[0]; };
484 if (m->ret) { *(m->ret) = NULL; };
485 if (was_interrupted) {
486 m->stat = Interrupted;
496 /* Top up the run queue from our spark pool. We try to make the
497 * number of threads in the run queue equal to the number of
502 nat n = n_free_capabilities;
503 StgTSO *tso = run_queue_hd;
505 /* Count the run queue */
506 while (n > 0 && tso != END_TSO_QUEUE) {
513 spark = findSpark(rtsFalse);
515 break; /* no more sparks in the pool */
517 /* I'd prefer this to be done in activateSpark -- HWL */
518 /* tricky - it needs to hold the scheduler lock and
519 * not try to re-acquire it -- SDM */
520 createSparkThread(spark);
522 sched_belch("==^^ turning spark of closure %p into a thread",
523 (StgClosure *)spark));
526 /* We need to wake up the other tasks if we just created some
529 if (n_free_capabilities - n > 1) {
530 pthread_cond_signal(&thread_ready_cond);
535 /* check for signals each time around the scheduler */
536 #ifndef mingw32_TARGET_OS
537 if (signals_pending()) {
538 startSignalHandlers();
542 /* Check whether any waiting threads need to be woken up. If the
543 * run queue is empty, and there are no other tasks running, we
544 * can wait indefinitely for something to happen.
545 * ToDo: what if another client comes along & requests another
548 if (blocked_queue_hd != END_TSO_QUEUE || sleeping_queue != END_TSO_QUEUE) {
550 (run_queue_hd == END_TSO_QUEUE)
552 && (n_free_capabilities == RtsFlags.ParFlags.nNodes)
556 /* we can be interrupted while waiting for I/O... */
557 if (interrupted) continue;
560 * Detect deadlock: when we have no threads to run, there are no
561 * threads waiting on I/O or sleeping, and all the other tasks are
562 * waiting for work, we must have a deadlock of some description.
564 * We first try to find threads blocked on themselves (ie. black
565 * holes), and generate NonTermination exceptions where necessary.
567 * If no threads are black holed, we have a deadlock situation, so
568 * inform all the main threads.
571 if (blocked_queue_hd == END_TSO_QUEUE
572 && run_queue_hd == END_TSO_QUEUE
573 && sleeping_queue == END_TSO_QUEUE
575 && (n_free_capabilities == RtsFlags.ParFlags.nNodes)
579 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
580 GarbageCollect(GetRoots,rtsTrue);
581 if (blocked_queue_hd == END_TSO_QUEUE
582 && run_queue_hd == END_TSO_QUEUE
583 && sleeping_queue == END_TSO_QUEUE) {
584 IF_DEBUG(scheduler, sched_belch("still deadlocked, checking for black holes..."));
586 if (run_queue_hd == END_TSO_QUEUE) {
587 StgMainThread *m = main_threads;
589 for (; m != NULL; m = m->link) {
590 deleteThread(m->tso);
593 pthread_cond_broadcast(&m->wakeup);
597 deleteThread(m->tso);
600 main_threads = m->link;
607 /* ToDo: add deadlock detection in GUM (similar to SMP) -- HWL */
611 /* If there's a GC pending, don't do anything until it has
615 IF_DEBUG(scheduler,sched_belch("waiting for GC"));
616 pthread_cond_wait(&gc_pending_cond, &sched_mutex);
619 /* block until we've got a thread on the run queue and a free
622 while (run_queue_hd == END_TSO_QUEUE || free_capabilities == NULL) {
623 IF_DEBUG(scheduler, sched_belch("waiting for work"));
624 pthread_cond_wait(&thread_ready_cond, &sched_mutex);
625 IF_DEBUG(scheduler, sched_belch("work now available"));
631 if (RtsFlags.GranFlags.Light)
632 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
634 /* adjust time based on time-stamp */
635 if (event->time > CurrentTime[CurrentProc] &&
636 event->evttype != ContinueThread)
637 CurrentTime[CurrentProc] = event->time;
639 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
640 if (!RtsFlags.GranFlags.Light)
643 IF_DEBUG(gran, fprintf(stderr, "GRAN: switch by event-type\n"));
645 /* main event dispatcher in GranSim */
646 switch (event->evttype) {
647 /* Should just be continuing execution */
649 IF_DEBUG(gran, fprintf(stderr, "GRAN: doing ContinueThread\n"));
650 /* ToDo: check assertion
651 ASSERT(run_queue_hd != (StgTSO*)NULL &&
652 run_queue_hd != END_TSO_QUEUE);
654 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
655 if (!RtsFlags.GranFlags.DoAsyncFetch &&
656 procStatus[CurrentProc]==Fetching) {
657 belch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]",
658 CurrentTSO->id, CurrentTSO, CurrentProc);
661 /* Ignore ContinueThreads for completed threads */
662 if (CurrentTSO->what_next == ThreadComplete) {
663 belch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)",
664 CurrentTSO->id, CurrentTSO, CurrentProc);
667 /* Ignore ContinueThreads for threads that are being migrated */
668 if (PROCS(CurrentTSO)==Nowhere) {
669 belch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)",
670 CurrentTSO->id, CurrentTSO, CurrentProc);
673 /* The thread should be at the beginning of the run queue */
674 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
675 belch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread",
676 CurrentTSO->id, CurrentTSO, CurrentProc);
677 break; // run the thread anyway
680 new_event(proc, proc, CurrentTime[proc],
682 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
684 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
685 break; // now actually run the thread; DaH Qu'vam yImuHbej
688 do_the_fetchnode(event);
689 goto next_thread; /* handle next event in event queue */
692 do_the_globalblock(event);
693 goto next_thread; /* handle next event in event queue */
696 do_the_fetchreply(event);
697 goto next_thread; /* handle next event in event queue */
699 case UnblockThread: /* Move from the blocked queue to the tail of */
700 do_the_unblock(event);
701 goto next_thread; /* handle next event in event queue */
703 case ResumeThread: /* Move from the blocked queue to the tail of */
704 /* the runnable queue ( i.e. Qu' SImqa'lu') */
705 event->tso->gran.blocktime +=
706 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
707 do_the_startthread(event);
708 goto next_thread; /* handle next event in event queue */
711 do_the_startthread(event);
712 goto next_thread; /* handle next event in event queue */
715 do_the_movethread(event);
716 goto next_thread; /* handle next event in event queue */
719 do_the_movespark(event);
720 goto next_thread; /* handle next event in event queue */
723 do_the_findwork(event);
724 goto next_thread; /* handle next event in event queue */
727 barf("Illegal event type %u\n", event->evttype);
730 /* This point was scheduler_loop in the old RTS */
732 IF_DEBUG(gran, belch("GRAN: after main switch"));
734 TimeOfLastEvent = CurrentTime[CurrentProc];
735 TimeOfNextEvent = get_time_of_next_event();
736 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
737 // CurrentTSO = ThreadQueueHd;
739 IF_DEBUG(gran, belch("GRAN: time of next event is: %ld",
742 if (RtsFlags.GranFlags.Light)
743 GranSimLight_leave_system(event, &ActiveTSO);
745 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
748 belch("GRAN: end of time-slice is %#lx", EndOfTimeSlice));
750 /* in a GranSim setup the TSO stays on the run queue */
752 /* Take a thread from the run queue. */
753 t = POP_RUN_QUEUE(); // take_off_run_queue(t);
756 fprintf(stderr, "GRAN: About to run current thread, which is\n");
759 context_switch = 0; // turned on via GranYield, checking events and time slice
762 DumpGranEvent(GR_SCHEDULE, t));
764 procStatus[CurrentProc] = Busy;
767 if (PendingFetches != END_BF_QUEUE) {
771 /* ToDo: phps merge with spark activation above */
772 /* check whether we have local work and send requests if we have none */
773 if (EMPTY_RUN_QUEUE()) { /* no runnable threads */
774 /* :-[ no local threads => look out for local sparks */
775 /* the spark pool for the current PE */
776 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
777 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
778 pool->hd < pool->tl) {
780 * ToDo: add GC code check that we really have enough heap afterwards!!
782 * If we're here (no runnable threads) and we have pending
783 * sparks, we must have a space problem. Get enough space
784 * to turn one of those pending sparks into a
788 spark = findSpark(rtsFalse); /* get a spark */
789 if (spark != (rtsSpark) NULL) {
790 tso = activateSpark(spark); /* turn the spark into a thread */
791 IF_PAR_DEBUG(schedule,
792 belch("==== schedule: Created TSO %d (%p); %d threads active",
793 tso->id, tso, advisory_thread_count));
795 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
796 belch("==^^ failed to activate spark");
798 } /* otherwise fall through & pick-up new tso */
800 IF_PAR_DEBUG(verbose,
801 belch("==^^ no local sparks (spark pool contains only NFs: %d)",
802 spark_queue_len(pool)));
807 /* If we still have no work we need to send a FISH to get a spark
810 if (EMPTY_RUN_QUEUE()) {
811 /* =8-[ no local sparks => look for work on other PEs */
813 * We really have absolutely no work. Send out a fish
814 * (there may be some out there already), and wait for
815 * something to arrive. We clearly can't run any threads
816 * until a SCHEDULE or RESUME arrives, and so that's what
817 * we're hoping to see. (Of course, we still have to
818 * respond to other types of messages.)
820 TIME now = msTime() /*CURRENT_TIME*/;
821 IF_PAR_DEBUG(verbose,
822 belch("-- now=%ld", now));
823 IF_PAR_DEBUG(verbose,
824 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
825 (last_fish_arrived_at!=0 &&
826 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
827 belch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)",
828 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
829 last_fish_arrived_at,
830 RtsFlags.ParFlags.fishDelay, now);
833 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
834 (last_fish_arrived_at==0 ||
835 (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
836 /* outstandingFishes is set in sendFish, processFish;
837 avoid flooding system with fishes via delay */
839 sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY,
842 // Global statistics: count no. of fishes
843 if (RtsFlags.ParFlags.ParStats.Global &&
844 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
845 globalParStats.tot_fish_mess++;
849 receivedFinish = processMessages();
852 } else if (PacketsWaiting()) { /* Look for incoming messages */
853 receivedFinish = processMessages();
856 /* Now we are sure that we have some work available */
857 ASSERT(run_queue_hd != END_TSO_QUEUE);
859 /* Take a thread from the run queue, if we have work */
860 t = POP_RUN_QUEUE(); // take_off_run_queue(END_TSO_QUEUE);
861 IF_DEBUG(sanity,checkTSO(t));
863 /* ToDo: write something to the log-file
864 if (RTSflags.ParFlags.granSimStats && !sameThread)
865 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
869 /* the spark pool for the current PE */
870 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
873 belch("--=^ %d threads, %d sparks on [%#x]",
874 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
877 if (0 && RtsFlags.ParFlags.ParStats.Full &&
878 t && LastTSO && t->id != LastTSO->id &&
879 LastTSO->why_blocked == NotBlocked &&
880 LastTSO->what_next != ThreadComplete) {
881 // if previously scheduled TSO not blocked we have to record the context switch
882 DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
883 GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
886 if (RtsFlags.ParFlags.ParStats.Full &&
887 (emitSchedule /* forced emit */ ||
888 (t && LastTSO && t->id != LastTSO->id))) {
890 we are running a different TSO, so write a schedule event to log file
891 NB: If we use fair scheduling we also have to write a deschedule
892 event for LastTSO; with unfair scheduling we know that the
893 previous tso has blocked whenever we switch to another tso, so
894 we don't need it in GUM for now
896 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
897 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
898 emitSchedule = rtsFalse;
902 #else /* !GRAN && !PAR */
904 /* grab a thread from the run queue
906 ASSERT(run_queue_hd != END_TSO_QUEUE);
909 // Sanity check the thread we're about to run. This can be
910 // expensive if there is lots of thread switching going on...
911 IF_DEBUG(sanity,checkTSO(t));
918 cap = free_capabilities;
919 free_capabilities = cap->link;
920 n_free_capabilities--;
922 cap = &MainCapability;
925 cap->r.rCurrentTSO = t;
927 /* context switches are now initiated by the timer signal, unless
928 * the user specified "context switch as often as possible", with
933 RtsFlags.ProfFlags.profileInterval == 0 ||
935 (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
936 && (run_queue_hd != END_TSO_QUEUE
937 || blocked_queue_hd != END_TSO_QUEUE
938 || sleeping_queue != END_TSO_QUEUE)))
943 RELEASE_LOCK(&sched_mutex);
945 IF_DEBUG(scheduler, sched_belch("-->> Running TSO %ld (%p) %s ...",
946 t->id, t, whatNext_strs[t->what_next]));
949 startHeapProfTimer();
952 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
953 /* Run the current thread
955 switch (cap->r.rCurrentTSO->what_next) {
958 /* Thread already finished, return to scheduler. */
959 ret = ThreadFinished;
962 ret = StgRun((StgFunPtr) stg_enterStackTop, &cap->r);
965 ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
967 case ThreadEnterInterp:
968 ret = interpretBCO(cap);
971 barf("schedule: invalid what_next field");
973 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
975 /* Costs for the scheduler are assigned to CCS_SYSTEM */
981 ACQUIRE_LOCK(&sched_mutex);
984 IF_DEBUG(scheduler,fprintf(stderr,"scheduler (task %ld): ", pthread_self()););
985 #elif !defined(GRAN) && !defined(PAR)
986 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: "););
988 t = cap->r.rCurrentTSO;
991 /* HACK 675: if the last thread didn't yield, make sure to print a
992 SCHEDULE event to the log file when StgRunning the next thread, even
993 if it is the same one as before */
995 TimeOfLastYield = CURRENT_TIME;
1001 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
1002 globalGranStats.tot_heapover++;
1004 globalParStats.tot_heapover++;
1007 // did the task ask for a large block?
1008 if (cap->r.rHpAlloc > BLOCK_SIZE_W) {
1009 // if so, get one and push it on the front of the nursery.
1013 blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc * sizeof(W_)) / BLOCK_SIZE;
1015 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: requesting a large block (size %d)",
1017 whatNext_strs[t->what_next], blocks));
1019 // don't do this if it would push us over the
1020 // alloc_blocks_lim limit; we'll GC first.
1021 if (alloc_blocks + blocks < alloc_blocks_lim) {
1023 alloc_blocks += blocks;
1024 bd = allocGroup( blocks );
1026 // link the new group into the list
1027 bd->link = cap->r.rCurrentNursery;
1028 bd->u.back = cap->r.rCurrentNursery->u.back;
1029 if (cap->r.rCurrentNursery->u.back != NULL) {
1030 cap->r.rCurrentNursery->u.back->link = bd;
1032 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1033 g0s0->blocks == cap->r.rNursery);
1034 cap->r.rNursery = g0s0->blocks = bd;
1036 cap->r.rCurrentNursery->u.back = bd;
1038 // initialise it as a nursery block
1042 bd->free = bd->start;
1044 // don't forget to update the block count in g0s0.
1045 g0s0->n_blocks += blocks;
1046 ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1048 // now update the nursery to point to the new block
1049 cap->r.rCurrentNursery = bd;
1051 // we might be unlucky and have another thread get on the
1052 // run queue before us and steal the large block, but in that
1053 // case the thread will just end up requesting another large
1055 PUSH_ON_RUN_QUEUE(t);
1060 /* make all the running tasks block on a condition variable,
1061 * maybe set context_switch and wait till they all pile in,
1062 * then have them wait on a GC condition variable.
1064 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: HeapOverflow",
1065 t->id, t, whatNext_strs[t->what_next]));
1068 ASSERT(!is_on_queue(t,CurrentProc));
1070 /* Currently we emit a DESCHEDULE event before GC in GUM.
1071 ToDo: either add separate event to distinguish SYSTEM time from rest
1072 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1073 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1074 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1075 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1076 emitSchedule = rtsTrue;
1080 ready_to_gc = rtsTrue;
1081 context_switch = 1; /* stop other threads ASAP */
1082 PUSH_ON_RUN_QUEUE(t);
1083 /* actual GC is done at the end of the while loop */
1089 DumpGranEvent(GR_DESCHEDULE, t));
1090 globalGranStats.tot_stackover++;
1093 // DumpGranEvent(GR_DESCHEDULE, t);
1094 globalParStats.tot_stackover++;
1096 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped, StackOverflow",
1097 t->id, t, whatNext_strs[t->what_next]));
1098 /* just adjust the stack for this thread, then pop it back
1104 /* enlarge the stack */
1105 StgTSO *new_t = threadStackOverflow(t);
1107 /* This TSO has moved, so update any pointers to it from the
1108 * main thread stack. It better not be on any other queues...
1109 * (it shouldn't be).
1111 for (m = main_threads; m != NULL; m = m->link) {
1116 threadPaused(new_t);
1117 PUSH_ON_RUN_QUEUE(new_t);
1121 case ThreadYielding:
1124 DumpGranEvent(GR_DESCHEDULE, t));
1125 globalGranStats.tot_yields++;
1128 // DumpGranEvent(GR_DESCHEDULE, t);
1129 globalParStats.tot_yields++;
1131 /* put the thread back on the run queue. Then, if we're ready to
1132 * GC, check whether this is the last task to stop. If so, wake
1133 * up the GC thread. getThread will block during a GC until the
1137 if (t->what_next == ThreadEnterInterp) {
1138 /* ToDo: or maybe a timer expired when we were in Hugs?
1139 * or maybe someone hit ctrl-C
1141 belch("--<< thread %ld (%p; %s) stopped to switch to Hugs",
1142 t->id, t, whatNext_strs[t->what_next]);
1144 belch("--<< thread %ld (%p; %s) stopped, yielding",
1145 t->id, t, whatNext_strs[t->what_next]);
1152 //belch("&& Doing sanity check on yielding TSO %ld.", t->id);
1154 ASSERT(t->link == END_TSO_QUEUE);
1156 ASSERT(!is_on_queue(t,CurrentProc));
1159 //belch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1160 checkThreadQsSanity(rtsTrue));
1163 if (RtsFlags.ParFlags.doFairScheduling) {
1164 /* this does round-robin scheduling; good for concurrency */
1165 APPEND_TO_RUN_QUEUE(t);
1167 /* this does unfair scheduling; good for parallelism */
1168 PUSH_ON_RUN_QUEUE(t);
1171 /* this does round-robin scheduling; good for concurrency */
1172 APPEND_TO_RUN_QUEUE(t);
1175 /* add a ContinueThread event to actually process the thread */
1176 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1178 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1180 belch("GRAN: eventq and runnableq after adding yielded thread to queue again:");
1189 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1190 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)));
1191 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1193 // ??? needed; should emit block before
1195 DumpGranEvent(GR_DESCHEDULE, t));
1196 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1199 ASSERT(procStatus[CurrentProc]==Busy ||
1200 ((procStatus[CurrentProc]==Fetching) &&
1201 (t->block_info.closure!=(StgClosure*)NULL)));
1202 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1203 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1204 procStatus[CurrentProc]==Fetching))
1205 procStatus[CurrentProc] = Idle;
1209 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: ",
1210 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1213 if (t->block_info.closure!=(StgClosure*)NULL)
1214 print_bq(t->block_info.closure));
1216 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1219 /* whatever we schedule next, we must log that schedule */
1220 emitSchedule = rtsTrue;
1223 /* don't need to do anything. Either the thread is blocked on
1224 * I/O, in which case we'll have called addToBlockedQueue
1225 * previously, or it's blocked on an MVar or Blackhole, in which
1226 * case it'll be on the relevant queue already.
1229 fprintf(stderr, "--<< thread %d (%p) stopped: ", t->id, t);
1230 printThreadBlockage(t);
1231 fprintf(stderr, "\n"));
1233 /* Only for dumping event to log file
1234 ToDo: do I need this in GranSim, too?
1241 case ThreadFinished:
1242 /* Need to check whether this was a main thread, and if so, signal
1243 * the task that started it with the return value. If we have no
1244 * more main threads, we probably need to stop all the tasks until
1247 /* We also end up here if the thread kills itself with an
1248 * uncaught exception, see Exception.hc.
1250 IF_DEBUG(scheduler,belch("--++ thread %d (%p) finished", t->id, t));
1252 endThread(t, CurrentProc); // clean-up the thread
1254 /* For now all are advisory -- HWL */
1255 //if(t->priority==AdvisoryPriority) ??
1256 advisory_thread_count--;
1259 if(t->dist.priority==RevalPriority)
1263 if (RtsFlags.ParFlags.ParStats.Full &&
1264 !RtsFlags.ParFlags.ParStats.Suppressed)
1265 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1270 barf("schedule: invalid thread return code %d", (int)ret);
1274 cap->link = free_capabilities;
1275 free_capabilities = cap;
1276 n_free_capabilities++;
1280 if (RtsFlags.ProfFlags.profileInterval==0 || performHeapProfile) {
1281 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER) {
1283 // Note: currently retainer profiling is performed after
1284 // a major garbage collection.
1286 GarbageCollect(GetRoots, rtsTrue);
1288 } else if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
1290 // We have LdvCensus() preceded by a major garbage
1291 // collection because we don't want *genuinely* dead
1292 // closures to be involved in LDV profiling. Another good
1293 // reason is to produce consistent profiling results
1294 // regardless of the interval at which GCs are performed.
1295 // In other words, we want LDV profiling results to be
1296 // completely independent of the GC interval.
1298 GarbageCollect(GetRoots, rtsTrue);
1302 // Normal creator-based heap profile
1304 GarbageCollect(GetRoots, rtsTrue);
1307 performHeapProfile = rtsFalse;
1308 ready_to_gc = rtsFalse; // we already GC'd
1313 if (ready_to_gc && n_free_capabilities == RtsFlags.ParFlags.nNodes)
1318 /* everybody back, start the GC.
1319 * Could do it in this thread, or signal a condition var
1320 * to do it in another thread. Either way, we need to
1321 * broadcast on gc_pending_cond afterward.
1324 IF_DEBUG(scheduler,sched_belch("doing GC"));
1326 GarbageCollect(GetRoots,rtsFalse);
1327 ready_to_gc = rtsFalse;
1329 pthread_cond_broadcast(&gc_pending_cond);
1332 /* add a ContinueThread event to continue execution of current thread */
1333 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1335 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1337 fprintf(stderr, "GRAN: eventq and runnableq after Garbage collection:\n");
1345 IF_GRAN_DEBUG(unused,
1346 print_eventq(EventHd));
1348 event = get_next_event();
1351 /* ToDo: wait for next message to arrive rather than busy wait */
1354 } /* end of while(1) */
1356 IF_PAR_DEBUG(verbose,
1357 belch("== Leaving schedule() after having received Finish"));
1360 /* ---------------------------------------------------------------------------
1361 * deleteAllThreads(): kill all the live threads.
1363 * This is used when we catch a user interrupt (^C), before performing
1364 * any necessary cleanups and running finalizers.
1365 * ------------------------------------------------------------------------- */
1367 void deleteAllThreads ( void )
1370 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
1371 for (t = run_queue_hd; t != END_TSO_QUEUE; t = t->link) {
1374 for (t = blocked_queue_hd; t != END_TSO_QUEUE; t = t->link) {
1377 for (t = sleeping_queue; t != END_TSO_QUEUE; t = t->link) {
1380 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1381 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
1382 sleeping_queue = END_TSO_QUEUE;
1385 /* startThread and insertThread are now in GranSim.c -- HWL */
1387 //@node Suspend and Resume, Run queue code, Main scheduling loop, Main scheduling code
1388 //@subsection Suspend and Resume
1390 /* ---------------------------------------------------------------------------
1391 * Suspending & resuming Haskell threads.
1393 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1394 * its capability before calling the C function. This allows another
1395 * task to pick up the capability and carry on running Haskell
1396 * threads. It also means that if the C call blocks, it won't lock
1399 * The Haskell thread making the C call is put to sleep for the
1400 * duration of the call, on the susepended_ccalling_threads queue. We
1401 * give out a token to the task, which it can use to resume the thread
1402 * on return from the C function.
1403 * ------------------------------------------------------------------------- */
1406 suspendThread( StgRegTable *reg )
1411 // assume that *reg is a pointer to the StgRegTable part of a Capability
1412 cap = (Capability *)((void *)reg - sizeof(StgFunTable));
1414 ACQUIRE_LOCK(&sched_mutex);
1417 sched_belch("thread %d did a _ccall_gc", cap->r.rCurrentTSO->id));
1419 threadPaused(cap->r.rCurrentTSO);
1420 cap->r.rCurrentTSO->link = suspended_ccalling_threads;
1421 suspended_ccalling_threads = cap->r.rCurrentTSO;
1423 /* Use the thread ID as the token; it should be unique */
1424 tok = cap->r.rCurrentTSO->id;
1427 cap->link = free_capabilities;
1428 free_capabilities = cap;
1429 n_free_capabilities++;
1432 RELEASE_LOCK(&sched_mutex);
1437 resumeThread( StgInt tok )
1439 StgTSO *tso, **prev;
1442 ACQUIRE_LOCK(&sched_mutex);
1444 prev = &suspended_ccalling_threads;
1445 for (tso = suspended_ccalling_threads;
1446 tso != END_TSO_QUEUE;
1447 prev = &tso->link, tso = tso->link) {
1448 if (tso->id == (StgThreadID)tok) {
1453 if (tso == END_TSO_QUEUE) {
1454 barf("resumeThread: thread not found");
1456 tso->link = END_TSO_QUEUE;
1459 while (free_capabilities == NULL) {
1460 IF_DEBUG(scheduler, sched_belch("waiting to resume"));
1461 pthread_cond_wait(&thread_ready_cond, &sched_mutex);
1462 IF_DEBUG(scheduler, sched_belch("resuming thread %d", tso->id));
1464 cap = free_capabilities;
1465 free_capabilities = cap->link;
1466 n_free_capabilities--;
1468 cap = &MainCapability;
1471 cap->r.rCurrentTSO = tso;
1473 RELEASE_LOCK(&sched_mutex);
1478 /* ---------------------------------------------------------------------------
1480 * ------------------------------------------------------------------------ */
1481 static void unblockThread(StgTSO *tso);
1483 /* ---------------------------------------------------------------------------
1484 * Comparing Thread ids.
1486 * This is used from STG land in the implementation of the
1487 * instances of Eq/Ord for ThreadIds.
1488 * ------------------------------------------------------------------------ */
1490 int cmp_thread(const StgTSO *tso1, const StgTSO *tso2)
1492 StgThreadID id1 = tso1->id;
1493 StgThreadID id2 = tso2->id;
1495 if (id1 < id2) return (-1);
1496 if (id1 > id2) return 1;
1500 /* ---------------------------------------------------------------------------
1501 * Fetching the ThreadID from an StgTSO.
1503 * This is used in the implementation of Show for ThreadIds.
1504 * ------------------------------------------------------------------------ */
1505 int rts_getThreadId(const StgTSO *tso)
1510 /* ---------------------------------------------------------------------------
1511 Create a new thread.
1513 The new thread starts with the given stack size. Before the
1514 scheduler can run, however, this thread needs to have a closure
1515 (and possibly some arguments) pushed on its stack. See
1516 pushClosure() in Schedule.h.
1518 createGenThread() and createIOThread() (in SchedAPI.h) are
1519 convenient packaged versions of this function.
1521 currently pri (priority) is only used in a GRAN setup -- HWL
1522 ------------------------------------------------------------------------ */
1523 //@cindex createThread
1525 /* currently pri (priority) is only used in a GRAN setup -- HWL */
1527 createThread(nat stack_size, StgInt pri)
1529 return createThread_(stack_size, rtsFalse, pri);
1533 createThread_(nat size, rtsBool have_lock, StgInt pri)
1537 createThread(nat stack_size)
1539 return createThread_(stack_size, rtsFalse);
1543 createThread_(nat size, rtsBool have_lock)
1550 /* First check whether we should create a thread at all */
1552 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1553 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1555 belch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1556 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1557 return END_TSO_QUEUE;
1563 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
1566 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
1568 /* catch ridiculously small stack sizes */
1569 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
1570 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
1573 stack_size = size - TSO_STRUCT_SIZEW;
1575 tso = (StgTSO *)allocate(size);
1576 TICK_ALLOC_TSO(size-TSO_STRUCT_SIZEW, 0);
1578 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
1580 SET_GRAN_HDR(tso, ThisPE);
1582 tso->what_next = ThreadEnterGHC;
1584 /* tso->id needs to be unique. For now we use a heavyweight mutex to
1585 * protect the increment operation on next_thread_id.
1586 * In future, we could use an atomic increment instead.
1588 if (!have_lock) { ACQUIRE_LOCK(&sched_mutex); }
1589 tso->id = next_thread_id++;
1590 if (!have_lock) { RELEASE_LOCK(&sched_mutex); }
1592 tso->why_blocked = NotBlocked;
1593 tso->blocked_exceptions = NULL;
1595 tso->stack_size = stack_size;
1596 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
1598 tso->sp = (P_)&(tso->stack) + stack_size;
1601 tso->prof.CCCS = CCS_MAIN;
1604 /* put a stop frame on the stack */
1605 tso->sp -= sizeofW(StgStopFrame);
1606 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
1607 tso->su = (StgUpdateFrame*)tso->sp;
1611 tso->link = END_TSO_QUEUE;
1612 /* uses more flexible routine in GranSim */
1613 insertThread(tso, CurrentProc);
1615 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
1621 if (RtsFlags.GranFlags.GranSimStats.Full)
1622 DumpGranEvent(GR_START,tso);
1624 if (RtsFlags.ParFlags.ParStats.Full)
1625 DumpGranEvent(GR_STARTQ,tso);
1626 /* HACk to avoid SCHEDULE
1630 /* Link the new thread on the global thread list.
1632 tso->global_link = all_threads;
1636 tso->dist.priority = MandatoryPriority; //by default that is...
1640 tso->gran.pri = pri;
1642 tso->gran.magic = TSO_MAGIC; // debugging only
1644 tso->gran.sparkname = 0;
1645 tso->gran.startedat = CURRENT_TIME;
1646 tso->gran.exported = 0;
1647 tso->gran.basicblocks = 0;
1648 tso->gran.allocs = 0;
1649 tso->gran.exectime = 0;
1650 tso->gran.fetchtime = 0;
1651 tso->gran.fetchcount = 0;
1652 tso->gran.blocktime = 0;
1653 tso->gran.blockcount = 0;
1654 tso->gran.blockedat = 0;
1655 tso->gran.globalsparks = 0;
1656 tso->gran.localsparks = 0;
1657 if (RtsFlags.GranFlags.Light)
1658 tso->gran.clock = Now; /* local clock */
1660 tso->gran.clock = 0;
1662 IF_DEBUG(gran,printTSO(tso));
1665 tso->par.magic = TSO_MAGIC; // debugging only
1667 tso->par.sparkname = 0;
1668 tso->par.startedat = CURRENT_TIME;
1669 tso->par.exported = 0;
1670 tso->par.basicblocks = 0;
1671 tso->par.allocs = 0;
1672 tso->par.exectime = 0;
1673 tso->par.fetchtime = 0;
1674 tso->par.fetchcount = 0;
1675 tso->par.blocktime = 0;
1676 tso->par.blockcount = 0;
1677 tso->par.blockedat = 0;
1678 tso->par.globalsparks = 0;
1679 tso->par.localsparks = 0;
1683 globalGranStats.tot_threads_created++;
1684 globalGranStats.threads_created_on_PE[CurrentProc]++;
1685 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
1686 globalGranStats.tot_sq_probes++;
1688 // collect parallel global statistics (currently done together with GC stats)
1689 if (RtsFlags.ParFlags.ParStats.Global &&
1690 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1691 //fprintf(stderr, "Creating thread %d @ %11.2f\n", tso->id, usertime());
1692 globalParStats.tot_threads_created++;
1698 belch("==__ schedule: Created TSO %d (%p);",
1699 CurrentProc, tso, tso->id));
1701 IF_PAR_DEBUG(verbose,
1702 belch("==__ schedule: Created TSO %d (%p); %d threads active",
1703 tso->id, tso, advisory_thread_count));
1705 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
1706 tso->id, tso->stack_size));
1713 all parallel thread creation calls should fall through the following routine.
1716 createSparkThread(rtsSpark spark)
1718 ASSERT(spark != (rtsSpark)NULL);
1719 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
1721 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1722 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1723 return END_TSO_QUEUE;
1727 tso = createThread_(RtsFlags.GcFlags.initialStkSize, rtsTrue);
1728 if (tso==END_TSO_QUEUE)
1729 barf("createSparkThread: Cannot create TSO");
1731 tso->priority = AdvisoryPriority;
1733 pushClosure(tso,spark);
1734 PUSH_ON_RUN_QUEUE(tso);
1735 advisory_thread_count++;
1742 Turn a spark into a thread.
1743 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
1746 //@cindex activateSpark
1748 activateSpark (rtsSpark spark)
1752 tso = createSparkThread(spark);
1753 if (RtsFlags.ParFlags.ParStats.Full) {
1754 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
1755 IF_PAR_DEBUG(verbose,
1756 belch("==^^ activateSpark: turning spark of closure %p (%s) into a thread",
1757 (StgClosure *)spark, info_type((StgClosure *)spark)));
1759 // ToDo: fwd info on local/global spark to thread -- HWL
1760 // tso->gran.exported = spark->exported;
1761 // tso->gran.locked = !spark->global;
1762 // tso->gran.sparkname = spark->name;
1768 /* ---------------------------------------------------------------------------
1771 * scheduleThread puts a thread on the head of the runnable queue.
1772 * This will usually be done immediately after a thread is created.
1773 * The caller of scheduleThread must create the thread using e.g.
1774 * createThread and push an appropriate closure
1775 * on this thread's stack before the scheduler is invoked.
1776 * ------------------------------------------------------------------------ */
1779 scheduleThread(StgTSO *tso)
1781 if (tso==END_TSO_QUEUE){
1786 ACQUIRE_LOCK(&sched_mutex);
1788 /* Put the new thread on the head of the runnable queue. The caller
1789 * better push an appropriate closure on this thread's stack
1790 * beforehand. In the SMP case, the thread may start running as
1791 * soon as we release the scheduler lock below.
1793 PUSH_ON_RUN_QUEUE(tso);
1797 IF_DEBUG(scheduler,printTSO(tso));
1799 RELEASE_LOCK(&sched_mutex);
1802 /* ---------------------------------------------------------------------------
1805 * Start up Posix threads to run each of the scheduler tasks.
1806 * I believe the task ids are not needed in the system as defined.
1808 * ------------------------------------------------------------------------ */
1810 #if defined(PAR) || defined(SMP)
1812 taskStart(void) /* ( void *arg STG_UNUSED) */
1814 scheduleThread(END_TSO_QUEUE);
1818 /* ---------------------------------------------------------------------------
1821 * Initialise the scheduler. This resets all the queues - if the
1822 * queues contained any threads, they'll be garbage collected at the
1825 * This now calls startTasks(), so should only be called once! KH @ 25/10/99
1826 * ------------------------------------------------------------------------ */
1830 term_handler(int sig STG_UNUSED)
1833 ACQUIRE_LOCK(&term_mutex);
1835 RELEASE_LOCK(&term_mutex);
1841 initCapability( Capability *cap )
1843 cap->f.stgChk0 = (F_)__stg_chk_0;
1844 cap->f.stgChk1 = (F_)__stg_chk_1;
1845 cap->f.stgGCEnter1 = (F_)__stg_gc_enter_1;
1846 cap->f.stgUpdatePAP = (F_)__stg_update_PAP;
1855 for (i=0; i<=MAX_PROC; i++) {
1856 run_queue_hds[i] = END_TSO_QUEUE;
1857 run_queue_tls[i] = END_TSO_QUEUE;
1858 blocked_queue_hds[i] = END_TSO_QUEUE;
1859 blocked_queue_tls[i] = END_TSO_QUEUE;
1860 ccalling_threadss[i] = END_TSO_QUEUE;
1861 sleeping_queue = END_TSO_QUEUE;
1864 run_queue_hd = END_TSO_QUEUE;
1865 run_queue_tl = END_TSO_QUEUE;
1866 blocked_queue_hd = END_TSO_QUEUE;
1867 blocked_queue_tl = END_TSO_QUEUE;
1868 sleeping_queue = END_TSO_QUEUE;
1871 suspended_ccalling_threads = END_TSO_QUEUE;
1873 main_threads = NULL;
1874 all_threads = END_TSO_QUEUE;
1879 RtsFlags.ConcFlags.ctxtSwitchTicks =
1880 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
1882 /* Install the SIGHUP handler */
1885 struct sigaction action,oact;
1887 action.sa_handler = term_handler;
1888 sigemptyset(&action.sa_mask);
1889 action.sa_flags = 0;
1890 if (sigaction(SIGTERM, &action, &oact) != 0) {
1891 barf("can't install TERM handler");
1897 /* Allocate N Capabilities */
1900 Capability *cap, *prev;
1903 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1904 cap = stgMallocBytes(sizeof(Capability), "initScheduler:capabilities");
1905 initCapability(cap);
1909 free_capabilities = cap;
1910 n_free_capabilities = RtsFlags.ParFlags.nNodes;
1912 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Allocated %d capabilities\n",
1913 n_free_capabilities););
1915 initCapability(&MainCapability);
1918 #if defined(SMP) || defined(PAR)
1931 /* make some space for saving all the thread ids */
1932 task_ids = stgMallocBytes(RtsFlags.ParFlags.nNodes * sizeof(task_info),
1933 "initScheduler:task_ids");
1935 /* and create all the threads */
1936 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1937 r = pthread_create(&tid,NULL,taskStart,NULL);
1939 barf("startTasks: Can't create new Posix thread");
1941 task_ids[i].id = tid;
1942 task_ids[i].mut_time = 0.0;
1943 task_ids[i].mut_etime = 0.0;
1944 task_ids[i].gc_time = 0.0;
1945 task_ids[i].gc_etime = 0.0;
1946 task_ids[i].elapsedtimestart = elapsedtime();
1947 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Started task: %ld\n",tid););
1953 exitScheduler( void )
1958 /* Don't want to use pthread_cancel, since we'd have to install
1959 * these silly exception handlers (pthread_cleanup_{push,pop}) around
1963 /* Cancel all our tasks */
1964 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1965 pthread_cancel(task_ids[i].id);
1968 /* Wait for all the tasks to terminate */
1969 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1970 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: waiting for task %ld\n",
1972 pthread_join(task_ids[i].id, NULL);
1976 /* Send 'em all a SIGHUP. That should shut 'em up.
1978 await_death = RtsFlags.ParFlags.nNodes;
1979 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1980 pthread_kill(task_ids[i].id,SIGTERM);
1982 while (await_death > 0) {
1988 /* -----------------------------------------------------------------------------
1989 Managing the per-task allocation areas.
1991 Each capability comes with an allocation area. These are
1992 fixed-length block lists into which allocation can be done.
1994 ToDo: no support for two-space collection at the moment???
1995 -------------------------------------------------------------------------- */
1997 /* -----------------------------------------------------------------------------
1998 * waitThread is the external interface for running a new computation
1999 * and waiting for the result.
2001 * In the non-SMP case, we create a new main thread, push it on the
2002 * main-thread stack, and invoke the scheduler to run it. The
2003 * scheduler will return when the top main thread on the stack has
2004 * completed or died, and fill in the necessary fields of the
2005 * main_thread structure.
2007 * In the SMP case, we create a main thread as before, but we then
2008 * create a new condition variable and sleep on it. When our new
2009 * main thread has completed, we'll be woken up and the status/result
2010 * will be in the main_thread struct.
2011 * -------------------------------------------------------------------------- */
2014 howManyThreadsAvail ( void )
2018 for (q = run_queue_hd; q != END_TSO_QUEUE; q = q->link)
2020 for (q = blocked_queue_hd; q != END_TSO_QUEUE; q = q->link)
2022 for (q = sleeping_queue; q != END_TSO_QUEUE; q = q->link)
2028 finishAllThreads ( void )
2031 while (run_queue_hd != END_TSO_QUEUE) {
2032 waitThread ( run_queue_hd, NULL );
2034 while (blocked_queue_hd != END_TSO_QUEUE) {
2035 waitThread ( blocked_queue_hd, NULL );
2037 while (sleeping_queue != END_TSO_QUEUE) {
2038 waitThread ( blocked_queue_hd, NULL );
2041 (blocked_queue_hd != END_TSO_QUEUE ||
2042 run_queue_hd != END_TSO_QUEUE ||
2043 sleeping_queue != END_TSO_QUEUE);
2047 waitThread(StgTSO *tso, /*out*/StgClosure **ret)
2050 SchedulerStatus stat;
2052 ACQUIRE_LOCK(&sched_mutex);
2054 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2060 pthread_cond_init(&m->wakeup, NULL);
2063 m->link = main_threads;
2066 IF_DEBUG(scheduler, fprintf(stderr, "== scheduler: new main thread (%d)\n",
2071 pthread_cond_wait(&m->wakeup, &sched_mutex);
2072 } while (m->stat == NoStatus);
2074 /* GranSim specific init */
2075 CurrentTSO = m->tso; // the TSO to run
2076 procStatus[MainProc] = Busy; // status of main PE
2077 CurrentProc = MainProc; // PE to run it on
2082 ASSERT(m->stat != NoStatus);
2088 pthread_cond_destroy(&m->wakeup);
2091 IF_DEBUG(scheduler, fprintf(stderr, "== scheduler: main thread (%d) finished\n",
2095 RELEASE_LOCK(&sched_mutex);
2100 //@node Run queue code, Garbage Collextion Routines, Suspend and Resume, Main scheduling code
2101 //@subsection Run queue code
2105 NB: In GranSim we have many run queues; run_queue_hd is actually a macro
2106 unfolding to run_queue_hds[CurrentProc], thus CurrentProc is an
2107 implicit global variable that has to be correct when calling these
2111 /* Put the new thread on the head of the runnable queue.
2112 * The caller of createThread better push an appropriate closure
2113 * on this thread's stack before the scheduler is invoked.
2115 static /* inline */ void
2116 add_to_run_queue(tso)
2119 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2120 tso->link = run_queue_hd;
2122 if (run_queue_tl == END_TSO_QUEUE) {
2127 /* Put the new thread at the end of the runnable queue. */
2128 static /* inline */ void
2129 push_on_run_queue(tso)
2132 ASSERT(get_itbl((StgClosure *)tso)->type == TSO);
2133 ASSERT(run_queue_hd!=NULL && run_queue_tl!=NULL);
2134 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2135 if (run_queue_hd == END_TSO_QUEUE) {
2138 run_queue_tl->link = tso;
2144 Should be inlined because it's used very often in schedule. The tso
2145 argument is actually only needed in GranSim, where we want to have the
2146 possibility to schedule *any* TSO on the run queue, irrespective of the
2147 actual ordering. Therefore, if tso is not the nil TSO then we traverse
2148 the run queue and dequeue the tso, adjusting the links in the queue.
2150 //@cindex take_off_run_queue
2151 static /* inline */ StgTSO*
2152 take_off_run_queue(StgTSO *tso) {
2156 qetlaHbogh Qu' ngaSbogh ghomDaQ {tso} yIteq!
2158 if tso is specified, unlink that tso from the run_queue (doesn't have
2159 to be at the beginning of the queue); GranSim only
2161 if (tso!=END_TSO_QUEUE) {
2162 /* find tso in queue */
2163 for (t=run_queue_hd, prev=END_TSO_QUEUE;
2164 t!=END_TSO_QUEUE && t!=tso;
2168 /* now actually dequeue the tso */
2169 if (prev!=END_TSO_QUEUE) {
2170 ASSERT(run_queue_hd!=t);
2171 prev->link = t->link;
2173 /* t is at beginning of thread queue */
2174 ASSERT(run_queue_hd==t);
2175 run_queue_hd = t->link;
2177 /* t is at end of thread queue */
2178 if (t->link==END_TSO_QUEUE) {
2179 ASSERT(t==run_queue_tl);
2180 run_queue_tl = prev;
2182 ASSERT(run_queue_tl!=t);
2184 t->link = END_TSO_QUEUE;
2186 /* take tso from the beginning of the queue; std concurrent code */
2188 if (t != END_TSO_QUEUE) {
2189 run_queue_hd = t->link;
2190 t->link = END_TSO_QUEUE;
2191 if (run_queue_hd == END_TSO_QUEUE) {
2192 run_queue_tl = END_TSO_QUEUE;
2201 //@node Garbage Collextion Routines, Blocking Queue Routines, Run queue code, Main scheduling code
2202 //@subsection Garbage Collextion Routines
2204 /* ---------------------------------------------------------------------------
2205 Where are the roots that we know about?
2207 - all the threads on the runnable queue
2208 - all the threads on the blocked queue
2209 - all the threads on the sleeping queue
2210 - all the thread currently executing a _ccall_GC
2211 - all the "main threads"
2213 ------------------------------------------------------------------------ */
2215 /* This has to be protected either by the scheduler monitor, or by the
2216 garbage collection monitor (probably the latter).
2221 GetRoots(evac_fn evac)
2228 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2229 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2230 evac((StgClosure **)&run_queue_hds[i]);
2231 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2232 evac((StgClosure **)&run_queue_tls[i]);
2234 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2235 evac((StgClosure **)&blocked_queue_hds[i]);
2236 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2237 evac((StgClosure **)&blocked_queue_tls[i]);
2238 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2239 evac((StgClosure **)&ccalling_threads[i]);
2246 if (run_queue_hd != END_TSO_QUEUE) {
2247 ASSERT(run_queue_tl != END_TSO_QUEUE);
2248 evac((StgClosure **)&run_queue_hd);
2249 evac((StgClosure **)&run_queue_tl);
2252 if (blocked_queue_hd != END_TSO_QUEUE) {
2253 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2254 evac((StgClosure **)&blocked_queue_hd);
2255 evac((StgClosure **)&blocked_queue_tl);
2258 if (sleeping_queue != END_TSO_QUEUE) {
2259 evac((StgClosure **)&sleeping_queue);
2263 for (m = main_threads; m != NULL; m = m->link) {
2264 evac((StgClosure **)&m->tso);
2266 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2267 evac((StgClosure **)&suspended_ccalling_threads);
2270 #if defined(SMP) || defined(PAR) || defined(GRAN)
2271 markSparkQueue(evac);
2275 /* -----------------------------------------------------------------------------
2278 This is the interface to the garbage collector from Haskell land.
2279 We provide this so that external C code can allocate and garbage
2280 collect when called from Haskell via _ccall_GC.
2282 It might be useful to provide an interface whereby the programmer
2283 can specify more roots (ToDo).
2285 This needs to be protected by the GC condition variable above. KH.
2286 -------------------------------------------------------------------------- */
2288 void (*extra_roots)(evac_fn);
2293 GarbageCollect(GetRoots,rtsFalse);
2297 performMajorGC(void)
2299 GarbageCollect(GetRoots,rtsTrue);
2303 AllRoots(evac_fn evac)
2305 GetRoots(evac); // the scheduler's roots
2306 extra_roots(evac); // the user's roots
2310 performGCWithRoots(void (*get_roots)(evac_fn))
2312 extra_roots = get_roots;
2313 GarbageCollect(AllRoots,rtsFalse);
2316 /* -----------------------------------------------------------------------------
2319 If the thread has reached its maximum stack size, then raise the
2320 StackOverflow exception in the offending thread. Otherwise
2321 relocate the TSO into a larger chunk of memory and adjust its stack
2323 -------------------------------------------------------------------------- */
2326 threadStackOverflow(StgTSO *tso)
2328 nat new_stack_size, new_tso_size, diff, stack_words;
2332 IF_DEBUG(sanity,checkTSO(tso));
2333 if (tso->stack_size >= tso->max_stack_size) {
2336 belch("@@ threadStackOverflow of TSO %d (%p): stack too large (now %ld; max is %ld",
2337 tso->id, tso, tso->stack_size, tso->max_stack_size);
2338 /* If we're debugging, just print out the top of the stack */
2339 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2342 /* Send this thread the StackOverflow exception */
2343 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2347 /* Try to double the current stack size. If that takes us over the
2348 * maximum stack size for this thread, then use the maximum instead.
2349 * Finally round up so the TSO ends up as a whole number of blocks.
2351 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2352 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2353 TSO_STRUCT_SIZE)/sizeof(W_);
2354 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2355 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2357 IF_DEBUG(scheduler, fprintf(stderr,"== scheduler: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2359 dest = (StgTSO *)allocate(new_tso_size);
2360 TICK_ALLOC_TSO(new_tso_size-sizeofW(StgTSO),0);
2362 /* copy the TSO block and the old stack into the new area */
2363 memcpy(dest,tso,TSO_STRUCT_SIZE);
2364 stack_words = tso->stack + tso->stack_size - tso->sp;
2365 new_sp = (P_)dest + new_tso_size - stack_words;
2366 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2368 /* relocate the stack pointers... */
2369 diff = (P_)new_sp - (P_)tso->sp; /* In *words* */
2370 dest->su = (StgUpdateFrame *) ((P_)dest->su + diff);
2372 dest->stack_size = new_stack_size;
2374 /* and relocate the update frame list */
2375 relocate_stack(dest, diff);
2377 /* Mark the old TSO as relocated. We have to check for relocated
2378 * TSOs in the garbage collector and any primops that deal with TSOs.
2380 * It's important to set the sp and su values to just beyond the end
2381 * of the stack, so we don't attempt to scavenge any part of the
2384 tso->what_next = ThreadRelocated;
2386 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2387 tso->su = (StgUpdateFrame *)tso->sp;
2388 tso->why_blocked = NotBlocked;
2389 dest->mut_link = NULL;
2391 IF_PAR_DEBUG(verbose,
2392 belch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld",
2393 tso->id, tso, tso->stack_size);
2394 /* If we're debugging, just print out the top of the stack */
2395 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2398 IF_DEBUG(sanity,checkTSO(tso));
2400 IF_DEBUG(scheduler,printTSO(dest));
2406 //@node Blocking Queue Routines, Exception Handling Routines, Garbage Collextion Routines, Main scheduling code
2407 //@subsection Blocking Queue Routines
2409 /* ---------------------------------------------------------------------------
2410 Wake up a queue that was blocked on some resource.
2411 ------------------------------------------------------------------------ */
2415 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2420 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2422 /* write RESUME events to log file and
2423 update blocked and fetch time (depending on type of the orig closure) */
2424 if (RtsFlags.ParFlags.ParStats.Full) {
2425 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2426 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2427 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2428 if (EMPTY_RUN_QUEUE())
2429 emitSchedule = rtsTrue;
2431 switch (get_itbl(node)->type) {
2433 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2438 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2445 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2452 static StgBlockingQueueElement *
2453 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2456 PEs node_loc, tso_loc;
2458 node_loc = where_is(node); // should be lifted out of loop
2459 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2460 tso_loc = where_is((StgClosure *)tso);
2461 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2462 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2463 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2464 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2465 // insertThread(tso, node_loc);
2466 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2468 tso, node, (rtsSpark*)NULL);
2469 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2472 } else { // TSO is remote (actually should be FMBQ)
2473 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2474 RtsFlags.GranFlags.Costs.gunblocktime +
2475 RtsFlags.GranFlags.Costs.latency;
2476 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2478 tso, node, (rtsSpark*)NULL);
2479 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2482 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2484 fprintf(stderr," %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2485 (node_loc==tso_loc ? "Local" : "Global"),
2486 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2487 tso->block_info.closure = NULL;
2488 IF_DEBUG(scheduler,belch("-- Waking up thread %ld (%p)",
2492 static StgBlockingQueueElement *
2493 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2495 StgBlockingQueueElement *next;
2497 switch (get_itbl(bqe)->type) {
2499 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2500 /* if it's a TSO just push it onto the run_queue */
2502 // ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2503 PUSH_ON_RUN_QUEUE((StgTSO *)bqe);
2505 unblockCount(bqe, node);
2506 /* reset blocking status after dumping event */
2507 ((StgTSO *)bqe)->why_blocked = NotBlocked;
2511 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2513 bqe->link = (StgBlockingQueueElement *)PendingFetches;
2514 PendingFetches = (StgBlockedFetch *)bqe;
2518 /* can ignore this case in a non-debugging setup;
2519 see comments on RBHSave closures above */
2521 /* check that the closure is an RBHSave closure */
2522 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2523 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2524 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2528 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2529 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
2533 IF_PAR_DEBUG(bq, fprintf(stderr, ", %p (%s)", bqe, info_type((StgClosure*)bqe)));
2537 #else /* !GRAN && !PAR */
2539 unblockOneLocked(StgTSO *tso)
2543 ASSERT(get_itbl(tso)->type == TSO);
2544 ASSERT(tso->why_blocked != NotBlocked);
2545 tso->why_blocked = NotBlocked;
2547 PUSH_ON_RUN_QUEUE(tso);
2549 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
2554 #if defined(GRAN) || defined(PAR)
2555 inline StgBlockingQueueElement *
2556 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2558 ACQUIRE_LOCK(&sched_mutex);
2559 bqe = unblockOneLocked(bqe, node);
2560 RELEASE_LOCK(&sched_mutex);
2565 unblockOne(StgTSO *tso)
2567 ACQUIRE_LOCK(&sched_mutex);
2568 tso = unblockOneLocked(tso);
2569 RELEASE_LOCK(&sched_mutex);
2576 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2578 StgBlockingQueueElement *bqe;
2583 belch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): ", \
2584 node, CurrentProc, CurrentTime[CurrentProc],
2585 CurrentTSO->id, CurrentTSO));
2587 node_loc = where_is(node);
2589 ASSERT(q == END_BQ_QUEUE ||
2590 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
2591 get_itbl(q)->type == CONSTR); // closure (type constructor)
2592 ASSERT(is_unique(node));
2594 /* FAKE FETCH: magically copy the node to the tso's proc;
2595 no Fetch necessary because in reality the node should not have been
2596 moved to the other PE in the first place
2598 if (CurrentProc!=node_loc) {
2600 belch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)",
2601 node, node_loc, CurrentProc, CurrentTSO->id,
2602 // CurrentTSO, where_is(CurrentTSO),
2603 node->header.gran.procs));
2604 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
2606 belch("## new bitmask of node %p is %#x",
2607 node, node->header.gran.procs));
2608 if (RtsFlags.GranFlags.GranSimStats.Global) {
2609 globalGranStats.tot_fake_fetches++;
2614 // ToDo: check: ASSERT(CurrentProc==node_loc);
2615 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
2618 bqe points to the current element in the queue
2619 next points to the next element in the queue
2621 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2622 //tso_loc = where_is(tso);
2624 bqe = unblockOneLocked(bqe, node);
2627 /* if this is the BQ of an RBH, we have to put back the info ripped out of
2628 the closure to make room for the anchor of the BQ */
2629 if (bqe!=END_BQ_QUEUE) {
2630 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
2632 ASSERT((info_ptr==&RBH_Save_0_info) ||
2633 (info_ptr==&RBH_Save_1_info) ||
2634 (info_ptr==&RBH_Save_2_info));
2636 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
2637 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
2638 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
2641 belch("## Filled in RBH_Save for %p (%s) at end of AwBQ",
2642 node, info_type(node)));
2645 /* statistics gathering */
2646 if (RtsFlags.GranFlags.GranSimStats.Global) {
2647 // globalGranStats.tot_bq_processing_time += bq_processing_time;
2648 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
2649 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
2650 globalGranStats.tot_awbq++; // total no. of bqs awakened
2653 fprintf(stderr,"## BQ Stats of %p: [%d entries] %s\n",
2654 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
2658 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2660 StgBlockingQueueElement *bqe;
2662 ACQUIRE_LOCK(&sched_mutex);
2664 IF_PAR_DEBUG(verbose,
2665 belch("##-_ AwBQ for node %p on [%x]: ",
2669 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
2670 IF_PAR_DEBUG(verbose, belch("## ... nothing to unblock so lets just return. RFP (BUG?)"));
2675 ASSERT(q == END_BQ_QUEUE ||
2676 get_itbl(q)->type == TSO ||
2677 get_itbl(q)->type == BLOCKED_FETCH ||
2678 get_itbl(q)->type == CONSTR);
2681 while (get_itbl(bqe)->type==TSO ||
2682 get_itbl(bqe)->type==BLOCKED_FETCH) {
2683 bqe = unblockOneLocked(bqe, node);
2685 RELEASE_LOCK(&sched_mutex);
2688 #else /* !GRAN && !PAR */
2690 awakenBlockedQueue(StgTSO *tso)
2692 ACQUIRE_LOCK(&sched_mutex);
2693 while (tso != END_TSO_QUEUE) {
2694 tso = unblockOneLocked(tso);
2696 RELEASE_LOCK(&sched_mutex);
2700 //@node Exception Handling Routines, Debugging Routines, Blocking Queue Routines, Main scheduling code
2701 //@subsection Exception Handling Routines
2703 /* ---------------------------------------------------------------------------
2705 - usually called inside a signal handler so it mustn't do anything fancy.
2706 ------------------------------------------------------------------------ */
2709 interruptStgRts(void)
2715 /* -----------------------------------------------------------------------------
2718 This is for use when we raise an exception in another thread, which
2720 This has nothing to do with the UnblockThread event in GranSim. -- HWL
2721 -------------------------------------------------------------------------- */
2723 #if defined(GRAN) || defined(PAR)
2725 NB: only the type of the blocking queue is different in GranSim and GUM
2726 the operations on the queue-elements are the same
2727 long live polymorphism!
2730 unblockThread(StgTSO *tso)
2732 StgBlockingQueueElement *t, **last;
2734 ACQUIRE_LOCK(&sched_mutex);
2735 switch (tso->why_blocked) {
2738 return; /* not blocked */
2741 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2743 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
2744 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2746 last = (StgBlockingQueueElement **)&mvar->head;
2747 for (t = (StgBlockingQueueElement *)mvar->head;
2749 last = &t->link, last_tso = t, t = t->link) {
2750 if (t == (StgBlockingQueueElement *)tso) {
2751 *last = (StgBlockingQueueElement *)tso->link;
2752 if (mvar->tail == tso) {
2753 mvar->tail = (StgTSO *)last_tso;
2758 barf("unblockThread (MVAR): TSO not found");
2761 case BlockedOnBlackHole:
2762 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2764 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2766 last = &bq->blocking_queue;
2767 for (t = bq->blocking_queue;
2769 last = &t->link, t = t->link) {
2770 if (t == (StgBlockingQueueElement *)tso) {
2771 *last = (StgBlockingQueueElement *)tso->link;
2775 barf("unblockThread (BLACKHOLE): TSO not found");
2778 case BlockedOnException:
2780 StgTSO *target = tso->block_info.tso;
2782 ASSERT(get_itbl(target)->type == TSO);
2784 if (target->what_next == ThreadRelocated) {
2785 target = target->link;
2786 ASSERT(get_itbl(target)->type == TSO);
2789 ASSERT(target->blocked_exceptions != NULL);
2791 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
2792 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
2794 last = &t->link, t = t->link) {
2795 ASSERT(get_itbl(t)->type == TSO);
2796 if (t == (StgBlockingQueueElement *)tso) {
2797 *last = (StgBlockingQueueElement *)tso->link;
2801 barf("unblockThread (Exception): TSO not found");
2805 case BlockedOnWrite:
2807 /* take TSO off blocked_queue */
2808 StgBlockingQueueElement *prev = NULL;
2809 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
2810 prev = t, t = t->link) {
2811 if (t == (StgBlockingQueueElement *)tso) {
2813 blocked_queue_hd = (StgTSO *)t->link;
2814 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2815 blocked_queue_tl = END_TSO_QUEUE;
2818 prev->link = t->link;
2819 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2820 blocked_queue_tl = (StgTSO *)prev;
2826 barf("unblockThread (I/O): TSO not found");
2829 case BlockedOnDelay:
2831 /* take TSO off sleeping_queue */
2832 StgBlockingQueueElement *prev = NULL;
2833 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
2834 prev = t, t = t->link) {
2835 if (t == (StgBlockingQueueElement *)tso) {
2837 sleeping_queue = (StgTSO *)t->link;
2839 prev->link = t->link;
2844 barf("unblockThread (I/O): TSO not found");
2848 barf("unblockThread");
2852 tso->link = END_TSO_QUEUE;
2853 tso->why_blocked = NotBlocked;
2854 tso->block_info.closure = NULL;
2855 PUSH_ON_RUN_QUEUE(tso);
2856 RELEASE_LOCK(&sched_mutex);
2860 unblockThread(StgTSO *tso)
2864 ACQUIRE_LOCK(&sched_mutex);
2865 switch (tso->why_blocked) {
2868 return; /* not blocked */
2871 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2873 StgTSO *last_tso = END_TSO_QUEUE;
2874 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2877 for (t = mvar->head; t != END_TSO_QUEUE;
2878 last = &t->link, last_tso = t, t = t->link) {
2881 if (mvar->tail == tso) {
2882 mvar->tail = last_tso;
2887 barf("unblockThread (MVAR): TSO not found");
2890 case BlockedOnBlackHole:
2891 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2893 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2895 last = &bq->blocking_queue;
2896 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
2897 last = &t->link, t = t->link) {
2903 barf("unblockThread (BLACKHOLE): TSO not found");
2906 case BlockedOnException:
2908 StgTSO *target = tso->block_info.tso;
2910 ASSERT(get_itbl(target)->type == TSO);
2912 while (target->what_next == ThreadRelocated) {
2913 target = target->link;
2914 ASSERT(get_itbl(target)->type == TSO);
2917 ASSERT(target->blocked_exceptions != NULL);
2919 last = &target->blocked_exceptions;
2920 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
2921 last = &t->link, t = t->link) {
2922 ASSERT(get_itbl(t)->type == TSO);
2928 barf("unblockThread (Exception): TSO not found");
2932 case BlockedOnWrite:
2934 StgTSO *prev = NULL;
2935 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
2936 prev = t, t = t->link) {
2939 blocked_queue_hd = t->link;
2940 if (blocked_queue_tl == t) {
2941 blocked_queue_tl = END_TSO_QUEUE;
2944 prev->link = t->link;
2945 if (blocked_queue_tl == t) {
2946 blocked_queue_tl = prev;
2952 barf("unblockThread (I/O): TSO not found");
2955 case BlockedOnDelay:
2957 StgTSO *prev = NULL;
2958 for (t = sleeping_queue; t != END_TSO_QUEUE;
2959 prev = t, t = t->link) {
2962 sleeping_queue = t->link;
2964 prev->link = t->link;
2969 barf("unblockThread (I/O): TSO not found");
2973 barf("unblockThread");
2977 tso->link = END_TSO_QUEUE;
2978 tso->why_blocked = NotBlocked;
2979 tso->block_info.closure = NULL;
2980 PUSH_ON_RUN_QUEUE(tso);
2981 RELEASE_LOCK(&sched_mutex);
2985 /* -----------------------------------------------------------------------------
2988 * The following function implements the magic for raising an
2989 * asynchronous exception in an existing thread.
2991 * We first remove the thread from any queue on which it might be
2992 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
2994 * We strip the stack down to the innermost CATCH_FRAME, building
2995 * thunks in the heap for all the active computations, so they can
2996 * be restarted if necessary. When we reach a CATCH_FRAME, we build
2997 * an application of the handler to the exception, and push it on
2998 * the top of the stack.
3000 * How exactly do we save all the active computations? We create an
3001 * AP_UPD for every UpdateFrame on the stack. Entering one of these
3002 * AP_UPDs pushes everything from the corresponding update frame
3003 * upwards onto the stack. (Actually, it pushes everything up to the
3004 * next update frame plus a pointer to the next AP_UPD object.
3005 * Entering the next AP_UPD object pushes more onto the stack until we
3006 * reach the last AP_UPD object - at which point the stack should look
3007 * exactly as it did when we killed the TSO and we can continue
3008 * execution by entering the closure on top of the stack.
3010 * We can also kill a thread entirely - this happens if either (a) the
3011 * exception passed to raiseAsync is NULL, or (b) there's no
3012 * CATCH_FRAME on the stack. In either case, we strip the entire
3013 * stack and replace the thread with a zombie.
3015 * -------------------------------------------------------------------------- */
3018 deleteThread(StgTSO *tso)
3020 raiseAsync(tso,NULL);
3024 raiseAsync(StgTSO *tso, StgClosure *exception)
3026 StgUpdateFrame* su = tso->su;
3027 StgPtr sp = tso->sp;
3029 /* Thread already dead? */
3030 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3034 IF_DEBUG(scheduler, sched_belch("raising exception in thread %ld.", tso->id));
3036 /* Remove it from any blocking queues */
3039 /* The stack freezing code assumes there's a closure pointer on
3040 * the top of the stack. This isn't always the case with compiled
3041 * code, so we have to push a dummy closure on the top which just
3042 * returns to the next return address on the stack.
3044 if ( LOOKS_LIKE_GHC_INFO((void*)*sp) ) {
3045 *(--sp) = (W_)&stg_dummy_ret_closure;
3049 nat words = ((P_)su - (P_)sp) - 1;
3053 /* If we find a CATCH_FRAME, and we've got an exception to raise,
3054 * then build PAP(handler,exception,realworld#), and leave it on
3055 * top of the stack ready to enter.
3057 if (get_itbl(su)->type == CATCH_FRAME && exception != NULL) {
3058 StgCatchFrame *cf = (StgCatchFrame *)su;
3059 /* we've got an exception to raise, so let's pass it to the
3060 * handler in this frame.
3062 ap = (StgAP_UPD *)allocate(sizeofW(StgPAP) + 2);
3063 TICK_ALLOC_UPD_PAP(3,0);
3064 SET_HDR(ap,&stg_PAP_info,cf->header.prof.ccs);
3067 ap->fun = cf->handler; /* :: Exception -> IO a */
3068 ap->payload[0] = exception;
3069 ap->payload[1] = ARG_TAG(0); /* realworld token */
3071 /* throw away the stack from Sp up to and including the
3074 sp = (P_)su + sizeofW(StgCatchFrame) - 1;
3077 /* Restore the blocked/unblocked state for asynchronous exceptions
3078 * at the CATCH_FRAME.
3080 * If exceptions were unblocked at the catch, arrange that they
3081 * are unblocked again after executing the handler by pushing an
3082 * unblockAsyncExceptions_ret stack frame.
3084 if (!cf->exceptions_blocked) {
3085 *(sp--) = (W_)&stg_unblockAsyncExceptionszh_ret_info;
3088 /* Ensure that async exceptions are blocked when running the handler.
3090 if (tso->blocked_exceptions == NULL) {
3091 tso->blocked_exceptions = END_TSO_QUEUE;
3094 /* Put the newly-built PAP on top of the stack, ready to execute
3095 * when the thread restarts.
3099 tso->what_next = ThreadEnterGHC;
3100 IF_DEBUG(sanity, checkTSO(tso));
3104 /* First build an AP_UPD consisting of the stack chunk above the
3105 * current update frame, with the top word on the stack as the
3108 ap = (StgAP_UPD *)allocate(AP_sizeW(words));
3113 ap->fun = (StgClosure *)sp[0];
3115 for(i=0; i < (nat)words; ++i) {
3116 ap->payload[i] = (StgClosure *)*sp++;
3119 switch (get_itbl(su)->type) {
3123 SET_HDR(ap,&stg_AP_UPD_info,su->header.prof.ccs /* ToDo */);
3124 TICK_ALLOC_UP_THK(words+1,0);
3127 fprintf(stderr, "scheduler: Updating ");
3128 printPtr((P_)su->updatee);
3129 fprintf(stderr, " with ");
3130 printObj((StgClosure *)ap);
3133 /* Replace the updatee with an indirection - happily
3134 * this will also wake up any threads currently
3135 * waiting on the result.
3137 * Warning: if we're in a loop, more than one update frame on
3138 * the stack may point to the same object. Be careful not to
3139 * overwrite an IND_OLDGEN in this case, because we'll screw
3140 * up the mutable lists. To be on the safe side, don't
3141 * overwrite any kind of indirection at all. See also
3142 * threadSqueezeStack in GC.c, where we have to make a similar
3145 if (!closure_IND(su->updatee)) {
3146 UPD_IND_NOLOCK(su->updatee,ap); /* revert the black hole */
3149 sp += sizeofW(StgUpdateFrame) -1;
3150 sp[0] = (W_)ap; /* push onto stack */
3156 StgCatchFrame *cf = (StgCatchFrame *)su;
3159 /* We want a PAP, not an AP_UPD. Fortunately, the
3160 * layout's the same.
3162 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3163 TICK_ALLOC_UPD_PAP(words+1,0);
3165 /* now build o = FUN(catch,ap,handler) */
3166 o = (StgClosure *)allocate(sizeofW(StgClosure)+2);
3167 TICK_ALLOC_FUN(2,0);
3168 SET_HDR(o,&stg_catch_info,su->header.prof.ccs /* ToDo */);
3169 o->payload[0] = (StgClosure *)ap;
3170 o->payload[1] = cf->handler;
3173 fprintf(stderr, "scheduler: Built ");
3174 printObj((StgClosure *)o);
3177 /* pop the old handler and put o on the stack */
3179 sp += sizeofW(StgCatchFrame) - 1;
3186 StgSeqFrame *sf = (StgSeqFrame *)su;
3189 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3190 TICK_ALLOC_UPD_PAP(words+1,0);
3192 /* now build o = FUN(seq,ap) */
3193 o = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3194 TICK_ALLOC_SE_THK(1,0);
3195 SET_HDR(o,&stg_seq_info,su->header.prof.ccs /* ToDo */);
3196 o->payload[0] = (StgClosure *)ap;
3199 fprintf(stderr, "scheduler: Built ");
3200 printObj((StgClosure *)o);
3203 /* pop the old handler and put o on the stack */
3205 sp += sizeofW(StgSeqFrame) - 1;
3211 /* We've stripped the entire stack, the thread is now dead. */
3212 sp += sizeofW(StgStopFrame) - 1;
3213 sp[0] = (W_)exception; /* save the exception */
3214 tso->what_next = ThreadKilled;
3215 tso->su = (StgUpdateFrame *)(sp+1);
3226 /* -----------------------------------------------------------------------------
3227 resurrectThreads is called after garbage collection on the list of
3228 threads found to be garbage. Each of these threads will be woken
3229 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3230 on an MVar, or NonTermination if the thread was blocked on a Black
3232 -------------------------------------------------------------------------- */
3235 resurrectThreads( StgTSO *threads )
3239 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3240 next = tso->global_link;
3241 tso->global_link = all_threads;
3243 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3245 switch (tso->why_blocked) {
3247 case BlockedOnException:
3248 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3250 case BlockedOnBlackHole:
3251 raiseAsync(tso,(StgClosure *)NonTermination_closure);
3254 /* This might happen if the thread was blocked on a black hole
3255 * belonging to a thread that we've just woken up (raiseAsync
3256 * can wake up threads, remember...).
3260 barf("resurrectThreads: thread blocked in a strange way");
3265 /* -----------------------------------------------------------------------------
3266 * Blackhole detection: if we reach a deadlock, test whether any
3267 * threads are blocked on themselves. Any threads which are found to
3268 * be self-blocked get sent a NonTermination exception.
3270 * This is only done in a deadlock situation in order to avoid
3271 * performance overhead in the normal case.
3272 * -------------------------------------------------------------------------- */
3275 detectBlackHoles( void )
3277 StgTSO *t = all_threads;
3278 StgUpdateFrame *frame;
3279 StgClosure *blocked_on;
3281 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3283 while (t->what_next == ThreadRelocated) {
3285 ASSERT(get_itbl(t)->type == TSO);
3288 if (t->why_blocked != BlockedOnBlackHole) {
3292 blocked_on = t->block_info.closure;
3294 for (frame = t->su; ; frame = frame->link) {
3295 switch (get_itbl(frame)->type) {
3298 if (frame->updatee == blocked_on) {
3299 /* We are blocking on one of our own computations, so
3300 * send this thread the NonTermination exception.
3303 sched_belch("thread %d is blocked on itself", t->id));
3304 raiseAsync(t, (StgClosure *)NonTermination_closure);
3325 //@node Debugging Routines, Index, Exception Handling Routines, Main scheduling code
3326 //@subsection Debugging Routines
3328 /* -----------------------------------------------------------------------------
3329 Debugging: why is a thread blocked
3330 -------------------------------------------------------------------------- */
3335 printThreadBlockage(StgTSO *tso)
3337 switch (tso->why_blocked) {
3339 fprintf(stderr,"is blocked on read from fd %d", tso->block_info.fd);
3341 case BlockedOnWrite:
3342 fprintf(stderr,"is blocked on write to fd %d", tso->block_info.fd);
3344 case BlockedOnDelay:
3345 fprintf(stderr,"is blocked until %d", tso->block_info.target);
3348 fprintf(stderr,"is blocked on an MVar");
3350 case BlockedOnException:
3351 fprintf(stderr,"is blocked on delivering an exception to thread %d",
3352 tso->block_info.tso->id);
3354 case BlockedOnBlackHole:
3355 fprintf(stderr,"is blocked on a black hole");
3358 fprintf(stderr,"is not blocked");
3362 fprintf(stderr,"is blocked on global address; local FM_BQ is %p (%s)",
3363 tso->block_info.closure, info_type(tso->block_info.closure));
3365 case BlockedOnGA_NoSend:
3366 fprintf(stderr,"is blocked on global address (no send); local FM_BQ is %p (%s)",
3367 tso->block_info.closure, info_type(tso->block_info.closure));
3371 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3372 tso->why_blocked, tso->id, tso);
3377 printThreadStatus(StgTSO *tso)
3379 switch (tso->what_next) {
3381 fprintf(stderr,"has been killed");
3383 case ThreadComplete:
3384 fprintf(stderr,"has completed");
3387 printThreadBlockage(tso);
3392 printAllThreads(void)
3397 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3398 ullong_format_string(TIME_ON_PROC(CurrentProc),
3399 time_string, rtsFalse/*no commas!*/);
3401 sched_belch("all threads at [%s]:", time_string);
3403 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3404 ullong_format_string(CURRENT_TIME,
3405 time_string, rtsFalse/*no commas!*/);
3407 sched_belch("all threads at [%s]:", time_string);
3409 sched_belch("all threads:");
3412 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3413 fprintf(stderr, "\tthread %d ", t->id);
3414 printThreadStatus(t);
3415 fprintf(stderr,"\n");
3420 Print a whole blocking queue attached to node (debugging only).
3425 print_bq (StgClosure *node)
3427 StgBlockingQueueElement *bqe;
3431 fprintf(stderr,"## BQ of closure %p (%s): ",
3432 node, info_type(node));
3434 /* should cover all closures that may have a blocking queue */
3435 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3436 get_itbl(node)->type == FETCH_ME_BQ ||
3437 get_itbl(node)->type == RBH ||
3438 get_itbl(node)->type == MVAR);
3440 ASSERT(node!=(StgClosure*)NULL); // sanity check
3442 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
3446 Print a whole blocking queue starting with the element bqe.
3449 print_bqe (StgBlockingQueueElement *bqe)
3454 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3456 for (end = (bqe==END_BQ_QUEUE);
3457 !end; // iterate until bqe points to a CONSTR
3458 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
3459 bqe = end ? END_BQ_QUEUE : bqe->link) {
3460 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3461 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3462 /* types of closures that may appear in a blocking queue */
3463 ASSERT(get_itbl(bqe)->type == TSO ||
3464 get_itbl(bqe)->type == BLOCKED_FETCH ||
3465 get_itbl(bqe)->type == CONSTR);
3466 /* only BQs of an RBH end with an RBH_Save closure */
3467 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3469 switch (get_itbl(bqe)->type) {
3471 fprintf(stderr," TSO %u (%x),",
3472 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
3475 fprintf(stderr," BF (node=%p, ga=((%x, %d, %x)),",
3476 ((StgBlockedFetch *)bqe)->node,
3477 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
3478 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
3479 ((StgBlockedFetch *)bqe)->ga.weight);
3482 fprintf(stderr," %s (IP %p),",
3483 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3484 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3485 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3486 "RBH_Save_?"), get_itbl(bqe));
3489 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
3490 info_type((StgClosure *)bqe)); // , node, info_type(node));
3494 fputc('\n', stderr);
3496 # elif defined(GRAN)
3498 print_bq (StgClosure *node)
3500 StgBlockingQueueElement *bqe;
3501 PEs node_loc, tso_loc;
3504 /* should cover all closures that may have a blocking queue */
3505 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3506 get_itbl(node)->type == FETCH_ME_BQ ||
3507 get_itbl(node)->type == RBH);
3509 ASSERT(node!=(StgClosure*)NULL); // sanity check
3510 node_loc = where_is(node);
3512 fprintf(stderr,"## BQ of closure %p (%s) on [PE %d]: ",
3513 node, info_type(node), node_loc);
3516 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3518 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
3519 !end; // iterate until bqe points to a CONSTR
3520 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
3521 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3522 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3523 /* types of closures that may appear in a blocking queue */
3524 ASSERT(get_itbl(bqe)->type == TSO ||
3525 get_itbl(bqe)->type == CONSTR);
3526 /* only BQs of an RBH end with an RBH_Save closure */
3527 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3529 tso_loc = where_is((StgClosure *)bqe);
3530 switch (get_itbl(bqe)->type) {
3532 fprintf(stderr," TSO %d (%p) on [PE %d],",
3533 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
3536 fprintf(stderr," %s (IP %p),",
3537 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3538 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3539 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3540 "RBH_Save_?"), get_itbl(bqe));
3543 barf("Unexpected closure type %s in blocking queue of %p (%s)",
3544 info_type((StgClosure *)bqe), node, info_type(node));
3548 fputc('\n', stderr);
3552 Nice and easy: only TSOs on the blocking queue
3555 print_bq (StgClosure *node)
3559 ASSERT(node!=(StgClosure*)NULL); // sanity check
3560 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
3561 tso != END_TSO_QUEUE;
3563 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
3564 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
3565 fprintf(stderr," TSO %d (%p),", tso->id, tso);
3567 fputc('\n', stderr);
3578 for (i=0, tso=run_queue_hd;
3579 tso != END_TSO_QUEUE;
3588 sched_belch(char *s, ...)
3593 fprintf(stderr, "scheduler (task %ld): ", pthread_self());
3595 fprintf(stderr, "== ");
3597 fprintf(stderr, "scheduler: ");
3599 vfprintf(stderr, s, ap);
3600 fprintf(stderr, "\n");
3606 //@node Index, , Debugging Routines, Main scheduling code
3610 //* MainRegTable:: @cindex\s-+MainRegTable
3611 //* StgMainThread:: @cindex\s-+StgMainThread
3612 //* awaken_blocked_queue:: @cindex\s-+awaken_blocked_queue
3613 //* blocked_queue_hd:: @cindex\s-+blocked_queue_hd
3614 //* blocked_queue_tl:: @cindex\s-+blocked_queue_tl
3615 //* context_switch:: @cindex\s-+context_switch
3616 //* createThread:: @cindex\s-+createThread
3617 //* free_capabilities:: @cindex\s-+free_capabilities
3618 //* gc_pending_cond:: @cindex\s-+gc_pending_cond
3619 //* initScheduler:: @cindex\s-+initScheduler
3620 //* interrupted:: @cindex\s-+interrupted
3621 //* n_free_capabilities:: @cindex\s-+n_free_capabilities
3622 //* next_thread_id:: @cindex\s-+next_thread_id
3623 //* print_bq:: @cindex\s-+print_bq
3624 //* run_queue_hd:: @cindex\s-+run_queue_hd
3625 //* run_queue_tl:: @cindex\s-+run_queue_tl
3626 //* sched_mutex:: @cindex\s-+sched_mutex
3627 //* schedule:: @cindex\s-+schedule
3628 //* take_off_run_queue:: @cindex\s-+take_off_run_queue
3629 //* task_ids:: @cindex\s-+task_ids
3630 //* term_mutex:: @cindex\s-+term_mutex
3631 //* thread_ready_cond:: @cindex\s-+thread_ready_cond