Schedule.c 103 KB
Newer Older
1
/* ---------------------------------------------------------------------------
sof's avatar
sof committed
2
 * $Id: Schedule.c,v 1.194 2004/03/13 00:56:45 sof Exp $
3
 *
4
 * (c) The GHC Team, 1998-2003
5 6 7
 *
 * Scheduler
 *
8 9 10 11 12
 * Different GHC ways use this scheduler quite differently (see comments below)
 * Here is the global picture:
 *
 * WAY  Name     CPP flag  What's it for
 * --------------------------------------
13
 * mp   GUM      PAR          Parallel execution on a distrib. memory machine
sof's avatar
sof committed
14 15 16 17
 * 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)
 *
18 19
 * --------------------------------------------------------------------------*/

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/* 
 * 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
38 39
*/

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

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

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

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

95 96 97 98 99 100 101 102 103 104 105 106
#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

107 108 109
/* Main thread queue.
 * Locks required: sched_mutex.
 */
110
StgMainThread *main_threads = NULL;
111 112 113 114

/* Thread queues.
 * Locks required: sched_mutex.
 */
115 116 117
#if defined(GRAN)

StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
118
/* rtsTime TimeOfNextEvent, EndOfTimeSlice;            now in GranSim.c */
119 120

/* 
sof's avatar
sof committed
121
   In GranSim we have a runnable and a blocked queue for each processor.
122 123 124 125 126 127 128 129
   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];
130 131 132 133
/* 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).  */
134 135 136

#else /* !GRAN */

137 138 139 140 141
StgTSO *run_queue_hd = NULL;
StgTSO *run_queue_tl = NULL;
StgTSO *blocked_queue_hd = NULL;
StgTSO *blocked_queue_tl = NULL;
StgTSO *sleeping_queue = NULL;    /* perhaps replace with a hash table? */
142

143 144
#endif

145 146 147
/* Linked list of all threads.
 * Used for detecting garbage collected threads.
 */
148
StgTSO *all_threads = NULL;
149

sof's avatar
sof committed
150 151 152
/* 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.
153 154 155
 */
static StgTSO *suspended_ccalling_threads;

156 157
static StgTSO *threadStackOverflow(StgTSO *tso);

158 159 160 161 162
/* 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.
*/

163
/* flag set by signal handler to precipitate a context switch */
164
nat context_switch = 0;
165

166
/* if this flag is set as well, give up execution */
167
rtsBool interrupted = rtsFalse;
168

169
/* Next thread ID to allocate.
sof's avatar
sof committed
170
 * Locks required: thread_id_mutex
171
 */
172
static StgThreadID next_thread_id = 1;
173 174 175 176 177 178

/*
 * 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.
 */
179
 
180 181 182 183
/* 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)
184 185
 *  + 1			      (stg_ap_v_ret)
 *  + 1			      (spare slot req'd by stg_ap_v_ret)
186 187 188 189 190
 *
 * A thread with this stack will bomb immediately with a stack
 * overflow, which will increase its stack size.  
 */

191
#define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 3)
192

sof's avatar
sof committed
193

194
#if defined(GRAN)
195
StgTSO *CurrentTSO;
196 197
#endif

198 199 200 201 202 203
/*  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;

204
static rtsBool ready_to_gc;
sof's avatar
sof committed
205 206 207 208 209 210 211

/*
 * 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;
212 213 214

void            addToBlockedQueue ( StgTSO *tso );

215
static void     schedule          ( StgMainThread *mainThread, Capability *initialCapability );
216
       void     interruptStgRts   ( void );
217

218 219
static void     detectBlackHoles  ( void );

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

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

229 230 231
#if defined(PAR)
StgTSO *LastTSO;
rtsTime TimeOfLastYield;
232
rtsBool emitSchedule = rtsTrue;
233 234
#endif

235
#if DEBUG
236
static char *whatNext_strs[] = {
237
  "ThreadRunGHC",
238
  "ThreadInterpret",
239
  "ThreadKilled",
240
  "ThreadRelocated",
241 242 243 244
  "ThreadComplete"
};
#endif

sof's avatar
sof committed
245
#if defined(PAR)
246 247 248 249
StgTSO * createSparkThread(rtsSpark spark);
StgTSO * activateSpark (rtsSpark spark);  
#endif

250 251 252
/* ----------------------------------------------------------------------------
 * Starting Tasks
 * ------------------------------------------------------------------------- */
