Schedule.c 129 KB
Newer Older
1
/* ---------------------------------------------------------------------------
2
 *
3
 * (c) The GHC Team, 1998-2004
4
5
6
 *
 * Scheduler
 *
7
8
9
10
11
 * Different GHC ways use this scheduler quite differently (see comments below)
 * Here is the global picture:
 *
 * WAY  Name     CPP flag  What's it for
 * --------------------------------------
12
 * mp   GUM      PARALLEL_HASKELL          Parallel execution on a distrib. memory machine
sof's avatar
sof committed
13
14
15
16
 * s    SMP      SMP          Parallel execution on a shared memory machine
 * mg   GranSim  GRAN         Simulation of parallel execution
 * md   GUM/GdH  DIST         Distributed execution (based on GUM)
 *
17
18
 * --------------------------------------------------------------------------*/

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* 
 * Version with support for distributed memory parallelism aka GUM (WAY=mp):

   The main scheduling loop in GUM iterates until a finish message is received.
   In that case a global flag @receivedFinish@ is set and this instance of
   the RTS shuts down. See ghc/rts/parallel/HLComms.c:processMessages()
   for the handling of incoming messages, such as PP_FINISH.
   Note that in the parallel case we have a system manager that coordinates
   different PEs, each of which are running one instance of the RTS.
   See ghc/rts/parallel/SysMan.c for the main routine of the parallel program.
   From this routine processes executing ghc/rts/Main.c are spawned. -- HWL

 * Version with support for simulating parallel execution aka GranSim (WAY=mg):

   The main scheduling code in GranSim is quite different from that in std
   (concurrent) Haskell: while concurrent Haskell just iterates over the
   threads in the runnable queue, GranSim is event driven, i.e. it iterates
   over the events in the global event queue.  -- HWL
37
38
*/

39
#include "PosixSource.h"
40
41
42
43
#include "Rts.h"
#include "SchedAPI.h"
#include "RtsUtils.h"
#include "RtsFlags.h"
44
#include "BlockAlloc.h"
45
#include "OSThreads.h"
46
47
48
#include "Storage.h"
#include "StgRun.h"
#include "Hooks.h"
sof's avatar
sof committed
49
#define COMPILING_SCHEDULER
50
51
#include "Schedule.h"
#include "StgMiscClosures.h"
52
#include "Interpreter.h"
53
#include "Exception.h"
54
55
56
#include "Printer.h"
#include "Signals.h"
#include "Sanity.h"
57
#include "Stats.h"
58
#include "STM.h"
sof's avatar
sof committed
59
#include "Timer.h"
60
#include "Prelude.h"
61
#include "ThreadLabels.h"
62
63
#include "LdvProfile.h"
#include "Updates.h"
64
65
66
67
#ifdef PROFILING
#include "Proftimer.h"
#include "ProfHeap.h"
#endif
68
#if defined(GRAN) || defined(PARALLEL_HASKELL)
69
70
71
72
73
74
75
76
# include "GranSimRts.h"
# include "GranSim.h"
# include "ParallelRts.h"
# include "Parallel.h"
# include "ParallelDebug.h"
# include "FetchMe.h"
# include "HLC.h"
#endif
77
#include "Sparks.h"
sof's avatar
sof committed
78
#include "Capability.h"
sof's avatar
sof committed
79
#include  "Task.h"
80

81
82
83
84
85
86
87
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

88
89
#include <string.h>
#include <stdlib.h>
90
#include <stdarg.h>
91

92
93
94
95
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif

96
97
98
99
100
101
// Turn off inlining when debugging - it obfuscates things
#ifdef DEBUG
# undef  STATIC_INLINE
# define STATIC_INLINE static
#endif

102
103
104
105
106
107
108
109
110
111
112
113
#ifdef THREADED_RTS
#define USED_IN_THREADED_RTS
#else
#define USED_IN_THREADED_RTS STG_UNUSED
#endif

#ifdef RTS_SUPPORTS_THREADS
#define USED_WHEN_RTS_SUPPORTS_THREADS
#else
#define USED_WHEN_RTS_SUPPORTS_THREADS STG_UNUSED
#endif

114
115
116
/* Main thread queue.
 * Locks required: sched_mutex.
 */
117
StgMainThread *main_threads = NULL;
118

119
120
121
#if defined(GRAN)

StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
122
/* rtsTime TimeOfNextEvent, EndOfTimeSlice;            now in GranSim.c */
123
124

/* 
sof's avatar
sof committed
125
   In GranSim we have a runnable and a blocked queue for each processor.
126
127
128
129
130
131
132
133
   In order to minimise code changes new arrays run_queue_hds/tls
   are created. run_queue_hd is then a short cut (macro) for
   run_queue_hds[CurrentProc] (see GranSim.h).
   -- HWL
*/
StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
StgTSO *ccalling_threadss[MAX_PROC];
134
135
136
137
/* We use the same global list of threads (all_threads) in GranSim as in
   the std RTS (i.e. we are cheating). However, we don't use this list in
   the GranSim specific code at the moment (so we are only potentially
   cheating).  */
138
139
140

#else /* !GRAN */

141
142
143
/* Thread queues.
 * Locks required: sched_mutex.
 */
144
145
146
147
StgTSO *run_queue_hd = NULL;
StgTSO *run_queue_tl = NULL;
StgTSO *blocked_queue_hd = NULL;
StgTSO *blocked_queue_tl = NULL;
148
StgTSO *blackhole_queue = NULL;
149
StgTSO *sleeping_queue = NULL;    /* perhaps replace with a hash table? */
150

151
152
#endif

153
154
155
156
157
/* The blackhole_queue should be checked for threads to wake up.  See
 * Schedule.h for more thorough comment.
 */
rtsBool blackholes_need_checking = rtsFalse;

158
159
160
/* Linked list of all threads.
 * Used for detecting garbage collected threads.
 */
161
StgTSO *all_threads = NULL;
162

sof's avatar
sof committed
163
164
165
/* When a thread performs a safe C call (_ccall_GC, using old
 * terminology), it gets put on the suspended_ccalling_threads
 * list. Used by the garbage collector.
166
167
168
169
170
171
172
173
 */
static StgTSO *suspended_ccalling_threads;

/* KH: The following two flags are shared memory locations.  There is no need
       to lock them, since they are only unset at the end of a scheduler
       operation.
*/

174
/* flag set by signal handler to precipitate a context switch */
175
int context_switch = 0;
176

177
/* if this flag is set as well, give up execution */
178
rtsBool interrupted = rtsFalse;
179

180
/* Next thread ID to allocate.
sof's avatar
sof committed
181
 * Locks required: thread_id_mutex
182
 */
183
static StgThreadID next_thread_id = 1;
184
185
186
187
188
189

/*
 * Pointers to the state of the current thread.
 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
 * thread.  If CurrentTSO == NULL, then we're at the scheduler level.
 */
190
 
191
192
193
194
/* The smallest stack size that makes any sense is:
 *    RESERVED_STACK_WORDS    (so we can get back from the stack overflow)
 *  + sizeofW(StgStopFrame)   (the stg_stop_thread_info frame)
 *  + 1                       (the closure to enter)
195
196
 *  + 1			      (stg_ap_v_ret)
 *  + 1			      (spare slot req'd by stg_ap_v_ret)
197
198
199
200
201
 *
 * A thread with this stack will bomb immediately with a stack
 * overflow, which will increase its stack size.  
 */

202
#define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 3)
203

sof's avatar
sof committed
204

205
#if defined(GRAN)
206
StgTSO *CurrentTSO;
207
208
#endif

209
210
211
212
213
214
/*  This is used in `TSO.h' and gcc 2.96 insists that this variable actually 
 *  exists - earlier gccs apparently didn't.
 *  -= chak
 */
StgTSO dummy_tso;

sof's avatar
sof committed
215
216
217
218
219
220
/*
 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
 * in an MT setting, needed to signal that a worker thread shouldn't hang around
 * in the scheduler when it is out of work.
 */
static rtsBool shutting_down_scheduler = rtsFalse;
221

sof's avatar
sof committed
222
223
224
225
#if defined(RTS_SUPPORTS_THREADS)
/* ToDo: carefully document the invariants that go together
 *       with these synchronisation objects.
 */
sof's avatar
sof committed
226
227
Mutex     sched_mutex       = INIT_MUTEX_VAR;
Mutex     term_mutex        = INIT_MUTEX_VAR;
sof's avatar
sof committed
228
229

#endif /* RTS_SUPPORTS_THREADS */
sof's avatar
sof committed
230

