1 /* ---------------------------------------------------------------------------
2 * $Id: Schedule.c,v 1.131 2002/02/18 13:26:13 sof Exp $
4 * (c) The GHC Team, 1998-2000
8 * Different GHC ways use this scheduler quite differently (see comments below)
9 * Here is the global picture:
11 * WAY Name CPP flag What's it for
12 * --------------------------------------
13 * mp GUM PAR Parallel execution on a distributed memory machine
14 * s SMP SMP Parallel execution on a shared memory machine
15 * mg GranSim GRAN Simulation of parallel execution
16 * md GUM/GdH DIST Distributed execution (based on GUM)
18 * --------------------------------------------------------------------------*/
20 //@node Main scheduling code, , ,
21 //@section Main scheduling code
24 * Version with scheduler monitor support for SMPs (WAY=s):
26 This design provides a high-level API to create and schedule threads etc.
27 as documented in the SMP design document.
29 It uses a monitor design controlled by a single mutex to exercise control
30 over accesses to shared data structures, and builds on the Posix threads
33 The majority of state is shared. In order to keep essential per-task state,
34 there is a Capability structure, which contains all the information
35 needed to run a thread: its STG registers, a pointer to its TSO, a
36 nursery etc. During STG execution, a pointer to the capability is
37 kept in a register (BaseReg).
39 In a non-SMP build, there is one global capability, namely MainRegTable.
43 * Version with support for distributed memory parallelism aka GUM (WAY=mp):
45 The main scheduling loop in GUM iterates until a finish message is received.
46 In that case a global flag @receivedFinish@ is set and this instance of
47 the RTS shuts down. See ghc/rts/parallel/HLComms.c:processMessages()
48 for the handling of incoming messages, such as PP_FINISH.
49 Note that in the parallel case we have a system manager that coordinates
50 different PEs, each of which are running one instance of the RTS.
51 See ghc/rts/parallel/SysMan.c for the main routine of the parallel program.
52 From this routine processes executing ghc/rts/Main.c are spawned. -- HWL
54 * Version with support for simulating parallel execution aka GranSim (WAY=mg):
56 The main scheduling code in GranSim is quite different from that in std
57 (concurrent) Haskell: while concurrent Haskell just iterates over the
58 threads in the runnable queue, GranSim is event driven, i.e. it iterates
59 over the events in the global event queue. -- HWL
64 //* Variables and Data structures::
65 //* Main scheduling loop::
66 //* Suspend and Resume::
68 //* Garbage Collextion Routines::
69 //* Blocking Queue Routines::
70 //* Exception Handling Routines::
71 //* Debugging Routines::
75 //@node Includes, Variables and Data structures, Main scheduling code, Main scheduling code
76 //@subsection Includes
78 #include "PosixSource.h"
85 #include "StgStartup.h"
88 #include "StgMiscClosures.h"
90 #include "Interpreter.h"
91 #include "Exception.h"
100 #include "Proftimer.h"
101 #include "ProfHeap.h"
103 #if defined(GRAN) || defined(PAR)
104 # include "GranSimRts.h"
105 # include "GranSim.h"
106 # include "ParallelRts.h"
107 # include "Parallel.h"
108 # include "ParallelDebug.h"
109 # include "FetchMe.h"
113 #include "Capability.h"
114 #include "OSThreads.h"
119 //@node Variables and Data structures, Prototypes, Includes, Main scheduling code
120 //@subsection Variables and Data structures
124 * These are the threads which clients have requested that we run.
126 * In a 'threaded' build, we might have several concurrent clients all
127 * waiting for results, and each one will wait on a condition variable
128 * until the result is available.
130 * In non-SMP, clients are strictly nested: the first client calls
131 * into the RTS, which might call out again to C with a _ccall_GC, and
132 * eventually re-enter the RTS.
134 * Main threads information is kept in a linked list:
136 //@cindex StgMainThread
137 typedef struct StgMainThread_ {
139 SchedulerStatus stat;
141 #if defined(RTS_SUPPORTS_THREADS)
144 struct StgMainThread_ *link;
147 /* Main thread queue.
148 * Locks required: sched_mutex.
150 static StgMainThread *main_threads;
153 * Locks required: sched_mutex.
157 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
158 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
161 In GranSim we have a runnable and a blocked queue for each processor.
162 In order to minimise code changes new arrays run_queue_hds/tls
163 are created. run_queue_hd is then a short cut (macro) for
164 run_queue_hds[CurrentProc] (see GranSim.h).
167 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
168 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
169 StgTSO *ccalling_threadss[MAX_PROC];
170 /* We use the same global list of threads (all_threads) in GranSim as in
171 the std RTS (i.e. we are cheating). However, we don't use this list in
172 the GranSim specific code at the moment (so we are only potentially
177 StgTSO *run_queue_hd, *run_queue_tl;
178 StgTSO *blocked_queue_hd, *blocked_queue_tl;
179 StgTSO *sleeping_queue; /* perhaps replace with a hash table? */
183 /* Linked list of all threads.
184 * Used for detecting garbage collected threads.
188 /* When a thread performs a safe C call (_ccall_GC, using old
189 * terminology), it gets put on the suspended_ccalling_threads
190 * list. Used by the garbage collector.
192 static StgTSO *suspended_ccalling_threads;
194 static StgTSO *threadStackOverflow(StgTSO *tso);
196 /* KH: The following two flags are shared memory locations. There is no need
197 to lock them, since they are only unset at the end of a scheduler
201 /* flag set by signal handler to precipitate a context switch */
202 //@cindex context_switch
205 /* if this flag is set as well, give up execution */
206 //@cindex interrupted
209 /* Next thread ID to allocate.
210 * Locks required: sched_mutex
212 //@cindex next_thread_id
213 StgThreadID next_thread_id = 1;
216 * Pointers to the state of the current thread.
217 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
218 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
221 /* The smallest stack size that makes any sense is:
222 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
223 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
224 * + 1 (the realworld token for an IO thread)
225 * + 1 (the closure to enter)
227 * A thread with this stack will bomb immediately with a stack
228 * overflow, which will increase its stack size.
231 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 2)
238 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
239 * exists - earlier gccs apparently didn't.
246 void addToBlockedQueue ( StgTSO *tso );
248 static void schedule ( void );
249 void interruptStgRts ( void );
251 static StgTSO * createThread_ ( nat size, rtsBool have_lock, StgInt pri );
253 static StgTSO * createThread_ ( nat size, rtsBool have_lock );
256 static void detectBlackHoles ( void );
259 static void sched_belch(char *s, ...);
262 #if defined(RTS_SUPPORTS_THREADS)
263 /* ToDo: carefully document the invariants that go together
264 * with these synchronisation objects.
266 Mutex sched_mutex = INIT_MUTEX_VAR;
267 Mutex term_mutex = INIT_MUTEX_VAR;
270 static Condition gc_pending_cond = INIT_COND_VAR;
274 #endif /* RTS_SUPPORTS_THREADS */
278 rtsTime TimeOfLastYield;
279 rtsBool emitSchedule = rtsTrue;
283 char *whatNext_strs[] = {
291 char *threadReturnCode_strs[] = {
292 "HeapOverflow", /* might also be StackOverflow */
301 StgTSO * createSparkThread(rtsSpark spark);
302 StgTSO * activateSpark (rtsSpark spark);
306 * The thread state for the main thread.
307 // ToDo: check whether not needed any more
311 #if defined(PAR) || defined(RTS_SUPPORTS_THREADS)
312 static void taskStart(void);
323 //@node Main scheduling loop, Suspend and Resume, Prototypes, Main scheduling code
324 //@subsection Main scheduling loop
326 /* ---------------------------------------------------------------------------
327 Main scheduling loop.
329 We use round-robin scheduling, each thread returning to the
330 scheduler loop when one of these conditions is detected:
333 * timer expires (thread yields)
338 Locking notes: we acquire the scheduler lock once at the beginning
339 of the scheduler loop, and release it when
341 * running a thread, or
342 * waiting for work, or
343 * waiting for a GC to complete.
346 In a GranSim setup this loop iterates over the global event queue.
347 This revolves around the global event queue, which determines what
348 to do next. Therefore, it's more complicated than either the
349 concurrent or the parallel (GUM) setup.
352 GUM iterates over incoming messages.
353 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
354 and sends out a fish whenever it has nothing to do; in-between
355 doing the actual reductions (shared code below) it processes the
356 incoming messages and deals with delayed operations
357 (see PendingFetches).
358 This is not the ugliest code you could imagine, but it's bloody close.
360 ------------------------------------------------------------------------ */
367 StgThreadReturnCode ret;
375 rtsBool receivedFinish = rtsFalse;
377 nat tp_size, sp_size; // stats only
380 rtsBool was_interrupted = rtsFalse;
382 ACQUIRE_LOCK(&sched_mutex);
384 #if defined(RTS_SUPPORTS_THREADS)
385 /* Check to see whether there are any worker threads
386 waiting to deposit external call results. If so,
387 yield our capability */
388 yieldToReturningWorker(&sched_mutex, cap);
390 waitForWorkCapability(&sched_mutex, &cap, rtsFalse);
394 /* set up first event to get things going */
395 /* ToDo: assign costs for system setup and init MainTSO ! */
396 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
398 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
401 fprintf(stderr, "GRAN: Init CurrentTSO (in schedule) = %p\n", CurrentTSO);
402 G_TSO(CurrentTSO, 5));
404 if (RtsFlags.GranFlags.Light) {
405 /* Save current time; GranSim Light only */
406 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
409 event = get_next_event();
411 while (event!=(rtsEvent*)NULL) {
412 /* Choose the processor with the next event */
413 CurrentProc = event->proc;
414 CurrentTSO = event->tso;
418 while (!receivedFinish) { /* set by processMessages */
419 /* when receiving PP_FINISH message */
426 IF_DEBUG(scheduler, printAllThreads());
428 /* If we're interrupted (the user pressed ^C, or some other
429 * termination condition occurred), kill all the currently running
433 IF_DEBUG(scheduler, sched_belch("interrupted"));
435 interrupted = rtsFalse;
436 was_interrupted = rtsTrue;
439 /* Go through the list of main threads and wake up any
440 * clients whose computations have finished. ToDo: this
441 * should be done more efficiently without a linear scan
442 * of the main threads list, somehow...
444 #if defined(RTS_SUPPORTS_THREADS)
446 StgMainThread *m, **prev;
447 prev = &main_threads;
448 for (m = main_threads; m != NULL; m = m->link) {
449 switch (m->tso->what_next) {
452 *(m->ret) = (StgClosure *)m->tso->sp[0];
456 broadcastCondition(&m->wakeup);
459 if (m->ret) *(m->ret) = NULL;
461 if (was_interrupted) {
462 m->stat = Interrupted;
466 broadcastCondition(&m->wakeup);
474 #else /* not threaded */
477 /* in GUM do this only on the Main PE */
480 /* If our main thread has finished or been killed, return.
483 StgMainThread *m = main_threads;
484 if (m->tso->what_next == ThreadComplete
485 || m->tso->what_next == ThreadKilled) {
486 main_threads = main_threads->link;
487 if (m->tso->what_next == ThreadComplete) {
488 /* we finished successfully, fill in the return value */
489 if (m->ret) { *(m->ret) = (StgClosure *)m->tso->sp[0]; };
493 if (m->ret) { *(m->ret) = NULL; };
494 if (was_interrupted) {
495 m->stat = Interrupted;
505 /* Top up the run queue from our spark pool. We try to make the
506 * number of threads in the run queue equal to the number of
509 * Disable spark support in SMP for now, non-essential & requires
510 * a little bit of work to make it compile cleanly. -- sof 1/02.
512 #if 0 /* defined(SMP) */
514 nat n = getFreeCapabilities();
515 StgTSO *tso = run_queue_hd;
517 /* Count the run queue */
518 while (n > 0 && tso != END_TSO_QUEUE) {
525 spark = findSpark(rtsFalse);
527 break; /* no more sparks in the pool */
529 /* I'd prefer this to be done in activateSpark -- HWL */
530 /* tricky - it needs to hold the scheduler lock and
531 * not try to re-acquire it -- SDM */
532 createSparkThread(spark);
534 sched_belch("==^^ turning spark of closure %p into a thread",
535 (StgClosure *)spark));
538 /* We need to wake up the other tasks if we just created some
541 if (getFreeCapabilities() - n > 1) {
542 signalCondition( &thread_ready_cond );
547 /* check for signals each time around the scheduler */
548 #ifndef mingw32_TARGET_OS
549 if (signals_pending()) {
550 startSignalHandlers();
554 /* Check whether any waiting threads need to be woken up. If the
555 * run queue is empty, and there are no other tasks running, we
556 * can wait indefinitely for something to happen.
557 * ToDo: what if another client comes along & requests another
560 if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue) ) {
561 awaitEvent( EMPTY_RUN_QUEUE()
563 && allFreeCapabilities()
567 /* we can be interrupted while waiting for I/O... */
568 if (interrupted) continue;
571 * Detect deadlock: when we have no threads to run, there are no
572 * threads waiting on I/O or sleeping, and all the other tasks are
573 * waiting for work, we must have a deadlock of some description.
575 * We first try to find threads blocked on themselves (ie. black
576 * holes), and generate NonTermination exceptions where necessary.
578 * If no threads are black holed, we have a deadlock situation, so
579 * inform all the main threads.
582 if ( EMPTY_RUN_QUEUE()
583 && EMPTY_QUEUE(blocked_queue_hd)
584 && EMPTY_QUEUE(sleeping_queue)
585 #if defined(RTS_SUPPORTS_THREADS)
586 && EMPTY_QUEUE(suspended_ccalling_threads)
589 && allFreeCapabilities()
593 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
594 #if defined(THREADED_RTS)
595 /* and SMP mode ..? */
596 releaseCapability(cap);
598 GarbageCollect(GetRoots,rtsTrue);
599 if ( EMPTY_QUEUE(blocked_queue_hd)
601 && EMPTY_QUEUE(sleeping_queue) ) {
603 IF_DEBUG(scheduler, sched_belch("still deadlocked, checking for black holes..."));
606 /* No black holes, so probably a real deadlock. Send the
607 * current main thread the Deadlock exception (or in the SMP
608 * build, send *all* main threads the deadlock exception,
609 * since none of them can make progress).
611 if ( EMPTY_RUN_QUEUE() ) {
613 #if defined(RTS_SUPPORTS_THREADS)
614 for (m = main_threads; m != NULL; m = m->link) {
615 switch (m->tso->why_blocked) {
616 case BlockedOnBlackHole:
617 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
619 case BlockedOnException:
621 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
624 barf("deadlock: main thread blocked in a strange way");
629 switch (m->tso->why_blocked) {
630 case BlockedOnBlackHole:
631 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
633 case BlockedOnException:
635 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
638 barf("deadlock: main thread blocked in a strange way");
642 #if defined(RTS_SUPPORTS_THREADS)
643 /* ToDo: revisit conditions (and mechanism) for shutting
644 down a multi-threaded world */
645 if ( EMPTY_RUN_QUEUE() ) {
646 IF_DEBUG(scheduler, sched_belch("all done, i think...shutting down."));
647 shutdownHaskellAndExit(0);
650 ASSERT( !EMPTY_RUN_QUEUE() );
654 /* ToDo: add deadlock detection in GUM (similar to SMP) -- HWL */
658 /* If there's a GC pending, don't do anything until it has
662 IF_DEBUG(scheduler,sched_belch("waiting for GC"));
663 waitCondition( &gc_pending_cond, &sched_mutex );
667 #if defined(RTS_SUPPORTS_THREADS)
668 /* block until we've got a thread on the run queue and a free
672 if ( EMPTY_RUN_QUEUE() ) {
673 /* Give up our capability */
674 releaseCapability(cap);
675 IF_DEBUG(scheduler, sched_belch("thread %d: waiting for work", osThreadId()));
676 waitForWorkCapability(&sched_mutex, &cap, rtsTrue);
677 IF_DEBUG(scheduler, sched_belch("thread %d: work now available", osThreadId()));
679 while ( EMPTY_RUN_QUEUE() ) {
680 waitForWorkCapability(&sched_mutex, &cap);
681 IF_DEBUG(scheduler, sched_belch("thread %d: work now available", osThreadId()));
688 if (RtsFlags.GranFlags.Light)
689 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
691 /* adjust time based on time-stamp */
692 if (event->time > CurrentTime[CurrentProc] &&
693 event->evttype != ContinueThread)
694 CurrentTime[CurrentProc] = event->time;
696 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
697 if (!RtsFlags.GranFlags.Light)
700 IF_DEBUG(gran, fprintf(stderr, "GRAN: switch by event-type\n"));
702 /* main event dispatcher in GranSim */
703 switch (event->evttype) {
704 /* Should just be continuing execution */
706 IF_DEBUG(gran, fprintf(stderr, "GRAN: doing ContinueThread\n"));
707 /* ToDo: check assertion
708 ASSERT(run_queue_hd != (StgTSO*)NULL &&
709 run_queue_hd != END_TSO_QUEUE);
711 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
712 if (!RtsFlags.GranFlags.DoAsyncFetch &&
713 procStatus[CurrentProc]==Fetching) {
714 belch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]",
715 CurrentTSO->id, CurrentTSO, CurrentProc);
718 /* Ignore ContinueThreads for completed threads */
719 if (CurrentTSO->what_next == ThreadComplete) {
720 belch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)",
721 CurrentTSO->id, CurrentTSO, CurrentProc);
724 /* Ignore ContinueThreads for threads that are being migrated */
725 if (PROCS(CurrentTSO)==Nowhere) {
726 belch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)",
727 CurrentTSO->id, CurrentTSO, CurrentProc);
730 /* The thread should be at the beginning of the run queue */
731 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
732 belch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread",
733 CurrentTSO->id, CurrentTSO, CurrentProc);
734 break; // run the thread anyway
737 new_event(proc, proc, CurrentTime[proc],
739 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
741 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
742 break; // now actually run the thread; DaH Qu'vam yImuHbej
745 do_the_fetchnode(event);
746 goto next_thread; /* handle next event in event queue */
749 do_the_globalblock(event);
750 goto next_thread; /* handle next event in event queue */
753 do_the_fetchreply(event);
754 goto next_thread; /* handle next event in event queue */
756 case UnblockThread: /* Move from the blocked queue to the tail of */
757 do_the_unblock(event);
758 goto next_thread; /* handle next event in event queue */
760 case ResumeThread: /* Move from the blocked queue to the tail of */
761 /* the runnable queue ( i.e. Qu' SImqa'lu') */
762 event->tso->gran.blocktime +=
763 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
764 do_the_startthread(event);
765 goto next_thread; /* handle next event in event queue */
768 do_the_startthread(event);
769 goto next_thread; /* handle next event in event queue */
772 do_the_movethread(event);
773 goto next_thread; /* handle next event in event queue */
776 do_the_movespark(event);
777 goto next_thread; /* handle next event in event queue */
780 do_the_findwork(event);
781 goto next_thread; /* handle next event in event queue */
784 barf("Illegal event type %u\n", event->evttype);
787 /* This point was scheduler_loop in the old RTS */
789 IF_DEBUG(gran, belch("GRAN: after main switch"));
791 TimeOfLastEvent = CurrentTime[CurrentProc];
792 TimeOfNextEvent = get_time_of_next_event();
793 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
794 // CurrentTSO = ThreadQueueHd;
796 IF_DEBUG(gran, belch("GRAN: time of next event is: %ld",
799 if (RtsFlags.GranFlags.Light)
800 GranSimLight_leave_system(event, &ActiveTSO);
802 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
805 belch("GRAN: end of time-slice is %#lx", EndOfTimeSlice));
807 /* in a GranSim setup the TSO stays on the run queue */
809 /* Take a thread from the run queue. */
810 t = POP_RUN_QUEUE(); // take_off_run_queue(t);
813 fprintf(stderr, "GRAN: About to run current thread, which is\n");
816 context_switch = 0; // turned on via GranYield, checking events and time slice
819 DumpGranEvent(GR_SCHEDULE, t));
821 procStatus[CurrentProc] = Busy;
824 if (PendingFetches != END_BF_QUEUE) {
828 /* ToDo: phps merge with spark activation above */
829 /* check whether we have local work and send requests if we have none */
830 if (EMPTY_RUN_QUEUE()) { /* no runnable threads */
831 /* :-[ no local threads => look out for local sparks */
832 /* the spark pool for the current PE */
833 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
834 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
835 pool->hd < pool->tl) {
837 * ToDo: add GC code check that we really have enough heap afterwards!!
839 * If we're here (no runnable threads) and we have pending
840 * sparks, we must have a space problem. Get enough space
841 * to turn one of those pending sparks into a
845 spark = findSpark(rtsFalse); /* get a spark */
846 if (spark != (rtsSpark) NULL) {
847 tso = activateSpark(spark); /* turn the spark into a thread */
848 IF_PAR_DEBUG(schedule,
849 belch("==== schedule: Created TSO %d (%p); %d threads active",
850 tso->id, tso, advisory_thread_count));
852 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
853 belch("==^^ failed to activate spark");
855 } /* otherwise fall through & pick-up new tso */
857 IF_PAR_DEBUG(verbose,
858 belch("==^^ no local sparks (spark pool contains only NFs: %d)",
859 spark_queue_len(pool)));
864 /* If we still have no work we need to send a FISH to get a spark
867 if (EMPTY_RUN_QUEUE()) {
868 /* =8-[ no local sparks => look for work on other PEs */
870 * We really have absolutely no work. Send out a fish
871 * (there may be some out there already), and wait for
872 * something to arrive. We clearly can't run any threads
873 * until a SCHEDULE or RESUME arrives, and so that's what
874 * we're hoping to see. (Of course, we still have to
875 * respond to other types of messages.)
877 TIME now = msTime() /*CURRENT_TIME*/;
878 IF_PAR_DEBUG(verbose,
879 belch("-- now=%ld", now));
880 IF_PAR_DEBUG(verbose,
881 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
882 (last_fish_arrived_at!=0 &&
883 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
884 belch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)",
885 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
886 last_fish_arrived_at,
887 RtsFlags.ParFlags.fishDelay, now);
890 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
891 (last_fish_arrived_at==0 ||
892 (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
893 /* outstandingFishes is set in sendFish, processFish;
894 avoid flooding system with fishes via delay */
896 sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY,
899 // Global statistics: count no. of fishes
900 if (RtsFlags.ParFlags.ParStats.Global &&
901 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
902 globalParStats.tot_fish_mess++;
906 receivedFinish = processMessages();
909 } else if (PacketsWaiting()) { /* Look for incoming messages */
910 receivedFinish = processMessages();
913 /* Now we are sure that we have some work available */
914 ASSERT(run_queue_hd != END_TSO_QUEUE);
916 /* Take a thread from the run queue, if we have work */
917 t = POP_RUN_QUEUE(); // take_off_run_queue(END_TSO_QUEUE);
918 IF_DEBUG(sanity,checkTSO(t));
920 /* ToDo: write something to the log-file
921 if (RTSflags.ParFlags.granSimStats && !sameThread)
922 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
926 /* the spark pool for the current PE */
927 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
930 belch("--=^ %d threads, %d sparks on [%#x]",
931 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
934 if (0 && RtsFlags.ParFlags.ParStats.Full &&
935 t && LastTSO && t->id != LastTSO->id &&
936 LastTSO->why_blocked == NotBlocked &&
937 LastTSO->what_next != ThreadComplete) {
938 // if previously scheduled TSO not blocked we have to record the context switch
939 DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
940 GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
943 if (RtsFlags.ParFlags.ParStats.Full &&
944 (emitSchedule /* forced emit */ ||
945 (t && LastTSO && t->id != LastTSO->id))) {
947 we are running a different TSO, so write a schedule event to log file
948 NB: If we use fair scheduling we also have to write a deschedule
949 event for LastTSO; with unfair scheduling we know that the
950 previous tso has blocked whenever we switch to another tso, so
951 we don't need it in GUM for now
953 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
954 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
955 emitSchedule = rtsFalse;
959 #else /* !GRAN && !PAR */
961 /* grab a thread from the run queue */
962 ASSERT(run_queue_hd != END_TSO_QUEUE);
964 // Sanity check the thread we're about to run. This can be
965 // expensive if there is lots of thread switching going on...
966 IF_DEBUG(sanity,checkTSO(t));
969 grabCapability(&cap);
970 cap->r.rCurrentTSO = t;
972 /* context switches are now initiated by the timer signal, unless
973 * the user specified "context switch as often as possible", with
978 RtsFlags.ProfFlags.profileInterval == 0 ||
980 (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
981 && (run_queue_hd != END_TSO_QUEUE
982 || blocked_queue_hd != END_TSO_QUEUE
983 || sleeping_queue != END_TSO_QUEUE)))
988 RELEASE_LOCK(&sched_mutex);
990 IF_DEBUG(scheduler, sched_belch("-->> Running TSO %ld (%p) %s ...",
991 t->id, t, whatNext_strs[t->what_next]));
994 startHeapProfTimer();
997 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
998 /* Run the current thread
1000 switch (cap->r.rCurrentTSO->what_next) {
1002 case ThreadComplete:
1003 /* Thread already finished, return to scheduler. */
1004 ret = ThreadFinished;
1006 case ThreadEnterGHC:
1007 ret = StgRun((StgFunPtr) stg_enterStackTop, &cap->r);
1010 ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
1012 case ThreadEnterInterp:
1013 ret = interpretBCO(cap);
1016 barf("schedule: invalid what_next field");
1018 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1020 /* Costs for the scheduler are assigned to CCS_SYSTEM */
1022 stopHeapProfTimer();
1026 ACQUIRE_LOCK(&sched_mutex);
1029 IF_DEBUG(scheduler,fprintf(stderr,"scheduler (task %ld): ", osThreadId()););
1030 #elif !defined(GRAN) && !defined(PAR)
1031 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: "););
1033 t = cap->r.rCurrentTSO;
1036 /* HACK 675: if the last thread didn't yield, make sure to print a
1037 SCHEDULE event to the log file when StgRunning the next thread, even
1038 if it is the same one as before */
1040 TimeOfLastYield = CURRENT_TIME;
1046 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
1047 globalGranStats.tot_heapover++;
1049 globalParStats.tot_heapover++;
1052 // did the task ask for a large block?
1053 if (cap->r.rHpAlloc > BLOCK_SIZE_W) {
1054 // if so, get one and push it on the front of the nursery.
1058 blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc * sizeof(W_)) / BLOCK_SIZE;
1060 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: requesting a large block (size %d)",
1062 whatNext_strs[t->what_next], blocks));
1064 // don't do this if it would push us over the
1065 // alloc_blocks_lim limit; we'll GC first.
1066 if (alloc_blocks + blocks < alloc_blocks_lim) {
1068 alloc_blocks += blocks;
1069 bd = allocGroup( blocks );
1071 // link the new group into the list
1072 bd->link = cap->r.rCurrentNursery;
1073 bd->u.back = cap->r.rCurrentNursery->u.back;
1074 if (cap->r.rCurrentNursery->u.back != NULL) {
1075 cap->r.rCurrentNursery->u.back->link = bd;
1077 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1078 g0s0->blocks == cap->r.rNursery);
1079 cap->r.rNursery = g0s0->blocks = bd;
1081 cap->r.rCurrentNursery->u.back = bd;
1083 // initialise it as a nursery block
1087 bd->free = bd->start;
1089 // don't forget to update the block count in g0s0.
1090 g0s0->n_blocks += blocks;
1091 ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1093 // now update the nursery to point to the new block
1094 cap->r.rCurrentNursery = bd;
1096 // we might be unlucky and have another thread get on the
1097 // run queue before us and steal the large block, but in that
1098 // case the thread will just end up requesting another large
1100 PUSH_ON_RUN_QUEUE(t);
1105 /* make all the running tasks block on a condition variable,
1106 * maybe set context_switch and wait till they all pile in,
1107 * then have them wait on a GC condition variable.
1109 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: HeapOverflow",
1110 t->id, t, whatNext_strs[t->what_next]));
1113 ASSERT(!is_on_queue(t,CurrentProc));
1115 /* Currently we emit a DESCHEDULE event before GC in GUM.
1116 ToDo: either add separate event to distinguish SYSTEM time from rest
1117 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1118 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1119 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1120 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1121 emitSchedule = rtsTrue;
1125 ready_to_gc = rtsTrue;
1126 context_switch = 1; /* stop other threads ASAP */
1127 PUSH_ON_RUN_QUEUE(t);
1128 /* actual GC is done at the end of the while loop */
1134 DumpGranEvent(GR_DESCHEDULE, t));
1135 globalGranStats.tot_stackover++;
1138 // DumpGranEvent(GR_DESCHEDULE, t);
1139 globalParStats.tot_stackover++;
1141 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped, StackOverflow",
1142 t->id, t, whatNext_strs[t->what_next]));
1143 /* just adjust the stack for this thread, then pop it back
1149 /* enlarge the stack */
1150 StgTSO *new_t = threadStackOverflow(t);
1152 /* This TSO has moved, so update any pointers to it from the
1153 * main thread stack. It better not be on any other queues...
1154 * (it shouldn't be).
1156 for (m = main_threads; m != NULL; m = m->link) {
1161 threadPaused(new_t);
1162 PUSH_ON_RUN_QUEUE(new_t);
1166 case ThreadYielding:
1169 DumpGranEvent(GR_DESCHEDULE, t));
1170 globalGranStats.tot_yields++;
1173 // DumpGranEvent(GR_DESCHEDULE, t);
1174 globalParStats.tot_yields++;
1176 /* put the thread back on the run queue. Then, if we're ready to
1177 * GC, check whether this is the last task to stop. If so, wake
1178 * up the GC thread. getThread will block during a GC until the
1182 if (t->what_next == ThreadEnterInterp) {
1183 /* ToDo: or maybe a timer expired when we were in Hugs?
1184 * or maybe someone hit ctrl-C
1186 belch("--<< thread %ld (%p; %s) stopped to switch to Hugs",
1187 t->id, t, whatNext_strs[t->what_next]);
1189 belch("--<< thread %ld (%p; %s) stopped, yielding",
1190 t->id, t, whatNext_strs[t->what_next]);
1197 //belch("&& Doing sanity check on yielding TSO %ld.", t->id);
1199 ASSERT(t->link == END_TSO_QUEUE);
1201 ASSERT(!is_on_queue(t,CurrentProc));
1204 //belch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1205 checkThreadQsSanity(rtsTrue));
1208 if (RtsFlags.ParFlags.doFairScheduling) {
1209 /* this does round-robin scheduling; good for concurrency */
1210 APPEND_TO_RUN_QUEUE(t);
1212 /* this does unfair scheduling; good for parallelism */
1213 PUSH_ON_RUN_QUEUE(t);
1216 /* this does round-robin scheduling; good for concurrency */
1217 APPEND_TO_RUN_QUEUE(t);
1220 /* add a ContinueThread event to actually process the thread */
1221 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1223 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1225 belch("GRAN: eventq and runnableq after adding yielded thread to queue again:");
1234 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1235 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)));
1236 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1238 // ??? needed; should emit block before
1240 DumpGranEvent(GR_DESCHEDULE, t));
1241 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1244 ASSERT(procStatus[CurrentProc]==Busy ||
1245 ((procStatus[CurrentProc]==Fetching) &&
1246 (t->block_info.closure!=(StgClosure*)NULL)));
1247 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1248 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1249 procStatus[CurrentProc]==Fetching))
1250 procStatus[CurrentProc] = Idle;
1254 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: ",
1255 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1258 if (t->block_info.closure!=(StgClosure*)NULL)
1259 print_bq(t->block_info.closure));
1261 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1264 /* whatever we schedule next, we must log that schedule */
1265 emitSchedule = rtsTrue;
1268 /* don't need to do anything. Either the thread is blocked on
1269 * I/O, in which case we'll have called addToBlockedQueue
1270 * previously, or it's blocked on an MVar or Blackhole, in which
1271 * case it'll be on the relevant queue already.
1274 fprintf(stderr, "--<< thread %d (%p) stopped: ", t->id, t);
1275 printThreadBlockage(t);
1276 fprintf(stderr, "\n"));
1278 /* Only for dumping event to log file
1279 ToDo: do I need this in GranSim, too?
1286 case ThreadFinished:
1287 /* Need to check whether this was a main thread, and if so, signal
1288 * the task that started it with the return value. If we have no
1289 * more main threads, we probably need to stop all the tasks until
1292 /* We also end up here if the thread kills itself with an
1293 * uncaught exception, see Exception.hc.
1295 IF_DEBUG(scheduler,belch("--++ thread %d (%p) finished", t->id, t));
1297 endThread(t, CurrentProc); // clean-up the thread
1299 /* For now all are advisory -- HWL */
1300 //if(t->priority==AdvisoryPriority) ??
1301 advisory_thread_count--;
1304 if(t->dist.priority==RevalPriority)
1308 if (RtsFlags.ParFlags.ParStats.Full &&
1309 !RtsFlags.ParFlags.ParStats.Suppressed)
1310 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1315 barf("schedule: invalid thread return code %d", (int)ret);
1318 #if defined(RTS_SUPPORTS_THREADS)
1319 /* I don't understand what this re-grab is doing -- sof */
1320 grabCapability(&cap);
1324 if (RtsFlags.ProfFlags.profileInterval==0 || performHeapProfile) {
1325 GarbageCollect(GetRoots, rtsTrue);
1327 performHeapProfile = rtsFalse;
1328 ready_to_gc = rtsFalse; // we already GC'd
1334 && allFreeCapabilities()
1337 /* everybody back, start the GC.
1338 * Could do it in this thread, or signal a condition var
1339 * to do it in another thread. Either way, we need to
1340 * broadcast on gc_pending_cond afterward.
1342 #if defined(RTS_SUPPORTS_THREADS)
1343 IF_DEBUG(scheduler,sched_belch("doing GC"));
1345 GarbageCollect(GetRoots,rtsFalse);
1346 ready_to_gc = rtsFalse;
1348 broadcastCondition(&gc_pending_cond);
1351 /* add a ContinueThread event to continue execution of current thread */
1352 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1354 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1356 fprintf(stderr, "GRAN: eventq and runnableq after Garbage collection:\n");
1364 IF_GRAN_DEBUG(unused,
1365 print_eventq(EventHd));
1367 event = get_next_event();
1370 /* ToDo: wait for next message to arrive rather than busy wait */
1373 } /* end of while(1) */
1375 IF_PAR_DEBUG(verbose,
1376 belch("== Leaving schedule() after having received Finish"));
1379 /* ---------------------------------------------------------------------------
1380 * deleteAllThreads(): kill all the live threads.
1382 * This is used when we catch a user interrupt (^C), before performing
1383 * any necessary cleanups and running finalizers.
1384 * ------------------------------------------------------------------------- */
1386 void deleteAllThreads ( void )
1389 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
1390 for (t = run_queue_hd; t != END_TSO_QUEUE; t = next) {
1394 for (t = blocked_queue_hd; t != END_TSO_QUEUE; t = next) {
1398 for (t = sleeping_queue; t != END_TSO_QUEUE; t = next) {
1402 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1403 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
1404 sleeping_queue = END_TSO_QUEUE;
1407 /* startThread and insertThread are now in GranSim.c -- HWL */
1410 //@node Suspend and Resume, Run queue code, Main scheduling loop, Main scheduling code
1411 //@subsection Suspend and Resume
1413 /* ---------------------------------------------------------------------------
1414 * Suspending & resuming Haskell threads.
1416 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1417 * its capability before calling the C function. This allows another
1418 * task to pick up the capability and carry on running Haskell
1419 * threads. It also means that if the C call blocks, it won't lock
1422 * The Haskell thread making the C call is put to sleep for the
1423 * duration of the call, on the susepended_ccalling_threads queue. We
1424 * give out a token to the task, which it can use to resume the thread
1425 * on return from the C function.
1426 * ------------------------------------------------------------------------- */
1429 suspendThread( StgRegTable *reg, rtsBool concCall )
1434 /* assume that *reg is a pointer to the StgRegTable part
1437 cap = (Capability *)((void *)reg - sizeof(StgFunTable));
1439 ACQUIRE_LOCK(&sched_mutex);
1442 sched_belch("thread %d did a _ccall_gc", cap->r.rCurrentTSO->id));
1444 threadPaused(cap->r.rCurrentTSO);
1445 cap->r.rCurrentTSO->link = suspended_ccalling_threads;
1446 suspended_ccalling_threads = cap->r.rCurrentTSO;
1448 #if defined(RTS_SUPPORTS_THREADS)
1449 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall;
1452 /* Use the thread ID as the token; it should be unique */
1453 tok = cap->r.rCurrentTSO->id;
1455 /* Hand back capability */
1456 releaseCapability(cap);
1458 #if defined(RTS_SUPPORTS_THREADS)
1459 /* Preparing to leave the RTS, so ensure there's a native thread/task
1460 waiting to take over.
1462 ToDo: optimise this and only create a new task if there's a need
1463 for one (i.e., if there's only one Concurrent Haskell thread alive,
1464 there's no need to create a new task).
1466 IF_DEBUG(scheduler, sched_belch("worker thread (%d): leaving RTS", tok));
1468 startTask(taskStart);
1472 /* Other threads _might_ be available for execution; signal this */
1474 RELEASE_LOCK(&sched_mutex);
1479 resumeThread( StgInt tok, rtsBool concCall )
1481 StgTSO *tso, **prev;
1484 #if defined(RTS_SUPPORTS_THREADS)
1485 /* Wait for permission to re-enter the RTS with the result. */
1487 grabReturnCapability(&sched_mutex, &cap);
1489 grabCapability(&cap);
1492 grabCapability(&cap);
1495 /* Remove the thread off of the suspended list */
1496 prev = &suspended_ccalling_threads;
1497 for (tso = suspended_ccalling_threads;
1498 tso != END_TSO_QUEUE;
1499 prev = &tso->link, tso = tso->link) {
1500 if (tso->id == (StgThreadID)tok) {
1505 if (tso == END_TSO_QUEUE) {
1506 barf("resumeThread: thread not found");
1508 tso->link = END_TSO_QUEUE;
1509 /* Reset blocking status */
1510 tso->why_blocked = NotBlocked;
1512 RELEASE_LOCK(&sched_mutex);
1514 cap->r.rCurrentTSO = tso;
1519 /* ---------------------------------------------------------------------------
1521 * ------------------------------------------------------------------------ */
1522 static void unblockThread(StgTSO *tso);
1524 /* ---------------------------------------------------------------------------
1525 * Comparing Thread ids.
1527 * This is used from STG land in the implementation of the
1528 * instances of Eq/Ord for ThreadIds.
1529 * ------------------------------------------------------------------------ */
1531 int cmp_thread(const StgTSO *tso1, const StgTSO *tso2)
1533 StgThreadID id1 = tso1->id;
1534 StgThreadID id2 = tso2->id;
1536 if (id1 < id2) return (-1);
1537 if (id1 > id2) return 1;
1541 /* ---------------------------------------------------------------------------
1542 * Fetching the ThreadID from an StgTSO.
1544 * This is used in the implementation of Show for ThreadIds.
1545 * ------------------------------------------------------------------------ */
1546 int rts_getThreadId(const StgTSO *tso)
1551 /* ---------------------------------------------------------------------------
1552 Create a new thread.
1554 The new thread starts with the given stack size. Before the
1555 scheduler can run, however, this thread needs to have a closure
1556 (and possibly some arguments) pushed on its stack. See
1557 pushClosure() in Schedule.h.
1559 createGenThread() and createIOThread() (in SchedAPI.h) are
1560 convenient packaged versions of this function.
1562 currently pri (priority) is only used in a GRAN setup -- HWL
1563 ------------------------------------------------------------------------ */
1564 //@cindex createThread
1566 /* currently pri (priority) is only used in a GRAN setup -- HWL */
1568 createThread(nat stack_size, StgInt pri)
1570 return createThread_(stack_size, rtsFalse, pri);
1574 createThread_(nat size, rtsBool have_lock, StgInt pri)
1578 createThread(nat stack_size)
1580 return createThread_(stack_size, rtsFalse);
1584 createThread_(nat size, rtsBool have_lock)
1591 /* First check whether we should create a thread at all */
1593 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1594 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1596 belch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1597 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1598 return END_TSO_QUEUE;
1604 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
1607 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
1609 /* catch ridiculously small stack sizes */
1610 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
1611 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
1614 stack_size = size - TSO_STRUCT_SIZEW;
1616 tso = (StgTSO *)allocate(size);
1617 TICK_ALLOC_TSO(stack_size, 0);
1619 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
1621 SET_GRAN_HDR(tso, ThisPE);
1623 tso->what_next = ThreadEnterGHC;
1625 /* tso->id needs to be unique. For now we use a heavyweight mutex to
1626 * protect the increment operation on next_thread_id.
1627 * In future, we could use an atomic increment instead.
1629 if (!have_lock) { ACQUIRE_LOCK(&sched_mutex); }
1630 tso->id = next_thread_id++;
1631 if (!have_lock) { RELEASE_LOCK(&sched_mutex); }
1633 tso->why_blocked = NotBlocked;
1634 tso->blocked_exceptions = NULL;
1636 tso->stack_size = stack_size;
1637 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
1639 tso->sp = (P_)&(tso->stack) + stack_size;
1642 tso->prof.CCCS = CCS_MAIN;
1645 /* put a stop frame on the stack */
1646 tso->sp -= sizeofW(StgStopFrame);
1647 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
1648 tso->su = (StgUpdateFrame*)tso->sp;
1652 tso->link = END_TSO_QUEUE;
1653 /* uses more flexible routine in GranSim */
1654 insertThread(tso, CurrentProc);
1656 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
1662 if (RtsFlags.GranFlags.GranSimStats.Full)
1663 DumpGranEvent(GR_START,tso);
1665 if (RtsFlags.ParFlags.ParStats.Full)
1666 DumpGranEvent(GR_STARTQ,tso);
1667 /* HACk to avoid SCHEDULE
1671 /* Link the new thread on the global thread list.
1673 tso->global_link = all_threads;
1677 tso->dist.priority = MandatoryPriority; //by default that is...
1681 tso->gran.pri = pri;
1683 tso->gran.magic = TSO_MAGIC; // debugging only
1685 tso->gran.sparkname = 0;
1686 tso->gran.startedat = CURRENT_TIME;
1687 tso->gran.exported = 0;
1688 tso->gran.basicblocks = 0;
1689 tso->gran.allocs = 0;
1690 tso->gran.exectime = 0;
1691 tso->gran.fetchtime = 0;
1692 tso->gran.fetchcount = 0;
1693 tso->gran.blocktime = 0;
1694 tso->gran.blockcount = 0;
1695 tso->gran.blockedat = 0;
1696 tso->gran.globalsparks = 0;
1697 tso->gran.localsparks = 0;
1698 if (RtsFlags.GranFlags.Light)
1699 tso->gran.clock = Now; /* local clock */
1701 tso->gran.clock = 0;
1703 IF_DEBUG(gran,printTSO(tso));
1706 tso->par.magic = TSO_MAGIC; // debugging only
1708 tso->par.sparkname = 0;
1709 tso->par.startedat = CURRENT_TIME;
1710 tso->par.exported = 0;
1711 tso->par.basicblocks = 0;
1712 tso->par.allocs = 0;
1713 tso->par.exectime = 0;
1714 tso->par.fetchtime = 0;
1715 tso->par.fetchcount = 0;
1716 tso->par.blocktime = 0;
1717 tso->par.blockcount = 0;
1718 tso->par.blockedat = 0;
1719 tso->par.globalsparks = 0;
1720 tso->par.localsparks = 0;
1724 globalGranStats.tot_threads_created++;
1725 globalGranStats.threads_created_on_PE[CurrentProc]++;
1726 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
1727 globalGranStats.tot_sq_probes++;
1729 // collect parallel global statistics (currently done together with GC stats)
1730 if (RtsFlags.ParFlags.ParStats.Global &&
1731 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1732 //fprintf(stderr, "Creating thread %d @ %11.2f\n", tso->id, usertime());
1733 globalParStats.tot_threads_created++;
1739 belch("==__ schedule: Created TSO %d (%p);",
1740 CurrentProc, tso, tso->id));
1742 IF_PAR_DEBUG(verbose,
1743 belch("==__ schedule: Created TSO %d (%p); %d threads active",
1744 tso->id, tso, advisory_thread_count));
1746 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
1747 tso->id, tso->stack_size));
1754 all parallel thread creation calls should fall through the following routine.
1757 createSparkThread(rtsSpark spark)
1759 ASSERT(spark != (rtsSpark)NULL);
1760 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
1762 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1763 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1764 return END_TSO_QUEUE;
1768 tso = createThread_(RtsFlags.GcFlags.initialStkSize, rtsTrue);
1769 if (tso==END_TSO_QUEUE)
1770 barf("createSparkThread: Cannot create TSO");
1772 tso->priority = AdvisoryPriority;
1774 pushClosure(tso,spark);
1775 PUSH_ON_RUN_QUEUE(tso);
1776 advisory_thread_count++;
1783 Turn a spark into a thread.
1784 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
1787 //@cindex activateSpark
1789 activateSpark (rtsSpark spark)
1793 tso = createSparkThread(spark);
1794 if (RtsFlags.ParFlags.ParStats.Full) {
1795 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
1796 IF_PAR_DEBUG(verbose,
1797 belch("==^^ activateSpark: turning spark of closure %p (%s) into a thread",
1798 (StgClosure *)spark, info_type((StgClosure *)spark)));
1800 // ToDo: fwd info on local/global spark to thread -- HWL
1801 // tso->gran.exported = spark->exported;
1802 // tso->gran.locked = !spark->global;
1803 // tso->gran.sparkname = spark->name;
1809 /* ---------------------------------------------------------------------------
1812 * scheduleThread puts a thread on the head of the runnable queue.
1813 * This will usually be done immediately after a thread is created.
1814 * The caller of scheduleThread must create the thread using e.g.
1815 * createThread and push an appropriate closure
1816 * on this thread's stack before the scheduler is invoked.
1817 * ------------------------------------------------------------------------ */
1819 static void scheduleThread_ (StgTSO* tso, rtsBool createTask);
1822 scheduleThread_(StgTSO *tso
1823 , rtsBool createTask
1824 #if !defined(THREADED_RTS)
1829 ACQUIRE_LOCK(&sched_mutex);
1831 /* Put the new thread on the head of the runnable queue. The caller
1832 * better push an appropriate closure on this thread's stack
1833 * beforehand. In the SMP case, the thread may start running as
1834 * soon as we release the scheduler lock below.
1836 PUSH_ON_RUN_QUEUE(tso);
1837 #if defined(THREADED_RTS)
1838 /* If main() is scheduling a thread, don't bother creating a
1842 startTask(taskStart);
1848 IF_DEBUG(scheduler,printTSO(tso));
1850 RELEASE_LOCK(&sched_mutex);
1853 void scheduleThread(StgTSO* tso)
1855 return scheduleThread_(tso, rtsFalse);
1858 void scheduleExtThread(StgTSO* tso)
1860 return scheduleThread_(tso, rtsTrue);
1863 /* ---------------------------------------------------------------------------
1866 * Initialise the scheduler. This resets all the queues - if the
1867 * queues contained any threads, they'll be garbage collected at the
1870 * ------------------------------------------------------------------------ */
1874 term_handler(int sig STG_UNUSED)
1877 ACQUIRE_LOCK(&term_mutex);
1879 RELEASE_LOCK(&term_mutex);
1890 for (i=0; i<=MAX_PROC; i++) {
1891 run_queue_hds[i] = END_TSO_QUEUE;
1892 run_queue_tls[i] = END_TSO_QUEUE;
1893 blocked_queue_hds[i] = END_TSO_QUEUE;
1894 blocked_queue_tls[i] = END_TSO_QUEUE;
1895 ccalling_threadss[i] = END_TSO_QUEUE;
1896 sleeping_queue = END_TSO_QUEUE;
1899 run_queue_hd = END_TSO_QUEUE;
1900 run_queue_tl = END_TSO_QUEUE;
1901 blocked_queue_hd = END_TSO_QUEUE;
1902 blocked_queue_tl = END_TSO_QUEUE;
1903 sleeping_queue = END_TSO_QUEUE;
1906 suspended_ccalling_threads = END_TSO_QUEUE;
1908 main_threads = NULL;
1909 all_threads = END_TSO_QUEUE;
1914 RtsFlags.ConcFlags.ctxtSwitchTicks =
1915 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
1917 #if defined(RTS_SUPPORTS_THREADS)
1918 /* Initialise the mutex and condition variables used by
1920 initMutex(&sched_mutex);
1921 initMutex(&term_mutex);
1923 initCondition(&thread_ready_cond);
1927 initCondition(&gc_pending_cond);
1930 #if defined(RTS_SUPPORTS_THREADS)
1931 ACQUIRE_LOCK(&sched_mutex);
1934 /* Install the SIGHUP handler */
1937 struct sigaction action,oact;
1939 action.sa_handler = term_handler;
1940 sigemptyset(&action.sa_mask);
1941 action.sa_flags = 0;
1942 if (sigaction(SIGTERM, &action, &oact) != 0) {
1943 barf("can't install TERM handler");
1948 /* A capability holds the state a native thread needs in
1949 * order to execute STG code. At least one capability is
1950 * floating around (only SMP builds have more than one).
1954 #if defined(RTS_SUPPORTS_THREADS)
1955 /* start our haskell execution tasks */
1957 startTaskManager(RtsFlags.ParFlags.nNodes, taskStart);
1959 startTaskManager(0,taskStart);
1963 #if /* defined(SMP) ||*/ defined(PAR)
1967 #if defined(RTS_SUPPORTS_THREADS)
1968 RELEASE_LOCK(&sched_mutex);
1974 exitScheduler( void )
1976 #if defined(RTS_SUPPORTS_THREADS)
1981 /* -----------------------------------------------------------------------------
1982 Managing the per-task allocation areas.
1984 Each capability comes with an allocation area. These are
1985 fixed-length block lists into which allocation can be done.
1987 ToDo: no support for two-space collection at the moment???
1988 -------------------------------------------------------------------------- */
1990 /* -----------------------------------------------------------------------------
1991 * waitThread is the external interface for running a new computation
1992 * and waiting for the result.
1994 * In the non-SMP case, we create a new main thread, push it on the
1995 * main-thread stack, and invoke the scheduler to run it. The
1996 * scheduler will return when the top main thread on the stack has
1997 * completed or died, and fill in the necessary fields of the
1998 * main_thread structure.
2000 * In the SMP case, we create a main thread as before, but we then
2001 * create a new condition variable and sleep on it. When our new
2002 * main thread has completed, we'll be woken up and the status/result
2003 * will be in the main_thread struct.
2004 * -------------------------------------------------------------------------- */
2007 howManyThreadsAvail ( void )
2011 for (q = run_queue_hd; q != END_TSO_QUEUE; q = q->link)
2013 for (q = blocked_queue_hd; q != END_TSO_QUEUE; q = q->link)
2015 for (q = sleeping_queue; q != END_TSO_QUEUE; q = q->link)
2021 finishAllThreads ( void )
2024 while (run_queue_hd != END_TSO_QUEUE) {
2025 waitThread ( run_queue_hd, NULL);
2027 while (blocked_queue_hd != END_TSO_QUEUE) {
2028 waitThread ( blocked_queue_hd, NULL);
2030 while (sleeping_queue != END_TSO_QUEUE) {
2031 waitThread ( blocked_queue_hd, NULL);
2034 (blocked_queue_hd != END_TSO_QUEUE ||
2035 run_queue_hd != END_TSO_QUEUE ||
2036 sleeping_queue != END_TSO_QUEUE);
2040 waitThread(StgTSO *tso, /*out*/StgClosure **ret)
2042 #if defined(THREADED_RTS)
2043 return waitThread_(tso,ret, rtsFalse);
2045 return waitThread_(tso,ret);
2050 waitThread_(StgTSO *tso,
2051 /*out*/StgClosure **ret
2052 #if defined(THREADED_RTS)
2053 , rtsBool blockWaiting
2058 SchedulerStatus stat;
2060 ACQUIRE_LOCK(&sched_mutex);
2062 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2067 #if defined(RTS_SUPPORTS_THREADS)
2068 initCondition(&m->wakeup);
2071 m->link = main_threads;
2074 IF_DEBUG(scheduler, sched_belch("== scheduler: new main thread (%d)\n", m->tso->id));
2076 #if defined(RTS_SUPPORTS_THREADS)
2078 # if defined(THREADED_RTS)
2079 if (!blockWaiting) {
2080 /* In the threaded case, the OS thread that called main()
2081 * gets to enter the RTS directly without going via another
2084 RELEASE_LOCK(&sched_mutex);
2086 ASSERT(m->stat != NoStatus);
2090 IF_DEBUG(scheduler, sched_belch("sfoo"));
2092 waitCondition(&m->wakeup, &sched_mutex);
2093 } while (m->stat == NoStatus);
2096 /* GranSim specific init */
2097 CurrentTSO = m->tso; // the TSO to run
2098 procStatus[MainProc] = Busy; // status of main PE
2099 CurrentProc = MainProc; // PE to run it on
2103 RELEASE_LOCK(&sched_mutex);
2105 ASSERT(m->stat != NoStatus);
2110 #if defined(RTS_SUPPORTS_THREADS)
2111 closeCondition(&m->wakeup);
2114 IF_DEBUG(scheduler, fprintf(stderr, "== scheduler: main thread (%d) finished\n",
2118 #if defined(THREADED_RTS)
2121 RELEASE_LOCK(&sched_mutex);
2126 //@node Run queue code, Garbage Collextion Routines, Suspend and Resume, Main scheduling code
2127 //@subsection Run queue code
2131 NB: In GranSim we have many run queues; run_queue_hd is actually a macro
2132 unfolding to run_queue_hds[CurrentProc], thus CurrentProc is an
2133 implicit global variable that has to be correct when calling these
2137 /* Put the new thread on the head of the runnable queue.
2138 * The caller of createThread better push an appropriate closure
2139 * on this thread's stack before the scheduler is invoked.
2141 static /* inline */ void
2142 add_to_run_queue(tso)
2145 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2146 tso->link = run_queue_hd;
2148 if (run_queue_tl == END_TSO_QUEUE) {
2153 /* Put the new thread at the end of the runnable queue. */
2154 static /* inline */ void
2155 push_on_run_queue(tso)
2158 ASSERT(get_itbl((StgClosure *)tso)->type == TSO);
2159 ASSERT(run_queue_hd!=NULL && run_queue_tl!=NULL);
2160 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2161 if (run_queue_hd == END_TSO_QUEUE) {
2164 run_queue_tl->link = tso;
2170 Should be inlined because it's used very often in schedule. The tso
2171 argument is actually only needed in GranSim, where we want to have the
2172 possibility to schedule *any* TSO on the run queue, irrespective of the
2173 actual ordering. Therefore, if tso is not the nil TSO then we traverse
2174 the run queue and dequeue the tso, adjusting the links in the queue.
2176 //@cindex take_off_run_queue
2177 static /* inline */ StgTSO*
2178 take_off_run_queue(StgTSO *tso) {
2182 qetlaHbogh Qu' ngaSbogh ghomDaQ {tso} yIteq!
2184 if tso is specified, unlink that tso from the run_queue (doesn't have
2185 to be at the beginning of the queue); GranSim only
2187 if (tso!=END_TSO_QUEUE) {
2188 /* find tso in queue */
2189 for (t=run_queue_hd, prev=END_TSO_QUEUE;
2190 t!=END_TSO_QUEUE && t!=tso;
2194 /* now actually dequeue the tso */
2195 if (prev!=END_TSO_QUEUE) {
2196 ASSERT(run_queue_hd!=t);
2197 prev->link = t->link;
2199 /* t is at beginning of thread queue */
2200 ASSERT(run_queue_hd==t);
2201 run_queue_hd = t->link;
2203 /* t is at end of thread queue */
2204 if (t->link==END_TSO_QUEUE) {
2205 ASSERT(t==run_queue_tl);
2206 run_queue_tl = prev;
2208 ASSERT(run_queue_tl!=t);
2210 t->link = END_TSO_QUEUE;
2212 /* take tso from the beginning of the queue; std concurrent code */
2214 if (t != END_TSO_QUEUE) {
2215 run_queue_hd = t->link;
2216 t->link = END_TSO_QUEUE;
2217 if (run_queue_hd == END_TSO_QUEUE) {
2218 run_queue_tl = END_TSO_QUEUE;
2227 //@node Garbage Collextion Routines, Blocking Queue Routines, Run queue code, Main scheduling code
2228 //@subsection Garbage Collextion Routines
2230 /* ---------------------------------------------------------------------------
2231 Where are the roots that we know about?
2233 - all the threads on the runnable queue
2234 - all the threads on the blocked queue
2235 - all the threads on the sleeping queue
2236 - all the thread currently executing a _ccall_GC
2237 - all the "main threads"
2239 ------------------------------------------------------------------------ */
2241 /* This has to be protected either by the scheduler monitor, or by the
2242 garbage collection monitor (probably the latter).
2247 GetRoots(evac_fn evac)
2254 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2255 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2256 evac((StgClosure **)&run_queue_hds[i]);
2257 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2258 evac((StgClosure **)&run_queue_tls[i]);
2260 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2261 evac((StgClosure **)&blocked_queue_hds[i]);
2262 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2263 evac((StgClosure **)&blocked_queue_tls[i]);
2264 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2265 evac((StgClosure **)&ccalling_threads[i]);
2272 if (run_queue_hd != END_TSO_QUEUE) {
2273 ASSERT(run_queue_tl != END_TSO_QUEUE);
2274 evac((StgClosure **)&run_queue_hd);
2275 evac((StgClosure **)&run_queue_tl);
2278 if (blocked_queue_hd != END_TSO_QUEUE) {
2279 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2280 evac((StgClosure **)&blocked_queue_hd);
2281 evac((StgClosure **)&blocked_queue_tl);
2284 if (sleeping_queue != END_TSO_QUEUE) {
2285 evac((StgClosure **)&sleeping_queue);
2289 for (m = main_threads; m != NULL; m = m->link) {
2290 evac((StgClosure **)&m->tso);
2292 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2293 evac((StgClosure **)&suspended_ccalling_threads);
2296 #if defined(PAR) || defined(GRAN)
2297 markSparkQueue(evac);
2301 /* -----------------------------------------------------------------------------
2304 This is the interface to the garbage collector from Haskell land.
2305 We provide this so that external C code can allocate and garbage
2306 collect when called from Haskell via _ccall_GC.
2308 It might be useful to provide an interface whereby the programmer
2309 can specify more roots (ToDo).
2311 This needs to be protected by the GC condition variable above. KH.
2312 -------------------------------------------------------------------------- */
2314 void (*extra_roots)(evac_fn);
2319 /* Obligated to hold this lock upon entry */
2320 ACQUIRE_LOCK(&sched_mutex);
2321 GarbageCollect(GetRoots,rtsFalse);
2322 RELEASE_LOCK(&sched_mutex);
2326 performMajorGC(void)
2328 ACQUIRE_LOCK(&sched_mutex);
2329 GarbageCollect(GetRoots,rtsTrue);
2330 RELEASE_LOCK(&sched_mutex);
2334 AllRoots(evac_fn evac)
2336 GetRoots(evac); // the scheduler's roots
2337 extra_roots(evac); // the user's roots
2341 performGCWithRoots(void (*get_roots)(evac_fn))
2343 ACQUIRE_LOCK(&sched_mutex);
2344 extra_roots = get_roots;
2345 GarbageCollect(AllRoots,rtsFalse);
2346 RELEASE_LOCK(&sched_mutex);
2349 /* -----------------------------------------------------------------------------
2352 If the thread has reached its maximum stack size, then raise the
2353 StackOverflow exception in the offending thread. Otherwise
2354 relocate the TSO into a larger chunk of memory and adjust its stack
2356 -------------------------------------------------------------------------- */
2359 threadStackOverflow(StgTSO *tso)
2361 nat new_stack_size, new_tso_size, diff, stack_words;
2365 IF_DEBUG(sanity,checkTSO(tso));
2366 if (tso->stack_size >= tso->max_stack_size) {
2369 belch("@@ threadStackOverflow of TSO %d (%p): stack too large (now %ld; max is %ld",
2370 tso->id, tso, tso->stack_size, tso->max_stack_size);
2371 /* If we're debugging, just print out the top of the stack */
2372 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2375 /* Send this thread the StackOverflow exception */
2376 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2380 /* Try to double the current stack size. If that takes us over the
2381 * maximum stack size for this thread, then use the maximum instead.
2382 * Finally round up so the TSO ends up as a whole number of blocks.
2384 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2385 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2386 TSO_STRUCT_SIZE)/sizeof(W_);
2387 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2388 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2390 IF_DEBUG(scheduler, fprintf(stderr,"== scheduler: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2392 dest = (StgTSO *)allocate(new_tso_size);
2393 TICK_ALLOC_TSO(new_stack_size,0);
2395 /* copy the TSO block and the old stack into the new area */
2396 memcpy(dest,tso,TSO_STRUCT_SIZE);
2397 stack_words = tso->stack + tso->stack_size - tso->sp;
2398 new_sp = (P_)dest + new_tso_size - stack_words;
2399 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2401 /* relocate the stack pointers... */
2402 diff = (P_)new_sp - (P_)tso->sp; /* In *words* */
2403 dest->su = (StgUpdateFrame *) ((P_)dest->su + diff);
2405 dest->stack_size = new_stack_size;
2407 /* and relocate the update frame list */
2408 relocate_stack(dest, diff);
2410 /* Mark the old TSO as relocated. We have to check for relocated
2411 * TSOs in the garbage collector and any primops that deal with TSOs.
2413 * It's important to set the sp and su values to just beyond the end
2414 * of the stack, so we don't attempt to scavenge any part of the
2417 tso->what_next = ThreadRelocated;
2419 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2420 tso->su = (StgUpdateFrame *)tso->sp;
2421 tso->why_blocked = NotBlocked;
2422 dest->mut_link = NULL;
2424 IF_PAR_DEBUG(verbose,
2425 belch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld",
2426 tso->id, tso, tso->stack_size);
2427 /* If we're debugging, just print out the top of the stack */
2428 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2431 IF_DEBUG(sanity,checkTSO(tso));
2433 IF_DEBUG(scheduler,printTSO(dest));
2439 //@node Blocking Queue Routines, Exception Handling Routines, Garbage Collextion Routines, Main scheduling code
2440 //@subsection Blocking Queue Routines
2442 /* ---------------------------------------------------------------------------
2443 Wake up a queue that was blocked on some resource.
2444 ------------------------------------------------------------------------ */
2448 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2453 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2455 /* write RESUME events to log file and
2456 update blocked and fetch time (depending on type of the orig closure) */
2457 if (RtsFlags.ParFlags.ParStats.Full) {
2458 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2459 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2460 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2461 if (EMPTY_RUN_QUEUE())
2462 emitSchedule = rtsTrue;
2464 switch (get_itbl(node)->type) {
2466 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2471 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2478 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2485 static StgBlockingQueueElement *
2486 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2489 PEs node_loc, tso_loc;
2491 node_loc = where_is(node); // should be lifted out of loop
2492 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2493 tso_loc = where_is((StgClosure *)tso);
2494 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2495 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2496 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2497 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2498 // insertThread(tso, node_loc);
2499 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2501 tso, node, (rtsSpark*)NULL);
2502 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2505 } else { // TSO is remote (actually should be FMBQ)
2506 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2507 RtsFlags.GranFlags.Costs.gunblocktime +
2508 RtsFlags.GranFlags.Costs.latency;
2509 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2511 tso, node, (rtsSpark*)NULL);
2512 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2515 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2517 fprintf(stderr," %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2518 (node_loc==tso_loc ? "Local" : "Global"),
2519 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2520 tso->block_info.closure = NULL;
2521 IF_DEBUG(scheduler,belch("-- Waking up thread %ld (%p)",
2525 static StgBlockingQueueElement *
2526 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2528 StgBlockingQueueElement *next;
2530 switch (get_itbl(bqe)->type) {
2532 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2533 /* if it's a TSO just push it onto the run_queue */
2535 // ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2536 PUSH_ON_RUN_QUEUE((StgTSO *)bqe);
2538 unblockCount(bqe, node);
2539 /* reset blocking status after dumping event */
2540 ((StgTSO *)bqe)->why_blocked = NotBlocked;
2544 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2546 bqe->link = (StgBlockingQueueElement *)PendingFetches;
2547 PendingFetches = (StgBlockedFetch *)bqe;
2551 /* can ignore this case in a non-debugging setup;
2552 see comments on RBHSave closures above */
2554 /* check that the closure is an RBHSave closure */
2555 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2556 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2557 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2561 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2562 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
2566 IF_PAR_DEBUG(bq, fprintf(stderr, ", %p (%s)", bqe, info_type((StgClosure*)bqe)));
2570 #else /* !GRAN && !PAR */
2572 unblockOneLocked(StgTSO *tso)
2576 ASSERT(get_itbl(tso)->type == TSO);
2577 ASSERT(tso->why_blocked != NotBlocked);
2578 tso->why_blocked = NotBlocked;
2580 PUSH_ON_RUN_QUEUE(tso);
2582 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
2587 #if defined(GRAN) || defined(PAR)
2588 inline StgBlockingQueueElement *
2589 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2591 ACQUIRE_LOCK(&sched_mutex);
2592 bqe = unblockOneLocked(bqe, node);
2593 RELEASE_LOCK(&sched_mutex);
2598 unblockOne(StgTSO *tso)
2600 ACQUIRE_LOCK(&sched_mutex);
2601 tso = unblockOneLocked(tso);
2602 RELEASE_LOCK(&sched_mutex);
2609 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2611 StgBlockingQueueElement *bqe;
2616 belch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): ", \
2617 node, CurrentProc, CurrentTime[CurrentProc],
2618 CurrentTSO->id, CurrentTSO));
2620 node_loc = where_is(node);
2622 ASSERT(q == END_BQ_QUEUE ||
2623 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
2624 get_itbl(q)->type == CONSTR); // closure (type constructor)
2625 ASSERT(is_unique(node));
2627 /* FAKE FETCH: magically copy the node to the tso's proc;
2628 no Fetch necessary because in reality the node should not have been
2629 moved to the other PE in the first place
2631 if (CurrentProc!=node_loc) {
2633 belch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)",
2634 node, node_loc, CurrentProc, CurrentTSO->id,
2635 // CurrentTSO, where_is(CurrentTSO),
2636 node->header.gran.procs));
2637 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
2639 belch("## new bitmask of node %p is %#x",
2640 node, node->header.gran.procs));
2641 if (RtsFlags.GranFlags.GranSimStats.Global) {
2642 globalGranStats.tot_fake_fetches++;
2647 // ToDo: check: ASSERT(CurrentProc==node_loc);
2648 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
2651 bqe points to the current element in the queue
2652 next points to the next element in the queue
2654 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2655 //tso_loc = where_is(tso);
2657 bqe = unblockOneLocked(bqe, node);
2660 /* if this is the BQ of an RBH, we have to put back the info ripped out of
2661 the closure to make room for the anchor of the BQ */
2662 if (bqe!=END_BQ_QUEUE) {
2663 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
2665 ASSERT((info_ptr==&RBH_Save_0_info) ||
2666 (info_ptr==&RBH_Save_1_info) ||
2667 (info_ptr==&RBH_Save_2_info));
2669 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
2670 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
2671 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
2674 belch("## Filled in RBH_Save for %p (%s) at end of AwBQ",
2675 node, info_type(node)));
2678 /* statistics gathering */
2679 if (RtsFlags.GranFlags.GranSimStats.Global) {
2680 // globalGranStats.tot_bq_processing_time += bq_processing_time;
2681 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
2682 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
2683 globalGranStats.tot_awbq++; // total no. of bqs awakened
2686 fprintf(stderr,"## BQ Stats of %p: [%d entries] %s\n",
2687 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
2691 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2693 StgBlockingQueueElement *bqe;
2695 ACQUIRE_LOCK(&sched_mutex);
2697 IF_PAR_DEBUG(verbose,
2698 belch("##-_ AwBQ for node %p on [%x]: ",
2702 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
2703 IF_PAR_DEBUG(verbose, belch("## ... nothing to unblock so lets just return. RFP (BUG?)"));
2708 ASSERT(q == END_BQ_QUEUE ||
2709 get_itbl(q)->type == TSO ||
2710 get_itbl(q)->type == BLOCKED_FETCH ||
2711 get_itbl(q)->type == CONSTR);
2714 while (get_itbl(bqe)->type==TSO ||
2715 get_itbl(bqe)->type==BLOCKED_FETCH) {
2716 bqe = unblockOneLocked(bqe, node);
2718 RELEASE_LOCK(&sched_mutex);
2721 #else /* !GRAN && !PAR */
2723 awakenBlockedQueue(StgTSO *tso)
2725 ACQUIRE_LOCK(&sched_mutex);
2726 while (tso != END_TSO_QUEUE) {
2727 tso = unblockOneLocked(tso);
2729 RELEASE_LOCK(&sched_mutex);
2733 //@node Exception Handling Routines, Debugging Routines, Blocking Queue Routines, Main scheduling code
2734 //@subsection Exception Handling Routines
2736 /* ---------------------------------------------------------------------------
2738 - usually called inside a signal handler so it mustn't do anything fancy.
2739 ------------------------------------------------------------------------ */
2742 interruptStgRts(void)
2748 /* -----------------------------------------------------------------------------
2751 This is for use when we raise an exception in another thread, which
2753 This has nothing to do with the UnblockThread event in GranSim. -- HWL
2754 -------------------------------------------------------------------------- */
2756 #if defined(GRAN) || defined(PAR)
2758 NB: only the type of the blocking queue is different in GranSim and GUM
2759 the operations on the queue-elements are the same
2760 long live polymorphism!
2763 unblockThread(StgTSO *tso)
2765 StgBlockingQueueElement *t, **last;
2767 ACQUIRE_LOCK(&sched_mutex);
2768 switch (tso->why_blocked) {
2771 return; /* not blocked */
2774 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2776 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
2777 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2779 last = (StgBlockingQueueElement **)&mvar->head;
2780 for (t = (StgBlockingQueueElement *)mvar->head;
2782 last = &t->link, last_tso = t, t = t->link) {
2783 if (t == (StgBlockingQueueElement *)tso) {
2784 *last = (StgBlockingQueueElement *)tso->link;
2785 if (mvar->tail == tso) {
2786 mvar->tail = (StgTSO *)last_tso;
2791 barf("unblockThread (MVAR): TSO not found");
2794 case BlockedOnBlackHole:
2795 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2797 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2799 last = &bq->blocking_queue;
2800 for (t = bq->blocking_queue;
2802 last = &t->link, t = t->link) {
2803 if (t == (StgBlockingQueueElement *)tso) {
2804 *last = (StgBlockingQueueElement *)tso->link;
2808 barf("unblockThread (BLACKHOLE): TSO not found");
2811 case BlockedOnException:
2813 StgTSO *target = tso->block_info.tso;
2815 ASSERT(get_itbl(target)->type == TSO);
2817 if (target->what_next == ThreadRelocated) {
2818 target = target->link;
2819 ASSERT(get_itbl(target)->type == TSO);
2822 ASSERT(target->blocked_exceptions != NULL);
2824 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
2825 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
2827 last = &t->link, t = t->link) {
2828 ASSERT(get_itbl(t)->type == TSO);
2829 if (t == (StgBlockingQueueElement *)tso) {
2830 *last = (StgBlockingQueueElement *)tso->link;
2834 barf("unblockThread (Exception): TSO not found");
2838 case BlockedOnWrite:
2840 /* take TSO off blocked_queue */
2841 StgBlockingQueueElement *prev = NULL;
2842 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
2843 prev = t, t = t->link) {
2844 if (t == (StgBlockingQueueElement *)tso) {
2846 blocked_queue_hd = (StgTSO *)t->link;
2847 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2848 blocked_queue_tl = END_TSO_QUEUE;
2851 prev->link = t->link;
2852 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2853 blocked_queue_tl = (StgTSO *)prev;
2859 barf("unblockThread (I/O): TSO not found");
2862 case BlockedOnDelay:
2864 /* take TSO off sleeping_queue */
2865 StgBlockingQueueElement *prev = NULL;
2866 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
2867 prev = t, t = t->link) {
2868 if (t == (StgBlockingQueueElement *)tso) {
2870 sleeping_queue = (StgTSO *)t->link;
2872 prev->link = t->link;
2877 barf("unblockThread (I/O): TSO not found");
2881 barf("unblockThread");
2885 tso->link = END_TSO_QUEUE;
2886 tso->why_blocked = NotBlocked;
2887 tso->block_info.closure = NULL;
2888 PUSH_ON_RUN_QUEUE(tso);
2889 RELEASE_LOCK(&sched_mutex);
2893 unblockThread(StgTSO *tso)
2897 ACQUIRE_LOCK(&sched_mutex);
2898 switch (tso->why_blocked) {
2901 return; /* not blocked */
2904 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2906 StgTSO *last_tso = END_TSO_QUEUE;
2907 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2910 for (t = mvar->head; t != END_TSO_QUEUE;
2911 last = &t->link, last_tso = t, t = t->link) {
2914 if (mvar->tail == tso) {
2915 mvar->tail = last_tso;
2920 barf("unblockThread (MVAR): TSO not found");
2923 case BlockedOnBlackHole:
2924 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2926 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2928 last = &bq->blocking_queue;
2929 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
2930 last = &t->link, t = t->link) {
2936 barf("unblockThread (BLACKHOLE): TSO not found");
2939 case BlockedOnException:
2941 StgTSO *target = tso->block_info.tso;
2943 ASSERT(get_itbl(target)->type == TSO);
2945 while (target->what_next == ThreadRelocated) {
2946 target = target->link;
2947 ASSERT(get_itbl(target)->type == TSO);
2950 ASSERT(target->blocked_exceptions != NULL);
2952 last = &target->blocked_exceptions;
2953 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
2954 last = &t->link, t = t->link) {
2955 ASSERT(get_itbl(t)->type == TSO);
2961 barf("unblockThread (Exception): TSO not found");
2965 case BlockedOnWrite:
2967 StgTSO *prev = NULL;
2968 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
2969 prev = t, t = t->link) {
2972 blocked_queue_hd = t->link;
2973 if (blocked_queue_tl == t) {
2974 blocked_queue_tl = END_TSO_QUEUE;
2977 prev->link = t->link;
2978 if (blocked_queue_tl == t) {
2979 blocked_queue_tl = prev;
2985 barf("unblockThread (I/O): TSO not found");
2988 case BlockedOnDelay:
2990 StgTSO *prev = NULL;
2991 for (t = sleeping_queue; t != END_TSO_QUEUE;
2992 prev = t, t = t->link) {
2995 sleeping_queue = t->link;
2997 prev->link = t->link;
3002 barf("unblockThread (I/O): TSO not found");
3006 barf("unblockThread");
3010 tso->link = END_TSO_QUEUE;
3011 tso->why_blocked = NotBlocked;
3012 tso->block_info.closure = NULL;
3013 PUSH_ON_RUN_QUEUE(tso);
3014 RELEASE_LOCK(&sched_mutex);
3018 /* -----------------------------------------------------------------------------
3021 * The following function implements the magic for raising an
3022 * asynchronous exception in an existing thread.
3024 * We first remove the thread from any queue on which it might be
3025 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
3027 * We strip the stack down to the innermost CATCH_FRAME, building
3028 * thunks in the heap for all the active computations, so they can
3029 * be restarted if necessary. When we reach a CATCH_FRAME, we build
3030 * an application of the handler to the exception, and push it on
3031 * the top of the stack.
3033 * How exactly do we save all the active computations? We create an
3034 * AP_UPD for every UpdateFrame on the stack. Entering one of these
3035 * AP_UPDs pushes everything from the corresponding update frame
3036 * upwards onto the stack. (Actually, it pushes everything up to the
3037 * next update frame plus a pointer to the next AP_UPD object.
3038 * Entering the next AP_UPD object pushes more onto the stack until we
3039 * reach the last AP_UPD object - at which point the stack should look
3040 * exactly as it did when we killed the TSO and we can continue
3041 * execution by entering the closure on top of the stack.
3043 * We can also kill a thread entirely - this happens if either (a) the
3044 * exception passed to raiseAsync is NULL, or (b) there's no
3045 * CATCH_FRAME on the stack. In either case, we strip the entire
3046 * stack and replace the thread with a zombie.
3048 * -------------------------------------------------------------------------- */
3051 deleteThread(StgTSO *tso)
3053 raiseAsync(tso,NULL);
3057 raiseAsync(StgTSO *tso, StgClosure *exception)
3059 StgUpdateFrame* su = tso->su;
3060 StgPtr sp = tso->sp;
3062 /* Thread already dead? */
3063 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3067 IF_DEBUG(scheduler, sched_belch("raising exception in thread %ld.", tso->id));
3069 /* Remove it from any blocking queues */
3072 /* The stack freezing code assumes there's a closure pointer on
3073 * the top of the stack. This isn't always the case with compiled
3074 * code, so we have to push a dummy closure on the top which just
3075 * returns to the next return address on the stack.
3077 if ( LOOKS_LIKE_GHC_INFO((void*)*sp) ) {
3078 *(--sp) = (W_)&stg_dummy_ret_closure;
3082 nat words = ((P_)su - (P_)sp) - 1;
3086 /* If we find a CATCH_FRAME, and we've got an exception to raise,
3087 * then build the THUNK raise(exception), and leave it on
3088 * top of the CATCH_FRAME ready to enter.
3090 if (get_itbl(su)->type == CATCH_FRAME && exception != NULL) {
3091 StgCatchFrame *cf = (StgCatchFrame *)su;
3094 /* we've got an exception to raise, so let's pass it to the
3095 * handler in this frame.
3097 raise = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3098 TICK_ALLOC_SE_THK(1,0);
3099 SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
3100 raise->payload[0] = exception;
3102 /* throw away the stack from Sp up to the CATCH_FRAME.
3106 /* Ensure that async excpetions are blocked now, so we don't get
3107 * a surprise exception before we get around to executing the
3110 if (tso->blocked_exceptions == NULL) {
3111 tso->blocked_exceptions = END_TSO_QUEUE;
3114 /* Put the newly-built THUNK on top of the stack, ready to execute
3115 * when the thread restarts.
3120 tso->what_next = ThreadEnterGHC;
3121 IF_DEBUG(sanity, checkTSO(tso));
3125 /* First build an AP_UPD consisting of the stack chunk above the
3126 * current update frame, with the top word on the stack as the
3129 ap = (StgAP_UPD *)allocate(AP_sizeW(words));
3134 ap->fun = (StgClosure *)sp[0];
3136 for(i=0; i < (nat)words; ++i) {
3137 ap->payload[i] = (StgClosure *)*sp++;
3140 switch (get_itbl(su)->type) {
3144 SET_HDR(ap,&stg_AP_UPD_info,su->header.prof.ccs /* ToDo */);
3145 TICK_ALLOC_UP_THK(words+1,0);
3148 fprintf(stderr, "scheduler: Updating ");
3149 printPtr((P_)su->updatee);
3150 fprintf(stderr, " with ");
3151 printObj((StgClosure *)ap);
3154 /* Replace the updatee with an indirection - happily
3155 * this will also wake up any threads currently
3156 * waiting on the result.
3158 * Warning: if we're in a loop, more than one update frame on
3159 * the stack may point to the same object. Be careful not to
3160 * overwrite an IND_OLDGEN in this case, because we'll screw
3161 * up the mutable lists. To be on the safe side, don't
3162 * overwrite any kind of indirection at all. See also
3163 * threadSqueezeStack in GC.c, where we have to make a similar
3166 if (!closure_IND(su->updatee)) {
3167 UPD_IND_NOLOCK(su->updatee,ap); /* revert the black hole */
3170 sp += sizeofW(StgUpdateFrame) -1;
3171 sp[0] = (W_)ap; /* push onto stack */
3177 StgCatchFrame *cf = (StgCatchFrame *)su;
3180 /* We want a PAP, not an AP_UPD. Fortunately, the
3181 * layout's the same.
3183 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3184 TICK_ALLOC_UPD_PAP(words+1,0);
3186 /* now build o = FUN(catch,ap,handler) */
3187 o = (StgClosure *)allocate(sizeofW(StgClosure)+2);
3188 TICK_ALLOC_FUN(2,0);
3189 SET_HDR(o,&stg_catch_info,su->header.prof.ccs /* ToDo */);
3190 o->payload[0] = (StgClosure *)ap;
3191 o->payload[1] = cf->handler;
3194 fprintf(stderr, "scheduler: Built ");
3195 printObj((StgClosure *)o);
3198 /* pop the old handler and put o on the stack */
3200 sp += sizeofW(StgCatchFrame) - 1;
3207 StgSeqFrame *sf = (StgSeqFrame *)su;
3210 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3211 TICK_ALLOC_UPD_PAP(words+1,0);
3213 /* now build o = FUN(seq,ap) */
3214 o = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3215 TICK_ALLOC_SE_THK(1,0);
3216 SET_HDR(o,&stg_seq_info,su->header.prof.ccs /* ToDo */);
3217 o->payload[0] = (StgClosure *)ap;
3220 fprintf(stderr, "scheduler: Built ");
3221 printObj((StgClosure *)o);
3224 /* pop the old handler and put o on the stack */
3226 sp += sizeofW(StgSeqFrame) - 1;
3232 /* We've stripped the entire stack, the thread is now dead. */
3233 sp += sizeofW(StgStopFrame) - 1;
3234 sp[0] = (W_)exception; /* save the exception */
3235 tso->what_next = ThreadKilled;
3236 tso->su = (StgUpdateFrame *)(sp+1);
3247 /* -----------------------------------------------------------------------------
3248 resurrectThreads is called after garbage collection on the list of
3249 threads found to be garbage. Each of these threads will be woken
3250 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3251 on an MVar, or NonTermination if the thread was blocked on a Black
3253 -------------------------------------------------------------------------- */
3256 resurrectThreads( StgTSO *threads )
3260 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3261 next = tso->global_link;
3262 tso->global_link = all_threads;
3264 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3266 switch (tso->why_blocked) {
3268 case BlockedOnException:
3269 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3271 case BlockedOnBlackHole:
3272 raiseAsync(tso,(StgClosure *)NonTermination_closure);
3275 /* This might happen if the thread was blocked on a black hole
3276 * belonging to a thread that we've just woken up (raiseAsync
3277 * can wake up threads, remember...).
3281 barf("resurrectThreads: thread blocked in a strange way");
3286 /* -----------------------------------------------------------------------------
3287 * Blackhole detection: if we reach a deadlock, test whether any
3288 * threads are blocked on themselves. Any threads which are found to
3289 * be self-blocked get sent a NonTermination exception.
3291 * This is only done in a deadlock situation in order to avoid
3292 * performance overhead in the normal case.
3293 * -------------------------------------------------------------------------- */
3296 detectBlackHoles( void )
3298 StgTSO *t = all_threads;
3299 StgUpdateFrame *frame;
3300 StgClosure *blocked_on;
3302 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3304 while (t->what_next == ThreadRelocated) {
3306 ASSERT(get_itbl(t)->type == TSO);
3309 if (t->why_blocked != BlockedOnBlackHole) {
3313 blocked_on = t->block_info.closure;
3315 for (frame = t->su; ; frame = frame->link) {
3316 switch (get_itbl(frame)->type) {
3319 if (frame->updatee == blocked_on) {
3320 /* We are blocking on one of our own computations, so
3321 * send this thread the NonTermination exception.
3324 sched_belch("thread %d is blocked on itself", t->id));
3325 raiseAsync(t, (StgClosure *)NonTermination_closure);
3346 //@node Debugging Routines, Index, Exception Handling Routines, Main scheduling code
3347 //@subsection Debugging Routines
3349 /* -----------------------------------------------------------------------------
3350 Debugging: why is a thread blocked
3351 -------------------------------------------------------------------------- */
3356 printThreadBlockage(StgTSO *tso)
3358 switch (tso->why_blocked) {
3360 fprintf(stderr,"is blocked on read from fd %d", tso->block_info.fd);
3362 case BlockedOnWrite:
3363 fprintf(stderr,"is blocked on write to fd %d", tso->block_info.fd);
3365 case BlockedOnDelay:
3366 fprintf(stderr,"is blocked until %d", tso->block_info.target);
3369 fprintf(stderr,"is blocked on an MVar");
3371 case BlockedOnException:
3372 fprintf(stderr,"is blocked on delivering an exception to thread %d",
3373 tso->block_info.tso->id);
3375 case BlockedOnBlackHole:
3376 fprintf(stderr,"is blocked on a black hole");
3379 fprintf(stderr,"is not blocked");
3383 fprintf(stderr,"is blocked on global address; local FM_BQ is %p (%s)",
3384 tso->block_info.closure, info_type(tso->block_info.closure));
3386 case BlockedOnGA_NoSend:
3387 fprintf(stderr,"is blocked on global address (no send); local FM_BQ is %p (%s)",
3388 tso->block_info.closure, info_type(tso->block_info.closure));
3391 #if defined(RTS_SUPPORTS_THREADS)
3392 case BlockedOnCCall:
3393 fprintf(stderr,"is blocked on an external call");
3397 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3398 tso->why_blocked, tso->id, tso);
3403 printThreadStatus(StgTSO *tso)
3405 switch (tso->what_next) {
3407 fprintf(stderr,"has been killed");
3409 case ThreadComplete:
3410 fprintf(stderr,"has completed");
3413 printThreadBlockage(tso);
3418 printAllThreads(void)
3423 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3424 ullong_format_string(TIME_ON_PROC(CurrentProc),
3425 time_string, rtsFalse/*no commas!*/);
3427 sched_belch("all threads at [%s]:", time_string);
3429 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3430 ullong_format_string(CURRENT_TIME,
3431 time_string, rtsFalse/*no commas!*/);
3433 sched_belch("all threads at [%s]:", time_string);
3435 sched_belch("all threads:");
3438 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3439 fprintf(stderr, "\tthread %d ", t->id);
3440 printThreadStatus(t);
3441 fprintf(stderr,"\n");
3446 Print a whole blocking queue attached to node (debugging only).
3451 print_bq (StgClosure *node)
3453 StgBlockingQueueElement *bqe;
3457 fprintf(stderr,"## BQ of closure %p (%s): ",
3458 node, info_type(node));
3460 /* should cover all closures that may have a blocking queue */
3461 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3462 get_itbl(node)->type == FETCH_ME_BQ ||
3463 get_itbl(node)->type == RBH ||
3464 get_itbl(node)->type == MVAR);
3466 ASSERT(node!=(StgClosure*)NULL); // sanity check
3468 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
3472 Print a whole blocking queue starting with the element bqe.
3475 print_bqe (StgBlockingQueueElement *bqe)
3480 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3482 for (end = (bqe==END_BQ_QUEUE);
3483 !end; // iterate until bqe points to a CONSTR
3484 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
3485 bqe = end ? END_BQ_QUEUE : bqe->link) {
3486 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3487 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3488 /* types of closures that may appear in a blocking queue */
3489 ASSERT(get_itbl(bqe)->type == TSO ||
3490 get_itbl(bqe)->type == BLOCKED_FETCH ||
3491 get_itbl(bqe)->type == CONSTR);
3492 /* only BQs of an RBH end with an RBH_Save closure */
3493 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3495 switch (get_itbl(bqe)->type) {
3497 fprintf(stderr," TSO %u (%x),",
3498 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
3501 fprintf(stderr," BF (node=%p, ga=((%x, %d, %x)),",
3502 ((StgBlockedFetch *)bqe)->node,
3503 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
3504 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
3505 ((StgBlockedFetch *)bqe)->ga.weight);
3508 fprintf(stderr," %s (IP %p),",
3509 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3510 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3511 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3512 "RBH_Save_?"), get_itbl(bqe));
3515 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
3516 info_type((StgClosure *)bqe)); // , node, info_type(node));
3520 fputc('\n', stderr);
3522 # elif defined(GRAN)
3524 print_bq (StgClosure *node)
3526 StgBlockingQueueElement *bqe;
3527 PEs node_loc, tso_loc;
3530 /* should cover all closures that may have a blocking queue */
3531 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3532 get_itbl(node)->type == FETCH_ME_BQ ||
3533 get_itbl(node)->type == RBH);
3535 ASSERT(node!=(StgClosure*)NULL); // sanity check
3536 node_loc = where_is(node);
3538 fprintf(stderr,"## BQ of closure %p (%s) on [PE %d]: ",
3539 node, info_type(node), node_loc);
3542 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3544 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
3545 !end; // iterate until bqe points to a CONSTR
3546 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
3547 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3548 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3549 /* types of closures that may appear in a blocking queue */
3550 ASSERT(get_itbl(bqe)->type == TSO ||
3551 get_itbl(bqe)->type == CONSTR);
3552 /* only BQs of an RBH end with an RBH_Save closure */
3553 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3555 tso_loc = where_is((StgClosure *)bqe);
3556 switch (get_itbl(bqe)->type) {
3558 fprintf(stderr," TSO %d (%p) on [PE %d],",
3559 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
3562 fprintf(stderr," %s (IP %p),",
3563 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3564 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3565 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3566 "RBH_Save_?"), get_itbl(bqe));
3569 barf("Unexpected closure type %s in blocking queue of %p (%s)",
3570 info_type((StgClosure *)bqe), node, info_type(node));
3574 fputc('\n', stderr);
3578 Nice and easy: only TSOs on the blocking queue
3581 print_bq (StgClosure *node)
3585 ASSERT(node!=(StgClosure*)NULL); // sanity check
3586 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
3587 tso != END_TSO_QUEUE;
3589 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
3590 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
3591 fprintf(stderr," TSO %d (%p),", tso->id, tso);
3593 fputc('\n', stderr);
3604 for (i=0, tso=run_queue_hd;
3605 tso != END_TSO_QUEUE;
3614 sched_belch(char *s, ...)
3619 fprintf(stderr, "scheduler (task %ld): ", osThreadId());
3621 fprintf(stderr, "== ");
3623 fprintf(stderr, "scheduler: ");
3625 vfprintf(stderr, s, ap);
3626 fprintf(stderr, "\n");
3632 //@node Index, , Debugging Routines, Main scheduling code
3636 //* StgMainThread:: @cindex\s-+StgMainThread
3637 //* awaken_blocked_queue:: @cindex\s-+awaken_blocked_queue
3638 //* blocked_queue_hd:: @cindex\s-+blocked_queue_hd
3639 //* blocked_queue_tl:: @cindex\s-+blocked_queue_tl
3640 //* context_switch:: @cindex\s-+context_switch
3641 //* createThread:: @cindex\s-+createThread
3642 //* gc_pending_cond:: @cindex\s-+gc_pending_cond
3643 //* initScheduler:: @cindex\s-+initScheduler
3644 //* interrupted:: @cindex\s-+interrupted
3645 //* next_thread_id:: @cindex\s-+next_thread_id
3646 //* print_bq:: @cindex\s-+print_bq
3647 //* run_queue_hd:: @cindex\s-+run_queue_hd
3648 //* run_queue_tl:: @cindex\s-+run_queue_tl
3649 //* sched_mutex:: @cindex\s-+sched_mutex
3650 //* schedule:: @cindex\s-+schedule
3651 //* take_off_run_queue:: @cindex\s-+take_off_run_queue
3652 //* term_mutex:: @cindex\s-+term_mutex