[project @ 2003-03-25 17:58:47 by sof]
[ghc-hetmet.git] / ghc / rts / Schedule.c
1 /* ---------------------------------------------------------------------------
2  * $Id: Schedule.c,v 1.165 2003/03/25 17:58:50 sof Exp $
3  *
4  * (c) The GHC Team, 1998-2000
5  *
6  * Scheduler
7  *
8  * Different GHC ways use this scheduler quite differently (see comments below)
9  * Here is the global picture:
10  *
11  * WAY  Name     CPP flag  What's it for
12  * --------------------------------------
13  * mp   GUM      PAR          Parallel execution on a distributed memory machine
14  * s    SMP      SMP          Parallel execution on a shared memory machine
15  * mg   GranSim  GRAN         Simulation of parallel execution
16  * md   GUM/GdH  DIST         Distributed execution (based on GUM)
17  *
18  * --------------------------------------------------------------------------*/
19
20 //@node Main scheduling code, , ,
21 //@section Main scheduling code
22
23 /* 
24  * Version with scheduler monitor support for SMPs (WAY=s):
25
26    This design provides a high-level API to create and schedule threads etc.
27    as documented in the SMP design document.
28
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
31    library.
32
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).
38
39    In a non-SMP build, there is one global capability, namely MainRegTable.
40
41    SDM & KH, 10/99
42
43  * Version with support for distributed memory parallelism aka GUM (WAY=mp):
44
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
53
54  * Version with support for simulating parallel execution aka GranSim (WAY=mg):
55
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
60 */
61
62 //@menu
63 //* Includes::                  
64 //* Variables and Data structures::  
65 //* Main scheduling loop::      
66 //* Suspend and Resume::        
67 //* Run queue code::            
68 //* Garbage Collextion Routines::  
69 //* Blocking Queue Routines::   
70 //* Exception Handling Routines::  
71 //* Debugging Routines::        
72 //* Index::                     
73 //@end menu
74
75 //@node Includes, Variables and Data structures, Main scheduling code, Main scheduling code
76 //@subsection Includes
77
78 #include "PosixSource.h"
79 #include "Rts.h"
80 #include "SchedAPI.h"
81 #include "RtsUtils.h"
82 #include "RtsFlags.h"
83 #include "Storage.h"
84 #include "StgRun.h"
85 #include "StgStartup.h"
86 #include "Hooks.h"
87 #define COMPILING_SCHEDULER
88 #include "Schedule.h"
89 #include "StgMiscClosures.h"
90 #include "Storage.h"
91 #include "Interpreter.h"
92 #include "Exception.h"
93 #include "Printer.h"
94 #include "Signals.h"
95 #include "Sanity.h"
96 #include "Stats.h"
97 #include "Timer.h"
98 #include "Prelude.h"
99 #include "ThreadLabels.h"
100 #ifdef PROFILING
101 #include "Proftimer.h"
102 #include "ProfHeap.h"
103 #endif
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"
111 # include "HLC.h"
112 #endif
113 #include "Sparks.h"
114 #include "Capability.h"
115 #include "OSThreads.h"
116 #include  "Task.h"
117
118 #ifdef HAVE_SYS_TYPES_H
119 #include <sys/types.h>
120 #endif
121 #ifdef HAVE_UNISTD_H
122 #include <unistd.h>
123 #endif
124
125 #include <string.h>
126 #include <stdlib.h>
127 #include <stdarg.h>
128
129 //@node Variables and Data structures, Prototypes, Includes, Main scheduling code
130 //@subsection Variables and Data structures
131
132 /* Main thread queue.
133  * Locks required: sched_mutex.
134  */
135 StgMainThread *main_threads = NULL;
136
137 #ifdef THREADED_RTS
138 // Pointer to the thread that executes main
139 // When this thread is finished, the program terminates
140 // by calling shutdownHaskellAndExit.
141 // It would be better to add a call to shutdownHaskellAndExit
142 // to the Main.main wrapper and to remove this hack.
143 StgMainThread *main_main_thread = NULL;
144 #endif
145
146 /* Thread queues.
147  * Locks required: sched_mutex.
148  */
149 #if defined(GRAN)
150
151 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
152 /* rtsTime TimeOfNextEvent, EndOfTimeSlice;            now in GranSim.c */
153
154 /* 
155    In GranSim we have a runnable and a blocked queue for each processor.
156    In order to minimise code changes new arrays run_queue_hds/tls
157    are created. run_queue_hd is then a short cut (macro) for
158    run_queue_hds[CurrentProc] (see GranSim.h).
159    -- HWL
160 */
161 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
162 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
163 StgTSO *ccalling_threadss[MAX_PROC];
164 /* We use the same global list of threads (all_threads) in GranSim as in
165    the std RTS (i.e. we are cheating). However, we don't use this list in
166    the GranSim specific code at the moment (so we are only potentially
167    cheating).  */
168
169 #else /* !GRAN */
170
171 StgTSO *run_queue_hd = NULL;
172 StgTSO *run_queue_tl = NULL;
173 StgTSO *blocked_queue_hd = NULL;
174 StgTSO *blocked_queue_tl = NULL;
175 StgTSO *sleeping_queue = NULL;    /* perhaps replace with a hash table? */
176
177 #endif
178
179 /* Linked list of all threads.
180  * Used for detecting garbage collected threads.
181  */
182 StgTSO *all_threads = NULL;
183
184 /* When a thread performs a safe C call (_ccall_GC, using old
185  * terminology), it gets put on the suspended_ccalling_threads
186  * list. Used by the garbage collector.
187  */
188 static StgTSO *suspended_ccalling_threads;
189
190 static StgTSO *threadStackOverflow(StgTSO *tso);
191
192 /* KH: The following two flags are shared memory locations.  There is no need
193        to lock them, since they are only unset at the end of a scheduler
194        operation.
195 */
196
197 /* flag set by signal handler to precipitate a context switch */
198 //@cindex context_switch
199 nat context_switch = 0;
200
201 /* if this flag is set as well, give up execution */
202 //@cindex interrupted
203 rtsBool interrupted = rtsFalse;
204
205 /* Next thread ID to allocate.
206  * Locks required: thread_id_mutex
207  */
208 //@cindex next_thread_id
209 static StgThreadID next_thread_id = 1;
210
211 /*
212  * Pointers to the state of the current thread.
213  * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
214  * thread.  If CurrentTSO == NULL, then we're at the scheduler level.
215  */
216  
217 /* The smallest stack size that makes any sense is:
218  *    RESERVED_STACK_WORDS    (so we can get back from the stack overflow)
219  *  + sizeofW(StgStopFrame)   (the stg_stop_thread_info frame)
220  *  + 1                       (the realworld token for an IO thread)
221  *  + 1                       (the closure to enter)
222  *
223  * A thread with this stack will bomb immediately with a stack
224  * overflow, which will increase its stack size.  
225  */
226
227 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 2)
228
229
230 #if defined(GRAN)
231 StgTSO *CurrentTSO;
232 #endif
233
234 /*  This is used in `TSO.h' and gcc 2.96 insists that this variable actually 
235  *  exists - earlier gccs apparently didn't.
236  *  -= chak
237  */
238 StgTSO dummy_tso;
239
240 static rtsBool ready_to_gc;
241
242 /*
243  * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
244  * in an MT setting, needed to signal that a worker thread shouldn't hang around
245  * in the scheduler when it is out of work.
246  */
247 static rtsBool shutting_down_scheduler = rtsFalse;
248
249 void            addToBlockedQueue ( StgTSO *tso );
250
251 static void     schedule          ( void );
252        void     interruptStgRts   ( void );
253
254 static void     detectBlackHoles  ( void );
255
256 #ifdef DEBUG
257 static void sched_belch(char *s, ...);
258 #endif
259
260 #if defined(RTS_SUPPORTS_THREADS)
261 /* ToDo: carefully document the invariants that go together
262  *       with these synchronisation objects.
263  */
264 Mutex     sched_mutex       = INIT_MUTEX_VAR;
265 Mutex     term_mutex        = INIT_MUTEX_VAR;
266
267 /*
268  * A heavyweight solution to the problem of protecting
269  * the thread_id from concurrent update.
270  */
271 Mutex     thread_id_mutex   = INIT_MUTEX_VAR;
272
273
274 # if defined(SMP)
275 static Condition gc_pending_cond = INIT_COND_VAR;
276 nat await_death;
277 # endif
278
279 #endif /* RTS_SUPPORTS_THREADS */
280
281 #if defined(PAR)
282 StgTSO *LastTSO;
283 rtsTime TimeOfLastYield;
284 rtsBool emitSchedule = rtsTrue;
285 #endif
286
287 #if DEBUG
288 static char *whatNext_strs[] = {
289   "ThreadRunGHC",
290   "ThreadInterpret",
291   "ThreadKilled",
292   "ThreadRelocated",
293   "ThreadComplete"
294 };
295 #endif
296
297 #if defined(PAR)
298 StgTSO * createSparkThread(rtsSpark spark);
299 StgTSO * activateSpark (rtsSpark spark);  
300 #endif
301
302 /*
303  * The thread state for the main thread.
304 // ToDo: check whether not needed any more
305 StgTSO   *MainTSO;
306  */
307
308 #if defined(PAR) || defined(RTS_SUPPORTS_THREADS)
309 static void taskStart(void);
310 static void
311 taskStart(void)
312 {
313   schedule();
314 }
315 #endif
316
317 #if defined(RTS_SUPPORTS_THREADS)
318 void
319 startSchedulerTask(void)
320 {
321     startTask(taskStart);
322 }
323 #endif
324
325 //@node Main scheduling loop, Suspend and Resume, Prototypes, Main scheduling code
326 //@subsection Main scheduling loop
327
328 /* ---------------------------------------------------------------------------
329    Main scheduling loop.
330
331    We use round-robin scheduling, each thread returning to the
332    scheduler loop when one of these conditions is detected:
333
334       * out of heap space
335       * timer expires (thread yields)
336       * thread blocks
337       * thread ends
338       * stack overflow
339
340    Locking notes:  we acquire the scheduler lock once at the beginning
341    of the scheduler loop, and release it when
342     
343       * running a thread, or
344       * waiting for work, or
345       * waiting for a GC to complete.
346
347    GRAN version:
348      In a GranSim setup this loop iterates over the global event queue.
349      This revolves around the global event queue, which determines what 
350      to do next. Therefore, it's more complicated than either the 
351      concurrent or the parallel (GUM) setup.
352
353    GUM version:
354      GUM iterates over incoming messages.
355      It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
356      and sends out a fish whenever it has nothing to do; in-between
357      doing the actual reductions (shared code below) it processes the
358      incoming messages and deals with delayed operations 
359      (see PendingFetches).
360      This is not the ugliest code you could imagine, but it's bloody close.
361
362    ------------------------------------------------------------------------ */
363 //@cindex schedule
364 static void
365 schedule( void )
366 {
367   StgTSO *t;
368   Capability *cap;
369   StgThreadReturnCode ret;
370 #if defined(GRAN)
371   rtsEvent *event;
372 #elif defined(PAR)
373   StgSparkPool *pool;
374   rtsSpark spark;
375   StgTSO *tso;
376   GlobalTaskId pe;
377   rtsBool receivedFinish = rtsFalse;
378 # if defined(DEBUG)
379   nat tp_size, sp_size; // stats only
380 # endif
381 #endif
382   rtsBool was_interrupted = rtsFalse;
383   StgTSOWhatNext prev_what_next;
384   
385   ACQUIRE_LOCK(&sched_mutex);
386  
387 #if defined(RTS_SUPPORTS_THREADS)
388   waitForWorkCapability(&sched_mutex, &cap, rtsFalse);
389   IF_DEBUG(scheduler, sched_belch("worker thread (osthread %p): entering RTS", osThreadId()));
390 #else
391   /* simply initialise it in the non-threaded case */
392   grabCapability(&cap);
393 #endif
394
395 #if defined(GRAN)
396   /* set up first event to get things going */
397   /* ToDo: assign costs for system setup and init MainTSO ! */
398   new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
399             ContinueThread, 
400             CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
401
402   IF_DEBUG(gran,
403            fprintf(stderr, "GRAN: Init CurrentTSO (in schedule) = %p\n", CurrentTSO);
404            G_TSO(CurrentTSO, 5));
405
406   if (RtsFlags.GranFlags.Light) {
407     /* Save current time; GranSim Light only */
408     CurrentTSO->gran.clock = CurrentTime[CurrentProc];
409   }      
410
411   event = get_next_event();
412
413   while (event!=(rtsEvent*)NULL) {
414     /* Choose the processor with the next event */
415     CurrentProc = event->proc;
416     CurrentTSO = event->tso;
417
418 #elif defined(PAR)
419
420   while (!receivedFinish) {    /* set by processMessages */
421                                /* when receiving PP_FINISH message         */ 
422 #else
423
424   while (1) {
425
426 #endif
427
428     IF_DEBUG(scheduler, printAllThreads());
429
430 #if defined(RTS_SUPPORTS_THREADS)
431     /* Check to see whether there are any worker threads
432        waiting to deposit external call results. If so,
433        yield our capability */
434     yieldToReturningWorker(&sched_mutex, &cap);
435 #endif
436
437     /* If we're interrupted (the user pressed ^C, or some other
438      * termination condition occurred), kill all the currently running
439      * threads.
440      */
441     if (interrupted) {
442       IF_DEBUG(scheduler, sched_belch("interrupted"));
443       interrupted = rtsFalse;
444       was_interrupted = rtsTrue;
445 #if defined(RTS_SUPPORTS_THREADS)
446       // In the threaded RTS, deadlock detection doesn't work,
447       // so just exit right away.
448       prog_belch("interrupted");
449       releaseCapability(cap);
450       startTask(taskStart);     // thread-safe-call to shutdownHaskellAndExit
451       RELEASE_LOCK(&sched_mutex);
452       shutdownHaskellAndExit(EXIT_SUCCESS);
453 #else
454       deleteAllThreads();
455 #endif
456     }
457
458     /* Go through the list of main threads and wake up any
459      * clients whose computations have finished.  ToDo: this
460      * should be done more efficiently without a linear scan
461      * of the main threads list, somehow...
462      */
463 #if defined(RTS_SUPPORTS_THREADS)
464     { 
465       StgMainThread *m, **prev;
466       prev = &main_threads;
467       for (m = main_threads; m != NULL; prev = &m->link, m = m->link) {
468         switch (m->tso->what_next) {
469         case ThreadComplete:
470           if (m->ret) {
471               // NOTE: return val is tso->sp[1] (see StgStartup.hc)
472               *(m->ret) = (StgClosure *)m->tso->sp[1]; 
473           }
474           *prev = m->link;
475           m->stat = Success;
476           broadcastCondition(&m->wakeup);
477 #ifdef DEBUG
478           removeThreadLabel((StgWord)m->tso);
479 #endif
480           if(m == main_main_thread)
481           {
482               releaseCapability(cap);
483               startTask(taskStart);     // thread-safe-call to shutdownHaskellAndExit
484               RELEASE_LOCK(&sched_mutex);
485               shutdownHaskellAndExit(EXIT_SUCCESS);
486           }
487           break;
488         case ThreadKilled:
489           if (m->ret) *(m->ret) = NULL;
490           *prev = m->link;
491           if (was_interrupted) {
492             m->stat = Interrupted;
493           } else {
494             m->stat = Killed;
495           }
496           broadcastCondition(&m->wakeup);
497 #ifdef DEBUG
498           removeThreadLabel((StgWord)m->tso);
499 #endif
500           if(m == main_main_thread)
501           {
502               releaseCapability(cap);
503               startTask(taskStart);     // thread-safe-call to shutdownHaskellAndExit
504               RELEASE_LOCK(&sched_mutex);
505               shutdownHaskellAndExit(EXIT_SUCCESS);
506           }
507           break;
508         default:
509           break;
510         }
511       }
512     }
513
514 #else /* not threaded */
515
516 # if defined(PAR)
517     /* in GUM do this only on the Main PE */
518     if (IAmMainThread)
519 # endif
520     /* If our main thread has finished or been killed, return.
521      */
522     {
523       StgMainThread *m = main_threads;
524       if (m->tso->what_next == ThreadComplete
525           || m->tso->what_next == ThreadKilled) {
526 #ifdef DEBUG
527         removeThreadLabel((StgWord)m->tso);
528 #endif
529         main_threads = main_threads->link;
530         if (m->tso->what_next == ThreadComplete) {
531             // We finished successfully, fill in the return value
532             // NOTE: return val is tso->sp[1] (see StgStartup.hc)
533             if (m->ret) { *(m->ret) = (StgClosure *)m->tso->sp[1]; };
534             m->stat = Success;
535             return;
536         } else {
537           if (m->ret) { *(m->ret) = NULL; };
538           if (was_interrupted) {
539             m->stat = Interrupted;
540           } else {
541             m->stat = Killed;
542           }
543           return;
544         }
545       }
546     }
547 #endif
548
549     /* Top up the run queue from our spark pool.  We try to make the
550      * number of threads in the run queue equal to the number of
551      * free capabilities.
552      *
553      * Disable spark support in SMP for now, non-essential & requires
554      * a little bit of work to make it compile cleanly. -- sof 1/02.
555      */
556 #if 0 /* defined(SMP) */
557     {
558       nat n = getFreeCapabilities();
559       StgTSO *tso = run_queue_hd;
560
561       /* Count the run queue */
562       while (n > 0 && tso != END_TSO_QUEUE) {
563         tso = tso->link;
564         n--;
565       }
566
567       for (; n > 0; n--) {
568         StgClosure *spark;
569         spark = findSpark(rtsFalse);
570         if (spark == NULL) {
571           break; /* no more sparks in the pool */
572         } else {
573           /* I'd prefer this to be done in activateSpark -- HWL */
574           /* tricky - it needs to hold the scheduler lock and
575            * not try to re-acquire it -- SDM */
576           createSparkThread(spark);       
577           IF_DEBUG(scheduler,
578                    sched_belch("==^^ turning spark of closure %p into a thread",
579                                (StgClosure *)spark));
580         }
581       }
582       /* We need to wake up the other tasks if we just created some
583        * work for them.
584        */
585       if (getFreeCapabilities() - n > 1) {
586           signalCondition( &thread_ready_cond );
587       }
588     }
589 #endif // SMP
590
591     /* check for signals each time around the scheduler */
592 #ifndef mingw32_TARGET_OS
593     if (signals_pending()) {
594       RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
595       startSignalHandlers();
596       ACQUIRE_LOCK(&sched_mutex);
597     }
598 #endif
599
600     /* Check whether any waiting threads need to be woken up.  If the
601      * run queue is empty, and there are no other tasks running, we
602      * can wait indefinitely for something to happen.
603      */
604     if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue) 
605 #if defined(RTS_SUPPORTS_THREADS) && !defined(SMP)
606                 || EMPTY_RUN_QUEUE()
607 #endif
608         )
609     {
610       awaitEvent( EMPTY_RUN_QUEUE()
611 #if defined(SMP)
612         && allFreeCapabilities()
613 #endif
614         );
615     }
616     /* we can be interrupted while waiting for I/O... */
617     if (interrupted) continue;
618
619     /* 
620      * Detect deadlock: when we have no threads to run, there are no
621      * threads waiting on I/O or sleeping, and all the other tasks are
622      * waiting for work, we must have a deadlock of some description.
623      *
624      * We first try to find threads blocked on themselves (ie. black
625      * holes), and generate NonTermination exceptions where necessary.
626      *
627      * If no threads are black holed, we have a deadlock situation, so
628      * inform all the main threads.
629      */
630 #if !defined(PAR) && !defined(RTS_SUPPORTS_THREADS)
631     if (   EMPTY_THREAD_QUEUES()
632 #if defined(RTS_SUPPORTS_THREADS)
633         && EMPTY_QUEUE(suspended_ccalling_threads)
634 #endif
635 #ifdef SMP
636         && allFreeCapabilities()
637 #endif
638         )
639     {
640         IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
641 #if defined(THREADED_RTS)
642         /* and SMP mode ..? */
643         releaseCapability(cap);
644 #endif
645         // Garbage collection can release some new threads due to
646         // either (a) finalizers or (b) threads resurrected because
647         // they are about to be send BlockedOnDeadMVar.  Any threads
648         // thus released will be immediately runnable.
649         GarbageCollect(GetRoots,rtsTrue);
650
651         if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
652
653         IF_DEBUG(scheduler, 
654                  sched_belch("still deadlocked, checking for black holes..."));
655         detectBlackHoles();
656
657         if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
658
659 #ifndef mingw32_TARGET_OS
660         /* If we have user-installed signal handlers, then wait
661          * for signals to arrive rather then bombing out with a
662          * deadlock.
663          */
664 #if defined(RTS_SUPPORTS_THREADS)
665         if ( 0 ) { /* hmm..what to do? Simply stop waiting for
666                       a signal with no runnable threads (or I/O
667                       suspended ones) leads nowhere quick.
668                       For now, simply shut down when we reach this
669                       condition.
670                       
671                       ToDo: define precisely under what conditions
672                       the Scheduler should shut down in an MT setting.
673                    */
674 #else
675         if ( anyUserHandlers() ) {
676 #endif
677             IF_DEBUG(scheduler, 
678                      sched_belch("still deadlocked, waiting for signals..."));
679
680             awaitUserSignals();
681
682             // we might be interrupted...
683             if (interrupted) { continue; }
684
685             if (signals_pending()) {
686                 RELEASE_LOCK(&sched_mutex);
687                 startSignalHandlers();
688                 ACQUIRE_LOCK(&sched_mutex);
689             }
690             ASSERT(!EMPTY_RUN_QUEUE());
691             goto not_deadlocked;
692         }
693 #endif
694
695         /* Probably a real deadlock.  Send the current main thread the
696          * Deadlock exception (or in the SMP build, send *all* main
697          * threads the deadlock exception, since none of them can make
698          * progress).
699          */
700         {
701             StgMainThread *m;
702 #if defined(RTS_SUPPORTS_THREADS)
703             for (m = main_threads; m != NULL; m = m->link) {
704                 switch (m->tso->why_blocked) {
705                 case BlockedOnBlackHole:
706                     raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
707                     break;
708                 case BlockedOnException:
709                 case BlockedOnMVar:
710                     raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
711                     break;
712                 default:
713                     barf("deadlock: main thread blocked in a strange way");
714                 }
715             }
716 #else
717             m = main_threads;
718             switch (m->tso->why_blocked) {
719             case BlockedOnBlackHole:
720                 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
721                 break;
722             case BlockedOnException:
723             case BlockedOnMVar:
724                 raiseAsync(m->tso, (StgClosure *)Deadlock_closure);
725                 break;
726             default:
727                 barf("deadlock: main thread blocked in a strange way");
728             }
729 #endif
730         }
731
732 #if defined(RTS_SUPPORTS_THREADS)
733         /* ToDo: revisit conditions (and mechanism) for shutting
734            down a multi-threaded world  */
735         IF_DEBUG(scheduler, sched_belch("all done, i think...shutting down."));
736         RELEASE_LOCK(&sched_mutex);
737         shutdownHaskell();
738         return;
739 #endif
740     }
741   not_deadlocked:
742
743 #elif defined(RTS_SUPPORTS_THREADS)
744     /* ToDo: add deadlock detection in threaded RTS */
745 #elif defined(PAR)
746     /* ToDo: add deadlock detection in GUM (similar to SMP) -- HWL */
747 #endif
748
749 #if defined(SMP)
750     /* If there's a GC pending, don't do anything until it has
751      * completed.
752      */
753     if (ready_to_gc) {
754       IF_DEBUG(scheduler,sched_belch("waiting for GC"));
755       waitCondition( &gc_pending_cond, &sched_mutex );
756     }
757 #endif    
758
759 #if defined(RTS_SUPPORTS_THREADS)
760 #if defined(SMP)
761     /* block until we've got a thread on the run queue and a free
762      * capability.
763      *
764      */
765     if ( EMPTY_RUN_QUEUE() ) {
766       /* Give up our capability */
767       releaseCapability(cap);
768
769       /* If we're in the process of shutting down (& running the
770        * a batch of finalisers), don't wait around.
771        */
772       if ( shutting_down_scheduler ) {
773         RELEASE_LOCK(&sched_mutex);
774         return;
775       }
776       IF_DEBUG(scheduler, sched_belch("thread %d: waiting for work", osThreadId()));
777       waitForWorkCapability(&sched_mutex, &cap, rtsTrue);
778       IF_DEBUG(scheduler, sched_belch("thread %d: work now available", osThreadId()));
779     }
780 #else
781     if ( EMPTY_RUN_QUEUE() ) {
782       continue; // nothing to do
783     }
784 #endif
785 #endif
786
787 #if defined(GRAN)
788     if (RtsFlags.GranFlags.Light)
789       GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
790
791     /* adjust time based on time-stamp */
792     if (event->time > CurrentTime[CurrentProc] &&
793         event->evttype != ContinueThread)
794       CurrentTime[CurrentProc] = event->time;
795     
796     /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
797     if (!RtsFlags.GranFlags.Light)
798       handleIdlePEs();
799
800     IF_DEBUG(gran, fprintf(stderr, "GRAN: switch by event-type\n"));
801
802     /* main event dispatcher in GranSim */
803     switch (event->evttype) {
804       /* Should just be continuing execution */
805     case ContinueThread:
806       IF_DEBUG(gran, fprintf(stderr, "GRAN: doing ContinueThread\n"));
807       /* ToDo: check assertion
808       ASSERT(run_queue_hd != (StgTSO*)NULL &&
809              run_queue_hd != END_TSO_QUEUE);
810       */
811       /* Ignore ContinueThreads for fetching threads (if synchr comm) */
812       if (!RtsFlags.GranFlags.DoAsyncFetch &&
813           procStatus[CurrentProc]==Fetching) {
814         belch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]",
815               CurrentTSO->id, CurrentTSO, CurrentProc);
816         goto next_thread;
817       } 
818       /* Ignore ContinueThreads for completed threads */
819       if (CurrentTSO->what_next == ThreadComplete) {
820         belch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)", 
821               CurrentTSO->id, CurrentTSO, CurrentProc);
822         goto next_thread;
823       } 
824       /* Ignore ContinueThreads for threads that are being migrated */
825       if (PROCS(CurrentTSO)==Nowhere) { 
826         belch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)",
827               CurrentTSO->id, CurrentTSO, CurrentProc);
828         goto next_thread;
829       }
830       /* The thread should be at the beginning of the run queue */
831       if (CurrentTSO!=run_queue_hds[CurrentProc]) { 
832         belch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread",
833               CurrentTSO->id, CurrentTSO, CurrentProc);
834         break; // run the thread anyway
835       }
836       /*
837       new_event(proc, proc, CurrentTime[proc],
838                 FindWork,
839                 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
840       goto next_thread; 
841       */ /* Catches superfluous CONTINUEs -- should be unnecessary */
842       break; // now actually run the thread; DaH Qu'vam yImuHbej 
843
844     case FetchNode:
845       do_the_fetchnode(event);
846       goto next_thread;             /* handle next event in event queue  */
847       
848     case GlobalBlock:
849       do_the_globalblock(event);
850       goto next_thread;             /* handle next event in event queue  */
851       
852     case FetchReply:
853       do_the_fetchreply(event);
854       goto next_thread;             /* handle next event in event queue  */
855       
856     case UnblockThread:   /* Move from the blocked queue to the tail of */
857       do_the_unblock(event);
858       goto next_thread;             /* handle next event in event queue  */
859       
860     case ResumeThread:  /* Move from the blocked queue to the tail of */
861       /* the runnable queue ( i.e. Qu' SImqa'lu') */ 
862       event->tso->gran.blocktime += 
863         CurrentTime[CurrentProc] - event->tso->gran.blockedat;
864       do_the_startthread(event);
865       goto next_thread;             /* handle next event in event queue  */
866       
867     case StartThread:
868       do_the_startthread(event);
869       goto next_thread;             /* handle next event in event queue  */
870       
871     case MoveThread:
872       do_the_movethread(event);
873       goto next_thread;             /* handle next event in event queue  */
874       
875     case MoveSpark:
876       do_the_movespark(event);
877       goto next_thread;             /* handle next event in event queue  */
878       
879     case FindWork:
880       do_the_findwork(event);
881       goto next_thread;             /* handle next event in event queue  */
882       
883     default:
884       barf("Illegal event type %u\n", event->evttype);
885     }  /* switch */
886     
887     /* This point was scheduler_loop in the old RTS */
888
889     IF_DEBUG(gran, belch("GRAN: after main switch"));
890
891     TimeOfLastEvent = CurrentTime[CurrentProc];
892     TimeOfNextEvent = get_time_of_next_event();
893     IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
894     // CurrentTSO = ThreadQueueHd;
895
896     IF_DEBUG(gran, belch("GRAN: time of next event is: %ld", 
897                          TimeOfNextEvent));
898
899     if (RtsFlags.GranFlags.Light) 
900       GranSimLight_leave_system(event, &ActiveTSO); 
901
902     EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
903
904     IF_DEBUG(gran, 
905              belch("GRAN: end of time-slice is %#lx", EndOfTimeSlice));
906
907     /* in a GranSim setup the TSO stays on the run queue */
908     t = CurrentTSO;
909     /* Take a thread from the run queue. */
910     t = POP_RUN_QUEUE(); // take_off_run_queue(t);
911
912     IF_DEBUG(gran, 
913              fprintf(stderr, "GRAN: About to run current thread, which is\n");
914              G_TSO(t,5));
915
916     context_switch = 0; // turned on via GranYield, checking events and time slice
917
918     IF_DEBUG(gran, 
919              DumpGranEvent(GR_SCHEDULE, t));
920
921     procStatus[CurrentProc] = Busy;
922
923 #elif defined(PAR)
924     if (PendingFetches != END_BF_QUEUE) {
925         processFetches();
926     }
927
928     /* ToDo: phps merge with spark activation above */
929     /* check whether we have local work and send requests if we have none */
930     if (EMPTY_RUN_QUEUE()) {  /* no runnable threads */
931       /* :-[  no local threads => look out for local sparks */
932       /* the spark pool for the current PE */
933       pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
934       if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
935           pool->hd < pool->tl) {
936         /* 
937          * ToDo: add GC code check that we really have enough heap afterwards!!
938          * Old comment:
939          * If we're here (no runnable threads) and we have pending
940          * sparks, we must have a space problem.  Get enough space
941          * to turn one of those pending sparks into a
942          * thread... 
943          */
944
945         spark = findSpark(rtsFalse);                /* get a spark */
946         if (spark != (rtsSpark) NULL) {
947           tso = activateSpark(spark);       /* turn the spark into a thread */
948           IF_PAR_DEBUG(schedule,
949                        belch("==== schedule: Created TSO %d (%p); %d threads active",
950                              tso->id, tso, advisory_thread_count));
951
952           if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
953             belch("==^^ failed to activate spark");
954             goto next_thread;
955           }               /* otherwise fall through & pick-up new tso */
956         } else {
957           IF_PAR_DEBUG(verbose,
958                        belch("==^^ no local sparks (spark pool contains only NFs: %d)", 
959                              spark_queue_len(pool)));
960           goto next_thread;
961         }
962       }
963
964       /* If we still have no work we need to send a FISH to get a spark
965          from another PE 
966       */
967       if (EMPTY_RUN_QUEUE()) {
968       /* =8-[  no local sparks => look for work on other PEs */
969         /*
970          * We really have absolutely no work.  Send out a fish
971          * (there may be some out there already), and wait for
972          * something to arrive.  We clearly can't run any threads
973          * until a SCHEDULE or RESUME arrives, and so that's what
974          * we're hoping to see.  (Of course, we still have to
975          * respond to other types of messages.)
976          */
977         TIME now = msTime() /*CURRENT_TIME*/;
978         IF_PAR_DEBUG(verbose, 
979                      belch("--  now=%ld", now));
980         IF_PAR_DEBUG(verbose,
981                      if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
982                          (last_fish_arrived_at!=0 &&
983                           last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
984                        belch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)",
985                              last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
986                              last_fish_arrived_at,
987                              RtsFlags.ParFlags.fishDelay, now);
988                      });
989         
990         if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
991             (last_fish_arrived_at==0 ||
992              (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
993           /* outstandingFishes is set in sendFish, processFish;
994              avoid flooding system with fishes via delay */
995           pe = choosePE();
996           sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY, 
997                    NEW_FISH_HUNGER);
998
999           // Global statistics: count no. of fishes
1000           if (RtsFlags.ParFlags.ParStats.Global &&
1001               RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1002             globalParStats.tot_fish_mess++;
1003           }
1004         }
1005       
1006         receivedFinish = processMessages();
1007         goto next_thread;
1008       }
1009     } else if (PacketsWaiting()) {  /* Look for incoming messages */
1010       receivedFinish = processMessages();
1011     }
1012
1013     /* Now we are sure that we have some work available */
1014     ASSERT(run_queue_hd != END_TSO_QUEUE);
1015
1016     /* Take a thread from the run queue, if we have work */
1017     t = POP_RUN_QUEUE();  // take_off_run_queue(END_TSO_QUEUE);
1018     IF_DEBUG(sanity,checkTSO(t));
1019
1020     /* ToDo: write something to the log-file
1021     if (RTSflags.ParFlags.granSimStats && !sameThread)
1022         DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
1023
1024     CurrentTSO = t;
1025     */
1026     /* the spark pool for the current PE */
1027     pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
1028
1029     IF_DEBUG(scheduler, 
1030              belch("--=^ %d threads, %d sparks on [%#x]", 
1031                    run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
1032
1033 # if 1
1034     if (0 && RtsFlags.ParFlags.ParStats.Full && 
1035         t && LastTSO && t->id != LastTSO->id && 
1036         LastTSO->why_blocked == NotBlocked && 
1037         LastTSO->what_next != ThreadComplete) {
1038       // if previously scheduled TSO not blocked we have to record the context switch
1039       DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
1040                            GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
1041     }
1042
1043     if (RtsFlags.ParFlags.ParStats.Full && 
1044         (emitSchedule /* forced emit */ ||
1045         (t && LastTSO && t->id != LastTSO->id))) {
1046       /* 
1047          we are running a different TSO, so write a schedule event to log file
1048          NB: If we use fair scheduling we also have to write  a deschedule 
1049              event for LastTSO; with unfair scheduling we know that the
1050              previous tso has blocked whenever we switch to another tso, so
1051              we don't need it in GUM for now
1052       */
1053       DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1054                        GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
1055       emitSchedule = rtsFalse;
1056     }
1057      
1058 # endif
1059 #else /* !GRAN && !PAR */
1060   
1061     /* grab a thread from the run queue */
1062     ASSERT(run_queue_hd != END_TSO_QUEUE);
1063     t = POP_RUN_QUEUE();
1064     // Sanity check the thread we're about to run.  This can be
1065     // expensive if there is lots of thread switching going on...
1066     IF_DEBUG(sanity,checkTSO(t));
1067 #endif
1068
1069     cap->r.rCurrentTSO = t;
1070     
1071     /* context switches are now initiated by the timer signal, unless
1072      * the user specified "context switch as often as possible", with
1073      * +RTS -C0
1074      */
1075     if ((RtsFlags.ConcFlags.ctxtSwitchTicks == 0
1076          && (run_queue_hd != END_TSO_QUEUE
1077              || blocked_queue_hd != END_TSO_QUEUE
1078              || sleeping_queue != END_TSO_QUEUE)))
1079         context_switch = 1;
1080     else
1081         context_switch = 0;
1082
1083 run_thread:
1084
1085     RELEASE_LOCK(&sched_mutex);
1086
1087     IF_DEBUG(scheduler, sched_belch("-->> running thread %ld %s ...", 
1088                               t->id, whatNext_strs[t->what_next]));
1089
1090 #ifdef PROFILING
1091     startHeapProfTimer();
1092 #endif
1093
1094     /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1095     /* Run the current thread 
1096      */
1097     prev_what_next = t->what_next;
1098     switch (prev_what_next) {
1099     case ThreadKilled:
1100     case ThreadComplete:
1101         /* Thread already finished, return to scheduler. */
1102         ret = ThreadFinished;
1103         break;
1104     case ThreadRunGHC:
1105         ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
1106         break;
1107     case ThreadInterpret:
1108         ret = interpretBCO(cap);
1109         break;
1110     default:
1111       barf("schedule: invalid what_next field");
1112     }
1113     /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
1114     
1115     /* Costs for the scheduler are assigned to CCS_SYSTEM */
1116 #ifdef PROFILING
1117     stopHeapProfTimer();
1118     CCCS = CCS_SYSTEM;
1119 #endif
1120     
1121     ACQUIRE_LOCK(&sched_mutex);
1122     
1123 #ifdef RTS_SUPPORTS_THREADS
1124     IF_DEBUG(scheduler,fprintf(stderr,"scheduler (task %ld): ", osThreadId()););
1125 #elif !defined(GRAN) && !defined(PAR)
1126     IF_DEBUG(scheduler,fprintf(stderr,"scheduler: "););
1127 #endif
1128     t = cap->r.rCurrentTSO;
1129     
1130 #if defined(PAR)
1131     /* HACK 675: if the last thread didn't yield, make sure to print a 
1132        SCHEDULE event to the log file when StgRunning the next thread, even
1133        if it is the same one as before */
1134     LastTSO = t; 
1135     TimeOfLastYield = CURRENT_TIME;
1136 #endif
1137
1138     switch (ret) {
1139     case HeapOverflow:
1140 #if defined(GRAN)
1141       IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
1142       globalGranStats.tot_heapover++;
1143 #elif defined(PAR)
1144       globalParStats.tot_heapover++;
1145 #endif
1146
1147       // did the task ask for a large block?
1148       if (cap->r.rHpAlloc > BLOCK_SIZE_W) {
1149           // if so, get one and push it on the front of the nursery.
1150           bdescr *bd;
1151           nat blocks;
1152           
1153           blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc * sizeof(W_)) / BLOCK_SIZE;
1154
1155           IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped: requesting a large block (size %d)", 
1156                                    t->id, whatNext_strs[t->what_next], blocks));
1157
1158           // don't do this if it would push us over the
1159           // alloc_blocks_lim limit; we'll GC first.
1160           if (alloc_blocks + blocks < alloc_blocks_lim) {
1161
1162               alloc_blocks += blocks;
1163               bd = allocGroup( blocks );
1164
1165               // link the new group into the list
1166               bd->link = cap->r.rCurrentNursery;
1167               bd->u.back = cap->r.rCurrentNursery->u.back;
1168               if (cap->r.rCurrentNursery->u.back != NULL) {
1169                   cap->r.rCurrentNursery->u.back->link = bd;
1170               } else {
1171                   ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1172                          g0s0->blocks == cap->r.rNursery);
1173                   cap->r.rNursery = g0s0->blocks = bd;
1174               }           
1175               cap->r.rCurrentNursery->u.back = bd;
1176
1177               // initialise it as a nursery block.  We initialise the
1178               // step, gen_no, and flags field of *every* sub-block in
1179               // this large block, because this is easier than making
1180               // sure that we always find the block head of a large
1181               // block whenever we call Bdescr() (eg. evacuate() and
1182               // isAlive() in the GC would both have to do this, at
1183               // least).
1184               { 
1185                   bdescr *x;
1186                   for (x = bd; x < bd + blocks; x++) {
1187                       x->step = g0s0;
1188                       x->gen_no = 0;
1189                       x->flags = 0;
1190                   }
1191               }
1192
1193               // don't forget to update the block count in g0s0.
1194               g0s0->n_blocks += blocks;
1195               // This assert can be a killer if the app is doing lots
1196               // of large block allocations.
1197               ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1198
1199               // now update the nursery to point to the new block
1200               cap->r.rCurrentNursery = bd;
1201
1202               // we might be unlucky and have another thread get on the
1203               // run queue before us and steal the large block, but in that
1204               // case the thread will just end up requesting another large
1205               // block.
1206               PUSH_ON_RUN_QUEUE(t);
1207               break;
1208           }
1209       }
1210
1211       /* make all the running tasks block on a condition variable,
1212        * maybe set context_switch and wait till they all pile in,
1213        * then have them wait on a GC condition variable.
1214        */
1215       IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped: HeapOverflow", 
1216                                t->id, whatNext_strs[t->what_next]));
1217       threadPaused(t);
1218 #if defined(GRAN)
1219       ASSERT(!is_on_queue(t,CurrentProc));
1220 #elif defined(PAR)
1221       /* Currently we emit a DESCHEDULE event before GC in GUM.
1222          ToDo: either add separate event to distinguish SYSTEM time from rest
1223                or just nuke this DESCHEDULE (and the following SCHEDULE) */
1224       if (0 && RtsFlags.ParFlags.ParStats.Full) {
1225         DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1226                          GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1227         emitSchedule = rtsTrue;
1228       }
1229 #endif
1230       
1231       ready_to_gc = rtsTrue;
1232       context_switch = 1;               /* stop other threads ASAP */
1233       PUSH_ON_RUN_QUEUE(t);
1234       /* actual GC is done at the end of the while loop */
1235       break;
1236       
1237     case StackOverflow:
1238 #if defined(GRAN)
1239       IF_DEBUG(gran, 
1240                DumpGranEvent(GR_DESCHEDULE, t));
1241       globalGranStats.tot_stackover++;
1242 #elif defined(PAR)
1243       // IF_DEBUG(par, 
1244       // DumpGranEvent(GR_DESCHEDULE, t);
1245       globalParStats.tot_stackover++;
1246 #endif
1247       IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped, StackOverflow", 
1248                                t->id, whatNext_strs[t->what_next]));
1249       /* just adjust the stack for this thread, then pop it back
1250        * on the run queue.
1251        */
1252       threadPaused(t);
1253       { 
1254         StgMainThread *m;
1255         /* enlarge the stack */
1256         StgTSO *new_t = threadStackOverflow(t);
1257         
1258         /* This TSO has moved, so update any pointers to it from the
1259          * main thread stack.  It better not be on any other queues...
1260          * (it shouldn't be).
1261          */
1262         for (m = main_threads; m != NULL; m = m->link) {
1263           if (m->tso == t) {
1264             m->tso = new_t;
1265           }
1266         }
1267         threadPaused(new_t);
1268         PUSH_ON_RUN_QUEUE(new_t);
1269       }
1270       break;
1271
1272     case ThreadYielding:
1273 #if defined(GRAN)
1274       IF_DEBUG(gran, 
1275                DumpGranEvent(GR_DESCHEDULE, t));
1276       globalGranStats.tot_yields++;
1277 #elif defined(PAR)
1278       // IF_DEBUG(par, 
1279       // DumpGranEvent(GR_DESCHEDULE, t);
1280       globalParStats.tot_yields++;
1281 #endif
1282       /* put the thread back on the run queue.  Then, if we're ready to
1283        * GC, check whether this is the last task to stop.  If so, wake
1284        * up the GC thread.  getThread will block during a GC until the
1285        * GC is finished.
1286        */
1287       IF_DEBUG(scheduler,
1288                if (t->what_next != prev_what_next) {
1289                    belch("--<< thread %ld (%s) stopped to switch evaluators", 
1290                          t->id, whatNext_strs[t->what_next]);
1291                } else {
1292                    belch("--<< thread %ld (%s) stopped, yielding", 
1293                          t->id, whatNext_strs[t->what_next]);
1294                }
1295                );
1296
1297       IF_DEBUG(sanity,
1298                //belch("&& Doing sanity check on yielding TSO %ld.", t->id);
1299                checkTSO(t));
1300       ASSERT(t->link == END_TSO_QUEUE);
1301
1302       // Shortcut if we're just switching evaluators: don't bother
1303       // doing stack squeezing (which can be expensive), just run the
1304       // thread.
1305       if (t->what_next != prev_what_next) {
1306           goto run_thread;
1307       }
1308
1309       threadPaused(t);
1310
1311 #if defined(GRAN)
1312       ASSERT(!is_on_queue(t,CurrentProc));
1313
1314       IF_DEBUG(sanity,
1315                //belch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1316                checkThreadQsSanity(rtsTrue));
1317 #endif
1318
1319 #if defined(PAR)
1320       if (RtsFlags.ParFlags.doFairScheduling) { 
1321         /* this does round-robin scheduling; good for concurrency */
1322         APPEND_TO_RUN_QUEUE(t);
1323       } else {
1324         /* this does unfair scheduling; good for parallelism */
1325         PUSH_ON_RUN_QUEUE(t);
1326       }
1327 #else
1328       // this does round-robin scheduling; good for concurrency
1329       APPEND_TO_RUN_QUEUE(t);
1330 #endif
1331
1332 #if defined(GRAN)
1333       /* add a ContinueThread event to actually process the thread */
1334       new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1335                 ContinueThread,
1336                 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1337       IF_GRAN_DEBUG(bq, 
1338                belch("GRAN: eventq and runnableq after adding yielded thread to queue again:");
1339                G_EVENTQ(0);
1340                G_CURR_THREADQ(0));
1341 #endif /* GRAN */
1342       break;
1343
1344     case ThreadBlocked:
1345 #if defined(GRAN)
1346       IF_DEBUG(scheduler,
1347                belch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ", 
1348                                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)));
1349                if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1350
1351       // ??? needed; should emit block before
1352       IF_DEBUG(gran, 
1353                DumpGranEvent(GR_DESCHEDULE, t)); 
1354       prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1355       /*
1356         ngoq Dogh!
1357       ASSERT(procStatus[CurrentProc]==Busy || 
1358               ((procStatus[CurrentProc]==Fetching) && 
1359               (t->block_info.closure!=(StgClosure*)NULL)));
1360       if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1361           !(!RtsFlags.GranFlags.DoAsyncFetch &&
1362             procStatus[CurrentProc]==Fetching)) 
1363         procStatus[CurrentProc] = Idle;
1364       */
1365 #elif defined(PAR)
1366       IF_DEBUG(scheduler,
1367                belch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: ", 
1368                      t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1369       IF_PAR_DEBUG(bq,
1370
1371                    if (t->block_info.closure!=(StgClosure*)NULL) 
1372                      print_bq(t->block_info.closure));
1373
1374       /* Send a fetch (if BlockedOnGA) and dump event to log file */
1375       blockThread(t);
1376
1377       /* whatever we schedule next, we must log that schedule */
1378       emitSchedule = rtsTrue;
1379
1380 #else /* !GRAN */
1381       /* don't need to do anything.  Either the thread is blocked on
1382        * I/O, in which case we'll have called addToBlockedQueue
1383        * previously, or it's blocked on an MVar or Blackhole, in which
1384        * case it'll be on the relevant queue already.
1385        */
1386       IF_DEBUG(scheduler,
1387                fprintf(stderr, "--<< thread %d (%s) stopped: ", 
1388                        t->id, whatNext_strs[t->what_next]);
1389                printThreadBlockage(t);
1390                fprintf(stderr, "\n"));
1391
1392       /* Only for dumping event to log file 
1393          ToDo: do I need this in GranSim, too?
1394       blockThread(t);
1395       */
1396 #endif
1397       threadPaused(t);
1398       break;
1399       
1400     case ThreadFinished:
1401       /* Need to check whether this was a main thread, and if so, signal
1402        * the task that started it with the return value.  If we have no
1403        * more main threads, we probably need to stop all the tasks until
1404        * we get a new one.
1405        */
1406       /* We also end up here if the thread kills itself with an
1407        * uncaught exception, see Exception.hc.
1408        */
1409       IF_DEBUG(scheduler,belch("--++ thread %d (%s) finished", 
1410                                t->id, whatNext_strs[t->what_next]));
1411 #if defined(GRAN)
1412       endThread(t, CurrentProc); // clean-up the thread
1413 #elif defined(PAR)
1414       /* For now all are advisory -- HWL */
1415       //if(t->priority==AdvisoryPriority) ??
1416       advisory_thread_count--;
1417       
1418 # ifdef DIST
1419       if(t->dist.priority==RevalPriority)
1420         FinishReval(t);
1421 # endif
1422       
1423       if (RtsFlags.ParFlags.ParStats.Full &&
1424           !RtsFlags.ParFlags.ParStats.Suppressed) 
1425         DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1426 #endif
1427       break;
1428       
1429     default:
1430       barf("schedule: invalid thread return code %d", (int)ret);
1431     }
1432
1433 #ifdef PROFILING
1434     // When we have +RTS -i0 and we're heap profiling, do a census at
1435     // every GC.  This lets us get repeatable runs for debugging.
1436     if (performHeapProfile ||
1437         (RtsFlags.ProfFlags.profileInterval==0 &&
1438          RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1439         GarbageCollect(GetRoots, rtsTrue);
1440         heapCensus();
1441         performHeapProfile = rtsFalse;
1442         ready_to_gc = rtsFalse; // we already GC'd
1443     }
1444 #endif
1445
1446     if (ready_to_gc 
1447 #ifdef SMP
1448         && allFreeCapabilities() 
1449 #endif
1450         ) {
1451       /* everybody back, start the GC.
1452        * Could do it in this thread, or signal a condition var
1453        * to do it in another thread.  Either way, we need to
1454        * broadcast on gc_pending_cond afterward.
1455        */
1456 #if defined(RTS_SUPPORTS_THREADS)
1457       IF_DEBUG(scheduler,sched_belch("doing GC"));
1458 #endif
1459       GarbageCollect(GetRoots,rtsFalse);
1460       ready_to_gc = rtsFalse;
1461 #ifdef SMP
1462       broadcastCondition(&gc_pending_cond);
1463 #endif
1464 #if defined(GRAN)
1465       /* add a ContinueThread event to continue execution of current thread */
1466       new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1467                 ContinueThread,
1468                 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1469       IF_GRAN_DEBUG(bq, 
1470                fprintf(stderr, "GRAN: eventq and runnableq after Garbage collection:\n");
1471                G_EVENTQ(0);
1472                G_CURR_THREADQ(0));
1473 #endif /* GRAN */
1474     }
1475
1476 #if defined(GRAN)
1477   next_thread:
1478     IF_GRAN_DEBUG(unused,
1479                   print_eventq(EventHd));
1480
1481     event = get_next_event();
1482 #elif defined(PAR)
1483   next_thread:
1484     /* ToDo: wait for next message to arrive rather than busy wait */
1485 #endif /* GRAN */
1486
1487   } /* end of while(1) */
1488
1489   IF_PAR_DEBUG(verbose,
1490                belch("== Leaving schedule() after having received Finish"));
1491 }
1492
1493 /* ---------------------------------------------------------------------------
1494  * Singleton fork(). Do not copy any running threads.
1495  * ------------------------------------------------------------------------- */
1496
1497 StgInt forkProcess(StgTSO* tso) {
1498
1499 #ifndef mingw32_TARGET_OS
1500   pid_t pid;
1501   StgTSO* t,*next;
1502   StgMainThread *m;
1503   rtsBool doKill;
1504
1505   IF_DEBUG(scheduler,sched_belch("forking!"));
1506
1507   pid = fork();
1508   if (pid) { /* parent */
1509
1510   /* just return the pid */
1511     
1512   } else { /* child */
1513   /* wipe all other threads */
1514   run_queue_hd = run_queue_tl = tso;
1515   tso->link = END_TSO_QUEUE;
1516
1517   /* When clearing out the threads, we need to ensure
1518      that a 'main thread' is left behind; if there isn't,
1519      the Scheduler will shutdown next time it is entered.
1520      
1521      ==> we don't kill a thread that's on the main_threads
1522          list (nor the current thread.)
1523     
1524      [ Attempts at implementing the more ambitious scheme of
1525        killing the main_threads also, and then adding the
1526        current thread onto the main_threads list if it wasn't
1527        there already, failed -- waitThread() (for one) wasn't
1528        up to it. If it proves to be desirable to also kill
1529        the main threads, then this scheme will have to be
1530        revisited (and fully debugged!)
1531        
1532        -- sof 7/2002
1533      ]
1534   */
1535   /* DO NOT TOUCH THE QUEUES directly because most of the code around
1536      us is picky about finding the thread still in its queue when
1537      handling the deleteThread() */
1538
1539   for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1540     next = t->link;
1541     
1542     /* Don't kill the current thread.. */
1543     if (t->id == tso->id) continue;
1544     doKill=rtsTrue;
1545     /* ..or a main thread */
1546     for (m = main_threads; m != NULL; m = m->link) {
1547         if (m->tso->id == t->id) {
1548           doKill=rtsFalse;
1549           break;
1550         }
1551     }
1552     if (doKill) {
1553       deleteThread(t);
1554     }
1555   }
1556   }
1557   return pid;
1558 #else /* mingw32 */
1559   barf("forkProcess#: primop not implemented for mingw32, sorry! (%u)\n", tso->id);
1560   /* pointlessly printing out the TSOs 'id' to avoid CC unused warning. */
1561   return -1;
1562 #endif /* mingw32 */
1563 }
1564
1565 /* ---------------------------------------------------------------------------
1566  * deleteAllThreads():  kill all the live threads.
1567  *
1568  * This is used when we catch a user interrupt (^C), before performing
1569  * any necessary cleanups and running finalizers.
1570  *
1571  * Locks: sched_mutex held.
1572  * ------------------------------------------------------------------------- */
1573    
1574 void deleteAllThreads ( void )
1575 {
1576   StgTSO* t, *next;
1577   IF_DEBUG(scheduler,sched_belch("deleting all threads"));
1578   for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1579       next = t->global_link;
1580       deleteThread(t);
1581   }      
1582   run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1583   blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
1584   sleeping_queue = END_TSO_QUEUE;
1585 }
1586
1587 /* startThread and  insertThread are now in GranSim.c -- HWL */
1588
1589
1590 //@node Suspend and Resume, Run queue code, Main scheduling loop, Main scheduling code
1591 //@subsection Suspend and Resume
1592
1593 /* ---------------------------------------------------------------------------
1594  * Suspending & resuming Haskell threads.
1595  * 
1596  * When making a "safe" call to C (aka _ccall_GC), the task gives back
1597  * its capability before calling the C function.  This allows another
1598  * task to pick up the capability and carry on running Haskell
1599  * threads.  It also means that if the C call blocks, it won't lock
1600  * the whole system.
1601  *
1602  * The Haskell thread making the C call is put to sleep for the
1603  * duration of the call, on the susepended_ccalling_threads queue.  We
1604  * give out a token to the task, which it can use to resume the thread
1605  * on return from the C function.
1606  * ------------------------------------------------------------------------- */
1607    
1608 StgInt
1609 suspendThread( StgRegTable *reg, 
1610                rtsBool concCall
1611 #if !defined(RTS_SUPPORTS_THREADS) && !defined(DEBUG)
1612                STG_UNUSED
1613 #endif
1614                )
1615 {
1616   nat tok;
1617   Capability *cap;
1618
1619   /* assume that *reg is a pointer to the StgRegTable part
1620    * of a Capability.
1621    */
1622   cap = (Capability *)((void *)reg - sizeof(StgFunTable));
1623
1624   ACQUIRE_LOCK(&sched_mutex);
1625
1626   IF_DEBUG(scheduler,
1627            sched_belch("thread %d did a _ccall_gc (is_concurrent: %d)", cap->r.rCurrentTSO->id,concCall));
1628
1629   // XXX this might not be necessary --SDM
1630   cap->r.rCurrentTSO->what_next = ThreadRunGHC;
1631
1632   threadPaused(cap->r.rCurrentTSO);
1633   cap->r.rCurrentTSO->link = suspended_ccalling_threads;
1634   suspended_ccalling_threads = cap->r.rCurrentTSO;
1635
1636 #if defined(RTS_SUPPORTS_THREADS)
1637   if(cap->r.rCurrentTSO->blocked_exceptions == NULL)
1638   {
1639       cap->r.rCurrentTSO->why_blocked = BlockedOnCCall;
1640       cap->r.rCurrentTSO->blocked_exceptions = END_TSO_QUEUE;
1641   }
1642   else
1643   {
1644       cap->r.rCurrentTSO->why_blocked = BlockedOnCCall_NoUnblockExc;
1645   }
1646 #endif
1647
1648   /* Use the thread ID as the token; it should be unique */
1649   tok = cap->r.rCurrentTSO->id;
1650
1651   /* Hand back capability */
1652   releaseCapability(cap);
1653   
1654 #if defined(RTS_SUPPORTS_THREADS)
1655   /* Preparing to leave the RTS, so ensure there's a native thread/task
1656      waiting to take over.
1657   */
1658   IF_DEBUG(scheduler, sched_belch("worker thread (%d, osthread %p): leaving RTS", tok, osThreadId()));
1659   //if (concCall) { // implementing "safe" as opposed to "threadsafe" is more difficult
1660       startTask(taskStart);
1661   //}
1662 #endif
1663
1664   /* Other threads _might_ be available for execution; signal this */
1665   THREAD_RUNNABLE();
1666   RELEASE_LOCK(&sched_mutex);
1667   return tok; 
1668 }
1669
1670 StgRegTable *
1671 resumeThread( StgInt tok,
1672               rtsBool concCall
1673 #if !defined(RTS_SUPPORTS_THREADS)
1674                STG_UNUSED
1675 #endif
1676               )
1677 {
1678   StgTSO *tso, **prev;
1679   Capability *cap;
1680
1681 #if defined(RTS_SUPPORTS_THREADS)
1682   /* Wait for permission to re-enter the RTS with the result. */
1683   ACQUIRE_LOCK(&sched_mutex);
1684   grabReturnCapability(&sched_mutex, &cap);
1685
1686   IF_DEBUG(scheduler, sched_belch("worker thread (%d, osthread %p): re-entering RTS", tok, osThreadId()));
1687 #else
1688   grabCapability(&cap);
1689 #endif
1690
1691   /* Remove the thread off of the suspended list */
1692   prev = &suspended_ccalling_threads;
1693   for (tso = suspended_ccalling_threads; 
1694        tso != END_TSO_QUEUE; 
1695        prev = &tso->link, tso = tso->link) {
1696     if (tso->id == (StgThreadID)tok) {
1697       *prev = tso->link;
1698       break;
1699     }
1700   }
1701   if (tso == END_TSO_QUEUE) {
1702     barf("resumeThread: thread not found");
1703   }
1704   tso->link = END_TSO_QUEUE;
1705   
1706 #if defined(RTS_SUPPORTS_THREADS)
1707   if(tso->why_blocked == BlockedOnCCall)
1708   {
1709       awakenBlockedQueueNoLock(tso->blocked_exceptions);
1710       tso->blocked_exceptions = NULL;
1711   }
1712 #endif
1713   
1714   /* Reset blocking status */
1715   tso->why_blocked  = NotBlocked;
1716
1717   cap->r.rCurrentTSO = tso;
1718 #if defined(RTS_SUPPORTS_THREADS)
1719   RELEASE_LOCK(&sched_mutex);
1720 #endif
1721   return &cap->r;
1722 }
1723
1724
1725 /* ---------------------------------------------------------------------------
1726  * Static functions
1727  * ------------------------------------------------------------------------ */
1728 static void unblockThread(StgTSO *tso);
1729
1730 /* ---------------------------------------------------------------------------
1731  * Comparing Thread ids.
1732  *
1733  * This is used from STG land in the implementation of the
1734  * instances of Eq/Ord for ThreadIds.
1735  * ------------------------------------------------------------------------ */
1736
1737 int
1738 cmp_thread(StgPtr tso1, StgPtr tso2) 
1739
1740   StgThreadID id1 = ((StgTSO *)tso1)->id; 
1741   StgThreadID id2 = ((StgTSO *)tso2)->id;
1742  
1743   if (id1 < id2) return (-1);
1744   if (id1 > id2) return 1;
1745   return 0;
1746 }
1747
1748 /* ---------------------------------------------------------------------------
1749  * Fetching the ThreadID from an StgTSO.
1750  *
1751  * This is used in the implementation of Show for ThreadIds.
1752  * ------------------------------------------------------------------------ */
1753 int
1754 rts_getThreadId(StgPtr tso) 
1755 {
1756   return ((StgTSO *)tso)->id;
1757 }
1758
1759 #ifdef DEBUG
1760 void
1761 labelThread(StgPtr tso, char *label)
1762 {
1763   int len;
1764   void *buf;
1765
1766   /* Caveat: Once set, you can only set the thread name to "" */
1767   len = strlen(label)+1;
1768   buf = stgMallocBytes(len * sizeof(char), "Schedule.c:labelThread()");
1769   strncpy(buf,label,len);
1770   /* Update will free the old memory for us */
1771   updateThreadLabel((StgWord)tso,buf);
1772 }
1773 #endif /* DEBUG */
1774
1775 /* ---------------------------------------------------------------------------
1776    Create a new thread.
1777
1778    The new thread starts with the given stack size.  Before the
1779    scheduler can run, however, this thread needs to have a closure
1780    (and possibly some arguments) pushed on its stack.  See
1781    pushClosure() in Schedule.h.
1782
1783    createGenThread() and createIOThread() (in SchedAPI.h) are
1784    convenient packaged versions of this function.
1785
1786    currently pri (priority) is only used in a GRAN setup -- HWL
1787    ------------------------------------------------------------------------ */
1788 //@cindex createThread
1789 #if defined(GRAN)
1790 /*   currently pri (priority) is only used in a GRAN setup -- HWL */
1791 StgTSO *
1792 createThread(nat size, StgInt pri)
1793 #else
1794 StgTSO *
1795 createThread(nat size)
1796 #endif
1797 {
1798
1799     StgTSO *tso;
1800     nat stack_size;
1801
1802     /* First check whether we should create a thread at all */
1803 #if defined(PAR)
1804   /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1805   if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1806     threadsIgnored++;
1807     belch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1808           RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1809     return END_TSO_QUEUE;
1810   }
1811   threadsCreated++;
1812 #endif
1813
1814 #if defined(GRAN)
1815   ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
1816 #endif
1817
1818   // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
1819
1820   /* catch ridiculously small stack sizes */
1821   if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
1822     size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
1823   }
1824
1825   stack_size = size - TSO_STRUCT_SIZEW;
1826
1827   tso = (StgTSO *)allocate(size);
1828   TICK_ALLOC_TSO(stack_size, 0);
1829
1830   SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
1831 #if defined(GRAN)
1832   SET_GRAN_HDR(tso, ThisPE);
1833 #endif
1834
1835   // Always start with the compiled code evaluator
1836   tso->what_next = ThreadRunGHC;
1837
1838   /* tso->id needs to be unique.  For now we use a heavyweight mutex to
1839    * protect the increment operation on next_thread_id.
1840    * In future, we could use an atomic increment instead.
1841    */
1842   ACQUIRE_LOCK(&thread_id_mutex);
1843   tso->id = next_thread_id++; 
1844   RELEASE_LOCK(&thread_id_mutex);
1845
1846   tso->why_blocked  = NotBlocked;
1847   tso->blocked_exceptions = NULL;
1848
1849   tso->stack_size   = stack_size;
1850   tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize) 
1851                               - TSO_STRUCT_SIZEW;
1852   tso->sp           = (P_)&(tso->stack) + stack_size;
1853
1854 #ifdef PROFILING
1855   tso->prof.CCCS = CCS_MAIN;
1856 #endif
1857
1858   /* put a stop frame on the stack */
1859   tso->sp -= sizeofW(StgStopFrame);
1860   SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
1861   // ToDo: check this
1862 #if defined(GRAN)
1863   tso->link = END_TSO_QUEUE;
1864   /* uses more flexible routine in GranSim */
1865   insertThread(tso, CurrentProc);
1866 #else
1867   /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
1868    * from its creation
1869    */
1870 #endif
1871
1872 #if defined(GRAN) 
1873   if (RtsFlags.GranFlags.GranSimStats.Full) 
1874     DumpGranEvent(GR_START,tso);
1875 #elif defined(PAR)
1876   if (RtsFlags.ParFlags.ParStats.Full) 
1877     DumpGranEvent(GR_STARTQ,tso);
1878   /* HACk to avoid SCHEDULE 
1879      LastTSO = tso; */
1880 #endif
1881
1882   /* Link the new thread on the global thread list.
1883    */
1884   tso->global_link = all_threads;
1885   all_threads = tso;
1886
1887 #if defined(DIST)
1888   tso->dist.priority = MandatoryPriority; //by default that is...
1889 #endif
1890
1891 #if defined(GRAN)
1892   tso->gran.pri = pri;
1893 # if defined(DEBUG)
1894   tso->gran.magic = TSO_MAGIC; // debugging only
1895 # endif
1896   tso->gran.sparkname   = 0;
1897   tso->gran.startedat   = CURRENT_TIME; 
1898   tso->gran.exported    = 0;
1899   tso->gran.basicblocks = 0;
1900   tso->gran.allocs      = 0;
1901   tso->gran.exectime    = 0;
1902   tso->gran.fetchtime   = 0;
1903   tso->gran.fetchcount  = 0;
1904   tso->gran.blocktime   = 0;
1905   tso->gran.blockcount  = 0;
1906   tso->gran.blockedat   = 0;
1907   tso->gran.globalsparks = 0;
1908   tso->gran.localsparks  = 0;
1909   if (RtsFlags.GranFlags.Light)
1910     tso->gran.clock  = Now; /* local clock */
1911   else
1912     tso->gran.clock  = 0;
1913
1914   IF_DEBUG(gran,printTSO(tso));
1915 #elif defined(PAR)
1916 # if defined(DEBUG)
1917   tso->par.magic = TSO_MAGIC; // debugging only
1918 # endif
1919   tso->par.sparkname   = 0;
1920   tso->par.startedat   = CURRENT_TIME; 
1921   tso->par.exported    = 0;
1922   tso->par.basicblocks = 0;
1923   tso->par.allocs      = 0;
1924   tso->par.exectime    = 0;
1925   tso->par.fetchtime   = 0;
1926   tso->par.fetchcount  = 0;
1927   tso->par.blocktime   = 0;
1928   tso->par.blockcount  = 0;
1929   tso->par.blockedat   = 0;
1930   tso->par.globalsparks = 0;
1931   tso->par.localsparks  = 0;
1932 #endif
1933
1934 #if defined(GRAN)
1935   globalGranStats.tot_threads_created++;
1936   globalGranStats.threads_created_on_PE[CurrentProc]++;
1937   globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
1938   globalGranStats.tot_sq_probes++;
1939 #elif defined(PAR)
1940   // collect parallel global statistics (currently done together with GC stats)
1941   if (RtsFlags.ParFlags.ParStats.Global &&
1942       RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1943     //fprintf(stderr, "Creating thread %d @ %11.2f\n", tso->id, usertime()); 
1944     globalParStats.tot_threads_created++;
1945   }
1946 #endif 
1947
1948 #if defined(GRAN)
1949   IF_GRAN_DEBUG(pri,
1950                 belch("==__ schedule: Created TSO %d (%p);",
1951                       CurrentProc, tso, tso->id));
1952 #elif defined(PAR)
1953     IF_PAR_DEBUG(verbose,
1954                  belch("==__ schedule: Created TSO %d (%p); %d threads active",
1955                        tso->id, tso, advisory_thread_count));
1956 #else
1957   IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words", 
1958                                  tso->id, tso->stack_size));
1959 #endif    
1960   return tso;
1961 }
1962
1963 #if defined(PAR)
1964 /* RFP:
1965    all parallel thread creation calls should fall through the following routine.
1966 */
1967 StgTSO *
1968 createSparkThread(rtsSpark spark) 
1969 { StgTSO *tso;
1970   ASSERT(spark != (rtsSpark)NULL);
1971   if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) 
1972   { threadsIgnored++;
1973     barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1974           RtsFlags.ParFlags.maxThreads, advisory_thread_count);    
1975     return END_TSO_QUEUE;
1976   }
1977   else
1978   { threadsCreated++;
1979     tso = createThread(RtsFlags.GcFlags.initialStkSize);
1980     if (tso==END_TSO_QUEUE)     
1981       barf("createSparkThread: Cannot create TSO");
1982 #if defined(DIST)
1983     tso->priority = AdvisoryPriority;
1984 #endif
1985     pushClosure(tso,spark);
1986     PUSH_ON_RUN_QUEUE(tso);
1987     advisory_thread_count++;    
1988   }
1989   return tso;
1990 }
1991 #endif
1992
1993 /*
1994   Turn a spark into a thread.
1995   ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
1996 */
1997 #if defined(PAR)
1998 //@cindex activateSpark
1999 StgTSO *
2000 activateSpark (rtsSpark spark) 
2001 {
2002   StgTSO *tso;
2003
2004   tso = createSparkThread(spark);
2005   if (RtsFlags.ParFlags.ParStats.Full) {   
2006     //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
2007     IF_PAR_DEBUG(verbose,
2008                  belch("==^^ activateSpark: turning spark of closure %p (%s) into a thread",
2009                        (StgClosure *)spark, info_type((StgClosure *)spark)));
2010   }
2011   // ToDo: fwd info on local/global spark to thread -- HWL
2012   // tso->gran.exported =  spark->exported;
2013   // tso->gran.locked =   !spark->global;
2014   // tso->gran.sparkname = spark->name;
2015
2016   return tso;
2017 }
2018 #endif
2019
2020 static SchedulerStatus waitThread_(/*out*/StgMainThread* m
2021 #if defined(THREADED_RTS)
2022                                    , rtsBool blockWaiting
2023 #endif
2024                                    );
2025
2026
2027 /* ---------------------------------------------------------------------------
2028  * scheduleThread()
2029  *
2030  * scheduleThread puts a thread on the head of the runnable queue.
2031  * This will usually be done immediately after a thread is created.
2032  * The caller of scheduleThread must create the thread using e.g.
2033  * createThread and push an appropriate closure
2034  * on this thread's stack before the scheduler is invoked.
2035  * ------------------------------------------------------------------------ */
2036
2037 static void scheduleThread_ (StgTSO* tso);
2038
2039 void
2040 scheduleThread_(StgTSO *tso)
2041 {
2042   // Precondition: sched_mutex must be held.
2043
2044   /* Put the new thread on the head of the runnable queue.  The caller
2045    * better push an appropriate closure on this thread's stack
2046    * beforehand.  In the SMP case, the thread may start running as
2047    * soon as we release the scheduler lock below.
2048    */
2049   PUSH_ON_RUN_QUEUE(tso);
2050   THREAD_RUNNABLE();
2051
2052 #if 0
2053   IF_DEBUG(scheduler,printTSO(tso));
2054 #endif
2055 }
2056
2057 void scheduleThread(StgTSO* tso)
2058 {
2059   ACQUIRE_LOCK(&sched_mutex);
2060   scheduleThread_(tso);
2061   RELEASE_LOCK(&sched_mutex);
2062 }
2063
2064 SchedulerStatus
2065 scheduleWaitThread(StgTSO* tso, /*[out]*/HaskellObj* ret)
2066 {       // Precondition: sched_mutex must be held
2067   StgMainThread *m;
2068
2069   m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2070   m->tso = tso;
2071   m->ret = ret;
2072   m->stat = NoStatus;
2073 #if defined(RTS_SUPPORTS_THREADS)
2074   initCondition(&m->wakeup);
2075 #endif
2076
2077   /* Put the thread on the main-threads list prior to scheduling the TSO.
2078      Failure to do so introduces a race condition in the MT case (as
2079      identified by Wolfgang Thaller), whereby the new task/OS thread 
2080      created by scheduleThread_() would complete prior to the thread
2081      that spawned it managed to put 'itself' on the main-threads list.
2082      The upshot of it all being that the worker thread wouldn't get to
2083      signal the completion of the its work item for the main thread to
2084      see (==> it got stuck waiting.)    -- sof 6/02.
2085   */
2086   IF_DEBUG(scheduler, sched_belch("waiting for thread (%d)\n", tso->id));
2087   
2088   m->link = main_threads;
2089   main_threads = m;
2090
2091   scheduleThread_(tso);
2092 #if defined(THREADED_RTS)
2093   return waitThread_(m, rtsTrue);
2094 #else
2095   return waitThread_(m);
2096 #endif
2097 }
2098
2099 /* ---------------------------------------------------------------------------
2100  * initScheduler()
2101  *
2102  * Initialise the scheduler.  This resets all the queues - if the
2103  * queues contained any threads, they'll be garbage collected at the
2104  * next pass.
2105  *
2106  * ------------------------------------------------------------------------ */
2107
2108 #ifdef SMP
2109 static void
2110 term_handler(int sig STG_UNUSED)
2111 {
2112   stat_workerStop();
2113   ACQUIRE_LOCK(&term_mutex);
2114   await_death--;
2115   RELEASE_LOCK(&term_mutex);
2116   shutdownThread();
2117 }
2118 #endif
2119
2120 void 
2121 initScheduler(void)
2122 {
2123 #if defined(GRAN)
2124   nat i;
2125
2126   for (i=0; i<=MAX_PROC; i++) {
2127     run_queue_hds[i]      = END_TSO_QUEUE;
2128     run_queue_tls[i]      = END_TSO_QUEUE;
2129     blocked_queue_hds[i]  = END_TSO_QUEUE;
2130     blocked_queue_tls[i]  = END_TSO_QUEUE;
2131     ccalling_threadss[i]  = END_TSO_QUEUE;
2132     sleeping_queue        = END_TSO_QUEUE;
2133   }
2134 #else
2135   run_queue_hd      = END_TSO_QUEUE;
2136   run_queue_tl      = END_TSO_QUEUE;
2137   blocked_queue_hd  = END_TSO_QUEUE;
2138   blocked_queue_tl  = END_TSO_QUEUE;
2139   sleeping_queue    = END_TSO_QUEUE;
2140 #endif 
2141
2142   suspended_ccalling_threads  = END_TSO_QUEUE;
2143
2144   main_threads = NULL;
2145   all_threads  = END_TSO_QUEUE;
2146
2147   context_switch = 0;
2148   interrupted    = 0;
2149
2150   RtsFlags.ConcFlags.ctxtSwitchTicks =
2151       RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
2152       
2153 #if defined(RTS_SUPPORTS_THREADS)
2154   /* Initialise the mutex and condition variables used by
2155    * the scheduler. */
2156   initMutex(&sched_mutex);
2157   initMutex(&term_mutex);
2158   initMutex(&thread_id_mutex);
2159
2160   initCondition(&thread_ready_cond);
2161 #endif
2162   
2163 #if defined(SMP)
2164   initCondition(&gc_pending_cond);
2165 #endif
2166
2167 #if defined(RTS_SUPPORTS_THREADS)
2168   ACQUIRE_LOCK(&sched_mutex);
2169 #endif
2170
2171   /* Install the SIGHUP handler */
2172 #if defined(SMP)
2173   {
2174     struct sigaction action,oact;
2175
2176     action.sa_handler = term_handler;
2177     sigemptyset(&action.sa_mask);
2178     action.sa_flags = 0;
2179     if (sigaction(SIGTERM, &action, &oact) != 0) {
2180       barf("can't install TERM handler");
2181     }
2182   }
2183 #endif
2184
2185   /* A capability holds the state a native thread needs in
2186    * order to execute STG code. At least one capability is
2187    * floating around (only SMP builds have more than one).
2188    */
2189   initCapabilities();
2190   
2191 #if defined(RTS_SUPPORTS_THREADS)
2192     /* start our haskell execution tasks */
2193 # if defined(SMP)
2194     startTaskManager(RtsFlags.ParFlags.nNodes, taskStart);
2195 # else
2196     startTaskManager(0,taskStart);
2197 # endif
2198 #endif
2199
2200 #if /* defined(SMP) ||*/ defined(PAR)
2201   initSparkPools();
2202 #endif
2203
2204 #if defined(RTS_SUPPORTS_THREADS)
2205   RELEASE_LOCK(&sched_mutex);
2206 #endif
2207
2208 }
2209
2210 void
2211 exitScheduler( void )
2212 {
2213 #if defined(RTS_SUPPORTS_THREADS)
2214   stopTaskManager();
2215 #endif
2216   shutting_down_scheduler = rtsTrue;
2217 }
2218
2219 /* -----------------------------------------------------------------------------
2220    Managing the per-task allocation areas.
2221    
2222    Each capability comes with an allocation area.  These are
2223    fixed-length block lists into which allocation can be done.
2224
2225    ToDo: no support for two-space collection at the moment???
2226    -------------------------------------------------------------------------- */
2227
2228 /* -----------------------------------------------------------------------------
2229  * waitThread is the external interface for running a new computation
2230  * and waiting for the result.
2231  *
2232  * In the non-SMP case, we create a new main thread, push it on the 
2233  * main-thread stack, and invoke the scheduler to run it.  The
2234  * scheduler will return when the top main thread on the stack has
2235  * completed or died, and fill in the necessary fields of the
2236  * main_thread structure.
2237  *
2238  * In the SMP case, we create a main thread as before, but we then
2239  * create a new condition variable and sleep on it.  When our new
2240  * main thread has completed, we'll be woken up and the status/result
2241  * will be in the main_thread struct.
2242  * -------------------------------------------------------------------------- */
2243
2244 int 
2245 howManyThreadsAvail ( void )
2246 {
2247    int i = 0;
2248    StgTSO* q;
2249    for (q = run_queue_hd; q != END_TSO_QUEUE; q = q->link)
2250       i++;
2251    for (q = blocked_queue_hd; q != END_TSO_QUEUE; q = q->link)
2252       i++;
2253    for (q = sleeping_queue; q != END_TSO_QUEUE; q = q->link)
2254       i++;
2255    return i;
2256 }
2257
2258 void
2259 finishAllThreads ( void )
2260 {
2261    do {
2262       while (run_queue_hd != END_TSO_QUEUE) {
2263          waitThread ( run_queue_hd, NULL);
2264       }
2265       while (blocked_queue_hd != END_TSO_QUEUE) {
2266          waitThread ( blocked_queue_hd, NULL);
2267       }
2268       while (sleeping_queue != END_TSO_QUEUE) {
2269          waitThread ( blocked_queue_hd, NULL);
2270       }
2271    } while 
2272       (blocked_queue_hd != END_TSO_QUEUE || 
2273        run_queue_hd     != END_TSO_QUEUE ||
2274        sleeping_queue   != END_TSO_QUEUE);
2275 }
2276
2277 SchedulerStatus
2278 waitThread(StgTSO *tso, /*out*/StgClosure **ret)
2279
2280   StgMainThread *m;
2281   SchedulerStatus stat;
2282
2283   m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2284   m->tso = tso;
2285   m->ret = ret;
2286   m->stat = NoStatus;
2287 #if defined(RTS_SUPPORTS_THREADS)
2288   initCondition(&m->wakeup);
2289 #endif
2290
2291   /* see scheduleWaitThread() comment */
2292   ACQUIRE_LOCK(&sched_mutex);
2293   m->link = main_threads;
2294   main_threads = m;
2295
2296   IF_DEBUG(scheduler, sched_belch("waiting for thread %d", tso->id));
2297 #if defined(THREADED_RTS)
2298   stat = waitThread_(m, rtsFalse);
2299 #else
2300   stat = waitThread_(m);
2301 #endif
2302   RELEASE_LOCK(&sched_mutex);
2303   return stat;
2304 }
2305
2306 static
2307 SchedulerStatus
2308 waitThread_(StgMainThread* m
2309 #if defined(THREADED_RTS)
2310             , rtsBool blockWaiting
2311 #endif
2312            )
2313 {
2314   SchedulerStatus stat;
2315
2316   // Precondition: sched_mutex must be held.
2317   IF_DEBUG(scheduler, sched_belch("== scheduler: new main thread (%d)\n", m->tso->id));
2318
2319 #if defined(RTS_SUPPORTS_THREADS)
2320
2321 # if defined(THREADED_RTS)
2322   if (!blockWaiting) {
2323     /* In the threaded case, the OS thread that called main()
2324      * gets to enter the RTS directly without going via another
2325      * task/thread.
2326      */
2327     main_main_thread = m;
2328     RELEASE_LOCK(&sched_mutex);
2329     schedule();
2330     ACQUIRE_LOCK(&sched_mutex);
2331     main_main_thread = NULL;
2332     ASSERT(m->stat != NoStatus);
2333   } else 
2334 # endif
2335   {
2336     do {
2337       waitCondition(&m->wakeup, &sched_mutex);
2338     } while (m->stat == NoStatus);
2339   }
2340 #elif defined(GRAN)
2341   /* GranSim specific init */
2342   CurrentTSO = m->tso;                // the TSO to run
2343   procStatus[MainProc] = Busy;        // status of main PE
2344   CurrentProc = MainProc;             // PE to run it on
2345
2346   RELEASE_LOCK(&sched_mutex);
2347   schedule();
2348 #else
2349   RELEASE_LOCK(&sched_mutex);
2350   schedule();
2351   ASSERT(m->stat != NoStatus);
2352 #endif
2353
2354   stat = m->stat;
2355
2356 #if defined(RTS_SUPPORTS_THREADS)
2357   closeCondition(&m->wakeup);
2358 #endif
2359
2360   IF_DEBUG(scheduler, fprintf(stderr, "== scheduler: main thread (%d) finished\n", 
2361                               m->tso->id));
2362   stgFree(m);
2363
2364   // Postcondition: sched_mutex still held
2365   return stat;
2366 }
2367
2368 //@node Run queue code, Garbage Collextion Routines, Suspend and Resume, Main scheduling code
2369 //@subsection Run queue code 
2370
2371 #if 0
2372 /* 
2373    NB: In GranSim we have many run queues; run_queue_hd is actually a macro
2374        unfolding to run_queue_hds[CurrentProc], thus CurrentProc is an
2375        implicit global variable that has to be correct when calling these
2376        fcts -- HWL 
2377 */
2378
2379 /* Put the new thread on the head of the runnable queue.
2380  * The caller of createThread better push an appropriate closure
2381  * on this thread's stack before the scheduler is invoked.
2382  */
2383 static /* inline */ void
2384 add_to_run_queue(tso)
2385 StgTSO* tso; 
2386 {
2387   ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2388   tso->link = run_queue_hd;
2389   run_queue_hd = tso;
2390   if (run_queue_tl == END_TSO_QUEUE) {
2391     run_queue_tl = tso;
2392   }
2393 }
2394
2395 /* Put the new thread at the end of the runnable queue. */
2396 static /* inline */ void
2397 push_on_run_queue(tso)
2398 StgTSO* tso; 
2399 {
2400   ASSERT(get_itbl((StgClosure *)tso)->type == TSO);
2401   ASSERT(run_queue_hd!=NULL && run_queue_tl!=NULL);
2402   ASSERT(tso!=run_queue_hd && tso!=run_queue_tl);
2403   if (run_queue_hd == END_TSO_QUEUE) {
2404     run_queue_hd = tso;
2405   } else {
2406     run_queue_tl->link = tso;
2407   }
2408   run_queue_tl = tso;
2409 }
2410
2411 /* 
2412    Should be inlined because it's used very often in schedule.  The tso
2413    argument is actually only needed in GranSim, where we want to have the
2414    possibility to schedule *any* TSO on the run queue, irrespective of the
2415    actual ordering. Therefore, if tso is not the nil TSO then we traverse
2416    the run queue and dequeue the tso, adjusting the links in the queue. 
2417 */
2418 //@cindex take_off_run_queue
2419 static /* inline */ StgTSO*
2420 take_off_run_queue(StgTSO *tso) {
2421   StgTSO *t, *prev;
2422
2423   /* 
2424      qetlaHbogh Qu' ngaSbogh ghomDaQ {tso} yIteq!
2425
2426      if tso is specified, unlink that tso from the run_queue (doesn't have
2427      to be at the beginning of the queue); GranSim only 
2428   */
2429   if (tso!=END_TSO_QUEUE) {
2430     /* find tso in queue */
2431     for (t=run_queue_hd, prev=END_TSO_QUEUE; 
2432          t!=END_TSO_QUEUE && t!=tso;
2433          prev=t, t=t->link) 
2434       /* nothing */ ;
2435     ASSERT(t==tso);
2436     /* now actually dequeue the tso */
2437     if (prev!=END_TSO_QUEUE) {
2438       ASSERT(run_queue_hd!=t);
2439       prev->link = t->link;
2440     } else {
2441       /* t is at beginning of thread queue */
2442       ASSERT(run_queue_hd==t);
2443       run_queue_hd = t->link;
2444     }
2445     /* t is at end of thread queue */
2446     if (t->link==END_TSO_QUEUE) {
2447       ASSERT(t==run_queue_tl);
2448       run_queue_tl = prev;
2449     } else {
2450       ASSERT(run_queue_tl!=t);
2451     }
2452     t->link = END_TSO_QUEUE;
2453   } else {
2454     /* take tso from the beginning of the queue; std concurrent code */
2455     t = run_queue_hd;
2456     if (t != END_TSO_QUEUE) {
2457       run_queue_hd = t->link;
2458       t->link = END_TSO_QUEUE;
2459       if (run_queue_hd == END_TSO_QUEUE) {
2460         run_queue_tl = END_TSO_QUEUE;
2461       }
2462     }
2463   }
2464   return t;
2465 }
2466
2467 #endif /* 0 */
2468
2469 //@node Garbage Collextion Routines, Blocking Queue Routines, Run queue code, Main scheduling code
2470 //@subsection Garbage Collextion Routines
2471
2472 /* ---------------------------------------------------------------------------
2473    Where are the roots that we know about?
2474
2475         - all the threads on the runnable queue
2476         - all the threads on the blocked queue
2477         - all the threads on the sleeping queue
2478         - all the thread currently executing a _ccall_GC
2479         - all the "main threads"
2480      
2481    ------------------------------------------------------------------------ */
2482
2483 /* This has to be protected either by the scheduler monitor, or by the
2484         garbage collection monitor (probably the latter).
2485         KH @ 25/10/99
2486 */
2487
2488 void
2489 GetRoots(evac_fn evac)
2490 {
2491 #if defined(GRAN)
2492   {
2493     nat i;
2494     for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2495       if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2496           evac((StgClosure **)&run_queue_hds[i]);
2497       if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2498           evac((StgClosure **)&run_queue_tls[i]);
2499       
2500       if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2501           evac((StgClosure **)&blocked_queue_hds[i]);
2502       if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2503           evac((StgClosure **)&blocked_queue_tls[i]);
2504       if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2505           evac((StgClosure **)&ccalling_threads[i]);
2506     }
2507   }
2508
2509   markEventQueue();
2510
2511 #else /* !GRAN */
2512   if (run_queue_hd != END_TSO_QUEUE) {
2513       ASSERT(run_queue_tl != END_TSO_QUEUE);
2514       evac((StgClosure **)&run_queue_hd);
2515       evac((StgClosure **)&run_queue_tl);
2516   }
2517   
2518   if (blocked_queue_hd != END_TSO_QUEUE) {
2519       ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2520       evac((StgClosure **)&blocked_queue_hd);
2521       evac((StgClosure **)&blocked_queue_tl);
2522   }
2523   
2524   if (sleeping_queue != END_TSO_QUEUE) {
2525       evac((StgClosure **)&sleeping_queue);
2526   }
2527 #endif 
2528
2529   if (suspended_ccalling_threads != END_TSO_QUEUE) {
2530       evac((StgClosure **)&suspended_ccalling_threads);
2531   }
2532
2533 #if defined(PAR) || defined(GRAN)
2534   markSparkQueue(evac);
2535 #endif
2536
2537 #ifndef mingw32_TARGET_OS
2538   // mark the signal handlers (signals should be already blocked)
2539   markSignalHandlers(evac);
2540 #endif
2541
2542   // main threads which have completed need to be retained until they
2543   // are dealt with in the main scheduler loop.  They won't be
2544   // retained any other way: the GC will drop them from the
2545   // all_threads list, so we have to be careful to treat them as roots
2546   // here.
2547   { 
2548       StgMainThread *m;
2549       for (m = main_threads; m != NULL; m = m->link) {
2550           switch (m->tso->what_next) {
2551           case ThreadComplete:
2552           case ThreadKilled:
2553               evac((StgClosure **)&m->tso);
2554               break;
2555           default:
2556               break;
2557           }
2558       }
2559   }
2560 }
2561
2562 /* -----------------------------------------------------------------------------
2563    performGC
2564
2565    This is the interface to the garbage collector from Haskell land.
2566    We provide this so that external C code can allocate and garbage
2567    collect when called from Haskell via _ccall_GC.
2568
2569    It might be useful to provide an interface whereby the programmer
2570    can specify more roots (ToDo).
2571    
2572    This needs to be protected by the GC condition variable above.  KH.
2573    -------------------------------------------------------------------------- */
2574
2575 static void (*extra_roots)(evac_fn);
2576
2577 void
2578 performGC(void)
2579 {
2580   /* Obligated to hold this lock upon entry */
2581   ACQUIRE_LOCK(&sched_mutex);
2582   GarbageCollect(GetRoots,rtsFalse);
2583   RELEASE_LOCK(&sched_mutex);
2584 }
2585
2586 void
2587 performMajorGC(void)
2588 {
2589   ACQUIRE_LOCK(&sched_mutex);
2590   GarbageCollect(GetRoots,rtsTrue);
2591   RELEASE_LOCK(&sched_mutex);
2592 }
2593
2594 static void
2595 AllRoots(evac_fn evac)
2596 {
2597     GetRoots(evac);             // the scheduler's roots
2598     extra_roots(evac);          // the user's roots
2599 }
2600
2601 void
2602 performGCWithRoots(void (*get_roots)(evac_fn))
2603 {
2604   ACQUIRE_LOCK(&sched_mutex);
2605   extra_roots = get_roots;
2606   GarbageCollect(AllRoots,rtsFalse);
2607   RELEASE_LOCK(&sched_mutex);
2608 }
2609
2610 /* -----------------------------------------------------------------------------
2611    Stack overflow
2612
2613    If the thread has reached its maximum stack size, then raise the
2614    StackOverflow exception in the offending thread.  Otherwise
2615    relocate the TSO into a larger chunk of memory and adjust its stack
2616    size appropriately.
2617    -------------------------------------------------------------------------- */
2618
2619 static StgTSO *
2620 threadStackOverflow(StgTSO *tso)
2621 {
2622   nat new_stack_size, new_tso_size, diff, stack_words;
2623   StgPtr new_sp;
2624   StgTSO *dest;
2625
2626   IF_DEBUG(sanity,checkTSO(tso));
2627   if (tso->stack_size >= tso->max_stack_size) {
2628
2629     IF_DEBUG(gc,
2630              belch("@@ threadStackOverflow of TSO %d (%p): stack too large (now %ld; max is %ld",
2631                    tso->id, tso, tso->stack_size, tso->max_stack_size);
2632              /* If we're debugging, just print out the top of the stack */
2633              printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size, 
2634                                               tso->sp+64)));
2635
2636     /* Send this thread the StackOverflow exception */
2637     raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2638     return tso;
2639   }
2640
2641   /* Try to double the current stack size.  If that takes us over the
2642    * maximum stack size for this thread, then use the maximum instead.
2643    * Finally round up so the TSO ends up as a whole number of blocks.
2644    */
2645   new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2646   new_tso_size   = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) + 
2647                                        TSO_STRUCT_SIZE)/sizeof(W_);
2648   new_tso_size = round_to_mblocks(new_tso_size);  /* Be MBLOCK-friendly */
2649   new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2650
2651   IF_DEBUG(scheduler, fprintf(stderr,"== scheduler: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2652
2653   dest = (StgTSO *)allocate(new_tso_size);
2654   TICK_ALLOC_TSO(new_stack_size,0);
2655
2656   /* copy the TSO block and the old stack into the new area */
2657   memcpy(dest,tso,TSO_STRUCT_SIZE);
2658   stack_words = tso->stack + tso->stack_size - tso->sp;
2659   new_sp = (P_)dest + new_tso_size - stack_words;
2660   memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2661
2662   /* relocate the stack pointers... */
2663   diff = (P_)new_sp - (P_)tso->sp; /* In *words* */
2664   dest->sp    = new_sp;
2665   dest->stack_size = new_stack_size;
2666         
2667   /* Mark the old TSO as relocated.  We have to check for relocated
2668    * TSOs in the garbage collector and any primops that deal with TSOs.
2669    *
2670    * It's important to set the sp value to just beyond the end
2671    * of the stack, so we don't attempt to scavenge any part of the
2672    * dead TSO's stack.
2673    */
2674   tso->what_next = ThreadRelocated;
2675   tso->link = dest;
2676   tso->sp = (P_)&(tso->stack[tso->stack_size]);
2677   tso->why_blocked = NotBlocked;
2678   dest->mut_link = NULL;
2679
2680   IF_PAR_DEBUG(verbose,
2681                belch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld",
2682                      tso->id, tso, tso->stack_size);
2683                /* If we're debugging, just print out the top of the stack */
2684                printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size, 
2685                                                 tso->sp+64)));
2686   
2687   IF_DEBUG(sanity,checkTSO(tso));
2688 #if 0
2689   IF_DEBUG(scheduler,printTSO(dest));
2690 #endif
2691
2692   return dest;
2693 }
2694
2695 //@node Blocking Queue Routines, Exception Handling Routines, Garbage Collextion Routines, Main scheduling code
2696 //@subsection Blocking Queue Routines
2697
2698 /* ---------------------------------------------------------------------------
2699    Wake up a queue that was blocked on some resource.
2700    ------------------------------------------------------------------------ */
2701
2702 #if defined(GRAN)
2703 static inline void
2704 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2705 {
2706 }
2707 #elif defined(PAR)
2708 static inline void
2709 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2710 {
2711   /* write RESUME events to log file and
2712      update blocked and fetch time (depending on type of the orig closure) */
2713   if (RtsFlags.ParFlags.ParStats.Full) {
2714     DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC, 
2715                      GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2716                      0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2717     if (EMPTY_RUN_QUEUE())
2718       emitSchedule = rtsTrue;
2719
2720     switch (get_itbl(node)->type) {
2721         case FETCH_ME_BQ:
2722           ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2723           break;
2724         case RBH:
2725         case FETCH_ME:
2726         case BLACKHOLE_BQ:
2727           ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2728           break;
2729 #ifdef DIST
2730         case MVAR:
2731           break;
2732 #endif    
2733         default:
2734           barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2735         }
2736       }
2737 }
2738 #endif
2739
2740 #if defined(GRAN)
2741 static StgBlockingQueueElement *
2742 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2743 {
2744     StgTSO *tso;
2745     PEs node_loc, tso_loc;
2746
2747     node_loc = where_is(node); // should be lifted out of loop
2748     tso = (StgTSO *)bqe;  // wastes an assignment to get the type right
2749     tso_loc = where_is((StgClosure *)tso);
2750     if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2751       /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2752       ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2753       CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2754       // insertThread(tso, node_loc);
2755       new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2756                 ResumeThread,
2757                 tso, node, (rtsSpark*)NULL);
2758       tso->link = END_TSO_QUEUE; // overwrite link just to be sure 
2759       // len_local++;
2760       // len++;
2761     } else { // TSO is remote (actually should be FMBQ)
2762       CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2763                                   RtsFlags.GranFlags.Costs.gunblocktime +
2764                                   RtsFlags.GranFlags.Costs.latency;
2765       new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2766                 UnblockThread,
2767                 tso, node, (rtsSpark*)NULL);
2768       tso->link = END_TSO_QUEUE; // overwrite link just to be sure 
2769       // len++;
2770     }
2771     /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2772     IF_GRAN_DEBUG(bq,
2773                   fprintf(stderr," %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2774                           (node_loc==tso_loc ? "Local" : "Global"), 
2775                           tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2776     tso->block_info.closure = NULL;
2777     IF_DEBUG(scheduler,belch("-- Waking up thread %ld (%p)", 
2778                              tso->id, tso));
2779 }
2780 #elif defined(PAR)
2781 static StgBlockingQueueElement *
2782 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2783 {
2784     StgBlockingQueueElement *next;
2785
2786     switch (get_itbl(bqe)->type) {
2787     case TSO:
2788       ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2789       /* if it's a TSO just push it onto the run_queue */
2790       next = bqe->link;
2791       // ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2792       PUSH_ON_RUN_QUEUE((StgTSO *)bqe); 
2793       THREAD_RUNNABLE();
2794       unblockCount(bqe, node);
2795       /* reset blocking status after dumping event */
2796       ((StgTSO *)bqe)->why_blocked = NotBlocked;
2797       break;
2798
2799     case BLOCKED_FETCH:
2800       /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2801       next = bqe->link;
2802       bqe->link = (StgBlockingQueueElement *)PendingFetches;
2803       PendingFetches = (StgBlockedFetch *)bqe;
2804       break;
2805
2806 # if defined(DEBUG)
2807       /* can ignore this case in a non-debugging setup; 
2808          see comments on RBHSave closures above */
2809     case CONSTR:
2810       /* check that the closure is an RBHSave closure */
2811       ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2812              get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2813              get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2814       break;
2815
2816     default:
2817       barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2818            get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe), 
2819            (StgClosure *)bqe);
2820 # endif
2821     }
2822   IF_PAR_DEBUG(bq, fprintf(stderr, ", %p (%s)", bqe, info_type((StgClosure*)bqe)));
2823   return next;
2824 }
2825
2826 #else /* !GRAN && !PAR */
2827 static StgTSO *
2828 unblockOneLocked(StgTSO *tso)
2829 {
2830   StgTSO *next;
2831
2832   ASSERT(get_itbl(tso)->type == TSO);
2833   ASSERT(tso->why_blocked != NotBlocked);
2834   tso->why_blocked = NotBlocked;
2835   next = tso->link;
2836   PUSH_ON_RUN_QUEUE(tso);
2837   THREAD_RUNNABLE();
2838   IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
2839   return next;
2840 }
2841 #endif
2842
2843 #if defined(GRAN) || defined(PAR)
2844 inline StgBlockingQueueElement *
2845 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2846 {
2847   ACQUIRE_LOCK(&sched_mutex);
2848   bqe = unblockOneLocked(bqe, node);
2849   RELEASE_LOCK(&sched_mutex);
2850   return bqe;
2851 }
2852 #else
2853 inline StgTSO *
2854 unblockOne(StgTSO *tso)
2855 {
2856   ACQUIRE_LOCK(&sched_mutex);
2857   tso = unblockOneLocked(tso);
2858   RELEASE_LOCK(&sched_mutex);
2859   return tso;
2860 }
2861 #endif
2862
2863 #if defined(GRAN)
2864 void 
2865 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2866 {
2867   StgBlockingQueueElement *bqe;
2868   PEs node_loc;
2869   nat len = 0; 
2870
2871   IF_GRAN_DEBUG(bq, 
2872                 belch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): ", \
2873                       node, CurrentProc, CurrentTime[CurrentProc], 
2874                       CurrentTSO->id, CurrentTSO));
2875
2876   node_loc = where_is(node);
2877
2878   ASSERT(q == END_BQ_QUEUE ||
2879          get_itbl(q)->type == TSO ||   // q is either a TSO or an RBHSave
2880          get_itbl(q)->type == CONSTR); // closure (type constructor)
2881   ASSERT(is_unique(node));
2882
2883   /* FAKE FETCH: magically copy the node to the tso's proc;
2884      no Fetch necessary because in reality the node should not have been 
2885      moved to the other PE in the first place
2886   */
2887   if (CurrentProc!=node_loc) {
2888     IF_GRAN_DEBUG(bq, 
2889                   belch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)",
2890                         node, node_loc, CurrentProc, CurrentTSO->id, 
2891                         // CurrentTSO, where_is(CurrentTSO),
2892                         node->header.gran.procs));
2893     node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
2894     IF_GRAN_DEBUG(bq, 
2895                   belch("## new bitmask of node %p is %#x",
2896                         node, node->header.gran.procs));
2897     if (RtsFlags.GranFlags.GranSimStats.Global) {
2898       globalGranStats.tot_fake_fetches++;
2899     }
2900   }
2901
2902   bqe = q;
2903   // ToDo: check: ASSERT(CurrentProc==node_loc);
2904   while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
2905     //next = bqe->link;
2906     /* 
2907        bqe points to the current element in the queue
2908        next points to the next element in the queue
2909     */
2910     //tso = (StgTSO *)bqe;  // wastes an assignment to get the type right
2911     //tso_loc = where_is(tso);
2912     len++;
2913     bqe = unblockOneLocked(bqe, node);
2914   }
2915
2916   /* if this is the BQ of an RBH, we have to put back the info ripped out of
2917      the closure to make room for the anchor of the BQ */
2918   if (bqe!=END_BQ_QUEUE) {
2919     ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
2920     /*
2921     ASSERT((info_ptr==&RBH_Save_0_info) ||
2922            (info_ptr==&RBH_Save_1_info) ||
2923            (info_ptr==&RBH_Save_2_info));
2924     */
2925     /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
2926     ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
2927     ((StgRBH *)node)->mut_link       = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
2928
2929     IF_GRAN_DEBUG(bq,
2930                   belch("## Filled in RBH_Save for %p (%s) at end of AwBQ",
2931                         node, info_type(node)));
2932   }
2933
2934   /* statistics gathering */
2935   if (RtsFlags.GranFlags.GranSimStats.Global) {
2936     // globalGranStats.tot_bq_processing_time += bq_processing_time;
2937     globalGranStats.tot_bq_len += len;      // total length of all bqs awakened
2938     // globalGranStats.tot_bq_len_local += len_local;  // same for local TSOs only
2939     globalGranStats.tot_awbq++;             // total no. of bqs awakened
2940   }
2941   IF_GRAN_DEBUG(bq,
2942                 fprintf(stderr,"## BQ Stats of %p: [%d entries] %s\n",
2943                         node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
2944 }
2945 #elif defined(PAR)
2946 void 
2947 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2948 {
2949   StgBlockingQueueElement *bqe;
2950
2951   ACQUIRE_LOCK(&sched_mutex);
2952
2953   IF_PAR_DEBUG(verbose, 
2954                belch("##-_ AwBQ for node %p on [%x]: ",
2955                      node, mytid));
2956 #ifdef DIST  
2957   //RFP
2958   if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
2959     IF_PAR_DEBUG(verbose, belch("## ... nothing to unblock so lets just return. RFP (BUG?)"));
2960     return;
2961   }
2962 #endif
2963   
2964   ASSERT(q == END_BQ_QUEUE ||
2965          get_itbl(q)->type == TSO ||           
2966          get_itbl(q)->type == BLOCKED_FETCH || 
2967          get_itbl(q)->type == CONSTR); 
2968
2969   bqe = q;
2970   while (get_itbl(bqe)->type==TSO || 
2971          get_itbl(bqe)->type==BLOCKED_FETCH) {
2972     bqe = unblockOneLocked(bqe, node);
2973   }
2974   RELEASE_LOCK(&sched_mutex);
2975 }
2976
2977 #else   /* !GRAN && !PAR */
2978
2979 #ifdef RTS_SUPPORTS_THREADS
2980 void
2981 awakenBlockedQueueNoLock(StgTSO *tso)
2982 {
2983   while (tso != END_TSO_QUEUE) {
2984     tso = unblockOneLocked(tso);
2985   }
2986 }
2987 #endif
2988
2989 void
2990 awakenBlockedQueue(StgTSO *tso)
2991 {
2992   ACQUIRE_LOCK(&sched_mutex);
2993   while (tso != END_TSO_QUEUE) {
2994     tso = unblockOneLocked(tso);
2995   }
2996   RELEASE_LOCK(&sched_mutex);
2997 }
2998 #endif
2999
3000 //@node Exception Handling Routines, Debugging Routines, Blocking Queue Routines, Main scheduling code
3001 //@subsection Exception Handling Routines
3002
3003 /* ---------------------------------------------------------------------------
3004    Interrupt execution
3005    - usually called inside a signal handler so it mustn't do anything fancy.   
3006    ------------------------------------------------------------------------ */
3007
3008 void
3009 interruptStgRts(void)
3010 {
3011     interrupted    = 1;
3012     context_switch = 1;
3013 }
3014
3015 /* -----------------------------------------------------------------------------
3016    Unblock a thread
3017
3018    This is for use when we raise an exception in another thread, which
3019    may be blocked.
3020    This has nothing to do with the UnblockThread event in GranSim. -- HWL
3021    -------------------------------------------------------------------------- */
3022
3023 #if defined(GRAN) || defined(PAR)
3024 /*
3025   NB: only the type of the blocking queue is different in GranSim and GUM
3026       the operations on the queue-elements are the same
3027       long live polymorphism!
3028
3029   Locks: sched_mutex is held upon entry and exit.
3030
3031 */
3032 static void
3033 unblockThread(StgTSO *tso)
3034 {
3035   StgBlockingQueueElement *t, **last;
3036
3037   switch (tso->why_blocked) {
3038
3039   case NotBlocked:
3040     return;  /* not blocked */
3041
3042   case BlockedOnMVar:
3043     ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3044     {
3045       StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
3046       StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3047
3048       last = (StgBlockingQueueElement **)&mvar->head;
3049       for (t = (StgBlockingQueueElement *)mvar->head; 
3050            t != END_BQ_QUEUE; 
3051            last = &t->link, last_tso = t, t = t->link) {
3052         if (t == (StgBlockingQueueElement *)tso) {
3053           *last = (StgBlockingQueueElement *)tso->link;
3054           if (mvar->tail == tso) {
3055             mvar->tail = (StgTSO *)last_tso;
3056           }
3057           goto done;
3058         }
3059       }
3060       barf("unblockThread (MVAR): TSO not found");
3061     }
3062
3063   case BlockedOnBlackHole:
3064     ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3065     {
3066       StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3067
3068       last = &bq->blocking_queue;
3069       for (t = bq->blocking_queue; 
3070            t != END_BQ_QUEUE; 
3071            last = &t->link, t = t->link) {
3072         if (t == (StgBlockingQueueElement *)tso) {
3073           *last = (StgBlockingQueueElement *)tso->link;
3074           goto done;
3075         }
3076       }
3077       barf("unblockThread (BLACKHOLE): TSO not found");
3078     }
3079
3080   case BlockedOnException:
3081     {
3082       StgTSO *target  = tso->block_info.tso;
3083
3084       ASSERT(get_itbl(target)->type == TSO);
3085
3086       if (target->what_next == ThreadRelocated) {
3087           target = target->link;
3088           ASSERT(get_itbl(target)->type == TSO);
3089       }
3090
3091       ASSERT(target->blocked_exceptions != NULL);
3092
3093       last = (StgBlockingQueueElement **)&target->blocked_exceptions;
3094       for (t = (StgBlockingQueueElement *)target->blocked_exceptions; 
3095            t != END_BQ_QUEUE; 
3096            last = &t->link, t = t->link) {
3097         ASSERT(get_itbl(t)->type == TSO);
3098         if (t == (StgBlockingQueueElement *)tso) {
3099           *last = (StgBlockingQueueElement *)tso->link;
3100           goto done;
3101         }
3102       }
3103       barf("unblockThread (Exception): TSO not found");
3104     }
3105
3106   case BlockedOnRead:
3107   case BlockedOnWrite:
3108     {
3109       /* take TSO off blocked_queue */
3110       StgBlockingQueueElement *prev = NULL;
3111       for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE; 
3112            prev = t, t = t->link) {
3113         if (t == (StgBlockingQueueElement *)tso) {
3114           if (prev == NULL) {
3115             blocked_queue_hd = (StgTSO *)t->link;
3116             if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3117               blocked_queue_tl = END_TSO_QUEUE;
3118             }
3119           } else {
3120             prev->link = t->link;
3121             if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
3122               blocked_queue_tl = (StgTSO *)prev;
3123             }
3124           }
3125           goto done;
3126         }
3127       }
3128       barf("unblockThread (I/O): TSO not found");
3129     }
3130
3131   case BlockedOnDelay:
3132     {
3133       /* take TSO off sleeping_queue */
3134       StgBlockingQueueElement *prev = NULL;
3135       for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE; 
3136            prev = t, t = t->link) {
3137         if (t == (StgBlockingQueueElement *)tso) {
3138           if (prev == NULL) {
3139             sleeping_queue = (StgTSO *)t->link;
3140           } else {
3141             prev->link = t->link;
3142           }
3143           goto done;
3144         }
3145       }
3146       barf("unblockThread (I/O): TSO not found");
3147     }
3148
3149   default:
3150     barf("unblockThread");
3151   }
3152
3153  done:
3154   tso->link = END_TSO_QUEUE;
3155   tso->why_blocked = NotBlocked;
3156   tso->block_info.closure = NULL;
3157   PUSH_ON_RUN_QUEUE(tso);
3158 }
3159 #else
3160 static void
3161 unblockThread(StgTSO *tso)
3162 {
3163   StgTSO *t, **last;
3164   
3165   /* To avoid locking unnecessarily. */
3166   if (tso->why_blocked == NotBlocked) {
3167     return;
3168   }
3169
3170   switch (tso->why_blocked) {
3171
3172   case BlockedOnMVar:
3173     ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
3174     {
3175       StgTSO *last_tso = END_TSO_QUEUE;
3176       StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
3177
3178       last = &mvar->head;
3179       for (t = mvar->head; t != END_TSO_QUEUE; 
3180            last = &t->link, last_tso = t, t = t->link) {
3181         if (t == tso) {
3182           *last = tso->link;
3183           if (mvar->tail == tso) {
3184             mvar->tail = last_tso;
3185           }
3186           goto done;
3187         }
3188       }
3189       barf("unblockThread (MVAR): TSO not found");
3190     }
3191
3192   case BlockedOnBlackHole:
3193     ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
3194     {
3195       StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
3196
3197       last = &bq->blocking_queue;
3198       for (t = bq->blocking_queue; t != END_TSO_QUEUE; 
3199            last = &t->link, t = t->link) {
3200         if (t == tso) {
3201           *last = tso->link;
3202           goto done;
3203         }
3204       }
3205       barf("unblockThread (BLACKHOLE): TSO not found");
3206     }
3207
3208   case BlockedOnException:
3209     {
3210       StgTSO *target  = tso->block_info.tso;
3211
3212       ASSERT(get_itbl(target)->type == TSO);
3213
3214       while (target->what_next == ThreadRelocated) {
3215           target = target->link;
3216           ASSERT(get_itbl(target)->type == TSO);
3217       }
3218       
3219       ASSERT(target->blocked_exceptions != NULL);
3220
3221       last = &target->blocked_exceptions;
3222       for (t = target->blocked_exceptions; t != END_TSO_QUEUE; 
3223            last = &t->link, t = t->link) {
3224         ASSERT(get_itbl(t)->type == TSO);
3225         if (t == tso) {
3226           *last = tso->link;
3227           goto done;
3228         }
3229       }
3230       barf("unblockThread (Exception): TSO not found");
3231     }
3232
3233   case BlockedOnRead:
3234   case BlockedOnWrite:
3235     {
3236       StgTSO *prev = NULL;
3237       for (t = blocked_queue_hd; t != END_TSO_QUEUE; 
3238            prev = t, t = t->link) {
3239         if (t == tso) {
3240           if (prev == NULL) {
3241             blocked_queue_hd = t->link;
3242             if (blocked_queue_tl == t) {
3243               blocked_queue_tl = END_TSO_QUEUE;
3244             }
3245           } else {
3246             prev->link = t->link;
3247             if (blocked_queue_tl == t) {
3248               blocked_queue_tl = prev;
3249             }
3250           }
3251           goto done;
3252         }
3253       }
3254       barf("unblockThread (I/O): TSO not found");
3255     }
3256
3257   case BlockedOnDelay:
3258     {
3259       StgTSO *prev = NULL;
3260       for (t = sleeping_queue; t != END_TSO_QUEUE; 
3261            prev = t, t = t->link) {
3262         if (t == tso) {
3263           if (prev == NULL) {
3264             sleeping_queue = t->link;
3265           } else {
3266             prev->link = t->link;
3267           }
3268           goto done;
3269         }
3270       }
3271       barf("unblockThread (I/O): TSO not found");
3272     }
3273
3274   default:
3275     barf("unblockThread");
3276   }
3277
3278  done:
3279   tso->link = END_TSO_QUEUE;
3280   tso->why_blocked = NotBlocked;
3281   tso->block_info.closure = NULL;
3282   PUSH_ON_RUN_QUEUE(tso);
3283 }
3284 #endif
3285
3286 /* -----------------------------------------------------------------------------
3287  * raiseAsync()
3288  *
3289  * The following function implements the magic for raising an
3290  * asynchronous exception in an existing thread.
3291  *
3292  * We first remove the thread from any queue on which it might be
3293  * blocked.  The possible blockages are MVARs and BLACKHOLE_BQs.
3294  *
3295  * We strip the stack down to the innermost CATCH_FRAME, building
3296  * thunks in the heap for all the active computations, so they can 
3297  * be restarted if necessary.  When we reach a CATCH_FRAME, we build
3298  * an application of the handler to the exception, and push it on
3299  * the top of the stack.
3300  * 
3301  * How exactly do we save all the active computations?  We create an
3302  * AP_STACK for every UpdateFrame on the stack.  Entering one of these
3303  * AP_STACKs pushes everything from the corresponding update frame
3304  * upwards onto the stack.  (Actually, it pushes everything up to the
3305  * next update frame plus a pointer to the next AP_STACK object.
3306  * Entering the next AP_STACK object pushes more onto the stack until we
3307  * reach the last AP_STACK object - at which point the stack should look
3308  * exactly as it did when we killed the TSO and we can continue
3309  * execution by entering the closure on top of the stack.
3310  *
3311  * We can also kill a thread entirely - this happens if either (a) the 
3312  * exception passed to raiseAsync is NULL, or (b) there's no
3313  * CATCH_FRAME on the stack.  In either case, we strip the entire
3314  * stack and replace the thread with a zombie.
3315  *
3316  * Locks: sched_mutex held upon entry nor exit.
3317  *
3318  * -------------------------------------------------------------------------- */
3319  
3320 void 
3321 deleteThread(StgTSO *tso)
3322 {
3323   raiseAsync(tso,NULL);
3324 }
3325
3326 void
3327 raiseAsyncWithLock(StgTSO *tso, StgClosure *exception)
3328 {
3329   /* When raising async exs from contexts where sched_mutex isn't held;
3330      use raiseAsyncWithLock(). */
3331   ACQUIRE_LOCK(&sched_mutex);
3332   raiseAsync(tso,exception);
3333   RELEASE_LOCK(&sched_mutex);
3334 }
3335
3336 void
3337 raiseAsync(StgTSO *tso, StgClosure *exception)
3338 {
3339     StgRetInfoTable *info;
3340     StgPtr sp;
3341   
3342     // Thread already dead?
3343     if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3344         return;
3345     }
3346
3347     IF_DEBUG(scheduler, 
3348              sched_belch("raising exception in thread %ld.", tso->id));
3349     
3350     // Remove it from any blocking queues
3351     unblockThread(tso);
3352
3353     sp = tso->sp;
3354     
3355     // The stack freezing code assumes there's a closure pointer on
3356     // the top of the stack, so we have to arrange that this is the case...
3357     //
3358     if (sp[0] == (W_)&stg_enter_info) {
3359         sp++;
3360     } else {
3361         sp--;
3362         sp[0] = (W_)&stg_dummy_ret_closure;
3363     }
3364
3365     while (1) {
3366         nat i;
3367
3368         // 1. Let the top of the stack be the "current closure"
3369         //
3370         // 2. Walk up the stack until we find either an UPDATE_FRAME or a
3371         // CATCH_FRAME.
3372         //
3373         // 3. If it's an UPDATE_FRAME, then make an AP_STACK containing the
3374         // current closure applied to the chunk of stack up to (but not
3375         // including) the update frame.  This closure becomes the "current
3376         // closure".  Go back to step 2.
3377         //
3378         // 4. If it's a CATCH_FRAME, then leave the exception handler on
3379         // top of the stack applied to the exception.
3380         // 
3381         // 5. If it's a STOP_FRAME, then kill the thread.
3382         
3383         StgPtr frame;
3384         
3385         frame = sp + 1;
3386         info = get_ret_itbl((StgClosure *)frame);
3387         
3388         while (info->i.type != UPDATE_FRAME
3389                && (info->i.type != CATCH_FRAME || exception == NULL)
3390                && info->i.type != STOP_FRAME) {
3391             frame += stack_frame_sizeW((StgClosure *)frame);
3392             info = get_ret_itbl((StgClosure *)frame);
3393         }
3394         
3395         switch (info->i.type) {
3396             
3397         case CATCH_FRAME:
3398             // If we find a CATCH_FRAME, and we've got an exception to raise,
3399             // then build the THUNK raise(exception), and leave it on
3400             // top of the CATCH_FRAME ready to enter.
3401             //
3402         {
3403 #ifdef PROFILING
3404             StgCatchFrame *cf = (StgCatchFrame *)frame;
3405 #endif
3406             StgClosure *raise;
3407             
3408             // we've got an exception to raise, so let's pass it to the
3409             // handler in this frame.
3410             //
3411             raise = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3412             TICK_ALLOC_SE_THK(1,0);
3413             SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
3414             raise->payload[0] = exception;
3415             
3416             // throw away the stack from Sp up to the CATCH_FRAME.
3417             //
3418             sp = frame - 1;
3419             
3420             /* Ensure that async excpetions are blocked now, so we don't get
3421              * a surprise exception before we get around to executing the
3422              * handler.
3423              */
3424             if (tso->blocked_exceptions == NULL) {
3425                 tso->blocked_exceptions = END_TSO_QUEUE;
3426             }
3427             
3428             /* Put the newly-built THUNK on top of the stack, ready to execute
3429              * when the thread restarts.
3430              */
3431             sp[0] = (W_)raise;
3432             sp[-1] = (W_)&stg_enter_info;
3433             tso->sp = sp-1;
3434             tso->what_next = ThreadRunGHC;
3435             IF_DEBUG(sanity, checkTSO(tso));
3436             return;
3437         }
3438         
3439         case UPDATE_FRAME:
3440         {
3441             StgAP_STACK * ap;
3442             nat words;
3443             
3444             // First build an AP_STACK consisting of the stack chunk above the
3445             // current update frame, with the top word on the stack as the
3446             // fun field.
3447             //
3448             words = frame - sp - 1;
3449             ap = (StgAP_STACK *)allocate(PAP_sizeW(words));
3450             
3451             ap->size = words;
3452             ap->fun  = (StgClosure *)sp[0];
3453             sp++;
3454             for(i=0; i < (nat)words; ++i) {
3455                 ap->payload[i] = (StgClosure *)*sp++;
3456             }
3457             
3458             SET_HDR(ap,&stg_AP_STACK_info,
3459                     ((StgClosure *)frame)->header.prof.ccs /* ToDo */); 
3460             TICK_ALLOC_UP_THK(words+1,0);
3461             
3462             IF_DEBUG(scheduler,
3463                      fprintf(stderr,  "scheduler: Updating ");
3464                      printPtr((P_)((StgUpdateFrame *)frame)->updatee); 
3465                      fprintf(stderr,  " with ");
3466                      printObj((StgClosure *)ap);
3467                 );
3468
3469             // Replace the updatee with an indirection - happily
3470             // this will also wake up any threads currently
3471             // waiting on the result.
3472             //
3473             // Warning: if we're in a loop, more than one update frame on
3474             // the stack may point to the same object.  Be careful not to
3475             // overwrite an IND_OLDGEN in this case, because we'll screw
3476             // up the mutable lists.  To be on the safe side, don't
3477             // overwrite any kind of indirection at all.  See also
3478             // threadSqueezeStack in GC.c, where we have to make a similar
3479             // check.
3480             //
3481             if (!closure_IND(((StgUpdateFrame *)frame)->updatee)) {
3482                 // revert the black hole
3483                 UPD_IND_NOLOCK(((StgUpdateFrame *)frame)->updatee,ap);
3484             }
3485             sp += sizeofW(StgUpdateFrame) - 1;
3486             sp[0] = (W_)ap; // push onto stack
3487             break;
3488         }
3489         
3490         case STOP_FRAME:
3491             // We've stripped the entire stack, the thread is now dead.
3492             sp += sizeofW(StgStopFrame);
3493             tso->what_next = ThreadKilled;
3494             tso->sp = sp;
3495             return;
3496             
3497         default:
3498             barf("raiseAsync");
3499         }
3500     }
3501     barf("raiseAsync");
3502 }
3503
3504 /* -----------------------------------------------------------------------------
3505    resurrectThreads is called after garbage collection on the list of
3506    threads found to be garbage.  Each of these threads will be woken
3507    up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3508    on an MVar, or NonTermination if the thread was blocked on a Black
3509    Hole.
3510
3511    Locks: sched_mutex isn't held upon entry nor exit.
3512    -------------------------------------------------------------------------- */
3513
3514 void
3515 resurrectThreads( StgTSO *threads )
3516 {
3517   StgTSO *tso, *next;
3518
3519   for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3520     next = tso->global_link;
3521     tso->global_link = all_threads;
3522     all_threads = tso;
3523     IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3524
3525     switch (tso->why_blocked) {
3526     case BlockedOnMVar:
3527     case BlockedOnException:
3528       /* Called by GC - sched_mutex lock is currently held. */
3529       raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3530       break;
3531     case BlockedOnBlackHole:
3532       raiseAsync(tso,(StgClosure *)NonTermination_closure);
3533       break;
3534     case NotBlocked:
3535       /* This might happen if the thread was blocked on a black hole
3536        * belonging to a thread that we've just woken up (raiseAsync
3537        * can wake up threads, remember...).
3538        */
3539       continue;
3540     default:
3541       barf("resurrectThreads: thread blocked in a strange way");
3542     }
3543   }
3544 }
3545
3546 /* -----------------------------------------------------------------------------
3547  * Blackhole detection: if we reach a deadlock, test whether any
3548  * threads are blocked on themselves.  Any threads which are found to
3549  * be self-blocked get sent a NonTermination exception.
3550  *
3551  * This is only done in a deadlock situation in order to avoid
3552  * performance overhead in the normal case.
3553  *
3554  * Locks: sched_mutex is held upon entry and exit.
3555  * -------------------------------------------------------------------------- */
3556
3557 static void
3558 detectBlackHoles( void )
3559 {
3560     StgTSO *tso = all_threads;
3561     StgClosure *frame;
3562     StgClosure *blocked_on;
3563     StgRetInfoTable *info;
3564
3565     for (tso = all_threads; tso != END_TSO_QUEUE; tso = tso->global_link) {
3566
3567         while (tso->what_next == ThreadRelocated) {
3568             tso = tso->link;
3569             ASSERT(get_itbl(tso)->type == TSO);
3570         }
3571       
3572         if (tso->why_blocked != BlockedOnBlackHole) {
3573             continue;
3574         }
3575         blocked_on = tso->block_info.closure;
3576
3577         frame = (StgClosure *)tso->sp;
3578
3579         while(1) {
3580             info = get_ret_itbl(frame);
3581             switch (info->i.type) {
3582             case UPDATE_FRAME:
3583                 if (((StgUpdateFrame *)frame)->updatee == blocked_on) {
3584                     /* We are blocking on one of our own computations, so
3585                      * send this thread the NonTermination exception.  
3586                      */
3587                     IF_DEBUG(scheduler, 
3588                              sched_belch("thread %d is blocked on itself", tso->id));
3589                     raiseAsync(tso, (StgClosure *)NonTermination_closure);
3590                     goto done;
3591                 }
3592                 
3593                 frame = (StgClosure *) ((StgUpdateFrame *)frame + 1);
3594                 continue;
3595
3596             case STOP_FRAME:
3597                 goto done;
3598
3599                 // normal stack frames; do nothing except advance the pointer
3600             default:
3601                 (StgPtr)frame += stack_frame_sizeW(frame);
3602             }
3603         }   
3604         done: ;
3605     }
3606 }
3607
3608 //@node Debugging Routines, Index, Exception Handling Routines, Main scheduling code
3609 //@subsection Debugging Routines
3610
3611 /* -----------------------------------------------------------------------------
3612  * Debugging: why is a thread blocked
3613  * [Also provides useful information when debugging threaded programs
3614  *  at the Haskell source code level, so enable outside of DEBUG. --sof 7/02]
3615    -------------------------------------------------------------------------- */
3616
3617 static
3618 void
3619 printThreadBlockage(StgTSO *tso)
3620 {
3621   switch (tso->why_blocked) {
3622   case BlockedOnRead:
3623     fprintf(stderr,"is blocked on read from fd %d", tso->block_info.fd);
3624     break;
3625   case BlockedOnWrite:
3626     fprintf(stderr,"is blocked on write to fd %d", tso->block_info.fd);
3627     break;
3628   case BlockedOnDelay:
3629     fprintf(stderr,"is blocked until %d", tso->block_info.target);
3630     break;
3631   case BlockedOnMVar:
3632     fprintf(stderr,"is blocked on an MVar");
3633     break;
3634   case BlockedOnException:
3635     fprintf(stderr,"is blocked on delivering an exception to thread %d",
3636             tso->block_info.tso->id);
3637     break;
3638   case BlockedOnBlackHole:
3639     fprintf(stderr,"is blocked on a black hole");
3640     break;
3641   case NotBlocked:
3642     fprintf(stderr,"is not blocked");
3643     break;
3644 #if defined(PAR)
3645   case BlockedOnGA:
3646     fprintf(stderr,"is blocked on global address; local FM_BQ is %p (%s)",
3647             tso->block_info.closure, info_type(tso->block_info.closure));
3648     break;
3649   case BlockedOnGA_NoSend:
3650     fprintf(stderr,"is blocked on global address (no send); local FM_BQ is %p (%s)",
3651             tso->block_info.closure, info_type(tso->block_info.closure));
3652     break;
3653 #endif
3654 #if defined(RTS_SUPPORTS_THREADS)
3655   case BlockedOnCCall:
3656     fprintf(stderr,"is blocked on an external call");
3657     break;
3658   case BlockedOnCCall_NoUnblockExc:
3659     fprintf(stderr,"is blocked on an external call (exceptions were already blocked)");
3660     break;
3661 #endif
3662   default:
3663     barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3664          tso->why_blocked, tso->id, tso);
3665   }
3666 }
3667
3668 static
3669 void
3670 printThreadStatus(StgTSO *tso)
3671 {
3672   switch (tso->what_next) {
3673   case ThreadKilled:
3674     fprintf(stderr,"has been killed");
3675     break;
3676   case ThreadComplete:
3677     fprintf(stderr,"has completed");
3678     break;
3679   default:
3680     printThreadBlockage(tso);
3681   }
3682 }
3683
3684 void
3685 printAllThreads(void)
3686 {
3687   StgTSO *t;
3688   void *label;
3689
3690 # if defined(GRAN)
3691   char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3692   ullong_format_string(TIME_ON_PROC(CurrentProc), 
3693                        time_string, rtsFalse/*no commas!*/);
3694
3695   fprintf(stderr, "all threads at [%s]:\n", time_string);
3696 # elif defined(PAR)
3697   char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3698   ullong_format_string(CURRENT_TIME,
3699                        time_string, rtsFalse/*no commas!*/);
3700
3701   fprintf(stderr,"all threads at [%s]:\n", time_string);
3702 # else
3703   fprintf(stderr,"all threads:\n");
3704 # endif
3705
3706   for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3707     fprintf(stderr, "\tthread %d @ %p ", t->id, (void *)t);
3708     label = lookupThreadLabel((StgWord)t);
3709     if (label) fprintf(stderr,"[\"%s\"] ",(char *)label);
3710     printThreadStatus(t);
3711     fprintf(stderr,"\n");
3712   }
3713 }
3714     
3715 #ifdef DEBUG
3716
3717 /* 
3718    Print a whole blocking queue attached to node (debugging only).
3719 */
3720 //@cindex print_bq
3721 # if defined(PAR)
3722 void 
3723 print_bq (StgClosure *node)
3724 {
3725   StgBlockingQueueElement *bqe;
3726   StgTSO *tso;
3727   rtsBool end;
3728
3729   fprintf(stderr,"## BQ of closure %p (%s): ",
3730           node, info_type(node));
3731
3732   /* should cover all closures that may have a blocking queue */
3733   ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3734          get_itbl(node)->type == FETCH_ME_BQ ||
3735          get_itbl(node)->type == RBH ||
3736          get_itbl(node)->type == MVAR);
3737     
3738   ASSERT(node!=(StgClosure*)NULL);         // sanity check
3739
3740   print_bqe(((StgBlockingQueue*)node)->blocking_queue);
3741 }
3742
3743 /* 
3744    Print a whole blocking queue starting with the element bqe.
3745 */
3746 void 
3747 print_bqe (StgBlockingQueueElement *bqe)
3748 {
3749   rtsBool end;
3750
3751   /* 
3752      NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3753   */
3754   for (end = (bqe==END_BQ_QUEUE);
3755        !end; // iterate until bqe points to a CONSTR
3756        end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), 
3757        bqe = end ? END_BQ_QUEUE : bqe->link) {
3758     ASSERT(bqe != END_BQ_QUEUE);                               // sanity check
3759     ASSERT(bqe != (StgBlockingQueueElement *)NULL);            // sanity check
3760     /* types of closures that may appear in a blocking queue */
3761     ASSERT(get_itbl(bqe)->type == TSO ||           
3762            get_itbl(bqe)->type == BLOCKED_FETCH || 
3763            get_itbl(bqe)->type == CONSTR); 
3764     /* only BQs of an RBH end with an RBH_Save closure */
3765     //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3766
3767     switch (get_itbl(bqe)->type) {
3768     case TSO:
3769       fprintf(stderr," TSO %u (%x),",
3770               ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
3771       break;
3772     case BLOCKED_FETCH:
3773       fprintf(stderr," BF (node=%p, ga=((%x, %d, %x)),",
3774               ((StgBlockedFetch *)bqe)->node, 
3775               ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
3776               ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
3777               ((StgBlockedFetch *)bqe)->ga.weight);
3778       break;
3779     case CONSTR:
3780       fprintf(stderr," %s (IP %p),",
3781               (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3782                get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3783                get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3784                "RBH_Save_?"), get_itbl(bqe));
3785       break;
3786     default:
3787       barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
3788            info_type((StgClosure *)bqe)); // , node, info_type(node));
3789       break;
3790     }
3791   } /* for */
3792   fputc('\n', stderr);
3793 }
3794 # elif defined(GRAN)
3795 void 
3796 print_bq (StgClosure *node)
3797 {
3798   StgBlockingQueueElement *bqe;
3799   PEs node_loc, tso_loc;
3800   rtsBool end;
3801
3802   /* should cover all closures that may have a blocking queue */
3803   ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3804          get_itbl(node)->type == FETCH_ME_BQ ||
3805          get_itbl(node)->type == RBH);
3806     
3807   ASSERT(node!=(StgClosure*)NULL);         // sanity check
3808   node_loc = where_is(node);
3809
3810   fprintf(stderr,"## BQ of closure %p (%s) on [PE %d]: ",
3811           node, info_type(node), node_loc);
3812
3813   /* 
3814      NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3815   */
3816   for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
3817        !end; // iterate until bqe points to a CONSTR
3818        end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
3819     ASSERT(bqe != END_BQ_QUEUE);             // sanity check
3820     ASSERT(bqe != (StgBlockingQueueElement *)NULL);  // sanity check
3821     /* types of closures that may appear in a blocking queue */
3822     ASSERT(get_itbl(bqe)->type == TSO ||           
3823            get_itbl(bqe)->type == CONSTR); 
3824     /* only BQs of an RBH end with an RBH_Save closure */
3825     ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3826
3827     tso_loc = where_is((StgClosure *)bqe);
3828     switch (get_itbl(bqe)->type) {
3829     case TSO:
3830       fprintf(stderr," TSO %d (%p) on [PE %d],",
3831               ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
3832       break;
3833     case CONSTR:
3834       fprintf(stderr," %s (IP %p),",
3835               (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3836                get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3837                get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3838                "RBH_Save_?"), get_itbl(bqe));
3839       break;
3840     default:
3841       barf("Unexpected closure type %s in blocking queue of %p (%s)",
3842            info_type((StgClosure *)bqe), node, info_type(node));
3843       break;
3844     }
3845   } /* for */
3846   fputc('\n', stderr);
3847 }
3848 #else
3849 /* 
3850    Nice and easy: only TSOs on the blocking queue
3851 */
3852 void 
3853 print_bq (StgClosure *node)
3854 {
3855   StgTSO *tso;
3856
3857   ASSERT(node!=(StgClosure*)NULL);         // sanity check
3858   for (tso = ((StgBlockingQueue*)node)->blocking_queue;
3859        tso != END_TSO_QUEUE; 
3860        tso=tso->link) {
3861     ASSERT(tso!=NULL && tso!=END_TSO_QUEUE);   // sanity check
3862     ASSERT(get_itbl(tso)->type == TSO);  // guess what, sanity check
3863     fprintf(stderr," TSO %d (%p),", tso->id, tso);
3864   }
3865   fputc('\n', stderr);
3866 }
3867 # endif
3868
3869 #if defined(PAR)
3870 static nat
3871 run_queue_len(void)
3872 {
3873   nat i;
3874   StgTSO *tso;
3875
3876   for (i=0, tso=run_queue_hd; 
3877        tso != END_TSO_QUEUE;
3878        i++, tso=tso->link)
3879     /* nothing */
3880
3881   return i;
3882 }
3883 #endif
3884
3885 static void
3886 sched_belch(char *s, ...)
3887 {
3888   va_list ap;
3889   va_start(ap,s);
3890 #ifdef SMP
3891   fprintf(stderr, "scheduler (task %ld): ", osThreadId());
3892 #elif defined(PAR)
3893   fprintf(stderr, "== ");
3894 #else
3895   fprintf(stderr, "scheduler: ");
3896 #endif
3897   vfprintf(stderr, s, ap);
3898   fprintf(stderr, "\n");
3899   va_end(ap);
3900 }
3901
3902 #endif /* DEBUG */
3903
3904
3905 //@node Index,  , Debugging Routines, Main scheduling code
3906 //@subsection Index
3907
3908 //@index
3909 //* StgMainThread::  @cindex\s-+StgMainThread
3910 //* awaken_blocked_queue::  @cindex\s-+awaken_blocked_queue
3911 //* blocked_queue_hd::  @cindex\s-+blocked_queue_hd
3912 //* blocked_queue_tl::  @cindex\s-+blocked_queue_tl
3913 //* context_switch::  @cindex\s-+context_switch
3914 //* createThread::  @cindex\s-+createThread
3915 //* gc_pending_cond::  @cindex\s-+gc_pending_cond
3916 //* initScheduler::  @cindex\s-+initScheduler
3917 //* interrupted::  @cindex\s-+interrupted
3918 //* next_thread_id::  @cindex\s-+next_thread_id
3919 //* print_bq::  @cindex\s-+print_bq
3920 //* run_queue_hd::  @cindex\s-+run_queue_hd
3921 //* run_queue_tl::  @cindex\s-+run_queue_tl
3922 //* sched_mutex::  @cindex\s-+sched_mutex
3923 //* schedule::  @cindex\s-+schedule
3924 //* take_off_run_queue::  @cindex\s-+take_off_run_queue
3925 //* term_mutex::  @cindex\s-+term_mutex
3926 //@end index