231
#if defined(PARALLEL_HASKELL)
232
233
StgTSO *LastTSO;
rtsTime TimeOfLastYield;
234
rtsBool emitSchedule = rtsTrue;
235
236
#endif

237
#if DEBUG
238
static char *whatNext_strs[] = {
239
  "(unknown)",
240
  "ThreadRunGHC",
241
  "ThreadInterpret",
242
  "ThreadKilled",
243
  "ThreadRelocated",
244
245
246
247
  "ThreadComplete"
};
#endif

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/* -----------------------------------------------------------------------------
 * static function prototypes
 * -------------------------------------------------------------------------- */

#if defined(RTS_SUPPORTS_THREADS)
static void taskStart(void);
#endif

static void schedule( StgMainThread *mainThread USED_WHEN_RTS_SUPPORTS_THREADS,
		      Capability *initialCapability );

//
// These function all encapsulate parts of the scheduler loop, and are
// abstracted only to make the structure and control flow of the
// scheduler clearer.
//
static void schedulePreLoop(void);
static void scheduleStartSignalHandlers(void);
static void scheduleCheckBlockedThreads(void);
267
static void scheduleCheckBlackHoles(void);
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
static void scheduleDetectDeadlock(void);
#if defined(GRAN)
static StgTSO *scheduleProcessEvent(rtsEvent *event);
#endif
#if defined(PARALLEL_HASKELL)
static StgTSO *scheduleSendPendingMessages(void);
static void scheduleActivateSpark(void);
static rtsBool scheduleGetRemoteWork(rtsBool *receivedFinish);
#endif
#if defined(PAR) || defined(GRAN)
static void scheduleGranParReport(void);
#endif
static void schedulePostRunThread(void);
static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
static void scheduleHandleStackOverflow( StgTSO *t);
static rtsBool scheduleHandleYield( StgTSO *t, nat prev_what_next );
static void scheduleHandleThreadBlocked( StgTSO *t );
static rtsBool scheduleHandleThreadFinished( StgMainThread *mainThread, 
					     Capability *cap, StgTSO *t );
287
static rtsBool scheduleDoHeapProfile(rtsBool ready_to_gc);
288
static void scheduleDoGC(Capability *cap);
289
290

static void unblockThread(StgTSO *tso);
291
static rtsBool checkBlackHoles(void);
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
static SchedulerStatus waitThread_(/*out*/StgMainThread* m,
				   Capability *initialCapability
				   );
static void scheduleThread_ (StgTSO* tso);
static void AllRoots(evac_fn evac);

static StgTSO *threadStackOverflow(StgTSO *tso);

static void raiseAsync_(StgTSO *tso, StgClosure *exception, 
			rtsBool stop_at_atomically);

static void printThreadBlockage(StgTSO *tso);
static void printThreadStatus(StgTSO *tso);

#if defined(PARALLEL_HASKELL)
307
308
309
310
StgTSO * createSparkThread(rtsSpark spark);
StgTSO * activateSpark (rtsSpark spark);  
#endif

311
312
313
/* ----------------------------------------------------------------------------
 * Starting Tasks
 * ------------------------------------------------------------------------- */
314

315
#if defined(RTS_SUPPORTS_THREADS)
316
static nat startingWorkerThread = 0;
317

sof's avatar
sof committed
318
319
320
static void
taskStart(void)
{
321
  ACQUIRE_LOCK(&sched_mutex);
322
  startingWorkerThread--;
323
  schedule(NULL,NULL);
324
  taskStop();
325
  RELEASE_LOCK(&sched_mutex);
sof's avatar
sof committed
326
327
}

328
void
329
startSchedulerTaskIfNecessary(void)
330
{
331
332
    if ( !EMPTY_RUN_QUEUE()
	 && !shutting_down_scheduler // not if we're shutting down
333
	 && startingWorkerThread==0)
334
335
336
337
    {
	// we don't want to start another worker thread
	// just because the last one hasn't yet reached the
	// "waiting for capability" state
338
	startingWorkerThread++;
339
	if (!maybeStartNewWorker(taskStart)) {
340
	    startingWorkerThread--;
341
	}
342
    }
343
344
}
#endif
sof's avatar
sof committed
345

346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/* -----------------------------------------------------------------------------
 * Putting a thread on the run queue: different scheduling policies
 * -------------------------------------------------------------------------- */

