1 /* ---------------------------------------------------------------------------
2 * $Id: Schedule.c,v 1.52 2000/03/14 09:55:05 simonmar Exp $
4 * (c) The GHC Team, 1998-2000
8 * The main scheduling code in GranSim is quite different from that in std
9 * (concurrent) Haskell: while concurrent Haskell just iterates over the
10 * threads in the runnable queue, GranSim is event driven, i.e. it iterates
11 * over the events in the global event queue. -- HWL
12 * --------------------------------------------------------------------------*/
14 //@node Main scheduling code, , ,
15 //@section Main scheduling code
17 /* Version with scheduler monitor support for SMPs.
19 This design provides a high-level API to create and schedule threads etc.
20 as documented in the SMP design document.
22 It uses a monitor design controlled by a single mutex to exercise control
23 over accesses to shared data structures, and builds on the Posix threads
26 The majority of state is shared. In order to keep essential per-task state,
27 there is a Capability structure, which contains all the information
28 needed to run a thread: its STG registers, a pointer to its TSO, a
29 nursery etc. During STG execution, a pointer to the capability is
30 kept in a register (BaseReg).
32 In a non-SMP build, there is one global capability, namely MainRegTable.
39 //* Variables and Data structures::
41 //* Main scheduling loop::
42 //* Suspend and Resume::
44 //* Garbage Collextion Routines::
45 //* Blocking Queue Routines::
46 //* Exception Handling Routines::
47 //* Debugging Routines::
51 //@node Includes, Variables and Data structures, Main scheduling code, Main scheduling code
52 //@subsection Includes
60 #include "StgStartup.h"
64 #include "StgMiscClosures.h"
66 #include "Evaluator.h"
67 #include "Exception.h"
71 #include "Profiling.h"
76 #if defined(GRAN) || defined(PAR)
77 # include "GranSimRts.h"
79 # include "ParallelRts.h"
80 # include "Parallel.h"
81 # include "ParallelDebug.h"
88 //@node Variables and Data structures, Prototypes, Includes, Main scheduling code
89 //@subsection Variables and Data structures
93 * These are the threads which clients have requested that we run.
95 * In an SMP build, we might have several concurrent clients all
96 * waiting for results, and each one will wait on a condition variable
97 * until the result is available.
99 * In non-SMP, clients are strictly nested: the first client calls
100 * into the RTS, which might call out again to C with a _ccall_GC, and
101 * eventually re-enter the RTS.
103 * Main threads information is kept in a linked list:
105 //@cindex StgMainThread
106 typedef struct StgMainThread_ {
108 SchedulerStatus stat;
111 pthread_cond_t wakeup;
113 struct StgMainThread_ *link;
116 /* Main thread queue.
117 * Locks required: sched_mutex.
119 static StgMainThread *main_threads;
122 * Locks required: sched_mutex.
127 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
128 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
131 In GranSim we have a runable and a blocked queue for each processor.
132 In order to minimise code changes new arrays run_queue_hds/tls
133 are created. run_queue_hd is then a short cut (macro) for
134 run_queue_hds[CurrentProc] (see GranSim.h).
137 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
138 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
139 StgTSO *ccalling_threadss[MAX_PROC];
143 //@cindex run_queue_hd
144 //@cindex run_queue_tl
145 //@cindex blocked_queue_hd
146 //@cindex blocked_queue_tl
147 StgTSO *run_queue_hd, *run_queue_tl;
148 StgTSO *blocked_queue_hd, *blocked_queue_tl;
150 /* Threads suspended in _ccall_GC.
151 * Locks required: sched_mutex.
153 static StgTSO *suspended_ccalling_threads;
155 static void GetRoots(void);
156 static StgTSO *threadStackOverflow(StgTSO *tso);
159 /* KH: The following two flags are shared memory locations. There is no need
160 to lock them, since they are only unset at the end of a scheduler
164 /* flag set by signal handler to precipitate a context switch */
165 //@cindex context_switch
168 /* if this flag is set as well, give up execution */
169 //@cindex interrupted
172 /* Next thread ID to allocate.
173 * Locks required: sched_mutex
175 //@cindex next_thread_id
176 StgThreadID next_thread_id = 1;
179 * Pointers to the state of the current thread.
180 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
181 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
184 /* The smallest stack size that makes any sense is:
185 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
186 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
187 * + 1 (the realworld token for an IO thread)
188 * + 1 (the closure to enter)
190 * A thread with this stack will bomb immediately with a stack
191 * overflow, which will increase its stack size.
194 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 2)
196 /* Free capability list.
197 * Locks required: sched_mutex.
200 //@cindex free_capabilities
201 //@cindex n_free_capabilities
202 Capability *free_capabilities; /* Available capabilities for running threads */
203 nat n_free_capabilities; /* total number of available capabilities */
205 //@cindex MainRegTable
206 Capability MainRegTable; /* for non-SMP, we have one global capability */
210 StgTSO *CurrentTSOs[MAX_PROC];
217 /* All our current task ids, saved in case we need to kill them later.
224 void addToBlockedQueue ( StgTSO *tso );
226 static void schedule ( void );
227 void interruptStgRts ( void );
228 static StgTSO * createThread_ ( nat size, rtsBool have_lock );
231 static void sched_belch(char *s, ...);
235 //@cindex sched_mutex
237 //@cindex thread_ready_cond
238 //@cindex gc_pending_cond
239 pthread_mutex_t sched_mutex = PTHREAD_MUTEX_INITIALIZER;
240 pthread_mutex_t term_mutex = PTHREAD_MUTEX_INITIALIZER;
241 pthread_cond_t thread_ready_cond = PTHREAD_COND_INITIALIZER;
242 pthread_cond_t gc_pending_cond = PTHREAD_COND_INITIALIZER;
249 rtsTime TimeOfLastYield;
253 * The thread state for the main thread.
254 // ToDo: check whether not needed any more
259 //@node Prototypes, Main scheduling loop, Variables and Data structures, Main scheduling code
260 //@subsection Prototypes
262 //@node Main scheduling loop, Suspend and Resume, Prototypes, Main scheduling code
263 //@subsection Main scheduling loop
265 /* ---------------------------------------------------------------------------
266 Main scheduling loop.
268 We use round-robin scheduling, each thread returning to the
269 scheduler loop when one of these conditions is detected:
272 * timer expires (thread yields)
277 Locking notes: we acquire the scheduler lock once at the beginning
278 of the scheduler loop, and release it when
280 * running a thread, or
281 * waiting for work, or
282 * waiting for a GC to complete.
284 ------------------------------------------------------------------------ */
291 StgThreadReturnCode ret;
299 rtsBool was_interrupted = rtsFalse;
301 ACQUIRE_LOCK(&sched_mutex);
304 # error ToDo: implement GranSim scheduler
306 while (!GlobalStopPending) { /* GlobalStopPending set in par_exit */
308 if (PendingFetches != END_BF_QUEUE) {
315 /* If we're interrupted (the user pressed ^C, or some other
316 * termination condition occurred), kill all the currently running
320 IF_DEBUG(scheduler, sched_belch("interrupted"));
321 for (t = run_queue_hd; t != END_TSO_QUEUE; t = t->link) {
324 for (t = blocked_queue_hd; t != END_TSO_QUEUE; t = t->link) {
327 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
328 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
329 interrupted = rtsFalse;
330 was_interrupted = rtsTrue;
333 /* Go through the list of main threads and wake up any
334 * clients whose computations have finished. ToDo: this
335 * should be done more efficiently without a linear scan
336 * of the main threads list, somehow...
340 StgMainThread *m, **prev;
341 prev = &main_threads;
342 for (m = main_threads; m != NULL; m = m->link) {
343 switch (m->tso->whatNext) {
346 *(m->ret) = (StgClosure *)m->tso->sp[0];
350 pthread_cond_broadcast(&m->wakeup);
354 if (was_interrupted) {
355 m->stat = Interrupted;
359 pthread_cond_broadcast(&m->wakeup);
367 /* If our main thread has finished or been killed, return.
370 StgMainThread *m = main_threads;
371 if (m->tso->whatNext == ThreadComplete
372 || m->tso->whatNext == ThreadKilled) {
373 main_threads = main_threads->link;
374 if (m->tso->whatNext == ThreadComplete) {
375 /* we finished successfully, fill in the return value */
376 if (m->ret) { *(m->ret) = (StgClosure *)m->tso->sp[0]; };
380 if (was_interrupted) {
381 m->stat = Interrupted;
391 /* Top up the run queue from our spark pool. We try to make the
392 * number of threads in the run queue equal to the number of
397 nat n = n_free_capabilities;
398 StgTSO *tso = run_queue_hd;
400 /* Count the run queue */
401 while (n > 0 && tso != END_TSO_QUEUE) {
410 break; /* no more sparks in the pool */
412 /* I'd prefer this to be done in activateSpark -- HWL */
413 /* tricky - it needs to hold the scheduler lock and
414 * not try to re-acquire it -- SDM */
416 tso = createThread_(RtsFlags.GcFlags.initialStkSize, rtsTrue);
417 pushClosure(tso,spark);
418 PUSH_ON_RUN_QUEUE(tso);
420 advisory_thread_count++;
424 sched_belch("turning spark of closure %p into a thread",
425 (StgClosure *)spark));
428 /* We need to wake up the other tasks if we just created some
431 if (n_free_capabilities - n > 1) {
432 pthread_cond_signal(&thread_ready_cond);
437 /* Check whether any waiting threads need to be woken up. If the
438 * run queue is empty, and there are no other tasks running, we
439 * can wait indefinitely for something to happen.
440 * ToDo: what if another client comes along & requests another
443 if (blocked_queue_hd != END_TSO_QUEUE) {
445 (run_queue_hd == END_TSO_QUEUE)
447 && (n_free_capabilities == RtsFlags.ParFlags.nNodes)
452 /* check for signals each time around the scheduler */
454 if (signals_pending()) {
455 start_signal_handlers();
459 /* Detect deadlock: when we have no threads to run, there are
460 * no threads waiting on I/O or sleeping, and all the other
461 * tasks are waiting for work, we must have a deadlock. Inform
462 * all the main threads.
465 if (blocked_queue_hd == END_TSO_QUEUE
466 && run_queue_hd == END_TSO_QUEUE
467 && (n_free_capabilities == RtsFlags.ParFlags.nNodes)
470 for (m = main_threads; m != NULL; m = m->link) {
473 pthread_cond_broadcast(&m->wakeup);
478 if (blocked_queue_hd == END_TSO_QUEUE
479 && run_queue_hd == END_TSO_QUEUE) {
480 StgMainThread *m = main_threads;
483 main_threads = m->link;
489 /* If there's a GC pending, don't do anything until it has
493 IF_DEBUG(scheduler,sched_belch("waiting for GC"));
494 pthread_cond_wait(&gc_pending_cond, &sched_mutex);
497 /* block until we've got a thread on the run queue and a free
500 while (run_queue_hd == END_TSO_QUEUE || free_capabilities == NULL) {
501 IF_DEBUG(scheduler, sched_belch("waiting for work"));
502 pthread_cond_wait(&thread_ready_cond, &sched_mutex);
503 IF_DEBUG(scheduler, sched_belch("work now available"));
508 # error ToDo: implement GranSim scheduler
510 /* ToDo: phps merge with spark activation above */
511 /* check whether we have local work and send requests if we have none */
512 if (run_queue_hd == END_TSO_QUEUE) { /* no runnable threads */
513 /* :-[ no local threads => look out for local sparks */
514 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
515 (pending_sparks_hd[REQUIRED_POOL] < pending_sparks_tl[REQUIRED_POOL] ||
516 pending_sparks_hd[ADVISORY_POOL] < pending_sparks_tl[ADVISORY_POOL])) {
518 * ToDo: add GC code check that we really have enough heap afterwards!!
520 * If we're here (no runnable threads) and we have pending
521 * sparks, we must have a space problem. Get enough space
522 * to turn one of those pending sparks into a
526 spark = findSpark(); /* get a spark */
527 if (spark != (rtsSpark) NULL) {
528 tso = activateSpark(spark); /* turn the spark into a thread */
529 IF_PAR_DEBUG(verbose,
530 belch("== [%x] schedule: Created TSO %p (%d); %d threads active",
531 mytid, tso, tso->id, advisory_thread_count));
533 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
534 belch("^^ failed to activate spark");
536 } /* otherwise fall through & pick-up new tso */
538 IF_PAR_DEBUG(verbose,
539 belch("^^ no local sparks (spark pool contains only NFs: %d)",
540 spark_queue_len(ADVISORY_POOL)));
544 /* =8-[ no local sparks => look for work on other PEs */
547 * We really have absolutely no work. Send out a fish
548 * (there may be some out there already), and wait for
549 * something to arrive. We clearly can't run any threads
550 * until a SCHEDULE or RESUME arrives, and so that's what
551 * we're hoping to see. (Of course, we still have to
552 * respond to other types of messages.)
555 outstandingFishes < RtsFlags.ParFlags.maxFishes ) { // &&
556 // (last_fish_arrived_at+FISH_DELAY < CURRENT_TIME)) {
557 /* fishing set in sendFish, processFish;
558 avoid flooding system with fishes via delay */
560 sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY,
568 } else if (PacketsWaiting()) { /* Look for incoming messages */
572 /* Now we are sure that we have some work available */
573 ASSERT(run_queue_hd != END_TSO_QUEUE);
574 /* Take a thread from the run queue, if we have work */
575 t = take_off_run_queue(END_TSO_QUEUE);
577 /* ToDo: write something to the log-file
578 if (RTSflags.ParFlags.granSimStats && !sameThread)
579 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
584 IF_DEBUG(scheduler, belch("--^^ %d sparks on [%#x] (hd=%x; tl=%x; lim=%x)",
585 spark_queue_len(ADVISORY_POOL), CURRENT_PROC,
586 pending_sparks_hd[ADVISORY_POOL],
587 pending_sparks_tl[ADVISORY_POOL],
588 pending_sparks_lim[ADVISORY_POOL]));
590 IF_DEBUG(scheduler, belch("--== %d threads on [%#x] (hd=%x; tl=%x)",
591 run_queue_len(), CURRENT_PROC,
592 run_queue_hd, run_queue_tl));
596 we are running a different TSO, so write a schedule event to log file
597 NB: If we use fair scheduling we also have to write a deschedule
598 event for LastTSO; with unfair scheduling we know that the
599 previous tso has blocked whenever we switch to another tso, so
600 we don't need it in GUM for now
602 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
603 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
607 #else /* !GRAN && !PAR */
609 /* grab a thread from the run queue
612 IF_DEBUG(sanity,checkTSO(t));
619 cap = free_capabilities;
620 free_capabilities = cap->link;
621 n_free_capabilities--;
626 cap->rCurrentTSO = t;
628 /* set the context_switch flag
630 if (run_queue_hd == END_TSO_QUEUE)
635 RELEASE_LOCK(&sched_mutex);
637 IF_DEBUG(scheduler,sched_belch("running thread %d", t->id));
639 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
640 /* Run the current thread
642 switch (cap->rCurrentTSO->whatNext) {
645 /* Thread already finished, return to scheduler. */
646 ret = ThreadFinished;
649 ret = StgRun((StgFunPtr) stg_enterStackTop, cap);
652 ret = StgRun((StgFunPtr) stg_returnToStackTop, cap);
654 case ThreadEnterHugs:
658 IF_DEBUG(scheduler,sched_belch("entering Hugs"));
659 c = (StgClosure *)(cap->rCurrentTSO->sp[0]);
660 cap->rCurrentTSO->sp += 1;
665 barf("Panic: entered a BCO but no bytecode interpreter in this build");
668 barf("schedule: invalid whatNext field");
670 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
672 /* Costs for the scheduler are assigned to CCS_SYSTEM */
677 ACQUIRE_LOCK(&sched_mutex);
680 IF_DEBUG(scheduler,fprintf(stderr,"scheduler (task %ld): ", pthread_self()););
682 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: "););
684 t = cap->rCurrentTSO;
688 /* make all the running tasks block on a condition variable,
689 * maybe set context_switch and wait till they all pile in,
690 * then have them wait on a GC condition variable.
692 IF_DEBUG(scheduler,belch("thread %ld stopped: HeapOverflow", t->id));
695 ready_to_gc = rtsTrue;
696 context_switch = 1; /* stop other threads ASAP */
697 PUSH_ON_RUN_QUEUE(t);
701 /* just adjust the stack for this thread, then pop it back
704 IF_DEBUG(scheduler,belch("thread %ld stopped, StackOverflow", t->id));
708 /* enlarge the stack */
709 StgTSO *new_t = threadStackOverflow(t);
711 /* This TSO has moved, so update any pointers to it from the
712 * main thread stack. It better not be on any other queues...
715 for (m = main_threads; m != NULL; m = m->link) {
721 PUSH_ON_RUN_QUEUE(new_t);
728 DumpGranEvent(GR_DESCHEDULE, t));
729 globalGranStats.tot_yields++;
732 DumpGranEvent(GR_DESCHEDULE, t));
734 /* put the thread back on the run queue. Then, if we're ready to
735 * GC, check whether this is the last task to stop. If so, wake
736 * up the GC thread. getThread will block during a GC until the
740 if (t->whatNext == ThreadEnterHugs) {
741 /* ToDo: or maybe a timer expired when we were in Hugs?
742 * or maybe someone hit ctrl-C
744 belch("thread %ld stopped to switch to Hugs", t->id);
746 belch("thread %ld stopped, yielding", t->id);
750 APPEND_TO_RUN_QUEUE(t);
755 # error ToDo: implement GranSim scheduler
758 DumpGranEvent(GR_DESCHEDULE, t));
761 /* don't need to do anything. Either the thread is blocked on
762 * I/O, in which case we'll have called addToBlockedQueue
763 * previously, or it's blocked on an MVar or Blackhole, in which
764 * case it'll be on the relevant queue already.
767 fprintf(stderr, "thread %d stopped, ", t->id);
768 printThreadBlockage(t);
769 fprintf(stderr, "\n"));
774 /* Need to check whether this was a main thread, and if so, signal
775 * the task that started it with the return value. If we have no
776 * more main threads, we probably need to stop all the tasks until
779 IF_DEBUG(scheduler,belch("thread %ld finished", t->id));
780 t->whatNext = ThreadComplete;
782 // ToDo: endThread(t, CurrentProc); // clean-up the thread
784 advisory_thread_count--;
785 if (RtsFlags.ParFlags.ParStats.Full)
786 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
791 barf("doneThread: invalid thread return code");
795 cap->link = free_capabilities;
796 free_capabilities = cap;
797 n_free_capabilities++;
801 if (ready_to_gc && n_free_capabilities == RtsFlags.ParFlags.nNodes)
806 /* everybody back, start the GC.
807 * Could do it in this thread, or signal a condition var
808 * to do it in another thread. Either way, we need to
809 * broadcast on gc_pending_cond afterward.
812 IF_DEBUG(scheduler,sched_belch("doing GC"));
814 GarbageCollect(GetRoots);
815 ready_to_gc = rtsFalse;
817 pthread_cond_broadcast(&gc_pending_cond);
822 IF_GRAN_DEBUG(unused,
823 print_eventq(EventHd));
825 event = get_next_event();
829 /* ToDo: wait for next message to arrive rather than busy wait */
834 t = take_off_run_queue(END_TSO_QUEUE);
837 } /* end of while(1) */
840 /* A hack for Hugs concurrency support. Needs sanitisation (?) */
841 void deleteAllThreads ( void )
844 IF_DEBUG(scheduler,sched_belch("deleteAllThreads()"));
845 for (t = run_queue_hd; t != END_TSO_QUEUE; t = t->link) {
848 for (t = blocked_queue_hd; t != END_TSO_QUEUE; t = t->link) {
851 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
852 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
855 /* startThread and insertThread are now in GranSim.c -- HWL */
857 //@node Suspend and Resume, Run queue code, Main scheduling loop, Main scheduling code
858 //@subsection Suspend and Resume
860 /* ---------------------------------------------------------------------------
861 * Suspending & resuming Haskell threads.
863 * When making a "safe" call to C (aka _ccall_GC), the task gives back
864 * its capability before calling the C function. This allows another
865 * task to pick up the capability and carry on running Haskell
866 * threads. It also means that if the C call blocks, it won't lock
869 * The Haskell thread making the C call is put to sleep for the
870 * duration of the call, on the susepended_ccalling_threads queue. We
871 * give out a token to the task, which it can use to resume the thread
872 * on return from the C function.
873 * ------------------------------------------------------------------------- */
876 suspendThread( Capability *cap )
880 ACQUIRE_LOCK(&sched_mutex);
883 sched_belch("thread %d did a _ccall_gc\n", cap->rCurrentTSO->id));
885 threadPaused(cap->rCurrentTSO);
886 cap->rCurrentTSO->link = suspended_ccalling_threads;
887 suspended_ccalling_threads = cap->rCurrentTSO;
889 /* Use the thread ID as the token; it should be unique */
890 tok = cap->rCurrentTSO->id;
893 cap->link = free_capabilities;
894 free_capabilities = cap;
895 n_free_capabilities++;
898 RELEASE_LOCK(&sched_mutex);
903 resumeThread( StgInt tok )
908 ACQUIRE_LOCK(&sched_mutex);
910 prev = &suspended_ccalling_threads;
911 for (tso = suspended_ccalling_threads;
912 tso != END_TSO_QUEUE;
913 prev = &tso->link, tso = tso->link) {
914 if (tso->id == (StgThreadID)tok) {
919 if (tso == END_TSO_QUEUE) {
920 barf("resumeThread: thread not found");
924 while (free_capabilities == NULL) {
925 IF_DEBUG(scheduler, sched_belch("waiting to resume"));
926 pthread_cond_wait(&thread_ready_cond, &sched_mutex);
927 IF_DEBUG(scheduler, sched_belch("resuming thread %d", tso->id));
929 cap = free_capabilities;
930 free_capabilities = cap->link;
931 n_free_capabilities--;
936 cap->rCurrentTSO = tso;
938 RELEASE_LOCK(&sched_mutex);
943 /* ---------------------------------------------------------------------------
945 * ------------------------------------------------------------------------ */
946 static void unblockThread(StgTSO *tso);
948 /* ---------------------------------------------------------------------------
949 * Comparing Thread ids.
951 * This is used from STG land in the implementation of the
952 * instances of Eq/Ord for ThreadIds.
953 * ------------------------------------------------------------------------ */
955 int cmp_thread(const StgTSO *tso1, const StgTSO *tso2)
957 StgThreadID id1 = tso1->id;
958 StgThreadID id2 = tso2->id;
960 if (id1 < id2) return (-1);
961 if (id1 > id2) return 1;
965 /* ---------------------------------------------------------------------------
968 The new thread starts with the given stack size. Before the
969 scheduler can run, however, this thread needs to have a closure
970 (and possibly some arguments) pushed on its stack. See
971 pushClosure() in Schedule.h.
973 createGenThread() and createIOThread() (in SchedAPI.h) are
974 convenient packaged versions of this function.
975 ------------------------------------------------------------------------ */
976 //@cindex createThread
978 /* currently pri (priority) is only used in a GRAN setup -- HWL */
980 createThread(nat stack_size, StgInt pri)
982 return createThread_(stack_size, rtsFalse, pri);
986 createThread_(nat size, rtsBool have_lock, StgInt pri)
990 createThread(nat stack_size)
992 return createThread_(stack_size, rtsFalse);
996 createThread_(nat size, rtsBool have_lock)
1002 /* First check whether we should create a thread at all */
1004 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1005 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1007 belch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1008 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1009 return END_TSO_QUEUE;
1015 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
1018 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
1020 /* catch ridiculously small stack sizes */
1021 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
1022 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
1025 tso = (StgTSO *)allocate(size);
1026 TICK_ALLOC_TSO(size-sizeofW(StgTSO),0);
1028 stack_size = size - TSO_STRUCT_SIZEW;
1030 // Hmm, this CCS_MAIN is not protected by a PROFILING cpp var;
1031 SET_HDR(tso, &TSO_info, CCS_MAIN);
1033 SET_GRAN_HDR(tso, ThisPE);
1035 tso->whatNext = ThreadEnterGHC;
1037 /* tso->id needs to be unique. For now we use a heavyweight mutex to
1038 protect the increment operation on next_thread_id.
1039 In future, we could use an atomic increment instead.
1042 if (!have_lock) { ACQUIRE_LOCK(&sched_mutex); }
1043 tso->id = next_thread_id++;
1044 if (!have_lock) { RELEASE_LOCK(&sched_mutex); }
1046 tso->why_blocked = NotBlocked;
1047 tso->blocked_exceptions = NULL;
1049 tso->splim = (P_)&(tso->stack) + RESERVED_STACK_WORDS;
1050 tso->stack_size = stack_size;
1051 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
1053 tso->sp = (P_)&(tso->stack) + stack_size;
1056 tso->prof.CCCS = CCS_MAIN;
1059 /* put a stop frame on the stack */
1060 tso->sp -= sizeofW(StgStopFrame);
1061 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_MAIN);
1062 tso->su = (StgUpdateFrame*)tso->sp;
1064 IF_DEBUG(scheduler,belch("---- Initialised TSO %ld (%p), stack size = %lx words",
1065 tso->id, tso, tso->stack_size));
1069 tso->link = END_TSO_QUEUE;
1070 /* uses more flexible routine in GranSim */
1071 insertThread(tso, CurrentProc);
1073 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
1079 tso->gran.pri = pri;
1080 tso->gran.magic = TSO_MAGIC; // debugging only
1081 tso->gran.sparkname = 0;
1082 tso->gran.startedat = CURRENT_TIME;
1083 tso->gran.exported = 0;
1084 tso->gran.basicblocks = 0;
1085 tso->gran.allocs = 0;
1086 tso->gran.exectime = 0;
1087 tso->gran.fetchtime = 0;
1088 tso->gran.fetchcount = 0;
1089 tso->gran.blocktime = 0;
1090 tso->gran.blockcount = 0;
1091 tso->gran.blockedat = 0;
1092 tso->gran.globalsparks = 0;
1093 tso->gran.localsparks = 0;
1094 if (RtsFlags.GranFlags.Light)
1095 tso->gran.clock = Now; /* local clock */
1097 tso->gran.clock = 0;
1099 IF_DEBUG(gran,printTSO(tso));
1101 tso->par.sparkname = 0;
1102 tso->par.startedat = CURRENT_TIME;
1103 tso->par.exported = 0;
1104 tso->par.basicblocks = 0;
1105 tso->par.allocs = 0;
1106 tso->par.exectime = 0;
1107 tso->par.fetchtime = 0;
1108 tso->par.fetchcount = 0;
1109 tso->par.blocktime = 0;
1110 tso->par.blockcount = 0;
1111 tso->par.blockedat = 0;
1112 tso->par.globalsparks = 0;
1113 tso->par.localsparks = 0;
1117 globalGranStats.tot_threads_created++;
1118 globalGranStats.threads_created_on_PE[CurrentProc]++;
1119 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
1120 globalGranStats.tot_sq_probes++;
1123 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
1124 tso->id, tso->stack_size));
1128 /* ---------------------------------------------------------------------------
1131 * scheduleThread puts a thread on the head of the runnable queue.
1132 * This will usually be done immediately after a thread is created.
1133 * The caller of scheduleThread must create the thread using e.g.
1134 * createThread and push an appropriate closure
1135 * on this thread's stack before the scheduler is invoked.
1136 * ------------------------------------------------------------------------ */
1139 scheduleThread(StgTSO *tso)
1141 ACQUIRE_LOCK(&sched_mutex);
1143 /* Put the new thread on the head of the runnable queue. The caller
1144 * better push an appropriate closure on this thread's stack
1145 * beforehand. In the SMP case, the thread may start running as
1146 * soon as we release the scheduler lock below.
1148 PUSH_ON_RUN_QUEUE(tso);
1151 IF_DEBUG(scheduler,printTSO(tso));
1152 RELEASE_LOCK(&sched_mutex);
1155 /* ---------------------------------------------------------------------------
1158 * Start up Posix threads to run each of the scheduler tasks.
1159 * I believe the task ids are not needed in the system as defined.
1161 * ------------------------------------------------------------------------ */
1165 taskStart( void *arg STG_UNUSED )
1172 /* ---------------------------------------------------------------------------
1175 * Initialise the scheduler. This resets all the queues - if the
1176 * queues contained any threads, they'll be garbage collected at the
1179 * This now calls startTasks(), so should only be called once! KH @ 25/10/99
1180 * ------------------------------------------------------------------------ */
1184 term_handler(int sig STG_UNUSED)
1187 ACQUIRE_LOCK(&term_mutex);
1189 RELEASE_LOCK(&term_mutex);
1194 //@cindex initScheduler
1201 for (i=0; i<=MAX_PROC; i++) {
1202 run_queue_hds[i] = END_TSO_QUEUE;
1203 run_queue_tls[i] = END_TSO_QUEUE;
1204 blocked_queue_hds[i] = END_TSO_QUEUE;
1205 blocked_queue_tls[i] = END_TSO_QUEUE;
1206 ccalling_threadss[i] = END_TSO_QUEUE;
1209 run_queue_hd = END_TSO_QUEUE;
1210 run_queue_tl = END_TSO_QUEUE;
1211 blocked_queue_hd = END_TSO_QUEUE;
1212 blocked_queue_tl = END_TSO_QUEUE;
1215 suspended_ccalling_threads = END_TSO_QUEUE;
1217 main_threads = NULL;
1222 enteredCAFs = END_CAF_LIST;
1224 /* Install the SIGHUP handler */
1227 struct sigaction action,oact;
1229 action.sa_handler = term_handler;
1230 sigemptyset(&action.sa_mask);
1231 action.sa_flags = 0;
1232 if (sigaction(SIGTERM, &action, &oact) != 0) {
1233 barf("can't install TERM handler");
1239 /* Allocate N Capabilities */
1242 Capability *cap, *prev;
1245 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1246 cap = stgMallocBytes(sizeof(Capability), "initScheduler:capabilities");
1250 free_capabilities = cap;
1251 n_free_capabilities = RtsFlags.ParFlags.nNodes;
1253 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Allocated %d capabilities\n",
1254 n_free_capabilities););
1257 #if defined(SMP) || defined(PAR)
1270 /* make some space for saving all the thread ids */
1271 task_ids = stgMallocBytes(RtsFlags.ParFlags.nNodes * sizeof(task_info),
1272 "initScheduler:task_ids");
1274 /* and create all the threads */
1275 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1276 r = pthread_create(&tid,NULL,taskStart,NULL);
1278 barf("startTasks: Can't create new Posix thread");
1280 task_ids[i].id = tid;
1281 task_ids[i].mut_time = 0.0;
1282 task_ids[i].mut_etime = 0.0;
1283 task_ids[i].gc_time = 0.0;
1284 task_ids[i].gc_etime = 0.0;
1285 task_ids[i].elapsedtimestart = elapsedtime();
1286 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Started task: %ld\n",tid););
1292 exitScheduler( void )
1297 /* Don't want to use pthread_cancel, since we'd have to install
1298 * these silly exception handlers (pthread_cleanup_{push,pop}) around
1302 /* Cancel all our tasks */
1303 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1304 pthread_cancel(task_ids[i].id);
1307 /* Wait for all the tasks to terminate */
1308 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1309 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: waiting for task %ld\n",
1311 pthread_join(task_ids[i].id, NULL);
1315 /* Send 'em all a SIGHUP. That should shut 'em up.
1317 await_death = RtsFlags.ParFlags.nNodes;
1318 for (i = 0; i < RtsFlags.ParFlags.nNodes; i++) {
1319 pthread_kill(task_ids[i].id,SIGTERM);
1321 while (await_death > 0) {
1327 /* -----------------------------------------------------------------------------
1328 Managing the per-task allocation areas.
1330 Each capability comes with an allocation area. These are
1331 fixed-length block lists into which allocation can be done.
1333 ToDo: no support for two-space collection at the moment???
1334 -------------------------------------------------------------------------- */
1336 /* -----------------------------------------------------------------------------
1337 * waitThread is the external interface for running a new computataion
1338 * and waiting for the result.
1340 * In the non-SMP case, we create a new main thread, push it on the
1341 * main-thread stack, and invoke the scheduler to run it. The
1342 * scheduler will return when the top main thread on the stack has
1343 * completed or died, and fill in the necessary fields of the
1344 * main_thread structure.
1346 * In the SMP case, we create a main thread as before, but we then
1347 * create a new condition variable and sleep on it. When our new
1348 * main thread has completed, we'll be woken up and the status/result
1349 * will be in the main_thread struct.
1350 * -------------------------------------------------------------------------- */
1353 waitThread(StgTSO *tso, /*out*/StgClosure **ret)
1356 SchedulerStatus stat;
1358 ACQUIRE_LOCK(&sched_mutex);
1360 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
1366 pthread_cond_init(&m->wakeup, NULL);
1369 m->link = main_threads;
1372 IF_DEBUG(scheduler, fprintf(stderr, "scheduler: new main thread (%d)\n",
1377 pthread_cond_wait(&m->wakeup, &sched_mutex);
1378 } while (m->stat == NoStatus);
1381 ASSERT(m->stat != NoStatus);
1387 pthread_cond_destroy(&m->wakeup);
1390 IF_DEBUG(scheduler, fprintf(stderr, "scheduler: main thread (%d) finished\n",
1394 RELEASE_LOCK(&sched_mutex);
1399 //@node Run queue code, Garbage Collextion Routines, Suspend and Resume, Main scheduling code
1400 //@subsection Run queue code
1404 NB: In GranSim we have many run queues; run_queue_hd is actually a macro
1405 unfolding to run_queue_hds[CurrentProc], thus CurrentProc is an
1406 implicit global variable that has to be correct when calling these
1410 /* Put the new thread on the head of the runnable queue.
1411 * The caller of createThread better push an appropriate closure
1412 * on this thread's stack before the scheduler is invoked.
1414 static /* inline */ void
1415 add_to_run_queue(tso)
1418 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
1419 tso->link = run_queue_hd;
1421 if (run_queue_tl == END_TSO_QUEUE) {
1426 /* Put the new thread at the end of the runnable queue. */
1427 static /* inline */ void
1428 push_on_run_queue(tso)
1431 ASSERT(get_itbl((StgClosure *)tso)->type == TSO);
1432 ASSERT(run_queue_hd!=NULL && run_queue_tl!=NULL);
1433 ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
1434 if (run_queue_hd == END_TSO_QUEUE) {
1437 run_queue_tl->link = tso;
1443 Should be inlined because it's used very often in schedule. The tso
1444 argument is actually only needed in GranSim, where we want to have the
1445 possibility to schedule *any* TSO on the run queue, irrespective of the
1446 actual ordering. Therefore, if tso is not the nil TSO then we traverse
1447 the run queue and dequeue the tso, adjusting the links in the queue.
1449 //@cindex take_off_run_queue
1450 static /* inline */ StgTSO*
1451 take_off_run_queue(StgTSO *tso) {
1455 qetlaHbogh Qu' ngaSbogh ghomDaQ {tso} yIteq!
1457 if tso is specified, unlink that tso from the run_queue (doesn't have
1458 to be at the beginning of the queue); GranSim only
1460 if (tso!=END_TSO_QUEUE) {
1461 /* find tso in queue */
1462 for (t=run_queue_hd, prev=END_TSO_QUEUE;
1463 t!=END_TSO_QUEUE && t!=tso;
1467 /* now actually dequeue the tso */
1468 if (prev!=END_TSO_QUEUE) {
1469 ASSERT(run_queue_hd!=t);
1470 prev->link = t->link;
1472 /* t is at beginning of thread queue */
1473 ASSERT(run_queue_hd==t);
1474 run_queue_hd = t->link;
1476 /* t is at end of thread queue */
1477 if (t->link==END_TSO_QUEUE) {
1478 ASSERT(t==run_queue_tl);
1479 run_queue_tl = prev;
1481 ASSERT(run_queue_tl!=t);
1483 t->link = END_TSO_QUEUE;
1485 /* take tso from the beginning of the queue; std concurrent code */
1487 if (t != END_TSO_QUEUE) {
1488 run_queue_hd = t->link;
1489 t->link = END_TSO_QUEUE;
1490 if (run_queue_hd == END_TSO_QUEUE) {
1491 run_queue_tl = END_TSO_QUEUE;
1500 //@node Garbage Collextion Routines, Blocking Queue Routines, Run queue code, Main scheduling code
1501 //@subsection Garbage Collextion Routines
1503 /* ---------------------------------------------------------------------------
1504 Where are the roots that we know about?
1506 - all the threads on the runnable queue
1507 - all the threads on the blocked queue
1508 - all the thread currently executing a _ccall_GC
1509 - all the "main threads"
1511 ------------------------------------------------------------------------ */
1513 /* This has to be protected either by the scheduler monitor, or by the
1514 garbage collection monitor (probably the latter).
1518 static void GetRoots(void)
1525 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
1526 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
1527 run_queue_hds[i] = (StgTSO *)MarkRoot((StgClosure *)run_queue_hds[i]);
1528 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
1529 run_queue_tls[i] = (StgTSO *)MarkRoot((StgClosure *)run_queue_tls[i]);
1531 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
1532 blocked_queue_hds[i] = (StgTSO *)MarkRoot((StgClosure *)blocked_queue_hds[i]);
1533 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
1534 blocked_queue_tls[i] = (StgTSO *)MarkRoot((StgClosure *)blocked_queue_tls[i]);
1535 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
1536 ccalling_threadss[i] = (StgTSO *)MarkRoot((StgClosure *)ccalling_threadss[i]);
1543 run_queue_hd = (StgTSO *)MarkRoot((StgClosure *)run_queue_hd);
1544 run_queue_tl = (StgTSO *)MarkRoot((StgClosure *)run_queue_tl);
1546 blocked_queue_hd = (StgTSO *)MarkRoot((StgClosure *)blocked_queue_hd);
1547 blocked_queue_tl = (StgTSO *)MarkRoot((StgClosure *)blocked_queue_tl);
1550 for (m = main_threads; m != NULL; m = m->link) {
1551 m->tso = (StgTSO *)MarkRoot((StgClosure *)m->tso);
1553 suspended_ccalling_threads =
1554 (StgTSO *)MarkRoot((StgClosure *)suspended_ccalling_threads);
1556 #if defined(SMP) || defined(PAR) || defined(GRAN)
1561 /* -----------------------------------------------------------------------------
1564 This is the interface to the garbage collector from Haskell land.
1565 We provide this so that external C code can allocate and garbage
1566 collect when called from Haskell via _ccall_GC.
1568 It might be useful to provide an interface whereby the programmer
1569 can specify more roots (ToDo).
1571 This needs to be protected by the GC condition variable above. KH.
1572 -------------------------------------------------------------------------- */
1574 void (*extra_roots)(void);
1579 GarbageCollect(GetRoots);
1585 GetRoots(); /* the scheduler's roots */
1586 extra_roots(); /* the user's roots */
1590 performGCWithRoots(void (*get_roots)(void))
1592 extra_roots = get_roots;
1594 GarbageCollect(AllRoots);
1597 /* -----------------------------------------------------------------------------
1600 If the thread has reached its maximum stack size, then raise the
1601 StackOverflow exception in the offending thread. Otherwise
1602 relocate the TSO into a larger chunk of memory and adjust its stack
1604 -------------------------------------------------------------------------- */
1607 threadStackOverflow(StgTSO *tso)
1609 nat new_stack_size, new_tso_size, diff, stack_words;
1613 IF_DEBUG(sanity,checkTSO(tso));
1614 if (tso->stack_size >= tso->max_stack_size) {
1616 /* If we're debugging, just print out the top of the stack */
1617 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
1621 fprintf(stderr, "fatal: stack overflow in Hugs; aborting\n" );
1624 /* Send this thread the StackOverflow exception */
1625 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
1630 /* Try to double the current stack size. If that takes us over the
1631 * maximum stack size for this thread, then use the maximum instead.
1632 * Finally round up so the TSO ends up as a whole number of blocks.
1634 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
1635 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
1636 TSO_STRUCT_SIZE)/sizeof(W_);
1637 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
1638 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
1640 IF_DEBUG(scheduler, fprintf(stderr,"scheduler: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
1642 dest = (StgTSO *)allocate(new_tso_size);
1643 TICK_ALLOC_TSO(new_tso_size-sizeofW(StgTSO),0);
1645 /* copy the TSO block and the old stack into the new area */
1646 memcpy(dest,tso,TSO_STRUCT_SIZE);
1647 stack_words = tso->stack + tso->stack_size - tso->sp;
1648 new_sp = (P_)dest + new_tso_size - stack_words;
1649 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
1651 /* relocate the stack pointers... */
1652 diff = (P_)new_sp - (P_)tso->sp; /* In *words* */
1653 dest->su = (StgUpdateFrame *) ((P_)dest->su + diff);
1655 dest->splim = (P_)dest->splim + (nat)((P_)dest - (P_)tso);
1656 dest->stack_size = new_stack_size;
1658 /* and relocate the update frame list */
1659 relocate_TSO(tso, dest);
1661 /* Mark the old TSO as relocated. We have to check for relocated
1662 * TSOs in the garbage collector and any primops that deal with TSOs.
1664 * It's important to set the sp and su values to just beyond the end
1665 * of the stack, so we don't attempt to scavenge any part of the
1668 tso->whatNext = ThreadRelocated;
1670 tso->sp = (P_)&(tso->stack[tso->stack_size]);
1671 tso->su = (StgUpdateFrame *)tso->sp;
1672 tso->why_blocked = NotBlocked;
1673 dest->mut_link = NULL;
1675 IF_DEBUG(sanity,checkTSO(tso));
1677 IF_DEBUG(scheduler,printTSO(dest));
1683 //@node Blocking Queue Routines, Exception Handling Routines, Garbage Collextion Routines, Main scheduling code
1684 //@subsection Blocking Queue Routines
1686 /* ---------------------------------------------------------------------------
1687 Wake up a queue that was blocked on some resource.
1688 ------------------------------------------------------------------------ */
1690 /* ToDo: check push_on_run_queue vs. PUSH_ON_RUN_QUEUE */
1694 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
1699 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
1701 /* write RESUME events to log file and
1702 update blocked and fetch time (depending on type of the orig closure) */
1703 if (RtsFlags.ParFlags.ParStats.Full) {
1704 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1705 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
1706 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
1708 switch (get_itbl(node)->type) {
1710 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
1715 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
1718 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
1725 static StgBlockingQueueElement *
1726 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
1728 StgBlockingQueueElement *next;
1729 PEs node_loc, tso_loc;
1731 node_loc = where_is(node); // should be lifted out of loop
1732 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
1733 tso_loc = where_is(tso);
1734 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
1735 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
1736 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
1737 bq_processing_time += RtsFlags.GranFlags.Costs.lunblocktime;
1738 // insertThread(tso, node_loc);
1739 new_event(tso_loc, tso_loc,
1740 CurrentTime[CurrentProc]+bq_processing_time,
1742 tso, node, (rtsSpark*)NULL);
1743 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
1746 } else { // TSO is remote (actually should be FMBQ)
1747 bq_processing_time += RtsFlags.GranFlags.Costs.mpacktime;
1748 bq_processing_time += RtsFlags.GranFlags.Costs.gunblocktime;
1749 new_event(tso_loc, CurrentProc,
1750 CurrentTime[CurrentProc]+bq_processing_time+
1751 RtsFlags.GranFlags.Costs.latency,
1753 tso, node, (rtsSpark*)NULL);
1754 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
1755 bq_processing_time += RtsFlags.GranFlags.Costs.mtidytime;
1758 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
1760 fprintf(stderr," %s TSO %d (%p) [PE %d] (blocked_on=%p) (next=%p) ,",
1761 (node_loc==tso_loc ? "Local" : "Global"),
1762 tso->id, tso, CurrentProc, tso->blocked_on, tso->link))
1763 tso->blocked_on = NULL;
1764 IF_DEBUG(scheduler,belch("-- Waking up thread %ld (%p)",
1768 /* if this is the BQ of an RBH, we have to put back the info ripped out of
1769 the closure to make room for the anchor of the BQ */
1770 if (next!=END_BQ_QUEUE) {
1771 ASSERT(get_itbl(node)->type == RBH && get_itbl(next)->type == CONSTR);
1773 ASSERT((info_ptr==&RBH_Save_0_info) ||
1774 (info_ptr==&RBH_Save_1_info) ||
1775 (info_ptr==&RBH_Save_2_info));
1777 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
1778 ((StgRBH *)node)->blocking_queue = ((StgRBHSave *)next)->payload[0];
1779 ((StgRBH *)node)->mut_link = ((StgRBHSave *)next)->payload[1];
1782 belch("## Filled in RBH_Save for %p (%s) at end of AwBQ",
1783 node, info_type(node)));
1787 static StgBlockingQueueElement *
1788 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
1790 StgBlockingQueueElement *next;
1792 switch (get_itbl(bqe)->type) {
1794 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
1795 /* if it's a TSO just push it onto the run_queue */
1797 // ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
1798 PUSH_ON_RUN_QUEUE((StgTSO *)bqe);
1800 unblockCount(bqe, node);
1801 /* reset blocking status after dumping event */
1802 ((StgTSO *)bqe)->why_blocked = NotBlocked;
1806 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
1808 bqe->link = PendingFetches;
1809 PendingFetches = bqe;
1813 /* can ignore this case in a non-debugging setup;
1814 see comments on RBHSave closures above */
1816 /* check that the closure is an RBHSave closure */
1817 ASSERT(get_itbl((StgClosure *)bqe) == &RBH_Save_0_info ||
1818 get_itbl((StgClosure *)bqe) == &RBH_Save_1_info ||
1819 get_itbl((StgClosure *)bqe) == &RBH_Save_2_info);
1823 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
1824 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
1828 // IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
1832 #else /* !GRAN && !PAR */
1834 unblockOneLocked(StgTSO *tso)
1838 ASSERT(get_itbl(tso)->type == TSO);
1839 ASSERT(tso->why_blocked != NotBlocked);
1840 tso->why_blocked = NotBlocked;
1842 PUSH_ON_RUN_QUEUE(tso);
1844 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
1849 #if defined(PAR) || defined(GRAN)
1851 unblockOne(StgTSO *tso, StgClosure *node)
1853 ACQUIRE_LOCK(&sched_mutex);
1854 tso = unblockOneLocked(tso, node);
1855 RELEASE_LOCK(&sched_mutex);
1860 unblockOne(StgTSO *tso)
1862 ACQUIRE_LOCK(&sched_mutex);
1863 tso = unblockOneLocked(tso);
1864 RELEASE_LOCK(&sched_mutex);
1871 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
1873 StgBlockingQueueElement *bqe, *next;
1875 PEs node_loc, tso_loc;
1876 rtsTime bq_processing_time = 0;
1877 nat len = 0, len_local = 0;
1880 belch("## AwBQ for node %p on PE %d @ %ld by TSO %d (%p): ", \
1881 node, CurrentProc, CurrentTime[CurrentProc],
1882 CurrentTSO->id, CurrentTSO));
1884 node_loc = where_is(node);
1886 ASSERT(get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
1887 get_itbl(q)->type == CONSTR); // closure (type constructor)
1888 ASSERT(is_unique(node));
1890 /* FAKE FETCH: magically copy the node to the tso's proc;
1891 no Fetch necessary because in reality the node should not have been
1892 moved to the other PE in the first place
1894 if (CurrentProc!=node_loc) {
1896 belch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)",
1897 node, node_loc, CurrentProc, CurrentTSO->id,
1898 // CurrentTSO, where_is(CurrentTSO),
1899 node->header.gran.procs));
1900 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
1902 belch("## new bitmask of node %p is %#x",
1903 node, node->header.gran.procs));
1904 if (RtsFlags.GranFlags.GranSimStats.Global) {
1905 globalGranStats.tot_fake_fetches++;
1910 // ToDo: check: ASSERT(CurrentProc==node_loc);
1911 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
1914 bqe points to the current element in the queue
1915 next points to the next element in the queue
1917 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
1918 //tso_loc = where_is(tso);
1919 bqe = unblockOneLocked(bqe, node);
1922 /* statistics gathering */
1923 /* ToDo: fix counters
1924 if (RtsFlags.GranFlags.GranSimStats.Global) {
1925 globalGranStats.tot_bq_processing_time += bq_processing_time;
1926 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
1927 globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
1928 globalGranStats.tot_awbq++; // total no. of bqs awakened
1931 fprintf(stderr,"## BQ Stats of %p: [%d entries, %d local] %s\n",
1932 node, len, len_local, (next!=END_TSO_QUEUE) ? "RBH" : ""));
1937 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
1939 StgBlockingQueueElement *bqe, *next;
1941 ACQUIRE_LOCK(&sched_mutex);
1943 IF_PAR_DEBUG(verbose,
1944 belch("## AwBQ for node %p on [%x]: ",
1947 ASSERT(get_itbl(q)->type == TSO ||
1948 get_itbl(q)->type == BLOCKED_FETCH ||
1949 get_itbl(q)->type == CONSTR);
1952 while (get_itbl(bqe)->type==TSO ||
1953 get_itbl(bqe)->type==BLOCKED_FETCH) {
1954 bqe = unblockOneLocked(bqe, node);
1956 RELEASE_LOCK(&sched_mutex);
1959 #else /* !GRAN && !PAR */
1961 awakenBlockedQueue(StgTSO *tso)
1963 ACQUIRE_LOCK(&sched_mutex);
1964 while (tso != END_TSO_QUEUE) {
1965 tso = unblockOneLocked(tso);
1967 RELEASE_LOCK(&sched_mutex);
1971 //@node Exception Handling Routines, Debugging Routines, Blocking Queue Routines, Main scheduling code
1972 //@subsection Exception Handling Routines
1974 /* ---------------------------------------------------------------------------
1976 - usually called inside a signal handler so it mustn't do anything fancy.
1977 ------------------------------------------------------------------------ */
1980 interruptStgRts(void)
1986 /* -----------------------------------------------------------------------------
1989 This is for use when we raise an exception in another thread, which
1991 This has nothing to do with the UnblockThread event in GranSim. -- HWL
1992 -------------------------------------------------------------------------- */
1995 unblockThread(StgTSO *tso)
1999 ACQUIRE_LOCK(&sched_mutex);
2000 switch (tso->why_blocked) {
2003 return; /* not blocked */
2006 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2008 StgTSO *last_tso = END_TSO_QUEUE;
2009 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2012 for (t = mvar->head; t != END_TSO_QUEUE;
2013 last = &t->link, last_tso = t, t = t->link) {
2016 if (mvar->tail == tso) {
2017 mvar->tail = last_tso;
2022 barf("unblockThread (MVAR): TSO not found");
2025 case BlockedOnBlackHole:
2026 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2028 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2030 last = &bq->blocking_queue;
2031 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
2032 last = &t->link, t = t->link) {
2038 barf("unblockThread (BLACKHOLE): TSO not found");
2041 case BlockedOnException:
2043 StgTSO *target = tso->block_info.tso;
2045 ASSERT(get_itbl(target)->type == TSO);
2046 ASSERT(target->blocked_exceptions != NULL);
2048 last = &target->blocked_exceptions;
2049 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
2050 last = &t->link, t = t->link) {
2051 ASSERT(get_itbl(t)->type == TSO);
2057 barf("unblockThread (Exception): TSO not found");
2060 case BlockedOnDelay:
2062 case BlockedOnWrite:
2064 StgTSO *prev = NULL;
2065 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
2066 prev = t, t = t->link) {
2069 blocked_queue_hd = t->link;
2070 if (blocked_queue_tl == t) {
2071 blocked_queue_tl = END_TSO_QUEUE;
2074 prev->link = t->link;
2075 if (blocked_queue_tl == t) {
2076 blocked_queue_tl = prev;
2082 barf("unblockThread (I/O): TSO not found");
2086 barf("unblockThread");
2090 tso->link = END_TSO_QUEUE;
2091 tso->why_blocked = NotBlocked;
2092 tso->block_info.closure = NULL;
2093 PUSH_ON_RUN_QUEUE(tso);
2094 RELEASE_LOCK(&sched_mutex);
2097 /* -----------------------------------------------------------------------------
2100 * The following function implements the magic for raising an
2101 * asynchronous exception in an existing thread.
2103 * We first remove the thread from any queue on which it might be
2104 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
2106 * We strip the stack down to the innermost CATCH_FRAME, building
2107 * thunks in the heap for all the active computations, so they can
2108 * be restarted if necessary. When we reach a CATCH_FRAME, we build
2109 * an application of the handler to the exception, and push it on
2110 * the top of the stack.
2112 * How exactly do we save all the active computations? We create an
2113 * AP_UPD for every UpdateFrame on the stack. Entering one of these
2114 * AP_UPDs pushes everything from the corresponding update frame
2115 * upwards onto the stack. (Actually, it pushes everything up to the
2116 * next update frame plus a pointer to the next AP_UPD object.
2117 * Entering the next AP_UPD object pushes more onto the stack until we
2118 * reach the last AP_UPD object - at which point the stack should look
2119 * exactly as it did when we killed the TSO and we can continue
2120 * execution by entering the closure on top of the stack.
2122 * We can also kill a thread entirely - this happens if either (a) the
2123 * exception passed to raiseAsync is NULL, or (b) there's no
2124 * CATCH_FRAME on the stack. In either case, we strip the entire
2125 * stack and replace the thread with a zombie.
2127 * -------------------------------------------------------------------------- */
2130 deleteThread(StgTSO *tso)
2132 raiseAsync(tso,NULL);
2136 raiseAsync(StgTSO *tso, StgClosure *exception)
2138 StgUpdateFrame* su = tso->su;
2139 StgPtr sp = tso->sp;
2141 /* Thread already dead? */
2142 if (tso->whatNext == ThreadComplete || tso->whatNext == ThreadKilled) {
2146 IF_DEBUG(scheduler, sched_belch("raising exception in thread %ld.", tso->id));
2148 /* Remove it from any blocking queues */
2151 /* The stack freezing code assumes there's a closure pointer on
2152 * the top of the stack. This isn't always the case with compiled
2153 * code, so we have to push a dummy closure on the top which just
2154 * returns to the next return address on the stack.
2156 if ( LOOKS_LIKE_GHC_INFO((void*)*sp) ) {
2157 *(--sp) = (W_)&dummy_ret_closure;
2161 int words = ((P_)su - (P_)sp) - 1;
2165 /* If we find a CATCH_FRAME, and we've got an exception to raise,
2166 * then build PAP(handler,exception,realworld#), and leave it on
2167 * top of the stack ready to enter.
2169 if (get_itbl(su)->type == CATCH_FRAME && exception != NULL) {
2170 StgCatchFrame *cf = (StgCatchFrame *)su;
2171 /* we've got an exception to raise, so let's pass it to the
2172 * handler in this frame.
2174 ap = (StgAP_UPD *)allocate(sizeofW(StgPAP) + 2);
2175 TICK_ALLOC_UPD_PAP(3,0);
2176 SET_HDR(ap,&PAP_info,cf->header.prof.ccs);
2179 ap->fun = cf->handler; /* :: Exception -> IO a */
2180 ap->payload[0] = (P_)exception;
2181 ap->payload[1] = ARG_TAG(0); /* realworld token */
2183 /* throw away the stack from Sp up to and including the
2186 sp = (P_)su + sizeofW(StgCatchFrame) - 1;
2189 /* Restore the blocked/unblocked state for asynchronous exceptions
2190 * at the CATCH_FRAME.
2192 * If exceptions were unblocked at the catch, arrange that they
2193 * are unblocked again after executing the handler by pushing an
2194 * unblockAsyncExceptions_ret stack frame.
2196 if (!cf->exceptions_blocked) {
2197 *(sp--) = (W_)&unblockAsyncExceptionszh_ret_info;
2200 /* Ensure that async exceptions are blocked when running the handler.
2202 if (tso->blocked_exceptions == NULL) {
2203 tso->blocked_exceptions = END_TSO_QUEUE;
2206 /* Put the newly-built PAP on top of the stack, ready to execute
2207 * when the thread restarts.
2211 tso->whatNext = ThreadEnterGHC;
2215 /* First build an AP_UPD consisting of the stack chunk above the
2216 * current update frame, with the top word on the stack as the
2219 ap = (StgAP_UPD *)allocate(AP_sizeW(words));
2224 ap->fun = (StgClosure *)sp[0];
2226 for(i=0; i < (nat)words; ++i) {
2227 ap->payload[i] = (P_)*sp++;
2230 switch (get_itbl(su)->type) {
2234 SET_HDR(ap,&AP_UPD_info,su->header.prof.ccs /* ToDo */);
2235 TICK_ALLOC_UP_THK(words+1,0);
2238 fprintf(stderr, "scheduler: Updating ");
2239 printPtr((P_)su->updatee);
2240 fprintf(stderr, " with ");
2241 printObj((StgClosure *)ap);
2244 /* Replace the updatee with an indirection - happily
2245 * this will also wake up any threads currently
2246 * waiting on the result.
2248 UPD_IND_NOLOCK(su->updatee,ap); /* revert the black hole */
2250 sp += sizeofW(StgUpdateFrame) -1;
2251 sp[0] = (W_)ap; /* push onto stack */
2257 StgCatchFrame *cf = (StgCatchFrame *)su;
2260 /* We want a PAP, not an AP_UPD. Fortunately, the
2261 * layout's the same.
2263 SET_HDR(ap,&PAP_info,su->header.prof.ccs /* ToDo */);
2264 TICK_ALLOC_UPD_PAP(words+1,0);
2266 /* now build o = FUN(catch,ap,handler) */
2267 o = (StgClosure *)allocate(sizeofW(StgClosure)+2);
2268 TICK_ALLOC_FUN(2,0);
2269 SET_HDR(o,&catch_info,su->header.prof.ccs /* ToDo */);
2270 o->payload[0] = (StgClosure *)ap;
2271 o->payload[1] = cf->handler;
2274 fprintf(stderr, "scheduler: Built ");
2275 printObj((StgClosure *)o);
2278 /* pop the old handler and put o on the stack */
2280 sp += sizeofW(StgCatchFrame) - 1;
2287 StgSeqFrame *sf = (StgSeqFrame *)su;
2290 SET_HDR(ap,&PAP_info,su->header.prof.ccs /* ToDo */);
2291 TICK_ALLOC_UPD_PAP(words+1,0);
2293 /* now build o = FUN(seq,ap) */
2294 o = (StgClosure *)allocate(sizeofW(StgClosure)+1);
2295 TICK_ALLOC_SE_THK(1,0);
2296 SET_HDR(o,&seq_info,su->header.prof.ccs /* ToDo */);
2297 payloadCPtr(o,0) = (StgClosure *)ap;
2300 fprintf(stderr, "scheduler: Built ");
2301 printObj((StgClosure *)o);
2304 /* pop the old handler and put o on the stack */
2306 sp += sizeofW(StgSeqFrame) - 1;
2312 /* We've stripped the entire stack, the thread is now dead. */
2313 sp += sizeofW(StgStopFrame) - 1;
2314 sp[0] = (W_)exception; /* save the exception */
2315 tso->whatNext = ThreadKilled;
2316 tso->su = (StgUpdateFrame *)(sp+1);
2327 //@node Debugging Routines, Index, Exception Handling Routines, Main scheduling code
2328 //@subsection Debugging Routines
2330 /* -----------------------------------------------------------------------------
2331 Debugging: why is a thread blocked
2332 -------------------------------------------------------------------------- */
2336 void printThreadBlockage(StgTSO *tso)
2338 switch (tso->why_blocked) {
2340 fprintf(stderr,"blocked on read from fd %d", tso->block_info.fd);
2342 case BlockedOnWrite:
2343 fprintf(stderr,"blocked on write to fd %d", tso->block_info.fd);
2345 case BlockedOnDelay:
2346 fprintf(stderr,"blocked on delay of %d ms", tso->block_info.delay);
2349 fprintf(stderr,"blocked on an MVar");
2351 case BlockedOnException:
2352 fprintf(stderr,"blocked on delivering an exception to thread %d",
2353 tso->block_info.tso->id);
2355 case BlockedOnBlackHole:
2356 fprintf(stderr,"blocked on a black hole");
2359 fprintf(stderr,"not blocked");
2363 fprintf(stderr,"blocked on global address");
2370 Print a whole blocking queue attached to node (debugging only).
2375 print_bq (StgClosure *node)
2377 StgBlockingQueueElement *bqe;
2381 fprintf(stderr,"## BQ of closure %p (%s): ",
2382 node, info_type(node));
2384 /* should cover all closures that may have a blocking queue */
2385 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
2386 get_itbl(node)->type == FETCH_ME_BQ ||
2387 get_itbl(node)->type == RBH);
2389 ASSERT(node!=(StgClosure*)NULL); // sanity check
2391 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
2393 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
2394 !end; // iterate until bqe points to a CONSTR
2395 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
2396 ASSERT(bqe != END_BQ_QUEUE); // sanity check
2397 ASSERT(bqe != (StgTSO*)NULL); // sanity check
2398 /* types of closures that may appear in a blocking queue */
2399 ASSERT(get_itbl(bqe)->type == TSO ||
2400 get_itbl(bqe)->type == BLOCKED_FETCH ||
2401 get_itbl(bqe)->type == CONSTR);
2402 /* only BQs of an RBH end with an RBH_Save closure */
2403 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
2405 switch (get_itbl(bqe)->type) {
2407 fprintf(stderr," TSO %d (%x),",
2408 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
2411 fprintf(stderr," BF (node=%p, ga=((%x, %d, %x)),",
2412 ((StgBlockedFetch *)bqe)->node,
2413 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
2414 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
2415 ((StgBlockedFetch *)bqe)->ga.weight);
2418 fprintf(stderr," %s (IP %p),",
2419 (get_itbl(bqe) == &RBH_Save_0_info ? "RBH_Save_0" :
2420 get_itbl(bqe) == &RBH_Save_1_info ? "RBH_Save_1" :
2421 get_itbl(bqe) == &RBH_Save_2_info ? "RBH_Save_2" :
2422 "RBH_Save_?"), get_itbl(bqe));
2425 barf("Unexpected closure type %s in blocking queue of %p (%s)",
2426 info_type(bqe), node, info_type(node));
2430 fputc('\n', stderr);
2432 # elif defined(GRAN)
2434 print_bq (StgClosure *node)
2436 StgBlockingQueueElement *bqe;
2438 PEs node_loc, tso_loc;
2441 /* should cover all closures that may have a blocking queue */
2442 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
2443 get_itbl(node)->type == FETCH_ME_BQ ||
2444 get_itbl(node)->type == RBH);
2446 ASSERT(node!=(StgClosure*)NULL); // sanity check
2447 node_loc = where_is(node);
2449 fprintf(stderr,"## BQ of closure %p (%s) on [PE %d]: ",
2450 node, info_type(node), node_loc);
2453 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
2455 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
2456 !end; // iterate until bqe points to a CONSTR
2457 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
2458 ASSERT(bqe != END_BQ_QUEUE); // sanity check
2459 ASSERT(bqe != (StgTSO*)NULL); // sanity check
2460 /* types of closures that may appear in a blocking queue */
2461 ASSERT(get_itbl(bqe)->type == TSO ||
2462 get_itbl(bqe)->type == CONSTR);
2463 /* only BQs of an RBH end with an RBH_Save closure */
2464 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
2466 tso_loc = where_is((StgClosure *)bqe);
2467 switch (get_itbl(bqe)->type) {
2469 fprintf(stderr," TSO %d (%x) on [PE %d],",
2470 ((StgTSO *)bqe)->id, ((StgTSO *)bqe), tso_loc);
2473 fprintf(stderr," %s (IP %p),",
2474 (get_itbl(bqe) == &RBH_Save_0_info ? "RBH_Save_0" :
2475 get_itbl(bqe) == &RBH_Save_1_info ? "RBH_Save_1" :
2476 get_itbl(bqe) == &RBH_Save_2_info ? "RBH_Save_2" :
2477 "RBH_Save_?"), get_itbl(bqe));
2480 barf("Unexpected closure type %s in blocking queue of %p (%s)",
2481 info_type(bqe), node, info_type(node));
2485 fputc('\n', stderr);
2489 Nice and easy: only TSOs on the blocking queue
2492 print_bq (StgClosure *node)
2496 ASSERT(node!=(StgClosure*)NULL); // sanity check
2497 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
2498 tso != END_TSO_QUEUE;
2500 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
2501 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
2502 fprintf(stderr," TSO %d (%p),", tso->id, tso);
2504 fputc('\n', stderr);
2515 for (i=0, tso=run_queue_hd;
2516 tso != END_TSO_QUEUE;
2525 sched_belch(char *s, ...)
2530 fprintf(stderr, "scheduler (task %ld): ", pthread_self());
2532 fprintf(stderr, "scheduler: ");
2534 vfprintf(stderr, s, ap);
2535 fprintf(stderr, "\n");
2540 //@node Index, , Debugging Routines, Main scheduling code
2544 //* MainRegTable:: @cindex\s-+MainRegTable
2545 //* StgMainThread:: @cindex\s-+StgMainThread
2546 //* awaken_blocked_queue:: @cindex\s-+awaken_blocked_queue
2547 //* blocked_queue_hd:: @cindex\s-+blocked_queue_hd
2548 //* blocked_queue_tl:: @cindex\s-+blocked_queue_tl
2549 //* context_switch:: @cindex\s-+context_switch
2550 //* createThread:: @cindex\s-+createThread
2551 //* free_capabilities:: @cindex\s-+free_capabilities
2552 //* gc_pending_cond:: @cindex\s-+gc_pending_cond
2553 //* initScheduler:: @cindex\s-+initScheduler
2554 //* interrupted:: @cindex\s-+interrupted
2555 //* n_free_capabilities:: @cindex\s-+n_free_capabilities
2556 //* next_thread_id:: @cindex\s-+next_thread_id
2557 //* print_bq:: @cindex\s-+print_bq
2558 //* run_queue_hd:: @cindex\s-+run_queue_hd
2559 //* run_queue_tl:: @cindex\s-+run_queue_tl
2560 //* sched_mutex:: @cindex\s-+sched_mutex
2561 //* schedule:: @cindex\s-+schedule
2562 //* take_off_run_queue:: @cindex\s-+take_off_run_queue
2563 //* task_ids:: @cindex\s-+task_ids
2564 //* term_mutex:: @cindex\s-+term_mutex
2565 //* thread_ready_cond:: @cindex\s-+thread_ready_cond