1 /* ---------------------------------------------------------------------------
2 * $Id: Schedule.c,v 1.176 2003/10/01 10:49:08 wolfgang 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"
87 #define COMPILING_SCHEDULER
89 #include "StgMiscClosures.h"
91 #include "Interpreter.h"
92 #include "Exception.h"
99 #include "ThreadLabels.h"
101 #include "Proftimer.h"
102 #include "ProfHeap.h"
104 #if defined(GRAN) || defined(PAR)
105 # include "GranSimRts.h"
106 # include "GranSim.h"
107 # include "ParallelRts.h"
108 # include "Parallel.h"
109 # include "ParallelDebug.h"
110 # include "FetchMe.h"
114 #include "Capability.h"
115 #include "OSThreads.h"
118 #ifdef HAVE_SYS_TYPES_H
119 #include <sys/types.h>
134 #define USED_IN_THREADED_RTS
136 #define USED_IN_THREADED_RTS STG_UNUSED
139 #ifdef RTS_SUPPORTS_THREADS
140 #define USED_WHEN_RTS_SUPPORTS_THREADS
142 #define USED_WHEN_RTS_SUPPORTS_THREADS STG_UNUSED
145 //@node Variables and Data structures, Prototypes, Includes, Main scheduling code
146 //@subsection Variables and Data structures
148 /* Main thread queue.
149 * Locks required: sched_mutex.
151 StgMainThread *main_threads = NULL;
154 * Locks required: sched_mutex.
158 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
159 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
162 In GranSim we have a runnable and a blocked queue for each processor.
163 In order to minimise code changes new arrays run_queue_hds/tls
164 are created. run_queue_hd is then a short cut (macro) for
165 run_queue_hds[CurrentProc] (see GranSim.h).
168 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
169 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
170 StgTSO *ccalling_threadss[MAX_PROC];
171 /* We use the same global list of threads (all_threads) in GranSim as in
172 the std RTS (i.e. we are cheating). However, we don't use this list in
173 the GranSim specific code at the moment (so we are only potentially
178 StgTSO *run_queue_hd = NULL;
179 StgTSO *run_queue_tl = NULL;
180 StgTSO *blocked_queue_hd = NULL;
181 StgTSO *blocked_queue_tl = NULL;
182 StgTSO *sleeping_queue = NULL; /* perhaps replace with a hash table? */
186 /* Linked list of all threads.
187 * Used for detecting garbage collected threads.
189 StgTSO *all_threads = NULL;
191 /* When a thread performs a safe C call (_ccall_GC, using old
192 * terminology), it gets put on the suspended_ccalling_threads
193 * list. Used by the garbage collector.
195 static StgTSO *suspended_ccalling_threads;
197 static StgTSO *threadStackOverflow(StgTSO *tso);
199 /* KH: The following two flags are shared memory locations. There is no need
200 to lock them, since they are only unset at the end of a scheduler
204 /* flag set by signal handler to precipitate a context switch */
205 //@cindex context_switch
206 nat context_switch = 0;
208 /* if this flag is set as well, give up execution */
209 //@cindex interrupted
210 rtsBool interrupted = rtsFalse;
212 /* Next thread ID to allocate.
213 * Locks required: thread_id_mutex
215 //@cindex next_thread_id
216 static StgThreadID next_thread_id = 1;
219 * Pointers to the state of the current thread.
220 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
221 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
224 /* The smallest stack size that makes any sense is:
225 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
226 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
227 * + 1 (the closure to enter)
229 * + 1 (spare slot req'd by stg_ap_v_ret)
231 * A thread with this stack will bomb immediately with a stack
232 * overflow, which will increase its stack size.
235 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 3)
242 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
243 * exists - earlier gccs apparently didn't.
248 static rtsBool ready_to_gc;
251 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
252 * in an MT setting, needed to signal that a worker thread shouldn't hang around
253 * in the scheduler when it is out of work.
255 static rtsBool shutting_down_scheduler = rtsFalse;
257 void addToBlockedQueue ( StgTSO *tso );
259 static void schedule ( StgMainThread *mainThread, Capability *initialCapability );
260 void interruptStgRts ( void );
262 static void detectBlackHoles ( void );
265 static void sched_belch(char *s, ...);
268 #if defined(RTS_SUPPORTS_THREADS)
269 /* ToDo: carefully document the invariants that go together
270 * with these synchronisation objects.
272 Mutex sched_mutex = INIT_MUTEX_VAR;
273 Mutex term_mutex = INIT_MUTEX_VAR;
276 * A heavyweight solution to the problem of protecting
277 * the thread_id from concurrent update.
279 Mutex thread_id_mutex = INIT_MUTEX_VAR;
283 static Condition gc_pending_cond = INIT_COND_VAR;
287 #endif /* RTS_SUPPORTS_THREADS */
291 rtsTime TimeOfLastYield;
292 rtsBool emitSchedule = rtsTrue;
296 static char *whatNext_strs[] = {
306 StgTSO * createSparkThread(rtsSpark spark);
307 StgTSO * activateSpark (rtsSpark spark);
311 * The thread state for the main thread.
312 // ToDo: check whether not needed any more
316 #if defined(RTS_SUPPORTS_THREADS)
317 static rtsBool startingWorkerThread = rtsFalse;
319 static void taskStart(void);
325 ACQUIRE_LOCK(&sched_mutex);
326 startingWorkerThread = rtsFalse;
327 waitForWorkCapability(&sched_mutex, &cap, NULL);
328 RELEASE_LOCK(&sched_mutex);
334 startSchedulerTaskIfNecessary(void)
336 if(run_queue_hd != END_TSO_QUEUE
337 || blocked_queue_hd != END_TSO_QUEUE
338 || sleeping_queue != END_TSO_QUEUE)
340 if(!startingWorkerThread)
341 { // we don't want to start another worker thread
342 // just because the last one hasn't yet reached the
343 // "waiting for capability" state
344 startingWorkerThread = rtsTrue;
345 startTask(taskStart);
351 //@node Main scheduling loop, Suspend and Resume, Prototypes, Main scheduling code
352 //@subsection Main scheduling loop
354 /* ---------------------------------------------------------------------------
355 Main scheduling loop.
357 We use round-robin scheduling, each thread returning to the
358 scheduler loop when one of these conditions is detected:
361 * timer expires (thread yields)
366 Locking notes: we acquire the scheduler lock once at the beginning
367 of the scheduler loop, and release it when
369 * running a thread, or
370 * waiting for work, or
371 * waiting for a GC to complete.
374 In a GranSim setup this loop iterates over the global event queue.
375 This revolves around the global event queue, which determines what
376 to do next. Therefore, it's more complicated than either the
377 concurrent or the parallel (GUM) setup.
380 GUM iterates over incoming messages.
381 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
382 and sends out a fish whenever it has nothing to do; in-between
383 doing the actual reductions (shared code below) it processes the
384 incoming messages and deals with delayed operations
385 (see PendingFetches).
386 This is not the ugliest code you could imagine, but it's bloody close.
388 ------------------------------------------------------------------------ */
391 schedule( StgMainThread *mainThread USED_WHEN_RTS_SUPPORTS_THREADS,
392 Capability *initialCapability )
395 Capability *cap = initialCapability;
396 StgThreadReturnCode ret;
404 rtsBool receivedFinish = rtsFalse;
406 nat tp_size, sp_size; // stats only
409 rtsBool was_interrupted = rtsFalse;
410 StgTSOWhatNext prev_what_next;
412 ACQUIRE_LOCK(&sched_mutex);
414 #if defined(RTS_SUPPORTS_THREADS)
415 /* in the threaded case, the capability is either passed in via the initialCapability
416 parameter, or initialized inside the scheduler loop */
419 fprintf(stderr,"### NEW SCHEDULER LOOP in os thread %u(%p)\n",
420 osThreadId(), osThreadId()));
422 fprintf(stderr,"### main thread: %p\n",mainThread));
424 fprintf(stderr,"### initial cap: %p\n",initialCapability));
426 /* simply initialise it in the non-threaded case */
427 grabCapability(&cap);
431 /* set up first event to get things going */
432 /* ToDo: assign costs for system setup and init MainTSO ! */
433 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
435 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
438 fprintf(stderr, "GRAN: Init CurrentTSO (in schedule) = %p\n", CurrentTSO);
439 G_TSO(CurrentTSO, 5));
441 if (RtsFlags.GranFlags.Light) {
442 /* Save current time; GranSim Light only */
443 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
446 event = get_next_event();
448 while (event!=(rtsEvent*)NULL) {
449 /* Choose the processor with the next event */
450 CurrentProc = event->proc;
451 CurrentTSO = event->tso;
455 while (!receivedFinish) { /* set by processMessages */
456 /* when receiving PP_FINISH message */
463 IF_DEBUG(scheduler, printAllThreads());
465 #if defined(RTS_SUPPORTS_THREADS)
466 /* Check to see whether there are any worker threads
467 waiting to deposit external call results. If so,
468 yield our capability... if we have a capability, that is. */
470 yieldToReturningWorker(&sched_mutex, &cap,
471 mainThread ? &mainThread->bound_thread_cond : NULL);
473 /* If we do not currently hold a capability, we wait for one */
476 waitForWorkCapability(&sched_mutex, &cap,
477 mainThread ? &mainThread->bound_thread_cond : NULL);
478 IF_DEBUG(scheduler, sched_belch("worker thread (osthread %p): got cap",
483 /* If we're interrupted (the user pressed ^C, or some other
484 * termination condition occurred), kill all the currently running
488 IF_DEBUG(scheduler, sched_belch("interrupted"));
489 interrupted = rtsFalse;
490 was_interrupted = rtsTrue;
491 #if defined(RTS_SUPPORTS_THREADS)
492 // In the threaded RTS, deadlock detection doesn't work,
493 // so just exit right away.
494 prog_belch("interrupted");
495 releaseCapability(cap);
496 RELEASE_LOCK(&sched_mutex);
497 shutdownHaskellAndExit(EXIT_SUCCESS);
503 /* Go through the list of main threads and wake up any
504 * clients whose computations have finished. ToDo: this
505 * should be done more efficiently without a linear scan
506 * of the main threads list, somehow...
508 #if defined(RTS_SUPPORTS_THREADS)
510 StgMainThread *m, **prev;
511 prev = &main_threads;
512 for (m = main_threads; m != NULL; prev = &m->link, m = m->link) {
513 if (m->tso->what_next == ThreadComplete
514 || m->tso->what_next == ThreadKilled)
518 if(m->tso->what_next == ThreadComplete)
522 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
523 *(m->ret) = (StgClosure *)m->tso->sp[1];
535 m->stat = Interrupted;
545 removeThreadLabel((StgWord)m->tso);
547 releaseCapability(cap);
548 RELEASE_LOCK(&sched_mutex);
553 // The current OS thread can not handle the fact that the Haskell
554 // thread "m" has ended.
555 // "m" is bound; the scheduler loop in it's bound OS thread has
556 // to return, so let's pass our capability directly to that thread.
557 passCapability(&sched_mutex, cap, &m->bound_thread_cond);
564 if(!cap) // If we gave our capability away,
565 continue; // go to the top to get it back
567 #else /* not threaded */
570 /* in GUM do this only on the Main PE */
573 /* If our main thread has finished or been killed, return.
576 StgMainThread *m = main_threads;
577 if (m->tso->what_next == ThreadComplete
578 || m->tso->what_next == ThreadKilled) {
580 removeThreadLabel((StgWord)m->tso);
582 main_threads = main_threads->link;
583 if (m->tso->what_next == ThreadComplete) {
584 // We finished successfully, fill in the return value
585 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
586 if (m->ret) { *(m->ret) = (StgClosure *)m->tso->sp[1]; };
590 if (m->ret) { *(m->ret) = NULL; };
591 if (was_interrupted) {
592 m->stat = Interrupted;
602 /* Top up the run queue from our spark pool. We try to make the
603 * number of threads in the run queue equal to the number of
606 * Disable spark support in SMP for now, non-essential & requires
607 * a little bit of work to make it compile cleanly. -- sof 1/02.
609 #if 0 /* defined(SMP) */
611 nat n = getFreeCapabilities();
612 StgTSO *tso = run_queue_hd;
614 /* Count the run queue */
615 while (n > 0 && tso != END_TSO_QUEUE) {
622 spark = findSpark(rtsFalse);
624 break; /* no more sparks in the pool */
626 /* I'd prefer this to be done in activateSpark -- HWL */
627 /* tricky - it needs to hold the scheduler lock and
628 * not try to re-acquire it -- SDM */
629 createSparkThread(spark);
631 sched_belch("==^^ turning spark of closure %p into a thread",
632 (StgClosure *)spark));
635 /* We need to wake up the other tasks if we just created some
638 if (getFreeCapabilities() - n > 1) {
639 signalCondition( &thread_ready_cond );
644 /* check for signals each time around the scheduler */
645 #if defined(RTS_USER_SIGNALS)
646 if (signals_pending()) {
647 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
648 startSignalHandlers();
649 ACQUIRE_LOCK(&sched_mutex);
653 /* Check whether any waiting threads need to be woken up. If the
654 * run queue is empty, and there are no other tasks running, we
655 * can wait indefinitely for something to happen.
657 if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue)
658 #if defined(RTS_SUPPORTS_THREADS) && !defined(SMP)
663 awaitEvent( EMPTY_RUN_QUEUE()
665 && allFreeCapabilities()
669 /* we can be interrupted while waiting for I/O... */
670 if (interrupted) continue;
673 * Detect deadlock: when we have no threads to run, there are no
674 * threads waiting on I/O or sleeping, and all the other tasks are
675 * waiting for work, we must have a deadlock of some description.
677 * We first try to find threads blocked on themselves (ie. black
678 * holes), and generate NonTermination exceptions where necessary.
680 * If no threads are black holed, we have a deadlock situation, so
681 * inform all the main threads.
683 #if !defined(PAR) && !defined(RTS_SUPPORTS_THREADS)
684 if ( EMPTY_THREAD_QUEUES()
685 #if defined(RTS_SUPPORTS_THREADS)
686 && EMPTY_QUEUE(suspended_ccalling_threads)
689 && allFreeCapabilities()
693 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
694 #if defined(THREADED_RTS)
695 /* and SMP mode ..? */
696 releaseCapability(cap);
698 // Garbage collection can release some new threads due to
699 // either (a) finalizers or (b) threads resurrected because
700 // they are about to be send BlockedOnDeadMVar. Any threads
701 // thus released will be immediately runnable.
702 GarbageCollect(GetRoots,rtsTrue);
704 if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
707 sched_belch("still deadlocked, checking for black holes..."));
710 if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
712 #if defined(RTS_USER_SIGNALS)
713 /* If we have user-installed signal handlers, then wait
714 * for signals to arrive rather then bombing out with a
717 #if defined(RTS_SUPPORTS_THREADS)
718 if ( 0 ) { /* hmm..what to do? Simply stop waiting for
719 a signal with no runnable threads (or I/O
720 suspended ones) leads nowhere quick.
721 For now, simply shut down when we reach this
724 ToDo: define precisely under what conditions
725 the Scheduler should shut down in an MT setting.
728 if ( anyUserHandlers() ) {
731 sched_belch("still deadlocked, waiting for signals..."));
735 // we might be interrupted...
736 if (interrupted) { continue; }
738 if (signals_pending()) {
739 RELEASE_LOCK(&sched_mutex);
740 startSignalHandlers();
741 ACQUIRE_LOCK(&sched_mutex);
743 ASSERT(!EMPTY_RUN_QUEUE());
748 /* Probably a real deadlock. Send the current main thread the
749 * Deadlock exception (or in the SMP build, send *all* main
750 * threads the deadlock exception, since none of them can make
755 #if defined(RTS_SUPPORTS_THREADS)
756 for (m = main_threads; m != NULL; m = m->link) {
757 switch (m->tso->why_blocked) {
758 case BlockedOnBlackHole:
759 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
761 case BlockedOnException:
763 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
766 barf("deadlock: main thread blocked in a strange way");
771 switch (m->tso->why_blocked) {
772 case BlockedOnBlackHole:
773 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
775 case BlockedOnException:
777 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
780 barf("deadlock: main thread blocked in a strange way");
785 #if defined(RTS_SUPPORTS_THREADS)
786 /* ToDo: revisit conditions (and mechanism) for shutting
787 down a multi-threaded world */
788 IF_DEBUG(scheduler, sched_belch("all done, i think...shutting down."));
789 RELEASE_LOCK(&sched_mutex);
796 #elif defined(RTS_SUPPORTS_THREADS)
797 /* ToDo: add deadlock detection in threaded RTS */
799 /* ToDo: add deadlock detection in GUM (similar to SMP) -- HWL */
803 /* If there's a GC pending, don't do anything until it has
807 IF_DEBUG(scheduler,sched_belch("waiting for GC"));
808 waitCondition( &gc_pending_cond, &sched_mutex );
812 #if defined(RTS_SUPPORTS_THREADS)
814 /* block until we've got a thread on the run queue and a free
818 if ( EMPTY_RUN_QUEUE() ) {
819 /* Give up our capability */
820 releaseCapability(cap);
822 /* If we're in the process of shutting down (& running the
823 * a batch of finalisers), don't wait around.
825 if ( shutting_down_scheduler ) {
826 RELEASE_LOCK(&sched_mutex);
829 IF_DEBUG(scheduler, sched_belch("thread %d: waiting for work", osThreadId()));
830 waitForWorkCapability(&sched_mutex, &cap, rtsTrue);
831 IF_DEBUG(scheduler, sched_belch("thread %d: work now available", osThreadId()));
834 if ( EMPTY_RUN_QUEUE() ) {
835 continue; // nothing to do
841 if (RtsFlags.GranFlags.Light)
842 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
844 /* adjust time based on time-stamp */
845 if (event->time > CurrentTime[CurrentProc] &&
846 event->evttype != ContinueThread)
847 CurrentTime[CurrentProc] = event->time;
849 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
850 if (!RtsFlags.GranFlags.Light)
853 IF_DEBUG(gran, fprintf(stderr, "GRAN: switch by event-type\n"));
855 /* main event dispatcher in GranSim */
856 switch (event->evttype) {
857 /* Should just be continuing execution */
859 IF_DEBUG(gran, fprintf(stderr, "GRAN: doing ContinueThread\n"));
860 /* ToDo: check assertion
861 ASSERT(run_queue_hd != (StgTSO*)NULL &&
862 run_queue_hd != END_TSO_QUEUE);
864 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
865 if (!RtsFlags.GranFlags.DoAsyncFetch &&
866 procStatus[CurrentProc]==Fetching) {
867 belch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]",
868 CurrentTSO->id, CurrentTSO, CurrentProc);
871 /* Ignore ContinueThreads for completed threads */
872 if (CurrentTSO->what_next == ThreadComplete) {
873 belch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)",
874 CurrentTSO->id, CurrentTSO, CurrentProc);
877 /* Ignore ContinueThreads for threads that are being migrated */
878 if (PROCS(CurrentTSO)==Nowhere) {
879 belch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)",
880 CurrentTSO->id, CurrentTSO, CurrentProc);
883 /* The thread should be at the beginning of the run queue */
884 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
885 belch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread",
886 CurrentTSO->id, CurrentTSO, CurrentProc);
887 break; // run the thread anyway
890 new_event(proc, proc, CurrentTime[proc],
892 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
894 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
895 break; // now actually run the thread; DaH Qu'vam yImuHbej
898 do_the_fetchnode(event);
899 goto next_thread; /* handle next event in event queue */
902 do_the_globalblock(event);
903 goto next_thread; /* handle next event in event queue */
906 do_the_fetchreply(event);
907 goto next_thread; /* handle next event in event queue */
909 case UnblockThread: /* Move from the blocked queue to the tail of */
910 do_the_unblock(event);
911 goto next_thread; /* handle next event in event queue */
913 case ResumeThread: /* Move from the blocked queue to the tail of */
914 /* the runnable queue ( i.e. Qu' SImqa'lu') */
915 event->tso->gran.blocktime +=
916 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
917 do_the_startthread(event);
918 goto next_thread; /* handle next event in event queue */
921 do_the_startthread(event);
922 goto next_thread; /* handle next event in event queue */
925 do_the_movethread(event);
926 goto next_thread; /* handle next event in event queue */
929 do_the_movespark(event);
930 goto next_thread; /* handle next event in event queue */
933 do_the_findwork(event);
934 goto next_thread; /* handle next event in event queue */
937 barf("Illegal event type %u\n", event->evttype);
940 /* This point was scheduler_loop in the old RTS */
942 IF_DEBUG(gran, belch("GRAN: after main switch"));
944 TimeOfLastEvent = CurrentTime[CurrentProc];
945 TimeOfNextEvent = get_time_of_next_event();
946 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
947 // CurrentTSO = ThreadQueueHd;
949 IF_DEBUG(gran, belch("GRAN: time of next event is: %ld",
952 if (RtsFlags.GranFlags.Light)
953 GranSimLight_leave_system(event, &ActiveTSO);
955 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
958 belch("GRAN: end of time-slice is %#lx", EndOfTimeSlice));
960 /* in a GranSim setup the TSO stays on the run queue */
962 /* Take a thread from the run queue. */
963 t = POP_RUN_QUEUE(); // take_off_run_queue(t);
966 fprintf(stderr, "GRAN: About to run current thread, which is\n");
969 context_switch = 0; // turned on via GranYield, checking events and time slice
972 DumpGranEvent(GR_SCHEDULE, t));
974 procStatus[CurrentProc] = Busy;
977 if (PendingFetches != END_BF_QUEUE) {
981 /* ToDo: phps merge with spark activation above */
982 /* check whether we have local work and send requests if we have none */
983 if (EMPTY_RUN_QUEUE()) { /* no runnable threads */
984 /* :-[ no local threads => look out for local sparks */
985 /* the spark pool for the current PE */
986 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
987 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
988 pool->hd < pool->tl) {
990 * ToDo: add GC code check that we really have enough heap afterwards!!
992 * If we're here (no runnable threads) and we have pending
993 * sparks, we must have a space problem. Get enough space
994 * to turn one of those pending sparks into a
998 spark = findSpark(rtsFalse); /* get a spark */
999 if (spark != (rtsSpark) NULL) {
1000 tso = activateSpark(spark); /* turn the spark into a thread */
1001 IF_PAR_DEBUG(schedule,
1002 belch("==== schedule: Created TSO %d (%p); %d threads active",
1003 tso->id, tso, advisory_thread_count));
1005 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
1006 belch("==^^ failed to activate spark");
1008 } /* otherwise fall through & pick-up new tso */
1010 IF_PAR_DEBUG(verbose,
1011 belch("==^^ no local sparks (spark pool contains only NFs: %d)",
1012 spark_queue_len(pool)));
1017 /* If we still have no work we need to send a FISH to get a spark
1020 if (EMPTY_RUN_QUEUE()) {
1021 /* =8-[ no local sparks => look for work on other PEs */
1023 * We really have absolutely no work. Send out a fish
1024 * (there may be some out there already), and wait for
1025 * something to arrive. We clearly can't run any threads
1026 * until a SCHEDULE or RESUME arrives, and so that's what
1027 * we're hoping to see. (Of course, we still have to
1028 * respond to other types of messages.)
1030 TIME now = msTime() /*CURRENT_TIME*/;
1031 IF_PAR_DEBUG(verbose,
1032 belch("-- now=%ld", now));
1033 IF_PAR_DEBUG(verbose,
1034 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
1035 (last_fish_arrived_at!=0 &&
1036 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
1037 belch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)",
1038 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
1039 last_fish_arrived_at,
1040 RtsFlags.ParFlags.fishDelay, now);
1043 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
1044 (last_fish_arrived_at==0 ||
1045 (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
1046 /* outstandingFishes is set in sendFish, processFish;
1047 avoid flooding system with fishes via delay */
1049 sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY,
1052 // Global statistics: count no. of fishes
1053 if (RtsFlags.ParFlags.ParStats.Global &&
1054 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1055 globalParStats.tot_fish_mess++;
1059 receivedFinish = processMessages();
1062 } else if (PacketsWaiting()) { /* Look for incoming messages */
1063 receivedFinish = processMessages();
1066 /* Now we are sure that we have some work available */
1067 ASSERT(run_queue_hd != END_TSO_QUEUE);
1069 /* Take a thread from the run queue, if we have work */
1070 t = POP_RUN_QUEUE(); // take_off_run_queue(END_TSO_QUEUE);
1071 IF_DEBUG(sanity,checkTSO(t));
1073 /* ToDo: write something to the log-file
1074 if (RTSflags.ParFlags.granSimStats && !sameThread)
1075 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
1079 /* the spark pool for the current PE */
1080 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
1083 belch("--=^ %d threads, %d sparks on [%#x]",
1084 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
1087 if (0 && RtsFlags.ParFlags.ParStats.Full &&
1088 t && LastTSO && t->id != LastTSO->id &&
1089 LastTSO->why_blocked == NotBlocked &&
1090 LastTSO->what_next != ThreadComplete) {
1091 // if previously scheduled TSO not blocked we have to record the context switch
1092 DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
1093 GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
1096 if (RtsFlags.ParFlags.ParStats.Full &&
1097 (emitSchedule /* forced emit */ ||
1098 (t && LastTSO && t->id != LastTSO->id))) {
1100 we are running a different TSO, so write a schedule event to log file
1101 NB: If we use fair scheduling we also have to write a deschedule
1102 event for LastTSO; with unfair scheduling we know that the
1103 previous tso has blocked whenever we switch to another tso, so
1104 we don't need it in GUM for now
1106 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1107 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
1108 emitSchedule = rtsFalse;
1112 #else /* !GRAN && !PAR */
1114 /* grab a thread from the run queue */
1115 ASSERT(run_queue_hd != END_TSO_QUEUE);
1116 t = POP_RUN_QUEUE();
1117 // Sanity check the thread we're about to run. This can be
1118 // expensive if there is lots of thread switching going on...
1119 IF_DEBUG(sanity,checkTSO(t));
1125 for(m = main_threads; m; m = m->link)
1136 fprintf(stderr,"### Running TSO %p in bound OS thread %u\n",
1138 // yes, the Haskell thread is bound to the current native thread
1143 fprintf(stderr,"### TSO %p bound to other OS thread than %u\n",
1145 // no, bound to a different Haskell thread: pass to that thread
1146 PUSH_ON_RUN_QUEUE(t);
1147 passCapability(&sched_mutex,cap,&m->bound_thread_cond);
1154 // The thread we want to run is not bound.
1155 if(mainThread == NULL)
1158 fprintf(stderr,"### Running TSO %p in worker OS thread %u\n",
1160 // if we are a worker thread,
1161 // we may run it here
1166 fprintf(stderr,"### TSO %p is not appropriate for main thread %p in OS thread %u\n",
1167 t, mainThread, osThreadId()));
1168 // no, the current native thread is bound to a different
1169 // Haskell thread, so pass it to any worker thread
1170 PUSH_ON_RUN_QUEUE(t);
1171 passCapabilityToWorker(&sched_mutex, cap);
1179 cap->r.rCurrentTSO = t;
1181 /* context switches are now initiated by the timer signal, unless
1182 * the user specified "context switch as often as possible", with
1185 if ((RtsFlags.ConcFlags.ctxtSwitchTicks == 0
1186 && (run_queue_hd != END_TSO_QUEUE
1187 || blocked_queue_hd != END_TSO_QUEUE
1188 || sleeping_queue != END_TSO_QUEUE)))
1195 RELEASE_LOCK(&sched_mutex);
1197 IF_DEBUG(scheduler, sched_belch("-->> running thread %ld %s ...",
1198 t->id, whatNext_strs[t->what_next]));
1201 startHeapProfTimer();
1204 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1205 /* Run the current thread
1207 prev_what_next = t->what_next;
1208 switch (prev_what_next) {
1210 case ThreadComplete:
1211 /* Thread already finished, return to scheduler. */
1212 ret = ThreadFinished;
1215 errno = t->saved_errno;
1216 ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
1217 t->saved_errno = errno;
1219 case ThreadInterpret:
1220 ret = interpretBCO(cap);
1223 barf("schedule: invalid what_next field");
1225 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1227 /* Costs for the scheduler are assigned to CCS_SYSTEM */
1229 stopHeapProfTimer();
1233 ACQUIRE_LOCK(&sched_mutex);
1235 #ifdef RTS_SUPPORTS_THREADS
1236 IF_DEBUG(scheduler,fprintf(stderr,"scheduler (task %p): ", osThreadId()););
1237 #elif !defined(GRAN) && !defined(PAR)
1238 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: "););
1240 t = cap->r.rCurrentTSO;
1243 /* HACK 675: if the last thread didn't yield, make sure to print a
1244 SCHEDULE event to the log file when StgRunning the next thread, even
1245 if it is the same one as before */
1247 TimeOfLastYield = CURRENT_TIME;
1253 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
1254 globalGranStats.tot_heapover++;
1256 globalParStats.tot_heapover++;
1259 // did the task ask for a large block?
1260 if (cap->r.rHpAlloc > BLOCK_SIZE_W) {
1261 // if so, get one and push it on the front of the nursery.
1265 blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc * sizeof(W_)) / BLOCK_SIZE;
1267 IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped: requesting a large block (size %d)",
1268 t->id, whatNext_strs[t->what_next], blocks));
1270 // don't do this if it would push us over the
1271 // alloc_blocks_lim limit; we'll GC first.
1272 if (alloc_blocks + blocks < alloc_blocks_lim) {
1274 alloc_blocks += blocks;
1275 bd = allocGroup( blocks );
1277 // link the new group into the list
1278 bd->link = cap->r.rCurrentNursery;
1279 bd->u.back = cap->r.rCurrentNursery->u.back;
1280 if (cap->r.rCurrentNursery->u.back != NULL) {
1281 cap->r.rCurrentNursery->u.back->link = bd;
1283 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1284 g0s0->blocks == cap->r.rNursery);
1285 cap->r.rNursery = g0s0->blocks = bd;
1287 cap->r.rCurrentNursery->u.back = bd;
1289 // initialise it as a nursery block. We initialise the
1290 // step, gen_no, and flags field of *every* sub-block in
1291 // this large block, because this is easier than making
1292 // sure that we always find the block head of a large
1293 // block whenever we call Bdescr() (eg. evacuate() and
1294 // isAlive() in the GC would both have to do this, at
1298 for (x = bd; x < bd + blocks; x++) {
1305 // don't forget to update the block count in g0s0.
1306 g0s0->n_blocks += blocks;
1307 // This assert can be a killer if the app is doing lots
1308 // of large block allocations.
1309 ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1311 // now update the nursery to point to the new block
1312 cap->r.rCurrentNursery = bd;
1314 // we might be unlucky and have another thread get on the
1315 // run queue before us and steal the large block, but in that
1316 // case the thread will just end up requesting another large
1318 PUSH_ON_RUN_QUEUE(t);
1323 /* make all the running tasks block on a condition variable,
1324 * maybe set context_switch and wait till they all pile in,
1325 * then have them wait on a GC condition variable.
1327 IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped: HeapOverflow",
1328 t->id, whatNext_strs[t->what_next]));
1331 ASSERT(!is_on_queue(t,CurrentProc));
1333 /* Currently we emit a DESCHEDULE event before GC in GUM.
1334 ToDo: either add separate event to distinguish SYSTEM time from rest
1335 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1336 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1337 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1338 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1339 emitSchedule = rtsTrue;
1343 ready_to_gc = rtsTrue;
1344 context_switch = 1; /* stop other threads ASAP */
1345 PUSH_ON_RUN_QUEUE(t);
1346 /* actual GC is done at the end of the while loop */
1352 DumpGranEvent(GR_DESCHEDULE, t));
1353 globalGranStats.tot_stackover++;
1356 // DumpGranEvent(GR_DESCHEDULE, t);
1357 globalParStats.tot_stackover++;
1359 IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped, StackOverflow",
1360 t->id, whatNext_strs[t->what_next]));
1361 /* just adjust the stack for this thread, then pop it back
1367 /* enlarge the stack */
1368 StgTSO *new_t = threadStackOverflow(t);
1370 /* This TSO has moved, so update any pointers to it from the
1371 * main thread stack. It better not be on any other queues...
1372 * (it shouldn't be).
1374 for (m = main_threads; m != NULL; m = m->link) {
1379 threadPaused(new_t);
1380 PUSH_ON_RUN_QUEUE(new_t);
1384 case ThreadYielding:
1387 DumpGranEvent(GR_DESCHEDULE, t));
1388 globalGranStats.tot_yields++;
1391 // DumpGranEvent(GR_DESCHEDULE, t);
1392 globalParStats.tot_yields++;
1394 /* put the thread back on the run queue. Then, if we're ready to
1395 * GC, check whether this is the last task to stop. If so, wake
1396 * up the GC thread. getThread will block during a GC until the
1400 if (t->what_next != prev_what_next) {
1401 belch("--<< thread %ld (%s) stopped to switch evaluators",
1402 t->id, whatNext_strs[t->what_next]);
1404 belch("--<< thread %ld (%s) stopped, yielding",
1405 t->id, whatNext_strs[t->what_next]);
1410 //belch("&& Doing sanity check on yielding TSO %ld.", t->id);
1412 ASSERT(t->link == END_TSO_QUEUE);
1414 // Shortcut if we're just switching evaluators: don't bother
1415 // doing stack squeezing (which can be expensive), just run the
1417 if (t->what_next != prev_what_next) {
1424 ASSERT(!is_on_queue(t,CurrentProc));
1427 //belch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1428 checkThreadQsSanity(rtsTrue));
1432 if (RtsFlags.ParFlags.doFairScheduling) {
1433 /* this does round-robin scheduling; good for concurrency */
1434 APPEND_TO_RUN_QUEUE(t);
1436 /* this does unfair scheduling; good for parallelism */
1437 PUSH_ON_RUN_QUEUE(t);
1440 // this does round-robin scheduling; good for concurrency
1441 APPEND_TO_RUN_QUEUE(t);
1445 /* add a ContinueThread event to actually process the thread */
1446 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1448 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1450 belch("GRAN: eventq and runnableq after adding yielded thread to queue again:");
1459 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1460 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)));
1461 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1463 // ??? needed; should emit block before
1465 DumpGranEvent(GR_DESCHEDULE, t));
1466 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1469 ASSERT(procStatus[CurrentProc]==Busy ||
1470 ((procStatus[CurrentProc]==Fetching) &&
1471 (t->block_info.closure!=(StgClosure*)NULL)));
1472 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1473 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1474 procStatus[CurrentProc]==Fetching))
1475 procStatus[CurrentProc] = Idle;
1479 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: ",
1480 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1483 if (t->block_info.closure!=(StgClosure*)NULL)
1484 print_bq(t->block_info.closure));
1486 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1489 /* whatever we schedule next, we must log that schedule */
1490 emitSchedule = rtsTrue;
1493 /* don't need to do anything. Either the thread is blocked on
1494 * I/O, in which case we'll have called addToBlockedQueue
1495 * previously, or it's blocked on an MVar or Blackhole, in which
1496 * case it'll be on the relevant queue already.
1499 fprintf(stderr, "--<< thread %d (%s) stopped: ",
1500 t->id, whatNext_strs[t->what_next]);
1501 printThreadBlockage(t);
1502 fprintf(stderr, "\n"));
1504 /* Only for dumping event to log file
1505 ToDo: do I need this in GranSim, too?
1512 case ThreadFinished:
1513 /* Need to check whether this was a main thread, and if so, signal
1514 * the task that started it with the return value. If we have no
1515 * more main threads, we probably need to stop all the tasks until
1518 /* We also end up here if the thread kills itself with an
1519 * uncaught exception, see Exception.hc.
1521 IF_DEBUG(scheduler,belch("--++ thread %d (%s) finished",
1522 t->id, whatNext_strs[t->what_next]));
1524 endThread(t, CurrentProc); // clean-up the thread
1526 /* For now all are advisory -- HWL */
1527 //if(t->priority==AdvisoryPriority) ??
1528 advisory_thread_count--;
1531 if(t->dist.priority==RevalPriority)
1535 if (RtsFlags.ParFlags.ParStats.Full &&
1536 !RtsFlags.ParFlags.ParStats.Suppressed)
1537 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1542 barf("schedule: invalid thread return code %d", (int)ret);
1546 // When we have +RTS -i0 and we're heap profiling, do a census at
1547 // every GC. This lets us get repeatable runs for debugging.
1548 if (performHeapProfile ||
1549 (RtsFlags.ProfFlags.profileInterval==0 &&
1550 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1551 GarbageCollect(GetRoots, rtsTrue);
1553 performHeapProfile = rtsFalse;
1554 ready_to_gc = rtsFalse; // we already GC'd
1560 && allFreeCapabilities()
1563 /* everybody back, start the GC.
1564 * Could do it in this thread, or signal a condition var
1565 * to do it in another thread. Either way, we need to
1566 * broadcast on gc_pending_cond afterward.
1568 #if defined(RTS_SUPPORTS_THREADS)
1569 IF_DEBUG(scheduler,sched_belch("doing GC"));
1571 GarbageCollect(GetRoots,rtsFalse);
1572 ready_to_gc = rtsFalse;
1574 broadcastCondition(&gc_pending_cond);
1577 /* add a ContinueThread event to continue execution of current thread */
1578 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1580 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1582 fprintf(stderr, "GRAN: eventq and runnableq after Garbage collection:\n");
1590 IF_GRAN_DEBUG(unused,
1591 print_eventq(EventHd));
1593 event = get_next_event();
1596 /* ToDo: wait for next message to arrive rather than busy wait */
1599 } /* end of while(1) */
1601 IF_PAR_DEBUG(verbose,
1602 belch("== Leaving schedule() after having received Finish"));
1605 /* ---------------------------------------------------------------------------
1606 * rtsSupportsBoundThreads(): is the RTS built to support bound threads?
1607 * used by Control.Concurrent for error checking.
1608 * ------------------------------------------------------------------------- */
1611 rtsSupportsBoundThreads(void)
1620 /* ---------------------------------------------------------------------------
1621 * isThreadBound(tso): check whether tso is bound to an OS thread.
1622 * ------------------------------------------------------------------------- */
1625 isThreadBound(StgTSO* tso USED_IN_THREADED_RTS)
1629 for(m = main_threads; m; m = m->link)
1638 /* ---------------------------------------------------------------------------
1639 * Singleton fork(). Do not copy any running threads.
1640 * ------------------------------------------------------------------------- */
1644 deleteThreadImmediately(StgTSO *tso);
1648 forkProcess(StgTSO* tso)
1650 #ifndef mingw32_TARGET_OS
1654 IF_DEBUG(scheduler,sched_belch("forking!"));
1655 ACQUIRE_LOCK(&sched_mutex);
1658 if (pid) { /* parent */
1660 /* just return the pid */
1662 } else { /* child */
1664 /* wipe all other threads */
1665 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1666 tso->link = END_TSO_QUEUE;
1668 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1671 /* Don't kill the current thread.. */
1672 if (t->id == tso->id) {
1676 if (isThreadBound(t)) {
1677 // If the thread is bound, the OS thread that the thread is bound to
1678 // no longer exists after the fork() system call.
1679 // The bound Haskell thread is therefore unable to run at all;
1680 // we must not give it a chance to survive by catching the
1681 // ThreadKilled exception. So we kill it "brutally" rather than
1682 // using deleteThread.
1683 deleteThreadImmediately(t);
1689 if (isThreadBound(tso)) {
1691 // If the current is not bound, then we should make it so.
1692 // The OS thread left over by fork() is special in that the process
1693 // will terminate as soon as the thread terminates;
1694 // we'd expect forkProcess to behave similarily.
1695 // FIXME - we don't do this.
1700 /* wipe all other threads */
1701 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1702 tso->link = END_TSO_QUEUE;
1704 /* When clearing out the threads, we need to ensure
1705 that a 'main thread' is left behind; if there isn't,
1706 the Scheduler will shutdown next time it is entered.
1708 ==> we don't kill a thread that's on the main_threads
1709 list (nor the current thread.)
1711 [ Attempts at implementing the more ambitious scheme of
1712 killing the main_threads also, and then adding the
1713 current thread onto the main_threads list if it wasn't
1714 there already, failed -- waitThread() (for one) wasn't
1715 up to it. If it proves to be desirable to also kill
1716 the main threads, then this scheme will have to be
1717 revisited (and fully debugged!)
1722 /* DO NOT TOUCH THE QUEUES directly because most of the code around
1723 us is picky about finding the thread still in its queue when
1724 handling the deleteThread() */
1726 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1729 /* Don't kill the current thread.. */
1730 if (t->id == tso->id) continue;
1732 /* ..or a main thread */
1733 for (m = main_threads; m != NULL; m = m->link) {
1734 if (m->tso->id == t->id) {
1745 RELEASE_LOCK(&sched_mutex);
1748 barf("forkProcess#: primop not implemented for mingw32, sorry! (%u)\n", tso->id);
1749 /* pointlessly printing out the TSOs 'id' to avoid CC unused warning. */
1751 #endif /* mingw32 */
1754 /* ---------------------------------------------------------------------------
1755 * deleteAllThreads(): kill all the live threads.
1757 * This is used when we catch a user interrupt (^C), before performing
1758 * any necessary cleanups and running finalizers.
1760 * Locks: sched_mutex held.
1761 * ------------------------------------------------------------------------- */
1764 deleteAllThreads ( void )
1767 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
1768 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1769 next = t->global_link;
1772 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1773 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
1774 sleeping_queue = END_TSO_QUEUE;
1777 /* startThread and insertThread are now in GranSim.c -- HWL */
1780 //@node Suspend and Resume, Run queue code, Main scheduling loop, Main scheduling code
1781 //@subsection Suspend and Resume
1783 /* ---------------------------------------------------------------------------
1784 * Suspending & resuming Haskell threads.
1786 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1787 * its capability before calling the C function. This allows another
1788 * task to pick up the capability and carry on running Haskell
1789 * threads. It also means that if the C call blocks, it won't lock
1792 * The Haskell thread making the C call is put to sleep for the
1793 * duration of the call, on the susepended_ccalling_threads queue. We
1794 * give out a token to the task, which it can use to resume the thread
1795 * on return from the C function.
1796 * ------------------------------------------------------------------------- */
1799 suspendThread( StgRegTable *reg,
1801 #if !defined(RTS_SUPPORTS_THREADS) && !defined(DEBUG)
1808 int saved_errno = errno;
1810 /* assume that *reg is a pointer to the StgRegTable part
1813 cap = (Capability *)((void *)reg - sizeof(StgFunTable));
1815 ACQUIRE_LOCK(&sched_mutex);
1818 sched_belch("thread %d did a _ccall_gc (is_concurrent: %d)", cap->r.rCurrentTSO->id,concCall));
1820 // XXX this might not be necessary --SDM
1821 cap->r.rCurrentTSO->what_next = ThreadRunGHC;
1823 threadPaused(cap->r.rCurrentTSO);
1824 cap->r.rCurrentTSO->link = suspended_ccalling_threads;
1825 suspended_ccalling_threads = cap->r.rCurrentTSO;
1827 #if defined(RTS_SUPPORTS_THREADS)
1828 if(cap->r.rCurrentTSO->blocked_exceptions == NULL)
1830 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall;
1831 cap->r.rCurrentTSO->blocked_exceptions = END_TSO_QUEUE;
1835 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall_NoUnblockExc;
1839 /* Use the thread ID as the token; it should be unique */
1840 tok = cap->r.rCurrentTSO->id;
1842 /* Hand back capability */
1843 releaseCapability(cap);
1845 #if defined(RTS_SUPPORTS_THREADS)
1846 /* Preparing to leave the RTS, so ensure there's a native thread/task
1847 waiting to take over.
1849 IF_DEBUG(scheduler, sched_belch("worker thread (%d, osthread %p): leaving RTS", tok, osThreadId()));
1852 /* Other threads _might_ be available for execution; signal this */
1854 RELEASE_LOCK(&sched_mutex);
1856 errno = saved_errno;
1861 resumeThread( StgInt tok,
1862 rtsBool concCall STG_UNUSED )
1864 StgTSO *tso, **prev;
1866 int saved_errno = errno;
1868 #if defined(RTS_SUPPORTS_THREADS)
1869 /* Wait for permission to re-enter the RTS with the result. */
1870 ACQUIRE_LOCK(&sched_mutex);
1871 grabReturnCapability(&sched_mutex, &cap);
1873 IF_DEBUG(scheduler, sched_belch("worker thread (%d, osthread %p): re-entering RTS", tok, osThreadId()));
1875 grabCapability(&cap);
1878 /* Remove the thread off of the suspended list */
1879 prev = &suspended_ccalling_threads;
1880 for (tso = suspended_ccalling_threads;
1881 tso != END_TSO_QUEUE;
1882 prev = &tso->link, tso = tso->link) {
1883 if (tso->id == (StgThreadID)tok) {
1888 if (tso == END_TSO_QUEUE) {
1889 barf("resumeThread: thread not found");
1891 tso->link = END_TSO_QUEUE;
1893 #if defined(RTS_SUPPORTS_THREADS)
1894 if(tso->why_blocked == BlockedOnCCall)
1896 awakenBlockedQueueNoLock(tso->blocked_exceptions);
1897 tso->blocked_exceptions = NULL;
1901 /* Reset blocking status */
1902 tso->why_blocked = NotBlocked;
1904 cap->r.rCurrentTSO = tso;
1905 #if defined(RTS_SUPPORTS_THREADS)
1906 RELEASE_LOCK(&sched_mutex);
1908 errno = saved_errno;
1913 /* ---------------------------------------------------------------------------
1915 * ------------------------------------------------------------------------ */
1916 static void unblockThread(StgTSO *tso);
1918 /* ---------------------------------------------------------------------------
1919 * Comparing Thread ids.
1921 * This is used from STG land in the implementation of the
1922 * instances of Eq/Ord for ThreadIds.
1923 * ------------------------------------------------------------------------ */
1926 cmp_thread(StgPtr tso1, StgPtr tso2)
1928 StgThreadID id1 = ((StgTSO *)tso1)->id;
1929 StgThreadID id2 = ((StgTSO *)tso2)->id;
1931 if (id1 < id2) return (-1);
1932 if (id1 > id2) return 1;
1936 /* ---------------------------------------------------------------------------
1937 * Fetching the ThreadID from an StgTSO.
1939 * This is used in the implementation of Show for ThreadIds.
1940 * ------------------------------------------------------------------------ */
1942 rts_getThreadId(StgPtr tso)
1944 return ((StgTSO *)tso)->id;
1949 labelThread(StgPtr tso, char *label)
1954 /* Caveat: Once set, you can only set the thread name to "" */
1955 len = strlen(label)+1;
1956 buf = stgMallocBytes(len * sizeof(char), "Schedule.c:labelThread()");
1957 strncpy(buf,label,len);
1958 /* Update will free the old memory for us */
1959 updateThreadLabel((StgWord)tso,buf);
1963 /* ---------------------------------------------------------------------------
1964 Create a new thread.
1966 The new thread starts with the given stack size. Before the
1967 scheduler can run, however, this thread needs to have a closure
1968 (and possibly some arguments) pushed on its stack. See
1969 pushClosure() in Schedule.h.
1971 createGenThread() and createIOThread() (in SchedAPI.h) are
1972 convenient packaged versions of this function.
1974 currently pri (priority) is only used in a GRAN setup -- HWL
1975 ------------------------------------------------------------------------ */
1976 //@cindex createThread
1978 /* currently pri (priority) is only used in a GRAN setup -- HWL */
1980 createThread(nat size, StgInt pri)
1983 createThread(nat size)
1990 /* First check whether we should create a thread at all */
1992 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1993 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1995 belch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1996 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1997 return END_TSO_QUEUE;
2003 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
2006 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
2008 /* catch ridiculously small stack sizes */
2009 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
2010 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
2013 stack_size = size - TSO_STRUCT_SIZEW;
2015 tso = (StgTSO *)allocate(size);
2016 TICK_ALLOC_TSO(stack_size, 0);
2018 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
2020 SET_GRAN_HDR(tso, ThisPE);
2023 // Always start with the compiled code evaluator
2024 tso->what_next = ThreadRunGHC;
2026 /* tso->id needs to be unique. For now we use a heavyweight mutex to
2027 * protect the increment operation on next_thread_id.
2028 * In future, we could use an atomic increment instead.
2030 ACQUIRE_LOCK(&thread_id_mutex);
2031 tso->id = next_thread_id++;
2032 RELEASE_LOCK(&thread_id_mutex);
2034 tso->why_blocked = NotBlocked;
2035 tso->blocked_exceptions = NULL;
2037 tso->saved_errno = 0;
2039 tso->stack_size = stack_size;
2040 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
2042 tso->sp = (P_)&(tso->stack) + stack_size;
2045 tso->prof.CCCS = CCS_MAIN;
2048 /* put a stop frame on the stack */
2049 tso->sp -= sizeofW(StgStopFrame);
2050 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
2053 tso->link = END_TSO_QUEUE;
2054 /* uses more flexible routine in GranSim */
2055 insertThread(tso, CurrentProc);
2057 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
2063 if (RtsFlags.GranFlags.GranSimStats.Full)
2064 DumpGranEvent(GR_START,tso);
2066 if (RtsFlags.ParFlags.ParStats.Full)
2067 DumpGranEvent(GR_STARTQ,tso);
2068 /* HACk to avoid SCHEDULE
2072 /* Link the new thread on the global thread list.
2074 tso->global_link = all_threads;
2078 tso->dist.priority = MandatoryPriority; //by default that is...
2082 tso->gran.pri = pri;
2084 tso->gran.magic = TSO_MAGIC; // debugging only
2086 tso->gran.sparkname = 0;
2087 tso->gran.startedat = CURRENT_TIME;
2088 tso->gran.exported = 0;
2089 tso->gran.basicblocks = 0;
2090 tso->gran.allocs = 0;
2091 tso->gran.exectime = 0;
2092 tso->gran.fetchtime = 0;
2093 tso->gran.fetchcount = 0;
2094 tso->gran.blocktime = 0;
2095 tso->gran.blockcount = 0;
2096 tso->gran.blockedat = 0;
2097 tso->gran.globalsparks = 0;
2098 tso->gran.localsparks = 0;
2099 if (RtsFlags.GranFlags.Light)
2100 tso->gran.clock = Now; /* local clock */
2102 tso->gran.clock = 0;
2104 IF_DEBUG(gran,printTSO(tso));
2107 tso->par.magic = TSO_MAGIC; // debugging only
2109 tso->par.sparkname = 0;
2110 tso->par.startedat = CURRENT_TIME;
2111 tso->par.exported = 0;
2112 tso->par.basicblocks = 0;
2113 tso->par.allocs = 0;
2114 tso->par.exectime = 0;
2115 tso->par.fetchtime = 0;
2116 tso->par.fetchcount = 0;
2117 tso->par.blocktime = 0;
2118 tso->par.blockcount = 0;
2119 tso->par.blockedat = 0;
2120 tso->par.globalsparks = 0;
2121 tso->par.localsparks = 0;
2125 globalGranStats.tot_threads_created++;
2126 globalGranStats.threads_created_on_PE[CurrentProc]++;
2127 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
2128 globalGranStats.tot_sq_probes++;
2130 // collect parallel global statistics (currently done together with GC stats)
2131 if (RtsFlags.ParFlags.ParStats.Global &&
2132 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
2133 //fprintf(stderr, "Creating thread %d @ %11.2f\n", tso->id, usertime());
2134 globalParStats.tot_threads_created++;
2140 belch("==__ schedule: Created TSO %d (%p);",
2141 CurrentProc, tso, tso->id));
2143 IF_PAR_DEBUG(verbose,
2144 belch("==__ schedule: Created TSO %d (%p); %d threads active",
2145 tso->id, tso, advisory_thread_count));
2147 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
2148 tso->id, tso->stack_size));
2155 all parallel thread creation calls should fall through the following routine.
2158 createSparkThread(rtsSpark spark)
2160 ASSERT(spark != (rtsSpark)NULL);
2161 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
2163 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
2164 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
2165 return END_TSO_QUEUE;
2169 tso = createThread(RtsFlags.GcFlags.initialStkSize);
2170 if (tso==END_TSO_QUEUE)
2171 barf("createSparkThread: Cannot create TSO");
2173 tso->priority = AdvisoryPriority;
2175 pushClosure(tso,spark);
2176 PUSH_ON_RUN_QUEUE(tso);
2177 advisory_thread_count++;
2184 Turn a spark into a thread.
2185 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
2188 //@cindex activateSpark
2190 activateSpark (rtsSpark spark)
2194 tso = createSparkThread(spark);
2195 if (RtsFlags.ParFlags.ParStats.Full) {
2196 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
2197 IF_PAR_DEBUG(verbose,
2198 belch("==^^ activateSpark: turning spark of closure %p (%s) into a thread",
2199 (StgClosure *)spark, info_type((StgClosure *)spark)));
2201 // ToDo: fwd info on local/global spark to thread -- HWL
2202 // tso->gran.exported = spark->exported;
2203 // tso->gran.locked = !spark->global;
2204 // tso->gran.sparkname = spark->name;
2210 static SchedulerStatus waitThread_(/*out*/StgMainThread* m,
2211 Capability *initialCapability
2215 /* ---------------------------------------------------------------------------
2218 * scheduleThread puts a thread on the head of the runnable queue.
2219 * This will usually be done immediately after a thread is created.
2220 * The caller of scheduleThread must create the thread using e.g.
2221 * createThread and push an appropriate closure
2222 * on this thread's stack before the scheduler is invoked.
2223 * ------------------------------------------------------------------------ */
2225 static void scheduleThread_ (StgTSO* tso);
2228 scheduleThread_(StgTSO *tso)
2230 // Precondition: sched_mutex must be held.
2232 /* Put the new thread on the head of the runnable queue. The caller
2233 * better push an appropriate closure on this thread's stack
2234 * beforehand. In the SMP case, the thread may start running as
2235 * soon as we release the scheduler lock below.
2237 PUSH_ON_RUN_QUEUE(tso);
2241 IF_DEBUG(scheduler,printTSO(tso));
2245 void scheduleThread(StgTSO* tso)
2247 ACQUIRE_LOCK(&sched_mutex);
2248 scheduleThread_(tso);
2249 RELEASE_LOCK(&sched_mutex);
2253 scheduleWaitThread(StgTSO* tso, /*[out]*/HaskellObj* ret, Capability *initialCapability)
2254 { // Precondition: sched_mutex must be held
2257 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2261 #if defined(RTS_SUPPORTS_THREADS)
2262 #if defined(THREADED_RTS)
2263 initCondition(&m->bound_thread_cond);
2265 initCondition(&m->wakeup);
2269 /* Put the thread on the main-threads list prior to scheduling the TSO.
2270 Failure to do so introduces a race condition in the MT case (as
2271 identified by Wolfgang Thaller), whereby the new task/OS thread
2272 created by scheduleThread_() would complete prior to the thread
2273 that spawned it managed to put 'itself' on the main-threads list.
2274 The upshot of it all being that the worker thread wouldn't get to
2275 signal the completion of the its work item for the main thread to
2276 see (==> it got stuck waiting.) -- sof 6/02.
2278 IF_DEBUG(scheduler, sched_belch("waiting for thread (%d)\n", tso->id));
2280 m->link = main_threads;
2283 scheduleThread_(tso);
2285 return waitThread_(m, initialCapability);
2288 /* ---------------------------------------------------------------------------
2291 * Initialise the scheduler. This resets all the queues - if the
2292 * queues contained any threads, they'll be garbage collected at the
2295 * ------------------------------------------------------------------------ */
2299 term_handler(int sig STG_UNUSED)
2302 ACQUIRE_LOCK(&term_mutex);
2304 RELEASE_LOCK(&term_mutex);
2315 for (i=0; i<=MAX_PROC; i++) {
2316 run_queue_hds[i] = END_TSO_QUEUE;
2317 run_queue_tls[i] = END_TSO_QUEUE;
2318 blocked_queue_hds[i] = END_TSO_QUEUE;
2319 blocked_queue_tls[i] = END_TSO_QUEUE;
2320 ccalling_threadss[i] = END_TSO_QUEUE;
2321 sleeping_queue = END_TSO_QUEUE;
2324 run_queue_hd = END_TSO_QUEUE;
2325 run_queue_tl = END_TSO_QUEUE;
2326 blocked_queue_hd = END_TSO_QUEUE;
2327 blocked_queue_tl = END_TSO_QUEUE;
2328 sleeping_queue = END_TSO_QUEUE;
2331 suspended_ccalling_threads = END_TSO_QUEUE;
2333 main_threads = NULL;
2334 all_threads = END_TSO_QUEUE;
2339 RtsFlags.ConcFlags.ctxtSwitchTicks =
2340 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
2342 #if defined(RTS_SUPPORTS_THREADS)
2343 /* Initialise the mutex and condition variables used by
2345 initMutex(&sched_mutex);
2346 initMutex(&term_mutex);
2347 initMutex(&thread_id_mutex);
2349 initCondition(&thread_ready_cond);
2353 initCondition(&gc_pending_cond);
2356 #if defined(RTS_SUPPORTS_THREADS)
2357 ACQUIRE_LOCK(&sched_mutex);
2360 /* Install the SIGHUP handler */
2363 struct sigaction action,oact;
2365 action.sa_handler = term_handler;
2366 sigemptyset(&action.sa_mask);
2367 action.sa_flags = 0;
2368 if (sigaction(SIGTERM, &action, &oact) != 0) {
2369 barf("can't install TERM handler");
2374 /* A capability holds the state a native thread needs in
2375 * order to execute STG code. At least one capability is
2376 * floating around (only SMP builds have more than one).
2380 #if defined(RTS_SUPPORTS_THREADS)
2381 /* start our haskell execution tasks */
2383 startTaskManager(RtsFlags.ParFlags.nNodes, taskStart);
2385 startTaskManager(0,taskStart);
2389 #if /* defined(SMP) ||*/ defined(PAR)
2393 #if defined(RTS_SUPPORTS_THREADS)
2394 RELEASE_LOCK(&sched_mutex);
2400 exitScheduler( void )
2402 #if defined(RTS_SUPPORTS_THREADS)
2405 shutting_down_scheduler = rtsTrue;
2408 /* -----------------------------------------------------------------------------
2409 Managing the per-task allocation areas.
2411 Each capability comes with an allocation area. These are
2412 fixed-length block lists into which allocation can be done.
2414 ToDo: no support for two-space collection at the moment???
2415 -------------------------------------------------------------------------- */
2417 /* -----------------------------------------------------------------------------
2418 * waitThread is the external interface for running a new computation
2419 * and waiting for the result.
2421 * In the non-SMP case, we create a new main thread, push it on the
2422 * main-thread stack, and invoke the scheduler to run it. The
2423 * scheduler will return when the top main thread on the stack has
2424 * completed or died, and fill in the necessary fields of the
2425 * main_thread structure.
2427 * In the SMP case, we create a main thread as before, but we then
2428 * create a new condition variable and sleep on it. When our new
2429 * main thread has completed, we'll be woken up and the status/result
2430 * will be in the main_thread struct.
2431 * -------------------------------------------------------------------------- */
2434 howManyThreadsAvail ( void )
2438 for (q = run_queue_hd; q != END_TSO_QUEUE; q = q->link)
2440 for (q = blocked_queue_hd; q != END_TSO_QUEUE; q = q->link)
2442 for (q = sleeping_queue; q != END_TSO_QUEUE; q = q->link)
2448 finishAllThreads ( void )
2451 while (run_queue_hd != END_TSO_QUEUE) {
2452 waitThread ( run_queue_hd, NULL, NULL );
2454 while (blocked_queue_hd != END_TSO_QUEUE) {
2455 waitThread ( blocked_queue_hd, NULL, NULL );
2457 while (sleeping_queue != END_TSO_QUEUE) {
2458 waitThread ( blocked_queue_hd, NULL, NULL );
2461 (blocked_queue_hd != END_TSO_QUEUE ||
2462 run_queue_hd != END_TSO_QUEUE ||
2463 sleeping_queue != END_TSO_QUEUE);
2467 waitThread(StgTSO *tso, /*out*/StgClosure **ret, Capability *initialCapability)
2470 SchedulerStatus stat;
2472 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2476 #if defined(RTS_SUPPORTS_THREADS)
2477 #if defined(THREADED_RTS)
2478 initCondition(&m->bound_thread_cond);
2480 initCondition(&m->wakeup);
2484 /* see scheduleWaitThread() comment */
2485 ACQUIRE_LOCK(&sched_mutex);
2486 m->link = main_threads;
2489 IF_DEBUG(scheduler, sched_belch("waiting for thread %d", tso->id));
2491 stat = waitThread_(m,initialCapability);
2493 RELEASE_LOCK(&sched_mutex);
2499 waitThread_(StgMainThread* m, Capability *initialCapability)
2501 SchedulerStatus stat;
2503 // Precondition: sched_mutex must be held.
2504 IF_DEBUG(scheduler, sched_belch("== scheduler: new main thread (%d)\n", m->tso->id));
2506 #if defined(RTS_SUPPORTS_THREADS) && !defined(THREADED_RTS)
2507 { // FIXME: does this still make sense?
2508 // It's not for the threaded rts => SMP only
2510 waitCondition(&m->wakeup, &sched_mutex);
2511 } while (m->stat == NoStatus);
2514 /* GranSim specific init */
2515 CurrentTSO = m->tso; // the TSO to run
2516 procStatus[MainProc] = Busy; // status of main PE
2517 CurrentProc = MainProc; // PE to run it on
2519 RELEASE_LOCK(&sched_mutex);
2520 schedule(m,initialCapability);
2522 RELEASE_LOCK(&sched_mutex);
2523 schedule(m,initialCapability);
2524 ACQUIRE_LOCK(&sched_mutex);
2525 ASSERT(m->stat != NoStatus);
2530 #if defined(RTS_SUPPORTS_THREADS)
2531 #if defined(THREADED_RTS)
2532 closeCondition(&m->bound_thread_cond);
2534 closeCondition(&m->wakeup);
2538 IF_DEBUG(scheduler, fprintf(stderr, "== scheduler: main thread (%d) finished\n",
2542 // Postcondition: sched_mutex still held
2546 //@node Run queue code, Garbage Collextion Routines, Suspend and Resume, Main scheduling code
2547 //@subsection Run queue code
2551 NB: In GranSim we have many run queues; run_queue_hd is actually a macro
2552 unfolding to run_queue_hds[CurrentProc], thus CurrentProc is an
2553 implicit global variable that has to be correct when calling these
2557 /* Put the new thread on the head of the runnable queue.
2558 * The caller of createThread better push an appropriate closure
2559 * on this thread's stack before the scheduler is invoked.
2561 static /* inline */ void
2562 add_to_run_queue(tso)
2565 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2566 tso->link = run_queue_hd;
2568 if (run_queue_tl == END_TSO_QUEUE) {
2573 /* Put the new thread at the end of the runnable queue. */
2574 static /* inline */ void
2575 push_on_run_queue(tso)
2578 ASSERT(get_itbl((StgClosure *)tso)->type == TSO);
2579 ASSERT(run_queue_hd!=NULL && run_queue_tl!=NULL);
2580 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2581 if (run_queue_hd == END_TSO_QUEUE) {
2584 run_queue_tl->link = tso;
2590 Should be inlined because it's used very often in schedule. The tso
2591 argument is actually only needed in GranSim, where we want to have the
2592 possibility to schedule *any* TSO on the run queue, irrespective of the
2593 actual ordering. Therefore, if tso is not the nil TSO then we traverse
2594 the run queue and dequeue the tso, adjusting the links in the queue.
2596 //@cindex take_off_run_queue
2597 static /* inline */ StgTSO*
2598 take_off_run_queue(StgTSO *tso) {
2602 qetlaHbogh Qu' ngaSbogh ghomDaQ {tso} yIteq!
2604 if tso is specified, unlink that tso from the run_queue (doesn't have
2605 to be at the beginning of the queue); GranSim only
2607 if (tso!=END_TSO_QUEUE) {
2608 /* find tso in queue */
2609 for (t=run_queue_hd, prev=END_TSO_QUEUE;
2610 t!=END_TSO_QUEUE && t!=tso;
2614 /* now actually dequeue the tso */
2615 if (prev!=END_TSO_QUEUE) {
2616 ASSERT(run_queue_hd!=t);
2617 prev->link = t->link;
2619 /* t is at beginning of thread queue */
2620 ASSERT(run_queue_hd==t);
2621 run_queue_hd = t->link;
2623 /* t is at end of thread queue */
2624 if (t->link==END_TSO_QUEUE) {
2625 ASSERT(t==run_queue_tl);
2626 run_queue_tl = prev;
2628 ASSERT(run_queue_tl!=t);
2630 t->link = END_TSO_QUEUE;
2632 /* take tso from the beginning of the queue; std concurrent code */
2634 if (t != END_TSO_QUEUE) {
2635 run_queue_hd = t->link;
2636 t->link = END_TSO_QUEUE;
2637 if (run_queue_hd == END_TSO_QUEUE) {
2638 run_queue_tl = END_TSO_QUEUE;
2647 //@node Garbage Collextion Routines, Blocking Queue Routines, Run queue code, Main scheduling code
2648 //@subsection Garbage Collextion Routines
2650 /* ---------------------------------------------------------------------------
2651 Where are the roots that we know about?
2653 - all the threads on the runnable queue
2654 - all the threads on the blocked queue
2655 - all the threads on the sleeping queue
2656 - all the thread currently executing a _ccall_GC
2657 - all the "main threads"
2659 ------------------------------------------------------------------------ */
2661 /* This has to be protected either by the scheduler monitor, or by the
2662 garbage collection monitor (probably the latter).
2667 GetRoots(evac_fn evac)
2672 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2673 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2674 evac((StgClosure **)&run_queue_hds[i]);
2675 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2676 evac((StgClosure **)&run_queue_tls[i]);
2678 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2679 evac((StgClosure **)&blocked_queue_hds[i]);
2680 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2681 evac((StgClosure **)&blocked_queue_tls[i]);
2682 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2683 evac((StgClosure **)&ccalling_threads[i]);
2690 if (run_queue_hd != END_TSO_QUEUE) {
2691 ASSERT(run_queue_tl != END_TSO_QUEUE);
2692 evac((StgClosure **)&run_queue_hd);
2693 evac((StgClosure **)&run_queue_tl);
2696 if (blocked_queue_hd != END_TSO_QUEUE) {
2697 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2698 evac((StgClosure **)&blocked_queue_hd);
2699 evac((StgClosure **)&blocked_queue_tl);
2702 if (sleeping_queue != END_TSO_QUEUE) {
2703 evac((StgClosure **)&sleeping_queue);
2707 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2708 evac((StgClosure **)&suspended_ccalling_threads);
2711 #if defined(PAR) || defined(GRAN)
2712 markSparkQueue(evac);
2715 #if defined(RTS_USER_SIGNALS)
2716 // mark the signal handlers (signals should be already blocked)
2717 markSignalHandlers(evac);
2720 // main threads which have completed need to be retained until they
2721 // are dealt with in the main scheduler loop. They won't be
2722 // retained any other way: the GC will drop them from the
2723 // all_threads list, so we have to be careful to treat them as roots
2727 for (m = main_threads; m != NULL; m = m->link) {
2728 switch (m->tso->what_next) {
2729 case ThreadComplete:
2731 evac((StgClosure **)&m->tso);
2740 /* -----------------------------------------------------------------------------
2743 This is the interface to the garbage collector from Haskell land.
2744 We provide this so that external C code can allocate and garbage
2745 collect when called from Haskell via _ccall_GC.
2747 It might be useful to provide an interface whereby the programmer
2748 can specify more roots (ToDo).
2750 This needs to be protected by the GC condition variable above. KH.
2751 -------------------------------------------------------------------------- */
2753 static void (*extra_roots)(evac_fn);
2758 /* Obligated to hold this lock upon entry */
2759 ACQUIRE_LOCK(&sched_mutex);
2760 GarbageCollect(GetRoots,rtsFalse);
2761 RELEASE_LOCK(&sched_mutex);
2765 performMajorGC(void)
2767 ACQUIRE_LOCK(&sched_mutex);
2768 GarbageCollect(GetRoots,rtsTrue);
2769 RELEASE_LOCK(&sched_mutex);
2773 AllRoots(evac_fn evac)
2775 GetRoots(evac); // the scheduler's roots
2776 extra_roots(evac); // the user's roots
2780 performGCWithRoots(void (*get_roots)(evac_fn))
2782 ACQUIRE_LOCK(&sched_mutex);
2783 extra_roots = get_roots;
2784 GarbageCollect(AllRoots,rtsFalse);
2785 RELEASE_LOCK(&sched_mutex);
2788 /* -----------------------------------------------------------------------------
2791 If the thread has reached its maximum stack size, then raise the
2792 StackOverflow exception in the offending thread. Otherwise
2793 relocate the TSO into a larger chunk of memory and adjust its stack
2795 -------------------------------------------------------------------------- */
2798 threadStackOverflow(StgTSO *tso)
2800 nat new_stack_size, new_tso_size, stack_words;
2804 IF_DEBUG(sanity,checkTSO(tso));
2805 if (tso->stack_size >= tso->max_stack_size) {
2808 belch("@@ threadStackOverflow of TSO %d (%p): stack too large (now %ld; max is %ld",
2809 tso->id, tso, tso->stack_size, tso->max_stack_size);
2810 /* If we're debugging, just print out the top of the stack */
2811 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2814 /* Send this thread the StackOverflow exception */
2815 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2819 /* Try to double the current stack size. If that takes us over the
2820 * maximum stack size for this thread, then use the maximum instead.
2821 * Finally round up so the TSO ends up as a whole number of blocks.
2823 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2824 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2825 TSO_STRUCT_SIZE)/sizeof(W_);
2826 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2827 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2829 IF_DEBUG(scheduler, fprintf(stderr,"== scheduler: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2831 dest = (StgTSO *)allocate(new_tso_size);
2832 TICK_ALLOC_TSO(new_stack_size,0);
2834 /* copy the TSO block and the old stack into the new area */
2835 memcpy(dest,tso,TSO_STRUCT_SIZE);
2836 stack_words = tso->stack + tso->stack_size - tso->sp;
2837 new_sp = (P_)dest + new_tso_size - stack_words;
2838 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2840 /* relocate the stack pointers... */
2842 dest->stack_size = new_stack_size;
2844 /* Mark the old TSO as relocated. We have to check for relocated
2845 * TSOs in the garbage collector and any primops that deal with TSOs.
2847 * It's important to set the sp value to just beyond the end
2848 * of the stack, so we don't attempt to scavenge any part of the
2851 tso->what_next = ThreadRelocated;
2853 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2854 tso->why_blocked = NotBlocked;
2855 dest->mut_link = NULL;
2857 IF_PAR_DEBUG(verbose,
2858 belch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld",
2859 tso->id, tso, tso->stack_size);
2860 /* If we're debugging, just print out the top of the stack */
2861 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2864 IF_DEBUG(sanity,checkTSO(tso));
2866 IF_DEBUG(scheduler,printTSO(dest));
2872 //@node Blocking Queue Routines, Exception Handling Routines, Garbage Collextion Routines, Main scheduling code
2873 //@subsection Blocking Queue Routines
2875 /* ---------------------------------------------------------------------------
2876 Wake up a queue that was blocked on some resource.
2877 ------------------------------------------------------------------------ */
2881 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2886 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2888 /* write RESUME events to log file and
2889 update blocked and fetch time (depending on type of the orig closure) */
2890 if (RtsFlags.ParFlags.ParStats.Full) {
2891 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2892 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2893 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2894 if (EMPTY_RUN_QUEUE())
2895 emitSchedule = rtsTrue;
2897 switch (get_itbl(node)->type) {
2899 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2904 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2911 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2918 static StgBlockingQueueElement *
2919 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2922 PEs node_loc, tso_loc;
2924 node_loc = where_is(node); // should be lifted out of loop
2925 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2926 tso_loc = where_is((StgClosure *)tso);
2927 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2928 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2929 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2930 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2931 // insertThread(tso, node_loc);
2932 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2934 tso, node, (rtsSpark*)NULL);
2935 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2938 } else { // TSO is remote (actually should be FMBQ)
2939 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2940 RtsFlags.GranFlags.Costs.gunblocktime +
2941 RtsFlags.GranFlags.Costs.latency;
2942 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2944 tso, node, (rtsSpark*)NULL);
2945 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2948 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2950 fprintf(stderr," %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2951 (node_loc==tso_loc ? "Local" : "Global"),
2952 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2953 tso->block_info.closure = NULL;
2954 IF_DEBUG(scheduler,belch("-- Waking up thread %ld (%p)",
2958 static StgBlockingQueueElement *
2959 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2961 StgBlockingQueueElement *next;
2963 switch (get_itbl(bqe)->type) {
2965 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2966 /* if it's a TSO just push it onto the run_queue */
2968 // ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2969 PUSH_ON_RUN_QUEUE((StgTSO *)bqe);
2971 unblockCount(bqe, node);
2972 /* reset blocking status after dumping event */
2973 ((StgTSO *)bqe)->why_blocked = NotBlocked;
2977 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2979 bqe->link = (StgBlockingQueueElement *)PendingFetches;
2980 PendingFetches = (StgBlockedFetch *)bqe;
2984 /* can ignore this case in a non-debugging setup;
2985 see comments on RBHSave closures above */
2987 /* check that the closure is an RBHSave closure */
2988 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2989 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2990 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2994 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2995 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
2999 IF_PAR_DEBUG(bq, fprintf(stderr, ", %p (%s)", bqe, info_type((StgClosure*)bqe)));
3003 #else /* !GRAN && !PAR */
3005 unblockOneLocked(StgTSO *tso)
3009 ASSERT(get_itbl(tso)->type == TSO);
3010 ASSERT(tso->why_blocked != NotBlocked);
3011 tso->why_blocked = NotBlocked;
3013 PUSH_ON_RUN_QUEUE(tso);
3015 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
3020 #if defined(GRAN) || defined(PAR)
3021 inline StgBlockingQueueElement *
3022 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
3024 ACQUIRE_LOCK(&sched_mutex);
3025 bqe = unblockOneLocked(bqe, node);
3026 RELEASE_LOCK(&sched_mutex);
3031 unblockOne(StgTSO *tso)
3033 ACQUIRE_LOCK(&sched_mutex);
3034 tso = unblockOneLocked(tso);
3035 RELEASE_LOCK(&sched_mutex);
3042 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
3044 StgBlockingQueueElement *bqe;
3049 belch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): ", \
3050 node, CurrentProc, CurrentTime[CurrentProc],
3051 CurrentTSO->id, CurrentTSO));
3053 node_loc = where_is(node);
3055 ASSERT(q == END_BQ_QUEUE ||
3056 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
3057 get_itbl(q)->type == CONSTR); // closure (type constructor)
3058 ASSERT(is_unique(node));
3060 /* FAKE FETCH: magically copy the node to the tso's proc;
3061 no Fetch necessary because in reality the node should not have been
3062 moved to the other PE in the first place
3064 if (CurrentProc!=node_loc) {
3066 belch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)",
3067 node, node_loc, CurrentProc, CurrentTSO->id,
3068 // CurrentTSO, where_is(CurrentTSO),
3069 node->header.gran.procs));
3070 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
3072 belch("## new bitmask of node %p is %#x",
3073 node, node->header.gran.procs));
3074 if (RtsFlags.GranFlags.GranSimStats.Global) {
3075 globalGranStats.tot_fake_fetches++;
3080 // ToDo: check: ASSERT(CurrentProc==node_loc);
3081 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
3084 bqe points to the current element in the queue
3085 next points to the next element in the queue
3087 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
3088 //tso_loc = where_is(tso);
3090 bqe = unblockOneLocked(bqe, node);
3093 /* if this is the BQ of an RBH, we have to put back the info ripped out of
3094 the closure to make room for the anchor of the BQ */
3095 if (bqe!=END_BQ_QUEUE) {
3096 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
3098 ASSERT((info_ptr==&RBH_Save_0_info) ||
3099 (info_ptr==&RBH_Save_1_info) ||
3100 (info_ptr==&RBH_Save_2_info));
3102 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
3103 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
3104 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
3107 belch("## Filled in RBH_Save for %p (%s) at end of AwBQ",
3108 node, info_type(node)));
3111 /* statistics gathering */
3112 if (RtsFlags.GranFlags.GranSimStats.Global) {
3113 // globalGranStats.tot_bq_processing_time += bq_processing_time;
3114 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
3115 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
3116 globalGranStats.tot_awbq++; // total no. of bqs awakened
3119 fprintf(stderr,"## BQ Stats of %p: [%d entries] %s\n",
3120 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
3124 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
3126 StgBlockingQueueElement *bqe;
3128 ACQUIRE_LOCK(&sched_mutex);
3130 IF_PAR_DEBUG(verbose,
3131 belch("##-_ AwBQ for node %p on [%x]: ",
3135 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
3136 IF_PAR_DEBUG(verbose, belch("## ... nothing to unblock so lets just return. RFP (BUG?)"));
3141 ASSERT(q == END_BQ_QUEUE ||
3142 get_itbl(q)->type == TSO ||
3143 get_itbl(q)->type == BLOCKED_FETCH ||
3144 get_itbl(q)->type == CONSTR);
3147 while (get_itbl(bqe)->type==TSO ||
3148 get_itbl(bqe)->type==BLOCKED_FETCH) {
3149 bqe = unblockOneLocked(bqe, node);
3151 RELEASE_LOCK(&sched_mutex);
3154 #else /* !GRAN && !PAR */
3156 #ifdef RTS_SUPPORTS_THREADS
3158 awakenBlockedQueueNoLock(StgTSO *tso)
3160 while (tso != END_TSO_QUEUE) {
3161 tso = unblockOneLocked(tso);
3167 awakenBlockedQueue(StgTSO *tso)
3169 ACQUIRE_LOCK(&sched_mutex);
3170 while (tso != END_TSO_QUEUE) {
3171 tso = unblockOneLocked(tso);
3173 RELEASE_LOCK(&sched_mutex);
3177 //@node Exception Handling Routines, Debugging Routines, Blocking Queue Routines, Main scheduling code
3178 //@subsection Exception Handling Routines
3180 /* ---------------------------------------------------------------------------
3182 - usually called inside a signal handler so it mustn't do anything fancy.
3183 ------------------------------------------------------------------------ */
3186 interruptStgRts(void)
3192 /* -----------------------------------------------------------------------------
3195 This is for use when we raise an exception in another thread, which
3197 This has nothing to do with the UnblockThread event in GranSim. -- HWL
3198 -------------------------------------------------------------------------- */
3200 #if defined(GRAN) || defined(PAR)
3202 NB: only the type of the blocking queue is different in GranSim and GUM
3203 the operations on the queue-elements are the same
3204 long live polymorphism!
3206 Locks: sched_mutex is held upon entry and exit.
3210 unblockThread(StgTSO *tso)
3212 StgBlockingQueueElement *t, **last;
3214 switch (tso->why_blocked) {
3217 return; /* not blocked */
3220 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3222 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
3223 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3225 last = (StgBlockingQueueElement **)&mvar->head;
3226 for (t = (StgBlockingQueueElement *)mvar->head;
3228 last = &t->link, last_tso = t, t = t->link) {
3229 if (t == (StgBlockingQueueElement *)tso) {
3230 *last = (StgBlockingQueueElement *)tso->link;
3231 if (mvar->tail == tso) {
3232 mvar->tail = (StgTSO *)last_tso;
3237 barf("unblockThread (MVAR): TSO not found");
3240 case BlockedOnBlackHole:
3241 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3243 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3245 last = &bq->blocking_queue;
3246 for (t = bq->blocking_queue;
3248 last = &t->link, t = t->link) {
3249 if (t == (StgBlockingQueueElement *)tso) {
3250 *last = (StgBlockingQueueElement *)tso->link;
3254 barf("unblockThread (BLACKHOLE): TSO not found");
3257 case BlockedOnException:
3259 StgTSO *target = tso->block_info.tso;
3261 ASSERT(get_itbl(target)->type == TSO);
3263 if (target->what_next == ThreadRelocated) {
3264 target = target->link;
3265 ASSERT(get_itbl(target)->type == TSO);
3268 ASSERT(target->blocked_exceptions != NULL);
3270 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
3271 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
3273 last = &t->link, t = t->link) {
3274 ASSERT(get_itbl(t)->type == TSO);
3275 if (t == (StgBlockingQueueElement *)tso) {
3276 *last = (StgBlockingQueueElement *)tso->link;
3280 barf("unblockThread (Exception): TSO not found");
3284 case BlockedOnWrite:
3285 #if defined(mingw32_TARGET_OS)
3286 case BlockedOnDoProc:
3289 /* take TSO off blocked_queue */
3290 StgBlockingQueueElement *prev = NULL;
3291 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
3292 prev = t, t = t->link) {
3293 if (t == (StgBlockingQueueElement *)tso) {
3295 blocked_queue_hd = (StgTSO *)t->link;
3296 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3297 blocked_queue_tl = END_TSO_QUEUE;
3300 prev->link = t->link;
3301 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3302 blocked_queue_tl = (StgTSO *)prev;
3308 barf("unblockThread (I/O): TSO not found");
3311 case BlockedOnDelay:
3313 /* take TSO off sleeping_queue */
3314 StgBlockingQueueElement *prev = NULL;
3315 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
3316 prev = t, t = t->link) {
3317 if (t == (StgBlockingQueueElement *)tso) {
3319 sleeping_queue = (StgTSO *)t->link;
3321 prev->link = t->link;
3326 barf("unblockThread (delay): TSO not found");
3330 barf("unblockThread");
3334 tso->link = END_TSO_QUEUE;
3335 tso->why_blocked = NotBlocked;
3336 tso->block_info.closure = NULL;
3337 PUSH_ON_RUN_QUEUE(tso);
3341 unblockThread(StgTSO *tso)
3345 /* To avoid locking unnecessarily. */
3346 if (tso->why_blocked == NotBlocked) {
3350 switch (tso->why_blocked) {
3353 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3355 StgTSO *last_tso = END_TSO_QUEUE;
3356 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3359 for (t = mvar->head; t != END_TSO_QUEUE;
3360 last = &t->link, last_tso = t, t = t->link) {
3363 if (mvar->tail == tso) {
3364 mvar->tail = last_tso;
3369 barf("unblockThread (MVAR): TSO not found");
3372 case BlockedOnBlackHole:
3373 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3375 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3377 last = &bq->blocking_queue;
3378 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
3379 last = &t->link, t = t->link) {
3385 barf("unblockThread (BLACKHOLE): TSO not found");
3388 case BlockedOnException:
3390 StgTSO *target = tso->block_info.tso;
3392 ASSERT(get_itbl(target)->type == TSO);
3394 while (target->what_next == ThreadRelocated) {
3395 target = target->link;
3396 ASSERT(get_itbl(target)->type == TSO);
3399 ASSERT(target->blocked_exceptions != NULL);
3401 last = &target->blocked_exceptions;
3402 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
3403 last = &t->link, t = t->link) {
3404 ASSERT(get_itbl(t)->type == TSO);
3410 barf("unblockThread (Exception): TSO not found");
3414 case BlockedOnWrite:
3415 #if defined(mingw32_TARGET_OS)
3416 case BlockedOnDoProc:
3419 StgTSO *prev = NULL;
3420 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
3421 prev = t, t = t->link) {
3424 blocked_queue_hd = t->link;
3425 if (blocked_queue_tl == t) {
3426 blocked_queue_tl = END_TSO_QUEUE;
3429 prev->link = t->link;
3430 if (blocked_queue_tl == t) {
3431 blocked_queue_tl = prev;
3437 barf("unblockThread (I/O): TSO not found");
3440 case BlockedOnDelay:
3442 StgTSO *prev = NULL;
3443 for (t = sleeping_queue; t != END_TSO_QUEUE;
3444 prev = t, t = t->link) {
3447 sleeping_queue = t->link;
3449 prev->link = t->link;
3454 barf("unblockThread (delay): TSO not found");
3458 barf("unblockThread");
3462 tso->link = END_TSO_QUEUE;
3463 tso->why_blocked = NotBlocked;
3464 tso->block_info.closure = NULL;
3465 PUSH_ON_RUN_QUEUE(tso);
3469 /* -----------------------------------------------------------------------------
3472 * The following function implements the magic for raising an
3473 * asynchronous exception in an existing thread.
3475 * We first remove the thread from any queue on which it might be
3476 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
3478 * We strip the stack down to the innermost CATCH_FRAME, building
3479 * thunks in the heap for all the active computations, so they can
3480 * be restarted if necessary. When we reach a CATCH_FRAME, we build
3481 * an application of the handler to the exception, and push it on
3482 * the top of the stack.
3484 * How exactly do we save all the active computations? We create an
3485 * AP_STACK for every UpdateFrame on the stack. Entering one of these
3486 * AP_STACKs pushes everything from the corresponding update frame
3487 * upwards onto the stack. (Actually, it pushes everything up to the
3488 * next update frame plus a pointer to the next AP_STACK object.
3489 * Entering the next AP_STACK object pushes more onto the stack until we
3490 * reach the last AP_STACK object - at which point the stack should look
3491 * exactly as it did when we killed the TSO and we can continue
3492 * execution by entering the closure on top of the stack.
3494 * We can also kill a thread entirely - this happens if either (a) the
3495 * exception passed to raiseAsync is NULL, or (b) there's no
3496 * CATCH_FRAME on the stack. In either case, we strip the entire
3497 * stack and replace the thread with a zombie.
3499 * Locks: sched_mutex held upon entry nor exit.
3501 * -------------------------------------------------------------------------- */
3504 deleteThread(StgTSO *tso)
3506 raiseAsync(tso,NULL);
3511 deleteThreadImmediately(StgTSO *tso)
3512 { // for forkProcess only:
3513 // delete thread without giving it a chance to catch the KillThread exception
3515 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3518 #if defined(RTS_SUPPORTS_THREADS)
3519 if (tso->why_blocked != BlockedOnCCall
3520 && tso->why_blocked != BlockedOnCCall_NoUnblockExc)
3523 tso->what_next = ThreadKilled;
3528 raiseAsyncWithLock(StgTSO *tso, StgClosure *exception)
3530 /* When raising async exs from contexts where sched_mutex isn't held;
3531 use raiseAsyncWithLock(). */
3532 ACQUIRE_LOCK(&sched_mutex);
3533 raiseAsync(tso,exception);
3534 RELEASE_LOCK(&sched_mutex);
3538 raiseAsync(StgTSO *tso, StgClosure *exception)
3540 StgRetInfoTable *info;
3543 // Thread already dead?
3544 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3549 sched_belch("raising exception in thread %ld.", tso->id));
3551 // Remove it from any blocking queues
3556 // The stack freezing code assumes there's a closure pointer on
3557 // the top of the stack, so we have to arrange that this is the case...
3559 if (sp[0] == (W_)&stg_enter_info) {
3563 sp[0] = (W_)&stg_dummy_ret_closure;
3569 // 1. Let the top of the stack be the "current closure"
3571 // 2. Walk up the stack until we find either an UPDATE_FRAME or a
3574 // 3. If it's an UPDATE_FRAME, then make an AP_STACK containing the
3575 // current closure applied to the chunk of stack up to (but not
3576 // including) the update frame. This closure becomes the "current
3577 // closure". Go back to step 2.
3579 // 4. If it's a CATCH_FRAME, then leave the exception handler on
3580 // top of the stack applied to the exception.
3582 // 5. If it's a STOP_FRAME, then kill the thread.
3587 info = get_ret_itbl((StgClosure *)frame);
3589 while (info->i.type != UPDATE_FRAME
3590 && (info->i.type != CATCH_FRAME || exception == NULL)
3591 && info->i.type != STOP_FRAME) {
3592 frame += stack_frame_sizeW((StgClosure *)frame);
3593 info = get_ret_itbl((StgClosure *)frame);
3596 switch (info->i.type) {
3599 // If we find a CATCH_FRAME, and we've got an exception to raise,
3600 // then build the THUNK raise(exception), and leave it on
3601 // top of the CATCH_FRAME ready to enter.
3605 StgCatchFrame *cf = (StgCatchFrame *)frame;
3609 // we've got an exception to raise, so let's pass it to the
3610 // handler in this frame.
3612 raise = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3613 TICK_ALLOC_SE_THK(1,0);
3614 SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
3615 raise->payload[0] = exception;
3617 // throw away the stack from Sp up to the CATCH_FRAME.
3621 /* Ensure that async excpetions are blocked now, so we don't get
3622 * a surprise exception before we get around to executing the
3625 if (tso->blocked_exceptions == NULL) {
3626 tso->blocked_exceptions = END_TSO_QUEUE;
3629 /* Put the newly-built THUNK on top of the stack, ready to execute
3630 * when the thread restarts.
3633 sp[-1] = (W_)&stg_enter_info;
3635 tso->what_next = ThreadRunGHC;
3636 IF_DEBUG(sanity, checkTSO(tso));
3645 // First build an AP_STACK consisting of the stack chunk above the
3646 // current update frame, with the top word on the stack as the
3649 words = frame - sp - 1;
3650 ap = (StgAP_STACK *)allocate(PAP_sizeW(words));
3653 ap->fun = (StgClosure *)sp[0];
3655 for(i=0; i < (nat)words; ++i) {
3656 ap->payload[i] = (StgClosure *)*sp++;
3659 SET_HDR(ap,&stg_AP_STACK_info,
3660 ((StgClosure *)frame)->header.prof.ccs /* ToDo */);
3661 TICK_ALLOC_UP_THK(words+1,0);
3664 fprintf(stderr, "scheduler: Updating ");
3665 printPtr((P_)((StgUpdateFrame *)frame)->updatee);
3666 fprintf(stderr, " with ");
3667 printObj((StgClosure *)ap);
3670 // Replace the updatee with an indirection - happily
3671 // this will also wake up any threads currently
3672 // waiting on the result.
3674 // Warning: if we're in a loop, more than one update frame on
3675 // the stack may point to the same object. Be careful not to
3676 // overwrite an IND_OLDGEN in this case, because we'll screw
3677 // up the mutable lists. To be on the safe side, don't
3678 // overwrite any kind of indirection at all. See also
3679 // threadSqueezeStack in GC.c, where we have to make a similar
3682 if (!closure_IND(((StgUpdateFrame *)frame)->updatee)) {
3683 // revert the black hole
3684 UPD_IND_NOLOCK(((StgUpdateFrame *)frame)->updatee,ap);
3686 sp += sizeofW(StgUpdateFrame) - 1;
3687 sp[0] = (W_)ap; // push onto stack
3692 // We've stripped the entire stack, the thread is now dead.
3693 sp += sizeofW(StgStopFrame);
3694 tso->what_next = ThreadKilled;
3705 /* -----------------------------------------------------------------------------
3706 resurrectThreads is called after garbage collection on the list of
3707 threads found to be garbage. Each of these threads will be woken
3708 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3709 on an MVar, or NonTermination if the thread was blocked on a Black
3712 Locks: sched_mutex isn't held upon entry nor exit.
3713 -------------------------------------------------------------------------- */
3716 resurrectThreads( StgTSO *threads )
3720 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3721 next = tso->global_link;
3722 tso->global_link = all_threads;
3724 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3726 switch (tso->why_blocked) {
3728 case BlockedOnException:
3729 /* Called by GC - sched_mutex lock is currently held. */
3730 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3732 case BlockedOnBlackHole:
3733 raiseAsync(tso,(StgClosure *)NonTermination_closure);
3736 /* This might happen if the thread was blocked on a black hole
3737 * belonging to a thread that we've just woken up (raiseAsync
3738 * can wake up threads, remember...).
3742 barf("resurrectThreads: thread blocked in a strange way");
3747 /* -----------------------------------------------------------------------------
3748 * Blackhole detection: if we reach a deadlock, test whether any
3749 * threads are blocked on themselves. Any threads which are found to
3750 * be self-blocked get sent a NonTermination exception.
3752 * This is only done in a deadlock situation in order to avoid
3753 * performance overhead in the normal case.
3755 * Locks: sched_mutex is held upon entry and exit.
3756 * -------------------------------------------------------------------------- */
3759 detectBlackHoles( void )
3761 StgTSO *tso = all_threads;
3763 StgClosure *blocked_on;
3764 StgRetInfoTable *info;
3766 for (tso = all_threads; tso != END_TSO_QUEUE; tso = tso->global_link) {
3768 while (tso->what_next == ThreadRelocated) {
3770 ASSERT(get_itbl(tso)->type == TSO);
3773 if (tso->why_blocked != BlockedOnBlackHole) {
3776 blocked_on = tso->block_info.closure;
3778 frame = (StgClosure *)tso->sp;
3781 info = get_ret_itbl(frame);
3782 switch (info->i.type) {
3784 if (((StgUpdateFrame *)frame)->updatee == blocked_on) {
3785 /* We are blocking on one of our own computations, so
3786 * send this thread the NonTermination exception.
3789 sched_belch("thread %d is blocked on itself", tso->id));
3790 raiseAsync(tso, (StgClosure *)NonTermination_closure);
3794 frame = (StgClosure *) ((StgUpdateFrame *)frame + 1);
3800 // normal stack frames; do nothing except advance the pointer
3802 (StgPtr)frame += stack_frame_sizeW(frame);
3809 //@node Debugging Routines, Index, Exception Handling Routines, Main scheduling code
3810 //@subsection Debugging Routines
3812 /* -----------------------------------------------------------------------------
3813 * Debugging: why is a thread blocked
3814 * [Also provides useful information when debugging threaded programs
3815 * at the Haskell source code level, so enable outside of DEBUG. --sof 7/02]
3816 -------------------------------------------------------------------------- */
3820 printThreadBlockage(StgTSO *tso)
3822 switch (tso->why_blocked) {
3824 fprintf(stderr,"is blocked on read from fd %d", tso->block_info.fd);
3826 case BlockedOnWrite:
3827 fprintf(stderr,"is blocked on write to fd %d", tso->block_info.fd);
3829 #if defined(mingw32_TARGET_OS)
3830 case BlockedOnDoProc:
3831 fprintf(stderr,"is blocked on proc (request: %d)", tso->block_info.async_result->reqID);
3834 case BlockedOnDelay:
3835 fprintf(stderr,"is blocked until %d", tso->block_info.target);
3838 fprintf(stderr,"is blocked on an MVar");
3840 case BlockedOnException:
3841 fprintf(stderr,"is blocked on delivering an exception to thread %d",
3842 tso->block_info.tso->id);
3844 case BlockedOnBlackHole:
3845 fprintf(stderr,"is blocked on a black hole");
3848 fprintf(stderr,"is not blocked");
3852 fprintf(stderr,"is blocked on global address; local FM_BQ is %p (%s)",
3853 tso->block_info.closure, info_type(tso->block_info.closure));
3855 case BlockedOnGA_NoSend:
3856 fprintf(stderr,"is blocked on global address (no send); local FM_BQ is %p (%s)",
3857 tso->block_info.closure, info_type(tso->block_info.closure));
3860 #if defined(RTS_SUPPORTS_THREADS)
3861 case BlockedOnCCall:
3862 fprintf(stderr,"is blocked on an external call");
3864 case BlockedOnCCall_NoUnblockExc:
3865 fprintf(stderr,"is blocked on an external call (exceptions were already blocked)");
3869 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3870 tso->why_blocked, tso->id, tso);
3876 printThreadStatus(StgTSO *tso)
3878 switch (tso->what_next) {
3880 fprintf(stderr,"has been killed");
3882 case ThreadComplete:
3883 fprintf(stderr,"has completed");
3886 printThreadBlockage(tso);
3891 printAllThreads(void)
3897 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3898 ullong_format_string(TIME_ON_PROC(CurrentProc),
3899 time_string, rtsFalse/*no commas!*/);
3901 fprintf(stderr, "all threads at [%s]:\n", time_string);
3903 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3904 ullong_format_string(CURRENT_TIME,
3905 time_string, rtsFalse/*no commas!*/);
3907 fprintf(stderr,"all threads at [%s]:\n", time_string);
3909 fprintf(stderr,"all threads:\n");
3912 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3913 fprintf(stderr, "\tthread %d @ %p ", t->id, (void *)t);
3914 label = lookupThreadLabel((StgWord)t);
3915 if (label) fprintf(stderr,"[\"%s\"] ",(char *)label);
3916 printThreadStatus(t);
3917 fprintf(stderr,"\n");
3924 Print a whole blocking queue attached to node (debugging only).
3929 print_bq (StgClosure *node)
3931 StgBlockingQueueElement *bqe;
3935 fprintf(stderr,"## BQ of closure %p (%s): ",
3936 node, info_type(node));
3938 /* should cover all closures that may have a blocking queue */
3939 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3940 get_itbl(node)->type == FETCH_ME_BQ ||
3941 get_itbl(node)->type == RBH ||
3942 get_itbl(node)->type == MVAR);
3944 ASSERT(node!=(StgClosure*)NULL); // sanity check
3946 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
3950 Print a whole blocking queue starting with the element bqe.
3953 print_bqe (StgBlockingQueueElement *bqe)
3958 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3960 for (end = (bqe==END_BQ_QUEUE);
3961 !end; // iterate until bqe points to a CONSTR
3962 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
3963 bqe = end ? END_BQ_QUEUE : bqe->link) {
3964 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3965 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3966 /* types of closures that may appear in a blocking queue */
3967 ASSERT(get_itbl(bqe)->type == TSO ||
3968 get_itbl(bqe)->type == BLOCKED_FETCH ||
3969 get_itbl(bqe)->type == CONSTR);
3970 /* only BQs of an RBH end with an RBH_Save closure */
3971 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3973 switch (get_itbl(bqe)->type) {
3975 fprintf(stderr," TSO %u (%x),",
3976 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
3979 fprintf(stderr," BF (node=%p, ga=((%x, %d, %x)),",
3980 ((StgBlockedFetch *)bqe)->node,
3981 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
3982 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
3983 ((StgBlockedFetch *)bqe)->ga.weight);
3986 fprintf(stderr," %s (IP %p),",
3987 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3988 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3989 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3990 "RBH_Save_?"), get_itbl(bqe));
3993 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
3994 info_type((StgClosure *)bqe)); // , node, info_type(node));
3998 fputc('\n', stderr);
4000 # elif defined(GRAN)
4002 print_bq (StgClosure *node)
4004 StgBlockingQueueElement *bqe;
4005 PEs node_loc, tso_loc;
4008 /* should cover all closures that may have a blocking queue */
4009 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
4010 get_itbl(node)->type == FETCH_ME_BQ ||
4011 get_itbl(node)->type == RBH);
4013 ASSERT(node!=(StgClosure*)NULL); // sanity check
4014 node_loc = where_is(node);
4016 fprintf(stderr,"## BQ of closure %p (%s) on [PE %d]: ",
4017 node, info_type(node), node_loc);
4020 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
4022 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
4023 !end; // iterate until bqe points to a CONSTR
4024 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
4025 ASSERT(bqe != END_BQ_QUEUE); // sanity check
4026 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
4027 /* types of closures that may appear in a blocking queue */
4028 ASSERT(get_itbl(bqe)->type == TSO ||
4029 get_itbl(bqe)->type == CONSTR);
4030 /* only BQs of an RBH end with an RBH_Save closure */
4031 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
4033 tso_loc = where_is((StgClosure *)bqe);
4034 switch (get_itbl(bqe)->type) {
4036 fprintf(stderr," TSO %d (%p) on [PE %d],",
4037 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
4040 fprintf(stderr," %s (IP %p),",
4041 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
4042 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
4043 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
4044 "RBH_Save_?"), get_itbl(bqe));
4047 barf("Unexpected closure type %s in blocking queue of %p (%s)",
4048 info_type((StgClosure *)bqe), node, info_type(node));
4052 fputc('\n', stderr);
4056 Nice and easy: only TSOs on the blocking queue
4059 print_bq (StgClosure *node)
4063 ASSERT(node!=(StgClosure*)NULL); // sanity check
4064 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
4065 tso != END_TSO_QUEUE;
4067 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
4068 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
4069 fprintf(stderr," TSO %d (%p),", tso->id, tso);
4071 fputc('\n', stderr);
4082 for (i=0, tso=run_queue_hd;
4083 tso != END_TSO_QUEUE;
4092 sched_belch(char *s, ...)
4097 fprintf(stderr, "scheduler (task %ld): ", osThreadId());
4099 fprintf(stderr, "== ");
4101 fprintf(stderr, "scheduler: ");
4103 vfprintf(stderr, s, ap);
4104 fprintf(stderr, "\n");
4111 //@node Index, , Debugging Routines, Main scheduling code
4115 //* StgMainThread:: @cindex\s-+StgMainThread
4116 //* awaken_blocked_queue:: @cindex\s-+awaken_blocked_queue
4117 //* blocked_queue_hd:: @cindex\s-+blocked_queue_hd
4118 //* blocked_queue_tl:: @cindex\s-+blocked_queue_tl
4119 //* context_switch:: @cindex\s-+context_switch
4120 //* createThread:: @cindex\s-+createThread
4121 //* gc_pending_cond:: @cindex\s-+gc_pending_cond
4122 //* initScheduler:: @cindex\s-+initScheduler
4123 //* interrupted:: @cindex\s-+interrupted
4124 //* next_thread_id:: @cindex\s-+next_thread_id
4125 //* print_bq:: @cindex\s-+print_bq
4126 //* run_queue_hd:: @cindex\s-+run_queue_hd
4127 //* run_queue_tl:: @cindex\s-+run_queue_tl
4128 //* sched_mutex:: @cindex\s-+sched_mutex
4129 //* schedule:: @cindex\s-+schedule
4130 //* take_off_run_queue:: @cindex\s-+take_off_run_queue
4131 //* term_mutex:: @cindex\s-+term_mutex