1 /* ---------------------------------------------------------------------------
2 * $Id: Schedule.c,v 1.122 2002/02/13 08:48:06 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;
271 * When a native thread has completed executing an external
272 * call, it needs to communicate the result back to the
273 * (Haskell) thread that made the call. Do this as follows:
275 * - in resumeThread(), the thread increments the counter
276 * rts_n_returning_workers, and then blocks waiting on the
277 * condition returning_worker_cond.
278 * - upon entry to the scheduler, a worker/task checks
279 * rts_n_returning_workers. If it is > 0, worker threads
280 * are waiting to return, so it gives up its capability
281 * to let a worker deposit its result.
282 * - the worker thread that gave up its capability then tries
283 * to re-grab a capability and re-enter the Scheduler.
287 /* thread_ready_cond: when signalled, a thread has become runnable for a
290 * In the non-SMP case, it also implies that the thread that is woken up has
291 * exclusive access to the RTS and all its data structures (that are not
292 * under sched_mutex's control).
294 * thread_ready_cond is signalled whenever COND_NO_THREADS_READY doesn't hold.
297 Condition thread_ready_cond = INIT_COND_VAR;
299 /* For documentation purposes only */
300 #define COND_NO_THREADS_READY() (noCapabilities() || EMPTY_RUN_QUEUE())
304 * To be able to make an informed decision about whether or not
305 * to create a new task when making an external call, keep track of
306 * the number of tasks currently blocked waiting on thread_ready_cond.
307 * (if > 0 => no need for a new task, just unblock an existing one).
309 nat rts_n_waiting_tasks = 0;
311 /* returning_worker_cond: when a worker thread returns from executing an
312 * external call, it needs to wait for an RTS Capability before passing
313 * on the result of the call to the Haskell thread that made it.
315 * returning_worker_cond is signalled in Capability.releaseCapability().
318 Condition returning_worker_cond = INIT_COND_VAR;
321 * To avoid starvation of threads blocked on worker_thread_cond,
322 * the task(s) that enter the Scheduler will check to see whether
323 * there are one or more worker threads blocked waiting on
324 * returning_worker_cond.
326 * Locks needed: sched_mutex
328 nat rts_n_waiting_workers = 0;
332 static Condition gc_pending_cond = INIT_COND_VAR;
336 #endif /* RTS_SUPPORTS_THREADS */
340 rtsTime TimeOfLastYield;
341 rtsBool emitSchedule = rtsTrue;
345 char *whatNext_strs[] = {
353 char *threadReturnCode_strs[] = {
354 "HeapOverflow", /* might also be StackOverflow */
363 StgTSO * createSparkThread(rtsSpark spark);
364 StgTSO * activateSpark (rtsSpark spark);
368 * The thread state for the main thread.
369 // ToDo: check whether not needed any more
373 #if defined(PAR) || defined(RTS_SUPPORTS_THREADS)
374 static void taskStart(void);
385 //@node Main scheduling loop, Suspend and Resume, Prototypes, Main scheduling code
386 //@subsection Main scheduling loop
388 /* ---------------------------------------------------------------------------
389 Main scheduling loop.
391 We use round-robin scheduling, each thread returning to the
392 scheduler loop when one of these conditions is detected:
395 * timer expires (thread yields)
400 Locking notes: we acquire the scheduler lock once at the beginning
401 of the scheduler loop, and release it when
403 * running a thread, or
404 * waiting for work, or
405 * waiting for a GC to complete.
408 In a GranSim setup this loop iterates over the global event queue.
409 This revolves around the global event queue, which determines what
410 to do next. Therefore, it's more complicated than either the
411 concurrent or the parallel (GUM) setup.
414 GUM iterates over incoming messages.
415 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
416 and sends out a fish whenever it has nothing to do; in-between
417 doing the actual reductions (shared code below) it processes the
418 incoming messages and deals with delayed operations
419 (see PendingFetches).
420 This is not the ugliest code you could imagine, but it's bloody close.
422 ------------------------------------------------------------------------ */
429 StgThreadReturnCode ret;
437 rtsBool receivedFinish = rtsFalse;
439 nat tp_size, sp_size; // stats only
442 rtsBool was_interrupted = rtsFalse;
444 #if defined(RTS_SUPPORTS_THREADS)
448 #if defined(RTS_SUPPORTS_THREADS)
449 ACQUIRE_LOCK(&sched_mutex);
452 #if defined(RTS_SUPPORTS_THREADS)
453 /* ToDo: consider SMP support */
454 if ( rts_n_waiting_workers > 0 && noCapabilities() ) {
455 /* (At least) one native thread is waiting to
456 * deposit the result of an external call. So,
457 * be nice and hand over our capability.
459 IF_DEBUG(scheduler, sched_belch("worker thread (%d): giving up RTS token (waiting workers: %d)\n", osThreadId(), rts_n_waiting_workers));
460 releaseCapability(cap);
461 RELEASE_LOCK(&sched_mutex);
468 #if defined(RTS_SUPPORTS_THREADS)
469 while ( noCapabilities() ) {
470 rts_n_waiting_tasks++;
471 waitCondition(&thread_ready_cond, &sched_mutex);
472 rts_n_waiting_tasks--;
478 /* set up first event to get things going */
479 /* ToDo: assign costs for system setup and init MainTSO ! */
480 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
482 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
485 fprintf(stderr, "GRAN: Init CurrentTSO (in schedule) = %p\n", CurrentTSO);
486 G_TSO(CurrentTSO, 5));
488 if (RtsFlags.GranFlags.Light) {
489 /* Save current time; GranSim Light only */
490 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
493 event = get_next_event();
495 while (event!=(rtsEvent*)NULL) {
496 /* Choose the processor with the next event */
497 CurrentProc = event->proc;
498 CurrentTSO = event->tso;
502 while (!receivedFinish) { /* set by processMessages */
503 /* when receiving PP_FINISH message */
510 IF_DEBUG(scheduler, printAllThreads());
512 /* If we're interrupted (the user pressed ^C, or some other
513 * termination condition occurred), kill all the currently running
517 IF_DEBUG(scheduler, sched_belch("interrupted"));
519 interrupted = rtsFalse;
520 was_interrupted = rtsTrue;
523 /* Go through the list of main threads and wake up any
524 * clients whose computations have finished. ToDo: this
525 * should be done more efficiently without a linear scan
526 * of the main threads list, somehow...
528 #if defined(RTS_SUPPORTS_THREADS)
530 StgMainThread *m, **prev;
531 prev = &main_threads;
532 for (m = main_threads; m != NULL; m = m->link) {
533 switch (m->tso->what_next) {
536 *(m->ret) = (StgClosure *)m->tso->sp[0];
540 broadcastCondition(&m->wakeup);
543 if (m->ret) *(m->ret) = NULL;
545 if (was_interrupted) {
546 m->stat = Interrupted;
550 broadcastCondition(&m->wakeup);
558 #else /* not threaded */
561 /* in GUM do this only on the Main PE */
564 /* If our main thread has finished or been killed, return.
567 StgMainThread *m = main_threads;
568 if (m->tso->what_next == ThreadComplete
569 || m->tso->what_next == ThreadKilled) {
570 main_threads = main_threads->link;
571 if (m->tso->what_next == ThreadComplete) {
572 /* we finished successfully, fill in the return value */
573 if (m->ret) { *(m->ret) = (StgClosure *)m->tso->sp[0]; };
577 if (m->ret) { *(m->ret) = NULL; };
578 if (was_interrupted) {
579 m->stat = Interrupted;
589 /* Top up the run queue from our spark pool. We try to make the
590 * number of threads in the run queue equal to the number of
593 * Disable spark support in SMP for now, non-essential & requires
594 * a little bit of work to make it compile cleanly. -- sof 1/02.
596 #if 0 /* defined(SMP) */
598 nat n = getFreeCapabilities();
599 StgTSO *tso = run_queue_hd;
601 /* Count the run queue */
602 while (n > 0 && tso != END_TSO_QUEUE) {
609 spark = findSpark(rtsFalse);
611 break; /* no more sparks in the pool */
613 /* I'd prefer this to be done in activateSpark -- HWL */
614 /* tricky - it needs to hold the scheduler lock and
615 * not try to re-acquire it -- SDM */
616 createSparkThread(spark);
618 sched_belch("==^^ turning spark of closure %p into a thread",
619 (StgClosure *)spark));
622 /* We need to wake up the other tasks if we just created some
625 if (getFreeCapabilities() - n > 1) {
626 signalCondition( &thread_ready_cond );
631 /* check for signals each time around the scheduler */
632 #ifndef mingw32_TARGET_OS
633 if (signals_pending()) {
634 startSignalHandlers();
638 /* Check whether any waiting threads need to be woken up. If the
639 * run queue is empty, and there are no other tasks running, we
640 * can wait indefinitely for something to happen.
641 * ToDo: what if another client comes along & requests another
644 if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue) ) {
645 awaitEvent( EMPTY_RUN_QUEUE()
647 && allFreeCapabilities()
651 /* we can be interrupted while waiting for I/O... */
652 if (interrupted) continue;
655 * Detect deadlock: when we have no threads to run, there are no
656 * threads waiting on I/O or sleeping, and all the other tasks are
657 * waiting for work, we must have a deadlock of some description.
659 * We first try to find threads blocked on themselves (ie. black
660 * holes), and generate NonTermination exceptions where necessary.
662 * If no threads are black holed, we have a deadlock situation, so
663 * inform all the main threads.
666 if ( EMPTY_RUN_QUEUE()
667 && EMPTY_QUEUE(blocked_queue_hd)
668 && EMPTY_QUEUE(sleeping_queue)
669 #if defined(RTS_SUPPORTS_THREADS)
670 && EMPTY_QUEUE(suspended_ccalling_threads)
673 && allFreeCapabilities()
677 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
678 #if defined(THREADED_RTS)
679 /* and SMP mode ..? */
680 releaseCapability(cap);
682 RELEASE_LOCK(&sched_mutex);
683 GarbageCollect(GetRoots,rtsTrue);
684 ACQUIRE_LOCK(&sched_mutex);
685 if ( EMPTY_QUEUE(blocked_queue_hd)
687 && EMPTY_QUEUE(sleeping_queue) ) {
689 IF_DEBUG(scheduler, sched_belch("still deadlocked, checking for black holes..."));
692 /* No black holes, so probably a real deadlock. Send the
693 * current main thread the Deadlock exception (or in the SMP
694 * build, send *all* main threads the deadlock exception,
695 * since none of them can make progress).
697 if ( EMPTY_RUN_QUEUE() ) {
699 #if defined(RTS_SUPPORTS_THREADS)
700 for (m = main_threads; m != NULL; m = m->link) {
701 switch (m->tso->why_blocked) {
702 case BlockedOnBlackHole:
703 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
705 case BlockedOnException:
707 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
710 barf("deadlock: main thread blocked in a strange way");
715 switch (m->tso->why_blocked) {
716 case BlockedOnBlackHole:
717 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
719 case BlockedOnException:
721 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
724 barf("deadlock: main thread blocked in a strange way");
728 #if defined(RTS_SUPPORTS_THREADS)
729 /* ToDo: revisit conditions (and mechanism) for shutting
730 down a multi-threaded world */
731 if ( EMPTY_RUN_QUEUE() ) {
732 IF_DEBUG(scheduler, sched_belch("all done, i think...shutting down."));
733 shutdownHaskellAndExit(0);
737 ASSERT( !EMPTY_RUN_QUEUE() );
741 /* ToDo: add deadlock detection in GUM (similar to SMP) -- HWL */
745 /* If there's a GC pending, don't do anything until it has
749 IF_DEBUG(scheduler,sched_belch("waiting for GC"));
750 waitCondition( &gc_pending_cond, &sched_mutex );
754 #if defined(RTS_SUPPORTS_THREADS)
755 /* block until we've got a thread on the run queue and a free
759 if ( EMPTY_RUN_QUEUE() ) {
760 /* Give up our capability */
761 releaseCapability(cap);
762 while ( noCapabilities() || EMPTY_RUN_QUEUE() ) {
763 IF_DEBUG(scheduler, sched_belch("thread %d: waiting for work", osThreadId()));
764 rts_n_waiting_tasks++;
765 waitCondition( &thread_ready_cond, &sched_mutex );
766 rts_n_waiting_tasks--;
767 IF_DEBUG(scheduler, sched_belch("thread %d: work now available %d %d", osThreadId(), getFreeCapabilities(),EMPTY_RUN_QUEUE()));
774 if (RtsFlags.GranFlags.Light)
775 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
777 /* adjust time based on time-stamp */
778 if (event->time > CurrentTime[CurrentProc] &&
779 event->evttype != ContinueThread)
780 CurrentTime[CurrentProc] = event->time;
782 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
783 if (!RtsFlags.GranFlags.Light)
786 IF_DEBUG(gran, fprintf(stderr, "GRAN: switch by event-type\n"));
788 /* main event dispatcher in GranSim */
789 switch (event->evttype) {
790 /* Should just be continuing execution */
792 IF_DEBUG(gran, fprintf(stderr, "GRAN: doing ContinueThread\n"));
793 /* ToDo: check assertion
794 ASSERT(run_queue_hd != (StgTSO*)NULL &&
795 run_queue_hd != END_TSO_QUEUE);
797 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
798 if (!RtsFlags.GranFlags.DoAsyncFetch &&
799 procStatus[CurrentProc]==Fetching) {
800 belch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]",
801 CurrentTSO->id, CurrentTSO, CurrentProc);
804 /* Ignore ContinueThreads for completed threads */
805 if (CurrentTSO->what_next == ThreadComplete) {
806 belch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)",
807 CurrentTSO->id, CurrentTSO, CurrentProc);
810 /* Ignore ContinueThreads for threads that are being migrated */
811 if (PROCS(CurrentTSO)==Nowhere) {
812 belch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)",
813 CurrentTSO->id, CurrentTSO, CurrentProc);
816 /* The thread should be at the beginning of the run queue */
817 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
818 belch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread",
819 CurrentTSO->id, CurrentTSO, CurrentProc);
820 break; // run the thread anyway
823 new_event(proc, proc, CurrentTime[proc],
825 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
827 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
828 break; // now actually run the thread; DaH Qu'vam yImuHbej
831 do_the_fetchnode(event);
832 goto next_thread; /* handle next event in event queue */
835 do_the_globalblock(event);
836 goto next_thread; /* handle next event in event queue */
839 do_the_fetchreply(event);
840 goto next_thread; /* handle next event in event queue */
842 case UnblockThread: /* Move from the blocked queue to the tail of */
843 do_the_unblock(event);
844 goto next_thread; /* handle next event in event queue */
846 case ResumeThread: /* Move from the blocked queue to the tail of */
847 /* the runnable queue ( i.e. Qu' SImqa'lu') */
848 event->tso->gran.blocktime +=
849 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
850 do_the_startthread(event);
851 goto next_thread; /* handle next event in event queue */
854 do_the_startthread(event);
855 goto next_thread; /* handle next event in event queue */
858 do_the_movethread(event);
859 goto next_thread; /* handle next event in event queue */
862 do_the_movespark(event);
863 goto next_thread; /* handle next event in event queue */
866 do_the_findwork(event);
867 goto next_thread; /* handle next event in event queue */
870 barf("Illegal event type %u\n", event->evttype);
873 /* This point was scheduler_loop in the old RTS */
875 IF_DEBUG(gran, belch("GRAN: after main switch"));
877 TimeOfLastEvent = CurrentTime[CurrentProc];
878 TimeOfNextEvent = get_time_of_next_event();
879 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
880 // CurrentTSO = ThreadQueueHd;
882 IF_DEBUG(gran, belch("GRAN: time of next event is: %ld",
885 if (RtsFlags.GranFlags.Light)
886 GranSimLight_leave_system(event, &ActiveTSO);
888 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
891 belch("GRAN: end of time-slice is %#lx", EndOfTimeSlice));
893 /* in a GranSim setup the TSO stays on the run queue */
895 /* Take a thread from the run queue. */
896 t = POP_RUN_QUEUE(); // take_off_run_queue(t);
899 fprintf(stderr, "GRAN: About to run current thread, which is\n");
902 context_switch = 0; // turned on via GranYield, checking events and time slice
905 DumpGranEvent(GR_SCHEDULE, t));
907 procStatus[CurrentProc] = Busy;
910 if (PendingFetches != END_BF_QUEUE) {
914 /* ToDo: phps merge with spark activation above */
915 /* check whether we have local work and send requests if we have none */
916 if (EMPTY_RUN_QUEUE()) { /* no runnable threads */
917 /* :-[ no local threads => look out for local sparks */
918 /* the spark pool for the current PE */
919 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
920 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
921 pool->hd < pool->tl) {
923 * ToDo: add GC code check that we really have enough heap afterwards!!
925 * If we're here (no runnable threads) and we have pending
926 * sparks, we must have a space problem. Get enough space
927 * to turn one of those pending sparks into a
931 spark = findSpark(rtsFalse); /* get a spark */
932 if (spark != (rtsSpark) NULL) {
933 tso = activateSpark(spark); /* turn the spark into a thread */
934 IF_PAR_DEBUG(schedule,
935 belch("==== schedule: Created TSO %d (%p); %d threads active",
936 tso->id, tso, advisory_thread_count));
938 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
939 belch("==^^ failed to activate spark");
941 } /* otherwise fall through & pick-up new tso */
943 IF_PAR_DEBUG(verbose,
944 belch("==^^ no local sparks (spark pool contains only NFs: %d)",
945 spark_queue_len(pool)));
950 /* If we still have no work we need to send a FISH to get a spark
953 if (EMPTY_RUN_QUEUE()) {
954 /* =8-[ no local sparks => look for work on other PEs */
956 * We really have absolutely no work. Send out a fish
957 * (there may be some out there already), and wait for
958 * something to arrive. We clearly can't run any threads
959 * until a SCHEDULE or RESUME arrives, and so that's what
960 * we're hoping to see. (Of course, we still have to
961 * respond to other types of messages.)
963 TIME now = msTime() /*CURRENT_TIME*/;
964 IF_PAR_DEBUG(verbose,
965 belch("-- now=%ld", now));
966 IF_PAR_DEBUG(verbose,
967 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
968 (last_fish_arrived_at!=0 &&
969 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
970 belch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)",
971 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
972 last_fish_arrived_at,
973 RtsFlags.ParFlags.fishDelay, now);
976 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
977 (last_fish_arrived_at==0 ||
978 (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
979 /* outstandingFishes is set in sendFish, processFish;
980 avoid flooding system with fishes via delay */
982 sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY,
985 // Global statistics: count no. of fishes
986 if (RtsFlags.ParFlags.ParStats.Global &&
987 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
988 globalParStats.tot_fish_mess++;
992 receivedFinish = processMessages();
995 } else if (PacketsWaiting()) { /* Look for incoming messages */
996 receivedFinish = processMessages();
999 /* Now we are sure that we have some work available */
1000 ASSERT(run_queue_hd != END_TSO_QUEUE);
1002 /* Take a thread from the run queue, if we have work */
1003 t = POP_RUN_QUEUE(); // take_off_run_queue(END_TSO_QUEUE);
1004 IF_DEBUG(sanity,checkTSO(t));
1006 /* ToDo: write something to the log-file
1007 if (RTSflags.ParFlags.granSimStats && !sameThread)
1008 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
1012 /* the spark pool for the current PE */
1013 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
1016 belch("--=^ %d threads, %d sparks on [%#x]",
1017 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
1020 if (0 && RtsFlags.ParFlags.ParStats.Full &&
1021 t && LastTSO && t->id != LastTSO->id &&
1022 LastTSO->why_blocked == NotBlocked &&
1023 LastTSO->what_next != ThreadComplete) {
1024 // if previously scheduled TSO not blocked we have to record the context switch
1025 DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
1026 GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
1029 if (RtsFlags.ParFlags.ParStats.Full &&
1030 (emitSchedule /* forced emit */ ||
1031 (t && LastTSO && t->id != LastTSO->id))) {
1033 we are running a different TSO, so write a schedule event to log file
1034 NB: If we use fair scheduling we also have to write a deschedule
1035 event for LastTSO; with unfair scheduling we know that the
1036 previous tso has blocked whenever we switch to another tso, so
1037 we don't need it in GUM for now
1039 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1040 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
1041 emitSchedule = rtsFalse;
1045 #else /* !GRAN && !PAR */
1047 /* grab a thread from the run queue */
1048 ASSERT(run_queue_hd != END_TSO_QUEUE);
1049 t = POP_RUN_QUEUE();
1050 // Sanity check the thread we're about to run. This can be
1051 // expensive if there is lots of thread switching going on...
1052 IF_DEBUG(sanity,checkTSO(t));
1055 grabCapability(&cap);
1056 cap->r.rCurrentTSO = t;
1058 /* context switches are now initiated by the timer signal, unless
1059 * the user specified "context switch as often as possible", with
1064 RtsFlags.ProfFlags.profileInterval == 0 ||
1066 (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
1067 && (run_queue_hd != END_TSO_QUEUE
1068 || blocked_queue_hd != END_TSO_QUEUE
1069 || sleeping_queue != END_TSO_QUEUE)))
1074 RELEASE_LOCK(&sched_mutex);
1076 IF_DEBUG(scheduler, sched_belch("-->> Running TSO %ld (%p) %s ...",
1077 t->id, t, whatNext_strs[t->what_next]));
1080 startHeapProfTimer();
1083 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1084 /* Run the current thread
1086 switch (cap->r.rCurrentTSO->what_next) {
1088 case ThreadComplete:
1089 /* Thread already finished, return to scheduler. */
1090 ret = ThreadFinished;
1092 case ThreadEnterGHC:
1093 ret = StgRun((StgFunPtr) stg_enterStackTop, &cap->r);
1096 ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
1098 case ThreadEnterInterp:
1099 ret = interpretBCO(cap);
1102 barf("schedule: invalid what_next field");
1104 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1106 /* Costs for the scheduler are assigned to CCS_SYSTEM */
1108 stopHeapProfTimer();
1112 ACQUIRE_LOCK(&sched_mutex);
1115 IF_DEBUG(scheduler,fprintf(stderr,"scheduler (task %ld): ", osThreadId()););
1116 #elif !defined(GRAN) && !defined(PAR)
1117 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: "););
1119 t = cap->r.rCurrentTSO;
1122 /* HACK 675: if the last thread didn't yield, make sure to print a
1123 SCHEDULE event to the log file when StgRunning the next thread, even
1124 if it is the same one as before */
1126 TimeOfLastYield = CURRENT_TIME;
1132 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
1133 globalGranStats.tot_heapover++;
1135 globalParStats.tot_heapover++;
1138 // did the task ask for a large block?
1139 if (cap->r.rHpAlloc > BLOCK_SIZE_W) {
1140 // if so, get one and push it on the front of the nursery.
1144 blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc * sizeof(W_)) / BLOCK_SIZE;
1146 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: requesting a large block (size %d)",
1148 whatNext_strs[t->what_next], blocks));
1150 // don't do this if it would push us over the
1151 // alloc_blocks_lim limit; we'll GC first.
1152 if (alloc_blocks + blocks < alloc_blocks_lim) {
1154 alloc_blocks += blocks;
1155 bd = allocGroup( blocks );
1157 // link the new group into the list
1158 bd->link = cap->r.rCurrentNursery;
1159 bd->u.back = cap->r.rCurrentNursery->u.back;
1160 if (cap->r.rCurrentNursery->u.back != NULL) {
1161 cap->r.rCurrentNursery->u.back->link = bd;
1163 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1164 g0s0->blocks == cap->r.rNursery);
1165 cap->r.rNursery = g0s0->blocks = bd;
1167 cap->r.rCurrentNursery->u.back = bd;
1169 // initialise it as a nursery block
1173 bd->free = bd->start;
1175 // don't forget to update the block count in g0s0.
1176 g0s0->n_blocks += blocks;
1177 ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1179 // now update the nursery to point to the new block
1180 cap->r.rCurrentNursery = bd;
1182 // we might be unlucky and have another thread get on the
1183 // run queue before us and steal the large block, but in that
1184 // case the thread will just end up requesting another large
1186 PUSH_ON_RUN_QUEUE(t);
1191 /* make all the running tasks block on a condition variable,
1192 * maybe set context_switch and wait till they all pile in,
1193 * then have them wait on a GC condition variable.
1195 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped: HeapOverflow",
1196 t->id, t, whatNext_strs[t->what_next]));
1199 ASSERT(!is_on_queue(t,CurrentProc));
1201 /* Currently we emit a DESCHEDULE event before GC in GUM.
1202 ToDo: either add separate event to distinguish SYSTEM time from rest
1203 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1204 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1205 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1206 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1207 emitSchedule = rtsTrue;
1211 ready_to_gc = rtsTrue;
1212 context_switch = 1; /* stop other threads ASAP */
1213 PUSH_ON_RUN_QUEUE(t);
1214 /* actual GC is done at the end of the while loop */
1220 DumpGranEvent(GR_DESCHEDULE, t));
1221 globalGranStats.tot_stackover++;
1224 // DumpGranEvent(GR_DESCHEDULE, t);
1225 globalParStats.tot_stackover++;
1227 IF_DEBUG(scheduler,belch("--<< thread %ld (%p; %s) stopped, StackOverflow",
1228 t->id, t, whatNext_strs[t->what_next]));
1229 /* just adjust the stack for this thread, then pop it back
1235 /* enlarge the stack */
1236 StgTSO *new_t = threadStackOverflow(t);
1238 /* This TSO has moved, so update any pointers to it from the
1239 * main thread stack. It better not be on any other queues...
1240 * (it shouldn't be).
1242 for (m = main_threads; m != NULL; m = m->link) {
1247 threadPaused(new_t);
1248 PUSH_ON_RUN_QUEUE(new_t);
1252 case ThreadYielding:
1255 DumpGranEvent(GR_DESCHEDULE, t));
1256 globalGranStats.tot_yields++;
1259 // DumpGranEvent(GR_DESCHEDULE, t);
1260 globalParStats.tot_yields++;
1262 /* put the thread back on the run queue. Then, if we're ready to
1263 * GC, check whether this is the last task to stop. If so, wake
1264 * up the GC thread. getThread will block during a GC until the
1268 if (t->what_next == ThreadEnterInterp) {
1269 /* ToDo: or maybe a timer expired when we were in Hugs?
1270 * or maybe someone hit ctrl-C
1272 belch("--<< thread %ld (%p; %s) stopped to switch to Hugs",
1273 t->id, t, whatNext_strs[t->what_next]);
1275 belch("--<< thread %ld (%p; %s) stopped, yielding",
1276 t->id, t, whatNext_strs[t->what_next]);
1283 //belch("&& Doing sanity check on yielding TSO %ld.", t->id);
1285 ASSERT(t->link == END_TSO_QUEUE);
1287 ASSERT(!is_on_queue(t,CurrentProc));
1290 //belch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1291 checkThreadQsSanity(rtsTrue));
1294 if (RtsFlags.ParFlags.doFairScheduling) {
1295 /* this does round-robin scheduling; good for concurrency */
1296 APPEND_TO_RUN_QUEUE(t);
1298 /* this does unfair scheduling; good for parallelism */
1299 PUSH_ON_RUN_QUEUE(t);
1302 /* this does round-robin scheduling; good for concurrency */
1303 APPEND_TO_RUN_QUEUE(t);
1306 /* add a ContinueThread event to actually process the thread */
1307 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1309 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1311 belch("GRAN: eventq and runnableq after adding yielded thread to queue again:");
1320 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1321 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)));
1322 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1324 // ??? needed; should emit block before
1326 DumpGranEvent(GR_DESCHEDULE, t));
1327 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1330 ASSERT(procStatus[CurrentProc]==Busy ||
1331 ((procStatus[CurrentProc]==Fetching) &&
1332 (t->block_info.closure!=(StgClosure*)NULL)));
1333 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1334 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1335 procStatus[CurrentProc]==Fetching))
1336 procStatus[CurrentProc] = Idle;
1340 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: ",
1341 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1344 if (t->block_info.closure!=(StgClosure*)NULL)
1345 print_bq(t->block_info.closure));
1347 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1350 /* whatever we schedule next, we must log that schedule */
1351 emitSchedule = rtsTrue;
1354 /* don't need to do anything. Either the thread is blocked on
1355 * I/O, in which case we'll have called addToBlockedQueue
1356 * previously, or it's blocked on an MVar or Blackhole, in which
1357 * case it'll be on the relevant queue already.
1360 fprintf(stderr, "--<< thread %d (%p) stopped: ", t->id, t);
1361 printThreadBlockage(t);
1362 fprintf(stderr, "\n"));
1364 /* Only for dumping event to log file
1365 ToDo: do I need this in GranSim, too?
1372 case ThreadFinished:
1373 /* Need to check whether this was a main thread, and if so, signal
1374 * the task that started it with the return value. If we have no
1375 * more main threads, we probably need to stop all the tasks until
1378 /* We also end up here if the thread kills itself with an
1379 * uncaught exception, see Exception.hc.
1381 IF_DEBUG(scheduler,belch("--++ thread %d (%p) finished", t->id, t));
1383 endThread(t, CurrentProc); // clean-up the thread
1385 /* For now all are advisory -- HWL */
1386 //if(t->priority==AdvisoryPriority) ??
1387 advisory_thread_count--;
1390 if(t->dist.priority==RevalPriority)
1394 if (RtsFlags.ParFlags.ParStats.Full &&
1395 !RtsFlags.ParFlags.ParStats.Suppressed)
1396 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1401 barf("schedule: invalid thread return code %d", (int)ret);
1404 #if defined(RTS_SUPPORTS_THREADS)
1405 /* I don't understand what this re-grab is doing -- sof */
1406 grabCapability(&cap);
1410 if (RtsFlags.ProfFlags.profileInterval==0 || performHeapProfile) {
1411 GarbageCollect(GetRoots, rtsTrue);
1413 performHeapProfile = rtsFalse;
1414 ready_to_gc = rtsFalse; // we already GC'd
1419 if (ready_to_gc && allFreeCapabilities() )
1424 /* everybody back, start the GC.
1425 * Could do it in this thread, or signal a condition var
1426 * to do it in another thread. Either way, we need to
1427 * broadcast on gc_pending_cond afterward.
1429 #if defined(RTS_SUPPORTS_THREADS)
1430 IF_DEBUG(scheduler,sched_belch("doing GC"));
1432 GarbageCollect(GetRoots,rtsFalse);
1433 ready_to_gc = rtsFalse;
1435 broadcastCondition(&gc_pending_cond);
1438 /* add a ContinueThread event to continue execution of current thread */
1439 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1441 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1443 fprintf(stderr, "GRAN: eventq and runnableq after Garbage collection:\n");
1451 IF_GRAN_DEBUG(unused,
1452 print_eventq(EventHd));
1454 event = get_next_event();
1457 /* ToDo: wait for next message to arrive rather than busy wait */
1460 } /* end of while(1) */
1462 IF_PAR_DEBUG(verbose,
1463 belch("== Leaving schedule() after having received Finish"));
1466 /* ---------------------------------------------------------------------------
1467 * deleteAllThreads(): kill all the live threads.
1469 * This is used when we catch a user interrupt (^C), before performing
1470 * any necessary cleanups and running finalizers.
1471 * ------------------------------------------------------------------------- */
1473 void deleteAllThreads ( void )
1476 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
1477 for (t = run_queue_hd; t != END_TSO_QUEUE; t = next) {
1481 for (t = blocked_queue_hd; t != END_TSO_QUEUE; t = next) {
1485 for (t = sleeping_queue; t != END_TSO_QUEUE; t = next) {
1489 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1490 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
1491 sleeping_queue = END_TSO_QUEUE;
1494 /* startThread and insertThread are now in GranSim.c -- HWL */
1497 //@node Suspend and Resume, Run queue code, Main scheduling loop, Main scheduling code
1498 //@subsection Suspend and Resume
1500 /* ---------------------------------------------------------------------------
1501 * Suspending & resuming Haskell threads.
1503 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1504 * its capability before calling the C function. This allows another
1505 * task to pick up the capability and carry on running Haskell
1506 * threads. It also means that if the C call blocks, it won't lock
1509 * The Haskell thread making the C call is put to sleep for the
1510 * duration of the call, on the susepended_ccalling_threads queue. We
1511 * give out a token to the task, which it can use to resume the thread
1512 * on return from the C function.
1513 * ------------------------------------------------------------------------- */
1516 suspendThread( StgRegTable *reg )
1521 /* assume that *reg is a pointer to the StgRegTable part
1524 cap = (Capability *)((void *)reg - sizeof(StgFunTable));
1526 ACQUIRE_LOCK(&sched_mutex);
1529 sched_belch("thread %d did a _ccall_gc", cap->r.rCurrentTSO->id));
1531 threadPaused(cap->r.rCurrentTSO);
1532 cap->r.rCurrentTSO->link = suspended_ccalling_threads;
1533 suspended_ccalling_threads = cap->r.rCurrentTSO;
1535 #if defined(RTS_SUPPORTS_THREADS)
1536 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall;
1539 /* Use the thread ID as the token; it should be unique */
1540 tok = cap->r.rCurrentTSO->id;
1542 /* Hand back capability */
1543 releaseCapability(cap);
1545 #if defined(RTS_SUPPORTS_THREADS) && !defined(SMP)
1546 /* Preparing to leave the RTS, so ensure there's a native thread/task
1547 waiting to take over.
1549 ToDo: optimise this and only create a new task if there's a need
1550 for one (i.e., if there's only one Concurrent Haskell thread alive,
1551 there's no need to create a new task).
1553 IF_DEBUG(scheduler, sched_belch("worker thread (%d): leaving RTS\n", tok));
1554 startTask(taskStart);
1558 RELEASE_LOCK(&sched_mutex);
1563 resumeThread( StgInt tok )
1565 StgTSO *tso, **prev;
1568 #if defined(RTS_SUPPORTS_THREADS)
1569 IF_DEBUG(scheduler, sched_belch("worker %d: returning, waiting for sched. lock.\n", tok));
1570 ACQUIRE_LOCK(&sched_mutex);
1571 rts_n_waiting_workers++;
1572 IF_DEBUG(scheduler, sched_belch("worker %d: returning; workers waiting: %d.\n", tok, rts_n_waiting_workers));
1575 * Wait for the go ahead
1577 IF_DEBUG(scheduler, sched_belch("worker %d: waiting for capability %d...\n", tok, rts_n_free_capabilities));
1578 while ( noCapabilities() ) {
1579 waitCondition(&returning_worker_cond, &sched_mutex);
1581 rts_n_waiting_workers--;
1583 IF_DEBUG(scheduler, sched_belch("worker %d: acquired capability...\n", tok));
1586 /* Remove the thread off of the suspended list */
1587 prev = &suspended_ccalling_threads;
1588 for (tso = suspended_ccalling_threads;
1589 tso != END_TSO_QUEUE;
1590 prev = &tso->link, tso = tso->link) {
1591 if (tso->id == (StgThreadID)tok) {
1596 if (tso == END_TSO_QUEUE) {
1597 barf("resumeThread: thread not found");
1599 tso->link = END_TSO_QUEUE;
1601 #if defined(RTS_SUPPORTS_THREADS)
1602 /* Is it clever to block here with the TSO off the list,
1603 * but not hooked up to a capability?
1605 while ( noCapabilities() ) {
1606 IF_DEBUG(scheduler, sched_belch("waiting to resume"));
1607 rts_n_waiting_tasks++;
1608 waitCondition(&thread_ready_cond, &sched_mutex);
1609 rts_n_waiting_tasks--;
1610 IF_DEBUG(scheduler, sched_belch("resuming thread %d", tso->id));
1614 grabCapability(&cap);
1615 RELEASE_LOCK(&sched_mutex);
1617 /* Reset blocking status */
1618 tso->why_blocked = NotBlocked;
1620 cap->r.rCurrentTSO = tso;
1626 /* ---------------------------------------------------------------------------
1628 * ------------------------------------------------------------------------ */
1629 static void unblockThread(StgTSO *tso);
1631 /* ---------------------------------------------------------------------------
1632 * Comparing Thread ids.
1634 * This is used from STG land in the implementation of the
1635 * instances of Eq/Ord for ThreadIds.
1636 * ------------------------------------------------------------------------ */
1638 int cmp_thread(const StgTSO *tso1, const StgTSO *tso2)
1640 StgThreadID id1 = tso1->id;
1641 StgThreadID id2 = tso2->id;
1643 if (id1 < id2) return (-1);
1644 if (id1 > id2) return 1;
1648 /* ---------------------------------------------------------------------------
1649 * Fetching the ThreadID from an StgTSO.
1651 * This is used in the implementation of Show for ThreadIds.
1652 * ------------------------------------------------------------------------ */
1653 int rts_getThreadId(const StgTSO *tso)
1658 /* ---------------------------------------------------------------------------
1659 Create a new thread.
1661 The new thread starts with the given stack size. Before the
1662 scheduler can run, however, this thread needs to have a closure
1663 (and possibly some arguments) pushed on its stack. See
1664 pushClosure() in Schedule.h.
1666 createGenThread() and createIOThread() (in SchedAPI.h) are
1667 convenient packaged versions of this function.
1669 currently pri (priority) is only used in a GRAN setup -- HWL
1670 ------------------------------------------------------------------------ */
1671 //@cindex createThread
1673 /* currently pri (priority) is only used in a GRAN setup -- HWL */
1675 createThread(nat stack_size, StgInt pri)
1677 return createThread_(stack_size, rtsFalse, pri);
1681 createThread_(nat size, rtsBool have_lock, StgInt pri)
1685 createThread(nat stack_size)
1687 return createThread_(stack_size, rtsFalse);
1691 createThread_(nat size, rtsBool have_lock)
1698 /* First check whether we should create a thread at all */
1700 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1701 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1703 belch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1704 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1705 return END_TSO_QUEUE;
1711 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
1714 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
1716 /* catch ridiculously small stack sizes */
1717 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
1718 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
1721 stack_size = size - TSO_STRUCT_SIZEW;
1723 tso = (StgTSO *)allocate(size);
1724 TICK_ALLOC_TSO(stack_size, 0);
1726 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
1728 SET_GRAN_HDR(tso, ThisPE);
1730 tso->what_next = ThreadEnterGHC;
1732 /* tso->id needs to be unique. For now we use a heavyweight mutex to
1733 * protect the increment operation on next_thread_id.
1734 * In future, we could use an atomic increment instead.
1736 if (!have_lock) { ACQUIRE_LOCK(&sched_mutex); }
1737 tso->id = next_thread_id++;
1738 if (!have_lock) { RELEASE_LOCK(&sched_mutex); }
1740 tso->why_blocked = NotBlocked;
1741 tso->blocked_exceptions = NULL;
1743 tso->stack_size = stack_size;
1744 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
1746 tso->sp = (P_)&(tso->stack) + stack_size;
1749 tso->prof.CCCS = CCS_MAIN;
1752 /* put a stop frame on the stack */
1753 tso->sp -= sizeofW(StgStopFrame);
1754 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
1755 tso->su = (StgUpdateFrame*)tso->sp;
1759 tso->link = END_TSO_QUEUE;
1760 /* uses more flexible routine in GranSim */
1761 insertThread(tso, CurrentProc);
1763 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
1769 if (RtsFlags.GranFlags.GranSimStats.Full)
1770 DumpGranEvent(GR_START,tso);
1772 if (RtsFlags.ParFlags.ParStats.Full)
1773 DumpGranEvent(GR_STARTQ,tso);
1774 /* HACk to avoid SCHEDULE
1778 /* Link the new thread on the global thread list.
1780 tso->global_link = all_threads;
1784 tso->dist.priority = MandatoryPriority; //by default that is...
1788 tso->gran.pri = pri;
1790 tso->gran.magic = TSO_MAGIC; // debugging only
1792 tso->gran.sparkname = 0;
1793 tso->gran.startedat = CURRENT_TIME;
1794 tso->gran.exported = 0;
1795 tso->gran.basicblocks = 0;
1796 tso->gran.allocs = 0;
1797 tso->gran.exectime = 0;
1798 tso->gran.fetchtime = 0;
1799 tso->gran.fetchcount = 0;
1800 tso->gran.blocktime = 0;
1801 tso->gran.blockcount = 0;
1802 tso->gran.blockedat = 0;
1803 tso->gran.globalsparks = 0;
1804 tso->gran.localsparks = 0;
1805 if (RtsFlags.GranFlags.Light)
1806 tso->gran.clock = Now; /* local clock */
1808 tso->gran.clock = 0;
1810 IF_DEBUG(gran,printTSO(tso));
1813 tso->par.magic = TSO_MAGIC; // debugging only
1815 tso->par.sparkname = 0;
1816 tso->par.startedat = CURRENT_TIME;
1817 tso->par.exported = 0;
1818 tso->par.basicblocks = 0;
1819 tso->par.allocs = 0;
1820 tso->par.exectime = 0;
1821 tso->par.fetchtime = 0;
1822 tso->par.fetchcount = 0;
1823 tso->par.blocktime = 0;
1824 tso->par.blockcount = 0;
1825 tso->par.blockedat = 0;
1826 tso->par.globalsparks = 0;
1827 tso->par.localsparks = 0;
1831 globalGranStats.tot_threads_created++;
1832 globalGranStats.threads_created_on_PE[CurrentProc]++;
1833 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
1834 globalGranStats.tot_sq_probes++;
1836 // collect parallel global statistics (currently done together with GC stats)
1837 if (RtsFlags.ParFlags.ParStats.Global &&
1838 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1839 //fprintf(stderr, "Creating thread %d @ %11.2f\n", tso->id, usertime());
1840 globalParStats.tot_threads_created++;
1846 belch("==__ schedule: Created TSO %d (%p);",
1847 CurrentProc, tso, tso->id));
1849 IF_PAR_DEBUG(verbose,
1850 belch("==__ schedule: Created TSO %d (%p); %d threads active",
1851 tso->id, tso, advisory_thread_count));
1853 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
1854 tso->id, tso->stack_size));
1861 all parallel thread creation calls should fall through the following routine.
1864 createSparkThread(rtsSpark spark)
1866 ASSERT(spark != (rtsSpark)NULL);
1867 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
1869 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1870 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1871 return END_TSO_QUEUE;
1875 tso = createThread_(RtsFlags.GcFlags.initialStkSize, rtsTrue);
1876 if (tso==END_TSO_QUEUE)
1877 barf("createSparkThread: Cannot create TSO");
1879 tso->priority = AdvisoryPriority;
1881 pushClosure(tso,spark);
1882 PUSH_ON_RUN_QUEUE(tso);
1883 advisory_thread_count++;
1890 Turn a spark into a thread.
1891 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
1894 //@cindex activateSpark
1896 activateSpark (rtsSpark spark)
1900 tso = createSparkThread(spark);
1901 if (RtsFlags.ParFlags.ParStats.Full) {
1902 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
1903 IF_PAR_DEBUG(verbose,
1904 belch("==^^ activateSpark: turning spark of closure %p (%s) into a thread",
1905 (StgClosure *)spark, info_type((StgClosure *)spark)));
1907 // ToDo: fwd info on local/global spark to thread -- HWL
1908 // tso->gran.exported = spark->exported;
1909 // tso->gran.locked = !spark->global;
1910 // tso->gran.sparkname = spark->name;
1916 /* ---------------------------------------------------------------------------
1919 * scheduleThread puts a thread on the head of the runnable queue.
1920 * This will usually be done immediately after a thread is created.
1921 * The caller of scheduleThread must create the thread using e.g.
1922 * createThread and push an appropriate closure
1923 * on this thread's stack before the scheduler is invoked.
1924 * ------------------------------------------------------------------------ */
1927 scheduleThread_(StgTSO *tso
1928 #if defined(THREADED_RTS)
1929 , rtsBool createTask
1933 ACQUIRE_LOCK(&sched_mutex);
1935 /* Put the new thread on the head of the runnable queue. The caller
1936 * better push an appropriate closure on this thread's stack
1937 * beforehand. In the SMP case, the thread may start running as
1938 * soon as we release the scheduler lock below.
1940 PUSH_ON_RUN_QUEUE(tso);
1941 #if defined(THREADED_RTS)
1942 /* If main() is scheduling a thread, don't bother creating a
1946 startTask(taskStart);
1952 IF_DEBUG(scheduler,printTSO(tso));
1954 RELEASE_LOCK(&sched_mutex);
1957 void scheduleThread(StgTSO* tso)
1959 #if defined(THREADED_RTS)
1960 return scheduleThread_(tso, rtsTrue);
1962 return scheduleThread_(tso);
1966 /* ---------------------------------------------------------------------------
1969 * Initialise the scheduler. This resets all the queues - if the
1970 * queues contained any threads, they'll be garbage collected at the
1973 * ------------------------------------------------------------------------ */
1977 term_handler(int sig STG_UNUSED)
1980 ACQUIRE_LOCK(&term_mutex);
1982 RELEASE_LOCK(&term_mutex);
1993 for (i=0; i<=MAX_PROC; i++) {
1994 run_queue_hds[i] = END_TSO_QUEUE;
1995 run_queue_tls[i] = END_TSO_QUEUE;
1996 blocked_queue_hds[i] = END_TSO_QUEUE;
1997 blocked_queue_tls[i] = END_TSO_QUEUE;
1998 ccalling_threadss[i] = END_TSO_QUEUE;
1999 sleeping_queue = END_TSO_QUEUE;
2002 run_queue_hd = END_TSO_QUEUE;
2003 run_queue_tl = END_TSO_QUEUE;
2004 blocked_queue_hd = END_TSO_QUEUE;
2005 blocked_queue_tl = END_TSO_QUEUE;
2006 sleeping_queue = END_TSO_QUEUE;
2009 suspended_ccalling_threads = END_TSO_QUEUE;
2011 main_threads = NULL;
2012 all_threads = END_TSO_QUEUE;
2017 RtsFlags.ConcFlags.ctxtSwitchTicks =
2018 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
2020 #if defined(RTS_SUPPORTS_THREADS)
2021 /* Initialise the mutex and condition variables used by
2023 initMutex(&sched_mutex);
2024 initMutex(&term_mutex);
2026 initCondition(&thread_ready_cond);
2027 initCondition(&returning_worker_cond);
2031 initCondition(&gc_pending_cond);
2034 #if defined(RTS_SUPPORTS_THREADS)
2035 ACQUIRE_LOCK(&sched_mutex);
2038 /* Install the SIGHUP handler */
2041 struct sigaction action,oact;
2043 action.sa_handler = term_handler;
2044 sigemptyset(&action.sa_mask);
2045 action.sa_flags = 0;
2046 if (sigaction(SIGTERM, &action, &oact) != 0) {
2047 barf("can't install TERM handler");
2052 /* A capability holds the state a native thread needs in
2053 * order to execute STG code. At least one capability is
2054 * floating around (only SMP builds have more than one).
2058 #if defined(RTS_SUPPORTS_THREADS)
2059 /* start our haskell execution tasks */
2061 startTaskManager(RtsFlags.ParFlags.nNodes, taskStart);
2063 startTaskManager(0,taskStart);
2067 #if /* defined(SMP) ||*/ defined(PAR)
2071 #if defined(RTS_SUPPORTS_THREADS)
2072 RELEASE_LOCK(&sched_mutex);
2078 exitScheduler( void )
2080 #if defined(RTS_SUPPORTS_THREADS)
2085 /* -----------------------------------------------------------------------------
2086 Managing the per-task allocation areas.
2088 Each capability comes with an allocation area. These are
2089 fixed-length block lists into which allocation can be done.
2091 ToDo: no support for two-space collection at the moment???
2092 -------------------------------------------------------------------------- */
2094 /* -----------------------------------------------------------------------------
2095 * waitThread is the external interface for running a new computation
2096 * and waiting for the result.
2098 * In the non-SMP case, we create a new main thread, push it on the
2099 * main-thread stack, and invoke the scheduler to run it. The
2100 * scheduler will return when the top main thread on the stack has
2101 * completed or died, and fill in the necessary fields of the
2102 * main_thread structure.
2104 * In the SMP case, we create a main thread as before, but we then
2105 * create a new condition variable and sleep on it. When our new
2106 * main thread has completed, we'll be woken up and the status/result
2107 * will be in the main_thread struct.
2108 * -------------------------------------------------------------------------- */
2111 howManyThreadsAvail ( void )
2115 for (q = run_queue_hd; q != END_TSO_QUEUE; q = q->link)
2117 for (q = blocked_queue_hd; q != END_TSO_QUEUE; q = q->link)
2119 for (q = sleeping_queue; q != END_TSO_QUEUE; q = q->link)
2125 finishAllThreads ( void )
2128 while (run_queue_hd != END_TSO_QUEUE) {
2129 waitThread ( run_queue_hd, NULL);
2131 while (blocked_queue_hd != END_TSO_QUEUE) {
2132 waitThread ( blocked_queue_hd, NULL);
2134 while (sleeping_queue != END_TSO_QUEUE) {
2135 waitThread ( blocked_queue_hd, NULL);
2138 (blocked_queue_hd != END_TSO_QUEUE ||
2139 run_queue_hd != END_TSO_QUEUE ||
2140 sleeping_queue != END_TSO_QUEUE);
2144 waitThread(StgTSO *tso, /*out*/StgClosure **ret)
2146 #if defined(THREADED_RTS)
2147 return waitThread_(tso,ret, rtsFalse);
2149 return waitThread_(tso,ret);
2154 waitThread_(StgTSO *tso,
2155 /*out*/StgClosure **ret
2156 #if defined(THREADED_RTS)
2157 , rtsBool blockWaiting
2162 SchedulerStatus stat;
2164 ACQUIRE_LOCK(&sched_mutex);
2166 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2171 #if defined(RTS_SUPPORTS_THREADS)
2172 initCondition(&m->wakeup);
2175 m->link = main_threads;
2178 IF_DEBUG(scheduler, sched_belch("== scheduler: new main thread (%d)\n", m->tso->id));
2180 #if defined(RTS_SUPPORTS_THREADS)
2182 # if defined(THREADED_RTS)
2183 if (!blockWaiting) {
2184 /* In the threaded case, the OS thread that called main()
2185 * gets to enter the RTS directly without going via another
2188 RELEASE_LOCK(&sched_mutex);
2190 ASSERT(m->stat != NoStatus);
2194 IF_DEBUG(scheduler, sched_belch("sfoo"));
2196 waitCondition(&m->wakeup, &sched_mutex);
2197 } while (m->stat == NoStatus);
2200 /* GranSim specific init */
2201 CurrentTSO = m->tso; // the TSO to run
2202 procStatus[MainProc] = Busy; // status of main PE
2203 CurrentProc = MainProc; // PE to run it on
2207 RELEASE_LOCK(&sched_mutex);
2209 ASSERT(m->stat != NoStatus);
2214 #if defined(RTS_SUPPORTS_THREADS)
2215 closeCondition(&m->wakeup);
2218 IF_DEBUG(scheduler, fprintf(stderr, "== scheduler: main thread (%d) finished\n",
2222 #if defined(THREADED_RTS)
2225 RELEASE_LOCK(&sched_mutex);
2230 //@node Run queue code, Garbage Collextion Routines, Suspend and Resume, Main scheduling code
2231 //@subsection Run queue code
2235 NB: In GranSim we have many run queues; run_queue_hd is actually a macro
2236 unfolding to run_queue_hds[CurrentProc], thus CurrentProc is an
2237 implicit global variable that has to be correct when calling these
2241 /* Put the new thread on the head of the runnable queue.
2242 * The caller of createThread better push an appropriate closure
2243 * on this thread's stack before the scheduler is invoked.
2245 static /* inline */ void
2246 add_to_run_queue(tso)
2249 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2250 tso->link = run_queue_hd;
2252 if (run_queue_tl == END_TSO_QUEUE) {
2257 /* Put the new thread at the end of the runnable queue. */
2258 static /* inline */ void
2259 push_on_run_queue(tso)
2262 ASSERT(get_itbl((StgClosure *)tso)->type == TSO);
2263 ASSERT(run_queue_hd!=NULL && run_queue_tl!=NULL);
2264 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2265 if (run_queue_hd == END_TSO_QUEUE) {
2268 run_queue_tl->link = tso;
2274 Should be inlined because it's used very often in schedule. The tso
2275 argument is actually only needed in GranSim, where we want to have the
2276 possibility to schedule *any* TSO on the run queue, irrespective of the
2277 actual ordering. Therefore, if tso is not the nil TSO then we traverse
2278 the run queue and dequeue the tso, adjusting the links in the queue.
2280 //@cindex take_off_run_queue
2281 static /* inline */ StgTSO*
2282 take_off_run_queue(StgTSO *tso) {
2286 qetlaHbogh Qu' ngaSbogh ghomDaQ {tso} yIteq!
2288 if tso is specified, unlink that tso from the run_queue (doesn't have
2289 to be at the beginning of the queue); GranSim only
2291 if (tso!=END_TSO_QUEUE) {
2292 /* find tso in queue */
2293 for (t=run_queue_hd, prev=END_TSO_QUEUE;
2294 t!=END_TSO_QUEUE && t!=tso;
2298 /* now actually dequeue the tso */
2299 if (prev!=END_TSO_QUEUE) {
2300 ASSERT(run_queue_hd!=t);
2301 prev->link = t->link;
2303 /* t is at beginning of thread queue */
2304 ASSERT(run_queue_hd==t);
2305 run_queue_hd = t->link;
2307 /* t is at end of thread queue */
2308 if (t->link==END_TSO_QUEUE) {
2309 ASSERT(t==run_queue_tl);
2310 run_queue_tl = prev;
2312 ASSERT(run_queue_tl!=t);
2314 t->link = END_TSO_QUEUE;
2316 /* take tso from the beginning of the queue; std concurrent code */
2318 if (t != END_TSO_QUEUE) {
2319 run_queue_hd = t->link;
2320 t->link = END_TSO_QUEUE;
2321 if (run_queue_hd == END_TSO_QUEUE) {
2322 run_queue_tl = END_TSO_QUEUE;
2331 //@node Garbage Collextion Routines, Blocking Queue Routines, Run queue code, Main scheduling code
2332 //@subsection Garbage Collextion Routines
2334 /* ---------------------------------------------------------------------------
2335 Where are the roots that we know about?
2337 - all the threads on the runnable queue
2338 - all the threads on the blocked queue
2339 - all the threads on the sleeping queue
2340 - all the thread currently executing a _ccall_GC
2341 - all the "main threads"
2343 ------------------------------------------------------------------------ */
2345 /* This has to be protected either by the scheduler monitor, or by the
2346 garbage collection monitor (probably the latter).
2351 GetRoots(evac_fn evac)
2358 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2359 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2360 evac((StgClosure **)&run_queue_hds[i]);
2361 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2362 evac((StgClosure **)&run_queue_tls[i]);
2364 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2365 evac((StgClosure **)&blocked_queue_hds[i]);
2366 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2367 evac((StgClosure **)&blocked_queue_tls[i]);
2368 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2369 evac((StgClosure **)&ccalling_threads[i]);
2376 if (run_queue_hd != END_TSO_QUEUE) {
2377 ASSERT(run_queue_tl != END_TSO_QUEUE);
2378 evac((StgClosure **)&run_queue_hd);
2379 evac((StgClosure **)&run_queue_tl);
2382 if (blocked_queue_hd != END_TSO_QUEUE) {
2383 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2384 evac((StgClosure **)&blocked_queue_hd);
2385 evac((StgClosure **)&blocked_queue_tl);
2388 if (sleeping_queue != END_TSO_QUEUE) {
2389 evac((StgClosure **)&sleeping_queue);
2393 for (m = main_threads; m != NULL; m = m->link) {
2394 evac((StgClosure **)&m->tso);
2396 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2397 evac((StgClosure **)&suspended_ccalling_threads);
2400 #if defined(PAR) || defined(GRAN)
2401 markSparkQueue(evac);
2405 /* -----------------------------------------------------------------------------
2408 This is the interface to the garbage collector from Haskell land.
2409 We provide this so that external C code can allocate and garbage
2410 collect when called from Haskell via _ccall_GC.
2412 It might be useful to provide an interface whereby the programmer
2413 can specify more roots (ToDo).
2415 This needs to be protected by the GC condition variable above. KH.
2416 -------------------------------------------------------------------------- */
2418 void (*extra_roots)(evac_fn);
2423 GarbageCollect(GetRoots,rtsFalse);
2427 performMajorGC(void)
2429 GarbageCollect(GetRoots,rtsTrue);
2433 AllRoots(evac_fn evac)
2435 GetRoots(evac); // the scheduler's roots
2436 extra_roots(evac); // the user's roots
2440 performGCWithRoots(void (*get_roots)(evac_fn))
2442 extra_roots = get_roots;
2443 GarbageCollect(AllRoots,rtsFalse);
2446 /* -----------------------------------------------------------------------------
2449 If the thread has reached its maximum stack size, then raise the
2450 StackOverflow exception in the offending thread. Otherwise
2451 relocate the TSO into a larger chunk of memory and adjust its stack
2453 -------------------------------------------------------------------------- */
2456 threadStackOverflow(StgTSO *tso)
2458 nat new_stack_size, new_tso_size, diff, stack_words;
2462 IF_DEBUG(sanity,checkTSO(tso));
2463 if (tso->stack_size >= tso->max_stack_size) {
2466 belch("@@ threadStackOverflow of TSO %d (%p): stack too large (now %ld; max is %ld",
2467 tso->id, tso, tso->stack_size, tso->max_stack_size);
2468 /* If we're debugging, just print out the top of the stack */
2469 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2472 /* Send this thread the StackOverflow exception */
2473 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2477 /* Try to double the current stack size. If that takes us over the
2478 * maximum stack size for this thread, then use the maximum instead.
2479 * Finally round up so the TSO ends up as a whole number of blocks.
2481 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2482 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2483 TSO_STRUCT_SIZE)/sizeof(W_);
2484 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2485 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2487 IF_DEBUG(scheduler, fprintf(stderr,"== scheduler: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2489 dest = (StgTSO *)allocate(new_tso_size);
2490 TICK_ALLOC_TSO(new_stack_size,0);
2492 /* copy the TSO block and the old stack into the new area */
2493 memcpy(dest,tso,TSO_STRUCT_SIZE);
2494 stack_words = tso->stack + tso->stack_size - tso->sp;
2495 new_sp = (P_)dest + new_tso_size - stack_words;
2496 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2498 /* relocate the stack pointers... */
2499 diff = (P_)new_sp - (P_)tso->sp; /* In *words* */
2500 dest->su = (StgUpdateFrame *) ((P_)dest->su + diff);
2502 dest->stack_size = new_stack_size;
2504 /* and relocate the update frame list */
2505 relocate_stack(dest, diff);
2507 /* Mark the old TSO as relocated. We have to check for relocated
2508 * TSOs in the garbage collector and any primops that deal with TSOs.
2510 * It's important to set the sp and su values to just beyond the end
2511 * of the stack, so we don't attempt to scavenge any part of the
2514 tso->what_next = ThreadRelocated;
2516 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2517 tso->su = (StgUpdateFrame *)tso->sp;
2518 tso->why_blocked = NotBlocked;
2519 dest->mut_link = NULL;
2521 IF_PAR_DEBUG(verbose,
2522 belch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld",
2523 tso->id, tso, tso->stack_size);
2524 /* If we're debugging, just print out the top of the stack */
2525 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2528 IF_DEBUG(sanity,checkTSO(tso));
2530 IF_DEBUG(scheduler,printTSO(dest));
2536 //@node Blocking Queue Routines, Exception Handling Routines, Garbage Collextion Routines, Main scheduling code
2537 //@subsection Blocking Queue Routines
2539 /* ---------------------------------------------------------------------------
2540 Wake up a queue that was blocked on some resource.
2541 ------------------------------------------------------------------------ */
2545 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2550 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2552 /* write RESUME events to log file and
2553 update blocked and fetch time (depending on type of the orig closure) */
2554 if (RtsFlags.ParFlags.ParStats.Full) {
2555 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2556 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2557 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2558 if (EMPTY_RUN_QUEUE())
2559 emitSchedule = rtsTrue;
2561 switch (get_itbl(node)->type) {
2563 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2568 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2575 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2582 static StgBlockingQueueElement *
2583 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2586 PEs node_loc, tso_loc;
2588 node_loc = where_is(node); // should be lifted out of loop
2589 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2590 tso_loc = where_is((StgClosure *)tso);
2591 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2592 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2593 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2594 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2595 // insertThread(tso, node_loc);
2596 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2598 tso, node, (rtsSpark*)NULL);
2599 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2602 } else { // TSO is remote (actually should be FMBQ)
2603 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2604 RtsFlags.GranFlags.Costs.gunblocktime +
2605 RtsFlags.GranFlags.Costs.latency;
2606 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2608 tso, node, (rtsSpark*)NULL);
2609 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2612 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2614 fprintf(stderr," %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2615 (node_loc==tso_loc ? "Local" : "Global"),
2616 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2617 tso->block_info.closure = NULL;
2618 IF_DEBUG(scheduler,belch("-- Waking up thread %ld (%p)",
2622 static StgBlockingQueueElement *
2623 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2625 StgBlockingQueueElement *next;
2627 switch (get_itbl(bqe)->type) {
2629 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2630 /* if it's a TSO just push it onto the run_queue */
2632 // ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2633 PUSH_ON_RUN_QUEUE((StgTSO *)bqe);
2635 unblockCount(bqe, node);
2636 /* reset blocking status after dumping event */
2637 ((StgTSO *)bqe)->why_blocked = NotBlocked;
2641 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2643 bqe->link = (StgBlockingQueueElement *)PendingFetches;
2644 PendingFetches = (StgBlockedFetch *)bqe;
2648 /* can ignore this case in a non-debugging setup;
2649 see comments on RBHSave closures above */
2651 /* check that the closure is an RBHSave closure */
2652 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2653 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2654 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2658 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2659 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
2663 IF_PAR_DEBUG(bq, fprintf(stderr, ", %p (%s)", bqe, info_type((StgClosure*)bqe)));
2667 #else /* !GRAN && !PAR */
2669 unblockOneLocked(StgTSO *tso)
2673 ASSERT(get_itbl(tso)->type == TSO);
2674 ASSERT(tso->why_blocked != NotBlocked);
2675 tso->why_blocked = NotBlocked;
2677 PUSH_ON_RUN_QUEUE(tso);
2679 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
2684 #if defined(GRAN) || defined(PAR)
2685 inline StgBlockingQueueElement *
2686 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2688 ACQUIRE_LOCK(&sched_mutex);
2689 bqe = unblockOneLocked(bqe, node);
2690 RELEASE_LOCK(&sched_mutex);
2695 unblockOne(StgTSO *tso)
2697 ACQUIRE_LOCK(&sched_mutex);
2698 tso = unblockOneLocked(tso);
2699 RELEASE_LOCK(&sched_mutex);
2706 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2708 StgBlockingQueueElement *bqe;
2713 belch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): ", \
2714 node, CurrentProc, CurrentTime[CurrentProc],
2715 CurrentTSO->id, CurrentTSO));
2717 node_loc = where_is(node);
2719 ASSERT(q == END_BQ_QUEUE ||
2720 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
2721 get_itbl(q)->type == CONSTR); // closure (type constructor)
2722 ASSERT(is_unique(node));
2724 /* FAKE FETCH: magically copy the node to the tso's proc;
2725 no Fetch necessary because in reality the node should not have been
2726 moved to the other PE in the first place
2728 if (CurrentProc!=node_loc) {
2730 belch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)",
2731 node, node_loc, CurrentProc, CurrentTSO->id,
2732 // CurrentTSO, where_is(CurrentTSO),
2733 node->header.gran.procs));
2734 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
2736 belch("## new bitmask of node %p is %#x",
2737 node, node->header.gran.procs));
2738 if (RtsFlags.GranFlags.GranSimStats.Global) {
2739 globalGranStats.tot_fake_fetches++;
2744 // ToDo: check: ASSERT(CurrentProc==node_loc);
2745 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
2748 bqe points to the current element in the queue
2749 next points to the next element in the queue
2751 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2752 //tso_loc = where_is(tso);
2754 bqe = unblockOneLocked(bqe, node);
2757 /* if this is the BQ of an RBH, we have to put back the info ripped out of
2758 the closure to make room for the anchor of the BQ */
2759 if (bqe!=END_BQ_QUEUE) {
2760 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
2762 ASSERT((info_ptr==&RBH_Save_0_info) ||
2763 (info_ptr==&RBH_Save_1_info) ||
2764 (info_ptr==&RBH_Save_2_info));
2766 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
2767 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
2768 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
2771 belch("## Filled in RBH_Save for %p (%s) at end of AwBQ",
2772 node, info_type(node)));
2775 /* statistics gathering */
2776 if (RtsFlags.GranFlags.GranSimStats.Global) {
2777 // globalGranStats.tot_bq_processing_time += bq_processing_time;
2778 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
2779 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
2780 globalGranStats.tot_awbq++; // total no. of bqs awakened
2783 fprintf(stderr,"## BQ Stats of %p: [%d entries] %s\n",
2784 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
2788 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2790 StgBlockingQueueElement *bqe;
2792 ACQUIRE_LOCK(&sched_mutex);
2794 IF_PAR_DEBUG(verbose,
2795 belch("##-_ AwBQ for node %p on [%x]: ",
2799 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
2800 IF_PAR_DEBUG(verbose, belch("## ... nothing to unblock so lets just return. RFP (BUG?)"));
2805 ASSERT(q == END_BQ_QUEUE ||
2806 get_itbl(q)->type == TSO ||
2807 get_itbl(q)->type == BLOCKED_FETCH ||
2808 get_itbl(q)->type == CONSTR);
2811 while (get_itbl(bqe)->type==TSO ||
2812 get_itbl(bqe)->type==BLOCKED_FETCH) {
2813 bqe = unblockOneLocked(bqe, node);
2815 RELEASE_LOCK(&sched_mutex);
2818 #else /* !GRAN && !PAR */
2820 awakenBlockedQueue(StgTSO *tso)
2822 ACQUIRE_LOCK(&sched_mutex);
2823 while (tso != END_TSO_QUEUE) {
2824 tso = unblockOneLocked(tso);
2826 RELEASE_LOCK(&sched_mutex);
2830 //@node Exception Handling Routines, Debugging Routines, Blocking Queue Routines, Main scheduling code
2831 //@subsection Exception Handling Routines
2833 /* ---------------------------------------------------------------------------
2835 - usually called inside a signal handler so it mustn't do anything fancy.
2836 ------------------------------------------------------------------------ */
2839 interruptStgRts(void)
2845 /* -----------------------------------------------------------------------------
2848 This is for use when we raise an exception in another thread, which
2850 This has nothing to do with the UnblockThread event in GranSim. -- HWL
2851 -------------------------------------------------------------------------- */
2853 #if defined(GRAN) || defined(PAR)
2855 NB: only the type of the blocking queue is different in GranSim and GUM
2856 the operations on the queue-elements are the same
2857 long live polymorphism!
2860 unblockThread(StgTSO *tso)
2862 StgBlockingQueueElement *t, **last;
2864 ACQUIRE_LOCK(&sched_mutex);
2865 switch (tso->why_blocked) {
2868 return; /* not blocked */
2871 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2873 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
2874 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2876 last = (StgBlockingQueueElement **)&mvar->head;
2877 for (t = (StgBlockingQueueElement *)mvar->head;
2879 last = &t->link, last_tso = t, t = t->link) {
2880 if (t == (StgBlockingQueueElement *)tso) {
2881 *last = (StgBlockingQueueElement *)tso->link;
2882 if (mvar->tail == tso) {
2883 mvar->tail = (StgTSO *)last_tso;
2888 barf("unblockThread (MVAR): TSO not found");
2891 case BlockedOnBlackHole:
2892 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2894 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2896 last = &bq->blocking_queue;
2897 for (t = bq->blocking_queue;
2899 last = &t->link, t = t->link) {
2900 if (t == (StgBlockingQueueElement *)tso) {
2901 *last = (StgBlockingQueueElement *)tso->link;
2905 barf("unblockThread (BLACKHOLE): TSO not found");
2908 case BlockedOnException:
2910 StgTSO *target = tso->block_info.tso;
2912 ASSERT(get_itbl(target)->type == TSO);
2914 if (target->what_next == ThreadRelocated) {
2915 target = target->link;
2916 ASSERT(get_itbl(target)->type == TSO);
2919 ASSERT(target->blocked_exceptions != NULL);
2921 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
2922 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
2924 last = &t->link, t = t->link) {
2925 ASSERT(get_itbl(t)->type == TSO);
2926 if (t == (StgBlockingQueueElement *)tso) {
2927 *last = (StgBlockingQueueElement *)tso->link;
2931 barf("unblockThread (Exception): TSO not found");
2935 case BlockedOnWrite:
2937 /* take TSO off blocked_queue */
2938 StgBlockingQueueElement *prev = NULL;
2939 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
2940 prev = t, t = t->link) {
2941 if (t == (StgBlockingQueueElement *)tso) {
2943 blocked_queue_hd = (StgTSO *)t->link;
2944 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2945 blocked_queue_tl = END_TSO_QUEUE;
2948 prev->link = t->link;
2949 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2950 blocked_queue_tl = (StgTSO *)prev;
2956 barf("unblockThread (I/O): TSO not found");
2959 case BlockedOnDelay:
2961 /* take TSO off sleeping_queue */
2962 StgBlockingQueueElement *prev = NULL;
2963 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
2964 prev = t, t = t->link) {
2965 if (t == (StgBlockingQueueElement *)tso) {
2967 sleeping_queue = (StgTSO *)t->link;
2969 prev->link = t->link;
2974 barf("unblockThread (I/O): TSO not found");
2978 barf("unblockThread");
2982 tso->link = END_TSO_QUEUE;
2983 tso->why_blocked = NotBlocked;
2984 tso->block_info.closure = NULL;
2985 PUSH_ON_RUN_QUEUE(tso);
2986 RELEASE_LOCK(&sched_mutex);
2990 unblockThread(StgTSO *tso)
2994 ACQUIRE_LOCK(&sched_mutex);
2995 switch (tso->why_blocked) {
2998 return; /* not blocked */
3001 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3003 StgTSO *last_tso = END_TSO_QUEUE;
3004 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3007 for (t = mvar->head; t != END_TSO_QUEUE;
3008 last = &t->link, last_tso = t, t = t->link) {
3011 if (mvar->tail == tso) {
3012 mvar->tail = last_tso;
3017 barf("unblockThread (MVAR): TSO not found");
3020 case BlockedOnBlackHole:
3021 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3023 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3025 last = &bq->blocking_queue;
3026 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
3027 last = &t->link, t = t->link) {
3033 barf("unblockThread (BLACKHOLE): TSO not found");
3036 case BlockedOnException:
3038 StgTSO *target = tso->block_info.tso;
3040 ASSERT(get_itbl(target)->type == TSO);
3042 while (target->what_next == ThreadRelocated) {
3043 target = target->link;
3044 ASSERT(get_itbl(target)->type == TSO);
3047 ASSERT(target->blocked_exceptions != NULL);
3049 last = &target->blocked_exceptions;
3050 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
3051 last = &t->link, t = t->link) {
3052 ASSERT(get_itbl(t)->type == TSO);
3058 barf("unblockThread (Exception): TSO not found");
3062 case BlockedOnWrite:
3064 StgTSO *prev = NULL;
3065 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
3066 prev = t, t = t->link) {
3069 blocked_queue_hd = t->link;
3070 if (blocked_queue_tl == t) {
3071 blocked_queue_tl = END_TSO_QUEUE;
3074 prev->link = t->link;
3075 if (blocked_queue_tl == t) {
3076 blocked_queue_tl = prev;
3082 barf("unblockThread (I/O): TSO not found");
3085 case BlockedOnDelay:
3087 StgTSO *prev = NULL;
3088 for (t = sleeping_queue; t != END_TSO_QUEUE;
3089 prev = t, t = t->link) {
3092 sleeping_queue = t->link;
3094 prev->link = t->link;
3099 barf("unblockThread (I/O): TSO not found");
3103 barf("unblockThread");
3107 tso->link = END_TSO_QUEUE;
3108 tso->why_blocked = NotBlocked;
3109 tso->block_info.closure = NULL;
3110 PUSH_ON_RUN_QUEUE(tso);
3111 RELEASE_LOCK(&sched_mutex);
3115 /* -----------------------------------------------------------------------------
3118 * The following function implements the magic for raising an
3119 * asynchronous exception in an existing thread.
3121 * We first remove the thread from any queue on which it might be
3122 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
3124 * We strip the stack down to the innermost CATCH_FRAME, building
3125 * thunks in the heap for all the active computations, so they can
3126 * be restarted if necessary. When we reach a CATCH_FRAME, we build
3127 * an application of the handler to the exception, and push it on
3128 * the top of the stack.
3130 * How exactly do we save all the active computations? We create an
3131 * AP_UPD for every UpdateFrame on the stack. Entering one of these
3132 * AP_UPDs pushes everything from the corresponding update frame
3133 * upwards onto the stack. (Actually, it pushes everything up to the
3134 * next update frame plus a pointer to the next AP_UPD object.
3135 * Entering the next AP_UPD object pushes more onto the stack until we
3136 * reach the last AP_UPD object - at which point the stack should look
3137 * exactly as it did when we killed the TSO and we can continue
3138 * execution by entering the closure on top of the stack.
3140 * We can also kill a thread entirely - this happens if either (a) the
3141 * exception passed to raiseAsync is NULL, or (b) there's no
3142 * CATCH_FRAME on the stack. In either case, we strip the entire
3143 * stack and replace the thread with a zombie.
3145 * -------------------------------------------------------------------------- */
3148 deleteThread(StgTSO *tso)
3150 raiseAsync(tso,NULL);
3154 raiseAsync(StgTSO *tso, StgClosure *exception)
3156 StgUpdateFrame* su = tso->su;
3157 StgPtr sp = tso->sp;
3159 /* Thread already dead? */
3160 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3164 IF_DEBUG(scheduler, sched_belch("raising exception in thread %ld.", tso->id));
3166 /* Remove it from any blocking queues */
3169 /* The stack freezing code assumes there's a closure pointer on
3170 * the top of the stack. This isn't always the case with compiled
3171 * code, so we have to push a dummy closure on the top which just
3172 * returns to the next return address on the stack.
3174 if ( LOOKS_LIKE_GHC_INFO((void*)*sp) ) {
3175 *(--sp) = (W_)&stg_dummy_ret_closure;
3179 nat words = ((P_)su - (P_)sp) - 1;
3183 /* If we find a CATCH_FRAME, and we've got an exception to raise,
3184 * then build PAP(handler,exception,realworld#), and leave it on
3185 * top of the stack ready to enter.
3187 if (get_itbl(su)->type == CATCH_FRAME && exception != NULL) {
3188 StgCatchFrame *cf = (StgCatchFrame *)su;
3189 /* we've got an exception to raise, so let's pass it to the
3190 * handler in this frame.
3192 ap = (StgAP_UPD *)allocate(sizeofW(StgPAP) + 2);
3193 TICK_ALLOC_UPD_PAP(3,0);
3194 SET_HDR(ap,&stg_PAP_info,cf->header.prof.ccs);
3197 ap->fun = cf->handler; /* :: Exception -> IO a */
3198 ap->payload[0] = exception;
3199 ap->payload[1] = ARG_TAG(0); /* realworld token */
3201 /* throw away the stack from Sp up to and including the
3204 sp = (P_)su + sizeofW(StgCatchFrame) - 1;
3207 /* Restore the blocked/unblocked state for asynchronous exceptions
3208 * at the CATCH_FRAME.
3210 * If exceptions were unblocked at the catch, arrange that they
3211 * are unblocked again after executing the handler by pushing an
3212 * unblockAsyncExceptions_ret stack frame.
3214 if (!cf->exceptions_blocked) {
3215 *(sp--) = (W_)&stg_unblockAsyncExceptionszh_ret_info;
3218 /* Ensure that async exceptions are blocked when running the handler.
3220 if (tso->blocked_exceptions == NULL) {
3221 tso->blocked_exceptions = END_TSO_QUEUE;
3224 /* Put the newly-built PAP on top of the stack, ready to execute
3225 * when the thread restarts.
3229 tso->what_next = ThreadEnterGHC;
3230 IF_DEBUG(sanity, checkTSO(tso));
3234 /* First build an AP_UPD consisting of the stack chunk above the
3235 * current update frame, with the top word on the stack as the
3238 ap = (StgAP_UPD *)allocate(AP_sizeW(words));
3243 ap->fun = (StgClosure *)sp[0];
3245 for(i=0; i < (nat)words; ++i) {
3246 ap->payload[i] = (StgClosure *)*sp++;
3249 switch (get_itbl(su)->type) {
3253 SET_HDR(ap,&stg_AP_UPD_info,su->header.prof.ccs /* ToDo */);
3254 TICK_ALLOC_UP_THK(words+1,0);
3257 fprintf(stderr, "scheduler: Updating ");
3258 printPtr((P_)su->updatee);
3259 fprintf(stderr, " with ");
3260 printObj((StgClosure *)ap);
3263 /* Replace the updatee with an indirection - happily
3264 * this will also wake up any threads currently
3265 * waiting on the result.
3267 * Warning: if we're in a loop, more than one update frame on
3268 * the stack may point to the same object. Be careful not to
3269 * overwrite an IND_OLDGEN in this case, because we'll screw
3270 * up the mutable lists. To be on the safe side, don't
3271 * overwrite any kind of indirection at all. See also
3272 * threadSqueezeStack in GC.c, where we have to make a similar
3275 if (!closure_IND(su->updatee)) {
3276 UPD_IND_NOLOCK(su->updatee,ap); /* revert the black hole */
3279 sp += sizeofW(StgUpdateFrame) -1;
3280 sp[0] = (W_)ap; /* push onto stack */
3286 StgCatchFrame *cf = (StgCatchFrame *)su;
3289 /* We want a PAP, not an AP_UPD. Fortunately, the
3290 * layout's the same.
3292 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3293 TICK_ALLOC_UPD_PAP(words+1,0);
3295 /* now build o = FUN(catch,ap,handler) */
3296 o = (StgClosure *)allocate(sizeofW(StgClosure)+2);
3297 TICK_ALLOC_FUN(2,0);
3298 SET_HDR(o,&stg_catch_info,su->header.prof.ccs /* ToDo */);
3299 o->payload[0] = (StgClosure *)ap;
3300 o->payload[1] = cf->handler;
3303 fprintf(stderr, "scheduler: Built ");
3304 printObj((StgClosure *)o);
3307 /* pop the old handler and put o on the stack */
3309 sp += sizeofW(StgCatchFrame) - 1;
3316 StgSeqFrame *sf = (StgSeqFrame *)su;
3319 SET_HDR(ap,&stg_PAP_info,su->header.prof.ccs /* ToDo */);
3320 TICK_ALLOC_UPD_PAP(words+1,0);
3322 /* now build o = FUN(seq,ap) */
3323 o = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3324 TICK_ALLOC_SE_THK(1,0);
3325 SET_HDR(o,&stg_seq_info,su->header.prof.ccs /* ToDo */);
3326 o->payload[0] = (StgClosure *)ap;
3329 fprintf(stderr, "scheduler: Built ");
3330 printObj((StgClosure *)o);
3333 /* pop the old handler and put o on the stack */
3335 sp += sizeofW(StgSeqFrame) - 1;
3341 /* We've stripped the entire stack, the thread is now dead. */
3342 sp += sizeofW(StgStopFrame) - 1;
3343 sp[0] = (W_)exception; /* save the exception */
3344 tso->what_next = ThreadKilled;
3345 tso->su = (StgUpdateFrame *)(sp+1);
3356 /* -----------------------------------------------------------------------------
3357 resurrectThreads is called after garbage collection on the list of
3358 threads found to be garbage. Each of these threads will be woken
3359 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3360 on an MVar, or NonTermination if the thread was blocked on a Black
3362 -------------------------------------------------------------------------- */
3365 resurrectThreads( StgTSO *threads )
3369 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3370 next = tso->global_link;
3371 tso->global_link = all_threads;
3373 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3375 switch (tso->why_blocked) {
3377 case BlockedOnException:
3378 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3380 case BlockedOnBlackHole:
3381 raiseAsync(tso,(StgClosure *)NonTermination_closure);
3384 /* This might happen if the thread was blocked on a black hole
3385 * belonging to a thread that we've just woken up (raiseAsync
3386 * can wake up threads, remember...).
3390 barf("resurrectThreads: thread blocked in a strange way");
3395 /* -----------------------------------------------------------------------------
3396 * Blackhole detection: if we reach a deadlock, test whether any
3397 * threads are blocked on themselves. Any threads which are found to
3398 * be self-blocked get sent a NonTermination exception.
3400 * This is only done in a deadlock situation in order to avoid
3401 * performance overhead in the normal case.
3402 * -------------------------------------------------------------------------- */
3405 detectBlackHoles( void )
3407 StgTSO *t = all_threads;
3408 StgUpdateFrame *frame;
3409 StgClosure *blocked_on;
3411 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3413 while (t->what_next == ThreadRelocated) {
3415 ASSERT(get_itbl(t)->type == TSO);
3418 if (t->why_blocked != BlockedOnBlackHole) {
3422 blocked_on = t->block_info.closure;
3424 for (frame = t->su; ; frame = frame->link) {
3425 switch (get_itbl(frame)->type) {
3428 if (frame->updatee == blocked_on) {
3429 /* We are blocking on one of our own computations, so
3430 * send this thread the NonTermination exception.
3433 sched_belch("thread %d is blocked on itself", t->id));
3434 raiseAsync(t, (StgClosure *)NonTermination_closure);
3455 //@node Debugging Routines, Index, Exception Handling Routines, Main scheduling code
3456 //@subsection Debugging Routines
3458 /* -----------------------------------------------------------------------------
3459 Debugging: why is a thread blocked
3460 -------------------------------------------------------------------------- */
3465 printThreadBlockage(StgTSO *tso)
3467 switch (tso->why_blocked) {
3469 fprintf(stderr,"is blocked on read from fd %d", tso->block_info.fd);
3471 case BlockedOnWrite:
3472 fprintf(stderr,"is blocked on write to fd %d", tso->block_info.fd);
3474 case BlockedOnDelay:
3475 fprintf(stderr,"is blocked until %d", tso->block_info.target);
3478 fprintf(stderr,"is blocked on an MVar");
3480 case BlockedOnException:
3481 fprintf(stderr,"is blocked on delivering an exception to thread %d",
3482 tso->block_info.tso->id);
3484 case BlockedOnBlackHole:
3485 fprintf(stderr,"is blocked on a black hole");
3488 fprintf(stderr,"is not blocked");
3492 fprintf(stderr,"is blocked on global address; local FM_BQ is %p (%s)",
3493 tso->block_info.closure, info_type(tso->block_info.closure));
3495 case BlockedOnGA_NoSend:
3496 fprintf(stderr,"is blocked on global address (no send); local FM_BQ is %p (%s)",
3497 tso->block_info.closure, info_type(tso->block_info.closure));
3500 #if defined(RTS_SUPPORTS_THREADS)
3501 case BlockedOnCCall:
3502 fprintf(stderr,"is blocked on an external call");
3506 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3507 tso->why_blocked, tso->id, tso);
3512 printThreadStatus(StgTSO *tso)
3514 switch (tso->what_next) {
3516 fprintf(stderr,"has been killed");
3518 case ThreadComplete:
3519 fprintf(stderr,"has completed");
3522 printThreadBlockage(tso);
3527 printAllThreads(void)
3532 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3533 ullong_format_string(TIME_ON_PROC(CurrentProc),
3534 time_string, rtsFalse/*no commas!*/);
3536 sched_belch("all threads at [%s]:", time_string);
3538 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3539 ullong_format_string(CURRENT_TIME,
3540 time_string, rtsFalse/*no commas!*/);
3542 sched_belch("all threads at [%s]:", time_string);
3544 sched_belch("all threads:");
3547 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3548 fprintf(stderr, "\tthread %d ", t->id);
3549 printThreadStatus(t);
3550 fprintf(stderr,"\n");
3555 Print a whole blocking queue attached to node (debugging only).
3560 print_bq (StgClosure *node)
3562 StgBlockingQueueElement *bqe;
3566 fprintf(stderr,"## BQ of closure %p (%s): ",
3567 node, info_type(node));
3569 /* should cover all closures that may have a blocking queue */
3570 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3571 get_itbl(node)->type == FETCH_ME_BQ ||
3572 get_itbl(node)->type == RBH ||
3573 get_itbl(node)->type == MVAR);
3575 ASSERT(node!=(StgClosure*)NULL); // sanity check
3577 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
3581 Print a whole blocking queue starting with the element bqe.
3584 print_bqe (StgBlockingQueueElement *bqe)
3589 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3591 for (end = (bqe==END_BQ_QUEUE);
3592 !end; // iterate until bqe points to a CONSTR
3593 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
3594 bqe = end ? END_BQ_QUEUE : bqe->link) {
3595 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3596 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3597 /* types of closures that may appear in a blocking queue */
3598 ASSERT(get_itbl(bqe)->type == TSO ||
3599 get_itbl(bqe)->type == BLOCKED_FETCH ||
3600 get_itbl(bqe)->type == CONSTR);
3601 /* only BQs of an RBH end with an RBH_Save closure */
3602 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3604 switch (get_itbl(bqe)->type) {
3606 fprintf(stderr," TSO %u (%x),",
3607 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
3610 fprintf(stderr," BF (node=%p, ga=((%x, %d, %x)),",
3611 ((StgBlockedFetch *)bqe)->node,
3612 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
3613 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
3614 ((StgBlockedFetch *)bqe)->ga.weight);
3617 fprintf(stderr," %s (IP %p),",
3618 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3619 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3620 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3621 "RBH_Save_?"), get_itbl(bqe));
3624 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
3625 info_type((StgClosure *)bqe)); // , node, info_type(node));
3629 fputc('\n', stderr);
3631 # elif defined(GRAN)
3633 print_bq (StgClosure *node)
3635 StgBlockingQueueElement *bqe;
3636 PEs node_loc, tso_loc;
3639 /* should cover all closures that may have a blocking queue */
3640 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3641 get_itbl(node)->type == FETCH_ME_BQ ||
3642 get_itbl(node)->type == RBH);
3644 ASSERT(node!=(StgClosure*)NULL); // sanity check
3645 node_loc = where_is(node);
3647 fprintf(stderr,"## BQ of closure %p (%s) on [PE %d]: ",
3648 node, info_type(node), node_loc);
3651 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3653 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
3654 !end; // iterate until bqe points to a CONSTR
3655 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
3656 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3657 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3658 /* types of closures that may appear in a blocking queue */
3659 ASSERT(get_itbl(bqe)->type == TSO ||
3660 get_itbl(bqe)->type == CONSTR);
3661 /* only BQs of an RBH end with an RBH_Save closure */
3662 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3664 tso_loc = where_is((StgClosure *)bqe);
3665 switch (get_itbl(bqe)->type) {
3667 fprintf(stderr," TSO %d (%p) on [PE %d],",
3668 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
3671 fprintf(stderr," %s (IP %p),",
3672 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3673 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3674 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3675 "RBH_Save_?"), get_itbl(bqe));
3678 barf("Unexpected closure type %s in blocking queue of %p (%s)",
3679 info_type((StgClosure *)bqe), node, info_type(node));
3683 fputc('\n', stderr);
3687 Nice and easy: only TSOs on the blocking queue
3690 print_bq (StgClosure *node)
3694 ASSERT(node!=(StgClosure*)NULL); // sanity check
3695 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
3696 tso != END_TSO_QUEUE;
3698 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
3699 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
3700 fprintf(stderr," TSO %d (%p),", tso->id, tso);
3702 fputc('\n', stderr);
3713 for (i=0, tso=run_queue_hd;
3714 tso != END_TSO_QUEUE;
3723 sched_belch(char *s, ...)
3728 fprintf(stderr, "scheduler (task %ld): ", osThreadId());
3730 fprintf(stderr, "== ");
3732 fprintf(stderr, "scheduler: ");
3734 vfprintf(stderr, s, ap);
3735 fprintf(stderr, "\n");
3741 //@node Index, , Debugging Routines, Main scheduling code
3745 //* MainRegTable:: @cindex\s-+MainRegTable
3746 //* StgMainThread:: @cindex\s-+StgMainThread
3747 //* awaken_blocked_queue:: @cindex\s-+awaken_blocked_queue
3748 //* blocked_queue_hd:: @cindex\s-+blocked_queue_hd
3749 //* blocked_queue_tl:: @cindex\s-+blocked_queue_tl
3750 //* context_switch:: @cindex\s-+context_switch
3751 //* createThread:: @cindex\s-+createThread
3752 //* gc_pending_cond:: @cindex\s-+gc_pending_cond
3753 //* initScheduler:: @cindex\s-+initScheduler
3754 //* interrupted:: @cindex\s-+interrupted
3755 //* next_thread_id:: @cindex\s-+next_thread_id
3756 //* print_bq:: @cindex\s-+print_bq
3757 //* run_queue_hd:: @cindex\s-+run_queue_hd
3758 //* run_queue_tl:: @cindex\s-+run_queue_tl
3759 //* sched_mutex:: @cindex\s-+sched_mutex
3760 //* schedule:: @cindex\s-+schedule
3761 //* take_off_run_queue:: @cindex\s-+take_off_run_queue
3762 //* term_mutex:: @cindex\s-+term_mutex
3763 //* thread_ready_cond:: @cindex\s-+thread_ready_cond