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