STATIC_INLINE void
addToRunQueue( StgTSO *t )
{
#if defined(PARALLEL_HASKELL)
    if (RtsFlags.ParFlags.doFairScheduling) { 
	// this does round-robin scheduling; good for concurrency
	APPEND_TO_RUN_QUEUE(t);
    } else {
	// this does unfair scheduling; good for parallelism
	PUSH_ON_RUN_QUEUE(t);
    }
#else
    // this does round-robin scheduling; good for concurrency
    APPEND_TO_RUN_QUEUE(t);
#endif
}
    
367
/* ---------------------------------------------------------------------------
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
   Main scheduling loop.

   We use round-robin scheduling, each thread returning to the
   scheduler loop when one of these conditions is detected:

      * out of heap space
      * timer expires (thread yields)
      * thread blocks
      * thread ends
      * stack overflow

   Locking notes:  we acquire the scheduler lock once at the beginning
   of the scheduler loop, and release it when
    
      * running a thread, or
      * waiting for work, or
      * waiting for a GC to complete.

386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
   GRAN version:
     In a GranSim setup this loop iterates over the global event queue.
     This revolves around the global event queue, which determines what 
     to do next. Therefore, it's more complicated than either the 
     concurrent or the parallel (GUM) setup.

   GUM version:
     GUM iterates over incoming messages.
     It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
     and sends out a fish whenever it has nothing to do; in-between
     doing the actual reductions (shared code below) it processes the
     incoming messages and deals with delayed operations 
     (see PendingFetches).
     This is not the ugliest code you could imagine, but it's bloody close.

401
   ------------------------------------------------------------------------ */
402

403
static void
404
405
schedule( StgMainThread *mainThread USED_WHEN_RTS_SUPPORTS_THREADS,
          Capability *initialCapability )
