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"
60 #include "ThreadLabels.h"
61 #include "LdvProfile.h"
64 #include "Proftimer.h"
67 #if defined(GRAN) || defined(PAR)
68 # include "GranSimRts.h"
70 # include "ParallelRts.h"
71 # include "Parallel.h"
72 # include "ParallelDebug.h"
77 #include "Capability.h"
78 #include "OSThreads.h"
81 #ifdef HAVE_SYS_TYPES_H
82 #include <sys/types.h>
97 #define USED_IN_THREADED_RTS
99 #define USED_IN_THREADED_RTS STG_UNUSED
102 #ifdef RTS_SUPPORTS_THREADS
103 #define USED_WHEN_RTS_SUPPORTS_THREADS
105 #define USED_WHEN_RTS_SUPPORTS_THREADS STG_UNUSED
108 /* Main thread queue.
109 * Locks required: sched_mutex.
111 StgMainThread *main_threads = NULL;
114 * Locks required: sched_mutex.
118 StgTSO* ActiveTSO = NULL; /* for assigning system costs; GranSim-Light only */
119 /* rtsTime TimeOfNextEvent, EndOfTimeSlice; now in GranSim.c */
122 In GranSim we have a runnable and a blocked queue for each processor.
123 In order to minimise code changes new arrays run_queue_hds/tls
124 are created. run_queue_hd is then a short cut (macro) for
125 run_queue_hds[CurrentProc] (see GranSim.h).
128 StgTSO *run_queue_hds[MAX_PROC], *run_queue_tls[MAX_PROC];
129 StgTSO *blocked_queue_hds[MAX_PROC], *blocked_queue_tls[MAX_PROC];
130 StgTSO *ccalling_threadss[MAX_PROC];
131 /* We use the same global list of threads (all_threads) in GranSim as in
132 the std RTS (i.e. we are cheating). However, we don't use this list in
133 the GranSim specific code at the moment (so we are only potentially
138 StgTSO *run_queue_hd = NULL;
139 StgTSO *run_queue_tl = NULL;
140 StgTSO *blocked_queue_hd = NULL;
141 StgTSO *blocked_queue_tl = NULL;
142 StgTSO *sleeping_queue = NULL; /* perhaps replace with a hash table? */
146 /* Linked list of all threads.
147 * Used for detecting garbage collected threads.
149 StgTSO *all_threads = NULL;
151 /* When a thread performs a safe C call (_ccall_GC, using old
152 * terminology), it gets put on the suspended_ccalling_threads
153 * list. Used by the garbage collector.
155 static StgTSO *suspended_ccalling_threads;
157 static StgTSO *threadStackOverflow(StgTSO *tso);
159 /* KH: The following two flags are shared memory locations. There is no need
160 to lock them, since they are only unset at the end of a scheduler
164 /* flag set by signal handler to precipitate a context switch */
165 nat context_switch = 0;
167 /* if this flag is set as well, give up execution */
168 rtsBool interrupted = rtsFalse;
170 /* Next thread ID to allocate.
171 * Locks required: thread_id_mutex
173 static StgThreadID next_thread_id = 1;
176 * Pointers to the state of the current thread.
177 * Rule of thumb: if CurrentTSO != NULL, then we're running a Haskell
178 * thread. If CurrentTSO == NULL, then we're at the scheduler level.
181 /* The smallest stack size that makes any sense is:
182 * RESERVED_STACK_WORDS (so we can get back from the stack overflow)
183 * + sizeofW(StgStopFrame) (the stg_stop_thread_info frame)
184 * + 1 (the closure to enter)
186 * + 1 (spare slot req'd by stg_ap_v_ret)
188 * A thread with this stack will bomb immediately with a stack
189 * overflow, which will increase its stack size.
192 #define MIN_STACK_WORDS (RESERVED_STACK_WORDS + sizeofW(StgStopFrame) + 3)
199 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
200 * exists - earlier gccs apparently didn't.
205 static rtsBool ready_to_gc;
208 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
209 * in an MT setting, needed to signal that a worker thread shouldn't hang around
210 * in the scheduler when it is out of work.
212 static rtsBool shutting_down_scheduler = rtsFalse;
214 void addToBlockedQueue ( StgTSO *tso );
216 static void schedule ( StgMainThread *mainThread, Capability *initialCapability );
217 void interruptStgRts ( void );
219 static void detectBlackHoles ( void );
221 #if defined(RTS_SUPPORTS_THREADS)
222 /* ToDo: carefully document the invariants that go together
223 * with these synchronisation objects.
225 Mutex sched_mutex = INIT_MUTEX_VAR;
226 Mutex term_mutex = INIT_MUTEX_VAR;
228 #endif /* RTS_SUPPORTS_THREADS */
232 rtsTime TimeOfLastYield;
233 rtsBool emitSchedule = rtsTrue;
237 static char *whatNext_strs[] = {
248 StgTSO * createSparkThread(rtsSpark spark);
249 StgTSO * activateSpark (rtsSpark spark);
252 /* ----------------------------------------------------------------------------
254 * ------------------------------------------------------------------------- */
256 #if defined(RTS_SUPPORTS_THREADS)
257 static rtsBool startingWorkerThread = rtsFalse;
259 static void taskStart(void);
263 ACQUIRE_LOCK(&sched_mutex);
264 startingWorkerThread = rtsFalse;
266 RELEASE_LOCK(&sched_mutex);
270 startSchedulerTaskIfNecessary(void)
272 if(run_queue_hd != END_TSO_QUEUE
273 || blocked_queue_hd != END_TSO_QUEUE
274 || sleeping_queue != END_TSO_QUEUE)
276 if(!startingWorkerThread)
277 { // we don't want to start another worker thread
278 // just because the last one hasn't yet reached the
279 // "waiting for capability" state
280 startingWorkerThread = rtsTrue;
281 if(!startTask(taskStart))
283 startingWorkerThread = rtsFalse;
290 /* ---------------------------------------------------------------------------
291 Main scheduling loop.
293 We use round-robin scheduling, each thread returning to the
294 scheduler loop when one of these conditions is detected:
297 * timer expires (thread yields)
302 Locking notes: we acquire the scheduler lock once at the beginning
303 of the scheduler loop, and release it when
305 * running a thread, or
306 * waiting for work, or
307 * waiting for a GC to complete.
310 In a GranSim setup this loop iterates over the global event queue.
311 This revolves around the global event queue, which determines what
312 to do next. Therefore, it's more complicated than either the
313 concurrent or the parallel (GUM) setup.
316 GUM iterates over incoming messages.
317 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
318 and sends out a fish whenever it has nothing to do; in-between
319 doing the actual reductions (shared code below) it processes the
320 incoming messages and deals with delayed operations
321 (see PendingFetches).
322 This is not the ugliest code you could imagine, but it's bloody close.
324 ------------------------------------------------------------------------ */
326 schedule( StgMainThread *mainThread USED_WHEN_RTS_SUPPORTS_THREADS,
327 Capability *initialCapability )
331 StgThreadReturnCode ret;
339 rtsBool receivedFinish = rtsFalse;
341 nat tp_size, sp_size; // stats only
344 rtsBool was_interrupted = rtsFalse;
347 // Pre-condition: sched_mutex is held.
348 // We might have a capability, passed in as initialCapability.
349 cap = initialCapability;
351 #if defined(RTS_SUPPORTS_THREADS)
353 // in the threaded case, the capability is either passed in via the
354 // initialCapability parameter, or initialized inside the scheduler
358 sched_belch("### NEW SCHEDULER LOOP (main thr: %p, cap: %p)",
359 mainThread, initialCapability);
362 // simply initialise it in the non-threaded case
363 grabCapability(&cap);
367 /* set up first event to get things going */
368 /* ToDo: assign costs for system setup and init MainTSO ! */
369 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
371 CurrentTSO, (StgClosure*)NULL, (rtsSpark*)NULL);
374 fprintf(stderr, "GRAN: Init CurrentTSO (in schedule) = %p\n", CurrentTSO);
375 G_TSO(CurrentTSO, 5));
377 if (RtsFlags.GranFlags.Light) {
378 /* Save current time; GranSim Light only */
379 CurrentTSO->gran.clock = CurrentTime[CurrentProc];
382 event = get_next_event();
384 while (event!=(rtsEvent*)NULL) {
385 /* Choose the processor with the next event */
386 CurrentProc = event->proc;
387 CurrentTSO = event->tso;
391 while (!receivedFinish) { /* set by processMessages */
392 /* when receiving PP_FINISH message */
394 #else // everything except GRAN and PAR
400 IF_DEBUG(scheduler, printAllThreads());
402 #if defined(RTS_SUPPORTS_THREADS)
403 // Yield the capability to higher-priority tasks if necessary.
406 yieldCapability(&cap);
409 // If we do not currently hold a capability, we wait for one
412 waitForCapability(&sched_mutex, &cap,
413 mainThread ? &mainThread->bound_thread_cond : NULL);
416 // We now have a capability...
420 // If we're interrupted (the user pressed ^C, or some other
421 // termination condition occurred), kill all the currently running
425 IF_DEBUG(scheduler, sched_belch("interrupted"));
426 interrupted = rtsFalse;
427 was_interrupted = rtsTrue;
428 #if defined(RTS_SUPPORTS_THREADS)
429 // In the threaded RTS, deadlock detection doesn't work,
430 // so just exit right away.
431 prog_belch("interrupted");
432 releaseCapability(cap);
433 RELEASE_LOCK(&sched_mutex);
434 shutdownHaskellAndExit(EXIT_SUCCESS);
440 #if defined(RTS_USER_SIGNALS)
441 // check for signals each time around the scheduler
442 if (signals_pending()) {
443 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
444 startSignalHandlers();
445 ACQUIRE_LOCK(&sched_mutex);
450 // Check whether any waiting threads need to be woken up. If the
451 // run queue is empty, and there are no other tasks running, we
452 // can wait indefinitely for something to happen.
454 if ( !EMPTY_QUEUE(blocked_queue_hd) || !EMPTY_QUEUE(sleeping_queue)
455 #if defined(RTS_SUPPORTS_THREADS)
460 awaitEvent( EMPTY_RUN_QUEUE() );
462 // we can be interrupted while waiting for I/O...
463 if (interrupted) continue;
466 * Detect deadlock: when we have no threads to run, there are no
467 * threads waiting on I/O or sleeping, and all the other tasks are
468 * waiting for work, we must have a deadlock of some description.
470 * We first try to find threads blocked on themselves (ie. black
471 * holes), and generate NonTermination exceptions where necessary.
473 * If no threads are black holed, we have a deadlock situation, so
474 * inform all the main threads.
476 #if !defined(PAR) && !defined(RTS_SUPPORTS_THREADS)
477 if ( EMPTY_THREAD_QUEUES() )
479 IF_DEBUG(scheduler, sched_belch("deadlocked, forcing major GC..."));
480 // Garbage collection can release some new threads due to
481 // either (a) finalizers or (b) threads resurrected because
482 // they are about to be send BlockedOnDeadMVar. Any threads
483 // thus released will be immediately runnable.
484 GarbageCollect(GetRoots,rtsTrue);
486 if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
489 sched_belch("still deadlocked, checking for black holes..."));
492 if ( !EMPTY_RUN_QUEUE() ) { goto not_deadlocked; }
494 #if defined(RTS_USER_SIGNALS)
495 /* If we have user-installed signal handlers, then wait
496 * for signals to arrive rather then bombing out with a
499 if ( anyUserHandlers() ) {
501 sched_belch("still deadlocked, waiting for signals..."));
505 // we might be interrupted...
506 if (interrupted) { continue; }
508 if (signals_pending()) {
509 RELEASE_LOCK(&sched_mutex);
510 startSignalHandlers();
511 ACQUIRE_LOCK(&sched_mutex);
513 ASSERT(!EMPTY_RUN_QUEUE());
518 /* Probably a real deadlock. Send the current main thread the
519 * Deadlock exception (or in the SMP build, send *all* main
520 * threads the deadlock exception, since none of them can make
526 switch (m->tso->why_blocked) {
527 case BlockedOnBlackHole:
528 case BlockedOnException:
530 raiseAsync(m->tso, (StgClosure *)NonTermination_closure);
533 barf("deadlock: main thread blocked in a strange way");
539 #elif defined(RTS_SUPPORTS_THREADS)
540 // ToDo: add deadlock detection in threaded RTS
542 // ToDo: add deadlock detection in GUM (similar to SMP) -- HWL
545 #if defined(RTS_SUPPORTS_THREADS)
546 if ( EMPTY_RUN_QUEUE() ) {
547 continue; // nothing to do
552 if (RtsFlags.GranFlags.Light)
553 GranSimLight_enter_system(event, &ActiveTSO); // adjust ActiveTSO etc
555 /* adjust time based on time-stamp */
556 if (event->time > CurrentTime[CurrentProc] &&
557 event->evttype != ContinueThread)
558 CurrentTime[CurrentProc] = event->time;
560 /* Deal with the idle PEs (may issue FindWork or MoveSpark events) */
561 if (!RtsFlags.GranFlags.Light)
564 IF_DEBUG(gran, fprintf(stderr, "GRAN: switch by event-type\n"));
566 /* main event dispatcher in GranSim */
567 switch (event->evttype) {
568 /* Should just be continuing execution */
570 IF_DEBUG(gran, fprintf(stderr, "GRAN: doing ContinueThread\n"));
571 /* ToDo: check assertion
572 ASSERT(run_queue_hd != (StgTSO*)NULL &&
573 run_queue_hd != END_TSO_QUEUE);
575 /* Ignore ContinueThreads for fetching threads (if synchr comm) */
576 if (!RtsFlags.GranFlags.DoAsyncFetch &&
577 procStatus[CurrentProc]==Fetching) {
578 belch("ghuH: Spurious ContinueThread while Fetching ignored; TSO %d (%p) [PE %d]",
579 CurrentTSO->id, CurrentTSO, CurrentProc);
582 /* Ignore ContinueThreads for completed threads */
583 if (CurrentTSO->what_next == ThreadComplete) {
584 belch("ghuH: found a ContinueThread event for completed thread %d (%p) [PE %d] (ignoring ContinueThread)",
585 CurrentTSO->id, CurrentTSO, CurrentProc);
588 /* Ignore ContinueThreads for threads that are being migrated */
589 if (PROCS(CurrentTSO)==Nowhere) {
590 belch("ghuH: trying to run the migrating TSO %d (%p) [PE %d] (ignoring ContinueThread)",
591 CurrentTSO->id, CurrentTSO, CurrentProc);
594 /* The thread should be at the beginning of the run queue */
595 if (CurrentTSO!=run_queue_hds[CurrentProc]) {
596 belch("ghuH: TSO %d (%p) [PE %d] is not at the start of the run_queue when doing a ContinueThread",
597 CurrentTSO->id, CurrentTSO, CurrentProc);
598 break; // run the thread anyway
601 new_event(proc, proc, CurrentTime[proc],
603 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
605 */ /* Catches superfluous CONTINUEs -- should be unnecessary */
606 break; // now actually run the thread; DaH Qu'vam yImuHbej
609 do_the_fetchnode(event);
610 goto next_thread; /* handle next event in event queue */
613 do_the_globalblock(event);
614 goto next_thread; /* handle next event in event queue */
617 do_the_fetchreply(event);
618 goto next_thread; /* handle next event in event queue */
620 case UnblockThread: /* Move from the blocked queue to the tail of */
621 do_the_unblock(event);
622 goto next_thread; /* handle next event in event queue */
624 case ResumeThread: /* Move from the blocked queue to the tail of */
625 /* the runnable queue ( i.e. Qu' SImqa'lu') */
626 event->tso->gran.blocktime +=
627 CurrentTime[CurrentProc] - event->tso->gran.blockedat;
628 do_the_startthread(event);
629 goto next_thread; /* handle next event in event queue */
632 do_the_startthread(event);
633 goto next_thread; /* handle next event in event queue */
636 do_the_movethread(event);
637 goto next_thread; /* handle next event in event queue */
640 do_the_movespark(event);
641 goto next_thread; /* handle next event in event queue */
644 do_the_findwork(event);
645 goto next_thread; /* handle next event in event queue */
648 barf("Illegal event type %u\n", event->evttype);
651 /* This point was scheduler_loop in the old RTS */
653 IF_DEBUG(gran, belch("GRAN: after main switch"));
655 TimeOfLastEvent = CurrentTime[CurrentProc];
656 TimeOfNextEvent = get_time_of_next_event();
657 IgnoreEvents=(TimeOfNextEvent==0); // HWL HACK
658 // CurrentTSO = ThreadQueueHd;
660 IF_DEBUG(gran, belch("GRAN: time of next event is: %ld",
663 if (RtsFlags.GranFlags.Light)
664 GranSimLight_leave_system(event, &ActiveTSO);
666 EndOfTimeSlice = CurrentTime[CurrentProc]+RtsFlags.GranFlags.time_slice;
669 belch("GRAN: end of time-slice is %#lx", EndOfTimeSlice));
671 /* in a GranSim setup the TSO stays on the run queue */
673 /* Take a thread from the run queue. */
674 POP_RUN_QUEUE(t); // take_off_run_queue(t);
677 fprintf(stderr, "GRAN: About to run current thread, which is\n");
680 context_switch = 0; // turned on via GranYield, checking events and time slice
683 DumpGranEvent(GR_SCHEDULE, t));
685 procStatus[CurrentProc] = Busy;
688 if (PendingFetches != END_BF_QUEUE) {
692 /* ToDo: phps merge with spark activation above */
693 /* check whether we have local work and send requests if we have none */
694 if (EMPTY_RUN_QUEUE()) { /* no runnable threads */
695 /* :-[ no local threads => look out for local sparks */
696 /* the spark pool for the current PE */
697 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
698 if (advisory_thread_count < RtsFlags.ParFlags.maxThreads &&
699 pool->hd < pool->tl) {
701 * ToDo: add GC code check that we really have enough heap afterwards!!
703 * If we're here (no runnable threads) and we have pending
704 * sparks, we must have a space problem. Get enough space
705 * to turn one of those pending sparks into a
709 spark = findSpark(rtsFalse); /* get a spark */
710 if (spark != (rtsSpark) NULL) {
711 tso = activateSpark(spark); /* turn the spark into a thread */
712 IF_PAR_DEBUG(schedule,
713 belch("==== schedule: Created TSO %d (%p); %d threads active",
714 tso->id, tso, advisory_thread_count));
716 if (tso==END_TSO_QUEUE) { /* failed to activate spark->back to loop */
717 belch("==^^ failed to activate spark");
719 } /* otherwise fall through & pick-up new tso */
721 IF_PAR_DEBUG(verbose,
722 belch("==^^ no local sparks (spark pool contains only NFs: %d)",
723 spark_queue_len(pool)));
728 /* If we still have no work we need to send a FISH to get a spark
731 if (EMPTY_RUN_QUEUE()) {
732 /* =8-[ no local sparks => look for work on other PEs */
734 * We really have absolutely no work. Send out a fish
735 * (there may be some out there already), and wait for
736 * something to arrive. We clearly can't run any threads
737 * until a SCHEDULE or RESUME arrives, and so that's what
738 * we're hoping to see. (Of course, we still have to
739 * respond to other types of messages.)
741 TIME now = msTime() /*CURRENT_TIME*/;
742 IF_PAR_DEBUG(verbose,
743 belch("-- now=%ld", now));
744 IF_PAR_DEBUG(verbose,
745 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
746 (last_fish_arrived_at!=0 &&
747 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay > now)) {
748 belch("--$$ delaying FISH until %ld (last fish %ld, delay %ld, now %ld)",
749 last_fish_arrived_at+RtsFlags.ParFlags.fishDelay,
750 last_fish_arrived_at,
751 RtsFlags.ParFlags.fishDelay, now);
754 if (outstandingFishes < RtsFlags.ParFlags.maxFishes &&
755 (last_fish_arrived_at==0 ||
756 (last_fish_arrived_at+RtsFlags.ParFlags.fishDelay <= now))) {
757 /* outstandingFishes is set in sendFish, processFish;
758 avoid flooding system with fishes via delay */
760 sendFish(pe, mytid, NEW_FISH_AGE, NEW_FISH_HISTORY,
763 // Global statistics: count no. of fishes
764 if (RtsFlags.ParFlags.ParStats.Global &&
765 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
766 globalParStats.tot_fish_mess++;
770 receivedFinish = processMessages();
773 } else if (PacketsWaiting()) { /* Look for incoming messages */
774 receivedFinish = processMessages();
777 /* Now we are sure that we have some work available */
778 ASSERT(run_queue_hd != END_TSO_QUEUE);
780 /* Take a thread from the run queue, if we have work */
781 POP_RUN_QUEUE(t); // take_off_run_queue(END_TSO_QUEUE);
782 IF_DEBUG(sanity,checkTSO(t));
784 /* ToDo: write something to the log-file
785 if (RTSflags.ParFlags.granSimStats && !sameThread)
786 DumpGranEvent(GR_SCHEDULE, RunnableThreadsHd);
790 /* the spark pool for the current PE */
791 pool = &(MainRegTable.rSparks); // generalise to cap = &MainRegTable
794 belch("--=^ %d threads, %d sparks on [%#x]",
795 run_queue_len(), spark_queue_len(pool), CURRENT_PROC));
798 if (0 && RtsFlags.ParFlags.ParStats.Full &&
799 t && LastTSO && t->id != LastTSO->id &&
800 LastTSO->why_blocked == NotBlocked &&
801 LastTSO->what_next != ThreadComplete) {
802 // if previously scheduled TSO not blocked we have to record the context switch
803 DumpVeryRawGranEvent(TimeOfLastYield, CURRENT_PROC, CURRENT_PROC,
804 GR_DESCHEDULE, LastTSO, (StgClosure *)NULL, 0, 0);
807 if (RtsFlags.ParFlags.ParStats.Full &&
808 (emitSchedule /* forced emit */ ||
809 (t && LastTSO && t->id != LastTSO->id))) {
811 we are running a different TSO, so write a schedule event to log file
812 NB: If we use fair scheduling we also have to write a deschedule
813 event for LastTSO; with unfair scheduling we know that the
814 previous tso has blocked whenever we switch to another tso, so
815 we don't need it in GUM for now
817 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
818 GR_SCHEDULE, t, (StgClosure *)NULL, 0, 0);
819 emitSchedule = rtsFalse;
823 #else /* !GRAN && !PAR */
825 // grab a thread from the run queue
826 ASSERT(run_queue_hd != END_TSO_QUEUE);
829 // Sanity check the thread we're about to run. This can be
830 // expensive if there is lots of thread switching going on...
831 IF_DEBUG(sanity,checkTSO(t));
836 StgMainThread *m = t->main;
843 sched_belch("### Running thread %d in bound thread", t->id));
844 // yes, the Haskell thread is bound to the current native thread
849 sched_belch("### thread %d bound to another OS thread", t->id));
850 // no, bound to a different Haskell thread: pass to that thread
851 PUSH_ON_RUN_QUEUE(t);
852 passCapability(&m->bound_thread_cond);
858 if(mainThread != NULL)
859 // The thread we want to run is bound.
862 sched_belch("### this OS thread cannot run thread %d", t->id));
863 // no, the current native thread is bound to a different
864 // Haskell thread, so pass it to any worker thread
865 PUSH_ON_RUN_QUEUE(t);
866 passCapabilityToWorker();
873 cap->r.rCurrentTSO = t;
875 /* context switches are now initiated by the timer signal, unless
876 * the user specified "context switch as often as possible", with
879 if ((RtsFlags.ConcFlags.ctxtSwitchTicks == 0
880 && (run_queue_hd != END_TSO_QUEUE
881 || blocked_queue_hd != END_TSO_QUEUE
882 || sleeping_queue != END_TSO_QUEUE)))
887 RELEASE_LOCK(&sched_mutex);
889 IF_DEBUG(scheduler, sched_belch("-->> running thread %ld %s ...",
890 t->id, whatNext_strs[t->what_next]));
893 startHeapProfTimer();
896 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
897 /* Run the current thread
899 prev_what_next = t->what_next;
901 errno = t->saved_errno;
903 switch (prev_what_next) {
907 /* Thread already finished, return to scheduler. */
908 ret = ThreadFinished;
912 ret = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
915 case ThreadInterpret:
916 ret = interpretBCO(cap);
920 barf("schedule: invalid what_next field");
923 // The TSO might have moved, so find the new location:
924 t = cap->r.rCurrentTSO;
926 // And save the current errno in this thread.
927 t->saved_errno = errno;
929 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
931 /* Costs for the scheduler are assigned to CCS_SYSTEM */
937 ACQUIRE_LOCK(&sched_mutex);
939 #ifdef RTS_SUPPORTS_THREADS
940 IF_DEBUG(scheduler,fprintf(stderr,"sched (task %p): ", osThreadId()););
941 #elif !defined(GRAN) && !defined(PAR)
942 IF_DEBUG(scheduler,fprintf(stderr,"sched: "););
946 /* HACK 675: if the last thread didn't yield, make sure to print a
947 SCHEDULE event to the log file when StgRunning the next thread, even
948 if it is the same one as before */
950 TimeOfLastYield = CURRENT_TIME;
956 IF_DEBUG(gran, DumpGranEvent(GR_DESCHEDULE, t));
957 globalGranStats.tot_heapover++;
959 globalParStats.tot_heapover++;
962 // did the task ask for a large block?
963 if (cap->r.rHpAlloc > BLOCK_SIZE) {
964 // if so, get one and push it on the front of the nursery.
968 blocks = (nat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
970 IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped: requesting a large block (size %d)",
971 t->id, whatNext_strs[t->what_next], blocks));
973 // don't do this if it would push us over the
974 // alloc_blocks_lim limit; we'll GC first.
975 if (alloc_blocks + blocks < alloc_blocks_lim) {
977 alloc_blocks += blocks;
978 bd = allocGroup( blocks );
980 // link the new group into the list
981 bd->link = cap->r.rCurrentNursery;
982 bd->u.back = cap->r.rCurrentNursery->u.back;
983 if (cap->r.rCurrentNursery->u.back != NULL) {
984 cap->r.rCurrentNursery->u.back->link = bd;
986 ASSERT(g0s0->blocks == cap->r.rCurrentNursery &&
987 g0s0->blocks == cap->r.rNursery);
988 cap->r.rNursery = g0s0->blocks = bd;
990 cap->r.rCurrentNursery->u.back = bd;
992 // initialise it as a nursery block. We initialise the
993 // step, gen_no, and flags field of *every* sub-block in
994 // this large block, because this is easier than making
995 // sure that we always find the block head of a large
996 // block whenever we call Bdescr() (eg. evacuate() and
997 // isAlive() in the GC would both have to do this, at
1001 for (x = bd; x < bd + blocks; x++) {
1008 // don't forget to update the block count in g0s0.
1009 g0s0->n_blocks += blocks;
1010 // This assert can be a killer if the app is doing lots
1011 // of large block allocations.
1012 ASSERT(countBlocks(g0s0->blocks) == g0s0->n_blocks);
1014 // now update the nursery to point to the new block
1015 cap->r.rCurrentNursery = bd;
1017 // we might be unlucky and have another thread get on the
1018 // run queue before us and steal the large block, but in that
1019 // case the thread will just end up requesting another large
1021 PUSH_ON_RUN_QUEUE(t);
1026 /* make all the running tasks block on a condition variable,
1027 * maybe set context_switch and wait till they all pile in,
1028 * then have them wait on a GC condition variable.
1030 IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped: HeapOverflow",
1031 t->id, whatNext_strs[t->what_next]));
1034 ASSERT(!is_on_queue(t,CurrentProc));
1036 /* Currently we emit a DESCHEDULE event before GC in GUM.
1037 ToDo: either add separate event to distinguish SYSTEM time from rest
1038 or just nuke this DESCHEDULE (and the following SCHEDULE) */
1039 if (0 && RtsFlags.ParFlags.ParStats.Full) {
1040 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
1041 GR_DESCHEDULE, t, (StgClosure *)NULL, 0, 0);
1042 emitSchedule = rtsTrue;
1046 ready_to_gc = rtsTrue;
1047 context_switch = 1; /* stop other threads ASAP */
1048 PUSH_ON_RUN_QUEUE(t);
1049 /* actual GC is done at the end of the while loop */
1055 DumpGranEvent(GR_DESCHEDULE, t));
1056 globalGranStats.tot_stackover++;
1059 // DumpGranEvent(GR_DESCHEDULE, t);
1060 globalParStats.tot_stackover++;
1062 IF_DEBUG(scheduler,belch("--<< thread %ld (%s) stopped, StackOverflow",
1063 t->id, whatNext_strs[t->what_next]));
1064 /* just adjust the stack for this thread, then pop it back
1069 /* enlarge the stack */
1070 StgTSO *new_t = threadStackOverflow(t);
1072 /* This TSO has moved, so update any pointers to it from the
1073 * main thread stack. It better not be on any other queues...
1074 * (it shouldn't be).
1076 if (t->main != NULL) {
1077 t->main->tso = new_t;
1079 PUSH_ON_RUN_QUEUE(new_t);
1083 case ThreadYielding:
1084 // Reset the context switch flag. We don't do this just before
1085 // running the thread, because that would mean we would lose ticks
1086 // during GC, which can lead to unfair scheduling (a thread hogs
1087 // the CPU because the tick always arrives during GC). This way
1088 // penalises threads that do a lot of allocation, but that seems
1089 // better than the alternative.
1094 DumpGranEvent(GR_DESCHEDULE, t));
1095 globalGranStats.tot_yields++;
1098 // DumpGranEvent(GR_DESCHEDULE, t);
1099 globalParStats.tot_yields++;
1101 /* put the thread back on the run queue. Then, if we're ready to
1102 * GC, check whether this is the last task to stop. If so, wake
1103 * up the GC thread. getThread will block during a GC until the
1107 if (t->what_next != prev_what_next) {
1108 belch("--<< thread %ld (%s) stopped to switch evaluators",
1109 t->id, whatNext_strs[t->what_next]);
1111 belch("--<< thread %ld (%s) stopped, yielding",
1112 t->id, whatNext_strs[t->what_next]);
1117 //belch("&& Doing sanity check on yielding TSO %ld.", t->id);
1119 ASSERT(t->link == END_TSO_QUEUE);
1121 // Shortcut if we're just switching evaluators: don't bother
1122 // doing stack squeezing (which can be expensive), just run the
1124 if (t->what_next != prev_what_next) {
1131 ASSERT(!is_on_queue(t,CurrentProc));
1134 //belch("&& Doing sanity check on all ThreadQueues (and their TSOs).");
1135 checkThreadQsSanity(rtsTrue));
1139 if (RtsFlags.ParFlags.doFairScheduling) {
1140 /* this does round-robin scheduling; good for concurrency */
1141 APPEND_TO_RUN_QUEUE(t);
1143 /* this does unfair scheduling; good for parallelism */
1144 PUSH_ON_RUN_QUEUE(t);
1147 // this does round-robin scheduling; good for concurrency
1148 APPEND_TO_RUN_QUEUE(t);
1152 /* add a ContinueThread event to actually process the thread */
1153 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1155 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1157 belch("GRAN: eventq and runnableq after adding yielded thread to queue again:");
1166 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p [PE %d] with BQ: ",
1167 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)));
1168 if (t->block_info.closure!=(StgClosure*)NULL) print_bq(t->block_info.closure));
1170 // ??? needed; should emit block before
1172 DumpGranEvent(GR_DESCHEDULE, t));
1173 prune_eventq(t, (StgClosure *)NULL); // prune ContinueThreads for t
1176 ASSERT(procStatus[CurrentProc]==Busy ||
1177 ((procStatus[CurrentProc]==Fetching) &&
1178 (t->block_info.closure!=(StgClosure*)NULL)));
1179 if (run_queue_hds[CurrentProc] == END_TSO_QUEUE &&
1180 !(!RtsFlags.GranFlags.DoAsyncFetch &&
1181 procStatus[CurrentProc]==Fetching))
1182 procStatus[CurrentProc] = Idle;
1186 belch("--<< thread %ld (%p; %s) stopped, blocking on node %p with BQ: ",
1187 t->id, t, whatNext_strs[t->what_next], t->block_info.closure));
1190 if (t->block_info.closure!=(StgClosure*)NULL)
1191 print_bq(t->block_info.closure));
1193 /* Send a fetch (if BlockedOnGA) and dump event to log file */
1196 /* whatever we schedule next, we must log that schedule */
1197 emitSchedule = rtsTrue;
1200 /* don't need to do anything. Either the thread is blocked on
1201 * I/O, in which case we'll have called addToBlockedQueue
1202 * previously, or it's blocked on an MVar or Blackhole, in which
1203 * case it'll be on the relevant queue already.
1206 fprintf(stderr, "--<< thread %d (%s) stopped: ",
1207 t->id, whatNext_strs[t->what_next]);
1208 printThreadBlockage(t);
1209 fprintf(stderr, "\n"));
1212 /* Only for dumping event to log file
1213 ToDo: do I need this in GranSim, too?
1220 case ThreadFinished:
1221 /* Need to check whether this was a main thread, and if so, signal
1222 * the task that started it with the return value. If we have no
1223 * more main threads, we probably need to stop all the tasks until
1226 /* We also end up here if the thread kills itself with an
1227 * uncaught exception, see Exception.hc.
1229 IF_DEBUG(scheduler,belch("--++ thread %d (%s) finished",
1230 t->id, whatNext_strs[t->what_next]));
1232 endThread(t, CurrentProc); // clean-up the thread
1234 /* For now all are advisory -- HWL */
1235 //if(t->priority==AdvisoryPriority) ??
1236 advisory_thread_count--;
1239 if(t->dist.priority==RevalPriority)
1243 if (RtsFlags.ParFlags.ParStats.Full &&
1244 !RtsFlags.ParFlags.ParStats.Suppressed)
1245 DumpEndEvent(CURRENT_PROC, t, rtsFalse /* not mandatory */);
1249 // Check whether the thread that just completed was a main
1250 // thread, and if so return with the result.
1252 // There is an assumption here that all thread completion goes
1253 // through this point; we need to make sure that if a thread
1254 // ends up in the ThreadKilled state, that it stays on the run
1255 // queue so it can be dealt with here.
1258 #if defined(RTS_SUPPORTS_THREADS)
1261 mainThread->tso == t
1265 // We are a bound thread: this must be our thread that just
1267 ASSERT(mainThread->tso == t);
1269 if (t->what_next == ThreadComplete) {
1270 if (mainThread->ret) {
1271 // NOTE: return val is tso->sp[1] (see StgStartup.hc)
1272 *(mainThread->ret) = (StgClosure *)mainThread->tso->sp[1];
1274 mainThread->stat = Success;
1276 if (mainThread->ret) {
1277 *(mainThread->ret) = NULL;
1279 if (was_interrupted) {
1280 mainThread->stat = Interrupted;
1282 mainThread->stat = Killed;
1286 removeThreadLabel((StgWord)mainThread->tso->id);
1288 if (mainThread->prev == NULL) {
1289 main_threads = mainThread->link;
1291 mainThread->prev->link = mainThread->link;
1293 if (mainThread->link != NULL) {
1294 mainThread->link->prev = NULL;
1296 releaseCapability(cap);
1300 #ifdef RTS_SUPPORTS_THREADS
1301 ASSERT(t->main == NULL);
1303 if (t->main != NULL) {
1304 // Must be a main thread that is not the topmost one. Leave
1305 // it on the run queue until the stack has unwound to the
1306 // point where we can deal with this. Leaving it on the run
1307 // queue also ensures that the garbage collector knows about
1308 // this thread and its return value (it gets dropped from the
1309 // all_threads list so there's no other way to find it).
1310 APPEND_TO_RUN_QUEUE(t);
1316 barf("schedule: invalid thread return code %d", (int)ret);
1320 // When we have +RTS -i0 and we're heap profiling, do a census at
1321 // every GC. This lets us get repeatable runs for debugging.
1322 if (performHeapProfile ||
1323 (RtsFlags.ProfFlags.profileInterval==0 &&
1324 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1325 GarbageCollect(GetRoots, rtsTrue);
1327 performHeapProfile = rtsFalse;
1328 ready_to_gc = rtsFalse; // we already GC'd
1333 /* everybody back, start the GC.
1334 * Could do it in this thread, or signal a condition var
1335 * to do it in another thread. Either way, we need to
1336 * broadcast on gc_pending_cond afterward.
1338 #if defined(RTS_SUPPORTS_THREADS)
1339 IF_DEBUG(scheduler,sched_belch("doing GC"));
1341 GarbageCollect(GetRoots,rtsFalse);
1342 ready_to_gc = rtsFalse;
1344 /* add a ContinueThread event to continue execution of current thread */
1345 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc],
1347 t, (StgClosure*)NULL, (rtsSpark*)NULL);
1349 fprintf(stderr, "GRAN: eventq and runnableq after Garbage collection:\n");
1357 IF_GRAN_DEBUG(unused,
1358 print_eventq(EventHd));
1360 event = get_next_event();
1363 /* ToDo: wait for next message to arrive rather than busy wait */
1366 } /* end of while(1) */
1368 IF_PAR_DEBUG(verbose,
1369 belch("== Leaving schedule() after having received Finish"));
1372 /* ---------------------------------------------------------------------------
1373 * rtsSupportsBoundThreads(): is the RTS built to support bound threads?
1374 * used by Control.Concurrent for error checking.
1375 * ------------------------------------------------------------------------- */
1378 rtsSupportsBoundThreads(void)
1387 /* ---------------------------------------------------------------------------
1388 * isThreadBound(tso): check whether tso is bound to an OS thread.
1389 * ------------------------------------------------------------------------- */
1392 isThreadBound(StgTSO* tso USED_IN_THREADED_RTS)
1395 return (tso->main != NULL);
1400 /* ---------------------------------------------------------------------------
1401 * Singleton fork(). Do not copy any running threads.
1402 * ------------------------------------------------------------------------- */
1404 #ifndef mingw32_TARGET_OS
1405 #define FORKPROCESS_PRIMOP_SUPPORTED
1408 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1410 deleteThreadImmediately(StgTSO *tso);
1413 forkProcess(HsStablePtr *entry
1414 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1419 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1425 IF_DEBUG(scheduler,sched_belch("forking!"));
1426 rts_lock(); // This not only acquires sched_mutex, it also
1427 // makes sure that no other threads are running
1431 if (pid) { /* parent */
1433 /* just return the pid */
1437 } else { /* child */
1440 // delete all threads
1441 run_queue_hd = run_queue_tl = END_TSO_QUEUE;
1443 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1446 // don't allow threads to catch the ThreadKilled exception
1447 deleteThreadImmediately(t);
1450 // wipe the main thread list
1451 while((m = main_threads) != NULL) {
1452 main_threads = m->link;
1453 # ifdef THREADED_RTS
1454 closeCondition(&m->bound_thread_cond);
1459 # ifdef RTS_SUPPORTS_THREADS
1460 resetTaskManagerAfterFork(); // tell startTask() and friends that
1461 startingWorkerThread = rtsFalse; // we have no worker threads any more
1462 resetWorkerWakeupPipeAfterFork();
1465 rc = rts_evalStableIO(entry, NULL); // run the action
1466 rts_checkSchedStatus("forkProcess",rc);
1470 hs_exit(); // clean up and exit
1473 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1474 barf("forkProcess#: primop not supported, sorry!\n");
1479 /* ---------------------------------------------------------------------------
1480 * deleteAllThreads(): kill all the live threads.
1482 * This is used when we catch a user interrupt (^C), before performing
1483 * any necessary cleanups and running finalizers.
1485 * Locks: sched_mutex held.
1486 * ------------------------------------------------------------------------- */
1489 deleteAllThreads ( void )
1492 IF_DEBUG(scheduler,sched_belch("deleting all threads"));
1493 for (t = all_threads; t != END_TSO_QUEUE; t = next) {
1494 next = t->global_link;
1498 // The run queue now contains a bunch of ThreadKilled threads. We
1499 // must not throw these away: the main thread(s) will be in there
1500 // somewhere, and the main scheduler loop has to deal with it.
1501 // Also, the run queue is the only thing keeping these threads from
1502 // being GC'd, and we don't want the "main thread has been GC'd" panic.
1504 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
1505 ASSERT(sleeping_queue == END_TSO_QUEUE);
1508 /* startThread and insertThread are now in GranSim.c -- HWL */
1511 /* ---------------------------------------------------------------------------
1512 * Suspending & resuming Haskell threads.
1514 * When making a "safe" call to C (aka _ccall_GC), the task gives back
1515 * its capability before calling the C function. This allows another
1516 * task to pick up the capability and carry on running Haskell
1517 * threads. It also means that if the C call blocks, it won't lock
1520 * The Haskell thread making the C call is put to sleep for the
1521 * duration of the call, on the susepended_ccalling_threads queue. We
1522 * give out a token to the task, which it can use to resume the thread
1523 * on return from the C function.
1524 * ------------------------------------------------------------------------- */
1527 suspendThread( StgRegTable *reg )
1531 int saved_errno = errno;
1533 /* assume that *reg is a pointer to the StgRegTable part
1536 cap = (Capability *)((void *)((unsigned char*)reg - sizeof(StgFunTable)));
1538 ACQUIRE_LOCK(&sched_mutex);
1541 sched_belch("thread %d did a _ccall_gc", cap->r.rCurrentTSO->id));
1543 // XXX this might not be necessary --SDM
1544 cap->r.rCurrentTSO->what_next = ThreadRunGHC;
1546 threadPaused(cap->r.rCurrentTSO);
1547 cap->r.rCurrentTSO->link = suspended_ccalling_threads;
1548 suspended_ccalling_threads = cap->r.rCurrentTSO;
1550 if(cap->r.rCurrentTSO->blocked_exceptions == NULL) {
1551 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall;
1552 cap->r.rCurrentTSO->blocked_exceptions = END_TSO_QUEUE;
1554 cap->r.rCurrentTSO->why_blocked = BlockedOnCCall_NoUnblockExc;
1557 /* Use the thread ID as the token; it should be unique */
1558 tok = cap->r.rCurrentTSO->id;
1560 /* Hand back capability */
1561 releaseCapability(cap);
1563 #if defined(RTS_SUPPORTS_THREADS)
1564 /* Preparing to leave the RTS, so ensure there's a native thread/task
1565 waiting to take over.
1567 IF_DEBUG(scheduler, sched_belch("worker (token %d): leaving RTS", tok));
1570 /* Other threads _might_ be available for execution; signal this */
1572 RELEASE_LOCK(&sched_mutex);
1574 errno = saved_errno;
1579 resumeThread( StgInt tok )
1581 StgTSO *tso, **prev;
1583 int saved_errno = errno;
1585 #if defined(RTS_SUPPORTS_THREADS)
1586 /* Wait for permission to re-enter the RTS with the result. */
1587 ACQUIRE_LOCK(&sched_mutex);
1588 waitForReturnCapability(&sched_mutex, &cap);
1590 IF_DEBUG(scheduler, sched_belch("worker (token %d): re-entering RTS", tok));
1592 grabCapability(&cap);
1595 /* Remove the thread off of the suspended list */
1596 prev = &suspended_ccalling_threads;
1597 for (tso = suspended_ccalling_threads;
1598 tso != END_TSO_QUEUE;
1599 prev = &tso->link, tso = tso->link) {
1600 if (tso->id == (StgThreadID)tok) {
1605 if (tso == END_TSO_QUEUE) {
1606 barf("resumeThread: thread not found");
1608 tso->link = END_TSO_QUEUE;
1610 if(tso->why_blocked == BlockedOnCCall) {
1611 awakenBlockedQueueNoLock(tso->blocked_exceptions);
1612 tso->blocked_exceptions = NULL;
1615 /* Reset blocking status */
1616 tso->why_blocked = NotBlocked;
1618 cap->r.rCurrentTSO = tso;
1619 RELEASE_LOCK(&sched_mutex);
1620 errno = saved_errno;
1625 /* ---------------------------------------------------------------------------
1627 * ------------------------------------------------------------------------ */
1628 static void unblockThread(StgTSO *tso);
1630 /* ---------------------------------------------------------------------------
1631 * Comparing Thread ids.
1633 * This is used from STG land in the implementation of the
1634 * instances of Eq/Ord for ThreadIds.
1635 * ------------------------------------------------------------------------ */
1638 cmp_thread(StgPtr tso1, StgPtr tso2)
1640 StgThreadID id1 = ((StgTSO *)tso1)->id;
1641 StgThreadID id2 = ((StgTSO *)tso2)->id;
1643 if (id1 < id2) return (-1);
1644 if (id1 > id2) return 1;
1648 /* ---------------------------------------------------------------------------
1649 * Fetching the ThreadID from an StgTSO.
1651 * This is used in the implementation of Show for ThreadIds.
1652 * ------------------------------------------------------------------------ */
1654 rts_getThreadId(StgPtr tso)
1656 return ((StgTSO *)tso)->id;
1661 labelThread(StgPtr tso, char *label)
1666 /* Caveat: Once set, you can only set the thread name to "" */
1667 len = strlen(label)+1;
1668 buf = stgMallocBytes(len * sizeof(char), "Schedule.c:labelThread()");
1669 strncpy(buf,label,len);
1670 /* Update will free the old memory for us */
1671 updateThreadLabel(((StgTSO *)tso)->id,buf);
1675 /* ---------------------------------------------------------------------------
1676 Create a new thread.
1678 The new thread starts with the given stack size. Before the
1679 scheduler can run, however, this thread needs to have a closure
1680 (and possibly some arguments) pushed on its stack. See
1681 pushClosure() in Schedule.h.
1683 createGenThread() and createIOThread() (in SchedAPI.h) are
1684 convenient packaged versions of this function.
1686 currently pri (priority) is only used in a GRAN setup -- HWL
1687 ------------------------------------------------------------------------ */
1689 /* currently pri (priority) is only used in a GRAN setup -- HWL */
1691 createThread(nat size, StgInt pri)
1694 createThread(nat size)
1701 /* First check whether we should create a thread at all */
1703 /* check that no more than RtsFlags.ParFlags.maxThreads threads are created */
1704 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads) {
1706 belch("{createThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1707 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1708 return END_TSO_QUEUE;
1714 ASSERT(!RtsFlags.GranFlags.Light || CurrentProc==0);
1717 // ToDo: check whether size = stack_size - TSO_STRUCT_SIZEW
1719 /* catch ridiculously small stack sizes */
1720 if (size < MIN_STACK_WORDS + TSO_STRUCT_SIZEW) {
1721 size = MIN_STACK_WORDS + TSO_STRUCT_SIZEW;
1724 stack_size = size - TSO_STRUCT_SIZEW;
1726 tso = (StgTSO *)allocate(size);
1727 TICK_ALLOC_TSO(stack_size, 0);
1729 SET_HDR(tso, &stg_TSO_info, CCS_SYSTEM);
1731 SET_GRAN_HDR(tso, ThisPE);
1734 // Always start with the compiled code evaluator
1735 tso->what_next = ThreadRunGHC;
1737 tso->id = next_thread_id++;
1738 tso->why_blocked = NotBlocked;
1739 tso->blocked_exceptions = NULL;
1741 tso->saved_errno = 0;
1744 tso->stack_size = stack_size;
1745 tso->max_stack_size = round_to_mblocks(RtsFlags.GcFlags.maxStkSize)
1747 tso->sp = (P_)&(tso->stack) + stack_size;
1750 tso->prof.CCCS = CCS_MAIN;
1753 /* put a stop frame on the stack */
1754 tso->sp -= sizeofW(StgStopFrame);
1755 SET_HDR((StgClosure*)tso->sp,(StgInfoTable *)&stg_stop_thread_info,CCS_SYSTEM);
1756 tso->link = END_TSO_QUEUE;
1760 /* uses more flexible routine in GranSim */
1761 insertThread(tso, CurrentProc);
1763 /* In a non-GranSim setup the pushing of a TSO onto the runq is separated
1769 if (RtsFlags.GranFlags.GranSimStats.Full)
1770 DumpGranEvent(GR_START,tso);
1772 if (RtsFlags.ParFlags.ParStats.Full)
1773 DumpGranEvent(GR_STARTQ,tso);
1774 /* HACk to avoid SCHEDULE
1778 /* Link the new thread on the global thread list.
1780 tso->global_link = all_threads;
1784 tso->dist.priority = MandatoryPriority; //by default that is...
1788 tso->gran.pri = pri;
1790 tso->gran.magic = TSO_MAGIC; // debugging only
1792 tso->gran.sparkname = 0;
1793 tso->gran.startedat = CURRENT_TIME;
1794 tso->gran.exported = 0;
1795 tso->gran.basicblocks = 0;
1796 tso->gran.allocs = 0;
1797 tso->gran.exectime = 0;
1798 tso->gran.fetchtime = 0;
1799 tso->gran.fetchcount = 0;
1800 tso->gran.blocktime = 0;
1801 tso->gran.blockcount = 0;
1802 tso->gran.blockedat = 0;
1803 tso->gran.globalsparks = 0;
1804 tso->gran.localsparks = 0;
1805 if (RtsFlags.GranFlags.Light)
1806 tso->gran.clock = Now; /* local clock */
1808 tso->gran.clock = 0;
1810 IF_DEBUG(gran,printTSO(tso));
1813 tso->par.magic = TSO_MAGIC; // debugging only
1815 tso->par.sparkname = 0;
1816 tso->par.startedat = CURRENT_TIME;
1817 tso->par.exported = 0;
1818 tso->par.basicblocks = 0;
1819 tso->par.allocs = 0;
1820 tso->par.exectime = 0;
1821 tso->par.fetchtime = 0;
1822 tso->par.fetchcount = 0;
1823 tso->par.blocktime = 0;
1824 tso->par.blockcount = 0;
1825 tso->par.blockedat = 0;
1826 tso->par.globalsparks = 0;
1827 tso->par.localsparks = 0;
1831 globalGranStats.tot_threads_created++;
1832 globalGranStats.threads_created_on_PE[CurrentProc]++;
1833 globalGranStats.tot_sq_len += spark_queue_len(CurrentProc);
1834 globalGranStats.tot_sq_probes++;
1836 // collect parallel global statistics (currently done together with GC stats)
1837 if (RtsFlags.ParFlags.ParStats.Global &&
1838 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
1839 //fprintf(stderr, "Creating thread %d @ %11.2f\n", tso->id, usertime());
1840 globalParStats.tot_threads_created++;
1846 belch("==__ schedule: Created TSO %d (%p);",
1847 CurrentProc, tso, tso->id));
1849 IF_PAR_DEBUG(verbose,
1850 belch("==__ schedule: Created TSO %d (%p); %d threads active",
1851 tso->id, tso, advisory_thread_count));
1853 IF_DEBUG(scheduler,sched_belch("created thread %ld, stack size = %lx words",
1854 tso->id, tso->stack_size));
1861 all parallel thread creation calls should fall through the following routine.
1864 createSparkThread(rtsSpark spark)
1866 ASSERT(spark != (rtsSpark)NULL);
1867 if (advisory_thread_count >= RtsFlags.ParFlags.maxThreads)
1869 barf("{createSparkThread}Daq ghuH: refusing to create another thread; no more than %d threads allowed (currently %d)",
1870 RtsFlags.ParFlags.maxThreads, advisory_thread_count);
1871 return END_TSO_QUEUE;
1875 tso = createThread(RtsFlags.GcFlags.initialStkSize);
1876 if (tso==END_TSO_QUEUE)
1877 barf("createSparkThread: Cannot create TSO");
1879 tso->priority = AdvisoryPriority;
1881 pushClosure(tso,spark);
1882 PUSH_ON_RUN_QUEUE(tso);
1883 advisory_thread_count++;
1890 Turn a spark into a thread.
1891 ToDo: fix for SMP (needs to acquire SCHED_MUTEX!)
1895 activateSpark (rtsSpark spark)
1899 tso = createSparkThread(spark);
1900 if (RtsFlags.ParFlags.ParStats.Full) {
1901 //ASSERT(run_queue_hd == END_TSO_QUEUE); // I think ...
1902 IF_PAR_DEBUG(verbose,
1903 belch("==^^ activateSpark: turning spark of closure %p (%s) into a thread",
1904 (StgClosure *)spark, info_type((StgClosure *)spark)));
1906 // ToDo: fwd info on local/global spark to thread -- HWL
1907 // tso->gran.exported = spark->exported;
1908 // tso->gran.locked = !spark->global;
1909 // tso->gran.sparkname = spark->name;
1915 static SchedulerStatus waitThread_(/*out*/StgMainThread* m,
1916 Capability *initialCapability
1920 /* ---------------------------------------------------------------------------
1923 * scheduleThread puts a thread on the head of the runnable queue.
1924 * This will usually be done immediately after a thread is created.
1925 * The caller of scheduleThread must create the thread using e.g.
1926 * createThread and push an appropriate closure
1927 * on this thread's stack before the scheduler is invoked.
1928 * ------------------------------------------------------------------------ */
1930 static void scheduleThread_ (StgTSO* tso);
1933 scheduleThread_(StgTSO *tso)
1935 // Precondition: sched_mutex must be held.
1936 // The thread goes at the *end* of the run-queue, to avoid possible
1937 // starvation of any threads already on the queue.
1938 APPEND_TO_RUN_QUEUE(tso);
1943 scheduleThread(StgTSO* tso)
1945 ACQUIRE_LOCK(&sched_mutex);
1946 scheduleThread_(tso);
1947 RELEASE_LOCK(&sched_mutex);
1950 #if defined(RTS_SUPPORTS_THREADS)
1951 static Condition bound_cond_cache;
1952 static int bound_cond_cache_full = 0;
1957 scheduleWaitThread(StgTSO* tso, /*[out]*/HaskellObj* ret,
1958 Capability *initialCapability)
1960 // Precondition: sched_mutex must be held
1963 m = stgMallocBytes(sizeof(StgMainThread), "waitThread");
1968 m->link = main_threads;
1970 if (main_threads != NULL) {
1971 main_threads->prev = m;
1975 #if defined(RTS_SUPPORTS_THREADS)
1976 // Allocating a new condition for each thread is expensive, so we
1977 // cache one. This is a pretty feeble hack, but it helps speed up
1978 // consecutive call-ins quite a bit.
1979 if (bound_cond_cache_full) {
1980 m->bound_thread_cond = bound_cond_cache;
1981 bound_cond_cache_full = 0;
1983 initCondition(&m->bound_thread_cond);
1987 /* Put the thread on the main-threads list prior to scheduling the TSO.
1988 Failure to do so introduces a race condition in the MT case (as
1989 identified by Wolfgang Thaller), whereby the new task/OS thread
1990 created by scheduleThread_() would complete prior to the thread
1991 that spawned it managed to put 'itself' on the main-threads list.
1992 The upshot of it all being that the worker thread wouldn't get to
1993 signal the completion of the its work item for the main thread to
1994 see (==> it got stuck waiting.) -- sof 6/02.
1996 IF_DEBUG(scheduler, sched_belch("waiting for thread (%d)", tso->id));
1998 APPEND_TO_RUN_QUEUE(tso);
1999 // NB. Don't call THREAD_RUNNABLE() here, because the thread is
2000 // bound and only runnable by *this* OS thread, so waking up other
2001 // workers will just slow things down.
2003 return waitThread_(m, initialCapability);
2006 /* ---------------------------------------------------------------------------
2009 * Initialise the scheduler. This resets all the queues - if the
2010 * queues contained any threads, they'll be garbage collected at the
2013 * ------------------------------------------------------------------------ */
2021 for (i=0; i<=MAX_PROC; i++) {
2022 run_queue_hds[i] = END_TSO_QUEUE;
2023 run_queue_tls[i] = END_TSO_QUEUE;
2024 blocked_queue_hds[i] = END_TSO_QUEUE;
2025 blocked_queue_tls[i] = END_TSO_QUEUE;
2026 ccalling_threadss[i] = END_TSO_QUEUE;
2027 sleeping_queue = END_TSO_QUEUE;
2030 run_queue_hd = END_TSO_QUEUE;
2031 run_queue_tl = END_TSO_QUEUE;
2032 blocked_queue_hd = END_TSO_QUEUE;
2033 blocked_queue_tl = END_TSO_QUEUE;
2034 sleeping_queue = END_TSO_QUEUE;
2037 suspended_ccalling_threads = END_TSO_QUEUE;
2039 main_threads = NULL;
2040 all_threads = END_TSO_QUEUE;
2045 RtsFlags.ConcFlags.ctxtSwitchTicks =
2046 RtsFlags.ConcFlags.ctxtSwitchTime / TICK_MILLISECS;
2048 #if defined(RTS_SUPPORTS_THREADS)
2049 /* Initialise the mutex and condition variables used by
2051 initMutex(&sched_mutex);
2052 initMutex(&term_mutex);
2055 ACQUIRE_LOCK(&sched_mutex);
2057 /* A capability holds the state a native thread needs in
2058 * order to execute STG code. At least one capability is
2059 * floating around (only SMP builds have more than one).
2063 #if defined(RTS_SUPPORTS_THREADS)
2064 /* start our haskell execution tasks */
2065 startTaskManager(0,taskStart);
2068 #if /* defined(SMP) ||*/ defined(PAR)
2072 RELEASE_LOCK(&sched_mutex);
2076 exitScheduler( void )
2078 #if defined(RTS_SUPPORTS_THREADS)
2081 shutting_down_scheduler = rtsTrue;
2084 /* ----------------------------------------------------------------------------
2085 Managing the per-task allocation areas.
2087 Each capability comes with an allocation area. These are
2088 fixed-length block lists into which allocation can be done.
2090 ToDo: no support for two-space collection at the moment???
2091 ------------------------------------------------------------------------- */
2095 waitThread_(StgMainThread* m, Capability *initialCapability)
2097 SchedulerStatus stat;
2099 // Precondition: sched_mutex must be held.
2100 IF_DEBUG(scheduler, sched_belch("new main thread (%d)", m->tso->id));
2103 /* GranSim specific init */
2104 CurrentTSO = m->tso; // the TSO to run
2105 procStatus[MainProc] = Busy; // status of main PE
2106 CurrentProc = MainProc; // PE to run it on
2107 schedule(m,initialCapability);
2109 schedule(m,initialCapability);
2110 ASSERT(m->stat != NoStatus);
2115 #if defined(RTS_SUPPORTS_THREADS)
2116 // Free the condition variable, returning it to the cache if possible.
2117 if (!bound_cond_cache_full) {
2118 bound_cond_cache = m->bound_thread_cond;
2119 bound_cond_cache_full = 1;
2121 closeCondition(&m->bound_thread_cond);
2125 IF_DEBUG(scheduler, sched_belch("main thread (%d) finished", m->tso->id));
2128 // Postcondition: sched_mutex still held
2132 /* ---------------------------------------------------------------------------
2133 Where are the roots that we know about?
2135 - all the threads on the runnable queue
2136 - all the threads on the blocked queue
2137 - all the threads on the sleeping queue
2138 - all the thread currently executing a _ccall_GC
2139 - all the "main threads"
2141 ------------------------------------------------------------------------ */
2143 /* This has to be protected either by the scheduler monitor, or by the
2144 garbage collection monitor (probably the latter).
2149 GetRoots( evac_fn evac )
2154 for (i=0; i<=RtsFlags.GranFlags.proc; i++) {
2155 if ((run_queue_hds[i] != END_TSO_QUEUE) && ((run_queue_hds[i] != NULL)))
2156 evac((StgClosure **)&run_queue_hds[i]);
2157 if ((run_queue_tls[i] != END_TSO_QUEUE) && ((run_queue_tls[i] != NULL)))
2158 evac((StgClosure **)&run_queue_tls[i]);
2160 if ((blocked_queue_hds[i] != END_TSO_QUEUE) && ((blocked_queue_hds[i] != NULL)))
2161 evac((StgClosure **)&blocked_queue_hds[i]);
2162 if ((blocked_queue_tls[i] != END_TSO_QUEUE) && ((blocked_queue_tls[i] != NULL)))
2163 evac((StgClosure **)&blocked_queue_tls[i]);
2164 if ((ccalling_threadss[i] != END_TSO_QUEUE) && ((ccalling_threadss[i] != NULL)))
2165 evac((StgClosure **)&ccalling_threads[i]);
2172 if (run_queue_hd != END_TSO_QUEUE) {
2173 ASSERT(run_queue_tl != END_TSO_QUEUE);
2174 evac((StgClosure **)&run_queue_hd);
2175 evac((StgClosure **)&run_queue_tl);
2178 if (blocked_queue_hd != END_TSO_QUEUE) {
2179 ASSERT(blocked_queue_tl != END_TSO_QUEUE);
2180 evac((StgClosure **)&blocked_queue_hd);
2181 evac((StgClosure **)&blocked_queue_tl);
2184 if (sleeping_queue != END_TSO_QUEUE) {
2185 evac((StgClosure **)&sleeping_queue);
2189 if (suspended_ccalling_threads != END_TSO_QUEUE) {
2190 evac((StgClosure **)&suspended_ccalling_threads);
2193 #if defined(PAR) || defined(GRAN)
2194 markSparkQueue(evac);
2197 #if defined(RTS_USER_SIGNALS)
2198 // mark the signal handlers (signals should be already blocked)
2199 markSignalHandlers(evac);
2203 /* -----------------------------------------------------------------------------
2206 This is the interface to the garbage collector from Haskell land.
2207 We provide this so that external C code can allocate and garbage
2208 collect when called from Haskell via _ccall_GC.
2210 It might be useful to provide an interface whereby the programmer
2211 can specify more roots (ToDo).
2213 This needs to be protected by the GC condition variable above. KH.
2214 -------------------------------------------------------------------------- */
2216 static void (*extra_roots)(evac_fn);
2221 /* Obligated to hold this lock upon entry */
2222 ACQUIRE_LOCK(&sched_mutex);
2223 GarbageCollect(GetRoots,rtsFalse);
2224 RELEASE_LOCK(&sched_mutex);
2228 performMajorGC(void)
2230 ACQUIRE_LOCK(&sched_mutex);
2231 GarbageCollect(GetRoots,rtsTrue);
2232 RELEASE_LOCK(&sched_mutex);
2236 AllRoots(evac_fn evac)
2238 GetRoots(evac); // the scheduler's roots
2239 extra_roots(evac); // the user's roots
2243 performGCWithRoots(void (*get_roots)(evac_fn))
2245 ACQUIRE_LOCK(&sched_mutex);
2246 extra_roots = get_roots;
2247 GarbageCollect(AllRoots,rtsFalse);
2248 RELEASE_LOCK(&sched_mutex);
2251 /* -----------------------------------------------------------------------------
2254 If the thread has reached its maximum stack size, then raise the
2255 StackOverflow exception in the offending thread. Otherwise
2256 relocate the TSO into a larger chunk of memory and adjust its stack
2258 -------------------------------------------------------------------------- */
2261 threadStackOverflow(StgTSO *tso)
2263 nat new_stack_size, new_tso_size, stack_words;
2267 IF_DEBUG(sanity,checkTSO(tso));
2268 if (tso->stack_size >= tso->max_stack_size) {
2271 belch("@@ threadStackOverflow of TSO %d (%p): stack too large (now %ld; max is %ld)",
2272 tso->id, tso, tso->stack_size, tso->max_stack_size);
2273 /* If we're debugging, just print out the top of the stack */
2274 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2277 /* Send this thread the StackOverflow exception */
2278 raiseAsync(tso, (StgClosure *)stackOverflow_closure);
2282 /* Try to double the current stack size. If that takes us over the
2283 * maximum stack size for this thread, then use the maximum instead.
2284 * Finally round up so the TSO ends up as a whole number of blocks.
2286 new_stack_size = stg_min(tso->stack_size * 2, tso->max_stack_size);
2287 new_tso_size = (nat)BLOCK_ROUND_UP(new_stack_size * sizeof(W_) +
2288 TSO_STRUCT_SIZE)/sizeof(W_);
2289 new_tso_size = round_to_mblocks(new_tso_size); /* Be MBLOCK-friendly */
2290 new_stack_size = new_tso_size - TSO_STRUCT_SIZEW;
2292 IF_DEBUG(scheduler, fprintf(stderr,"== sched: increasing stack size from %d words to %d.\n", tso->stack_size, new_stack_size));
2294 dest = (StgTSO *)allocate(new_tso_size);
2295 TICK_ALLOC_TSO(new_stack_size,0);
2297 /* copy the TSO block and the old stack into the new area */
2298 memcpy(dest,tso,TSO_STRUCT_SIZE);
2299 stack_words = tso->stack + tso->stack_size - tso->sp;
2300 new_sp = (P_)dest + new_tso_size - stack_words;
2301 memcpy(new_sp, tso->sp, stack_words * sizeof(W_));
2303 /* relocate the stack pointers... */
2305 dest->stack_size = new_stack_size;
2307 /* Mark the old TSO as relocated. We have to check for relocated
2308 * TSOs in the garbage collector and any primops that deal with TSOs.
2310 * It's important to set the sp value to just beyond the end
2311 * of the stack, so we don't attempt to scavenge any part of the
2314 tso->what_next = ThreadRelocated;
2316 tso->sp = (P_)&(tso->stack[tso->stack_size]);
2317 tso->why_blocked = NotBlocked;
2318 dest->mut_link = NULL;
2320 IF_PAR_DEBUG(verbose,
2321 belch("@@ threadStackOverflow of TSO %d (now at %p): stack size increased to %ld",
2322 tso->id, tso, tso->stack_size);
2323 /* If we're debugging, just print out the top of the stack */
2324 printStackChunk(tso->sp, stg_min(tso->stack+tso->stack_size,
2327 IF_DEBUG(sanity,checkTSO(tso));
2329 IF_DEBUG(scheduler,printTSO(dest));
2335 /* ---------------------------------------------------------------------------
2336 Wake up a queue that was blocked on some resource.
2337 ------------------------------------------------------------------------ */
2341 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2346 unblockCount ( StgBlockingQueueElement *bqe, StgClosure *node )
2348 /* write RESUME events to log file and
2349 update blocked and fetch time (depending on type of the orig closure) */
2350 if (RtsFlags.ParFlags.ParStats.Full) {
2351 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
2352 GR_RESUMEQ, ((StgTSO *)bqe), ((StgTSO *)bqe)->block_info.closure,
2353 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
2354 if (EMPTY_RUN_QUEUE())
2355 emitSchedule = rtsTrue;
2357 switch (get_itbl(node)->type) {
2359 ((StgTSO *)bqe)->par.fetchtime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2364 ((StgTSO *)bqe)->par.blocktime += CURRENT_TIME-((StgTSO *)bqe)->par.blockedat;
2371 barf("{unblockOneLocked}Daq Qagh: unexpected closure in blocking queue");
2378 static StgBlockingQueueElement *
2379 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2382 PEs node_loc, tso_loc;
2384 node_loc = where_is(node); // should be lifted out of loop
2385 tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2386 tso_loc = where_is((StgClosure *)tso);
2387 if (IS_LOCAL_TO(PROCS(node),tso_loc)) { // TSO is local
2388 /* !fake_fetch => TSO is on CurrentProc is same as IS_LOCAL_TO */
2389 ASSERT(CurrentProc!=node_loc || tso_loc==CurrentProc);
2390 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.lunblocktime;
2391 // insertThread(tso, node_loc);
2392 new_event(tso_loc, tso_loc, CurrentTime[CurrentProc],
2394 tso, node, (rtsSpark*)NULL);
2395 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2398 } else { // TSO is remote (actually should be FMBQ)
2399 CurrentTime[CurrentProc] += RtsFlags.GranFlags.Costs.mpacktime +
2400 RtsFlags.GranFlags.Costs.gunblocktime +
2401 RtsFlags.GranFlags.Costs.latency;
2402 new_event(tso_loc, CurrentProc, CurrentTime[CurrentProc],
2404 tso, node, (rtsSpark*)NULL);
2405 tso->link = END_TSO_QUEUE; // overwrite link just to be sure
2408 /* the thread-queue-overhead is accounted for in either Resume or UnblockThread */
2410 fprintf(stderr," %s TSO %d (%p) [PE %d] (block_info.closure=%p) (next=%p) ,",
2411 (node_loc==tso_loc ? "Local" : "Global"),
2412 tso->id, tso, CurrentProc, tso->block_info.closure, tso->link));
2413 tso->block_info.closure = NULL;
2414 IF_DEBUG(scheduler,belch("-- Waking up thread %ld (%p)",
2418 static StgBlockingQueueElement *
2419 unblockOneLocked(StgBlockingQueueElement *bqe, StgClosure *node)
2421 StgBlockingQueueElement *next;
2423 switch (get_itbl(bqe)->type) {
2425 ASSERT(((StgTSO *)bqe)->why_blocked != NotBlocked);
2426 /* if it's a TSO just push it onto the run_queue */
2428 ((StgTSO *)bqe)->link = END_TSO_QUEUE; // debugging?
2429 APPEND_TO_RUN_QUEUE((StgTSO *)bqe);
2431 unblockCount(bqe, node);
2432 /* reset blocking status after dumping event */
2433 ((StgTSO *)bqe)->why_blocked = NotBlocked;
2437 /* if it's a BLOCKED_FETCH put it on the PendingFetches list */
2439 bqe->link = (StgBlockingQueueElement *)PendingFetches;
2440 PendingFetches = (StgBlockedFetch *)bqe;
2444 /* can ignore this case in a non-debugging setup;
2445 see comments on RBHSave closures above */
2447 /* check that the closure is an RBHSave closure */
2448 ASSERT(get_itbl((StgClosure *)bqe) == &stg_RBH_Save_0_info ||
2449 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_1_info ||
2450 get_itbl((StgClosure *)bqe) == &stg_RBH_Save_2_info);
2454 barf("{unblockOneLocked}Daq Qagh: Unexpected IP (%#lx; %s) in blocking queue at %#lx\n",
2455 get_itbl((StgClosure *)bqe), info_type((StgClosure *)bqe),
2459 IF_PAR_DEBUG(bq, fprintf(stderr, ", %p (%s)", bqe, info_type((StgClosure*)bqe)));
2463 #else /* !GRAN && !PAR */
2465 unblockOneLocked(StgTSO *tso)
2469 ASSERT(get_itbl(tso)->type == TSO);
2470 ASSERT(tso->why_blocked != NotBlocked);
2471 tso->why_blocked = NotBlocked;
2473 tso->link = END_TSO_QUEUE;
2474 APPEND_TO_RUN_QUEUE(tso);
2476 IF_DEBUG(scheduler,sched_belch("waking up thread %ld", tso->id));
2481 #if defined(GRAN) || defined(PAR)
2482 INLINE_ME StgBlockingQueueElement *
2483 unblockOne(StgBlockingQueueElement *bqe, StgClosure *node)
2485 ACQUIRE_LOCK(&sched_mutex);
2486 bqe = unblockOneLocked(bqe, node);
2487 RELEASE_LOCK(&sched_mutex);
2492 unblockOne(StgTSO *tso)
2494 ACQUIRE_LOCK(&sched_mutex);
2495 tso = unblockOneLocked(tso);
2496 RELEASE_LOCK(&sched_mutex);
2503 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2505 StgBlockingQueueElement *bqe;
2510 belch("##-_ AwBQ for node %p on PE %d @ %ld by TSO %d (%p): ", \
2511 node, CurrentProc, CurrentTime[CurrentProc],
2512 CurrentTSO->id, CurrentTSO));
2514 node_loc = where_is(node);
2516 ASSERT(q == END_BQ_QUEUE ||
2517 get_itbl(q)->type == TSO || // q is either a TSO or an RBHSave
2518 get_itbl(q)->type == CONSTR); // closure (type constructor)
2519 ASSERT(is_unique(node));
2521 /* FAKE FETCH: magically copy the node to the tso's proc;
2522 no Fetch necessary because in reality the node should not have been
2523 moved to the other PE in the first place
2525 if (CurrentProc!=node_loc) {
2527 belch("## node %p is on PE %d but CurrentProc is %d (TSO %d); assuming fake fetch and adjusting bitmask (old: %#x)",
2528 node, node_loc, CurrentProc, CurrentTSO->id,
2529 // CurrentTSO, where_is(CurrentTSO),
2530 node->header.gran.procs));
2531 node->header.gran.procs = (node->header.gran.procs) | PE_NUMBER(CurrentProc);
2533 belch("## new bitmask of node %p is %#x",
2534 node, node->header.gran.procs));
2535 if (RtsFlags.GranFlags.GranSimStats.Global) {
2536 globalGranStats.tot_fake_fetches++;
2541 // ToDo: check: ASSERT(CurrentProc==node_loc);
2542 while (get_itbl(bqe)->type==TSO) { // q != END_TSO_QUEUE) {
2545 bqe points to the current element in the queue
2546 next points to the next element in the queue
2548 //tso = (StgTSO *)bqe; // wastes an assignment to get the type right
2549 //tso_loc = where_is(tso);
2551 bqe = unblockOneLocked(bqe, node);
2554 /* if this is the BQ of an RBH, we have to put back the info ripped out of
2555 the closure to make room for the anchor of the BQ */
2556 if (bqe!=END_BQ_QUEUE) {
2557 ASSERT(get_itbl(node)->type == RBH && get_itbl(bqe)->type == CONSTR);
2559 ASSERT((info_ptr==&RBH_Save_0_info) ||
2560 (info_ptr==&RBH_Save_1_info) ||
2561 (info_ptr==&RBH_Save_2_info));
2563 /* cf. convertToRBH in RBH.c for writing the RBHSave closure */
2564 ((StgRBH *)node)->blocking_queue = (StgBlockingQueueElement *)((StgRBHSave *)bqe)->payload[0];
2565 ((StgRBH *)node)->mut_link = (StgMutClosure *)((StgRBHSave *)bqe)->payload[1];
2568 belch("## Filled in RBH_Save for %p (%s) at end of AwBQ",
2569 node, info_type(node)));
2572 /* statistics gathering */
2573 if (RtsFlags.GranFlags.GranSimStats.Global) {
2574 // globalGranStats.tot_bq_processing_time += bq_processing_time;
2575 globalGranStats.tot_bq_len += len; // total length of all bqs awakened
2576 // globalGranStats.tot_bq_len_local += len_local; // same for local TSOs only
2577 globalGranStats.tot_awbq++; // total no. of bqs awakened
2580 fprintf(stderr,"## BQ Stats of %p: [%d entries] %s\n",
2581 node, len, (bqe!=END_BQ_QUEUE) ? "RBH" : ""));
2585 awakenBlockedQueue(StgBlockingQueueElement *q, StgClosure *node)
2587 StgBlockingQueueElement *bqe;
2589 ACQUIRE_LOCK(&sched_mutex);
2591 IF_PAR_DEBUG(verbose,
2592 belch("##-_ AwBQ for node %p on [%x]: ",
2596 if(get_itbl(q)->type == CONSTR || q==END_BQ_QUEUE) {
2597 IF_PAR_DEBUG(verbose, belch("## ... nothing to unblock so lets just return. RFP (BUG?)"));
2602 ASSERT(q == END_BQ_QUEUE ||
2603 get_itbl(q)->type == TSO ||
2604 get_itbl(q)->type == BLOCKED_FETCH ||
2605 get_itbl(q)->type == CONSTR);
2608 while (get_itbl(bqe)->type==TSO ||
2609 get_itbl(bqe)->type==BLOCKED_FETCH) {
2610 bqe = unblockOneLocked(bqe, node);
2612 RELEASE_LOCK(&sched_mutex);
2615 #else /* !GRAN && !PAR */
2618 awakenBlockedQueueNoLock(StgTSO *tso)
2620 while (tso != END_TSO_QUEUE) {
2621 tso = unblockOneLocked(tso);
2626 awakenBlockedQueue(StgTSO *tso)
2628 ACQUIRE_LOCK(&sched_mutex);
2629 while (tso != END_TSO_QUEUE) {
2630 tso = unblockOneLocked(tso);
2632 RELEASE_LOCK(&sched_mutex);
2636 /* ---------------------------------------------------------------------------
2638 - usually called inside a signal handler so it mustn't do anything fancy.
2639 ------------------------------------------------------------------------ */
2642 interruptStgRts(void)
2646 #ifdef RTS_SUPPORTS_THREADS
2647 wakeBlockedWorkerThread();
2651 /* -----------------------------------------------------------------------------
2654 This is for use when we raise an exception in another thread, which
2656 This has nothing to do with the UnblockThread event in GranSim. -- HWL
2657 -------------------------------------------------------------------------- */
2659 #if defined(GRAN) || defined(PAR)
2661 NB: only the type of the blocking queue is different in GranSim and GUM
2662 the operations on the queue-elements are the same
2663 long live polymorphism!
2665 Locks: sched_mutex is held upon entry and exit.
2669 unblockThread(StgTSO *tso)
2671 StgBlockingQueueElement *t, **last;
2673 switch (tso->why_blocked) {
2676 return; /* not blocked */
2679 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2681 StgBlockingQueueElement *last_tso = END_BQ_QUEUE;
2682 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2684 last = (StgBlockingQueueElement **)&mvar->head;
2685 for (t = (StgBlockingQueueElement *)mvar->head;
2687 last = &t->link, last_tso = t, t = t->link) {
2688 if (t == (StgBlockingQueueElement *)tso) {
2689 *last = (StgBlockingQueueElement *)tso->link;
2690 if (mvar->tail == tso) {
2691 mvar->tail = (StgTSO *)last_tso;
2696 barf("unblockThread (MVAR): TSO not found");
2699 case BlockedOnBlackHole:
2700 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2702 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2704 last = &bq->blocking_queue;
2705 for (t = bq->blocking_queue;
2707 last = &t->link, t = t->link) {
2708 if (t == (StgBlockingQueueElement *)tso) {
2709 *last = (StgBlockingQueueElement *)tso->link;
2713 barf("unblockThread (BLACKHOLE): TSO not found");
2716 case BlockedOnException:
2718 StgTSO *target = tso->block_info.tso;
2720 ASSERT(get_itbl(target)->type == TSO);
2722 if (target->what_next == ThreadRelocated) {
2723 target = target->link;
2724 ASSERT(get_itbl(target)->type == TSO);
2727 ASSERT(target->blocked_exceptions != NULL);
2729 last = (StgBlockingQueueElement **)&target->blocked_exceptions;
2730 for (t = (StgBlockingQueueElement *)target->blocked_exceptions;
2732 last = &t->link, t = t->link) {
2733 ASSERT(get_itbl(t)->type == TSO);
2734 if (t == (StgBlockingQueueElement *)tso) {
2735 *last = (StgBlockingQueueElement *)tso->link;
2739 barf("unblockThread (Exception): TSO not found");
2743 case BlockedOnWrite:
2744 #if defined(mingw32_TARGET_OS)
2745 case BlockedOnDoProc:
2748 /* take TSO off blocked_queue */
2749 StgBlockingQueueElement *prev = NULL;
2750 for (t = (StgBlockingQueueElement *)blocked_queue_hd; t != END_BQ_QUEUE;
2751 prev = t, t = t->link) {
2752 if (t == (StgBlockingQueueElement *)tso) {
2754 blocked_queue_hd = (StgTSO *)t->link;
2755 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2756 blocked_queue_tl = END_TSO_QUEUE;
2759 prev->link = t->link;
2760 if ((StgBlockingQueueElement *)blocked_queue_tl == t) {
2761 blocked_queue_tl = (StgTSO *)prev;
2767 barf("unblockThread (I/O): TSO not found");
2770 case BlockedOnDelay:
2772 /* take TSO off sleeping_queue */
2773 StgBlockingQueueElement *prev = NULL;
2774 for (t = (StgBlockingQueueElement *)sleeping_queue; t != END_BQ_QUEUE;
2775 prev = t, t = t->link) {
2776 if (t == (StgBlockingQueueElement *)tso) {
2778 sleeping_queue = (StgTSO *)t->link;
2780 prev->link = t->link;
2785 barf("unblockThread (delay): TSO not found");
2789 barf("unblockThread");
2793 tso->link = END_TSO_QUEUE;
2794 tso->why_blocked = NotBlocked;
2795 tso->block_info.closure = NULL;
2796 PUSH_ON_RUN_QUEUE(tso);
2800 unblockThread(StgTSO *tso)
2804 /* To avoid locking unnecessarily. */
2805 if (tso->why_blocked == NotBlocked) {
2809 switch (tso->why_blocked) {
2812 ASSERT(get_itbl(tso->block_info.closure)->type == MVAR);
2814 StgTSO *last_tso = END_TSO_QUEUE;
2815 StgMVar *mvar = (StgMVar *)(tso->block_info.closure);
2818 for (t = mvar->head; t != END_TSO_QUEUE;
2819 last = &t->link, last_tso = t, t = t->link) {
2822 if (mvar->tail == tso) {
2823 mvar->tail = last_tso;
2828 barf("unblockThread (MVAR): TSO not found");
2831 case BlockedOnBlackHole:
2832 ASSERT(get_itbl(tso->block_info.closure)->type == BLACKHOLE_BQ);
2834 StgBlockingQueue *bq = (StgBlockingQueue *)(tso->block_info.closure);
2836 last = &bq->blocking_queue;
2837 for (t = bq->blocking_queue; t != END_TSO_QUEUE;
2838 last = &t->link, t = t->link) {
2844 barf("unblockThread (BLACKHOLE): TSO not found");
2847 case BlockedOnException:
2849 StgTSO *target = tso->block_info.tso;
2851 ASSERT(get_itbl(target)->type == TSO);
2853 while (target->what_next == ThreadRelocated) {
2854 target = target->link;
2855 ASSERT(get_itbl(target)->type == TSO);
2858 ASSERT(target->blocked_exceptions != NULL);
2860 last = &target->blocked_exceptions;
2861 for (t = target->blocked_exceptions; t != END_TSO_QUEUE;
2862 last = &t->link, t = t->link) {
2863 ASSERT(get_itbl(t)->type == TSO);
2869 barf("unblockThread (Exception): TSO not found");
2873 case BlockedOnWrite:
2874 #if defined(mingw32_TARGET_OS)
2875 case BlockedOnDoProc:
2878 StgTSO *prev = NULL;
2879 for (t = blocked_queue_hd; t != END_TSO_QUEUE;
2880 prev = t, t = t->link) {
2883 blocked_queue_hd = t->link;
2884 if (blocked_queue_tl == t) {
2885 blocked_queue_tl = END_TSO_QUEUE;
2888 prev->link = t->link;
2889 if (blocked_queue_tl == t) {
2890 blocked_queue_tl = prev;
2896 barf("unblockThread (I/O): TSO not found");
2899 case BlockedOnDelay:
2901 StgTSO *prev = NULL;
2902 for (t = sleeping_queue; t != END_TSO_QUEUE;
2903 prev = t, t = t->link) {
2906 sleeping_queue = t->link;
2908 prev->link = t->link;
2913 barf("unblockThread (delay): TSO not found");
2917 barf("unblockThread");
2921 tso->link = END_TSO_QUEUE;
2922 tso->why_blocked = NotBlocked;
2923 tso->block_info.closure = NULL;
2924 APPEND_TO_RUN_QUEUE(tso);
2928 /* -----------------------------------------------------------------------------
2931 * The following function implements the magic for raising an
2932 * asynchronous exception in an existing thread.
2934 * We first remove the thread from any queue on which it might be
2935 * blocked. The possible blockages are MVARs and BLACKHOLE_BQs.
2937 * We strip the stack down to the innermost CATCH_FRAME, building
2938 * thunks in the heap for all the active computations, so they can
2939 * be restarted if necessary. When we reach a CATCH_FRAME, we build
2940 * an application of the handler to the exception, and push it on
2941 * the top of the stack.
2943 * How exactly do we save all the active computations? We create an
2944 * AP_STACK for every UpdateFrame on the stack. Entering one of these
2945 * AP_STACKs pushes everything from the corresponding update frame
2946 * upwards onto the stack. (Actually, it pushes everything up to the
2947 * next update frame plus a pointer to the next AP_STACK object.
2948 * Entering the next AP_STACK object pushes more onto the stack until we
2949 * reach the last AP_STACK object - at which point the stack should look
2950 * exactly as it did when we killed the TSO and we can continue
2951 * execution by entering the closure on top of the stack.
2953 * We can also kill a thread entirely - this happens if either (a) the
2954 * exception passed to raiseAsync is NULL, or (b) there's no
2955 * CATCH_FRAME on the stack. In either case, we strip the entire
2956 * stack and replace the thread with a zombie.
2958 * Locks: sched_mutex held upon entry nor exit.
2960 * -------------------------------------------------------------------------- */
2963 deleteThread(StgTSO *tso)
2965 raiseAsync(tso,NULL);
2968 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2970 deleteThreadImmediately(StgTSO *tso)
2971 { // for forkProcess only:
2972 // delete thread without giving it a chance to catch the KillThread exception
2974 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
2978 if (tso->why_blocked != BlockedOnCCall &&
2979 tso->why_blocked != BlockedOnCCall_NoUnblockExc) {
2983 tso->what_next = ThreadKilled;
2988 raiseAsyncWithLock(StgTSO *tso, StgClosure *exception)
2990 /* When raising async exs from contexts where sched_mutex isn't held;
2991 use raiseAsyncWithLock(). */
2992 ACQUIRE_LOCK(&sched_mutex);
2993 raiseAsync(tso,exception);
2994 RELEASE_LOCK(&sched_mutex);
2998 raiseAsync(StgTSO *tso, StgClosure *exception)
3000 StgRetInfoTable *info;
3003 // Thread already dead?
3004 if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
3009 sched_belch("raising exception in thread %ld.", tso->id));
3011 // Remove it from any blocking queues
3016 // The stack freezing code assumes there's a closure pointer on
3017 // the top of the stack, so we have to arrange that this is the case...
3019 if (sp[0] == (W_)&stg_enter_info) {
3023 sp[0] = (W_)&stg_dummy_ret_closure;
3029 // 1. Let the top of the stack be the "current closure"
3031 // 2. Walk up the stack until we find either an UPDATE_FRAME or a
3034 // 3. If it's an UPDATE_FRAME, then make an AP_STACK containing the
3035 // current closure applied to the chunk of stack up to (but not
3036 // including) the update frame. This closure becomes the "current
3037 // closure". Go back to step 2.
3039 // 4. If it's a CATCH_FRAME, then leave the exception handler on
3040 // top of the stack applied to the exception.
3042 // 5. If it's a STOP_FRAME, then kill the thread.
3047 info = get_ret_itbl((StgClosure *)frame);
3049 while (info->i.type != UPDATE_FRAME
3050 && (info->i.type != CATCH_FRAME || exception == NULL)
3051 && info->i.type != STOP_FRAME) {
3052 frame += stack_frame_sizeW((StgClosure *)frame);
3053 info = get_ret_itbl((StgClosure *)frame);
3056 switch (info->i.type) {
3059 // If we find a CATCH_FRAME, and we've got an exception to raise,
3060 // then build the THUNK raise(exception), and leave it on
3061 // top of the CATCH_FRAME ready to enter.
3065 StgCatchFrame *cf = (StgCatchFrame *)frame;
3069 // we've got an exception to raise, so let's pass it to the
3070 // handler in this frame.
3072 raise = (StgClosure *)allocate(sizeofW(StgClosure)+1);
3073 TICK_ALLOC_SE_THK(1,0);
3074 SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
3075 raise->payload[0] = exception;
3077 // throw away the stack from Sp up to the CATCH_FRAME.
3081 /* Ensure that async excpetions are blocked now, so we don't get
3082 * a surprise exception before we get around to executing the
3085 if (tso->blocked_exceptions == NULL) {
3086 tso->blocked_exceptions = END_TSO_QUEUE;
3089 /* Put the newly-built THUNK on top of the stack, ready to execute
3090 * when the thread restarts.
3093 sp[-1] = (W_)&stg_enter_info;
3095 tso->what_next = ThreadRunGHC;
3096 IF_DEBUG(sanity, checkTSO(tso));
3105 // First build an AP_STACK consisting of the stack chunk above the
3106 // current update frame, with the top word on the stack as the
3109 words = frame - sp - 1;
3110 ap = (StgAP_STACK *)allocate(PAP_sizeW(words));
3113 ap->fun = (StgClosure *)sp[0];
3115 for(i=0; i < (nat)words; ++i) {
3116 ap->payload[i] = (StgClosure *)*sp++;
3119 SET_HDR(ap,&stg_AP_STACK_info,
3120 ((StgClosure *)frame)->header.prof.ccs /* ToDo */);
3121 TICK_ALLOC_UP_THK(words+1,0);
3124 fprintf(stderr, "sched: Updating ");
3125 printPtr((P_)((StgUpdateFrame *)frame)->updatee);
3126 fprintf(stderr, " with ");
3127 printObj((StgClosure *)ap);
3130 // Replace the updatee with an indirection - happily
3131 // this will also wake up any threads currently
3132 // waiting on the result.
3134 // Warning: if we're in a loop, more than one update frame on
3135 // the stack may point to the same object. Be careful not to
3136 // overwrite an IND_OLDGEN in this case, because we'll screw
3137 // up the mutable lists. To be on the safe side, don't
3138 // overwrite any kind of indirection at all. See also
3139 // threadSqueezeStack in GC.c, where we have to make a similar
3142 if (!closure_IND(((StgUpdateFrame *)frame)->updatee)) {
3143 // revert the black hole
3144 UPD_IND_NOLOCK(((StgUpdateFrame *)frame)->updatee,
3147 sp += sizeofW(StgUpdateFrame) - 1;
3148 sp[0] = (W_)ap; // push onto stack
3153 // We've stripped the entire stack, the thread is now dead.
3154 sp += sizeofW(StgStopFrame);
3155 tso->what_next = ThreadKilled;
3166 /* -----------------------------------------------------------------------------
3167 raiseExceptionHelper
3169 This function is called by the raise# primitve, just so that we can
3170 move some of the tricky bits of raising an exception from C-- into
3171 C. Who knows, it might be a useful re-useable thing here too.
3172 -------------------------------------------------------------------------- */
3175 raiseExceptionHelper (StgTSO *tso, StgClosure *exception)
3177 StgClosure *raise_closure = NULL;
3179 StgRetInfoTable *info;
3181 // This closure represents the expression 'raise# E' where E
3182 // is the exception raise. It is used to overwrite all the
3183 // thunks which are currently under evaluataion.
3187 // LDV profiling: stg_raise_info has THUNK as its closure
3188 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
3189 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
3190 // 1 does not cause any problem unless profiling is performed.
3191 // However, when LDV profiling goes on, we need to linearly scan
3192 // small object pool, where raise_closure is stored, so we should
3193 // use MIN_UPD_SIZE.
3195 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
3196 // sizeofW(StgClosure)+1);
3200 // Walk up the stack, looking for the catch frame. On the way,
3201 // we update any closures pointed to from update frames with the
3202 // raise closure that we just built.
3206 info = get_ret_itbl((StgClosure *)p);
3207 next = p + stack_frame_sizeW((StgClosure *)p);
3208 switch (info->i.type) {
3211 // Only create raise_closure if we need to.
3212 if (raise_closure == NULL) {
3214 (StgClosure *)allocate(sizeofW(StgClosure)+MIN_UPD_SIZE);
3215 SET_HDR(raise_closure, &stg_raise_info, CCCS);
3216 raise_closure->payload[0] = exception;
3218 UPD_IND(((StgUpdateFrame *)p)->updatee,raise_closure);
3237 /* -----------------------------------------------------------------------------
3238 resurrectThreads is called after garbage collection on the list of
3239 threads found to be garbage. Each of these threads will be woken
3240 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
3241 on an MVar, or NonTermination if the thread was blocked on a Black
3244 Locks: sched_mutex isn't held upon entry nor exit.
3245 -------------------------------------------------------------------------- */
3248 resurrectThreads( StgTSO *threads )
3252 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
3253 next = tso->global_link;
3254 tso->global_link = all_threads;
3256 IF_DEBUG(scheduler, sched_belch("resurrecting thread %d", tso->id));
3258 switch (tso->why_blocked) {
3260 case BlockedOnException:
3261 /* Called by GC - sched_mutex lock is currently held. */
3262 raiseAsync(tso,(StgClosure *)BlockedOnDeadMVar_closure);
3264 case BlockedOnBlackHole:
3265 raiseAsync(tso,(StgClosure *)NonTermination_closure);
3268 /* This might happen if the thread was blocked on a black hole
3269 * belonging to a thread that we've just woken up (raiseAsync
3270 * can wake up threads, remember...).
3274 barf("resurrectThreads: thread blocked in a strange way");
3279 /* -----------------------------------------------------------------------------
3280 * Blackhole detection: if we reach a deadlock, test whether any
3281 * threads are blocked on themselves. Any threads which are found to
3282 * be self-blocked get sent a NonTermination exception.
3284 * This is only done in a deadlock situation in order to avoid
3285 * performance overhead in the normal case.
3287 * Locks: sched_mutex is held upon entry and exit.
3288 * -------------------------------------------------------------------------- */
3291 detectBlackHoles( void )
3293 StgTSO *tso = all_threads;
3295 StgClosure *blocked_on;
3296 StgRetInfoTable *info;
3298 for (tso = all_threads; tso != END_TSO_QUEUE; tso = tso->global_link) {
3300 while (tso->what_next == ThreadRelocated) {
3302 ASSERT(get_itbl(tso)->type == TSO);
3305 if (tso->why_blocked != BlockedOnBlackHole) {
3308 blocked_on = tso->block_info.closure;
3310 frame = (StgClosure *)tso->sp;
3313 info = get_ret_itbl(frame);
3314 switch (info->i.type) {
3316 if (((StgUpdateFrame *)frame)->updatee == blocked_on) {
3317 /* We are blocking on one of our own computations, so
3318 * send this thread the NonTermination exception.
3321 sched_belch("thread %d is blocked on itself", tso->id));
3322 raiseAsync(tso, (StgClosure *)NonTermination_closure);
3326 frame = (StgClosure *) ((StgUpdateFrame *)frame + 1);
3332 // normal stack frames; do nothing except advance the pointer
3334 (StgPtr)frame += stack_frame_sizeW(frame);
3341 /* ----------------------------------------------------------------------------
3342 * Debugging: why is a thread blocked
3343 * [Also provides useful information when debugging threaded programs
3344 * at the Haskell source code level, so enable outside of DEBUG. --sof 7/02]
3345 ------------------------------------------------------------------------- */
3349 printThreadBlockage(StgTSO *tso)
3351 switch (tso->why_blocked) {
3353 fprintf(stderr,"is blocked on read from fd %d", tso->block_info.fd);
3355 case BlockedOnWrite:
3356 fprintf(stderr,"is blocked on write to fd %d", tso->block_info.fd);
3358 #if defined(mingw32_TARGET_OS)
3359 case BlockedOnDoProc:
3360 fprintf(stderr,"is blocked on proc (request: %d)", tso->block_info.async_result->reqID);
3363 case BlockedOnDelay:
3364 fprintf(stderr,"is blocked until %d", tso->block_info.target);
3367 fprintf(stderr,"is blocked on an MVar");
3369 case BlockedOnException:
3370 fprintf(stderr,"is blocked on delivering an exception to thread %d",
3371 tso->block_info.tso->id);
3373 case BlockedOnBlackHole:
3374 fprintf(stderr,"is blocked on a black hole");
3377 fprintf(stderr,"is not blocked");
3381 fprintf(stderr,"is blocked on global address; local FM_BQ is %p (%s)",
3382 tso->block_info.closure, info_type(tso->block_info.closure));
3384 case BlockedOnGA_NoSend:
3385 fprintf(stderr,"is blocked on global address (no send); local FM_BQ is %p (%s)",
3386 tso->block_info.closure, info_type(tso->block_info.closure));
3389 case BlockedOnCCall:
3390 fprintf(stderr,"is blocked on an external call");
3392 case BlockedOnCCall_NoUnblockExc:
3393 fprintf(stderr,"is blocked on an external call (exceptions were already blocked)");
3396 barf("printThreadBlockage: strange tso->why_blocked: %d for TSO %d (%d)",
3397 tso->why_blocked, tso->id, tso);
3403 printThreadStatus(StgTSO *tso)
3405 switch (tso->what_next) {
3407 fprintf(stderr,"has been killed");
3409 case ThreadComplete:
3410 fprintf(stderr,"has completed");
3413 printThreadBlockage(tso);
3418 printAllThreads(void)
3424 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3425 ullong_format_string(TIME_ON_PROC(CurrentProc),
3426 time_string, rtsFalse/*no commas!*/);
3428 fprintf(stderr, "all threads at [%s]:\n", time_string);
3430 char time_string[TIME_STR_LEN], node_str[NODE_STR_LEN];
3431 ullong_format_string(CURRENT_TIME,
3432 time_string, rtsFalse/*no commas!*/);
3434 fprintf(stderr,"all threads at [%s]:\n", time_string);
3436 fprintf(stderr,"all threads:\n");
3439 for (t = all_threads; t != END_TSO_QUEUE; t = t->global_link) {
3440 fprintf(stderr, "\tthread %d @ %p ", t->id, (void *)t);
3441 label = lookupThreadLabel(t->id);
3442 if (label) fprintf(stderr,"[\"%s\"] ",(char *)label);
3443 printThreadStatus(t);
3444 fprintf(stderr,"\n");
3451 Print a whole blocking queue attached to node (debugging only).
3455 print_bq (StgClosure *node)
3457 StgBlockingQueueElement *bqe;
3461 fprintf(stderr,"## BQ of closure %p (%s): ",
3462 node, info_type(node));
3464 /* should cover all closures that may have a blocking queue */
3465 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3466 get_itbl(node)->type == FETCH_ME_BQ ||
3467 get_itbl(node)->type == RBH ||
3468 get_itbl(node)->type == MVAR);
3470 ASSERT(node!=(StgClosure*)NULL); // sanity check
3472 print_bqe(((StgBlockingQueue*)node)->blocking_queue);
3476 Print a whole blocking queue starting with the element bqe.
3479 print_bqe (StgBlockingQueueElement *bqe)
3484 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3486 for (end = (bqe==END_BQ_QUEUE);
3487 !end; // iterate until bqe points to a CONSTR
3488 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE),
3489 bqe = end ? END_BQ_QUEUE : bqe->link) {
3490 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3491 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3492 /* types of closures that may appear in a blocking queue */
3493 ASSERT(get_itbl(bqe)->type == TSO ||
3494 get_itbl(bqe)->type == BLOCKED_FETCH ||
3495 get_itbl(bqe)->type == CONSTR);
3496 /* only BQs of an RBH end with an RBH_Save closure */
3497 //ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3499 switch (get_itbl(bqe)->type) {
3501 fprintf(stderr," TSO %u (%x),",
3502 ((StgTSO *)bqe)->id, ((StgTSO *)bqe));
3505 fprintf(stderr," BF (node=%p, ga=((%x, %d, %x)),",
3506 ((StgBlockedFetch *)bqe)->node,
3507 ((StgBlockedFetch *)bqe)->ga.payload.gc.gtid,
3508 ((StgBlockedFetch *)bqe)->ga.payload.gc.slot,
3509 ((StgBlockedFetch *)bqe)->ga.weight);
3512 fprintf(stderr," %s (IP %p),",
3513 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3514 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3515 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3516 "RBH_Save_?"), get_itbl(bqe));
3519 barf("Unexpected closure type %s in blocking queue", // of %p (%s)",
3520 info_type((StgClosure *)bqe)); // , node, info_type(node));
3524 fputc('\n', stderr);
3526 # elif defined(GRAN)
3528 print_bq (StgClosure *node)
3530 StgBlockingQueueElement *bqe;
3531 PEs node_loc, tso_loc;
3534 /* should cover all closures that may have a blocking queue */
3535 ASSERT(get_itbl(node)->type == BLACKHOLE_BQ ||
3536 get_itbl(node)->type == FETCH_ME_BQ ||
3537 get_itbl(node)->type == RBH);
3539 ASSERT(node!=(StgClosure*)NULL); // sanity check
3540 node_loc = where_is(node);
3542 fprintf(stderr,"## BQ of closure %p (%s) on [PE %d]: ",
3543 node, info_type(node), node_loc);
3546 NB: In a parallel setup a BQ of an RBH must end with an RBH_Save closure;
3548 for (bqe = ((StgBlockingQueue*)node)->blocking_queue, end = (bqe==END_BQ_QUEUE);
3549 !end; // iterate until bqe points to a CONSTR
3550 end = (get_itbl(bqe)->type == CONSTR) || (bqe->link==END_BQ_QUEUE), bqe = end ? END_BQ_QUEUE : bqe->link) {
3551 ASSERT(bqe != END_BQ_QUEUE); // sanity check
3552 ASSERT(bqe != (StgBlockingQueueElement *)NULL); // sanity check
3553 /* types of closures that may appear in a blocking queue */
3554 ASSERT(get_itbl(bqe)->type == TSO ||
3555 get_itbl(bqe)->type == CONSTR);
3556 /* only BQs of an RBH end with an RBH_Save closure */
3557 ASSERT(get_itbl(bqe)->type != CONSTR || get_itbl(node)->type == RBH);
3559 tso_loc = where_is((StgClosure *)bqe);
3560 switch (get_itbl(bqe)->type) {
3562 fprintf(stderr," TSO %d (%p) on [PE %d],",
3563 ((StgTSO *)bqe)->id, (StgTSO *)bqe, tso_loc);
3566 fprintf(stderr," %s (IP %p),",
3567 (get_itbl(bqe) == &stg_RBH_Save_0_info ? "RBH_Save_0" :
3568 get_itbl(bqe) == &stg_RBH_Save_1_info ? "RBH_Save_1" :
3569 get_itbl(bqe) == &stg_RBH_Save_2_info ? "RBH_Save_2" :
3570 "RBH_Save_?"), get_itbl(bqe));
3573 barf("Unexpected closure type %s in blocking queue of %p (%s)",
3574 info_type((StgClosure *)bqe), node, info_type(node));
3578 fputc('\n', stderr);
3582 Nice and easy: only TSOs on the blocking queue
3585 print_bq (StgClosure *node)
3589 ASSERT(node!=(StgClosure*)NULL); // sanity check
3590 for (tso = ((StgBlockingQueue*)node)->blocking_queue;
3591 tso != END_TSO_QUEUE;
3593 ASSERT(tso!=NULL && tso!=END_TSO_QUEUE); // sanity check
3594 ASSERT(get_itbl(tso)->type == TSO); // guess what, sanity check
3595 fprintf(stderr," TSO %d (%p),", tso->id, tso);
3597 fputc('\n', stderr);
3608 for (i=0, tso=run_queue_hd;
3609 tso != END_TSO_QUEUE;
3618 sched_belch(char *s, ...)
3622 #ifdef RTS_SUPPORTS_THREADS
3623 fprintf(stderr, "sched (task %p): ", osThreadId());
3625 fprintf(stderr, "== ");
3627 fprintf(stderr, "sched: ");
3629 vfprintf(stderr, s, ap);
3630 fprintf(stderr, "\n");