253

254 255 256
#if defined(RTS_SUPPORTS_THREADS)
static rtsBool startingWorkerThread = rtsFalse;

sof's avatar
sof committed
257 258 259 260
static void taskStart(void);
static void
taskStart(void)
{
261
  ACQUIRE_LOCK(&sched_mutex);
262
  startingWorkerThread = rtsFalse;
263
  schedule(NULL,NULL);
264
  RELEASE_LOCK(&sched_mutex);
sof's avatar
sof committed
265 266
}

267
void
268
startSchedulerTaskIfNecessary(void)
269
{
270 271 272 273 274 275 276 277 278 279 280 281
  if(run_queue_hd != END_TSO_QUEUE
    || blocked_queue_hd != END_TSO_QUEUE
    || sleeping_queue != END_TSO_QUEUE)
  {
    if(!startingWorkerThread)
    { // we don't want to start another worker thread
      // just because the last one hasn't yet reached the
      // "waiting for capability" state
      startingWorkerThread = rtsTrue;
      startTask(taskStart);
    }
  }
282 283
}
#endif
sof's avatar
sof committed
284

285
/* ---------------------------------------------------------------------------
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
   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.

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
   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.

319
   ------------------------------------------------------------------------ */
320
static void
321 322
schedule( StgMainThread *mainThread USED_WHEN_RTS_SUPPORTS_THREADS,
          Capability *initialCapability )