406
407
{
  StgTSO *t;
408
  Capability *cap;
409
  StgThreadReturnCode ret;
410
411
#if defined(GRAN)
  rtsEvent *event;
412
#elif defined(PARALLEL_HASKELL)
413
414
  StgTSO *tso;
  GlobalTaskId pe;
415
416
417
418
  rtsBool receivedFinish = rtsFalse;
# if defined(DEBUG)
  nat tp_size, sp_size; // stats only
# endif
419
#endif
420
  nat prev_what_next;
421
  rtsBool ready_to_gc;
422
  
423
  // Pre-condition: sched_mutex is held.
424
425
426
  // We might have a capability, passed in as initialCapability.
  cap = initialCapability;

427
#if !defined(RTS_SUPPORTS_THREADS)
428
  // simply initialise it in the non-threaded case
sof's avatar
sof committed
429
  grabCapability(&cap);
sof's avatar
sof committed
430
#endif
431

432
433
434
435
  IF_DEBUG(scheduler,
	   sched_belch("### NEW SCHEDULER LOOP (main thr: %p, cap: %p)",
		       mainThread, initialCapability);
      );
436

437
  schedulePreLoop();
438

439
440
  // -----------------------------------------------------------
  // Scheduler loop starts here:
441

442
443
444
445
446
447
448
#if defined(PARALLEL_HASKELL)
#define TERMINATION_CONDITION        (!receivedFinish)
#elif defined(GRAN)
#define TERMINATION_CONDITION        ((event = get_next_event()) != (rtsEvent*)NULL) 
#else
#define TERMINATION_CONDITION        rtsTrue
#endif
449

450
  while (TERMINATION_CONDITION) {
451

452
453
454
455
456
#if defined(GRAN)
      /* Choose the processor with the next event */
      CurrentProc = event->proc;
      CurrentTSO = event->tso;
#endif
457

458
      IF_DEBUG(scheduler, printAllThreads());
459

sof's avatar
sof committed
460
#if defined(RTS_SUPPORTS_THREADS)
461
462
463
464
465
      // Yield the capability to higher-priority tasks if necessary.
      //
      if (cap != NULL) {
	  yieldCapability(&cap);
      }
466

467
468
469
470
471
472
473
474
      // If we do not currently hold a capability, we wait for one
      //
      if (cap == NULL) {
	  waitForCapability(&sched_mutex, &cap,
			    mainThread ? &mainThread->bound_thread_cond : NULL);
      }

      // We now have a capability...
sof's avatar
sof committed
475
476
#endif

477
478
479
    // Check whether we have re-entered the RTS from Haskell without
    // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
    // call).
480
    if (cap->r.rInHaskell) {
481
482
483
484
485
    	  errorBelch("schedule: re-entered unsafely.\n"
    		     "   Perhaps a 'foreign import unsafe' should be 'safe'?");
    	  stg_exit(1);
    }

486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
    //
    // Test for interruption.  If interrupted==rtsTrue, then either
    // we received a keyboard interrupt (^C), or the scheduler is
    // trying to shut down all the tasks (shutting_down_scheduler) in
    // the threaded RTS.
    //
    if (interrupted) {
	if (shutting_down_scheduler) {
	    IF_DEBUG(scheduler, sched_belch("shutting down"));
	    releaseCapability(cap);
	    if (mainThread) {
		mainThread->stat = Interrupted;
		mainThread->ret  = NULL;
	    }
	    return;
	} else {
	    IF_DEBUG(scheduler, sched_belch("interrupted"));
	    deleteAllThreads();
	}
    }
506
507

#if defined(not_yet) && defined(SMP)
508
    //
509
510
511
    // Top up the run queue from our spark pool.  We try to make the
    // number of threads in the run queue equal to the number of
    // free capabilities.
512
    //
513
514
515
516
517
518
519
520
521
522
523
524
525
    {
	StgClosure *spark;
	if (EMPTY_RUN_QUEUE()) {
	    spark = findSpark(rtsFalse);
	    if (spark == NULL) {
		break; /* no more sparks in the pool */
	    } else {
		createSparkThread(spark);	  
		IF_DEBUG(scheduler,
			 sched_belch("==^^ turning spark of closure %p into a thread",
				     (StgClosure *)spark));
	    }
	}
526
    }
527
#endif // SMP
528

529
    scheduleStartSignalHandlers();
530

531
532
533
534
535
536
    // Only check the black holes here if we've nothing else to do.
    // During normal execution, the black hole list only gets checked
    // at GC time, to avoid repeatedly traversing this possibly long
    // list each time around the scheduler.
    if (EMPTY_RUN_QUEUE()) { scheduleCheckBlackHoles(); }

537
538
539
540
541
542
543
544
545
    scheduleCheckBlockedThreads();

    scheduleDetectDeadlock();

    // Normally, the only way we can get here with no threads to
    // run is if a keyboard interrupt received during 
    // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
    // Additionally, it is not fatal for the
    // threaded RTS to reach here with no threads to run.
546
    //
547
548
549
550
551
    // win32: might be here due to awaitEvent() being abandoned
    // as a result of a console event having been delivered.
    if ( EMPTY_RUN_QUEUE() ) {
#if !defined(RTS_SUPPORTS_THREADS) && !defined(mingw32_HOST_OS)
	ASSERT(interrupted);
552
#endif
553
	continue; // nothing to do
554
    }
555

556
557
558
559
#if defined(PARALLEL_HASKELL)
    scheduleSendPendingMessages();
    if (EMPTY_RUN_QUEUE() && scheduleActivateSpark()) 
	continue;
560

561
562
563
#if defined(SPARKS)
    ASSERT(next_fish_to_send_at==0);  // i.e. no delayed fishes left!
#endif
564

565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
    /* If we still have no work we need to send a FISH to get a spark
       from another PE */
    if (EMPTY_RUN_QUEUE()) {
	if (!scheduleGetRemoteWork(&receivedFinish)) continue;
	ASSERT(rtsFalse); // should not happen at the moment
    }
    // from here: non-empty run queue.
    //  TODO: merge above case with this, only one call processMessages() !
    if (PacketsWaiting()) {  /* process incoming messages, if
				any pending...  only in else
				because getRemoteWork waits for
				messages as well */
	receivedFinish = processMessages();
    }
#endif
580

581
582
583
#if defined(GRAN)
    scheduleProcessEvent(event);
#endif
584

585
586
587
588
589
    // 
    // Get a thread to run
    //
    ASSERT(run_queue_hd != END_TSO_QUEUE);
    POP_RUN_QUEUE(t);
590

591
592
593
594
595
596
#if defined(GRAN) || defined(PAR)
    scheduleGranParReport(); // some kind of debuging output
#else
    // Sanity check the thread we're about to run.  This can be
    // expensive if there is lots of thread switching going on...
    IF_DEBUG(sanity,checkTSO(t));
597
598
#endif

599
600
601
602
603
604
605
606
607
#if defined(RTS_SUPPORTS_THREADS)
    // Check whether we can run this thread in the current task.
    // If not, we have to pass our capability to the right task.
    {
      StgMainThread *m = t->main;
      
      if(m)
      {
	if(m == mainThread)
608
	{
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
	  IF_DEBUG(scheduler,
	    sched_belch("### Running thread %d in bound thread", t->id));
	  // yes, the Haskell thread is bound to the current native thread
	}
	else
	{
	  IF_DEBUG(scheduler,
	    sched_belch("### thread %d bound to another OS thread", t->id));
	  // no, bound to a different Haskell thread: pass to that thread
	  PUSH_ON_RUN_QUEUE(t);
	  passCapability(&m->bound_thread_cond);
	  continue;
	}
      }
      else
      {
	if(mainThread != NULL)
        // The thread we want to run is bound.
	{
	  IF_DEBUG(scheduler,
	    sched_belch("### this OS thread cannot run thread %d", t->id));
	  // no, the current native thread is bound to a different
	  // Haskell thread, so pass it to any worker thread
	  PUSH_ON_RUN_QUEUE(t);
	  passCapabilityToWorker();
	  continue; 
635
	}
636
      }
637
638
639
    }
#endif

640
641
642
643
644
    cap->r.rCurrentTSO = t;
    
    /* context switches are now initiated by the timer signal, unless
     * the user specified "context switch as often as possible", with
     * +RTS -C0
sof's avatar
sof committed
645
     */
646
647
648
649
650
    if ((RtsFlags.ConcFlags.ctxtSwitchTicks == 0
	 && (run_queue_hd != END_TSO_QUEUE
	     || blocked_queue_hd != END_TSO_QUEUE
	     || sleeping_queue != END_TSO_QUEUE)))
	context_switch = 1;
651

652
run_thread:
653

654
    RELEASE_LOCK(&sched_mutex);
655

656
657
    IF_DEBUG(scheduler, sched_belch("-->> running thread %ld %s ...", 
			      (long)t->id, whatNext_strs[t->what_next]));
658

659
660
661
662
#if defined(PROFILING)
    startHeapProfTimer();
#endif

663
664
665
    // ----------------------------------------------------------------------
    // Run the current thread 

666
667
668
    prev_what_next = t->what_next;

    errno = t->saved_errno;
669
    cap->r.rInHaskell = rtsTrue;
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690

    switch (prev_what_next) {

    case ThreadKilled:
    case ThreadComplete:
	/* Thread already finished, return to scheduler. */
	ret = ThreadFinished;
	break;

    case ThreadRunGHC:
	ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
	break;

    case ThreadInterpret:
	ret = interpretBCO(cap);
	break;

    default:
      barf("schedule: invalid what_next field");
    }

691
692
693
694
695
696
    // We have run some Haskell code: there might be blackhole-blocked
    // threads to wake up now.
    if ( blackhole_queue != END_TSO_QUEUE ) {
	blackholes_need_checking = rtsTrue;
    }

697
    cap->r.rInHaskell = rtsFalse;
698
699
700
701
702
703
704
705

    // The TSO might have moved, eg. if it re-entered the RTS and a GC
    // happened.  So find the new location:
    t = cap->r.rCurrentTSO;

    // And save the current errno in this thread.
    t->saved_errno = errno;

706
    // ----------------------------------------------------------------------
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
    
    /* Costs for the scheduler are assigned to CCS_SYSTEM */
#if defined(PROFILING)
    stopHeapProfTimer();
    CCCS = CCS_SYSTEM;
#endif
    
    ACQUIRE_LOCK(&sched_mutex);
    
#if defined(RTS_SUPPORTS_THREADS)
    IF_DEBUG(scheduler,debugBelch("sched (task %p): ", osThreadId()););
#elif !defined(GRAN) && !defined(PARALLEL_HASKELL)
    IF_DEBUG(scheduler,debugBelch("sched: "););
#endif
    
    schedulePostRunThread();

724
725
    ready_to_gc = rtsFalse;

726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
    switch (ret) {
    case HeapOverflow:
	ready_to_gc = scheduleHandleHeapOverflow(cap,t);
	break;

    case StackOverflow:
	scheduleHandleStackOverflow(t);
	break;

    case ThreadYielding:
	if (scheduleHandleYield(t, prev_what_next)) {
            // shortcut for switching between compiler/interpreter:
	    goto run_thread; 
	}
	break;

    case ThreadBlocked:
	scheduleHandleThreadBlocked(t);
	threadPaused(t);
	break;

    case ThreadFinished:
	if (scheduleHandleThreadFinished(mainThread, cap, t)) return;;
	break;

    default:
      barf("schedule: invalid thread return code %d", (int)ret);
    }

755
    if (scheduleDoHeapProfile(ready_to_gc)) { ready_to_gc = rtsFalse; }
756
    if (ready_to_gc) { scheduleDoGC(cap); }
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
  } /* end of while() */

  IF_PAR_DEBUG(verbose,
	       debugBelch("== Leaving schedule() after having received Finish\n"));
}

