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