323 324
{
  StgTSO *t;
325
  Capability *cap;
326
  StgThreadReturnCode ret;
327 328 329
#if defined(GRAN)
  rtsEvent *event;
#elif defined(PAR)
330
  StgSparkPool *pool;
331 332 333
  rtsSpark spark;
  StgTSO *tso;
  GlobalTaskId pe;
334 335 336 337
  rtsBool receivedFinish = rtsFalse;
# if defined(DEBUG)
  nat tp_size, sp_size; // stats only
# endif
338
#endif
339
  rtsBool was_interrupted = rtsFalse;
340
  StgTSOWhatNext prev_what_next;
341
  
342
  // Pre-condition: sched_mutex is held.
343 344 345
  // We might have a capability, passed in as initialCapability.
  cap = initialCapability;

sof's avatar
sof committed
346
#if defined(RTS_SUPPORTS_THREADS)
347 348 349 350 351
  //
  // in the threaded case, the capability is either passed in via the
  // initialCapability parameter, or initialized inside the scheduler
  // loop 
  //
352
  IF_DEBUG(scheduler,
353 354 355
	   sched_belch("### NEW SCHEDULER LOOP (main thr: %p, cap: %p)",
		       mainThread, initialCapability);
      );
sof's avatar
sof committed
356
#else
357
  // simply initialise it in the non-threaded case
sof's avatar
sof committed
358
  grabCapability(&cap);
sof's avatar
sof committed
359
#endif
360

361
#if defined(GRAN)
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
  /* 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,
	   fprintf(stderr, "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];
  }      

  event = get_next_event();

  while (event!=(rtsEvent*)NULL) {
    /* Choose the processor with the next event */
    CurrentProc = event->proc;
    CurrentTSO = event->tso;

384
#elif defined(PAR)
385

386 387
  while (!receivedFinish) {    /* set by processMessages */
                               /* when receiving PP_FINISH message         */ 
388 389

#else // everything except GRAN and PAR
390

391
  while (1) {
392

393
#endif
394

395
     IF_DEBUG(scheduler, printAllThreads());
396

sof's avatar
sof committed
397
#if defined(RTS_SUPPORTS_THREADS)
398 399 400 401 402
      // Yield the capability to higher-priority tasks if necessary.
      //
      if (cap != NULL) {
	  yieldCapability(&cap);
      }
403

404 405 406 407 408 409 410 411
      // 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
412 413
#endif

414 415 416 417 418
    //
    // If we're interrupted (the user pressed ^C, or some other
    // termination condition occurred), kill all the currently running
    // threads.
    //
419
    if (interrupted) {
420 421 422
	IF_DEBUG(scheduler, sched_belch("interrupted"));
	interrupted = rtsFalse;
	was_interrupted = rtsTrue;
423
#if defined(RTS_SUPPORTS_THREADS)
424 425 426 427 428 429
	// In the threaded RTS, deadlock detection doesn't work,
	// so just exit right away.
	prog_belch("interrupted");
	releaseCapability(cap);
	RELEASE_LOCK(&sched_mutex);
	shutdownHaskellAndExit(EXIT_SUCCESS);
430
#else
431
	deleteAllThreads();
432
#endif
433 434
    }

sof's avatar
sof committed
435
#if defined(RTS_USER_SIGNALS)
436
    // check for signals each time around the scheduler
437
    if (signals_pending()) {
sof's avatar
sof committed
438
      RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
439
      startSignalHandlers();
sof's avatar
sof committed
440
      ACQUIRE_LOCK(&sched_mutex);
441 442 443
    }
#endif

444 445 446 447 448 449
    //
    // 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)
450
#if defined(RTS_SUPPORTS_THREADS)
451 452
		|| EMPTY_RUN_QUEUE()
#endif
453
	)
454
    {
455
      awaitEvent( EMPTY_RUN_QUEUE() );
456
    }
457
    // we can be interrupted while waiting for I/O...
458 459
    if (interrupted) continue;

460 461 462 463 464 465 466 467 468 469
    /* 
     * Detect deadlock: when we have no threads to run, there are no
     * threads waiting on I/O or sleeping, and all the other tasks are
     * waiting for work, we must have a deadlock of some description.
     *
     * We first try to find threads blocked on themselves (ie. black
     * holes), and generate NonTermination exceptions where necessary.
     *
     * If no threads are black holed, we have a deadlock situation, so
     * inform all the main threads.
470
     */
471
#if !defined(PAR) && !defined(RTS_SUPPORTS_THREADS)
472
    if (   EMPTY_THREAD_QUEUES() )
473
    {
474
	IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
475 476 477 478
	// Garbage collection can release some new threads due to
	// either (a) finalizers or (b) threads resurrected because
	// they are about to be send BlockedOnDeadMVar.  Any threads
	// thus released will be immediately runnable.
479
	GarbageCollect(GetRoots,rtsTrue);
480 481 482 483 484 485 486 487 488

	if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }

	IF_DEBUG(scheduler, 
		 sched_belch("still deadlocked, checking for black holes..."));
	detectBlackHoles();

	if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }

sof's avatar
sof committed
489
#if defined(RTS_USER_SIGNALS)
490 491 492 493 494 495 496 497 498 499 500 501 502 503
	/* 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();

	    // we might be interrupted...
	    if (interrupted) { continue; }

	    if (signals_pending()) {
sof's avatar
sof committed
504
		RELEASE_LOCK(&sched_mutex);
505
		startSignalHandlers();
sof's avatar
sof committed
506
		ACQUIRE_LOCK(&sched_mutex);
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
	    }
	    ASSERT(!EMPTY_RUN_QUEUE());
	    goto not_deadlocked;
	}
#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) {
	    case BlockedOnBlackHole:
	    case BlockedOnException:
	    case BlockedOnMVar:
525
		raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
526 527 528
		break;
	    default:
		barf("deadlock: main thread blocked in a strange way");
sof's avatar
sof committed
529
	    }
530
	}
531
    }
532 533
  not_deadlocked:

534
#elif defined(RTS_SUPPORTS_THREADS)
535
    // ToDo: add deadlock detection in threaded RTS
536
#elif defined(PAR)
537
    // ToDo: add deadlock detection in GUM (similar to SMP) -- HWL
538 539
#endif

sof's avatar
sof committed
540
#if defined(RTS_SUPPORTS_THREADS)
541
    if ( EMPTY_RUN_QUEUE() ) {
542
	continue; // nothing to do
543 544
    }
#endif
545 546

#if defined(GRAN)
547 548 549 550 551 552 553 554 555 556 557 558
    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();

559
    IF_DEBUG(gran, fprintf(stderr, "GRAN: switch by event-type\n"));
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 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 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668

    /* main event dispatcher in GranSim */
    switch (event->evttype) {
      /* Should just be continuing execution */
    case ContinueThread:
      IF_DEBUG(gran, fprintf(stderr, "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) */
      if (!RtsFlags.GranFlags.DoAsyncFetch &&
	  procStatus[CurrentProc]==Fetching) {
	belch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]",
	      CurrentTSO->id, CurrentTSO, CurrentProc);
	goto next_thread;
      }	
      /* Ignore ContinueThreads for completed threads */
      if (CurrentTSO->what_next == ThreadComplete) {
	belch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)", 
	      CurrentTSO->id, CurrentTSO, CurrentProc);
	goto next_thread;
      }	
      /* Ignore ContinueThreads for threads that are being migrated */
      if (PROCS(CurrentTSO)==Nowhere) { 
	belch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)",
	      CurrentTSO->id, CurrentTSO, CurrentProc);
	goto next_thread;
      }
      /* The thread should be at the beginning of the run queue */
      if (CurrentTSO!=run_queue_hds[CurrentProc]) { 
	belch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread",
	      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 */
      do_the_unblock(event);
      goto next_thread;             /* handle next event in event queue  */
      
    case ResumeThread:  /* Move from the blocked queue to the tail of */
      /* the runnable queue ( i.e. Qu' SImqa'lu') */ 
      event->tso->gran.blocktime += 
	CurrentTime[CurrentProc] - event->tso->gran.blockedat;
      do_the_startthread(event);
      goto next_thread;             /* handle next event in event queue  */
      
    case StartThread:
      do_the_startthread(event);
      goto next_thread;             /* handle next event in event queue  */
      
    case MoveThread:
      do_the_movethread(event);
      goto next_thread;             /* handle next event in event queue  */
      
    case MoveSpark:
      do_the_movespark(event);
      goto next_thread;             /* handle next event in event queue  */
      
    case FindWork:
      do_the_findwork(event);
      goto next_thread;             /* handle next event in event queue  */
      
    default:
      barf("Illegal event type %u\n", event->evttype);
    }  /* switch */
    
    /* This point was scheduler_loop in the old RTS */

    IF_DEBUG(gran, belch("GRAN: after main switch"));

    TimeOfLastEvent = CurrentTime[CurrentProc];
    TimeOfNextEvent = get_time_of_next_event();
    IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
    // CurrentTSO = ThreadQueueHd;

    IF_DEBUG(gran, belch("GRAN: time of next event is: %ld", 
			 TimeOfNextEvent));

    if (RtsFlags.GranFlags.Light) 
      GranSimLight_leave_system(event, &ActiveTSO); 

    EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;

    IF_DEBUG(gran, 
	     belch("GRAN: end of time-slice is %#lx", EndOfTimeSlice));

    /* in a GranSim setup the TSO stays on the run queue */
    t = CurrentTSO;
    /* Take a thread from the run queue. */
