1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2004
7 * Different GHC ways use this scheduler quite differently (see comments below)
8 * Here is the global picture:
10 * WAY Name CPP flag What's it for
11 * --------------------------------------
12 * mp GUM PAR Parallel execution on a distrib. memory machine
13 * s SMP SMP Parallel execution on a shared memory machine
14 * mg GranSim GRAN Simulation of parallel execution
15 * md GUM/GdH DIST Distributed execution (based on GUM)
17 * --------------------------------------------------------------------------*/
20 * Version with support for distributed memory parallelism aka GUM (WAY=mp):
22 The main scheduling loop in GUM iterates until a finish message is received.
23 In that case a global flag @receivedFinish@ is set and this instance of
24 the RTS shuts down. See ghc/rts/parallel/HLComms.c:processMessages()
25 for the handling of incoming messages, such as PP_FINISH.
26 Note that in the parallel case we have a system manager that coordinates
27 different PEs, each of which are running one instance of the RTS.
28 See ghc/rts/parallel/SysMan.c for the main routine of the parallel program.
29 From this routine processes executing ghc/rts/Main.c are spawned. -- HWL
31 * Version with support for simulating parallel execution aka GranSim (WAY=mg):
33 The main scheduling code in GranSim is quite different from that in std
34 (concurrent) Haskell: while concurrent Haskell just iterates over the
35 threads in the runnable queue, GranSim is event driven, i.e. it iterates
36 over the events in the global event queue. -- HWL
39 #include "PosixSource.h"
44 #include "BlockAlloc.h"
48 #define COMPILING_SCHEDULER
50 #include "StgMiscClosures.h"
52 #include "Interpreter.h"
53 #include "Exception.h"
61 #include "ThreadLabels.h"
62 #include "LdvProfile.h"
65 #include "Proftimer.h"
68 #if defined(GRAN) || defined(PAR)
69 # include "GranSimRts.h"
71 # include "ParallelRts.h"
72 # include "Parallel.h"
73 # include "ParallelDebug.h"
78 #include "Capability.h"
79 #include "OSThreads.h"
82 #ifdef HAVE_SYS_TYPES_H
83 #include <sys/types.h>
98 #define USED_IN_THREADED_RTS
100 #define USED_IN_THREADED_RTS STG_UNUSED
103 #ifdef RTS_SUPPORTS_THREADS
104 #define USED_WHEN_RTS_SUPPORTS_THREADS
106 #define USED_WHEN_RTS_SUPPORTS_THREADS STG_UNUSED
109 /* Main thread queue.
110 * Locks required: sched_mutex.
112 StgMainThread *main_threads = NULL;
115 * Locks required: sched_mutex.
119 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
120 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
123 In GranSim we have a runnable and a blocked queue for each processor.
124 In order to minimise code changes new arrays run_queue_hds/tls
125 are created. run_queue_hd is then a short cut (macro) for
126 run_queue_hds[CurrentProc] (see GranSim.h).
129 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
130 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
131 StgTSO *ccalling_threadss[MAX_PROC];
132 /* We use the same global list of threads (all_threads) in GranSim as in
133 the std RTS (i.e. we are cheating). However, we don't use this list in
134 the GranSim specific code at the moment (so we are only potentially
139 StgTSO *run_queue_hd = NULL;
140 StgTSO *run_queue_tl = NULL;
141 StgTSO *blocked_queue_hd = NULL;
142 StgTSO *blocked_queue_tl = NULL;
143 StgTSO *sleeping_queue = NULL; /* perhaps replace with a hash table? */
147 /* Linked list of all threads.
148 * Used for detecting garbage collected threads.
150 StgTSO *all_threads = NULL;
152 /* When a thread performs a safe C call (_ccall_GC, using old
153 * terminology), it gets put on the suspended_ccalling_threads
154 * list. Used by the garbage collector.
156 static StgTSO *suspended_ccalling_threads;
158 static StgTSO *threadStackOverflow(StgTSO *tso);
160 /* KH: The following two flags are shared memory locations. There is no need
161 to lock them, since they are only unset at the end of a scheduler
165 /* flag set by signal handler to precipitate a context switch */
166 int context_switch = 0;
168 /* if this flag is set as well, give up execution */
169 rtsBool interrupted = rtsFalse;
171 /* If this flag is set, we are running Haskell code. Used to detect
172 * uses of 'foreign import unsafe' that should be 'safe'.
174 rtsBool in_haskell = rtsFalse;
176 /* Next thread ID to allocate.
177 * Locks required: thread_id_mutex
179 static StgThreadID next_thread_id = 1;
182 * Pointers to the state of the current thread.
183 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
184 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
187 /* The smallest stack size that makes any sense is:
188 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
189 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
190 * + 1 (the closure to enter)
192 * + 1 (spare slot req'd by stg_ap_v_ret)
194 * A thread with this stack will bomb immediately with a stack
195 * overflow, which will increase its stack size.
198 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 3)
205 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
206 * exists - earlier gccs apparently didn't.
211 static rtsBool ready_to_gc;
214 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
215 * in an MT setting, needed to signal that a worker thread shouldn't hang around
216 * in the scheduler when it is out of work.
218 static rtsBool shutting_down_scheduler = rtsFalse;
220 void addToBlockedQueue ( StgTSO *tso );
222 static void schedule ( StgMainThread *mainThread, Capability *initialCapability );
223 void interruptStgRts ( void );
225 #if !defined(PAR) && !defined(RTS_SUPPORTS_THREADS)
226 static void detectBlackHoles ( void );
229 static void raiseAsync_(StgTSO *tso, StgClosure *exception, rtsBool stop_at_atomically);
231 #if defined(RTS_SUPPORTS_THREADS)
232 /* ToDo: carefully document the invariants that go together
233 * with these synchronisation objects.
235 Mutex sched_mutex = INIT_MUTEX_VAR;
236 Mutex term_mutex = INIT_MUTEX_VAR;
238 #endif /* RTS_SUPPORTS_THREADS */
242 rtsTime TimeOfLastYield;
243 rtsBool emitSchedule = rtsTrue;
247 static char *whatNext_strs[] = {
258 StgTSO * createSparkThread(rtsSpark spark);
259 StgTSO * activateSpark (rtsSpark spark);
262 /* ----------------------------------------------------------------------------
264 * ------------------------------------------------------------------------- */
266 #if defined(RTS_SUPPORTS_THREADS)
267 static rtsBool startingWorkerThread = rtsFalse;
269 static void taskStart(void);
273 ACQUIRE_LOCK(&sched_mutex);
274 startingWorkerThread = rtsFalse;
276 RELEASE_LOCK(&sched_mutex);
280 startSchedulerTaskIfNecessary(void)
282 if(run_queue_hd != END_TSO_QUEUE
283 || blocked_queue_hd != END_TSO_QUEUE
284 || sleeping_queue != END_TSO_QUEUE)
286 if(!startingWorkerThread)
287 { // we don't want to start another worker thread
288 // just because the last one hasn't yet reached the
289 // "waiting for capability" state
290 startingWorkerThread = rtsTrue;
291 if(!startTask(taskStart))
293 startingWorkerThread = rtsFalse;
300 /* ---------------------------------------------------------------------------
301 Main scheduling loop.
303 We use round-robin scheduling, each thread returning to the
304 scheduler loop when one of these conditions is detected:
307 * timer expires (thread yields)
312 Locking notes: we acquire the scheduler lock once at the beginning
313 of the scheduler loop, and release it when
315 * running a thread, or
316 * waiting for work, or
317 * waiting for a GC to complete.
320 In a GranSim setup this loop iterates over the global event queue.
321 This revolves around the global event queue, which determines what
322 to do next. Therefore, it's more complicated than either the
323 concurrent or the parallel (GUM) setup.
326 GUM iterates over incoming messages.
327 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
328 and sends out a fish whenever it has nothing to do; in-between
329 doing the actual reductions (shared code below) it processes the
330 incoming messages and deals with delayed operations
331 (see PendingFetches).
332 This is not the ugliest code you could imagine, but it's bloody close.
334 ------------------------------------------------------------------------ */
336 schedule( StgMainThread *mainThread USED_WHEN_RTS_SUPPORTS_THREADS,
337 Capability *initialCapability )
341 StgThreadReturnCode ret;
349 rtsBool receivedFinish = rtsFalse;
351 nat tp_size, sp_size; // stats only
354 rtsBool was_interrupted = rtsFalse;
357 // Pre-condition: sched_mutex is held.
358 // We might have a capability, passed in as initialCapability.
359 cap = initialCapability;
361 #if defined(RTS_SUPPORTS_THREADS)
363 // in the threaded case, the capability is either passed in via the
364 // initialCapability parameter, or initialized inside the scheduler
368 sched_belch("### NEW SCHEDULER LOOP (main thr: %p, cap: %p)",
369 mainThread, initialCapability);
372 // simply initialise it in the non-threaded case
373 grabCapability(&cap);
377 /* set up first event to get things going */
378 /* ToDo: assign costs for system setup and init MainTSO ! */
379 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
381 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
384 debugBelch("GRAN: Init CurrentTSO (in schedule) = %p\n", CurrentTSO);
385 G_TSO(CurrentTSO, 5));
387 if (RtsFlags.GranFlags.Light) {
388 /* Save current time; GranSim Light only */
389 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
392 event = get_next_event();
394 while (event!=(rtsEvent*)NULL) {
395 /* Choose the processor with the next event */
396 CurrentProc = event->proc;
397 CurrentTSO = event->tso;
401 while (!receivedFinish) { /* set by processMessages */
402 /* when receiving PP_FINISH message */
404 #else // everything except GRAN and PAR
410 IF_DEBUG(scheduler, printAllThreads());
412 #if defined(RTS_SUPPORTS_THREADS)
413 // Yield the capability to higher-priority tasks if necessary.
416 yieldCapability(&cap);
419 // If we do not currently hold a capability, we wait for one
422 waitForCapability(&sched_mutex, &cap,
423 mainThread ? &mainThread->bound_thread_cond : NULL);
426 // We now have a capability...
429 // Check whether we have re-entered the RTS from Haskell without
430 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
433 errorBelch("schedule: re-entered unsafely.\n"
434 " Perhaps a 'foreign import unsafe' should be 'safe'?");
439 // If we're interrupted (the user pressed ^C, or some other
440 // termination condition occurred), kill all the currently running
444 IF_DEBUG(scheduler, sched_belch("interrupted"));
445 interrupted = rtsFalse;
446 was_interrupted = rtsTrue;
447 #if defined(RTS_SUPPORTS_THREADS)
448 // In the threaded RTS, deadlock detection doesn't work,
449 // so just exit right away.
450 errorBelch("interrupted");
451 releaseCapability(cap);
452 RELEASE_LOCK(&sched_mutex);
453 shutdownHaskellAndExit(EXIT_SUCCESS);
459 #if defined(RTS_USER_SIGNALS)
460 // check for signals each time around the scheduler
461 if (signals_pending()) {
462 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
463 startSignalHandlers();
464 ACQUIRE_LOCK(&sched_mutex);
469 // Check whether any waiting threads need to be woken up. If the
470 // run queue is empty, and there are no other tasks running, we
471 // can wait indefinitely for something to happen.
473 if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue) )
475 #if defined(RTS_SUPPORTS_THREADS)
476 // We shouldn't be here...
477 barf("schedule: awaitEvent() in threaded RTS");
479 awaitEvent( EMPTY_RUN_QUEUE() );
481 // we can be interrupted while waiting for I/O...
482 if (interrupted) continue;
485 * Detect deadlock: when we have no threads to run, there are no
486 * threads waiting on I/O or sleeping, and all the other tasks are
487 * waiting for work, we must have a deadlock of some description.
489 * We first try to find threads blocked on themselves (ie. black
490 * holes), and generate NonTermination exceptions where necessary.
492 * If no threads are black holed, we have a deadlock situation, so
493 * inform all the main threads.
495 #if !defined(PAR) && !defined(RTS_SUPPORTS_THREADS)
496 if ( EMPTY_THREAD_QUEUES() )
498 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
500 // Garbage collection can release some new threads due to
501 // either (a) finalizers or (b) threads resurrected because
502 // they are unreachable and will therefore be sent an
503 // exception. Any threads thus released will be immediately
505 GarbageCollect(GetRoots,rtsTrue);
506 if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
508 #if defined(RTS_USER_SIGNALS)
509 /* If we have user-installed signal handlers, then wait
510 * for signals to arrive rather then bombing out with a
513 if ( anyUserHandlers() ) {
515 sched_belch("still deadlocked, waiting for signals..."));
519 // we might be interrupted...
520 if (interrupted) { continue; }
522 if (signals_pending()) {
523 RELEASE_LOCK(&sched_mutex);
524 startSignalHandlers();
525 ACQUIRE_LOCK(&sched_mutex);
527 ASSERT(!EMPTY_RUN_QUEUE());
532 /* Probably a real deadlock. Send the current main thread the
533 * Deadlock exception (or in the SMP build, send *all* main
534 * threads the deadlock exception, since none of them can make
540 switch (m->tso->why_blocked) {
541 case BlockedOnBlackHole:
542 case BlockedOnException:
544 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
547 barf("deadlock: main thread blocked in a strange way");
553 #elif defined(RTS_SUPPORTS_THREADS)
554 // ToDo: add deadlock detection in threaded RTS
556 // ToDo: add deadlock detection in GUM (similar to SMP) -- HWL
559 #if defined(RTS_SUPPORTS_THREADS) || defined(mingw32_HOST_OS)
560 /* win32: might be back here due to awaitEvent() being abandoned
561 * as a result of a console event having been delivered.
563 if ( EMPTY_RUN_QUEUE() ) {
564 continue; // nothing to do
569 if (RtsFlags.GranFlags.Light)
570 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
572 /* adjust time based on time-stamp */
573 if (event->time > CurrentTime[CurrentProc] &&
574 event->evttype != ContinueThread)
575 CurrentTime[CurrentProc] = event->time;
577 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
578 if (!RtsFlags.GranFlags.Light)
581 IF_DEBUG(gran, debugBelch("GRAN: switch by event-type\n"));
583 /* main event dispatcher in GranSim */
584 switch (event->evttype) {
585 /* Should just be continuing execution */
587 IF_DEBUG(gran, debugBelch("GRAN: doing ContinueThread\n"));
588 /* ToDo: check assertion
589 ASSERT(run_queue_hd != (StgTSO*)NULL &&
590 run_queue_hd != END_TSO_QUEUE);
592 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
593 if (!RtsFlags.GranFlags.DoAsyncFetch &&
594 procStatus[CurrentProc]==Fetching) {
595 debugBelch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]\n",
596 CurrentTSO->id, CurrentTSO, CurrentProc);
599 /* Ignore ContinueThreads for completed threads */
600 if (CurrentTSO->what_next == ThreadComplete) {
601 debugBelch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)\n",
602 CurrentTSO->id, CurrentTSO, CurrentProc);
605 /* Ignore ContinueThreads for threads that are being migrated */
606 if (PROCS(CurrentTSO)==Nowhere) {
607 debugBelch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)\n",
608 CurrentTSO->id, CurrentTSO, CurrentProc);
611 /* The thread should be at the beginning of the run queue */
612 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
613 debugBelch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread\n",
614 CurrentTSO->id, CurrentTSO, CurrentProc);
615 break; // run the thread anyway
618 new_event(proc, proc, CurrentTime[proc],
620 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
622 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
623 break; // now actually run the thread; DaH Qu'vam yImuHbej
626 do_the_fetchnode(event);
627 goto next_thread; /* handle next event in event queue */
630 do_the_globalblock(event);
631 goto next_thread; /* handle next event in event queue */
634 do_the_fetchreply(event);
635 goto next_thread; /* handle next event in event queue */
637 case UnblockThread: /* Move from the blocked queue to the tail of */
638 do_the_unblock(event);
639 goto next_thread; /* handle next event in event queue */
641 case ResumeThread: /* Move from the blocked queue to the tail of */
642 /* the runnable queue ( i.e. Qu' SImqa'lu') */
643 event->tso->gran.blocktime +=
644 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
645 do_the_startthread(event);
646 goto next_thread; /* handle next event in event queue */
649 do_the_startthread(event);
650 goto next_thread; /* handle next event in event queue */
653 do_the_movethread(event);
654 goto next_thread; /* handle next event in event queue */
657 do_the_movespark(event);
658 goto next_thread; /* handle next event in event queue */
661 do_the_findwork(event);
662 goto next_thread; /* handle next event in event queue */
665 barf("Illegal event type %u\n", event->evttype);
668 /* This point was scheduler_loop in the old RTS */
670 IF_DEBUG(gran, debugBelch("GRAN: after main switch\n"));
672 TimeOfLastEvent = CurrentTime[CurrentProc];
673 TimeOfNextEvent = get_time_of_next_event();
674 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
675 // CurrentTSO = ThreadQueueHd;
677 IF_DEBUG(gran, debugBelch("GRAN: time of next event is: %ld\n",
680 if (RtsFlags.GranFlags.Light)
681 GranSimLight_leave_system(event, &ActiveTSO);
683 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
686 debugBelch("GRAN: end of time-slice is %#lx\n", EndOfTimeSlice));
688 /* in a GranSim setup the TSO stays on the run queue */
690 /* Take a thread from the run queue. */
691 POP_RUN_QUEUE(t); // take_off_run_queue(t);
694 debugBelch("GRAN: About to run current thread, which is\n");
697 context_switch = 0; // turned on via GranYield, checking events and time slice
700 DumpGranEvent(GR_SCHEDULE, t));
702 procStatus[CurrentProc] = Busy;
705 if (PendingFetches != END_BF_QUEUE) {
709 /* ToDo: phps merge with spark activation above */
710 /* check whether we have local work and send requests if we have none */
711 if (EMPTY_RUN_QUEUE()) { /* no runnable threads */
712 /* :-[ no local threads => look out for local sparks */
713 /* the spark pool for the current PE */
714 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
715 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
716 pool->hd < pool->tl) {
718 * ToDo: add GC code check that we really have enough heap afterwards!!
720 * If we're here (no runnable threads) and we have pending
721 * sparks, we must have a space problem. Get enough space
722 * to turn one of those pending sparks into a
726 spark = findSpark(rtsFalse); /* get a spark */
727 if (spark != (rtsSpark) NULL) {
728 tso = activateSpark(spark); /* turn the spark into a thread */
729 IF_PAR_DEBUG(schedule,
730 debugBelch("==== schedule: Created TSO %d (%p); %d threads active\n",
731 tso->id, tso, advisory_thread_count));
733 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
734 debugBelch("==^^ failed to activate spark\n");
736 } /* otherwise fall through & pick-up new tso */
738 IF_PAR_DEBUG(verbose,
739 debugBelch("==^^ no local sparks (spark pool contains only NFs: %d)\n",
740 spark_queue_len(pool)));
745 /* If we still have no work we need to send a FISH to get a spark
748 if (EMPTY_RUN_QUEUE()) {
749 /* =8-[ no local sparks => look for work on other PEs */
751 * We really have absolutely no work. Send out a fish
752 * (there may be some out there already), and wait for
753 * something to arrive. We clearly can't run any threads
754 * until a SCHEDULE or RESUME arrives, and so that's what
755 * we're hoping to see. (Of course, we still have to
756 * respond to other types of messages.)
758 TIME now = msTime() /*CURRENT_TIME*/;
759 IF_PAR_DEBUG(verbose,
760 debugBelch("-- now=%ld\n", now));
761 IF_PAR_DEBUG(verbose,
762 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
763 (last_fish_arrived_at!=0 &&
764 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
765 debugBelch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)\n",
766 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
767 last_fish_arrived_at,
768 RtsFlags.ParFlags.fishDelay, now);
771 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
772 (last_fish_arrived_at==0 ||
773 (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
774 /* outstandingFishes is set in sendFish, processFish;
775 avoid flooding system with fishes via delay */
777 sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY,
780 // Global statistics: count no. of fishes
781 if (RtsFlags.ParFlags.ParStats.Global &&
782 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
783 globalParStats.tot_fish_mess++;
787 receivedFinish = processMessages();
790 } else if (PacketsWaiting()) { /* Look for incoming messages */
791 receivedFinish = processMessages();
794 /* Now we are sure that we have some work available */
795 ASSERT(run_queue_hd != END_TSO_QUEUE);
797 /* Take a thread from the run queue, if we have work */
798 POP_RUN_QUEUE(t); // take_off_run_queue(END_TSO_QUEUE);
799 IF_DEBUG(sanity,checkTSO(t));
801 /* ToDo: write something to the log-file
802 if (RTSflags.ParFlags.granSimStats && !sameThread)
803 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
807 /* the spark pool for the current PE */
808 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
811 debugBelch("--=^ %d threads, %d sparks on [%#x]\n",
812 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
815 if (0 && RtsFlags.ParFlags.ParStats.Full &&
816 t && LastTSO && t->id != LastTSO->id &&
817 LastTSO->why_blocked == NotBlocked &&
818 LastTSO->what_next != ThreadComplete) {
819 // if previously scheduled TSO not blocked we have to record the context switch
820 DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
821 GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
824 if (RtsFlags.ParFlags.ParStats.Full &&
825 (emitSchedule /* forced emit */ ||
826 (t && LastTSO && t->id != LastTSO->id))) {
828 we are running a different TSO, so write a schedule event to log file
829 NB: If we use fair scheduling we also have to write a deschedule
830 event for LastTSO; with unfair scheduling we know that the
831 previous tso has blocked whenever we switch to another tso, so
832 we don't need it in GUM for now
834 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
835 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
836 emitSchedule = rtsFalse;
840 #else /* !GRAN && !PAR */
842 // grab a thread from the run queue
843 ASSERT(run_queue_hd != END_TSO_QUEUE);
846 // Sanity check the thread we're about to run. This can be
847 // expensive if there is lots of thread switching going on...
848 IF_DEBUG(sanity,checkTSO(t));
853 StgMainThread *m = t->main;
860 sched_belch("### Running thread %d in bound thread", t->id));
861 // yes, the Haskell thread is bound to the current native thread
866 sched_belch("### thread %d bound to another OS thread", t->id));
867 // no, bound to a different Haskell thread: pass to that thread
868 PUSH_ON_RUN_QUEUE(t);
869 passCapability(&m->bound_thread_cond);
875 if(mainThread != NULL)
876 // The thread we want to run is bound.
879 sched_belch("### this OS thread cannot run thread %d", t->id));
880 // no, the current native thread is bound to a different
881 // Haskell thread, so pass it to any worker thread
882 PUSH_ON_RUN_QUEUE(t);
883 passCapabilityToWorker();
890 cap->r.rCurrentTSO = t;
892 /* context switches are now initiated by the timer signal, unless
893 * the user specified "context switch as often as possible", with
896 if ((RtsFlags.ConcFlags.ctxtSwitchTicks == 0
897 && (run_queue_hd != END_TSO_QUEUE
898 || blocked_queue_hd != END_TSO_QUEUE
899 || sleeping_queue != END_TSO_QUEUE)))
904 RELEASE_LOCK(&sched_mutex);
906 IF_DEBUG(scheduler, sched_belch("-->> running thread %ld %s ...",
907 (long)t->id, whatNext_strs[t->what_next]));
910 startHeapProfTimer();
913 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
914 /* Run the current thread
916 prev_what_next = t->what_next;
918 errno = t->saved_errno;
919 in_haskell = rtsTrue;
921 switch (prev_what_next) {
925 /* Thread already finished, return to scheduler. */
926 ret = ThreadFinished;
930 ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
933 case ThreadInterpret:
934 ret = interpretBCO(cap);
938 barf("schedule: invalid what_next field");
941 in_haskell = rtsFalse;
943 // The TSO might have moved, so find the new location:
944 t = cap->r.rCurrentTSO;
946 // And save the current errno in this thread.
947 t->saved_errno = errno;
949 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
951 /* Costs for the scheduler are assigned to CCS_SYSTEM */
957 ACQUIRE_LOCK(&sched_mutex);
959 #ifdef RTS_SUPPORTS_THREADS
960 IF_DEBUG(scheduler,debugBelch("sched (task %p): ", osThreadId()););
961 #elif !defined(GRAN) && !defined(PAR)
962 IF_DEBUG(scheduler,debugBelch("sched: "););
966 /* HACK 675: if the last thread didn't yield, make sure to print a
967 SCHEDULE event to the log file when StgRunning the next thread, even
968 if it is the same one as before */
970 TimeOfLastYield = CURRENT_TIME;
976 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
977 globalGranStats.tot_heapover++;
979 globalParStats.tot_heapover++;
982 // did the task ask for a large block?
983 if (cap->r.rHpAlloc > BLOCK_SIZE) {
984 // if so, get one and push it on the front of the nursery.
988 blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
990 IF_DEBUG(scheduler,debugBelch("--<< thread %ld (%s) stopped: requesting a large block (size %d)\n",
991 (long)t->id, whatNext_strs[t->what_next], blocks));
993 // don't do this if it would push us over the
994 // alloc_blocks_lim limit; we'll GC first.
995 if (alloc_blocks + blocks < alloc_blocks_lim) {
997 alloc_blocks += blocks;
998 bd = allocGroup( blocks );
1000 // link the new group into the list
1001 bd->link = cap->r.rCurrentNursery;
1002 bd->u.back = cap->r.rCurrentNursery->u.back;
1003 if (cap->r.rCurrentNursery->u.back != NULL) {
1004 cap->r.rCurrentNursery->u.back->link = bd;
1006 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
1007 g0s0->blocks == cap->r.rNursery);
1008 cap->r.rNursery = g0s0->blocks = bd;
1010 cap->r.rCurrentNursery->u.back = bd;
1012 // initialise it as a nursery block. We initialise the
1013 // step, gen_no, and flags field of *every* sub-block in
1014 // this large block, because this is easier than making
1015 // sure that we always find the block head of a large
1016 // block whenever we call Bdescr() (eg. evacuate() and
1017 // isAlive() in the GC would both have to do this, at
1021 for (x = bd; x < bd + blocks; x++) {
1028 // don't forget to update the block count in g0s0.
1029 g0s0->n_blocks += blocks;
1030 // This assert can be a killer if the app is doing lots
1031 // of large block allocations.
1032 ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1034 // now update the nursery to point to the new block
1035 cap->r.rCurrentNursery = bd;
1037 // we might be unlucky and have another thread get on the
1038 // run queue before us and steal the large block, but in that
1039 // case the thread will just end up requesting another large
1041 PUSH_ON_RUN_QUEUE(t);
1046 /* make all the running tasks block on a condition variable,
1047 * maybe set context_switch and wait till they all pile in,
1048 * then have them wait on a GC condition variable.
1050 IF_DEBUG(scheduler,debugBelch("--<< thread %ld (%s) stopped: HeapOverflow\n",
1051 (long)t->id, whatNext_strs[t->what_next]));
1054 ASSERT(!is_on_queue(t,CurrentProc));
1056 /* Currently we emit a DESCHEDULE event before GC in GUM.
1057 ToDo: either add separate event to distinguish SYSTEM time from rest
1058 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1059 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1060 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1061 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1062 emitSchedule = rtsTrue;
1066 ready_to_gc = rtsTrue;
1067 PUSH_ON_RUN_QUEUE(t);
1068 /* actual GC is done at the end of the while loop */
1074 DumpGranEvent(GR_DESCHEDULE, t));
1075 globalGranStats.tot_stackover++;
1078 // DumpGranEvent(GR_DESCHEDULE, t);
1079 globalParStats.tot_stackover++;
1081 IF_DEBUG(scheduler,debugBelch("--<< thread %ld (%s) stopped, StackOverflow\n",
1082 (long)t->id, whatNext_strs[t->what_next]));
1083 /* just adjust the stack for this thread, then pop it back
1088 /* enlarge the stack */
1089 StgTSO *new_t = threadStackOverflow(t);
1091 /* This TSO has moved, so update any pointers to it from the
1092 * main thread stack. It better not be on any other queues...
1093 * (it shouldn't be).
1095 if (t->main != NULL) {
1096 t->main->tso = new_t;
1098 PUSH_ON_RUN_QUEUE(new_t);
1102 case ThreadYielding:
1103 // Reset the context switch flag. We don't do this just before
1104 // running the thread, because that would mean we would lose ticks
1105 // during GC, which can lead to unfair scheduling (a thread hogs
1106 // the CPU because the tick always arrives during GC). This way
1107 // penalises threads that do a lot of allocation, but that seems
1108 // better than the alternative.
1113 DumpGranEvent(GR_DESCHEDULE, t));
1114 globalGranStats.tot_yields++;
1117 // DumpGranEvent(GR_DESCHEDULE, t);
1118 globalParStats.tot_yields++;
1120 /* put the thread back on the run queue. Then, if we're ready to
1121 * GC, check whether this is the last task to stop. If so, wake
1122 * up the GC thread. getThread will block during a GC until the
1126 if (t->what_next != prev_what_next) {
1127 debugBelch("--<< thread %ld (%s) stopped to switch evaluators\n",
1128 (long)t->id, whatNext_strs[t->what_next]);
1130 debugBelch("--<< thread %ld (%s) stopped, yielding\n",
1131 (long)t->id, whatNext_strs[t->what_next]);
1136 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1138 ASSERT(t->link == END_TSO_QUEUE);
1140 // Shortcut if we're just switching evaluators: don't bother
1141 // doing stack squeezing (which can be expensive), just run the
1143 if (t->what_next != prev_what_next) {
1150 ASSERT(!is_on_queue(t,CurrentProc));
1153 //debugBelch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1154 checkThreadQsSanity(rtsTrue));
1158 if (RtsFlags.ParFlags.doFairScheduling) {
1159 /* this does round-robin scheduling; good for concurrency */
1160 APPEND_TO_RUN_QUEUE(t);
1162 /* this does unfair scheduling; good for parallelism */
1163 PUSH_ON_RUN_QUEUE(t);
1166 // this does round-robin scheduling; good for concurrency
1167 APPEND_TO_RUN_QUEUE(t);
1171 /* add a ContinueThread event to actually process the thread */
1172 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1174 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1176 debugBelch("GRAN: eventq and runnableq after adding yielded thread to queue again:\n");
1185 debugBelch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: \n",
1186 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)));
1187 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1189 // ??? needed; should emit block before
1191 DumpGranEvent(GR_DESCHEDULE, t));
1192 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1195 ASSERT(procStatus[CurrentProc]==Busy ||
1196 ((procStatus[CurrentProc]==Fetching) &&
1197 (t->block_info.closure!=(StgClosure*)NULL)));
1198 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1199 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1200 procStatus[CurrentProc]==Fetching))
1201 procStatus[CurrentProc] = Idle;
1205 debugBelch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: \n",
1206 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1209 if (t->block_info.closure!=(StgClosure*)NULL)
1210 print_bq(t->block_info.closure));
1212 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1215 /* whatever we schedule next, we must log that schedule */
1216 emitSchedule = rtsTrue;
1219 /* don't need to do anything. Either the thread is blocked on
1220 * I/O, in which case we'll have called addToBlockedQueue
1221 * previously, or it's blocked on an MVar or Blackhole, in which
1222 * case it'll be on the relevant queue already.
1224 ASSERT(t->why_blocked != NotBlocked);
1226 debugBelch("--<< thread %d (%s) stopped: ",
1227 t->id, whatNext_strs[t->what_next]);
1228 printThreadBlockage(t);
1231 /* Only for dumping event to log file
1232 ToDo: do I need this in GranSim, too?
1239 case ThreadFinished:
1240 /* Need to check whether this was a main thread, and if so, signal
1241 * the task that started it with the return value. If we have no
1242 * more main threads, we probably need to stop all the tasks until
1245 /* We also end up here if the thread kills itself with an
1246 * uncaught exception, see Exception.hc.
1248 IF_DEBUG(scheduler,debugBelch("--++ thread %d (%s) finished\n",
1249 t->id, whatNext_strs[t->what_next]));
1251 endThread(t, CurrentProc); // clean-up the thread
1253 /* For now all are advisory -- HWL */
1254 //if(t->priority==AdvisoryPriority) ??
1255 advisory_thread_count--;
1258 if(t->dist.priority==RevalPriority)
1262 if (RtsFlags.ParFlags.ParStats.Full &&
1263 !RtsFlags.ParFlags.ParStats.Suppressed)
1264 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1268 // Check whether the thread that just completed was a main
1269 // thread, and if so return with the result.
1271 // There is an assumption here that all thread completion goes
1272 // through this point; we need to make sure that if a thread
1273 // ends up in the ThreadKilled state, that it stays on the run
1274 // queue so it can be dealt with here.
1277 #if defined(RTS_SUPPORTS_THREADS)
1280 mainThread->tso == t
1284 // We are a bound thread: this must be our thread that just
1286 ASSERT(mainThread->tso == t);
1288 if (t->what_next == ThreadComplete) {
1289 if (mainThread->ret) {
1290 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1291 *(mainThread->ret) = (StgClosure *)mainThread->tso->sp[1];
1293 mainThread->stat = Success;
1295 if (mainThread->ret) {
1296 *(mainThread->ret) = NULL;
1298 if (was_interrupted) {
1299 mainThread->stat = Interrupted;
1301 mainThread->stat = Killed;
1305 removeThreadLabel((StgWord)mainThread->tso->id);
1307 if (mainThread->prev == NULL) {
1308 main_threads = mainThread->link;
1310 mainThread->prev->link = mainThread->link;
1312 if (mainThread->link != NULL) {
1313 mainThread->link->prev = NULL;
1315 releaseCapability(cap);
1319 #ifdef RTS_SUPPORTS_THREADS
1320 ASSERT(t->main == NULL);
1322 if (t->main != NULL) {
1323 // Must be a main thread that is not the topmost one. Leave
1324 // it on the run queue until the stack has unwound to the
1325 // point where we can deal with this. Leaving it on the run
1326 // queue also ensures that the garbage collector knows about
1327 // this thread and its return value (it gets dropped from the
1328 // all_threads list so there's no other way to find it).
1329 APPEND_TO_RUN_QUEUE(t);
1335 barf("schedule: invalid thread return code %d", (int)ret);
1339 // When we have +RTS -i0 and we're heap profiling, do a census at
1340 // every GC. This lets us get repeatable runs for debugging.
1341 if (performHeapProfile ||
1342 (RtsFlags.ProfFlags.profileInterval==0 &&
1343 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1344 GarbageCollect(GetRoots, rtsTrue);
1346 performHeapProfile = rtsFalse;
1347 ready_to_gc = rtsFalse; // we already GC'd
1352 /* Kick any transactions which are invalid back to their atomically frames.
1353 * When next scheduled they will try to commit, this commit will fail and
1354 * they will retry. */
1355 for (t = all_threads; t != END_TSO_QUEUE; t = t -> link) {
1356 if (t -> what_next != ThreadRelocated && t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1357 if (!stmValidateTransaction (t -> trec)) {
1358 IF_DEBUG(stm, sched_belch("trec %p found wasting its time", t));
1360 // strip the stack back to the ATOMICALLY_FRAME, aborting
1361 // the (nested) transaction, and saving the stack of any
1362 // partially-evaluated thunks on the heap.
1363 raiseAsync_(t, NULL, rtsTrue);
1366 ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1372 /* everybody back, start the GC.
1373 * Could do it in this thread, or signal a condition var
1374 * to do it in another thread. Either way, we need to
1375 * broadcast on gc_pending_cond afterward.
1377 #if defined(RTS_SUPPORTS_THREADS)
1378 IF_DEBUG(scheduler,sched_belch("doing GC"));
1380 GarbageCollect(GetRoots,rtsFalse);
1381 ready_to_gc = rtsFalse;
1383 /* add a ContinueThread event to continue execution of current thread */
1384 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1386 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1388 debugBelch("GRAN: eventq and runnableq after Garbage collection:\n\n");
1396 IF_GRAN_DEBUG(unused,
1397 print_eventq(EventHd));
1399 event = get_next_event();
1402 /* ToDo: wait for next message to arrive rather than busy wait */
1405 } /* end of while(1) */
1407 IF_PAR_DEBUG(verbose,
1408 debugBelch("== Leaving schedule() after having received Finish\n"));
1411 /* ---------------------------------------------------------------------------
1412 * rtsSupportsBoundThreads(): is the RTS built to support bound threads?
1413 * used by Control.Concurrent for error checking.
1414 * ------------------------------------------------------------------------- */
1417 rtsSupportsBoundThreads(void)
1426 /* ---------------------------------------------------------------------------
1427 * isThreadBound(tso): check whether tso is bound to an OS thread.
1428 * ------------------------------------------------------------------------- */
1431 isThreadBound(StgTSO* tso USED_IN_THREADED_RTS)
1434 return (tso->main != NULL);
1439 /* ---------------------------------------------------------------------------
1440 * Singleton fork(). Do not copy any running threads.
1441 * ------------------------------------------------------------------------- */
1443 #ifndef mingw32_HOST_OS
1444 #define FORKPROCESS_PRIMOP_SUPPORTED
1447 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1449 deleteThreadImmediately(StgTSO *tso);
1452 forkProcess(HsStablePtr *entry
1453 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1458 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1464 IF_DEBUG(scheduler,sched_belch("forking!"));
1465 rts_lock(); // This not only acquires sched_mutex, it also
1466 // makes sure that no other threads are running
1470 if (pid) { /* parent */
1472 /* just return the pid */
1476 } else { /* child */
1479 // delete all threads
1480 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1482 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1485 // don't allow threads to catch the ThreadKilled exception
1486 deleteThreadImmediately(t);
1489 // wipe the main thread list
1490 while((m = main_threads) != NULL) {
1491 main_threads = m->link;
1492 # ifdef THREADED_RTS
1493 closeCondition(&m->bound_thread_cond);
1498 rc = rts_evalStableIO(entry, NULL); // run the action
1499 rts_checkSchedStatus("forkProcess",rc);
1503 hs_exit(); // clean up and exit
1506 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1507 barf("forkProcess#: primop not supported, sorry!\n");
1512 /* ---------------------------------------------------------------------------
1513 * deleteAllThreads(): kill all the live threads.
1515 * This is used when we catch a user interrupt (^C), before performing
1516 * any necessary cleanups and running finalizers.
1518 * Locks: sched_mutex held.
1519 * ------------------------------------------------------------------------- */
1522 deleteAllThreads ( void )
1525 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
1526 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1527 next = t->global_link;
1531 // The run queue now contains a bunch of ThreadKilled threads. We
1532 // must not throw these away: the main thread(s) will be in there
1533 // somewhere, and the main scheduler loop has to deal with it.
1534 // Also, the run queue is the only thing keeping these threads from
1535 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1537 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1538 ASSERT(sleeping_queue == END_TSO_QUEUE);
1541 /* startThread and insertThread are now in GranSim.c -- HWL */
1544 /* ---------------------------------------------------------------------------
1545 * Suspending & resuming Haskell threads.
1547 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1548 * its capability before calling the C function. This allows another
1549 * task to pick up the capability and carry on running Haskell
1550 * threads. It also means that if the C call blocks, it won't lock
1553 * The Haskell thread making the C call is put to sleep for the
1554 * duration of the call, on the susepended_ccalling_threads queue. We
1555 * give out a token to the task, which it can use to resume the thread
1556 * on return from the C function.
1557 * ------------------------------------------------------------------------- */
1560 suspendThread( StgRegTable *reg )
1564 int saved_errno = errno;
1566 /* assume that *reg is a pointer to the StgRegTable part
1569 cap = (Capability *)((void *)((unsigned char*)reg - sizeof(StgFunTable)));
1571 ACQUIRE_LOCK(&sched_mutex);
1574 sched_belch("thread %d did a _ccall_gc", cap->r.rCurrentTSO->id));
1576 // XXX this might not be necessary --SDM
1577 cap->r.rCurrentTSO->what_next = ThreadRunGHC;
1579 threadPaused(cap->r.rCurrentTSO);
1580 cap->r.rCurrentTSO->link = suspended_ccalling_threads;
1581 suspended_ccalling_threads = cap->r.rCurrentTSO;
1583 if(cap->r.rCurrentTSO->blocked_exceptions == NULL) {
1584 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall;
1585 cap->r.rCurrentTSO->blocked_exceptions = END_TSO_QUEUE;
1587 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall_NoUnblockExc;
1590 /* Use the thread ID as the token; it should be unique */
1591 tok = cap->r.rCurrentTSO->id;
1593 /* Hand back capability */
1594 releaseCapability(cap);
1596 #if defined(RTS_SUPPORTS_THREADS)
1597 /* Preparing to leave the RTS, so ensure there's a native thread/task
1598 waiting to take over.
1600 IF_DEBUG(scheduler, sched_belch("worker (token %d): leaving RTS", tok));
1603 in_haskell = rtsFalse;
1604 RELEASE_LOCK(&sched_mutex);
1606 errno = saved_errno;
1611 resumeThread( StgInt tok )
1613 StgTSO *tso, **prev;
1615 int saved_errno = errno;
1617 #if defined(RTS_SUPPORTS_THREADS)
1618 /* Wait for permission to re-enter the RTS with the result. */
1619 ACQUIRE_LOCK(&sched_mutex);
1620 waitForReturnCapability(&sched_mutex, &cap);
1622 IF_DEBUG(scheduler, sched_belch("worker (token %d): re-entering RTS", tok));
1624 grabCapability(&cap);
1627 /* Remove the thread off of the suspended list */
1628 prev = &suspended_ccalling_threads;
1629 for (tso = suspended_ccalling_threads;
1630 tso != END_TSO_QUEUE;
1631 prev = &tso->link, tso = tso->link) {
1632 if (tso->id == (StgThreadID)tok) {
1637 if (tso == END_TSO_QUEUE) {
1638 barf("resumeThread: thread not found");
1640 tso->link = END_TSO_QUEUE;
1642 if(tso->why_blocked == BlockedOnCCall) {
1643 awakenBlockedQueueNoLock(tso->blocked_exceptions);
1644 tso->blocked_exceptions = NULL;
1647 /* Reset blocking status */
1648 tso->why_blocked = NotBlocked;
1650 cap->r.rCurrentTSO = tso;
1651 in_haskell = rtsTrue;
1652 RELEASE_LOCK(&sched_mutex);
1653 errno = saved_errno;
1658 /* ---------------------------------------------------------------------------
1660 * ------------------------------------------------------------------------ */
1661 static void unblockThread(StgTSO *tso);
1663 /* ---------------------------------------------------------------------------
1664 * Comparing Thread ids.
1666 * This is used from STG land in the implementation of the
1667 * instances of Eq/Ord for ThreadIds.
1668 * ------------------------------------------------------------------------ */
1671 cmp_thread(StgPtr tso1, StgPtr tso2)
1673 StgThreadID id1 = ((StgTSO *)tso1)->id;
1674 StgThreadID id2 = ((StgTSO *)tso2)->id;
1676 if (id1 < id2) return (-1);
1677 if (id1 > id2) return 1;
1681 /* ---------------------------------------------------------------------------
1682 * Fetching the ThreadID from an StgTSO.
1684 * This is used in the implementation of Show for ThreadIds.
1685 * ------------------------------------------------------------------------ */
1687 rts_getThreadId(StgPtr tso)
1689 return ((StgTSO *)tso)->id;
1694 labelThread(StgPtr tso, char *label)
1699 /* Caveat: Once set, you can only set the thread name to "" */
1700 len = strlen(label)+1;
1701 buf = stgMallocBytes(len * sizeof(char), "Schedule.c:labelThread()");
1702 strncpy(buf,label,len);
1703 /* Update will free the old memory for us */
1704 updateThreadLabel(((StgTSO *)tso)->id,buf);
1708 /* ---------------------------------------------------------------------------
1709 Create a new thread.
1711 The new thread starts with the given stack size. Before the
1712 scheduler can run, however, this thread needs to have a closure
1713 (and possibly some arguments) pushed on its stack. See
1714 pushClosure() in Schedule.h.
1716 createGenThread() and createIOThread() (in SchedAPI.h) are
1717 convenient packaged versions of this function.
1719 currently pri (priority) is only used in a GRAN setup -- HWL
1720 ------------------------------------------------------------------------ */
1722 /* currently pri (priority) is only used in a GRAN setup -- HWL */
1724 createThread(nat size, StgInt pri)
1727 createThread(nat size)
1734 /* First check whether we should create a thread at all */
1736 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1737 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1739 debugBelch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)\n",
1740 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1741 return END_TSO_QUEUE;
1747 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
1750 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
1752 /* catch ridiculously small stack sizes */
1753 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
1754 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
1757 stack_size = size - TSO_STRUCT_SIZEW;
1759 tso = (StgTSO *)allocate(size);
1760 TICK_ALLOC_TSO(stack_size, 0);
1762 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
1764 SET_GRAN_HDR(tso, ThisPE);
1767 // Always start with the compiled code evaluator
1768 tso->what_next = ThreadRunGHC;
1770 tso->id = next_thread_id++;
1771 tso->why_blocked = NotBlocked;
1772 tso->blocked_exceptions = NULL;
1774 tso->saved_errno = 0;
1777 tso->stack_size = stack_size;
1778 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
1780 tso->sp = (P_)&(tso->stack) + stack_size;
1782 tso->trec = NO_TREC;
1785 tso->prof.CCCS = CCS_MAIN;
1788 /* put a stop frame on the stack */
1789 tso->sp -= sizeofW(StgStopFrame);
1790 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
1791 tso->link = END_TSO_QUEUE;
1795 /* uses more flexible routine in GranSim */
1796 insertThread(tso, CurrentProc);
1798 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
1804 if (RtsFlags.GranFlags.GranSimStats.Full)
1805 DumpGranEvent(GR_START,tso);
1807 if (RtsFlags.ParFlags.ParStats.Full)
1808 DumpGranEvent(GR_STARTQ,tso);
1809 /* HACk to avoid SCHEDULE
1813 /* Link the new thread on the global thread list.
1815 tso->global_link = all_threads;
1819 tso->dist.priority = MandatoryPriority; //by default that is...
1823 tso->gran.pri = pri;
1825 tso->gran.magic = TSO_MAGIC; // debugging only
1827 tso->gran.sparkname = 0;
1828 tso->gran.startedat = CURRENT_TIME;
1829 tso->gran.exported = 0;
1830 tso->gran.basicblocks = 0;
1831 tso->gran.allocs = 0;
1832 tso->gran.exectime = 0;
1833 tso->gran.fetchtime = 0;
1834 tso->gran.fetchcount = 0;
1835 tso->gran.blocktime = 0;
1836 tso->gran.blockcount = 0;
1837 tso->gran.blockedat = 0;
1838 tso->gran.globalsparks = 0;
1839 tso->gran.localsparks = 0;
1840 if (RtsFlags.GranFlags.Light)
1841 tso->gran.clock = Now; /* local clock */
1843 tso->gran.clock = 0;
1845 IF_DEBUG(gran,printTSO(tso));
1848 tso->par.magic = TSO_MAGIC; // debugging only
1850 tso->par.sparkname = 0;
1851 tso->par.startedat = CURRENT_TIME;
1852 tso->par.exported = 0;
1853 tso->par.basicblocks = 0;
1854 tso->par.allocs = 0;
1855 tso->par.exectime = 0;
1856 tso->par.fetchtime = 0;
1857 tso->par.fetchcount = 0;
1858 tso->par.blocktime = 0;
1859 tso->par.blockcount = 0;
1860 tso->par.blockedat = 0;
1861 tso->par.globalsparks = 0;
1862 tso->par.localsparks = 0;
1866 globalGranStats.tot_threads_created++;
1867 globalGranStats.threads_created_on_PE[CurrentProc]++;
1868 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
1869 globalGranStats.tot_sq_probes++;
1871 // collect parallel global statistics (currently done together with GC stats)
1872 if (RtsFlags.ParFlags.ParStats.Global &&
1873 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1874 //debugBelch("Creating thread %d @ %11.2f\n", tso->id, usertime());
1875 globalParStats.tot_threads_created++;
1881 sched_belch("==__ schedule: Created TSO %d (%p);",
1882 CurrentProc, tso, tso->id));
1884 IF_PAR_DEBUG(verbose,
1885 sched_belch("==__ schedule: Created TSO %d (%p); %d threads active",
1886 (long)tso->id, tso, advisory_thread_count));
1888 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
1889 (long)tso->id, (long)tso->stack_size));
1896 all parallel thread creation calls should fall through the following routine.
1899 createSparkThread(rtsSpark spark)
1901 ASSERT(spark != (rtsSpark)NULL);
1902 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
1904 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1905 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1906 return END_TSO_QUEUE;
1910 tso = createThread(RtsFlags.GcFlags.initialStkSize);
1911 if (tso==END_TSO_QUEUE)
1912 barf("createSparkThread: Cannot create TSO");
1914 tso->priority = AdvisoryPriority;
1916 pushClosure(tso,spark);
1917 PUSH_ON_RUN_QUEUE(tso);
1918 advisory_thread_count++;
1925 Turn a spark into a thread.
1926 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
1930 activateSpark (rtsSpark spark)
1934 tso = createSparkThread(spark);
1935 if (RtsFlags.ParFlags.ParStats.Full) {
1936 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
1937 IF_PAR_DEBUG(verbose,
1938 debugBelch("==^^ activateSpark: turning spark of closure %p (%s) into a thread\n",
1939 (StgClosure *)spark, info_type((StgClosure *)spark)));
1941 // ToDo: fwd info on local/global spark to thread -- HWL
1942 // tso->gran.exported = spark->exported;
1943 // tso->gran.locked = !spark->global;
1944 // tso->gran.sparkname = spark->name;
1950 static SchedulerStatus waitThread_(/*out*/StgMainThread* m,
1951 Capability *initialCapability
1955 /* ---------------------------------------------------------------------------
1958 * scheduleThread puts a thread on the head of the runnable queue.
1959 * This will usually be done immediately after a thread is created.
1960 * The caller of scheduleThread must create the thread using e.g.
1961 * createThread and push an appropriate closure
1962 * on this thread's stack before the scheduler is invoked.
1963 * ------------------------------------------------------------------------ */
1965 static void scheduleThread_ (StgTSO* tso);
1968 scheduleThread_(StgTSO *tso)
1970 // The thread goes at the *end* of the run-queue, to avoid possible
1971 // starvation of any threads already on the queue.
1972 APPEND_TO_RUN_QUEUE(tso);
1977 scheduleThread(StgTSO* tso)
1979 ACQUIRE_LOCK(&sched_mutex);
1980 scheduleThread_(tso);
1981 RELEASE_LOCK(&sched_mutex);
1984 #if defined(RTS_SUPPORTS_THREADS)
1985 static Condition bound_cond_cache;
1986 static int bound_cond_cache_full = 0;
1991 scheduleWaitThread(StgTSO* tso, /*[out]*/HaskellObj* ret,
1992 Capability *initialCapability)
1994 // Precondition: sched_mutex must be held
1997 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
2002 m->link = main_threads;
2004 if (main_threads != NULL) {
2005 main_threads->prev = m;
2009 #if defined(RTS_SUPPORTS_THREADS)
2010 // Allocating a new condition for each thread is expensive, so we
2011 // cache one. This is a pretty feeble hack, but it helps speed up
2012 // consecutive call-ins quite a bit.
2013 if (bound_cond_cache_full) {
2014 m->bound_thread_cond = bound_cond_cache;
2015 bound_cond_cache_full = 0;
2017 initCondition(&m->bound_thread_cond);
2021 /* Put the thread on the main-threads list prior to scheduling the TSO.
2022 Failure to do so introduces a race condition in the MT case (as
2023 identified by Wolfgang Thaller), whereby the new task/OS thread
2024 created by scheduleThread_() would complete prior to the thread
2025 that spawned it managed to put 'itself' on the main-threads list.
2026 The upshot of it all being that the worker thread wouldn't get to
2027 signal the completion of the its work item for the main thread to
2028 see (==> it got stuck waiting.) -- sof 6/02.
2030 IF_DEBUG(scheduler, sched_belch("waiting for thread (%d)", tso->id));
2032 APPEND_TO_RUN_QUEUE(tso);
2033 // NB. Don't call threadRunnable() here, because the thread is
2034 // bound and only runnable by *this* OS thread, so waking up other
2035 // workers will just slow things down.
2037 return waitThread_(m, initialCapability);
2040 /* ---------------------------------------------------------------------------
2043 * Initialise the scheduler. This resets all the queues - if the
2044 * queues contained any threads, they'll be garbage collected at the
2047 * ------------------------------------------------------------------------ */
2055 for (i=0; i<=MAX_PROC; i++) {
2056 run_queue_hds[i] = END_TSO_QUEUE;
2057 run_queue_tls[i] = END_TSO_QUEUE;
2058 blocked_queue_hds[i] = END_TSO_QUEUE;
2059 blocked_queue_tls[i] = END_TSO_QUEUE;
2060 ccalling_threadss[i] = END_TSO_QUEUE;
2061 sleeping_queue = END_TSO_QUEUE;
2064 run_queue_hd = END_TSO_QUEUE;
2065 run_queue_tl = END_TSO_QUEUE;
2066 blocked_queue_hd = END_TSO_QUEUE;
2067 blocked_queue_tl = END_TSO_QUEUE;
2068 sleeping_queue = END_TSO_QUEUE;
2071 suspended_ccalling_threads = END_TSO_QUEUE;
2073 main_threads = NULL;
2074 all_threads = END_TSO_QUEUE;
2079 RtsFlags.ConcFlags.ctxtSwitchTicks =
2080 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
2082 #if defined(RTS_SUPPORTS_THREADS)
2083 /* Initialise the mutex and condition variables used by
2085 initMutex(&sched_mutex);
2086 initMutex(&term_mutex);
2089 ACQUIRE_LOCK(&sched_mutex);
2091 /* A capability holds the state a native thread needs in
2092 * order to execute STG code. At least one capability is
2093 * floating around (only SMP builds have more than one).
2097 #if defined(RTS_SUPPORTS_THREADS)
2098 /* start our haskell execution tasks */
2099 startTaskManager(0,taskStart);
2102 #if /* defined(SMP) ||*/ defined(PAR)
2106 RELEASE_LOCK(&sched_mutex);
2110 exitScheduler( void )
2112 #if defined(RTS_SUPPORTS_THREADS)
2115 shutting_down_scheduler = rtsTrue;
2118 /* ----------------------------------------------------------------------------
2119 Managing the per-task allocation areas.
2121 Each capability comes with an allocation area. These are
2122 fixed-length block lists into which allocation can be done.
2124 ToDo: no support for two-space collection at the moment???
2125 ------------------------------------------------------------------------- */
2129 waitThread_(StgMainThread* m, Capability *initialCapability)
2131 SchedulerStatus stat;
2133 // Precondition: sched_mutex must be held.
2134 IF_DEBUG(scheduler, sched_belch("new main thread (%d)", m->tso->id));
2137 /* GranSim specific init */
2138 CurrentTSO = m->tso; // the TSO to run
2139 procStatus[MainProc] = Busy; // status of main PE
2140 CurrentProc = MainProc; // PE to run it on
2141 schedule(m,initialCapability);
2143 schedule(m,initialCapability);
2144 ASSERT(m->stat != NoStatus);
2149 #if defined(RTS_SUPPORTS_THREADS)
2150 // Free the condition variable, returning it to the cache if possible.
2151 if (!bound_cond_cache_full) {
2152 bound_cond_cache = m->bound_thread_cond;
2153 bound_cond_cache_full = 1;
2155 closeCondition(&m->bound_thread_cond);
2159 IF_DEBUG(scheduler, sched_belch("main thread (%d) finished", m->tso->id));
2162 // Postcondition: sched_mutex still held
2166 /* ---------------------------------------------------------------------------
2167 Where are the roots that we know about?
2169 - all the threads on the runnable queue
2170 - all the threads on the blocked queue
2171 - all the threads on the sleeping queue
2172 - all the thread currently executing a _ccall_GC
2173 - all the "main threads"
2175 ------------------------------------------------------------------------ */
2177 /* This has to be protected either by the scheduler monitor, or by the
2178 garbage collection monitor (probably the latter).
2183 GetRoots( evac_fn evac )
2188 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2189 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2190 evac((StgClosure **)&run_queue_hds[i]);
2191 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2192 evac((StgClosure **)&run_queue_tls[i]);
2194 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2195 evac((StgClosure **)&blocked_queue_hds[i]);
2196 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2197 evac((StgClosure **)&blocked_queue_tls[i]);
2198 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2199 evac((StgClosure **)&ccalling_threads[i]);
2206 if (run_queue_hd != END_TSO_QUEUE) {
2207 ASSERT(run_queue_tl != END_TSO_QUEUE);
2208 evac((StgClosure **)&run_queue_hd);
2209 evac((StgClosure **)&run_queue_tl);
2212 if (blocked_queue_hd != END_TSO_QUEUE) {
2213 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2214 evac((StgClosure **)&blocked_queue_hd);
2215 evac((StgClosure **)&blocked_queue_tl);
2218 if (sleeping_queue != END_TSO_QUEUE) {
2219 evac((StgClosure **)&sleeping_queue);
2223 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2224 evac((StgClosure **)&suspended_ccalling_threads);
2227 #if defined(PAR) || defined(GRAN)
2228 markSparkQueue(evac);
2231 #if defined(RTS_USER_SIGNALS)
2232 // mark the signal handlers (signals should be already blocked)
2233 markSignalHandlers(evac);
2237 /* -----------------------------------------------------------------------------
2240 This is the interface to the garbage collector from Haskell land.
2241 We provide this so that external C code can allocate and garbage
2242 collect when called from Haskell via _ccall_GC.
2244 It might be useful to provide an interface whereby the programmer
2245 can specify more roots (ToDo).
2247 This needs to be protected by the GC condition variable above. KH.
2248 -------------------------------------------------------------------------- */
2250 static void (*extra_roots)(evac_fn);
2255 /* Obligated to hold this lock upon entry */
2256 ACQUIRE_LOCK(&sched_mutex);
2257 GarbageCollect(GetRoots,rtsFalse);
2258 RELEASE_LOCK(&sched_mutex);
2262 performMajorGC(void)
2264 ACQUIRE_LOCK(&sched_mutex);
2265 GarbageCollect(GetRoots,rtsTrue);
2266 RELEASE_LOCK(&sched_mutex);
2270 AllRoots(evac_fn evac)
2272 GetRoots(evac); // the scheduler's roots
2273 extra_roots(evac); // the user's roots
2277 performGCWithRoots(void (*get_roots)(evac_fn))
2279 ACQUIRE_LOCK(&sched_mutex);
2280 extra_roots = get_roots;
2281 GarbageCollect(AllRoots,rtsFalse);
2282 RELEASE_LOCK(&sched_mutex);
2285 /* -----------------------------------------------------------------------------
2288 If the thread has reached its maximum stack size, then raise the
2289 StackOverflow exception in the offending thread. Otherwise
2290 relocate the TSO into a larger chunk of memory and adjust its stack
2292 -------------------------------------------------------------------------- */
2295 threadStackOverflow(StgTSO *tso)
2297 nat new_stack_size, new_tso_size, stack_words;
2301 IF_DEBUG(sanity,checkTSO(tso));
2302 if (tso->stack_size >= tso->max_stack_size) {
2305 debugBelch("@@ threadStackOverflow of TSO %ld (%p): stack too large (now %ld; max is %ld)\n",
2306 (long)tso->id, tso, (long)tso->stack_size, (long)tso->max_stack_size);
2307 /* If we're debugging, just print out the top of the stack */
2308 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2311 /* Send this thread the StackOverflow exception */
2312 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2316 /* Try to double the current stack size. If that takes us over the
2317 * maximum stack size for this thread, then use the maximum instead.
2318 * Finally round up so the TSO ends up as a whole number of blocks.
2320 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2321 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2322 TSO_STRUCT_SIZE)/sizeof(W_);
2323 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2324 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2326 IF_DEBUG(scheduler, debugBelch("== sched: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2328 dest = (StgTSO *)allocate(new_tso_size);
2329 TICK_ALLOC_TSO(new_stack_size,0);
2331 /* copy the TSO block and the old stack into the new area */
2332 memcpy(dest,tso,TSO_STRUCT_SIZE);
2333 stack_words = tso->stack + tso->stack_size - tso->sp;
2334 new_sp = (P_)dest + new_tso_size - stack_words;
2335 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2337 /* relocate the stack pointers... */
2339 dest->stack_size = new_stack_size;
2341 /* Mark the old TSO as relocated. We have to check for relocated
2342 * TSOs in the garbage collector and any primops that deal with TSOs.
2344 * It's important to set the sp value to just beyond the end
2345 * of the stack, so we don't attempt to scavenge any part of the
2348 tso->what_next = ThreadRelocated;
2350 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2351 tso->why_blocked = NotBlocked;
2353 IF_PAR_DEBUG(verbose,
2354 debugBelch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld\n",
2355 tso->id, tso, tso->stack_size);
2356 /* If we're debugging, just print out the top of the stack */
2357 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2360 IF_DEBUG(sanity,checkTSO(tso));
2362 IF_DEBUG(scheduler,printTSO(dest));
2368 /* ---------------------------------------------------------------------------
2369 Wake up a queue that was blocked on some resource.
2370 ------------------------------------------------------------------------ */
2374 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2379 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2381 /* write RESUME events to log file and
2382 update blocked and fetch time (depending on type of the orig closure) */
2383 if (RtsFlags.ParFlags.ParStats.Full) {
2384 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2385 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2386 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2387 if (EMPTY_RUN_QUEUE())
2388 emitSchedule = rtsTrue;
2390 switch (get_itbl(node)->type) {
2392 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2397 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2404 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2411 static StgBlockingQueueElement *
2412 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2415 PEs node_loc, tso_loc;
2417 node_loc = where_is(node); // should be lifted out of loop
2418 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2419 tso_loc = where_is((StgClosure *)tso);
2420 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2421 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2422 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2423 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2424 // insertThread(tso, node_loc);
2425 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2427 tso, node, (rtsSpark*)NULL);
2428 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2431 } else { // TSO is remote (actually should be FMBQ)
2432 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2433 RtsFlags.GranFlags.Costs.gunblocktime +
2434 RtsFlags.GranFlags.Costs.latency;
2435 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2437 tso, node, (rtsSpark*)NULL);
2438 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2441 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2443 debugBelch(" %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2444 (node_loc==tso_loc ? "Local" : "Global"),
2445 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2446 tso->block_info.closure = NULL;
2447 IF_DEBUG(scheduler,debugBelch("-- Waking up thread %ld (%p)\n",
2451 static StgBlockingQueueElement *
2452 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2454 StgBlockingQueueElement *next;
2456 switch (get_itbl(bqe)->type) {
2458 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2459 /* if it's a TSO just push it onto the run_queue */
2461 ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2462 APPEND_TO_RUN_QUEUE((StgTSO *)bqe);
2464 unblockCount(bqe, node);
2465 /* reset blocking status after dumping event */
2466 ((StgTSO *)bqe)->why_blocked = NotBlocked;
2470 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2472 bqe->link = (StgBlockingQueueElement *)PendingFetches;
2473 PendingFetches = (StgBlockedFetch *)bqe;
2477 /* can ignore this case in a non-debugging setup;
2478 see comments on RBHSave closures above */
2480 /* check that the closure is an RBHSave closure */
2481 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2482 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2483 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2487 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2488 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
2492 IF_PAR_DEBUG(bq, debugBelch(", %p (%s)\n", bqe, info_type((StgClosure*)bqe)));
2496 #else /* !GRAN && !PAR */
2498 unblockOneLocked(StgTSO *tso)
2502 ASSERT(get_itbl(tso)->type == TSO);
2503 ASSERT(tso->why_blocked != NotBlocked);
2504 tso->why_blocked = NotBlocked;
2506 tso->link = END_TSO_QUEUE;
2507 APPEND_TO_RUN_QUEUE(tso);
2509 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", (long)tso->id));
2514 #if defined(GRAN) || defined(PAR)
2515 INLINE_ME StgBlockingQueueElement *
2516 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2518 ACQUIRE_LOCK(&sched_mutex);
2519 bqe = unblockOneLocked(bqe, node);
2520 RELEASE_LOCK(&sched_mutex);
2525 unblockOne(StgTSO *tso)
2527 ACQUIRE_LOCK(&sched_mutex);
2528 tso = unblockOneLocked(tso);
2529 RELEASE_LOCK(&sched_mutex);
2536 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2538 StgBlockingQueueElement *bqe;
2543 debugBelch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): \n", \
2544 node, CurrentProc, CurrentTime[CurrentProc],
2545 CurrentTSO->id, CurrentTSO));
2547 node_loc = where_is(node);
2549 ASSERT(q == END_BQ_QUEUE ||
2550 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
2551 get_itbl(q)->type == CONSTR); // closure (type constructor)
2552 ASSERT(is_unique(node));
2554 /* FAKE FETCH: magically copy the node to the tso's proc;
2555 no Fetch necessary because in reality the node should not have been
2556 moved to the other PE in the first place
2558 if (CurrentProc!=node_loc) {
2560 debugBelch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)\n",
2561 node, node_loc, CurrentProc, CurrentTSO->id,
2562 // CurrentTSO, where_is(CurrentTSO),
2563 node->header.gran.procs));
2564 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
2566 debugBelch("## new bitmask of node %p is %#x\n",
2567 node, node->header.gran.procs));
2568 if (RtsFlags.GranFlags.GranSimStats.Global) {
2569 globalGranStats.tot_fake_fetches++;
2574 // ToDo: check: ASSERT(CurrentProc==node_loc);
2575 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
2578 bqe points to the current element in the queue
2579 next points to the next element in the queue
2581 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2582 //tso_loc = where_is(tso);
2584 bqe = unblockOneLocked(bqe, node);
2587 /* if this is the BQ of an RBH, we have to put back the info ripped out of
2588 the closure to make room for the anchor of the BQ */
2589 if (bqe!=END_BQ_QUEUE) {
2590 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
2592 ASSERT((info_ptr==&RBH_Save_0_info) ||
2593 (info_ptr==&RBH_Save_1_info) ||
2594 (info_ptr==&RBH_Save_2_info));
2596 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
2597 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
2598 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
2601 debugBelch("## Filled in RBH_Save for %p (%s) at end of AwBQ\n",
2602 node, info_type(node)));
2605 /* statistics gathering */
2606 if (RtsFlags.GranFlags.GranSimStats.Global) {
2607 // globalGranStats.tot_bq_processing_time += bq_processing_time;
2608 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
2609 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
2610 globalGranStats.tot_awbq++; // total no. of bqs awakened
2613 debugBelch("## BQ Stats of %p: [%d entries] %s\n",
2614 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
2618 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2620 StgBlockingQueueElement *bqe;
2622 ACQUIRE_LOCK(&sched_mutex);
2624 IF_PAR_DEBUG(verbose,
2625 debugBelch("##-_ AwBQ for node %p on [%x]: \n",
2629 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
2630 IF_PAR_DEBUG(verbose, debugBelch("## ... nothing to unblock so lets just return. RFP (BUG?)\n"));
2635 ASSERT(q == END_BQ_QUEUE ||
2636 get_itbl(q)->type == TSO ||
2637 get_itbl(q)->type == BLOCKED_FETCH ||
2638 get_itbl(q)->type == CONSTR);
2641 while (get_itbl(bqe)->type==TSO ||
2642 get_itbl(bqe)->type==BLOCKED_FETCH) {
2643 bqe = unblockOneLocked(bqe, node);
2645 RELEASE_LOCK(&sched_mutex);
2648 #else /* !GRAN && !PAR */
2651 awakenBlockedQueueNoLock(StgTSO *tso)
2653 while (tso != END_TSO_QUEUE) {
2654 tso = unblockOneLocked(tso);
2659 awakenBlockedQueue(StgTSO *tso)
2661 ACQUIRE_LOCK(&sched_mutex);
2662 while (tso != END_TSO_QUEUE) {
2663 tso = unblockOneLocked(tso);
2665 RELEASE_LOCK(&sched_mutex);
2669 /* ---------------------------------------------------------------------------
2671 - usually called inside a signal handler so it mustn't do anything fancy.
2672 ------------------------------------------------------------------------ */
2675 interruptStgRts(void)
2681 /* -----------------------------------------------------------------------------
2684 This is for use when we raise an exception in another thread, which
2686 This has nothing to do with the UnblockThread event in GranSim. -- HWL
2687 -------------------------------------------------------------------------- */
2689 #if defined(GRAN) || defined(PAR)
2691 NB: only the type of the blocking queue is different in GranSim and GUM
2692 the operations on the queue-elements are the same
2693 long live polymorphism!
2695 Locks: sched_mutex is held upon entry and exit.
2699 unblockThread(StgTSO *tso)
2701 StgBlockingQueueElement *t, **last;
2703 switch (tso->why_blocked) {
2706 return; /* not blocked */
2709 // Be careful: nothing to do here! We tell the scheduler that the thread
2710 // is runnable and we leave it to the stack-walking code to abort the
2711 // transaction while unwinding the stack. We should perhaps have a debugging
2712 // test to make sure that this really happens and that the 'zombie' transaction
2713 // does not get committed.
2717 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2719 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
2720 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2722 last = (StgBlockingQueueElement **)&mvar->head;
2723 for (t = (StgBlockingQueueElement *)mvar->head;
2725 last = &t->link, last_tso = t, t = t->link) {
2726 if (t == (StgBlockingQueueElement *)tso) {
2727 *last = (StgBlockingQueueElement *)tso->link;
2728 if (mvar->tail == tso) {
2729 mvar->tail = (StgTSO *)last_tso;
2734 barf("unblockThread (MVAR): TSO not found");
2737 case BlockedOnBlackHole:
2738 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2740 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2742 last = &bq->blocking_queue;
2743 for (t = bq->blocking_queue;
2745 last = &t->link, t = t->link) {
2746 if (t == (StgBlockingQueueElement *)tso) {
2747 *last = (StgBlockingQueueElement *)tso->link;
2751 barf("unblockThread (BLACKHOLE): TSO not found");
2754 case BlockedOnException:
2756 StgTSO *target = tso->block_info.tso;
2758 ASSERT(get_itbl(target)->type == TSO);
2760 if (target->what_next == ThreadRelocated) {
2761 target = target->link;
2762 ASSERT(get_itbl(target)->type == TSO);
2765 ASSERT(target->blocked_exceptions != NULL);
2767 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
2768 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
2770 last = &t->link, t = t->link) {
2771 ASSERT(get_itbl(t)->type == TSO);
2772 if (t == (StgBlockingQueueElement *)tso) {
2773 *last = (StgBlockingQueueElement *)tso->link;
2777 barf("unblockThread (Exception): TSO not found");
2781 case BlockedOnWrite:
2782 #if defined(mingw32_HOST_OS)
2783 case BlockedOnDoProc:
2786 /* take TSO off blocked_queue */
2787 StgBlockingQueueElement *prev = NULL;
2788 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
2789 prev = t, t = t->link) {
2790 if (t == (StgBlockingQueueElement *)tso) {
2792 blocked_queue_hd = (StgTSO *)t->link;
2793 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2794 blocked_queue_tl = END_TSO_QUEUE;
2797 prev->link = t->link;
2798 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2799 blocked_queue_tl = (StgTSO *)prev;
2805 barf("unblockThread (I/O): TSO not found");
2808 case BlockedOnDelay:
2810 /* take TSO off sleeping_queue */
2811 StgBlockingQueueElement *prev = NULL;
2812 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
2813 prev = t, t = t->link) {
2814 if (t == (StgBlockingQueueElement *)tso) {
2816 sleeping_queue = (StgTSO *)t->link;
2818 prev->link = t->link;
2823 barf("unblockThread (delay): TSO not found");
2827 barf("unblockThread");
2831 tso->link = END_TSO_QUEUE;
2832 tso->why_blocked = NotBlocked;
2833 tso->block_info.closure = NULL;
2834 PUSH_ON_RUN_QUEUE(tso);
2838 unblockThread(StgTSO *tso)
2842 /* To avoid locking unnecessarily. */
2843 if (tso->why_blocked == NotBlocked) {
2847 switch (tso->why_blocked) {
2850 // Be careful: nothing to do here! We tell the scheduler that the thread
2851 // is runnable and we leave it to the stack-walking code to abort the
2852 // transaction while unwinding the stack. We should perhaps have a debugging
2853 // test to make sure that this really happens and that the 'zombie' transaction
2854 // does not get committed.
2858 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2860 StgTSO *last_tso = END_TSO_QUEUE;
2861 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2864 for (t = mvar->head; t != END_TSO_QUEUE;
2865 last = &t->link, last_tso = t, t = t->link) {
2868 if (mvar->tail == tso) {
2869 mvar->tail = last_tso;
2874 barf("unblockThread (MVAR): TSO not found");
2877 case BlockedOnBlackHole:
2878 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2880 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2882 last = &bq->blocking_queue;
2883 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
2884 last = &t->link, t = t->link) {
2890 barf("unblockThread (BLACKHOLE): TSO not found");
2893 case BlockedOnException:
2895 StgTSO *target = tso->block_info.tso;
2897 ASSERT(get_itbl(target)->type == TSO);
2899 while (target->what_next == ThreadRelocated) {
2900 target = target->link;
2901 ASSERT(get_itbl(target)->type == TSO);
2904 ASSERT(target->blocked_exceptions != NULL);
2906 last = &target->blocked_exceptions;
2907 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
2908 last = &t->link, t = t->link) {
2909 ASSERT(get_itbl(t)->type == TSO);
2915 barf("unblockThread (Exception): TSO not found");
2919 case BlockedOnWrite:
2920 #if defined(mingw32_HOST_OS)
2921 case BlockedOnDoProc:
2924 StgTSO *prev = NULL;
2925 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
2926 prev = t, t = t->link) {
2929 blocked_queue_hd = t->link;
2930 if (blocked_queue_tl == t) {
2931 blocked_queue_tl = END_TSO_QUEUE;
2934 prev->link = t->link;
2935 if (blocked_queue_tl == t) {
2936 blocked_queue_tl = prev;
2942 barf("unblockThread (I/O): TSO not found");
2945 case BlockedOnDelay:
2947 StgTSO *prev = NULL;
2948 for (t = sleeping_queue; t != END_TSO_QUEUE;
2949 prev = t, t = t->link) {
2952 sleeping_queue = t->link;
2954 prev->link = t->link;
2959 barf("unblockThread (delay): TSO not found");
2963 barf("unblockThread");
2967 tso->link = END_TSO_QUEUE;
2968 tso->why_blocked = NotBlocked;
2969 tso->block_info.closure = NULL;
2970 APPEND_TO_RUN_QUEUE(tso);
2974 /* -----------------------------------------------------------------------------
2977 * The following function implements the magic for raising an
2978 * asynchronous exception in an existing thread.
2980 * We first remove the thread from any queue on which it might be
2981 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
2983 * We strip the stack down to the innermost CATCH_FRAME, building
2984 * thunks in the heap for all the active computations, so they can
2985 * be restarted if necessary. When we reach a CATCH_FRAME, we build
2986 * an application of the handler to the exception, and push it on
2987 * the top of the stack.
2989 * How exactly do we save all the active computations? We create an
2990 * AP_STACK for every UpdateFrame on the stack. Entering one of these
2991 * AP_STACKs pushes everything from the corresponding update frame
2992 * upwards onto the stack. (Actually, it pushes everything up to the
2993 * next update frame plus a pointer to the next AP_STACK object.
2994 * Entering the next AP_STACK object pushes more onto the stack until we
2995 * reach the last AP_STACK object - at which point the stack should look
2996 * exactly as it did when we killed the TSO and we can continue
2997 * execution by entering the closure on top of the stack.
2999 * We can also kill a thread entirely - this happens if either (a) the
3000 * exception passed to raiseAsync is NULL, or (b) there's no
3001 * CATCH_FRAME on the stack. In either case, we strip the entire
3002 * stack and replace the thread with a zombie.
3004 * Locks: sched_mutex held upon entry nor exit.
3006 * -------------------------------------------------------------------------- */
3009 deleteThread(StgTSO *tso)
3011 if (tso->why_blocked != BlockedOnCCall &&
3012 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
3013 raiseAsync(tso,NULL);
3017 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
3019 deleteThreadImmediately(StgTSO *tso)
3020 { // for forkProcess only:
3021 // delete thread without giving it a chance to catch the KillThread exception
3023 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3027 if (tso->why_blocked != BlockedOnCCall &&
3028 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
3032 tso->what_next = ThreadKilled;
3037 raiseAsyncWithLock(StgTSO *tso, StgClosure *exception)
3039 /* When raising async exs from contexts where sched_mutex isn't held;
3040 use raiseAsyncWithLock(). */
3041 ACQUIRE_LOCK(&sched_mutex);
3042 raiseAsync(tso,exception);
3043 RELEASE_LOCK(&sched_mutex);
3047 raiseAsync(StgTSO *tso, StgClosure *exception)
3049 raiseAsync_(tso, exception, rtsFalse);
3053 raiseAsync_(StgTSO *tso, StgClosure *exception, rtsBool stop_at_atomically)
3055 StgRetInfoTable *info;
3058 // Thread already dead?
3059 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3064 sched_belch("raising exception in thread %ld.", (long)tso->id));
3066 // Remove it from any blocking queues
3071 // The stack freezing code assumes there's a closure pointer on
3072 // the top of the stack, so we have to arrange that this is the case...
3074 if (sp[0] == (W_)&stg_enter_info) {
3078 sp[0] = (W_)&stg_dummy_ret_closure;
3084 // 1. Let the top of the stack be the "current closure"
3086 // 2. Walk up the stack until we find either an UPDATE_FRAME or a
3089 // 3. If it's an UPDATE_FRAME, then make an AP_STACK containing the
3090 // current closure applied to the chunk of stack up to (but not
3091 // including) the update frame. This closure becomes the "current
3092 // closure". Go back to step 2.
3094 // 4. If it's a CATCH_FRAME, then leave the exception handler on
3095 // top of the stack applied to the exception.
3097 // 5. If it's a STOP_FRAME, then kill the thread.
3099 // NB: if we pass an ATOMICALLY_FRAME then abort the associated
3106 info = get_ret_itbl((StgClosure *)frame);
3108 while (info->i.type != UPDATE_FRAME
3109 && (info->i.type != CATCH_FRAME || exception == NULL)
3110 && info->i.type != STOP_FRAME
3111 && (info->i.type != ATOMICALLY_FRAME || stop_at_atomically == rtsFalse))
3113 if (info->i.type == CATCH_RETRY_FRAME || info->i.type == ATOMICALLY_FRAME) {
3114 // IF we find an ATOMICALLY_FRAME then we abort the
3115 // current transaction and propagate the exception. In
3116 // this case (unlike ordinary exceptions) we do not care
3117 // whether the transaction is valid or not because its
3118 // possible validity cannot have caused the exception
3119 // and will not be visible after the abort.
3121 debugBelch("Found atomically block delivering async exception\n"));
3122 stmAbortTransaction(tso -> trec);
3123 tso -> trec = stmGetEnclosingTRec(tso -> trec);
3125 frame += stack_frame_sizeW((StgClosure *)frame);
3126 info = get_ret_itbl((StgClosure *)frame);
3129 switch (info->i.type) {
3131 case ATOMICALLY_FRAME:
3132 ASSERT(stop_at_atomically);
3133 ASSERT(stmGetEnclosingTRec(tso->trec) == NO_TREC);
3134 stmCondemnTransaction(tso -> trec);
3138 // R1 is not a register: the return convention for IO in
3139 // this case puts the return value on the stack, so we
3140 // need to set up the stack to return to the atomically
3141 // frame properly...
3142 tso->sp = frame - 2;
3143 tso->sp[1] = (StgWord) &stg_NO_FINALIZER_closure; // why not?
3144 tso->sp[0] = (StgWord) &stg_ut_1_0_unreg_info;
3146 tso->what_next = ThreadRunGHC;
3150 // If we find a CATCH_FRAME, and we've got an exception to raise,
3151 // then build the THUNK raise(exception), and leave it on
3152 // top of the CATCH_FRAME ready to enter.
3156 StgCatchFrame *cf = (StgCatchFrame *)frame;
3160 // we've got an exception to raise, so let's pass it to the
3161 // handler in this frame.
3163 raise = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3164 TICK_ALLOC_SE_THK(1,0);
3165 SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
3166 raise->payload[0] = exception;
3168 // throw away the stack from Sp up to the CATCH_FRAME.
3172 /* Ensure that async excpetions are blocked now, so we don't get
3173 * a surprise exception before we get around to executing the
3176 if (tso->blocked_exceptions == NULL) {
3177 tso->blocked_exceptions = END_TSO_QUEUE;
3180 /* Put the newly-built THUNK on top of the stack, ready to execute
3181 * when the thread restarts.
3184 sp[-1] = (W_)&stg_enter_info;
3186 tso->what_next = ThreadRunGHC;
3187 IF_DEBUG(sanity, checkTSO(tso));
3196 // First build an AP_STACK consisting of the stack chunk above the
3197 // current update frame, with the top word on the stack as the
3200 words = frame - sp - 1;
3201 ap = (StgAP_STACK *)allocate(PAP_sizeW(words));
3204 ap->fun = (StgClosure *)sp[0];
3206 for(i=0; i < (nat)words; ++i) {
3207 ap->payload[i] = (StgClosure *)*sp++;
3210 SET_HDR(ap,&stg_AP_STACK_info,
3211 ((StgClosure *)frame)->header.prof.ccs /* ToDo */);
3212 TICK_ALLOC_UP_THK(words+1,0);
3215 debugBelch("sched: Updating ");
3216 printPtr((P_)((StgUpdateFrame *)frame)->updatee);
3217 debugBelch(" with ");
3218 printObj((StgClosure *)ap);
3221 // Replace the updatee with an indirection - happily
3222 // this will also wake up any threads currently
3223 // waiting on the result.
3225 // Warning: if we're in a loop, more than one update frame on
3226 // the stack may point to the same object. Be careful not to
3227 // overwrite an IND_OLDGEN in this case, because we'll screw
3228 // up the mutable lists. To be on the safe side, don't
3229 // overwrite any kind of indirection at all. See also
3230 // threadSqueezeStack in GC.c, where we have to make a similar
3233 if (!closure_IND(((StgUpdateFrame *)frame)->updatee)) {
3234 // revert the black hole
3235 UPD_IND_NOLOCK(((StgUpdateFrame *)frame)->updatee,
3238 sp += sizeofW(StgUpdateFrame) - 1;
3239 sp[0] = (W_)ap; // push onto stack
3244 // We've stripped the entire stack, the thread is now dead.
3245 sp += sizeofW(StgStopFrame);
3246 tso->what_next = ThreadKilled;
3257 /* -----------------------------------------------------------------------------
3258 raiseExceptionHelper
3260 This function is called by the raise# primitve, just so that we can
3261 move some of the tricky bits of raising an exception from C-- into
3262 C. Who knows, it might be a useful re-useable thing here too.
3263 -------------------------------------------------------------------------- */
3266 raiseExceptionHelper (StgTSO *tso, StgClosure *exception)
3268 StgClosure *raise_closure = NULL;
3270 StgRetInfoTable *info;
3272 // This closure represents the expression 'raise# E' where E
3273 // is the exception raise. It is used to overwrite all the
3274 // thunks which are currently under evaluataion.
3278 // LDV profiling: stg_raise_info has THUNK as its closure
3279 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
3280 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
3281 // 1 does not cause any problem unless profiling is performed.
3282 // However, when LDV profiling goes on, we need to linearly scan
3283 // small object pool, where raise_closure is stored, so we should
3284 // use MIN_UPD_SIZE.
3286 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
3287 // sizeofW(StgClosure)+1);
3291 // Walk up the stack, looking for the catch frame. On the way,
3292 // we update any closures pointed to from update frames with the
3293 // raise closure that we just built.
3297 info = get_ret_itbl((StgClosure *)p);
3298 next = p + stack_frame_sizeW((StgClosure *)p);
3299 switch (info->i.type) {
3302 // Only create raise_closure if we need to.
3303 if (raise_closure == NULL) {
3305 (StgClosure *)allocate(sizeofW(StgClosure)+MIN_UPD_SIZE);
3306 SET_HDR(raise_closure, &stg_raise_info, CCCS);
3307 raise_closure->payload[0] = exception;
3309 UPD_IND(((StgUpdateFrame *)p)->updatee,raise_closure);
3313 case ATOMICALLY_FRAME:
3314 IF_DEBUG(stm, debugBelch("Found ATOMICALLY_FRAME at %p\n", p));
3316 return ATOMICALLY_FRAME;
3322 case CATCH_STM_FRAME:
3323 IF_DEBUG(stm, debugBelch("Found CATCH_STM_FRAME at %p\n", p));
3325 return CATCH_STM_FRAME;
3331 case CATCH_RETRY_FRAME:
3340 /* -----------------------------------------------------------------------------
3341 findRetryFrameHelper
3343 This function is called by the retry# primitive. It traverses the stack
3344 leaving tso->sp referring to the frame which should handle the retry.
3346 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
3347 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
3349 We skip CATCH_STM_FRAMEs because retries are not considered to be exceptions,
3350 despite the similar implementation.
3352 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
3353 not be created within memory transactions.
3354 -------------------------------------------------------------------------- */
3357 findRetryFrameHelper (StgTSO *tso)
3360 StgRetInfoTable *info;
3364 info = get_ret_itbl((StgClosure *)p);
3365 next = p + stack_frame_sizeW((StgClosure *)p);
3366 switch (info->i.type) {
3368 case ATOMICALLY_FRAME:
3369 IF_DEBUG(stm, debugBelch("Found ATOMICALLY_FRAME at %p during retrry\n", p));
3371 return ATOMICALLY_FRAME;
3373 case CATCH_RETRY_FRAME:
3374 IF_DEBUG(stm, debugBelch("Found CATCH_RETRY_FRAME at %p during retrry\n", p));
3376 return CATCH_RETRY_FRAME;
3378 case CATCH_STM_FRAME:
3380 ASSERT(info->i.type != CATCH_FRAME);
3381 ASSERT(info->i.type != STOP_FRAME);
3388 /* -----------------------------------------------------------------------------
3389 resurrectThreads is called after garbage collection on the list of
3390 threads found to be garbage. Each of these threads will be woken
3391 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3392 on an MVar, or NonTermination if the thread was blocked on a Black
3395 Locks: sched_mutex isn't held upon entry nor exit.
3396 -------------------------------------------------------------------------- */
3399 resurrectThreads( StgTSO *threads )
3403 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3404 next = tso->global_link;
3405 tso->global_link = all_threads;
3407 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3409 switch (tso->why_blocked) {
3411 case BlockedOnException:
3412 /* Called by GC - sched_mutex lock is currently held. */
3413 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3415 case BlockedOnBlackHole:
3416 raiseAsync(tso,(StgClosure *)NonTermination_closure);
3419 raiseAsync(tso,(StgClosure *)BlockedIndefinitely_closure);
3422 /* This might happen if the thread was blocked on a black hole
3423 * belonging to a thread that we've just woken up (raiseAsync
3424 * can wake up threads, remember...).
3428 barf("resurrectThreads: thread blocked in a strange way");
3433 /* ----------------------------------------------------------------------------
3434 * Debugging: why is a thread blocked
3435 * [Also provides useful information when debugging threaded programs
3436 * at the Haskell source code level, so enable outside of DEBUG. --sof 7/02]
3437 ------------------------------------------------------------------------- */
3441 printThreadBlockage(StgTSO *tso)
3443 switch (tso->why_blocked) {
3445 debugBelch("is blocked on read from fd %d", tso->block_info.fd);
3447 case BlockedOnWrite:
3448 debugBelch("is blocked on write to fd %d", tso->block_info.fd);
3450 #if defined(mingw32_HOST_OS)
3451 case BlockedOnDoProc:
3452 debugBelch("is blocked on proc (request: %d)", tso->block_info.async_result->reqID);
3455 case BlockedOnDelay:
3456 debugBelch("is blocked until %d", tso->block_info.target);
3459 debugBelch("is blocked on an MVar");
3461 case BlockedOnException:
3462 debugBelch("is blocked on delivering an exception to thread %d",
3463 tso->block_info.tso->id);
3465 case BlockedOnBlackHole:
3466 debugBelch("is blocked on a black hole");
3469 debugBelch("is not blocked");
3473 debugBelch("is blocked on global address; local FM_BQ is %p (%s)",
3474 tso->block_info.closure, info_type(tso->block_info.closure));
3476 case BlockedOnGA_NoSend:
3477 debugBelch("is blocked on global address (no send); local FM_BQ is %p (%s)",
3478 tso->block_info.closure, info_type(tso->block_info.closure));
3481 case BlockedOnCCall:
3482 debugBelch("is blocked on an external call");
3484 case BlockedOnCCall_NoUnblockExc:
3485 debugBelch("is blocked on an external call (exceptions were already blocked)");
3488 debugBelch("is blocked on an STM operation");
3491 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3492 tso->why_blocked, tso->id, tso);
3498 printThreadStatus(StgTSO *tso)
3500 switch (tso->what_next) {
3502 debugBelch("has been killed");
3504 case ThreadComplete:
3505 debugBelch("has completed");
3508 printThreadBlockage(tso);
3513 printAllThreads(void)
3518 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3519 ullong_format_string(TIME_ON_PROC(CurrentProc),
3520 time_string, rtsFalse/*no commas!*/);
3522 debugBelch("all threads at [%s]:\n", time_string);
3524 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3525 ullong_format_string(CURRENT_TIME,
3526 time_string, rtsFalse/*no commas!*/);
3528 debugBelch("all threads at [%s]:\n", time_string);
3530 debugBelch("all threads:\n");
3533 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3534 debugBelch("\tthread %d @ %p ", t->id, (void *)t);
3537 void *label = lookupThreadLabel(t->id);
3538 if (label) debugBelch("[\"%s\"] ",(char *)label);
3541 printThreadStatus(t);
3549 Print a whole blocking queue attached to node (debugging only).
3553 print_bq (StgClosure *node)
3555 StgBlockingQueueElement *bqe;
3559 debugBelch("## BQ of closure %p (%s): ",
3560 node, info_type(node));
3562 /* should cover all closures that may have a blocking queue */
3563 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3564 get_itbl(node)->type == FETCH_ME_BQ ||
3565 get_itbl(node)->type == RBH ||
3566 get_itbl(node)->type == MVAR);
3568 ASSERT(node!=(StgClosure*)NULL); // sanity check
3570 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
3574 Print a whole blocking queue starting with the element bqe.
3577 print_bqe (StgBlockingQueueElement *bqe)
3582 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3584 for (end = (bqe==END_BQ_QUEUE);
3585 !end; // iterate until bqe points to a CONSTR
3586 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
3587 bqe = end ? END_BQ_QUEUE : bqe->link) {
3588 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3589 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3590 /* types of closures that may appear in a blocking queue */
3591 ASSERT(get_itbl(bqe)->type == TSO ||
3592 get_itbl(bqe)->type == BLOCKED_FETCH ||
3593 get_itbl(bqe)->type == CONSTR);
3594 /* only BQs of an RBH end with an RBH_Save closure */
3595 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3597 switch (get_itbl(bqe)->type) {
3599 debugBelch(" TSO %u (%x),",
3600 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
3603 debugBelch(" BF (node=%p, ga=((%x, %d, %x)),",
3604 ((StgBlockedFetch *)bqe)->node,
3605 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
3606 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
3607 ((StgBlockedFetch *)bqe)->ga.weight);
3610 debugBelch(" %s (IP %p),",
3611 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3612 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3613 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3614 "RBH_Save_?"), get_itbl(bqe));
3617 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
3618 info_type((StgClosure *)bqe)); // , node, info_type(node));
3624 # elif defined(GRAN)
3626 print_bq (StgClosure *node)
3628 StgBlockingQueueElement *bqe;
3629 PEs node_loc, tso_loc;
3632 /* should cover all closures that may have a blocking queue */
3633 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3634 get_itbl(node)->type == FETCH_ME_BQ ||
3635 get_itbl(node)->type == RBH);
3637 ASSERT(node!=(StgClosure*)NULL); // sanity check
3638 node_loc = where_is(node);
3640 debugBelch("## BQ of closure %p (%s) on [PE %d]: ",
3641 node, info_type(node), node_loc);
3644 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3646 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
3647 !end; // iterate until bqe points to a CONSTR
3648 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
3649 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3650 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3651 /* types of closures that may appear in a blocking queue */
3652 ASSERT(get_itbl(bqe)->type == TSO ||
3653 get_itbl(bqe)->type == CONSTR);
3654 /* only BQs of an RBH end with an RBH_Save closure */
3655 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3657 tso_loc = where_is((StgClosure *)bqe);
3658 switch (get_itbl(bqe)->type) {
3660 debugBelch(" TSO %d (%p) on [PE %d],",
3661 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
3664 debugBelch(" %s (IP %p),",
3665 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3666 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3667 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3668 "RBH_Save_?"), get_itbl(bqe));
3671 barf("Unexpected closure type %s in blocking queue of %p (%s)",
3672 info_type((StgClosure *)bqe), node, info_type(node));
3680 Nice and easy: only TSOs on the blocking queue
3683 print_bq (StgClosure *node)
3687 ASSERT(node!=(StgClosure*)NULL); // sanity check
3688 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
3689 tso != END_TSO_QUEUE;
3691 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
3692 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
3693 debugBelch(" TSO %d (%p),", tso->id, tso);
3706 for (i=0, tso=run_queue_hd;
3707 tso != END_TSO_QUEUE;
3716 sched_belch(char *s, ...)
3720 #ifdef RTS_SUPPORTS_THREADS
3721 debugBelch("sched (task %p): ", osThreadId());
3725 debugBelch("sched: ");