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