sof's avatar
sof committed
669
    POP_RUN_QUEUE(t); // take_off_run_queue(t);
670 671 672

    IF_DEBUG(gran, 
	     fprintf(stderr, "GRAN: About to run current thread, which is\n");
673
	     G_TSO(t,5));
674 675 676 677 678 679 680 681

    context_switch = 0; // turned on via GranYield, checking events and time slice

    IF_DEBUG(gran, 
	     DumpGranEvent(GR_SCHEDULE, t));

    procStatus[CurrentProc] = Busy;

682
#elif defined(PAR)
683 684 685 686
    if (PendingFetches != END_BF_QUEUE) {
        processFetches();
    }

687
    /* ToDo: phps merge with spark activation above */
688
    /* check whether we have local work and send requests if we have none */
689
    if (EMPTY_RUN_QUEUE()) {  /* no runnable threads */
690
      /* :-[  no local threads => look out for local sparks */
691 692
      /* the spark pool for the current PE */
      pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
693
      if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
694
	  pool->hd < pool->tl) {
695 696 697 698 699 700 701 702
	/* 
	 * ToDo: add GC code check that we really have enough heap afterwards!!
	 * Old comment:
	 * If we're here (no runnable threads) and we have pending
	 * sparks, we must have a space problem.  Get enough space
	 * to turn one of those pending sparks into a
	 * thread... 
	 */
703 704

	spark = findSpark(rtsFalse);                /* get a spark */
705 706
	if (spark != (rtsSpark) NULL) {
	  tso = activateSpark(spark);       /* turn the spark into a thread */
707 708 709
	  IF_PAR_DEBUG(schedule,
		       belch("==== schedule: Created TSO %d (%p); %d threads active",
			     tso->id, tso, advisory_thread_count));
710

711
	  if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
712
	    belch("==^^ failed to activate spark");
713
	    goto next_thread;
714
	  }               /* otherwise fall through & pick-up new tso */
715 716
	} else {
	  IF_PAR_DEBUG(verbose,
717 718
		       belch("==^^ no local sparks (spark pool contains only NFs: %d)", 
			     spark_queue_len(pool)));
719 720
	  goto next_thread;
	}