/* ----------------------------------------------------------------------------
 * Setting up the scheduler loop
 * ASSUMES: sched_mutex
 * ------------------------------------------------------------------------- */

static void
schedulePreLoop(void)
{
#if defined(GRAN) 
    /* set up first event to get things going */
    /* ToDo: assign costs for system setup and init MainTSO ! */
    new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
	      ContinueThread, 
	      CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
    
    IF_DEBUG(gran,
	     debugBelch("GRAN: Init CurrentTSO (in schedule) = %p\n", 
			CurrentTSO);
	     G_TSO(CurrentTSO, 5));
    
    if (RtsFlags.GranFlags.Light) {
	/* Save current time; GranSim Light only */
	CurrentTSO->gran.clock = CurrentTime[CurrentProc];
    }      
#endif
}

/* ----------------------------------------------------------------------------
 * Start any pending signal handlers
 * ASSUMES: sched_mutex
 * ------------------------------------------------------------------------- */

static void
scheduleStartSignalHandlers(void)
{
798
#if defined(RTS_USER_SIGNALS) && !defined(RTS_SUPPORTS_THREADS)
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
    if (signals_pending()) {
      RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
      startSignalHandlers();
      ACQUIRE_LOCK(&sched_mutex);
    }
#endif
}

/* ----------------------------------------------------------------------------
 * Check for blocked threads that can be woken up.
 * ASSUMES: sched_mutex
 * ------------------------------------------------------------------------- */

