Merge branch 'master' of darcs.haskell.org:/srv/darcs//ghc
[ghc.git] / rts / Schedule.c
1 /* ---------------------------------------------------------------------------
2 *
3 * (c) The GHC Team, 1998-2006
4 *
5 * The scheduler and thread-related functionality
6 *
7 * --------------------------------------------------------------------------*/
8
9 #include "PosixSource.h"
10 #define KEEP_LOCKCLOSURE
11 #include "Rts.h"
12
13 #include "sm/Storage.h"
14 #include "RtsUtils.h"
15 #include "StgRun.h"
16 #include "Schedule.h"
17 #include "Interpreter.h"
18 #include "Printer.h"
19 #include "RtsSignals.h"
20 #include "sm/Sanity.h"
21 #include "Stats.h"
22 #include "STM.h"
23 #include "Prelude.h"
24 #include "ThreadLabels.h"
25 #include "Updates.h"
26 #include "Proftimer.h"
27 #include "ProfHeap.h"
28 #include "Weak.h"
29 #include "sm/GC.h" // waitForGcThreads, releaseGCThreads, N
30 #include "sm/GCThread.h"
31 #include "Sparks.h"
32 #include "Capability.h"
33 #include "Task.h"
34 #include "AwaitEvent.h"
35 #if defined(mingw32_HOST_OS)
36 #include "win32/IOManager.h"
37 #endif
38 #include "Trace.h"
39 #include "RaiseAsync.h"
40 #include "Threads.h"
41 #include "Timer.h"
42 #include "ThreadPaused.h"
43 #include "Messages.h"
44 #include "Stable.h"
45
46 #ifdef HAVE_SYS_TYPES_H
47 #include <sys/types.h>
48 #endif
49 #ifdef HAVE_UNISTD_H
50 #include <unistd.h>
51 #endif
52
53 #include <string.h>
54 #include <stdlib.h>
55 #include <stdarg.h>
56
57 #ifdef HAVE_ERRNO_H
58 #include <errno.h>
59 #endif
60
61 #ifdef TRACING
62 #include "eventlog/EventLog.h"
63 #endif
64 /* -----------------------------------------------------------------------------
65 * Global variables
66 * -------------------------------------------------------------------------- */
67
68 #if !defined(THREADED_RTS)
69 // Blocked/sleeping thrads
70 StgTSO *blocked_queue_hd = NULL;
71 StgTSO *blocked_queue_tl = NULL;
72 StgTSO *sleeping_queue = NULL; // perhaps replace with a hash table?
73 #endif
74
75 /* Set to true when the latest garbage collection failed to reclaim
76 * enough space, and the runtime should proceed to shut itself down in
77 * an orderly fashion (emitting profiling info etc.)
78 */
79 rtsBool heap_overflow = rtsFalse;
80
81 /* flag that tracks whether we have done any execution in this time slice.
82 * LOCK: currently none, perhaps we should lock (but needs to be
83 * updated in the fast path of the scheduler).
84 *
85 * NB. must be StgWord, we do xchg() on it.
86 */
87 volatile StgWord recent_activity = ACTIVITY_YES;
88
89 /* if this flag is set as well, give up execution
90 * LOCK: none (changes monotonically)
91 */
92 volatile StgWord sched_state = SCHED_RUNNING;
93
94 /* This is used in `TSO.h' and gcc 2.96 insists that this variable actually
95 * exists - earlier gccs apparently didn't.
96 * -= chak
97 */
98 StgTSO dummy_tso;
99
100 /*
101 * Set to TRUE when entering a shutdown state (via shutdownHaskellAndExit()) --
102 * in an MT setting, needed to signal that a worker thread shouldn't hang around
103 * in the scheduler when it is out of work.
104 */
105 rtsBool shutting_down_scheduler = rtsFalse;
106
107 /*
108 * This mutex protects most of the global scheduler data in
109 * the THREADED_RTS runtime.
110 */
111 #if defined(THREADED_RTS)
112 Mutex sched_mutex;
113 #endif
114
115 #if !defined(mingw32_HOST_OS)
116 #define FORKPROCESS_PRIMOP_SUPPORTED
117 #endif
118
119 // Local stats
120 #ifdef THREADED_RTS
121 static nat n_failed_trygrab_idles = 0, n_idle_caps = 0;
122 #endif
123
124 /* -----------------------------------------------------------------------------
125 * static function prototypes
126 * -------------------------------------------------------------------------- */
127
128 static Capability *schedule (Capability *initialCapability, Task *task);
129
130 //
131 // These functions all encapsulate parts of the scheduler loop, and are
132 // abstracted only to make the structure and control flow of the
133 // scheduler clearer.
134 //
135 static void schedulePreLoop (void);
136 static void scheduleFindWork (Capability **pcap);
137 #if defined(THREADED_RTS)
138 static void scheduleYield (Capability **pcap, Task *task);
139 #endif
140 #if defined(THREADED_RTS)
141 static nat requestSync (Capability **pcap, Task *task, nat sync_type);
142 static void acquireAllCapabilities(Capability *cap, Task *task);
143 static void releaseAllCapabilities(Capability *cap, Task *task);
144 static void startWorkerTasks (nat from USED_IF_THREADS, nat to USED_IF_THREADS);
145 #endif
146 static void scheduleStartSignalHandlers (Capability *cap);
147 static void scheduleCheckBlockedThreads (Capability *cap);
148 static void scheduleProcessInbox(Capability **cap);
149 static void scheduleDetectDeadlock (Capability **pcap, Task *task);
150 static void schedulePushWork(Capability *cap, Task *task);
151 #if defined(THREADED_RTS)
152 static void scheduleActivateSpark(Capability *cap);
153 #endif
154 static void schedulePostRunThread(Capability *cap, StgTSO *t);
155 static rtsBool scheduleHandleHeapOverflow( Capability *cap, StgTSO *t );
156 static rtsBool scheduleHandleYield( Capability *cap, StgTSO *t,
157 nat prev_what_next );
158 static void scheduleHandleThreadBlocked( StgTSO *t );
159 static rtsBool scheduleHandleThreadFinished( Capability *cap, Task *task,
160 StgTSO *t );
161 static rtsBool scheduleNeedHeapProfile(rtsBool ready_to_gc);
162 static void scheduleDoGC(Capability **pcap, Task *task, rtsBool force_major);
163
164 static void deleteThread (Capability *cap, StgTSO *tso);
165 static void deleteAllThreads (Capability *cap);
166
167 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
168 static void deleteThread_(Capability *cap, StgTSO *tso);
169 #endif
170
171 /* ---------------------------------------------------------------------------
172 Main scheduling loop.
173
174 We use round-robin scheduling, each thread returning to the
175 scheduler loop when one of these conditions is detected:
176
177 * out of heap space
178 * timer expires (thread yields)
179 * thread blocks
180 * thread ends
181 * stack overflow
182
183 GRAN version:
184 In a GranSim setup this loop iterates over the global event queue.
185 This revolves around the global event queue, which determines what
186 to do next. Therefore, it's more complicated than either the
187 concurrent or the parallel (GUM) setup.
188 This version has been entirely removed (JB 2008/08).
189
190 GUM version:
191 GUM iterates over incoming messages.
192 It starts with nothing to do (thus CurrentTSO == END_TSO_QUEUE),
193 and sends out a fish whenever it has nothing to do; in-between
194 doing the actual reductions (shared code below) it processes the
195 incoming messages and deals with delayed operations
196 (see PendingFetches).
197 This is not the ugliest code you could imagine, but it's bloody close.
198
199 (JB 2008/08) This version was formerly indicated by a PP-Flag PAR,
200 now by PP-flag PARALLEL_HASKELL. The Eden RTS (in GHC-6.x) uses it,
201 as well as future GUM versions. This file has been refurbished to
202 only contain valid code, which is however incomplete, refers to
203 invalid includes etc.
204
205 ------------------------------------------------------------------------ */
206
207 static Capability *
208 schedule (Capability *initialCapability, Task *task)
209 {
210 StgTSO *t;
211 Capability *cap;
212 StgThreadReturnCode ret;
213 nat prev_what_next;
214 rtsBool ready_to_gc;
215 #if defined(THREADED_RTS)
216 rtsBool first = rtsTrue;
217 #endif
218
219 cap = initialCapability;
220
221 // Pre-condition: this task owns initialCapability.
222 // The sched_mutex is *NOT* held
223 // NB. on return, we still hold a capability.
224
225 debugTrace (DEBUG_sched, "cap %d: schedule()", initialCapability->no);
226
227 schedulePreLoop();
228
229 // -----------------------------------------------------------
230 // Scheduler loop starts here:
231
232 while (1) {
233
234 // Check whether we have re-entered the RTS from Haskell without
235 // going via suspendThread()/resumeThread (i.e. a 'safe' foreign
236 // call).
237 if (cap->in_haskell) {
238 errorBelch("schedule: re-entered unsafely.\n"
239 " Perhaps a 'foreign import unsafe' should be 'safe'?");
240 stg_exit(EXIT_FAILURE);
241 }
242
243 // The interruption / shutdown sequence.
244 //
245 // In order to cleanly shut down the runtime, we want to:
246 // * make sure that all main threads return to their callers
247 // with the state 'Interrupted'.
248 // * clean up all OS threads assocated with the runtime
249 // * free all memory etc.
250 //
251 // So the sequence for ^C goes like this:
252 //
253 // * ^C handler sets sched_state := SCHED_INTERRUPTING and
254 // arranges for some Capability to wake up
255 //
256 // * all threads in the system are halted, and the zombies are
257 // placed on the run queue for cleaning up. We acquire all
258 // the capabilities in order to delete the threads, this is
259 // done by scheduleDoGC() for convenience (because GC already
260 // needs to acquire all the capabilities). We can't kill
261 // threads involved in foreign calls.
262 //
263 // * somebody calls shutdownHaskell(), which calls exitScheduler()
264 //
265 // * sched_state := SCHED_SHUTTING_DOWN
266 //
267 // * all workers exit when the run queue on their capability
268 // drains. All main threads will also exit when their TSO
269 // reaches the head of the run queue and they can return.
270 //
271 // * eventually all Capabilities will shut down, and the RTS can
272 // exit.
273 //
274 // * We might be left with threads blocked in foreign calls,
275 // we should really attempt to kill these somehow (TODO);
276
277 switch (sched_state) {
278 case SCHED_RUNNING:
279 break;
280 case SCHED_INTERRUPTING:
281 debugTrace(DEBUG_sched, "SCHED_INTERRUPTING");
282 /* scheduleDoGC() deletes all the threads */
283 scheduleDoGC(&cap,task,rtsFalse);
284
285 // after scheduleDoGC(), we must be shutting down. Either some
286 // other Capability did the final GC, or we did it above,
287 // either way we can fall through to the SCHED_SHUTTING_DOWN
288 // case now.
289 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
290 // fall through
291
292 case SCHED_SHUTTING_DOWN:
293 debugTrace(DEBUG_sched, "SCHED_SHUTTING_DOWN");
294 // If we are a worker, just exit. If we're a bound thread
295 // then we will exit below when we've removed our TSO from
296 // the run queue.
297 if (!isBoundTask(task) && emptyRunQueue(cap)) {
298 return cap;
299 }
300 break;
301 default:
302 barf("sched_state: %d", sched_state);
303 }
304
305 scheduleFindWork(&cap);
306
307 /* work pushing, currently relevant only for THREADED_RTS:
308 (pushes threads, wakes up idle capabilities for stealing) */
309 schedulePushWork(cap,task);
310
311 scheduleDetectDeadlock(&cap,task);
312
313 // Normally, the only way we can get here with no threads to
314 // run is if a keyboard interrupt received during
315 // scheduleCheckBlockedThreads() or scheduleDetectDeadlock().
316 // Additionally, it is not fatal for the
317 // threaded RTS to reach here with no threads to run.
318 //
319 // win32: might be here due to awaitEvent() being abandoned
320 // as a result of a console event having been delivered.
321
322 #if defined(THREADED_RTS)
323 if (first)
324 {
325 // XXX: ToDo
326 // // don't yield the first time, we want a chance to run this
327 // // thread for a bit, even if there are others banging at the
328 // // door.
329 // first = rtsFalse;
330 // ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
331 }
332
333 scheduleYield(&cap,task);
334
335 if (emptyRunQueue(cap)) continue; // look for work again
336 #endif
337
338 #if !defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
339 if ( emptyRunQueue(cap) ) {
340 ASSERT(sched_state >= SCHED_INTERRUPTING);
341 }
342 #endif
343
344 //
345 // Get a thread to run
346 //
347 t = popRunQueue(cap);
348
349 // Sanity check the thread we're about to run. This can be
350 // expensive if there is lots of thread switching going on...
351 IF_DEBUG(sanity,checkTSO(t));
352
353 #if defined(THREADED_RTS)
354 // Check whether we can run this thread in the current task.
355 // If not, we have to pass our capability to the right task.
356 {
357 InCall *bound = t->bound;
358
359 if (bound) {
360 if (bound->task == task) {
361 // yes, the Haskell thread is bound to the current native thread
362 } else {
363 debugTrace(DEBUG_sched,
364 "thread %lu bound to another OS thread",
365 (unsigned long)t->id);
366 // no, bound to a different Haskell thread: pass to that thread
367 pushOnRunQueue(cap,t);
368 continue;
369 }
370 } else {
371 // The thread we want to run is unbound.
372 if (task->incall->tso) {
373 debugTrace(DEBUG_sched,
374 "this OS thread cannot run thread %lu",
375 (unsigned long)t->id);
376 // no, the current native thread is bound to a different
377 // Haskell thread, so pass it to any worker thread
378 pushOnRunQueue(cap,t);
379 continue;
380 }
381 }
382 }
383 #endif
384
385 // If we're shutting down, and this thread has not yet been
386 // killed, kill it now. This sometimes happens when a finalizer
387 // thread is created by the final GC, or a thread previously
388 // in a foreign call returns.
389 if (sched_state >= SCHED_INTERRUPTING &&
390 !(t->what_next == ThreadComplete || t->what_next == ThreadKilled)) {
391 deleteThread(cap,t);
392 }
393
394 // If this capability is disabled, migrate the thread away rather
395 // than running it. NB. but not if the thread is bound: it is
396 // really hard for a bound thread to migrate itself. Believe me,
397 // I tried several ways and couldn't find a way to do it.
398 // Instead, when everything is stopped for GC, we migrate all the
399 // threads on the run queue then (see scheduleDoGC()).
400 //
401 // ToDo: what about TSO_LOCKED? Currently we're migrating those
402 // when the number of capabilities drops, but we never migrate
403 // them back if it rises again. Presumably we should, but after
404 // the thread has been migrated we no longer know what capability
405 // it was originally on.
406 #ifdef THREADED_RTS
407 if (cap->disabled && !t->bound) {
408 Capability *dest_cap = &capabilities[cap->no % enabled_capabilities];
409 migrateThread(cap, t, dest_cap);
410 continue;
411 }
412 #endif
413
414 /* context switches are initiated by the timer signal, unless
415 * the user specified "context switch as often as possible", with
416 * +RTS -C0
417 */
418 if (RtsFlags.ConcFlags.ctxtSwitchTicks == 0
419 && !emptyThreadQueues(cap)) {
420 cap->context_switch = 1;
421 }
422
423 run_thread:
424
425 // CurrentTSO is the thread to run. t might be different if we
426 // loop back to run_thread, so make sure to set CurrentTSO after
427 // that.
428 cap->r.rCurrentTSO = t;
429
430 startHeapProfTimer();
431
432 // ----------------------------------------------------------------------
433 // Run the current thread
434
435 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
436 ASSERT(t->cap == cap);
437 ASSERT(t->bound ? t->bound->task->cap == cap : 1);
438
439 prev_what_next = t->what_next;
440
441 errno = t->saved_errno;
442 #if mingw32_HOST_OS
443 SetLastError(t->saved_winerror);
444 #endif
445
446 // reset the interrupt flag before running Haskell code
447 cap->interrupt = 0;
448
449 cap->in_haskell = rtsTrue;
450 cap->idle = 0;
451
452 dirty_TSO(cap,t);
453 dirty_STACK(cap,t->stackobj);
454
455 #if defined(THREADED_RTS)
456 if (recent_activity == ACTIVITY_DONE_GC) {
457 // ACTIVITY_DONE_GC means we turned off the timer signal to
458 // conserve power (see #1623). Re-enable it here.
459 nat prev;
460 prev = xchg((P_)&recent_activity, ACTIVITY_YES);
461 if (prev == ACTIVITY_DONE_GC) {
462 startTimer();
463 }
464 } else if (recent_activity != ACTIVITY_INACTIVE) {
465 // If we reached ACTIVITY_INACTIVE, then don't reset it until
466 // we've done the GC. The thread running here might just be
467 // the IO manager thread that handle_tick() woke up via
468 // wakeUpRts().
469 recent_activity = ACTIVITY_YES;
470 }
471 #endif
472
473 traceEventRunThread(cap, t);
474
475 switch (prev_what_next) {
476
477 case ThreadKilled:
478 case ThreadComplete:
479 /* Thread already finished, return to scheduler. */
480 ret = ThreadFinished;
481 break;
482
483 case ThreadRunGHC:
484 {
485 StgRegTable *r;
486 r = StgRun((StgFunPtr) stg_returnToStackTop, &cap->r);
487 cap = regTableToCapability(r);
488 ret = r->rRet;
489 break;
490 }
491
492 case ThreadInterpret:
493 cap = interpretBCO(cap);
494 ret = cap->r.rRet;
495 break;
496
497 default:
498 barf("schedule: invalid what_next field");
499 }
500
501 cap->in_haskell = rtsFalse;
502
503 // The TSO might have moved, eg. if it re-entered the RTS and a GC
504 // happened. So find the new location:
505 t = cap->r.rCurrentTSO;
506
507 // And save the current errno in this thread.
508 // XXX: possibly bogus for SMP because this thread might already
509 // be running again, see code below.
510 t->saved_errno = errno;
511 #if mingw32_HOST_OS
512 // Similarly for Windows error code
513 t->saved_winerror = GetLastError();
514 #endif
515
516 if (ret == ThreadBlocked) {
517 if (t->why_blocked == BlockedOnBlackHole) {
518 StgTSO *owner = blackHoleOwner(t->block_info.bh->bh);
519 traceEventStopThread(cap, t, t->why_blocked + 6,
520 owner != NULL ? owner->id : 0);
521 } else {
522 traceEventStopThread(cap, t, t->why_blocked + 6, 0);
523 }
524 } else {
525 traceEventStopThread(cap, t, ret, 0);
526 }
527
528 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
529 ASSERT(t->cap == cap);
530
531 // ----------------------------------------------------------------------
532
533 // Costs for the scheduler are assigned to CCS_SYSTEM
534 stopHeapProfTimer();
535 #if defined(PROFILING)
536 cap->r.rCCCS = CCS_SYSTEM;
537 #endif
538
539 schedulePostRunThread(cap,t);
540
541 ready_to_gc = rtsFalse;
542
543 switch (ret) {
544 case HeapOverflow:
545 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
546 break;
547
548 case StackOverflow:
549 // just adjust the stack for this thread, then pop it back
550 // on the run queue.
551 threadStackOverflow(cap, t);
552 pushOnRunQueue(cap,t);
553 break;
554
555 case ThreadYielding:
556 if (scheduleHandleYield(cap, t, prev_what_next)) {
557 // shortcut for switching between compiler/interpreter:
558 goto run_thread;
559 }
560 break;
561
562 case ThreadBlocked:
563 scheduleHandleThreadBlocked(t);
564 break;
565
566 case ThreadFinished:
567 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
568 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
569 break;
570
571 default:
572 barf("schedule: invalid thread return code %d", (int)ret);
573 }
574
575 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
576 scheduleDoGC(&cap,task,rtsFalse);
577 }
578 } /* end of while() */
579 }
580
581 /* -----------------------------------------------------------------------------
582 * Run queue operations
583 * -------------------------------------------------------------------------- */
584
585 void
586 removeFromRunQueue (Capability *cap, StgTSO *tso)
587 {
588 if (tso->block_info.prev == END_TSO_QUEUE) {
589 ASSERT(cap->run_queue_hd == tso);
590 cap->run_queue_hd = tso->_link;
591 } else {
592 setTSOLink(cap, tso->block_info.prev, tso->_link);
593 }
594 if (tso->_link == END_TSO_QUEUE) {
595 ASSERT(cap->run_queue_tl == tso);
596 cap->run_queue_tl = tso->block_info.prev;
597 } else {
598 setTSOPrev(cap, tso->_link, tso->block_info.prev);
599 }
600 tso->_link = tso->block_info.prev = END_TSO_QUEUE;
601
602 IF_DEBUG(sanity, checkRunQueue(cap));
603 }
604
605 /* ----------------------------------------------------------------------------
606 * Setting up the scheduler loop
607 * ------------------------------------------------------------------------- */
608
609 static void
610 schedulePreLoop(void)
611 {
612 // initialisation for scheduler - what cannot go into initScheduler()
613
614 #if defined(mingw32_HOST_OS) && !defined(USE_MINIINTERPRETER)
615 win32AllocStack();
616 #endif
617 }
618
619 /* -----------------------------------------------------------------------------
620 * scheduleFindWork()
621 *
622 * Search for work to do, and handle messages from elsewhere.
623 * -------------------------------------------------------------------------- */
624
625 static void
626 scheduleFindWork (Capability **pcap)
627 {
628 scheduleStartSignalHandlers(*pcap);
629
630 scheduleProcessInbox(pcap);
631
632 scheduleCheckBlockedThreads(*pcap);
633
634 #if defined(THREADED_RTS)
635 if (emptyRunQueue(*pcap)) { scheduleActivateSpark(*pcap); }
636 #endif
637 }
638
639 #if defined(THREADED_RTS)
640 STATIC_INLINE rtsBool
641 shouldYieldCapability (Capability *cap, Task *task, rtsBool didGcLast)
642 {
643 // we need to yield this capability to someone else if..
644 // - another thread is initiating a GC, and we didn't just do a GC
645 // (see Note [GC livelock])
646 // - another Task is returning from a foreign call
647 // - the thread at the head of the run queue cannot be run
648 // by this Task (it is bound to another Task, or it is unbound
649 // and this task it bound).
650 //
651 // Note [GC livelock]
652 //
653 // If we are interrupted to do a GC, then we do not immediately do
654 // another one. This avoids a starvation situation where one
655 // Capability keeps forcing a GC and the other Capabilities make no
656 // progress at all.
657
658 return ((pending_sync && !didGcLast) ||
659 cap->returning_tasks_hd != NULL ||
660 (!emptyRunQueue(cap) && (task->incall->tso == NULL
661 ? cap->run_queue_hd->bound != NULL
662 : cap->run_queue_hd->bound != task->incall)));
663 }
664
665 // This is the single place where a Task goes to sleep. There are
666 // two reasons it might need to sleep:
667 // - there are no threads to run
668 // - we need to yield this Capability to someone else
669 // (see shouldYieldCapability())
670 //
671 // Careful: the scheduler loop is quite delicate. Make sure you run
672 // the tests in testsuite/concurrent (all ways) after modifying this,
673 // and also check the benchmarks in nofib/parallel for regressions.
674
675 static void
676 scheduleYield (Capability **pcap, Task *task)
677 {
678 Capability *cap = *pcap;
679 int didGcLast = rtsFalse;
680
681 // if we have work, and we don't need to give up the Capability, continue.
682 //
683 if (!shouldYieldCapability(cap,task,rtsFalse) &&
684 (!emptyRunQueue(cap) ||
685 !emptyInbox(cap) ||
686 sched_state >= SCHED_INTERRUPTING)) {
687 return;
688 }
689
690 // otherwise yield (sleep), and keep yielding if necessary.
691 do {
692 didGcLast = yieldCapability(&cap,task, !didGcLast);
693 }
694 while (shouldYieldCapability(cap,task,didGcLast));
695
696 // note there may still be no threads on the run queue at this
697 // point, the caller has to check.
698
699 *pcap = cap;
700 return;
701 }
702 #endif
703
704 /* -----------------------------------------------------------------------------
705 * schedulePushWork()
706 *
707 * Push work to other Capabilities if we have some.
708 * -------------------------------------------------------------------------- */
709
710 static void
711 schedulePushWork(Capability *cap USED_IF_THREADS,
712 Task *task USED_IF_THREADS)
713 {
714 /* following code not for PARALLEL_HASKELL. I kept the call general,
715 future GUM versions might use pushing in a distributed setup */
716 #if defined(THREADED_RTS)
717
718 Capability *free_caps[n_capabilities], *cap0;
719 nat i, n_free_caps;
720
721 // migration can be turned off with +RTS -qm
722 if (!RtsFlags.ParFlags.migrate) return;
723
724 // Check whether we have more threads on our run queue, or sparks
725 // in our pool, that we could hand to another Capability.
726 if (cap->run_queue_hd == END_TSO_QUEUE) {
727 if (sparkPoolSizeCap(cap) < 2) return;
728 } else {
729 if (cap->run_queue_hd->_link == END_TSO_QUEUE &&
730 sparkPoolSizeCap(cap) < 1) return;
731 }
732
733 // First grab as many free Capabilities as we can.
734 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
735 cap0 = &capabilities[i];
736 if (cap != cap0 && !cap0->disabled && tryGrabCapability(cap0,task)) {
737 if (!emptyRunQueue(cap0)
738 || cap0->returning_tasks_hd != NULL
739 || cap0->inbox != (Message*)END_TSO_QUEUE) {
740 // it already has some work, we just grabbed it at
741 // the wrong moment. Or maybe it's deadlocked!
742 releaseCapability(cap0);
743 } else {
744 free_caps[n_free_caps++] = cap0;
745 }
746 }
747 }
748
749 // we now have n_free_caps free capabilities stashed in
750 // free_caps[]. Share our run queue equally with them. This is
751 // probably the simplest thing we could do; improvements we might
752 // want to do include:
753 //
754 // - giving high priority to moving relatively new threads, on
755 // the gournds that they haven't had time to build up a
756 // working set in the cache on this CPU/Capability.
757 //
758 // - giving low priority to moving long-lived threads
759
760 if (n_free_caps > 0) {
761 StgTSO *prev, *t, *next;
762 #ifdef SPARK_PUSHING
763 rtsBool pushed_to_all;
764 #endif
765
766 debugTrace(DEBUG_sched,
767 "cap %d: %s and %d free capabilities, sharing...",
768 cap->no,
769 (!emptyRunQueue(cap) && cap->run_queue_hd->_link != END_TSO_QUEUE)?
770 "excess threads on run queue":"sparks to share (>=2)",
771 n_free_caps);
772
773 i = 0;
774 #ifdef SPARK_PUSHING
775 pushed_to_all = rtsFalse;
776 #endif
777
778 if (cap->run_queue_hd != END_TSO_QUEUE) {
779 prev = cap->run_queue_hd;
780 t = prev->_link;
781 prev->_link = END_TSO_QUEUE;
782 for (; t != END_TSO_QUEUE; t = next) {
783 next = t->_link;
784 t->_link = END_TSO_QUEUE;
785 if (t->bound == task->incall // don't move my bound thread
786 || tsoLocked(t)) { // don't move a locked thread
787 setTSOLink(cap, prev, t);
788 setTSOPrev(cap, t, prev);
789 prev = t;
790 } else if (i == n_free_caps) {
791 #ifdef SPARK_PUSHING
792 pushed_to_all = rtsTrue;
793 #endif
794 i = 0;
795 // keep one for us
796 setTSOLink(cap, prev, t);
797 setTSOPrev(cap, t, prev);
798 prev = t;
799 } else {
800 appendToRunQueue(free_caps[i],t);
801
802 traceEventMigrateThread (cap, t, free_caps[i]->no);
803
804 if (t->bound) { t->bound->task->cap = free_caps[i]; }
805 t->cap = free_caps[i];
806 i++;
807 }
808 }
809 cap->run_queue_tl = prev;
810
811 IF_DEBUG(sanity, checkRunQueue(cap));
812 }
813
814 #ifdef SPARK_PUSHING
815 /* JB I left this code in place, it would work but is not necessary */
816
817 // If there are some free capabilities that we didn't push any
818 // threads to, then try to push a spark to each one.
819 if (!pushed_to_all) {
820 StgClosure *spark;
821 // i is the next free capability to push to
822 for (; i < n_free_caps; i++) {
823 if (emptySparkPoolCap(free_caps[i])) {
824 spark = tryStealSpark(cap->sparks);
825 if (spark != NULL) {
826 /* TODO: if anyone wants to re-enable this code then
827 * they must consider the fizzledSpark(spark) case
828 * and update the per-cap spark statistics.
829 */
830 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
831
832 traceEventStealSpark(free_caps[i], t, cap->no);
833
834 newSpark(&(free_caps[i]->r), spark);
835 }
836 }
837 }
838 }
839 #endif /* SPARK_PUSHING */
840
841 // release the capabilities
842 for (i = 0; i < n_free_caps; i++) {
843 task->cap = free_caps[i];
844 releaseAndWakeupCapability(free_caps[i]);
845 }
846 }
847 task->cap = cap; // reset to point to our Capability.
848
849 #endif /* THREADED_RTS */
850
851 }
852
853 /* ----------------------------------------------------------------------------
854 * Start any pending signal handlers
855 * ------------------------------------------------------------------------- */
856
857 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
858 static void
859 scheduleStartSignalHandlers(Capability *cap)
860 {
861 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
862 // safe outside the lock
863 startSignalHandlers(cap);
864 }
865 }
866 #else
867 static void
868 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
869 {
870 }
871 #endif
872
873 /* ----------------------------------------------------------------------------
874 * Check for blocked threads that can be woken up.
875 * ------------------------------------------------------------------------- */
876
877 static void
878 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
879 {
880 #if !defined(THREADED_RTS)
881 //
882 // Check whether any waiting threads need to be woken up. If the
883 // run queue is empty, and there are no other tasks running, we
884 // can wait indefinitely for something to happen.
885 //
886 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
887 {
888 awaitEvent (emptyRunQueue(cap));
889 }
890 #endif
891 }
892
893 /* ----------------------------------------------------------------------------
894 * Detect deadlock conditions and attempt to resolve them.
895 * ------------------------------------------------------------------------- */
896
897 static void
898 scheduleDetectDeadlock (Capability **pcap, Task *task)
899 {
900 Capability *cap = *pcap;
901 /*
902 * Detect deadlock: when we have no threads to run, there are no
903 * threads blocked, waiting for I/O, or sleeping, and all the
904 * other tasks are waiting for work, we must have a deadlock of
905 * some description.
906 */
907 if ( emptyThreadQueues(cap) )
908 {
909 #if defined(THREADED_RTS)
910 /*
911 * In the threaded RTS, we only check for deadlock if there
912 * has been no activity in a complete timeslice. This means
913 * we won't eagerly start a full GC just because we don't have
914 * any threads to run currently.
915 */
916 if (recent_activity != ACTIVITY_INACTIVE) return;
917 #endif
918
919 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
920
921 // Garbage collection can release some new threads due to
922 // either (a) finalizers or (b) threads resurrected because
923 // they are unreachable and will therefore be sent an
924 // exception. Any threads thus released will be immediately
925 // runnable.
926 scheduleDoGC (pcap, task, rtsTrue/*force major GC*/);
927 cap = *pcap;
928 // when force_major == rtsTrue. scheduleDoGC sets
929 // recent_activity to ACTIVITY_DONE_GC and turns off the timer
930 // signal.
931
932 if ( !emptyRunQueue(cap) ) return;
933
934 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
935 /* If we have user-installed signal handlers, then wait
936 * for signals to arrive rather then bombing out with a
937 * deadlock.
938 */
939 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
940 debugTrace(DEBUG_sched,
941 "still deadlocked, waiting for signals...");
942
943 awaitUserSignals();
944
945 if (signals_pending()) {
946 startSignalHandlers(cap);
947 }
948
949 // either we have threads to run, or we were interrupted:
950 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
951
952 return;
953 }
954 #endif
955
956 #if !defined(THREADED_RTS)
957 /* Probably a real deadlock. Send the current main thread the
958 * Deadlock exception.
959 */
960 if (task->incall->tso) {
961 switch (task->incall->tso->why_blocked) {
962 case BlockedOnSTM:
963 case BlockedOnBlackHole:
964 case BlockedOnMsgThrowTo:
965 case BlockedOnMVar:
966 throwToSingleThreaded(cap, task->incall->tso,
967 (StgClosure *)nonTermination_closure);
968 return;
969 default:
970 barf("deadlock: main thread blocked in a strange way");
971 }
972 }
973 return;
974 #endif
975 }
976 }
977
978
979 /* ----------------------------------------------------------------------------
980 * Send pending messages (PARALLEL_HASKELL only)
981 * ------------------------------------------------------------------------- */
982
983 #if defined(PARALLEL_HASKELL)
984 static void
985 scheduleSendPendingMessages(void)
986 {
987
988 # if defined(PAR) // global Mem.Mgmt., omit for now
989 if (PendingFetches != END_BF_QUEUE) {
990 processFetches();
991 }
992 # endif
993
994 if (RtsFlags.ParFlags.BufferTime) {
995 // if we use message buffering, we must send away all message
996 // packets which have become too old...
997 sendOldBuffers();
998 }
999 }
1000 #endif
1001
1002 /* ----------------------------------------------------------------------------
1003 * Process message in the current Capability's inbox
1004 * ------------------------------------------------------------------------- */
1005
1006 static void
1007 scheduleProcessInbox (Capability **pcap USED_IF_THREADS)
1008 {
1009 #if defined(THREADED_RTS)
1010 Message *m, *next;
1011 int r;
1012 Capability *cap = *pcap;
1013
1014 while (!emptyInbox(cap)) {
1015 if (cap->r.rCurrentNursery->link == NULL ||
1016 g0->n_new_large_words >= large_alloc_lim) {
1017 scheduleDoGC(pcap, cap->running_task, rtsFalse);
1018 cap = *pcap;
1019 }
1020
1021 // don't use a blocking acquire; if the lock is held by
1022 // another thread then just carry on. This seems to avoid
1023 // getting stuck in a message ping-pong situation with other
1024 // processors. We'll check the inbox again later anyway.
1025 //
1026 // We should really use a more efficient queue data structure
1027 // here. The trickiness is that we must ensure a Capability
1028 // never goes idle if the inbox is non-empty, which is why we
1029 // use cap->lock (cap->lock is released as the last thing
1030 // before going idle; see Capability.c:releaseCapability()).
1031 r = TRY_ACQUIRE_LOCK(&cap->lock);
1032 if (r != 0) return;
1033
1034 m = cap->inbox;
1035 cap->inbox = (Message*)END_TSO_QUEUE;
1036
1037 RELEASE_LOCK(&cap->lock);
1038
1039 while (m != (Message*)END_TSO_QUEUE) {
1040 next = m->link;
1041 executeMessage(cap, m);
1042 m = next;
1043 }
1044 }
1045 #endif
1046 }
1047
1048 /* ----------------------------------------------------------------------------
1049 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
1050 * ------------------------------------------------------------------------- */
1051
1052 #if defined(THREADED_RTS)
1053 static void
1054 scheduleActivateSpark(Capability *cap)
1055 {
1056 if (anySparks() && !cap->disabled)
1057 {
1058 createSparkThread(cap);
1059 debugTrace(DEBUG_sched, "creating a spark thread");
1060 }
1061 }
1062 #endif // PARALLEL_HASKELL || THREADED_RTS
1063
1064 /* ----------------------------------------------------------------------------
1065 * After running a thread...
1066 * ------------------------------------------------------------------------- */
1067
1068 static void
1069 schedulePostRunThread (Capability *cap, StgTSO *t)
1070 {
1071 // We have to be able to catch transactions that are in an
1072 // infinite loop as a result of seeing an inconsistent view of
1073 // memory, e.g.
1074 //
1075 // atomically $ do
1076 // [a,b] <- mapM readTVar [ta,tb]
1077 // when (a == b) loop
1078 //
1079 // and a is never equal to b given a consistent view of memory.
1080 //
1081 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1082 if (!stmValidateNestOfTransactions (t -> trec)) {
1083 debugTrace(DEBUG_sched | DEBUG_stm,
1084 "trec %p found wasting its time", t);
1085
1086 // strip the stack back to the
1087 // ATOMICALLY_FRAME, aborting the (nested)
1088 // transaction, and saving the stack of any
1089 // partially-evaluated thunks on the heap.
1090 throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1091
1092 // ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1093 }
1094 }
1095
1096 /* some statistics gathering in the parallel case */
1097 }
1098
1099 /* -----------------------------------------------------------------------------
1100 * Handle a thread that returned to the scheduler with ThreadHeepOverflow
1101 * -------------------------------------------------------------------------- */
1102
1103 static rtsBool
1104 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1105 {
1106 // did the task ask for a large block?
1107 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1108 // if so, get one and push it on the front of the nursery.
1109 bdescr *bd;
1110 lnat blocks;
1111
1112 blocks = (lnat)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1113
1114 if (blocks > BLOCKS_PER_MBLOCK) {
1115 barf("allocation of %ld bytes too large (GHC should have complained at compile-time)", (long)cap->r.rHpAlloc);
1116 }
1117
1118 debugTrace(DEBUG_sched,
1119 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1120 (long)t->id, what_next_strs[t->what_next], blocks);
1121
1122 // don't do this if the nursery is (nearly) full, we'll GC first.
1123 if (cap->r.rCurrentNursery->link != NULL ||
1124 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent infinite loop
1125 // if the nursery has only one block.
1126
1127 bd = allocGroup_lock(blocks);
1128 cap->r.rNursery->n_blocks += blocks;
1129
1130 // link the new group into the list
1131 bd->link = cap->r.rCurrentNursery;
1132 bd->u.back = cap->r.rCurrentNursery->u.back;
1133 if (cap->r.rCurrentNursery->u.back != NULL) {
1134 cap->r.rCurrentNursery->u.back->link = bd;
1135 } else {
1136 cap->r.rNursery->blocks = bd;
1137 }
1138 cap->r.rCurrentNursery->u.back = bd;
1139
1140 // initialise it as a nursery block. We initialise the
1141 // step, gen_no, and flags field of *every* sub-block in
1142 // this large block, because this is easier than making
1143 // sure that we always find the block head of a large
1144 // block whenever we call Bdescr() (eg. evacuate() and
1145 // isAlive() in the GC would both have to do this, at
1146 // least).
1147 {
1148 bdescr *x;
1149 for (x = bd; x < bd + blocks; x++) {
1150 initBdescr(x,g0,g0);
1151 x->free = x->start;
1152 x->flags = 0;
1153 }
1154 }
1155
1156 // This assert can be a killer if the app is doing lots
1157 // of large block allocations.
1158 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1159
1160 // now update the nursery to point to the new block
1161 cap->r.rCurrentNursery = bd;
1162
1163 // we might be unlucky and have another thread get on the
1164 // run queue before us and steal the large block, but in that
1165 // case the thread will just end up requesting another large
1166 // block.
1167 pushOnRunQueue(cap,t);
1168 return rtsFalse; /* not actually GC'ing */
1169 }
1170 }
1171
1172 if (cap->r.rHpLim == NULL || cap->context_switch) {
1173 // Sometimes we miss a context switch, e.g. when calling
1174 // primitives in a tight loop, MAYBE_GC() doesn't check the
1175 // context switch flag, and we end up waiting for a GC.
1176 // See #1984, and concurrent/should_run/1984
1177 cap->context_switch = 0;
1178 appendToRunQueue(cap,t);
1179 } else {
1180 pushOnRunQueue(cap,t);
1181 }
1182 return rtsTrue;
1183 /* actual GC is done at the end of the while loop in schedule() */
1184 }
1185
1186 /* -----------------------------------------------------------------------------
1187 * Handle a thread that returned to the scheduler with ThreadYielding
1188 * -------------------------------------------------------------------------- */
1189
1190 static rtsBool
1191 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1192 {
1193 /* put the thread back on the run queue. Then, if we're ready to
1194 * GC, check whether this is the last task to stop. If so, wake
1195 * up the GC thread. getThread will block during a GC until the
1196 * GC is finished.
1197 */
1198
1199 ASSERT(t->_link == END_TSO_QUEUE);
1200
1201 // Shortcut if we're just switching evaluators: don't bother
1202 // doing stack squeezing (which can be expensive), just run the
1203 // thread.
1204 if (cap->context_switch == 0 && t->what_next != prev_what_next) {
1205 debugTrace(DEBUG_sched,
1206 "--<< thread %ld (%s) stopped to switch evaluators",
1207 (long)t->id, what_next_strs[t->what_next]);
1208 return rtsTrue;
1209 }
1210
1211 // Reset the context switch flag. We don't do this just before
1212 // running the thread, because that would mean we would lose ticks
1213 // during GC, which can lead to unfair scheduling (a thread hogs
1214 // the CPU because the tick always arrives during GC). This way
1215 // penalises threads that do a lot of allocation, but that seems
1216 // better than the alternative.
1217 if (cap->context_switch != 0) {
1218 cap->context_switch = 0;
1219 appendToRunQueue(cap,t);
1220 } else {
1221 pushOnRunQueue(cap,t);
1222 }
1223
1224 IF_DEBUG(sanity,
1225 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1226 checkTSO(t));
1227
1228 return rtsFalse;
1229 }
1230
1231 /* -----------------------------------------------------------------------------
1232 * Handle a thread that returned to the scheduler with ThreadBlocked
1233 * -------------------------------------------------------------------------- */
1234
1235 static void
1236 scheduleHandleThreadBlocked( StgTSO *t
1237 #if !defined(DEBUG)
1238 STG_UNUSED
1239 #endif
1240 )
1241 {
1242
1243 // We don't need to do anything. The thread is blocked, and it
1244 // has tidied up its stack and placed itself on whatever queue
1245 // it needs to be on.
1246
1247 // ASSERT(t->why_blocked != NotBlocked);
1248 // Not true: for example,
1249 // - the thread may have woken itself up already, because
1250 // threadPaused() might have raised a blocked throwTo
1251 // exception, see maybePerformBlockedException().
1252
1253 #ifdef DEBUG
1254 traceThreadStatus(DEBUG_sched, t);
1255 #endif
1256 }
1257
1258 /* -----------------------------------------------------------------------------
1259 * Handle a thread that returned to the scheduler with ThreadFinished
1260 * -------------------------------------------------------------------------- */
1261
1262 static rtsBool
1263 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1264 {
1265 /* Need to check whether this was a main thread, and if so,
1266 * return with the return value.
1267 *
1268 * We also end up here if the thread kills itself with an
1269 * uncaught exception, see Exception.cmm.
1270 */
1271
1272 // blocked exceptions can now complete, even if the thread was in
1273 // blocked mode (see #2910).
1274 awakenBlockedExceptionQueue (cap, t);
1275
1276 //
1277 // Check whether the thread that just completed was a bound
1278 // thread, and if so return with the result.
1279 //
1280 // There is an assumption here that all thread completion goes
1281 // through this point; we need to make sure that if a thread
1282 // ends up in the ThreadKilled state, that it stays on the run
1283 // queue so it can be dealt with here.
1284 //
1285
1286 if (t->bound) {
1287
1288 if (t->bound != task->incall) {
1289 #if !defined(THREADED_RTS)
1290 // Must be a bound thread that is not the topmost one. Leave
1291 // it on the run queue until the stack has unwound to the
1292 // point where we can deal with this. Leaving it on the run
1293 // queue also ensures that the garbage collector knows about
1294 // this thread and its return value (it gets dropped from the
1295 // step->threads list so there's no other way to find it).
1296 appendToRunQueue(cap,t);
1297 return rtsFalse;
1298 #else
1299 // this cannot happen in the threaded RTS, because a
1300 // bound thread can only be run by the appropriate Task.
1301 barf("finished bound thread that isn't mine");
1302 #endif
1303 }
1304
1305 ASSERT(task->incall->tso == t);
1306
1307 if (t->what_next == ThreadComplete) {
1308 if (task->incall->ret) {
1309 // NOTE: return val is stack->sp[1] (see StgStartup.hc)
1310 *(task->incall->ret) = (StgClosure *)task->incall->tso->stackobj->sp[1];
1311 }
1312 task->incall->stat = Success;
1313 } else {
1314 if (task->incall->ret) {
1315 *(task->incall->ret) = NULL;
1316 }
1317 if (sched_state >= SCHED_INTERRUPTING) {
1318 if (heap_overflow) {
1319 task->incall->stat = HeapExhausted;
1320 } else {
1321 task->incall->stat = Interrupted;
1322 }
1323 } else {
1324 task->incall->stat = Killed;
1325 }
1326 }
1327 #ifdef DEBUG
1328 removeThreadLabel((StgWord)task->incall->tso->id);
1329 #endif
1330
1331 // We no longer consider this thread and task to be bound to
1332 // each other. The TSO lives on until it is GC'd, but the
1333 // task is about to be released by the caller, and we don't
1334 // want anyone following the pointer from the TSO to the
1335 // defunct task (which might have already been
1336 // re-used). This was a real bug: the GC updated
1337 // tso->bound->tso which lead to a deadlock.
1338 t->bound = NULL;
1339 task->incall->tso = NULL;
1340
1341 return rtsTrue; // tells schedule() to return
1342 }
1343
1344 return rtsFalse;
1345 }
1346
1347 /* -----------------------------------------------------------------------------
1348 * Perform a heap census
1349 * -------------------------------------------------------------------------- */
1350
1351 static rtsBool
1352 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1353 {
1354 // When we have +RTS -i0 and we're heap profiling, do a census at
1355 // every GC. This lets us get repeatable runs for debugging.
1356 if (performHeapProfile ||
1357 (RtsFlags.ProfFlags.heapProfileInterval==0 &&
1358 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1359 return rtsTrue;
1360 } else {
1361 return rtsFalse;
1362 }
1363 }
1364
1365 /* -----------------------------------------------------------------------------
1366 * Start a synchronisation of all capabilities
1367 * -------------------------------------------------------------------------- */
1368
1369 // Returns:
1370 // 0 if we successfully got a sync
1371 // non-0 if there was another sync request in progress,
1372 // and we yielded to it. The value returned is the
1373 // type of the other sync request.
1374 //
1375 #if defined(THREADED_RTS)
1376 static nat requestSync (Capability **pcap, Task *task, nat sync_type)
1377 {
1378 nat prev_pending_sync;
1379
1380 prev_pending_sync = cas(&pending_sync, 0, sync_type);
1381
1382 if (prev_pending_sync)
1383 {
1384 do {
1385 debugTrace(DEBUG_sched, "someone else is trying to sync (%d)...",
1386 prev_pending_sync);
1387 ASSERT(*pcap);
1388 yieldCapability(pcap,task,rtsTrue);
1389 } while (pending_sync);
1390 return prev_pending_sync; // NOTE: task->cap might have changed now
1391 }
1392 else
1393 {
1394 return 0;
1395 }
1396 }
1397
1398 //
1399 // Grab all the capabilities except the one we already hold. Used
1400 // when synchronising before a single-threaded GC (SYNC_SEQ_GC), and
1401 // before a fork (SYNC_OTHER).
1402 //
1403 // Only call this after requestSync(), otherwise a deadlock might
1404 // ensue if another thread is trying to synchronise.
1405 //
1406 static void acquireAllCapabilities(Capability *cap, Task *task)
1407 {
1408 Capability *tmpcap;
1409 nat i;
1410
1411 for (i=0; i < n_capabilities; i++) {
1412 debugTrace(DEBUG_sched, "grabbing all the capabilies (%d/%d)", i, n_capabilities);
1413 tmpcap = &capabilities[i];
1414 if (tmpcap != cap) {
1415 // we better hope this task doesn't get migrated to
1416 // another Capability while we're waiting for this one.
1417 // It won't, because load balancing happens while we have
1418 // all the Capabilities, but even so it's a slightly
1419 // unsavoury invariant.
1420 task->cap = tmpcap;
1421 waitForReturnCapability(&tmpcap, task);
1422 if (tmpcap->no != i) {
1423 barf("acquireAllCapabilities: got the wrong capability");
1424 }
1425 }
1426 }
1427 task->cap = cap;
1428 }
1429
1430 static void releaseAllCapabilities(Capability *cap, Task *task)
1431 {
1432 nat i;
1433
1434 for (i = 0; i < n_capabilities; i++) {
1435 if (cap->no != i) {
1436 task->cap = &capabilities[i];
1437 releaseCapability(&capabilities[i]);
1438 }
1439 }
1440 task->cap = cap;
1441 }
1442 #endif
1443
1444 /* -----------------------------------------------------------------------------
1445 * Perform a garbage collection if necessary
1446 * -------------------------------------------------------------------------- */
1447
1448 static void
1449 scheduleDoGC (Capability **pcap, Task *task USED_IF_THREADS,
1450 rtsBool force_major)
1451 {
1452 Capability *cap = *pcap;
1453 rtsBool heap_census;
1454 #ifdef THREADED_RTS
1455 rtsBool idle_cap[n_capabilities];
1456 rtsBool gc_type;
1457 nat i, sync;
1458 StgTSO *tso;
1459 #endif
1460
1461 if (sched_state == SCHED_SHUTTING_DOWN) {
1462 // The final GC has already been done, and the system is
1463 // shutting down. We'll probably deadlock if we try to GC
1464 // now.
1465 return;
1466 }
1467
1468 #ifdef THREADED_RTS
1469 if (sched_state < SCHED_INTERRUPTING
1470 && RtsFlags.ParFlags.parGcEnabled
1471 && N >= RtsFlags.ParFlags.parGcGen
1472 && ! oldest_gen->mark)
1473 {
1474 gc_type = SYNC_GC_PAR;
1475 } else {
1476 gc_type = SYNC_GC_SEQ;
1477 }
1478
1479 // In order to GC, there must be no threads running Haskell code.
1480 // Therefore, the GC thread needs to hold *all* the capabilities,
1481 // and release them after the GC has completed.
1482 //
1483 // This seems to be the simplest way: previous attempts involved
1484 // making all the threads with capabilities give up their
1485 // capabilities and sleep except for the *last* one, which
1486 // actually did the GC. But it's quite hard to arrange for all
1487 // the other tasks to sleep and stay asleep.
1488 //
1489
1490 /* Other capabilities are prevented from running yet more Haskell
1491 threads if pending_sync is set. Tested inside
1492 yieldCapability() and releaseCapability() in Capability.c */
1493
1494 do {
1495 sync = requestSync(pcap, task, gc_type);
1496 cap = *pcap;
1497 if (sync == SYNC_GC_SEQ || sync == SYNC_GC_PAR) {
1498 // someone else had a pending sync request for a GC, so
1499 // let's assume GC has been done and we don't need to GC
1500 // again.
1501 return;
1502 }
1503 if (sched_state == SCHED_SHUTTING_DOWN) {
1504 // The scheduler might now be shutting down. We tested
1505 // this above, but it might have become true since then as
1506 // we yielded the capability in requestSync().
1507 return;
1508 }
1509 } while (sync);
1510
1511 interruptAllCapabilities();
1512
1513 // The final shutdown GC is always single-threaded, because it's
1514 // possible that some of the Capabilities have no worker threads.
1515
1516 if (gc_type == SYNC_GC_SEQ)
1517 {
1518 traceEventRequestSeqGc(cap);
1519 }
1520 else
1521 {
1522 traceEventRequestParGc(cap);
1523 debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1524 }
1525
1526 if (gc_type == SYNC_GC_SEQ)
1527 {
1528 // single-threaded GC: grab all the capabilities
1529 acquireAllCapabilities(cap,task);
1530 }
1531 else
1532 {
1533 // If we are load-balancing collections in this
1534 // generation, then we require all GC threads to participate
1535 // in the collection. Otherwise, we only require active
1536 // threads to participate, and we set gc_threads[i]->idle for
1537 // any idle capabilities. The rationale here is that waking
1538 // up an idle Capability takes much longer than just doing any
1539 // GC work on its behalf.
1540
1541 if (RtsFlags.ParFlags.parGcNoSyncWithIdle == 0
1542 || (RtsFlags.ParFlags.parGcLoadBalancingEnabled &&
1543 N >= RtsFlags.ParFlags.parGcLoadBalancingGen)) {
1544 for (i=0; i < n_capabilities; i++) {
1545 if (capabilities[i].disabled) {
1546 idle_cap[i] = tryGrabCapability(&capabilities[i], task);
1547 } else {
1548 idle_cap[i] = rtsFalse;
1549 }
1550 }
1551 } else {
1552 for (i=0; i < n_capabilities; i++) {
1553 if (capabilities[i].disabled) {
1554 idle_cap[i] = tryGrabCapability(&capabilities[i], task);
1555 } else if (i == cap->no ||
1556 capabilities[i].idle < RtsFlags.ParFlags.parGcNoSyncWithIdle) {
1557 idle_cap[i] = rtsFalse;
1558 } else {
1559 idle_cap[i] = tryGrabCapability(&capabilities[i], task);
1560 if (!idle_cap[i]) {
1561 n_failed_trygrab_idles++;
1562 } else {
1563 n_idle_caps++;
1564 }
1565 }
1566 }
1567 }
1568
1569 // We set the gc_thread[i]->idle flag if that
1570 // capability/thread is not participating in this collection.
1571 // We also keep a local record of which capabilities are idle
1572 // in idle_cap[], because scheduleDoGC() is re-entrant:
1573 // another thread might start a GC as soon as we've finished
1574 // this one, and thus the gc_thread[]->idle flags are invalid
1575 // as soon as we release any threads after GC. Getting this
1576 // wrong leads to a rare and hard to debug deadlock!
1577
1578 for (i=0; i < n_capabilities; i++) {
1579 gc_threads[i]->idle = idle_cap[i];
1580 capabilities[i].idle++;
1581 }
1582
1583 // For all capabilities participating in this GC, wait until
1584 // they have stopped mutating and are standing by for GC.
1585 waitForGcThreads(cap);
1586
1587 #if defined(THREADED_RTS)
1588 // Stable point where we can do a global check on our spark counters
1589 ASSERT(checkSparkCountInvariant());
1590 #endif
1591 }
1592
1593 #endif
1594
1595 IF_DEBUG(scheduler, printAllThreads());
1596
1597 delete_threads_and_gc:
1598 /*
1599 * We now have all the capabilities; if we're in an interrupting
1600 * state, then we should take the opportunity to delete all the
1601 * threads in the system.
1602 */
1603 if (sched_state == SCHED_INTERRUPTING) {
1604 deleteAllThreads(cap);
1605 #if defined(THREADED_RTS)
1606 // Discard all the sparks from every Capability. Why?
1607 // They'll probably be GC'd anyway since we've killed all the
1608 // threads. It just avoids the GC having to do any work to
1609 // figure out that any remaining sparks are garbage.
1610 for (i = 0; i < n_capabilities; i++) {
1611 capabilities[i].spark_stats.gcd +=
1612 sparkPoolSize(capabilities[i].sparks);
1613 // No race here since all Caps are stopped.
1614 discardSparksCap(&capabilities[i]);
1615 }
1616 #endif
1617 sched_state = SCHED_SHUTTING_DOWN;
1618 }
1619
1620 /*
1621 * When there are disabled capabilities, we want to migrate any
1622 * threads away from them. Normally this happens in the
1623 * scheduler's loop, but only for unbound threads - it's really
1624 * hard for a bound thread to migrate itself. So we have another
1625 * go here.
1626 */
1627 #if defined(THREADED_RTS)
1628 for (i = enabled_capabilities; i < n_capabilities; i++) {
1629 Capability *tmp_cap, *dest_cap;
1630 tmp_cap = &capabilities[i];
1631 ASSERT(tmp_cap->disabled);
1632 if (i != cap->no) {
1633 dest_cap = &capabilities[i % enabled_capabilities];
1634 while (!emptyRunQueue(tmp_cap)) {
1635 tso = popRunQueue(tmp_cap);
1636 migrateThread(tmp_cap, tso, dest_cap);
1637 if (tso->bound) {
1638 traceTaskMigrate(tso->bound->task,
1639 tso->bound->task->cap,
1640 dest_cap);
1641 tso->bound->task->cap = dest_cap;
1642 }
1643 }
1644 }
1645 }
1646 #endif
1647
1648 heap_census = scheduleNeedHeapProfile(rtsTrue);
1649
1650 #if defined(THREADED_RTS)
1651 // reset pending_sync *before* GC, so that when the GC threads
1652 // emerge they don't immediately re-enter the GC.
1653 pending_sync = 0;
1654 GarbageCollect(force_major || heap_census, heap_census, gc_type, cap);
1655 #else
1656 GarbageCollect(force_major || heap_census, heap_census, 0, cap);
1657 #endif
1658
1659 traceSparkCounters(cap);
1660
1661 switch (recent_activity) {
1662 case ACTIVITY_INACTIVE:
1663 if (force_major) {
1664 // We are doing a GC because the system has been idle for a
1665 // timeslice and we need to check for deadlock. Record the
1666 // fact that we've done a GC and turn off the timer signal;
1667 // it will get re-enabled if we run any threads after the GC.
1668 recent_activity = ACTIVITY_DONE_GC;
1669 stopTimer();
1670 break;
1671 }
1672 // fall through...
1673
1674 case ACTIVITY_MAYBE_NO:
1675 // the GC might have taken long enough for the timer to set
1676 // recent_activity = ACTIVITY_MAYBE_NO or ACTIVITY_INACTIVE,
1677 // but we aren't necessarily deadlocked:
1678 recent_activity = ACTIVITY_YES;
1679 break;
1680
1681 case ACTIVITY_DONE_GC:
1682 // If we are actually active, the scheduler will reset the
1683 // recent_activity flag and re-enable the timer.
1684 break;
1685 }
1686
1687 #if defined(THREADED_RTS)
1688 // Stable point where we can do a global check on our spark counters
1689 ASSERT(checkSparkCountInvariant());
1690 #endif
1691
1692 // The heap census itself is done during GarbageCollect().
1693 if (heap_census) {
1694 performHeapProfile = rtsFalse;
1695 }
1696
1697 #if defined(THREADED_RTS)
1698 if (gc_type == SYNC_GC_PAR)
1699 {
1700 releaseGCThreads(cap);
1701 for (i = 0; i < n_capabilities; i++) {
1702 if (i != cap->no) {
1703 if (idle_cap[i]) {
1704 ASSERT(capabilities[i].running_task == task);
1705 task->cap = &capabilities[i];
1706 releaseCapability(&capabilities[i]);
1707 } else {
1708 ASSERT(capabilities[i].running_task != task);
1709 }
1710 }
1711 }
1712 task->cap = cap;
1713 }
1714 #endif
1715
1716 if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1717 // GC set the heap_overflow flag, so we should proceed with
1718 // an orderly shutdown now. Ultimately we want the main
1719 // thread to return to its caller with HeapExhausted, at which
1720 // point the caller should call hs_exit(). The first step is
1721 // to delete all the threads.
1722 //
1723 // Another way to do this would be to raise an exception in
1724 // the main thread, which we really should do because it gives
1725 // the program a chance to clean up. But how do we find the
1726 // main thread? It should presumably be the same one that
1727 // gets ^C exceptions, but that's all done on the Haskell side
1728 // (GHC.TopHandler).
1729 sched_state = SCHED_INTERRUPTING;
1730 goto delete_threads_and_gc;
1731 }
1732
1733 #ifdef SPARKBALANCE
1734 /* JB
1735 Once we are all together... this would be the place to balance all
1736 spark pools. No concurrent stealing or adding of new sparks can
1737 occur. Should be defined in Sparks.c. */
1738 balanceSparkPoolsCaps(n_capabilities, capabilities);
1739 #endif
1740
1741 #if defined(THREADED_RTS)
1742 if (gc_type == SYNC_GC_SEQ) {
1743 // release our stash of capabilities.
1744 releaseAllCapabilities(cap, task);
1745 }
1746 #endif
1747
1748 return;
1749 }
1750
1751 /* ---------------------------------------------------------------------------
1752 * Singleton fork(). Do not copy any running threads.
1753 * ------------------------------------------------------------------------- */
1754
1755 pid_t
1756 forkProcess(HsStablePtr *entry
1757 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1758 STG_UNUSED
1759 #endif
1760 )
1761 {
1762 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1763 pid_t pid;
1764 StgTSO* t,*next;
1765 Capability *cap;
1766 nat g;
1767 Task *task = NULL;
1768 nat i;
1769 #ifdef THREADED_RTS
1770 nat sync;
1771 #endif
1772
1773 debugTrace(DEBUG_sched, "forking!");
1774
1775 task = newBoundTask();
1776
1777 cap = NULL;
1778 waitForReturnCapability(&cap, task);
1779
1780 #ifdef THREADED_RTS
1781 do {
1782 sync = requestSync(&cap, task, SYNC_OTHER);
1783 } while (sync);
1784
1785 acquireAllCapabilities(cap,task);
1786
1787 pending_sync = 0;
1788 #endif
1789
1790 // no funny business: hold locks while we fork, otherwise if some
1791 // other thread is holding a lock when the fork happens, the data
1792 // structure protected by the lock will forever be in an
1793 // inconsistent state in the child. See also #1391.
1794 ACQUIRE_LOCK(&sched_mutex);
1795 ACQUIRE_LOCK(&sm_mutex);
1796 ACQUIRE_LOCK(&stable_mutex);
1797 ACQUIRE_LOCK(&task->lock);
1798
1799 for (i=0; i < n_capabilities; i++) {
1800 ACQUIRE_LOCK(&capabilities[i].lock);
1801 }
1802
1803 stopTimer(); // See #4074
1804
1805 #if defined(TRACING)
1806 flushEventLog(); // so that child won't inherit dirty file buffers
1807 #endif
1808
1809 pid = fork();
1810
1811 if (pid) { // parent
1812
1813 startTimer(); // #4074
1814
1815 RELEASE_LOCK(&sched_mutex);
1816 RELEASE_LOCK(&sm_mutex);
1817 RELEASE_LOCK(&stable_mutex);
1818 RELEASE_LOCK(&task->lock);
1819
1820 for (i=0; i < n_capabilities; i++) {
1821 releaseCapability_(&capabilities[i],rtsFalse);
1822 RELEASE_LOCK(&capabilities[i].lock);
1823 }
1824 boundTaskExiting(task);
1825
1826 // just return the pid
1827 return pid;
1828
1829 } else { // child
1830
1831 #if defined(THREADED_RTS)
1832 initMutex(&sched_mutex);
1833 initMutex(&sm_mutex);
1834 initMutex(&stable_mutex);
1835 initMutex(&task->lock);
1836
1837 for (i=0; i < n_capabilities; i++) {
1838 initMutex(&capabilities[i].lock);
1839 }
1840 #endif
1841
1842 #ifdef TRACING
1843 resetTracing();
1844 #endif
1845
1846 // Now, all OS threads except the thread that forked are
1847 // stopped. We need to stop all Haskell threads, including
1848 // those involved in foreign calls. Also we need to delete
1849 // all Tasks, because they correspond to OS threads that are
1850 // now gone.
1851
1852 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1853 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1854 next = t->global_link;
1855 // don't allow threads to catch the ThreadKilled
1856 // exception, but we do want to raiseAsync() because these
1857 // threads may be evaluating thunks that we need later.
1858 deleteThread_(t->cap,t);
1859
1860 // stop the GC from updating the InCall to point to
1861 // the TSO. This is only necessary because the
1862 // OSThread bound to the TSO has been killed, and
1863 // won't get a chance to exit in the usual way (see
1864 // also scheduleHandleThreadFinished).
1865 t->bound = NULL;
1866 }
1867 }
1868
1869 discardTasksExcept(task);
1870
1871 for (i=0; i < n_capabilities; i++) {
1872 cap = &capabilities[i];
1873
1874 // Empty the run queue. It seems tempting to let all the
1875 // killed threads stay on the run queue as zombies to be
1876 // cleaned up later, but some of them may correspond to
1877 // bound threads for which the corresponding Task does not
1878 // exist.
1879 cap->run_queue_hd = END_TSO_QUEUE;
1880 cap->run_queue_tl = END_TSO_QUEUE;
1881
1882 // Any suspended C-calling Tasks are no more, their OS threads
1883 // don't exist now:
1884 cap->suspended_ccalls = NULL;
1885
1886 #if defined(THREADED_RTS)
1887 // Wipe our spare workers list, they no longer exist. New
1888 // workers will be created if necessary.
1889 cap->spare_workers = NULL;
1890 cap->n_spare_workers = 0;
1891 cap->returning_tasks_hd = NULL;
1892 cap->returning_tasks_tl = NULL;
1893 #endif
1894
1895 // Release all caps except 0, we'll use that for starting
1896 // the IO manager and running the client action below.
1897 if (cap->no != 0) {
1898 task->cap = cap;
1899 releaseCapability(cap);
1900 }
1901 }
1902 cap = &capabilities[0];
1903 task->cap = cap;
1904
1905 // Empty the threads lists. Otherwise, the garbage
1906 // collector may attempt to resurrect some of these threads.
1907 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1908 generations[g].threads = END_TSO_QUEUE;
1909 }
1910
1911 // On Unix, all timers are reset in the child, so we need to start
1912 // the timer again.
1913 initTimer();
1914 startTimer();
1915
1916 // TODO: need to trace various other things in the child
1917 // like startup event, capabilities, process info etc
1918 traceTaskCreate(task, cap);
1919
1920 #if defined(THREADED_RTS)
1921 ioManagerStartCap(&cap);
1922 #endif
1923
1924 rts_evalStableIO(&cap, entry, NULL); // run the action
1925 rts_checkSchedStatus("forkProcess",cap);
1926
1927 rts_unlock(cap);
1928 hs_exit(); // clean up and exit
1929 stg_exit(EXIT_SUCCESS);
1930 }
1931 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1932 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1933 #endif
1934 }
1935
1936 /* ---------------------------------------------------------------------------
1937 * Changing the number of Capabilities
1938 *
1939 * Changing the number of Capabilities is very tricky! We can only do
1940 * it with the system fully stopped, so we do a full sync with
1941 * requestSync(SYNC_OTHER) and grab all the capabilities.
1942 *
1943 * Then we resize the appropriate data structures, and update all
1944 * references to the old data structures which have now moved.
1945 * Finally we release the Capabilities we are holding, and start
1946 * worker Tasks on the new Capabilities we created.
1947 *
1948 * ------------------------------------------------------------------------- */
1949
1950 void
1951 setNumCapabilities (nat new_n_capabilities USED_IF_THREADS)
1952 {
1953 #if !defined(THREADED_RTS)
1954 if (new_n_capabilities != 1) {
1955 errorBelch("setNumCapabilities: not supported in the non-threaded RTS");
1956 }
1957 return;
1958 #elif defined(NOSMP)
1959 if (new_n_capabilities != 1) {
1960 errorBelch("setNumCapabilities: not supported on this platform");
1961 }
1962 return;
1963 #else
1964 Task *task;
1965 Capability *cap;
1966 nat sync;
1967 StgTSO* t;
1968 nat g, n;
1969 Capability *old_capabilities = NULL;
1970
1971 if (new_n_capabilities == enabled_capabilities) return;
1972
1973 debugTrace(DEBUG_sched, "changing the number of Capabilities from %d to %d",
1974 enabled_capabilities, new_n_capabilities);
1975
1976 cap = rts_lock();
1977 task = cap->running_task;
1978
1979 do {
1980 sync = requestSync(&cap, task, SYNC_OTHER);
1981 } while (sync);
1982
1983 acquireAllCapabilities(cap,task);
1984
1985 pending_sync = 0;
1986
1987 if (new_n_capabilities < enabled_capabilities)
1988 {
1989 // Reducing the number of capabilities: we do not actually
1990 // remove the extra capabilities, we just mark them as
1991 // "disabled". This has the following effects:
1992 //
1993 // - threads on a disabled capability are migrated away by the
1994 // scheduler loop
1995 //
1996 // - disabled capabilities do not participate in GC
1997 // (see scheduleDoGC())
1998 //
1999 // - No spark threads are created on this capability
2000 // (see scheduleActivateSpark())
2001 //
2002 // - We do not attempt to migrate threads *to* a disabled
2003 // capability (see schedulePushWork()).
2004 //
2005 // but in other respects, a disabled capability remains
2006 // alive. Threads may be woken up on a disabled capability,
2007 // but they will be immediately migrated away.
2008 //
2009 // This approach is much easier than trying to actually remove
2010 // the capability; we don't have to worry about GC data
2011 // structures, the nursery, etc.
2012 //
2013 for (n = new_n_capabilities; n < enabled_capabilities; n++) {
2014 capabilities[n].disabled = rtsTrue;
2015 traceCapDisable(&capabilities[n]);
2016 }
2017 enabled_capabilities = new_n_capabilities;
2018 }
2019 else
2020 {
2021 // Increasing the number of enabled capabilities.
2022 //
2023 // enable any disabled capabilities, up to the required number
2024 for (n = enabled_capabilities;
2025 n < new_n_capabilities && n < n_capabilities; n++) {
2026 capabilities[n].disabled = rtsFalse;
2027 traceCapEnable(&capabilities[n]);
2028 }
2029 enabled_capabilities = n;
2030
2031 if (new_n_capabilities > n_capabilities) {
2032 #if defined(TRACING)
2033 // Allocate eventlog buffers for the new capabilities. Note this
2034 // must be done before calling moreCapabilities(), because that
2035 // will emit events about creating the new capabilities and adding
2036 // them to existing capsets.
2037 tracingAddCapapilities(n_capabilities, new_n_capabilities);
2038 #endif
2039
2040 // Resize the capabilities array
2041 // NB. after this, capabilities points somewhere new. Any pointers
2042 // of type (Capability *) are now invalid.
2043 old_capabilities = moreCapabilities(n_capabilities, new_n_capabilities);
2044
2045 // update our own cap pointer
2046 cap = &capabilities[cap->no];
2047
2048 // Resize and update storage manager data structures
2049 storageAddCapabilities(n_capabilities, new_n_capabilities);
2050
2051 // Update (Capability *) refs in the Task manager.
2052 updateCapabilityRefs();
2053
2054 // Update (Capability *) refs from TSOs
2055 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
2056 for (t = generations[g].threads; t != END_TSO_QUEUE; t = t->global_link) {
2057 t->cap = &capabilities[t->cap->no];
2058 }
2059 }
2060 }
2061 }
2062
2063 // We're done: release the original Capabilities
2064 releaseAllCapabilities(cap,task);
2065
2066 // Start worker tasks on the new Capabilities
2067 startWorkerTasks(n_capabilities, new_n_capabilities);
2068
2069 // finally, update n_capabilities
2070 if (new_n_capabilities > n_capabilities) {
2071 n_capabilities = enabled_capabilities = new_n_capabilities;
2072 }
2073
2074 // We can't free the old array until now, because we access it
2075 // while updating pointers in updateCapabilityRefs().
2076 if (old_capabilities) {
2077 stgFree(old_capabilities);
2078 }
2079
2080 rts_unlock(cap);
2081
2082 #endif // THREADED_RTS
2083 }
2084
2085
2086
2087 /* ---------------------------------------------------------------------------
2088 * Delete all the threads in the system
2089 * ------------------------------------------------------------------------- */
2090
2091 static void
2092 deleteAllThreads ( Capability *cap )
2093 {
2094 // NOTE: only safe to call if we own all capabilities.
2095
2096 StgTSO* t, *next;
2097 nat g;
2098
2099 debugTrace(DEBUG_sched,"deleting all threads");
2100 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
2101 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
2102 next = t->global_link;
2103 deleteThread(cap,t);
2104 }
2105 }
2106
2107 // The run queue now contains a bunch of ThreadKilled threads. We
2108 // must not throw these away: the main thread(s) will be in there
2109 // somewhere, and the main scheduler loop has to deal with it.
2110 // Also, the run queue is the only thing keeping these threads from
2111 // being GC'd, and we don't want the "main thread has been GC'd" panic.
2112
2113 #if !defined(THREADED_RTS)
2114 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
2115 ASSERT(sleeping_queue == END_TSO_QUEUE);
2116 #endif
2117 }
2118
2119 /* -----------------------------------------------------------------------------
2120 Managing the suspended_ccalls list.
2121 Locks required: sched_mutex
2122 -------------------------------------------------------------------------- */
2123
2124 STATIC_INLINE void
2125 suspendTask (Capability *cap, Task *task)
2126 {
2127 InCall *incall;
2128
2129 incall = task->incall;
2130 ASSERT(incall->next == NULL && incall->prev == NULL);
2131 incall->next = cap->suspended_ccalls;
2132 incall->prev = NULL;
2133 if (cap->suspended_ccalls) {
2134 cap->suspended_ccalls->prev = incall;
2135 }
2136 cap->suspended_ccalls = incall;
2137 }
2138
2139 STATIC_INLINE void
2140 recoverSuspendedTask (Capability *cap, Task *task)
2141 {
2142 InCall *incall;
2143
2144 incall = task->incall;
2145 if (incall->prev) {
2146 incall->prev->next = incall->next;
2147 } else {
2148 ASSERT(cap->suspended_ccalls == incall);
2149 cap->suspended_ccalls = incall->next;
2150 }
2151 if (incall->next) {
2152 incall->next->prev = incall->prev;
2153 }
2154 incall->next = incall->prev = NULL;
2155 }
2156
2157 /* ---------------------------------------------------------------------------
2158 * Suspending & resuming Haskell threads.
2159 *
2160 * When making a "safe" call to C (aka _ccall_GC), the task gives back
2161 * its capability before calling the C function. This allows another
2162 * task to pick up the capability and carry on running Haskell
2163 * threads. It also means that if the C call blocks, it won't lock
2164 * the whole system.
2165 *
2166 * The Haskell thread making the C call is put to sleep for the
2167 * duration of the call, on the suspended_ccalling_threads queue. We
2168 * give out a token to the task, which it can use to resume the thread
2169 * on return from the C function.
2170 *
2171 * If this is an interruptible C call, this means that the FFI call may be
2172 * unceremoniously terminated and should be scheduled on an
2173 * unbound worker thread.
2174 * ------------------------------------------------------------------------- */
2175
2176 void *
2177 suspendThread (StgRegTable *reg, rtsBool interruptible)
2178 {
2179 Capability *cap;
2180 int saved_errno;
2181 StgTSO *tso;
2182 Task *task;
2183 #if mingw32_HOST_OS
2184 StgWord32 saved_winerror;
2185 #endif
2186
2187 saved_errno = errno;
2188 #if mingw32_HOST_OS
2189 saved_winerror = GetLastError();
2190 #endif
2191
2192 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
2193 */
2194 cap = regTableToCapability(reg);
2195
2196 task = cap->running_task;
2197 tso = cap->r.rCurrentTSO;
2198
2199 traceEventStopThread(cap, tso, THREAD_SUSPENDED_FOREIGN_CALL, 0);
2200
2201 // XXX this might not be necessary --SDM
2202 tso->what_next = ThreadRunGHC;
2203
2204 threadPaused(cap,tso);
2205
2206 if (interruptible) {
2207 tso->why_blocked = BlockedOnCCall_Interruptible;
2208 } else {
2209 tso->why_blocked = BlockedOnCCall;
2210 }
2211
2212 // Hand back capability
2213 task->incall->suspended_tso = tso;
2214 task->incall->suspended_cap = cap;
2215
2216 ACQUIRE_LOCK(&cap->lock);
2217
2218 suspendTask(cap,task);
2219 cap->in_haskell = rtsFalse;
2220 releaseCapability_(cap,rtsFalse);
2221
2222 RELEASE_LOCK(&cap->lock);
2223
2224 errno = saved_errno;
2225 #if mingw32_HOST_OS
2226 SetLastError(saved_winerror);
2227 #endif
2228 return task;
2229 }
2230
2231 StgRegTable *
2232 resumeThread (void *task_)
2233 {
2234 StgTSO *tso;
2235 InCall *incall;
2236 Capability *cap;
2237 Task *task = task_;
2238 int saved_errno;
2239 #if mingw32_HOST_OS
2240 StgWord32 saved_winerror;
2241 #endif
2242
2243 saved_errno = errno;
2244 #if mingw32_HOST_OS
2245 saved_winerror = GetLastError();
2246 #endif
2247
2248 incall = task->incall;
2249 cap = incall->suspended_cap;
2250 task->cap = cap;
2251
2252 // Wait for permission to re-enter the RTS with the result.
2253 waitForReturnCapability(&cap,task);
2254 // we might be on a different capability now... but if so, our
2255 // entry on the suspended_ccalls list will also have been
2256 // migrated.
2257
2258 // Remove the thread from the suspended list
2259 recoverSuspendedTask(cap,task);
2260
2261 tso = incall->suspended_tso;
2262 incall->suspended_tso = NULL;
2263 incall->suspended_cap = NULL;
2264 tso->_link = END_TSO_QUEUE; // no write barrier reqd
2265
2266 traceEventRunThread(cap, tso);
2267
2268 /* Reset blocking status */
2269 tso->why_blocked = NotBlocked;
2270
2271 if ((tso->flags & TSO_BLOCKEX) == 0) {
2272 // avoid locking the TSO if we don't have to
2273 if (tso->blocked_exceptions != END_BLOCKED_EXCEPTIONS_QUEUE) {
2274 maybePerformBlockedException(cap,tso);
2275 }
2276 }
2277
2278 cap->r.rCurrentTSO = tso;
2279 cap->in_haskell = rtsTrue;
2280 errno = saved_errno;
2281 #if mingw32_HOST_OS
2282 SetLastError(saved_winerror);
2283 #endif
2284
2285 /* We might have GC'd, mark the TSO dirty again */
2286 dirty_TSO(cap,tso);
2287 dirty_STACK(cap,tso->stackobj);
2288
2289 IF_DEBUG(sanity, checkTSO(tso));
2290
2291 return &cap->r;
2292 }
2293
2294 /* ---------------------------------------------------------------------------
2295 * scheduleThread()
2296 *
2297 * scheduleThread puts a thread on the end of the runnable queue.
2298 * This will usually be done immediately after a thread is created.
2299 * The caller of scheduleThread must create the thread using e.g.
2300 * createThread and push an appropriate closure
2301 * on this thread's stack before the scheduler is invoked.
2302 * ------------------------------------------------------------------------ */
2303
2304 void
2305 scheduleThread(Capability *cap, StgTSO *tso)
2306 {
2307 // The thread goes at the *end* of the run-queue, to avoid possible
2308 // starvation of any threads already on the queue.
2309 appendToRunQueue(cap,tso);
2310 }
2311
2312 void
2313 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
2314 {
2315 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
2316 // move this thread from now on.
2317 #if defined(THREADED_RTS)
2318 cpu %= enabled_capabilities;
2319 if (cpu == cap->no) {
2320 appendToRunQueue(cap,tso);
2321 } else {
2322 migrateThread(cap, tso, &capabilities[cpu]);
2323 }
2324 #else
2325 appendToRunQueue(cap,tso);
2326 #endif
2327 }
2328
2329 void
2330 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability **pcap)
2331 {
2332 Task *task;
2333 DEBUG_ONLY( StgThreadID id );
2334 Capability *cap;
2335
2336 cap = *pcap;
2337
2338 // We already created/initialised the Task
2339 task = cap->running_task;
2340
2341 // This TSO is now a bound thread; make the Task and TSO
2342 // point to each other.
2343 tso->bound = task->incall;
2344 tso->cap = cap;
2345
2346 task->incall->tso = tso;
2347 task->incall->ret = ret;
2348 task->incall->stat = NoStatus;
2349
2350 appendToRunQueue(cap,tso);
2351
2352 DEBUG_ONLY( id = tso->id );
2353 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)id);
2354
2355 cap = schedule(cap,task);
2356
2357 ASSERT(task->incall->stat != NoStatus);
2358 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
2359
2360 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)id);
2361 *pcap = cap;
2362 }
2363
2364 /* ----------------------------------------------------------------------------
2365 * Starting Tasks
2366 * ------------------------------------------------------------------------- */
2367
2368 #if defined(THREADED_RTS)
2369 void scheduleWorker (Capability *cap, Task *task)
2370 {
2371 // schedule() runs without a lock.
2372 cap = schedule(cap,task);
2373
2374 // On exit from schedule(), we have a Capability, but possibly not
2375 // the same one we started with.
2376
2377 // During shutdown, the requirement is that after all the
2378 // Capabilities are shut down, all workers that are shutting down
2379 // have finished workerTaskStop(). This is why we hold on to
2380 // cap->lock until we've finished workerTaskStop() below.
2381 //
2382 // There may be workers still involved in foreign calls; those
2383 // will just block in waitForReturnCapability() because the
2384 // Capability has been shut down.
2385 //
2386 ACQUIRE_LOCK(&cap->lock);
2387 releaseCapability_(cap,rtsFalse);
2388 workerTaskStop(task);
2389 RELEASE_LOCK(&cap->lock);
2390 }
2391 #endif
2392
2393 /* ---------------------------------------------------------------------------
2394 * Start new worker tasks on Capabilities from--to
2395 * -------------------------------------------------------------------------- */
2396
2397 static void
2398 startWorkerTasks (nat from USED_IF_THREADS, nat to USED_IF_THREADS)
2399 {
2400 #if defined(THREADED_RTS)
2401 nat i;
2402 Capability *cap;
2403
2404 for (i = from; i < to; i++) {
2405 cap = &capabilities[i];
2406 ACQUIRE_LOCK(&cap->lock);
2407 startWorkerTask(cap);
2408 RELEASE_LOCK(&cap->lock);
2409 }
2410 #endif
2411 }
2412
2413 /* ---------------------------------------------------------------------------
2414 * initScheduler()
2415 *
2416 * Initialise the scheduler. This resets all the queues - if the
2417 * queues contained any threads, they'll be garbage collected at the
2418 * next pass.
2419 *
2420 * ------------------------------------------------------------------------ */
2421
2422 void
2423 initScheduler(void)
2424 {
2425 #if !defined(THREADED_RTS)
2426 blocked_queue_hd = END_TSO_QUEUE;
2427 blocked_queue_tl = END_TSO_QUEUE;
2428 sleeping_queue = END_TSO_QUEUE;
2429 #endif
2430
2431 sched_state = SCHED_RUNNING;
2432 recent_activity = ACTIVITY_YES;
2433
2434 #if defined(THREADED_RTS)
2435 /* Initialise the mutex and condition variables used by
2436 * the scheduler. */
2437 initMutex(&sched_mutex);
2438 #endif
2439
2440 ACQUIRE_LOCK(&sched_mutex);
2441
2442 /* A capability holds the state a native thread needs in
2443 * order to execute STG code. At least one capability is
2444 * floating around (only THREADED_RTS builds have more than one).
2445 */
2446 initCapabilities();
2447
2448 initTaskManager();
2449
2450 /*
2451 * Eagerly start one worker to run each Capability, except for
2452 * Capability 0. The idea is that we're probably going to start a
2453 * bound thread on Capability 0 pretty soon, so we don't want a
2454 * worker task hogging it.
2455 */
2456 startWorkerTasks(1, n_capabilities);
2457
2458 RELEASE_LOCK(&sched_mutex);
2459
2460 }
2461
2462 void
2463 exitScheduler (rtsBool wait_foreign USED_IF_THREADS)
2464 /* see Capability.c, shutdownCapability() */
2465 {
2466 Task *task = NULL;
2467
2468 task = newBoundTask();
2469
2470 // If we haven't killed all the threads yet, do it now.
2471 if (sched_state < SCHED_SHUTTING_DOWN) {
2472 sched_state = SCHED_INTERRUPTING;
2473 Capability *cap = task->cap;
2474 waitForReturnCapability(&cap,task);
2475 scheduleDoGC(&cap,task,rtsTrue);
2476 ASSERT(task->incall->tso == NULL);
2477 releaseCapability(cap);
2478 }
2479 sched_state = SCHED_SHUTTING_DOWN;
2480
2481 shutdownCapabilities(task, wait_foreign);
2482
2483 // debugBelch("n_failed_trygrab_idles = %d, n_idle_caps = %d\n",
2484 // n_failed_trygrab_idles, n_idle_caps);
2485
2486 boundTaskExiting(task);
2487 }
2488
2489 void
2490 freeScheduler( void )
2491 {
2492 nat still_running;
2493
2494 ACQUIRE_LOCK(&sched_mutex);
2495 still_running = freeTaskManager();
2496 // We can only free the Capabilities if there are no Tasks still
2497 // running. We might have a Task about to return from a foreign
2498 // call into waitForReturnCapability(), for example (actually,
2499 // this should be the *only* thing that a still-running Task can
2500 // do at this point, and it will block waiting for the
2501 // Capability).
2502 if (still_running == 0) {
2503 freeCapabilities();
2504 if (n_capabilities != 1) {
2505 stgFree(capabilities);
2506 }
2507 }
2508 RELEASE_LOCK(&sched_mutex);
2509 #if defined(THREADED_RTS)
2510 closeMutex(&sched_mutex);
2511 #endif
2512 }
2513
2514 void markScheduler (evac_fn evac USED_IF_NOT_THREADS,
2515 void *user USED_IF_NOT_THREADS)
2516 {
2517 #if !defined(THREADED_RTS)
2518 evac(user, (StgClosure **)(void *)&blocked_queue_hd);
2519 evac(user, (StgClosure **)(void *)&blocked_queue_tl);
2520 evac(user, (StgClosure **)(void *)&sleeping_queue);
2521 #endif
2522 }
2523
2524 /* -----------------------------------------------------------------------------
2525 performGC
2526
2527 This is the interface to the garbage collector from Haskell land.
2528 We provide this so that external C code can allocate and garbage
2529 collect when called from Haskell via _ccall_GC.
2530 -------------------------------------------------------------------------- */
2531
2532 static void
2533 performGC_(rtsBool force_major)
2534 {
2535 Task *task;
2536 Capability *cap = NULL;
2537
2538 // We must grab a new Task here, because the existing Task may be
2539 // associated with a particular Capability, and chained onto the
2540 // suspended_ccalls queue.
2541 task = newBoundTask();
2542
2543 // TODO: do we need to traceTask*() here?
2544
2545 waitForReturnCapability(&cap,task);
2546 scheduleDoGC(&cap,task,force_major);
2547 releaseCapability(cap);
2548 boundTaskExiting(task);
2549 }
2550
2551 void
2552 performGC(void)
2553 {
2554 performGC_(rtsFalse);
2555 }
2556
2557 void
2558 performMajorGC(void)
2559 {
2560 performGC_(rtsTrue);
2561 }
2562
2563 /* ---------------------------------------------------------------------------
2564 Interrupt execution
2565 - usually called inside a signal handler so it mustn't do anything fancy.
2566 ------------------------------------------------------------------------ */
2567
2568 void
2569 interruptStgRts(void)
2570 {
2571 sched_state = SCHED_INTERRUPTING;
2572 interruptAllCapabilities();
2573 #if defined(THREADED_RTS)
2574 wakeUpRts();
2575 #endif
2576 }
2577
2578 /* -----------------------------------------------------------------------------
2579 Wake up the RTS
2580
2581 This function causes at least one OS thread to wake up and run the
2582 scheduler loop. It is invoked when the RTS might be deadlocked, or
2583 an external event has arrived that may need servicing (eg. a
2584 keyboard interrupt).
2585
2586 In the single-threaded RTS we don't do anything here; we only have
2587 one thread anyway, and the event that caused us to want to wake up
2588 will have interrupted any blocking system call in progress anyway.
2589 -------------------------------------------------------------------------- */
2590
2591 #if defined(THREADED_RTS)
2592 void wakeUpRts(void)
2593 {
2594 // This forces the IO Manager thread to wakeup, which will
2595 // in turn ensure that some OS thread wakes up and runs the
2596 // scheduler loop, which will cause a GC and deadlock check.
2597 ioManagerWakeup();
2598 }
2599 #endif
2600
2601 /* -----------------------------------------------------------------------------
2602 Deleting threads
2603
2604 This is used for interruption (^C) and forking, and corresponds to
2605 raising an exception but without letting the thread catch the
2606 exception.
2607 -------------------------------------------------------------------------- */
2608
2609 static void
2610 deleteThread (Capability *cap STG_UNUSED, StgTSO *tso)
2611 {
2612 // NOTE: must only be called on a TSO that we have exclusive
2613 // access to, because we will call throwToSingleThreaded() below.
2614 // The TSO must be on the run queue of the Capability we own, or
2615 // we must own all Capabilities.
2616
2617 if (tso->why_blocked != BlockedOnCCall &&
2618 tso->why_blocked != BlockedOnCCall_Interruptible) {
2619 throwToSingleThreaded(tso->cap,tso,NULL);
2620 }
2621 }
2622
2623 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2624 static void
2625 deleteThread_(Capability *cap, StgTSO *tso)
2626 { // for forkProcess only:
2627 // like deleteThread(), but we delete threads in foreign calls, too.
2628
2629 if (tso->why_blocked == BlockedOnCCall ||
2630 tso->why_blocked == BlockedOnCCall_Interruptible) {
2631 tso->what_next = ThreadKilled;
2632 appendToRunQueue(tso->cap, tso);
2633 } else {
2634 deleteThread(cap,tso);
2635 }
2636 }
2637 #endif
2638
2639 /* -----------------------------------------------------------------------------
2640 raiseExceptionHelper
2641
2642 This function is called by the raise# primitve, just so that we can
2643 move some of the tricky bits of raising an exception from C-- into
2644 C. Who knows, it might be a useful re-useable thing here too.
2645 -------------------------------------------------------------------------- */
2646
2647 StgWord
2648 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2649 {
2650 Capability *cap = regTableToCapability(reg);
2651 StgThunk *raise_closure = NULL;
2652 StgPtr p, next;
2653 StgRetInfoTable *info;
2654 //
2655 // This closure represents the expression 'raise# E' where E
2656 // is the exception raise. It is used to overwrite all the
2657 // thunks which are currently under evaluataion.
2658 //
2659
2660 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2661 // LDV profiling: stg_raise_info has THUNK as its closure
2662 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2663 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2664 // 1 does not cause any problem unless profiling is performed.
2665 // However, when LDV profiling goes on, we need to linearly scan
2666 // small object pool, where raise_closure is stored, so we should
2667 // use MIN_UPD_SIZE.
2668 //
2669 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2670 // sizeofW(StgClosure)+1);
2671 //
2672
2673 //
2674 // Walk up the stack, looking for the catch frame. On the way,
2675 // we update any closures pointed to from update frames with the
2676 // raise closure that we just built.
2677 //
2678 p = tso->stackobj->sp;
2679 while(1) {
2680 info = get_ret_itbl((StgClosure *)p);
2681 next = p + stack_frame_sizeW((StgClosure *)p);
2682 switch (info->i.type) {
2683
2684 case UPDATE_FRAME:
2685 // Only create raise_closure if we need to.
2686 if (raise_closure == NULL) {
2687 raise_closure =
2688 (StgThunk *)allocate(cap,sizeofW(StgThunk)+1);
2689 SET_HDR(raise_closure, &stg_raise_info, cap->r.rCCCS);
2690 raise_closure->payload[0] = exception;
2691 }
2692 updateThunk(cap, tso, ((StgUpdateFrame *)p)->updatee,
2693 (StgClosure *)raise_closure);
2694 p = next;
2695 continue;
2696
2697 case ATOMICALLY_FRAME:
2698 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2699 tso->stackobj->sp = p;
2700 return ATOMICALLY_FRAME;
2701
2702 case CATCH_FRAME:
2703 tso->stackobj->sp = p;
2704 return CATCH_FRAME;
2705
2706 case CATCH_STM_FRAME:
2707 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2708 tso->stackobj->sp = p;
2709 return CATCH_STM_FRAME;
2710
2711 case UNDERFLOW_FRAME:
2712 tso->stackobj->sp = p;
2713 threadStackUnderflow(cap,tso);
2714 p = tso->stackobj->sp;
2715 continue;
2716
2717 case STOP_FRAME:
2718 tso->stackobj->sp = p;
2719 return STOP_FRAME;
2720
2721 case CATCH_RETRY_FRAME:
2722 default:
2723 p = next;
2724 continue;
2725 }
2726 }
2727 }
2728
2729
2730 /* -----------------------------------------------------------------------------
2731 findRetryFrameHelper
2732
2733 This function is called by the retry# primitive. It traverses the stack
2734 leaving tso->sp referring to the frame which should handle the retry.
2735
2736 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2737 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2738
2739 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2740 create) because retries are not considered to be exceptions, despite the
2741 similar implementation.
2742
2743 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2744 not be created within memory transactions.
2745 -------------------------------------------------------------------------- */
2746
2747 StgWord
2748 findRetryFrameHelper (Capability *cap, StgTSO *tso)
2749 {
2750 StgPtr p, next;
2751 StgRetInfoTable *info;
2752
2753 p = tso->stackobj->sp;
2754 while (1) {
2755 info = get_ret_itbl((StgClosure *)p);
2756 next = p + stack_frame_sizeW((StgClosure *)p);
2757 switch (info->i.type) {
2758
2759 case ATOMICALLY_FRAME:
2760 debugTrace(DEBUG_stm,
2761 "found ATOMICALLY_FRAME at %p during retry", p);
2762 tso->stackobj->sp = p;
2763 return ATOMICALLY_FRAME;
2764
2765 case CATCH_RETRY_FRAME:
2766 debugTrace(DEBUG_stm,
2767 "found CATCH_RETRY_FRAME at %p during retrry", p);
2768 tso->stackobj->sp = p;
2769 return CATCH_RETRY_FRAME;
2770
2771 case CATCH_STM_FRAME: {
2772 StgTRecHeader *trec = tso -> trec;
2773 StgTRecHeader *outer = trec -> enclosing_trec;
2774 debugTrace(DEBUG_stm,
2775 "found CATCH_STM_FRAME at %p during retry", p);
2776 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2777 stmAbortTransaction(cap, trec);
2778 stmFreeAbortedTRec(cap, trec);
2779 tso -> trec = outer;
2780 p = next;
2781 continue;
2782 }
2783
2784 case UNDERFLOW_FRAME:
2785 threadStackUnderflow(cap,tso);
2786 p = tso->stackobj->sp;
2787 continue;
2788
2789 default:
2790 ASSERT(info->i.type != CATCH_FRAME);
2791 ASSERT(info->i.type != STOP_FRAME);
2792 p = next;
2793 continue;
2794 }
2795 }
2796 }
2797
2798 /* -----------------------------------------------------------------------------
2799 resurrectThreads is called after garbage collection on the list of
2800 threads found to be garbage. Each of these threads will be woken
2801 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2802 on an MVar, or NonTermination if the thread was blocked on a Black
2803 Hole.
2804
2805 Locks: assumes we hold *all* the capabilities.
2806 -------------------------------------------------------------------------- */
2807
2808 void
2809 resurrectThreads (StgTSO *threads)
2810 {
2811 StgTSO *tso, *next;
2812 Capability *cap;
2813 generation *gen;
2814
2815 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2816 next = tso->global_link;
2817
2818 gen = Bdescr((P_)tso)->gen;
2819 tso->global_link = gen->threads;
2820 gen->threads = tso;
2821
2822 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2823
2824 // Wake up the thread on the Capability it was last on
2825 cap = tso->cap;
2826
2827 switch (tso->why_blocked) {
2828 case BlockedOnMVar:
2829 /* Called by GC - sched_mutex lock is currently held. */
2830 throwToSingleThreaded(cap, tso,
2831 (StgClosure *)blockedIndefinitelyOnMVar_closure);
2832 break;
2833 case BlockedOnBlackHole:
2834 throwToSingleThreaded(cap, tso,
2835 (StgClosure *)nonTermination_closure);
2836 break;
2837 case BlockedOnSTM:
2838 throwToSingleThreaded(cap, tso,
2839 (StgClosure *)blockedIndefinitelyOnSTM_closure);
2840 break;
2841 case NotBlocked:
2842 /* This might happen if the thread was blocked on a black hole
2843 * belonging to a thread that we've just woken up (raiseAsync
2844 * can wake up threads, remember...).
2845 */
2846 continue;
2847 case BlockedOnMsgThrowTo:
2848 // This can happen if the target is masking, blocks on a
2849 // black hole, and then is found to be unreachable. In
2850 // this case, we want to let the target wake up and carry
2851 // on, and do nothing to this thread.
2852 continue;
2853 default:
2854 barf("resurrectThreads: thread blocked in a strange way: %d",
2855 tso->why_blocked);
2856 }
2857 }
2858 }