721 722 723 724 725 726
      }

      /* If we still have no work we need to send a FISH to get a spark
	 from another PE 
      */
      if (EMPTY_RUN_QUEUE()) {
727 728 729 730 731 732 733 734 735
      /* =8-[  no local sparks => look for work on other PEs */
	/*
	 * We really have absolutely no work.  Send out a fish
	 * (there may be some out there already), and wait for
	 * something to arrive.  We clearly can't run any threads
	 * until a SCHEDULE or RESUME arrives, and so that's what
	 * we're hoping to see.  (Of course, we still have to
	 * respond to other types of messages.)
	 */
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
	TIME now = msTime() /*CURRENT_TIME*/;
	IF_PAR_DEBUG(verbose, 
		     belch("--  now=%ld", now));
	IF_PAR_DEBUG(verbose,
		     if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
			 (last_fish_arrived_at!=0 &&
			  last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
		       belch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)",
			     last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
			     last_fish_arrived_at,
			     RtsFlags.ParFlags.fishDelay, now);
		     });
	
	if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
	    (last_fish_arrived_at==0 ||
	     (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
	  /* outstandingFishes is set in sendFish, processFish;
753 754 755 756
	     avoid flooding system with fishes via delay */
	  pe = choosePE();
	  sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY, 
		   NEW_FISH_HUNGER);
757 758 759 760 761 762

	  // Global statistics: count no. of fishes
	  if (RtsFlags.ParFlags.ParStats.Global &&
	      RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
	    globalParStats.tot_fish_mess++;
	  }
763
	}
764 765
      
	receivedFinish = processMessages();
766 767 768
	goto next_thread;
      }
    } else if (PacketsWaiting()) {  /* Look for incoming messages */
769
      receivedFinish = processMessages();
770 771 772 773
    }

    /* Now we are sure that we have some work available */
    ASSERT(run_queue_hd != END_TSO_QUEUE);
774

775
    /* Take a thread from the run queue, if we have work */
sof's avatar
sof committed
776
    POP_RUN_QUEUE(t);  // take_off_run_queue(END_TSO_QUEUE);
777
    IF_DEBUG(sanity,checkTSO(t));
778 779 780 781 782 783

    /* ToDo: write something to the log-file
    if (RTSflags.ParFlags.granSimStats && !sameThread)
        DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);

    CurrentTSO = t;
784 785 786
    */
    /* the spark pool for the current PE */
    pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
787

788 789 790 791
    IF_DEBUG(scheduler, 
	     belch("--=^ %d threads, %d sparks on [%#x]", 
		   run_queue_len(), spark_queue_len(pool), CURRENT_PROC));

sof's avatar
sof committed
792
# if 1
793 794 795 796 797 798 799 800
    if (0 && RtsFlags.ParFlags.ParStats.Full && 
	t && LastTSO && t->id != LastTSO->id && 
	LastTSO->why_blocked == NotBlocked && 
	LastTSO->what_next != ThreadComplete) {
      // if previously scheduled TSO not blocked we have to record the context switch
      DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
			   GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
    }
801

802 803 804
    if (RtsFlags.ParFlags.ParStats.Full && 
	(emitSchedule /* forced emit */ ||
        (t && LastTSO && t->id != LastTSO->id))) {
805 806 807 808 809 810 811 812 813
      /* 
	 we are running a different TSO, so write a schedule event to log file
	 NB: If we use fair scheduling we also have to write  a deschedule 
	     event for LastTSO; with unfair scheduling we know that the
	     previous tso has blocked whenever we switch to another tso, so
	     we don't need it in GUM for now
      */
      DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
		       GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
814
      emitSchedule = rtsFalse;
815
    }
816
     
sof's avatar
sof committed
817
# endif
818
#else /* !GRAN && !PAR */
819
  
820
    // grab a thread from the run queue
821
    ASSERT(run_queue_hd != END_TSO_QUEUE);
sof's avatar
sof committed
822
    POP_RUN_QUEUE(t);
823

824 825
    // Sanity check the thread we're about to run.  This can be
    // expensive if there is lots of thread switching going on...
826
    IF_DEBUG(sanity,checkTSO(t));
827
#endif
828