static void
scheduleCheckBlockedThreads(void)
{
    //
    // Check whether any waiting threads need to be woken up.  If the
    // run queue is empty, and there are no other tasks running, we
    // can wait indefinitely for something to happen.
    //
    if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue) )
    {
#if defined(RTS_SUPPORTS_THREADS)
	// We shouldn't be here...
	barf("schedule: awaitEvent() in threaded RTS");
#endif
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
	awaitEvent( EMPTY_RUN_QUEUE() && !blackholes_need_checking );
    }
}


/* ----------------------------------------------------------------------------
 * Check for threads blocked on BLACKHOLEs that can be woken up
 * ASSUMES: sched_mutex
 * ------------------------------------------------------------------------- */
static void
scheduleCheckBlackHoles( void )
{
    if ( blackholes_need_checking )
    {
	checkBlackHoles();
	blackholes_need_checking = rtsFalse;
842
843
844
845
846
847
848
849
850
851
852
853
854
    }
}

/* ----------------------------------------------------------------------------
 * Detect deadlock conditions and attempt to resolve them.
 * ASSUMES: sched_mutex
 * ------------------------------------------------------------------------- */

static void
scheduleDetectDeadlock(void)
{
    /* 
     * Detect deadlock: when we have no threads to run, there are no
855
856
857
     * threads blocked, waiting for I/O, or sleeping, and all the
     * other tasks are waiting for work, we must have a deadlock of
     * some description.
858
859
860
     */
    if ( EMPTY_THREAD_QUEUES() )
    {
861
#if !defined(PARALLEL_HASKELL) && !defined(RTS_SUPPORTS_THREADS)
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
	IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));

	// Garbage collection can release some new threads due to
	// either (a) finalizers or (b) threads resurrected because
	// they are unreachable and will therefore be sent an
	// exception.  Any threads thus released will be immediately
	// runnable.
	GarbageCollect(GetRoots,rtsTrue);
	if ( !EMPTY_RUN_QUEUE() ) return;