829 830
#ifdef THREADED_RTS
    {
831
      StgMainThread *m = t->main;
832 833 834 835 836 837
      
      if(m)
      {
	if(m == mainThread)
	{
	  IF_DEBUG(scheduler,
838
	    sched_belch("### Running thread %d in bound thread", t->id));
839 840 841 842 843
	  // yes, the Haskell thread is bound to the current native thread
	}
	else
	{
	  IF_DEBUG(scheduler,
844
	    sched_belch("### thread %d bound to another OS thread", t->id));
845 846
	  // no, bound to a different Haskell thread: pass to that thread
	  PUSH_ON_RUN_QUEUE(t);
847
	  passCapability(&m->bound_thread_cond);
848 849 850 851 852
	  continue;
	}
      }
      else
      {
853 854
	if(mainThread != NULL)
        // The thread we want to run is bound.
855 856
	{
	  IF_DEBUG(scheduler,
857
	    sched_belch("### this OS thread cannot run thread %d", t->id));
858 859 860
	  // no, the current native thread is bound to a different
	  // Haskell thread, so pass it to any worker thread
	  PUSH_ON_RUN_QUEUE(t);
861
	  passCapabilityToWorker();
862 863 864 865 866 867
	  continue; 
	}
      }
    }
#endif

868
    cap->r.rCurrentTSO = t;
869
    
870 871 872 873
    /* context switches are now initiated by the timer signal, unless
     * the user specified "context switch as often as possible", with
     * +RTS -C0
     */
874
    if ((RtsFlags.ConcFlags.ctxtSwitchTicks == 0
875 876 877
	 && (run_queue_hd != END_TSO_QUEUE
	     || blocked_queue_hd != END_TSO_QUEUE
	     || sleeping_queue != END_TSO_QUEUE)))
878 879 880
	context_switch = 1;
    else
	context_switch = 0;
881

882 883
run_thread:

884
    RELEASE_LOCK(&sched_mutex);
885

886 887
    IF_DEBUG(scheduler, sched_belch("-->> running thread %ld %s ...", 
			      t->id, whatNext_strs[t->what_next]));
888

889 890 891 892
#ifdef PROFILING
    startHeapProfTimer();
#endif

893
    /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
894 895
    /* Run the current thread 
     */
896 897
    prev_what_next = t->what_next;
    switch (prev_what_next) {
898 899
    case ThreadKilled:
    case ThreadComplete:
900 901 902
	/* Thread already finished, return to scheduler. */
	ret = ThreadFinished;
	break;
903
    case ThreadRunGHC:
904
	errno = t->saved_errno;
905
	ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
906
	t->saved_errno = errno;
907
	break;
908
    case ThreadInterpret:
909 910
	ret = interpretBCO(cap);
	break;
911
    default:
912
      barf("schedule: invalid what_next field");
913
    }
914
    /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
915 916 917
    
    /* Costs for the scheduler are assigned to CCS_SYSTEM */
#ifdef PROFILING
918
    stopHeapProfTimer();
919 920 921 922
    CCCS = CCS_SYSTEM;
#endif
    
    ACQUIRE_LOCK(&sched_mutex);
923 924
    
#ifdef RTS_SUPPORTS_THREADS
925
    IF_DEBUG(scheduler,fprintf(stderr,"sched (task %p): ", osThreadId()););
926
#elif !defined(GRAN) && !defined(PAR)
927
    IF_DEBUG(scheduler,fprintf(stderr,"sched: "););
928
#endif
929
    t = cap->r.rCurrentTSO;
930
    
931 932 933 934
#if defined(PAR)
    /* HACK 675: if the last thread didn't yield, make sure to print a 
       SCHEDULE event to the log file when StgRunning the next thread, even
       if it is the same one as before */
935
    LastTSO = t; 
936 937 938
    TimeOfLastYield = CURRENT_TIME;
#endif

939 940
    switch (ret) {
    case HeapOverflow:
941
#if defined(GRAN)
942
      IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
943 944 945 946
      globalGranStats.tot_heapover++;
#elif defined(PAR)
      globalParStats.tot_heapover++;
#endif
947 948 949 950 951 952 953 954 955

      // did the task ask for a large block?
      if (cap->r.rHpAlloc > BLOCK_SIZE_W) {
	  // if so, get one and push it on the front of the nursery.
	  bdescr *bd;
	  nat blocks;
	  
	  blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc * sizeof(W_)) / BLOCK_SIZE;

956 957
	  IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped: requesting a large block (size %d)", 
				   t->id, whatNext_strs[t->what_next], blocks));
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977

	  // don't do this if it would push us over the
	  // alloc_blocks_lim limit; we'll GC first.
	  if (alloc_blocks + blocks < alloc_blocks_lim) {

	      alloc_blocks += blocks;
	      bd = allocGroup( blocks );

	      // link the new group into the list
	      bd->link = cap->r.rCurrentNursery;
	      bd->u.back = cap->r.rCurrentNursery->u.back;
	      if (cap->r.rCurrentNursery->u.back != NULL) {
		  cap->r.rCurrentNursery->u.back->link = bd;
	      } else {
		  ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
			 g0s0->blocks == cap->r.rNursery);
		  cap->r.rNursery = g0s0->blocks = bd;
	      }		  
	      cap->r.rCurrentNursery->u.back = bd;

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
	      // initialise it as a nursery block.  We initialise the
	      // step, gen_no, and flags field of *every* sub-block in
	      // this large block, because this is easier than making
	      // sure that we always find the block head of a large
	      // block whenever we call Bdescr() (eg. evacuate() and
	      // isAlive() in the GC would both have to do this, at
	      // least).
	      { 
		  bdescr *x;
		  for (x = bd; x < bd + blocks; x++) {
		      x->step = g0s0;
		      x->gen_no = 0;
		      x->flags = 0;
		  }
	      }
993 994 995

	      // don't forget to update the block count in g0s0.
	      g0s0->n_blocks += blocks;
996 997
	      // This assert can be a killer if the app is doing lots
	      // of large block allocations.
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
	      ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);

	      // now update the nursery to point to the new block
	      cap->r.rCurrentNursery = bd;

	      // we might be unlucky and have another thread get on the
	      // run queue before us and steal the large block, but in that
	      // case the thread will just end up requesting another large
	      // block.
	      PUSH_ON_RUN_QUEUE(t);
	      break;
	  }
      }

1012 1013 1014 1015
      /* make all the running tasks block on a condition variable,
       * maybe set context_switch and wait till they all pile in,
       * then have them wait on a GC condition variable.
       */
1016 1017
      IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped: HeapOverflow", 
			       t->id, whatNext_strs[t->what_next]));
1018
      threadPaused(t);
1019 1020
#if defined(GRAN)
      ASSERT(!is_on_queue(t,CurrentProc));
1021 1022 1023 1024 1025 1026 1027 1028 1029
#elif defined(PAR)
      /* Currently we emit a DESCHEDULE event before GC in GUM.
         ToDo: either add separate event to distinguish SYSTEM time from rest
	       or just nuke this DESCHEDULE (and the following SCHEDULE) */
      if (0 && RtsFlags.ParFlags.ParStats.Full) {
	DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
			 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
	emitSchedule = rtsTrue;
      }
1030
#endif
1031 1032 1033 1034
      
      ready_to_gc = rtsTrue;
      context_switch = 1;		/* stop other threads ASAP */
      PUSH_ON_RUN_QUEUE(t);
1035
      /* actual GC is done at the end of the while loop */
1036 1037 1038
      break;
      
    case StackOverflow:
1039 1040 1041 1042 1043 1044 1045 1046 1047
#if defined(GRAN)
      IF_DEBUG(gran, 
	       DumpGranEvent(GR_DESCHEDULE, t));
      globalGranStats.tot_stackover++;
#elif defined(PAR)
      // IF_DEBUG(par, 
      // DumpGranEvent(GR_DESCHEDULE, t);
      globalParStats.tot_stackover++;
#endif
1048 1049
      IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped, StackOverflow", 
			       t->id, whatNext_strs[t->what_next]));
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
      /* just adjust the stack for this thread, then pop it back
       * on the run queue.
       */
      threadPaused(t);
      { 
	/* enlarge the stack */
	StgTSO *new_t = threadStackOverflow(t);
	
	/* This TSO has moved, so update any pointers to it from the
	 * main thread stack.  It better not be on any other queues...
1060
	 * (it shouldn't be).
1061
	 */
1062 1063
	if (t->main != NULL) {
	    t->main->tso = new_t;
1064
	}
1065
	threadPaused(new_t);
1066 1067 1068 1069 1070