#if defined(RTS_USER_SIGNALS)
	/* If we have user-installed signal handlers, then wait
	 * for signals to arrive rather then bombing out with a
	 * deadlock.
	 */
	if ( anyUserHandlers() ) {
	    IF_DEBUG(scheduler, 
		     sched_belch("still deadlocked, waiting for signals..."));

	    awaitUserSignals();

	    if (signals_pending()) {
		RELEASE_LOCK(&sched_mutex);
		startSignalHandlers();
		ACQUIRE_LOCK(&sched_mutex);
	    }

	    // either we have threads to run, or we were interrupted:
	    ASSERT(!EMPTY_RUN_QUEUE() || interrupted);
	}
#endif

	/* Probably a real deadlock.  Send the current main thread the
	 * Deadlock exception (or in the SMP build, send *all* main
	 * threads the deadlock exception, since none of them can make
	 * progress).
	 */
	{
	    StgMainThread *m;
	    m = main_threads;
	    switch (m->tso->why_blocked) {
903
	    case BlockedOnSTM:
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
	    case BlockedOnBlackHole:
	    case BlockedOnException:
	    case BlockedOnMVar:
		raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
		return;
	    default:
		barf("deadlock: main thread blocked in a strange way");
	    }
	}

#elif defined(RTS_SUPPORTS_THREADS)
    // ToDo: add deadlock detection in threaded RTS
#elif defined(PARALLEL_HASKELL)
    // ToDo: add deadlock detection in GUM (similar to SMP) -- HWL
#endif
919
    }
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
}

/* ----------------------------------------------------------------------------
 * Process an event (GRAN only)
 * ------------------------------------------------------------------------- */

#if defined(GRAN)
static StgTSO *
scheduleProcessEvent(rtsEvent *event)
{
    StgTSO *t;

    if (RtsFlags.GranFlags.Light)
      GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc

    /* adjust time based on time-stamp */
    if (event->time > CurrentTime[CurrentProc] &&
        event->evttype != ContinueThread)
      CurrentTime[CurrentProc] = event->time;
    
    /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
    if (!RtsFlags.GranFlags.Light)
      handleIdlePEs();

    IF_DEBUG(gran, debugBelch("GRAN: switch by event-type\n"));

    /* main event dispatcher in GranSim */
    switch (event->evttype) {
      /* Should just be continuing execution */
    case ContinueThread:
      IF_DEBUG(gran, debugBelch("GRAN: doing ContinueThread\n"));
      /* ToDo: check assertion
      ASSERT(run_queue_hd != (StgTSO*)NULL &&
	     run_queue_hd != END_TSO_QUEUE);
      */
      /* Ignore ContinueThreads for fetching threads (if synchr comm) */
956
957
      if (!RtsFlags.GranFlags.DoAsyncFetch &&
	  procStatus[CurrentProc]==Fetching) {
958
	debugBelch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]\n",
959
960
961
962
963
	      CurrentTSO->id, CurrentTSO, CurrentProc);
	goto next_thread;
      }	
      /* Ignore ContinueThreads for completed threads */
      if (CurrentTSO->what_next == ThreadComplete) {
964
	debugBelch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)\n", 
965
966
967
968
969
	      CurrentTSO->id, CurrentTSO, CurrentProc);
	goto next_thread;
      }	
      /* Ignore ContinueThreads for threads that are being migrated */
      if (PROCS(CurrentTSO)==Nowhere) { 
970
	debugBelch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)\n",
971
972
973
974
975
	      CurrentTSO->id, CurrentTSO, CurrentProc);
	goto next_thread;
      }
      /* The thread should be at the beginning of the run queue */
      if (CurrentTSO!=run_queue_hds[CurrentProc]) { 
976
	debugBelch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread\n",
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
	      CurrentTSO->id, CurrentTSO, CurrentProc);
	break; // run the thread anyway
      }
      /*
      new_event(proc, proc, CurrentTime[proc],
		FindWork,
		(StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
      goto next_thread; 
      */ /* Catches superfluous CONTINUEs -- should be unnecessary */
      break; // now actually run the thread; DaH Qu'vam yImuHbej 

    case FetchNode:
      do_the_fetchnode(event);
      goto next_thread;             /* handle next event in event queue  */
      
    case GlobalBlock:
      do_the_globalblock(event);
      goto next_thread;             /* handle next event in event queue  */
      
    case FetchReply:
      do_the_fetchreply(event);
      goto next_thread;             /* handle next event in event queue  */
      
    case UnblockThread:   /* Move from the blocked queue to the tail of */