Make clearNursery free
[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(nat n, 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. It 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 // cap->r.rCurrentTSO is charged for calls to allocate(), so we
485 // don't want it set when not running a Haskell thread.
486 cap->r.rCurrentTSO = NULL;
487
488 // And save the current errno in this thread.
489 // XXX: possibly bogus for SMP because this thread might already
490 // be running again, see code below.
491 t->saved_errno = errno;
492 #if mingw32_HOST_OS
493 // Similarly for Windows error code
494 t->saved_winerror = GetLastError();
495 #endif
496
497 if (ret == ThreadBlocked) {
498 if (t->why_blocked == BlockedOnBlackHole) {
499 StgTSO *owner = blackHoleOwner(t->block_info.bh->bh);
500 traceEventStopThread(cap, t, t->why_blocked + 6,
501 owner != NULL ? owner->id : 0);
502 } else {
503 traceEventStopThread(cap, t, t->why_blocked + 6, 0);
504 }
505 } else {
506 traceEventStopThread(cap, t, ret, 0);
507 }
508
509 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
510 ASSERT(t->cap == cap);
511
512 // ----------------------------------------------------------------------
513
514 // Costs for the scheduler are assigned to CCS_SYSTEM
515 stopHeapProfTimer();
516 #if defined(PROFILING)
517 cap->r.rCCCS = CCS_SYSTEM;
518 #endif
519
520 schedulePostRunThread(cap,t);
521
522 ready_to_gc = rtsFalse;
523
524 switch (ret) {
525 case HeapOverflow:
526 ready_to_gc = scheduleHandleHeapOverflow(cap,t);
527 break;
528
529 case StackOverflow:
530 // just adjust the stack for this thread, then pop it back
531 // on the run queue.
532 threadStackOverflow(cap, t);
533 pushOnRunQueue(cap,t);
534 break;
535
536 case ThreadYielding:
537 if (scheduleHandleYield(cap, t, prev_what_next)) {
538 // shortcut for switching between compiler/interpreter:
539 goto run_thread;
540 }
541 break;
542
543 case ThreadBlocked:
544 scheduleHandleThreadBlocked(t);
545 break;
546
547 case ThreadFinished:
548 if (scheduleHandleThreadFinished(cap, task, t)) return cap;
549 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
550 break;
551
552 default:
553 barf("schedule: invalid thread return code %d", (int)ret);
554 }
555
556 if (ready_to_gc || scheduleNeedHeapProfile(ready_to_gc)) {
557 scheduleDoGC(&cap,task,rtsFalse);
558 }
559 } /* end of while() */
560 }
561
562 /* -----------------------------------------------------------------------------
563 * Run queue operations
564 * -------------------------------------------------------------------------- */
565
566 void
567 removeFromRunQueue (Capability *cap, StgTSO *tso)
568 {
569 if (tso->block_info.prev == END_TSO_QUEUE) {
570 ASSERT(cap->run_queue_hd == tso);
571 cap->run_queue_hd = tso->_link;
572 } else {
573 setTSOLink(cap, tso->block_info.prev, tso->_link);
574 }
575 if (tso->_link == END_TSO_QUEUE) {
576 ASSERT(cap->run_queue_tl == tso);
577 cap->run_queue_tl = tso->block_info.prev;
578 } else {
579 setTSOPrev(cap, tso->_link, tso->block_info.prev);
580 }
581 tso->_link = tso->block_info.prev = END_TSO_QUEUE;
582
583 IF_DEBUG(sanity, checkRunQueue(cap));
584 }
585
586 void
587 promoteInRunQueue (Capability *cap, StgTSO *tso)
588 {
589 removeFromRunQueue(cap, tso);
590 pushOnRunQueue(cap, tso);
591 }
592
593 /* ----------------------------------------------------------------------------
594 * Setting up the scheduler loop
595 * ------------------------------------------------------------------------- */
596
597 static void
598 schedulePreLoop(void)
599 {
600 // initialisation for scheduler - what cannot go into initScheduler()
601
602 #if defined(mingw32_HOST_OS) && !defined(USE_MINIINTERPRETER)
603 win32AllocStack();
604 #endif
605 }
606
607 /* -----------------------------------------------------------------------------
608 * scheduleFindWork()
609 *
610 * Search for work to do, and handle messages from elsewhere.
611 * -------------------------------------------------------------------------- */
612
613 static void
614 scheduleFindWork (Capability **pcap)
615 {
616 scheduleStartSignalHandlers(*pcap);
617
618 scheduleProcessInbox(pcap);
619
620 scheduleCheckBlockedThreads(*pcap);
621
622 #if defined(THREADED_RTS)
623 if (emptyRunQueue(*pcap)) { scheduleActivateSpark(*pcap); }
624 #endif
625 }
626
627 #if defined(THREADED_RTS)
628 STATIC_INLINE rtsBool
629 shouldYieldCapability (Capability *cap, Task *task, rtsBool didGcLast)
630 {
631 // we need to yield this capability to someone else if..
632 // - another thread is initiating a GC, and we didn't just do a GC
633 // (see Note [GC livelock])
634 // - another Task is returning from a foreign call
635 // - the thread at the head of the run queue cannot be run
636 // by this Task (it is bound to another Task, or it is unbound
637 // and this task it bound).
638 //
639 // Note [GC livelock]
640 //
641 // If we are interrupted to do a GC, then we do not immediately do
642 // another one. This avoids a starvation situation where one
643 // Capability keeps forcing a GC and the other Capabilities make no
644 // progress at all.
645
646 return ((pending_sync && !didGcLast) ||
647 cap->returning_tasks_hd != NULL ||
648 (!emptyRunQueue(cap) && (task->incall->tso == NULL
649 ? peekRunQueue(cap)->bound != NULL
650 : peekRunQueue(cap)->bound != task->incall)));
651 }
652
653 // This is the single place where a Task goes to sleep. There are
654 // two reasons it might need to sleep:
655 // - there are no threads to run
656 // - we need to yield this Capability to someone else
657 // (see shouldYieldCapability())
658 //
659 // Careful: the scheduler loop is quite delicate. Make sure you run
660 // the tests in testsuite/concurrent (all ways) after modifying this,
661 // and also check the benchmarks in nofib/parallel for regressions.
662
663 static void
664 scheduleYield (Capability **pcap, Task *task)
665 {
666 Capability *cap = *pcap;
667 int didGcLast = rtsFalse;
668
669 // if we have work, and we don't need to give up the Capability, continue.
670 //
671 if (!shouldYieldCapability(cap,task,rtsFalse) &&
672 (!emptyRunQueue(cap) ||
673 !emptyInbox(cap) ||
674 sched_state >= SCHED_INTERRUPTING)) {
675 return;
676 }
677
678 // otherwise yield (sleep), and keep yielding if necessary.
679 do {
680 didGcLast = yieldCapability(&cap,task, !didGcLast);
681 }
682 while (shouldYieldCapability(cap,task,didGcLast));
683
684 // note there may still be no threads on the run queue at this
685 // point, the caller has to check.
686
687 *pcap = cap;
688 return;
689 }
690 #endif
691
692 /* -----------------------------------------------------------------------------
693 * schedulePushWork()
694 *
695 * Push work to other Capabilities if we have some.
696 * -------------------------------------------------------------------------- */
697
698 static void
699 schedulePushWork(Capability *cap USED_IF_THREADS,
700 Task *task USED_IF_THREADS)
701 {
702 /* following code not for PARALLEL_HASKELL. I kept the call general,
703 future GUM versions might use pushing in a distributed setup */
704 #if defined(THREADED_RTS)
705
706 Capability *free_caps[n_capabilities], *cap0;
707 nat i, n_free_caps;
708
709 // migration can be turned off with +RTS -qm
710 if (!RtsFlags.ParFlags.migrate) return;
711
712 // Check whether we have more threads on our run queue, or sparks
713 // in our pool, that we could hand to another Capability.
714 if (emptyRunQueue(cap)) {
715 if (sparkPoolSizeCap(cap) < 2) return;
716 } else {
717 if (singletonRunQueue(cap) &&
718 sparkPoolSizeCap(cap) < 1) return;
719 }
720
721 // First grab as many free Capabilities as we can.
722 for (i=0, n_free_caps=0; i < n_capabilities; i++) {
723 cap0 = capabilities[i];
724 if (cap != cap0 && !cap0->disabled && tryGrabCapability(cap0,task)) {
725 if (!emptyRunQueue(cap0)
726 || cap0->returning_tasks_hd != NULL
727 || cap0->inbox != (Message*)END_TSO_QUEUE) {
728 // it already has some work, we just grabbed it at
729 // the wrong moment. Or maybe it's deadlocked!
730 releaseCapability(cap0);
731 } else {
732 free_caps[n_free_caps++] = cap0;
733 }
734 }
735 }
736
737 // we now have n_free_caps free capabilities stashed in
738 // free_caps[]. Share our run queue equally with them. This is
739 // probably the simplest thing we could do; improvements we might
740 // want to do include:
741 //
742 // - giving high priority to moving relatively new threads, on
743 // the gournds that they haven't had time to build up a
744 // working set in the cache on this CPU/Capability.
745 //
746 // - giving low priority to moving long-lived threads
747
748 if (n_free_caps > 0) {
749 StgTSO *prev, *t, *next;
750 #ifdef SPARK_PUSHING
751 rtsBool pushed_to_all;
752 #endif
753
754 debugTrace(DEBUG_sched,
755 "cap %d: %s and %d free capabilities, sharing...",
756 cap->no,
757 (!emptyRunQueue(cap) && !singletonRunQueue(cap))?
758 "excess threads on run queue":"sparks to share (>=2)",
759 n_free_caps);
760
761 i = 0;
762 #ifdef SPARK_PUSHING
763 pushed_to_all = rtsFalse;
764 #endif
765
766 if (cap->run_queue_hd != END_TSO_QUEUE) {
767 prev = cap->run_queue_hd;
768 t = prev->_link;
769 prev->_link = END_TSO_QUEUE;
770 for (; t != END_TSO_QUEUE; t = next) {
771 next = t->_link;
772 t->_link = END_TSO_QUEUE;
773 if (t->bound == task->incall // don't move my bound thread
774 || tsoLocked(t)) { // don't move a locked thread
775 setTSOLink(cap, prev, t);
776 setTSOPrev(cap, t, prev);
777 prev = t;
778 } else if (i == n_free_caps) {
779 #ifdef SPARK_PUSHING
780 pushed_to_all = rtsTrue;
781 #endif
782 i = 0;
783 // keep one for us
784 setTSOLink(cap, prev, t);
785 setTSOPrev(cap, t, prev);
786 prev = t;
787 } else {
788 appendToRunQueue(free_caps[i],t);
789
790 traceEventMigrateThread (cap, t, free_caps[i]->no);
791
792 if (t->bound) { t->bound->task->cap = free_caps[i]; }
793 t->cap = free_caps[i];
794 i++;
795 }
796 }
797 cap->run_queue_tl = prev;
798
799 IF_DEBUG(sanity, checkRunQueue(cap));
800 }
801
802 #ifdef SPARK_PUSHING
803 /* JB I left this code in place, it would work but is not necessary */
804
805 // If there are some free capabilities that we didn't push any
806 // threads to, then try to push a spark to each one.
807 if (!pushed_to_all) {
808 StgClosure *spark;
809 // i is the next free capability to push to
810 for (; i < n_free_caps; i++) {
811 if (emptySparkPoolCap(free_caps[i])) {
812 spark = tryStealSpark(cap->sparks);
813 if (spark != NULL) {
814 /* TODO: if anyone wants to re-enable this code then
815 * they must consider the fizzledSpark(spark) case
816 * and update the per-cap spark statistics.
817 */
818 debugTrace(DEBUG_sched, "pushing spark %p to capability %d", spark, free_caps[i]->no);
819
820 traceEventStealSpark(free_caps[i], t, cap->no);
821
822 newSpark(&(free_caps[i]->r), spark);
823 }
824 }
825 }
826 }
827 #endif /* SPARK_PUSHING */
828
829 // release the capabilities
830 for (i = 0; i < n_free_caps; i++) {
831 task->cap = free_caps[i];
832 releaseAndWakeupCapability(free_caps[i]);
833 }
834 }
835 task->cap = cap; // reset to point to our Capability.
836
837 #endif /* THREADED_RTS */
838
839 }
840
841 /* ----------------------------------------------------------------------------
842 * Start any pending signal handlers
843 * ------------------------------------------------------------------------- */
844
845 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
846 static void
847 scheduleStartSignalHandlers(Capability *cap)
848 {
849 if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
850 // safe outside the lock
851 startSignalHandlers(cap);
852 }
853 }
854 #else
855 static void
856 scheduleStartSignalHandlers(Capability *cap STG_UNUSED)
857 {
858 }
859 #endif
860
861 /* ----------------------------------------------------------------------------
862 * Check for blocked threads that can be woken up.
863 * ------------------------------------------------------------------------- */
864
865 static void
866 scheduleCheckBlockedThreads(Capability *cap USED_IF_NOT_THREADS)
867 {
868 #if !defined(THREADED_RTS)
869 //
870 // Check whether any waiting threads need to be woken up. If the
871 // run queue is empty, and there are no other tasks running, we
872 // can wait indefinitely for something to happen.
873 //
874 if ( !emptyQueue(blocked_queue_hd) || !emptyQueue(sleeping_queue) )
875 {
876 awaitEvent (emptyRunQueue(cap));
877 }
878 #endif
879 }
880
881 /* ----------------------------------------------------------------------------
882 * Detect deadlock conditions and attempt to resolve them.
883 * ------------------------------------------------------------------------- */
884
885 static void
886 scheduleDetectDeadlock (Capability **pcap, Task *task)
887 {
888 Capability *cap = *pcap;
889 /*
890 * Detect deadlock: when we have no threads to run, there are no
891 * threads blocked, waiting for I/O, or sleeping, and all the
892 * other tasks are waiting for work, we must have a deadlock of
893 * some description.
894 */
895 if ( emptyThreadQueues(cap) )
896 {
897 #if defined(THREADED_RTS)
898 /*
899 * In the threaded RTS, we only check for deadlock if there
900 * has been no activity in a complete timeslice. This means
901 * we won't eagerly start a full GC just because we don't have
902 * any threads to run currently.
903 */
904 if (recent_activity != ACTIVITY_INACTIVE) return;
905 #endif
906
907 debugTrace(DEBUG_sched, "deadlocked, forcing major GC...");
908
909 // Garbage collection can release some new threads due to
910 // either (a) finalizers or (b) threads resurrected because
911 // they are unreachable and will therefore be sent an
912 // exception. Any threads thus released will be immediately
913 // runnable.
914 scheduleDoGC (pcap, task, rtsTrue/*force major GC*/);
915 cap = *pcap;
916 // when force_major == rtsTrue. scheduleDoGC sets
917 // recent_activity to ACTIVITY_DONE_GC and turns off the timer
918 // signal.
919
920 if ( !emptyRunQueue(cap) ) return;
921
922 #if defined(RTS_USER_SIGNALS) && !defined(THREADED_RTS)
923 /* If we have user-installed signal handlers, then wait
924 * for signals to arrive rather then bombing out with a
925 * deadlock.
926 */
927 if ( RtsFlags.MiscFlags.install_signal_handlers && anyUserHandlers() ) {
928 debugTrace(DEBUG_sched,
929 "still deadlocked, waiting for signals...");
930
931 awaitUserSignals();
932
933 if (signals_pending()) {
934 startSignalHandlers(cap);
935 }
936
937 // either we have threads to run, or we were interrupted:
938 ASSERT(!emptyRunQueue(cap) || sched_state >= SCHED_INTERRUPTING);
939
940 return;
941 }
942 #endif
943
944 #if !defined(THREADED_RTS)
945 /* Probably a real deadlock. Send the current main thread the
946 * Deadlock exception.
947 */
948 if (task->incall->tso) {
949 switch (task->incall->tso->why_blocked) {
950 case BlockedOnSTM:
951 case BlockedOnBlackHole:
952 case BlockedOnMsgThrowTo:
953 case BlockedOnMVar:
954 case BlockedOnMVarRead:
955 throwToSingleThreaded(cap, task->incall->tso,
956 (StgClosure *)nonTermination_closure);
957 return;
958 default:
959 barf("deadlock: main thread blocked in a strange way");
960 }
961 }
962 return;
963 #endif
964 }
965 }
966
967
968 /* ----------------------------------------------------------------------------
969 * Send pending messages (PARALLEL_HASKELL only)
970 * ------------------------------------------------------------------------- */
971
972 #if defined(PARALLEL_HASKELL)
973 static void
974 scheduleSendPendingMessages(void)
975 {
976
977 # if defined(PAR) // global Mem.Mgmt., omit for now
978 if (PendingFetches != END_BF_QUEUE) {
979 processFetches();
980 }
981 # endif
982
983 if (RtsFlags.ParFlags.BufferTime) {
984 // if we use message buffering, we must send away all message
985 // packets which have become too old...
986 sendOldBuffers();
987 }
988 }
989 #endif
990
991 /* ----------------------------------------------------------------------------
992 * Process message in the current Capability's inbox
993 * ------------------------------------------------------------------------- */
994
995 static void
996 scheduleProcessInbox (Capability **pcap USED_IF_THREADS)
997 {
998 #if defined(THREADED_RTS)
999 Message *m, *next;
1000 int r;
1001 Capability *cap = *pcap;
1002
1003 while (!emptyInbox(cap)) {
1004 if (cap->r.rCurrentNursery->link == NULL ||
1005 g0->n_new_large_words >= large_alloc_lim) {
1006 scheduleDoGC(pcap, cap->running_task, rtsFalse);
1007 cap = *pcap;
1008 }
1009
1010 // don't use a blocking acquire; if the lock is held by
1011 // another thread then just carry on. This seems to avoid
1012 // getting stuck in a message ping-pong situation with other
1013 // processors. We'll check the inbox again later anyway.
1014 //
1015 // We should really use a more efficient queue data structure
1016 // here. The trickiness is that we must ensure a Capability
1017 // never goes idle if the inbox is non-empty, which is why we
1018 // use cap->lock (cap->lock is released as the last thing
1019 // before going idle; see Capability.c:releaseCapability()).
1020 r = TRY_ACQUIRE_LOCK(&cap->lock);
1021 if (r != 0) return;
1022
1023 m = cap->inbox;
1024 cap->inbox = (Message*)END_TSO_QUEUE;
1025
1026 RELEASE_LOCK(&cap->lock);
1027
1028 while (m != (Message*)END_TSO_QUEUE) {
1029 next = m->link;
1030 executeMessage(cap, m);
1031 m = next;
1032 }
1033 }
1034 #endif
1035 }
1036
1037 /* ----------------------------------------------------------------------------
1038 * Activate spark threads (PARALLEL_HASKELL and THREADED_RTS)
1039 * ------------------------------------------------------------------------- */
1040
1041 #if defined(THREADED_RTS)
1042 static void
1043 scheduleActivateSpark(Capability *cap)
1044 {
1045 if (anySparks() && !cap->disabled)
1046 {
1047 createSparkThread(cap);
1048 debugTrace(DEBUG_sched, "creating a spark thread");
1049 }
1050 }
1051 #endif // PARALLEL_HASKELL || THREADED_RTS
1052
1053 /* ----------------------------------------------------------------------------
1054 * After running a thread...
1055 * ------------------------------------------------------------------------- */
1056
1057 static void
1058 schedulePostRunThread (Capability *cap, StgTSO *t)
1059 {
1060 // We have to be able to catch transactions that are in an
1061 // infinite loop as a result of seeing an inconsistent view of
1062 // memory, e.g.
1063 //
1064 // atomically $ do
1065 // [a,b] <- mapM readTVar [ta,tb]
1066 // when (a == b) loop
1067 //
1068 // and a is never equal to b given a consistent view of memory.
1069 //
1070 if (t -> trec != NO_TREC && t -> why_blocked == NotBlocked) {
1071 if (!stmValidateNestOfTransactions(cap, t -> trec)) {
1072 debugTrace(DEBUG_sched | DEBUG_stm,
1073 "trec %p found wasting its time", t);
1074
1075 // strip the stack back to the
1076 // ATOMICALLY_FRAME, aborting the (nested)
1077 // transaction, and saving the stack of any
1078 // partially-evaluated thunks on the heap.
1079 throwToSingleThreaded_(cap, t, NULL, rtsTrue);
1080
1081 // ASSERT(get_itbl((StgClosure *)t->sp)->type == ATOMICALLY_FRAME);
1082 }
1083 }
1084
1085 //
1086 // If the current thread's allocation limit has run out, send it
1087 // the AllocationLimitExceeded exception.
1088
1089 if (t->alloc_limit < 0 && (t->flags & TSO_ALLOC_LIMIT)) {
1090 // Use a throwToSelf rather than a throwToSingleThreaded, because
1091 // it correctly handles the case where the thread is currently
1092 // inside mask. Also the thread might be blocked (e.g. on an
1093 // MVar), and throwToSingleThreaded doesn't unblock it
1094 // correctly in that case.
1095 throwToSelf(cap, t, allocationLimitExceeded_closure);
1096 t->alloc_limit = (StgInt64)RtsFlags.GcFlags.allocLimitGrace
1097 * BLOCK_SIZE;
1098 }
1099
1100 /* some statistics gathering in the parallel case */
1101 }
1102
1103 /* -----------------------------------------------------------------------------
1104 * Handle a thread that returned to the scheduler with ThreadHeapOverflow
1105 * -------------------------------------------------------------------------- */
1106
1107 static rtsBool
1108 scheduleHandleHeapOverflow( Capability *cap, StgTSO *t )
1109 {
1110 // did the task ask for a large block?
1111 if (cap->r.rHpAlloc > BLOCK_SIZE) {
1112 // if so, get one and push it on the front of the nursery.
1113 bdescr *bd;
1114 W_ blocks;
1115
1116 blocks = (W_)BLOCK_ROUND_UP(cap->r.rHpAlloc) / BLOCK_SIZE;
1117
1118 if (blocks > BLOCKS_PER_MBLOCK) {
1119 barf("allocation of %ld bytes too large (GHC should have complained at compile-time)", (long)cap->r.rHpAlloc);
1120 }
1121
1122 debugTrace(DEBUG_sched,
1123 "--<< thread %ld (%s) stopped: requesting a large block (size %ld)\n",
1124 (long)t->id, what_next_strs[t->what_next], blocks);
1125
1126 // don't do this if the nursery is (nearly) full, we'll GC first.
1127 if (cap->r.rCurrentNursery->link != NULL ||
1128 cap->r.rNursery->n_blocks == 1) { // paranoia to prevent
1129 // infinite loop if the
1130 // nursery has only one
1131 // block.
1132
1133 bd = allocGroup_lock(blocks);
1134 cap->r.rNursery->n_blocks += blocks;
1135
1136 // link the new group after CurrentNursery
1137 dbl_link_insert_after(bd, cap->r.rCurrentNursery);
1138
1139 // initialise it as a nursery block. We initialise the
1140 // step, gen_no, and flags field of *every* sub-block in
1141 // this large block, because this is easier than making
1142 // sure that we always find the block head of a large
1143 // block whenever we call Bdescr() (eg. evacuate() and
1144 // isAlive() in the GC would both have to do this, at
1145 // least).
1146 {
1147 bdescr *x;
1148 for (x = bd; x < bd + blocks; x++) {
1149 initBdescr(x,g0,g0);
1150 x->free = x->start;
1151 x->flags = 0;
1152 }
1153 }
1154
1155 // This assert can be a killer if the app is doing lots
1156 // of large block allocations.
1157 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1158
1159 // now update the nursery to point to the new block
1160 finishedNurseryBlock(cap, cap->r.rCurrentNursery);
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(nat n, Capability *cap, Task *task)
1431 {
1432 nat i;
1433
1434 for (i = 0; i < n; 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 nat collect_gen;
1455 #ifdef THREADED_RTS
1456 nat 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 heap_census = scheduleNeedHeapProfile(rtsTrue);
1469
1470 // Figure out which generation we are collecting, so that we can
1471 // decide whether this is a parallel GC or not.
1472 collect_gen = calcNeeded(force_major || heap_census, NULL);
1473
1474 #ifdef THREADED_RTS
1475 if (sched_state < SCHED_INTERRUPTING
1476 && RtsFlags.ParFlags.parGcEnabled
1477 && collect_gen >= RtsFlags.ParFlags.parGcGen
1478 && ! oldest_gen->mark)
1479 {
1480 gc_type = SYNC_GC_PAR;
1481 } else {
1482 gc_type = SYNC_GC_SEQ;
1483 }
1484
1485 // In order to GC, there must be no threads running Haskell code.
1486 // Therefore, the GC thread needs to hold *all* the capabilities,
1487 // and release them after the GC has completed.
1488 //
1489 // This seems to be the simplest way: previous attempts involved
1490 // making all the threads with capabilities give up their
1491 // capabilities and sleep except for the *last* one, which
1492 // actually did the GC. But it's quite hard to arrange for all
1493 // the other tasks to sleep and stay asleep.
1494 //
1495
1496 /* Other capabilities are prevented from running yet more Haskell
1497 threads if pending_sync is set. Tested inside
1498 yieldCapability() and releaseCapability() in Capability.c */
1499
1500 do {
1501 sync = requestSync(pcap, task, gc_type);
1502 cap = *pcap;
1503 if (sync == SYNC_GC_SEQ || sync == SYNC_GC_PAR) {
1504 // someone else had a pending sync request for a GC, so
1505 // let's assume GC has been done and we don't need to GC
1506 // again.
1507 return;
1508 }
1509 if (sched_state == SCHED_SHUTTING_DOWN) {
1510 // The scheduler might now be shutting down. We tested
1511 // this above, but it might have become true since then as
1512 // we yielded the capability in requestSync().
1513 return;
1514 }
1515 } while (sync);
1516
1517 // don't declare this until after we have sync'd, because
1518 // n_capabilities may change.
1519 rtsBool idle_cap[n_capabilities];
1520 #ifdef DEBUG
1521 unsigned int old_n_capabilities = n_capabilities;
1522 #endif
1523
1524 interruptAllCapabilities();
1525
1526 // The final shutdown GC is always single-threaded, because it's
1527 // possible that some of the Capabilities have no worker threads.
1528
1529 if (gc_type == SYNC_GC_SEQ)
1530 {
1531 traceEventRequestSeqGc(cap);
1532 }
1533 else
1534 {
1535 traceEventRequestParGc(cap);
1536 debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1537 }
1538
1539 if (gc_type == SYNC_GC_SEQ)
1540 {
1541 // single-threaded GC: grab all the capabilities
1542 acquireAllCapabilities(cap,task);
1543 }
1544 else
1545 {
1546 // If we are load-balancing collections in this
1547 // generation, then we require all GC threads to participate
1548 // in the collection. Otherwise, we only require active
1549 // threads to participate, and we set gc_threads[i]->idle for
1550 // any idle capabilities. The rationale here is that waking
1551 // up an idle Capability takes much longer than just doing any
1552 // GC work on its behalf.
1553
1554 if (RtsFlags.ParFlags.parGcNoSyncWithIdle == 0
1555 || (RtsFlags.ParFlags.parGcLoadBalancingEnabled &&
1556 collect_gen >= RtsFlags.ParFlags.parGcLoadBalancingGen)) {
1557 for (i=0; i < n_capabilities; i++) {
1558 if (capabilities[i]->disabled) {
1559 idle_cap[i] = tryGrabCapability(capabilities[i], task);
1560 } else {
1561 idle_cap[i] = rtsFalse;
1562 }
1563 }
1564 } else {
1565 for (i=0; i < n_capabilities; i++) {
1566 if (capabilities[i]->disabled) {
1567 idle_cap[i] = tryGrabCapability(capabilities[i], task);
1568 } else if (i == cap->no ||
1569 capabilities[i]->idle < RtsFlags.ParFlags.parGcNoSyncWithIdle) {
1570 idle_cap[i] = rtsFalse;
1571 } else {
1572 idle_cap[i] = tryGrabCapability(capabilities[i], task);
1573 if (!idle_cap[i]) {
1574 n_failed_trygrab_idles++;
1575 } else {
1576 n_idle_caps++;
1577 }
1578 }
1579 }
1580 }
1581
1582 // We set the gc_thread[i]->idle flag if that
1583 // capability/thread is not participating in this collection.
1584 // We also keep a local record of which capabilities are idle
1585 // in idle_cap[], because scheduleDoGC() is re-entrant:
1586 // another thread might start a GC as soon as we've finished
1587 // this one, and thus the gc_thread[]->idle flags are invalid
1588 // as soon as we release any threads after GC. Getting this
1589 // wrong leads to a rare and hard to debug deadlock!
1590
1591 for (i=0; i < n_capabilities; i++) {
1592 gc_threads[i]->idle = idle_cap[i];
1593 capabilities[i]->idle++;
1594 }
1595
1596 // For all capabilities participating in this GC, wait until
1597 // they have stopped mutating and are standing by for GC.
1598 waitForGcThreads(cap);
1599
1600 #if defined(THREADED_RTS)
1601 // Stable point where we can do a global check on our spark counters
1602 ASSERT(checkSparkCountInvariant());
1603 #endif
1604 }
1605
1606 #endif
1607
1608 IF_DEBUG(scheduler, printAllThreads());
1609
1610 delete_threads_and_gc:
1611 /*
1612 * We now have all the capabilities; if we're in an interrupting
1613 * state, then we should take the opportunity to delete all the
1614 * threads in the system.
1615 */
1616 if (sched_state == SCHED_INTERRUPTING) {
1617 deleteAllThreads(cap);
1618 #if defined(THREADED_RTS)
1619 // Discard all the sparks from every Capability. Why?
1620 // They'll probably be GC'd anyway since we've killed all the
1621 // threads. It just avoids the GC having to do any work to
1622 // figure out that any remaining sparks are garbage.
1623 for (i = 0; i < n_capabilities; i++) {
1624 capabilities[i]->spark_stats.gcd +=
1625 sparkPoolSize(capabilities[i]->sparks);
1626 // No race here since all Caps are stopped.
1627 discardSparksCap(capabilities[i]);
1628 }
1629 #endif
1630 sched_state = SCHED_SHUTTING_DOWN;
1631 }
1632
1633 /*
1634 * When there are disabled capabilities, we want to migrate any
1635 * threads away from them. Normally this happens in the
1636 * scheduler's loop, but only for unbound threads - it's really
1637 * hard for a bound thread to migrate itself. So we have another
1638 * go here.
1639 */
1640 #if defined(THREADED_RTS)
1641 for (i = enabled_capabilities; i < n_capabilities; i++) {
1642 Capability *tmp_cap, *dest_cap;
1643 tmp_cap = capabilities[i];
1644 ASSERT(tmp_cap->disabled);
1645 if (i != cap->no) {
1646 dest_cap = capabilities[i % enabled_capabilities];
1647 while (!emptyRunQueue(tmp_cap)) {
1648 tso = popRunQueue(tmp_cap);
1649 migrateThread(tmp_cap, tso, dest_cap);
1650 if (tso->bound) {
1651 traceTaskMigrate(tso->bound->task,
1652 tso->bound->task->cap,
1653 dest_cap);
1654 tso->bound->task->cap = dest_cap;
1655 }
1656 }
1657 }
1658 }
1659 #endif
1660
1661 #if defined(THREADED_RTS)
1662 // reset pending_sync *before* GC, so that when the GC threads
1663 // emerge they don't immediately re-enter the GC.
1664 pending_sync = 0;
1665 GarbageCollect(collect_gen, heap_census, gc_type, cap);
1666 #else
1667 GarbageCollect(collect_gen, heap_census, 0, cap);
1668 #endif
1669
1670 traceSparkCounters(cap);
1671
1672 switch (recent_activity) {
1673 case ACTIVITY_INACTIVE:
1674 if (force_major) {
1675 // We are doing a GC because the system has been idle for a
1676 // timeslice and we need to check for deadlock. Record the
1677 // fact that we've done a GC and turn off the timer signal;
1678 // it will get re-enabled if we run any threads after the GC.
1679 recent_activity = ACTIVITY_DONE_GC;
1680 #ifndef PROFILING
1681 stopTimer();
1682 #endif
1683 break;
1684 }
1685 // fall through...
1686
1687 case ACTIVITY_MAYBE_NO:
1688 // the GC might have taken long enough for the timer to set
1689 // recent_activity = ACTIVITY_MAYBE_NO or ACTIVITY_INACTIVE,
1690 // but we aren't necessarily deadlocked:
1691 recent_activity = ACTIVITY_YES;
1692 break;
1693
1694 case ACTIVITY_DONE_GC:
1695 // If we are actually active, the scheduler will reset the
1696 // recent_activity flag and re-enable the timer.
1697 break;
1698 }
1699
1700 #if defined(THREADED_RTS)
1701 // Stable point where we can do a global check on our spark counters
1702 ASSERT(checkSparkCountInvariant());
1703 #endif
1704
1705 // The heap census itself is done during GarbageCollect().
1706 if (heap_census) {
1707 performHeapProfile = rtsFalse;
1708 }
1709
1710 #if defined(THREADED_RTS)
1711
1712 // If n_capabilities has changed during GC, we're in trouble.
1713 ASSERT(n_capabilities == old_n_capabilities);
1714
1715 if (gc_type == SYNC_GC_PAR)
1716 {
1717 releaseGCThreads(cap);
1718 for (i = 0; i < n_capabilities; i++) {
1719 if (i != cap->no) {
1720 if (idle_cap[i]) {
1721 ASSERT(capabilities[i]->running_task == task);
1722 task->cap = capabilities[i];
1723 releaseCapability(capabilities[i]);
1724 } else {
1725 ASSERT(capabilities[i]->running_task != task);
1726 }
1727 }
1728 }
1729 task->cap = cap;
1730 }
1731 #endif
1732
1733 if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1734 // GC set the heap_overflow flag, so we should proceed with
1735 // an orderly shutdown now. Ultimately we want the main
1736 // thread to return to its caller with HeapExhausted, at which
1737 // point the caller should call hs_exit(). The first step is
1738 // to delete all the threads.
1739 //
1740 // Another way to do this would be to raise an exception in
1741 // the main thread, which we really should do because it gives
1742 // the program a chance to clean up. But how do we find the
1743 // main thread? It should presumably be the same one that
1744 // gets ^C exceptions, but that's all done on the Haskell side
1745 // (GHC.TopHandler).
1746 sched_state = SCHED_INTERRUPTING;
1747 goto delete_threads_and_gc;
1748 }
1749
1750 #ifdef SPARKBALANCE
1751 /* JB
1752 Once we are all together... this would be the place to balance all
1753 spark pools. No concurrent stealing or adding of new sparks can
1754 occur. Should be defined in Sparks.c. */
1755 balanceSparkPoolsCaps(n_capabilities, capabilities);
1756 #endif
1757
1758 #if defined(THREADED_RTS)
1759 if (gc_type == SYNC_GC_SEQ) {
1760 // release our stash of capabilities.
1761 releaseAllCapabilities(n_capabilities, cap, task);
1762 }
1763 #endif
1764
1765 return;
1766 }
1767
1768 /* ---------------------------------------------------------------------------
1769 * Singleton fork(). Do not copy any running threads.
1770 * ------------------------------------------------------------------------- */
1771
1772 pid_t
1773 forkProcess(HsStablePtr *entry
1774 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1775 STG_UNUSED
1776 #endif
1777 )
1778 {
1779 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1780 pid_t pid;
1781 StgTSO* t,*next;
1782 Capability *cap;
1783 nat g;
1784 Task *task = NULL;
1785 nat i;
1786 #ifdef THREADED_RTS
1787 nat sync;
1788 #endif
1789
1790 debugTrace(DEBUG_sched, "forking!");
1791
1792 task = newBoundTask();
1793
1794 cap = NULL;
1795 waitForReturnCapability(&cap, task);
1796
1797 #ifdef THREADED_RTS
1798 do {
1799 sync = requestSync(&cap, task, SYNC_OTHER);
1800 } while (sync);
1801
1802 acquireAllCapabilities(cap,task);
1803
1804 pending_sync = 0;
1805 #endif
1806
1807 // no funny business: hold locks while we fork, otherwise if some
1808 // other thread is holding a lock when the fork happens, the data
1809 // structure protected by the lock will forever be in an
1810 // inconsistent state in the child. See also #1391.
1811 ACQUIRE_LOCK(&sched_mutex);
1812 ACQUIRE_LOCK(&sm_mutex);
1813 ACQUIRE_LOCK(&stable_mutex);
1814 ACQUIRE_LOCK(&task->lock);
1815
1816 for (i=0; i < n_capabilities; i++) {
1817 ACQUIRE_LOCK(&capabilities[i]->lock);
1818 }
1819
1820 #ifdef THREADED_RTS
1821 ACQUIRE_LOCK(&all_tasks_mutex);
1822 #endif
1823
1824 stopTimer(); // See #4074
1825
1826 #if defined(TRACING)
1827 flushEventLog(); // so that child won't inherit dirty file buffers
1828 #endif
1829
1830 pid = fork();
1831
1832 if (pid) { // parent
1833
1834 startTimer(); // #4074
1835
1836 RELEASE_LOCK(&sched_mutex);
1837 RELEASE_LOCK(&sm_mutex);
1838 RELEASE_LOCK(&stable_mutex);
1839 RELEASE_LOCK(&task->lock);
1840
1841 for (i=0; i < n_capabilities; i++) {
1842 releaseCapability_(capabilities[i],rtsFalse);
1843 RELEASE_LOCK(&capabilities[i]->lock);
1844 }
1845
1846 #ifdef THREADED_RTS
1847 RELEASE_LOCK(&all_tasks_mutex);
1848 #endif
1849
1850 boundTaskExiting(task);
1851
1852 // just return the pid
1853 return pid;
1854
1855 } else { // child
1856
1857 #if defined(THREADED_RTS)
1858 initMutex(&sched_mutex);
1859 initMutex(&sm_mutex);
1860 initMutex(&stable_mutex);
1861 initMutex(&task->lock);
1862
1863 for (i=0; i < n_capabilities; i++) {
1864 initMutex(&capabilities[i]->lock);
1865 }
1866
1867 initMutex(&all_tasks_mutex);
1868 #endif
1869
1870 #ifdef TRACING
1871 resetTracing();
1872 #endif
1873
1874 // Now, all OS threads except the thread that forked are
1875 // stopped. We need to stop all Haskell threads, including
1876 // those involved in foreign calls. Also we need to delete
1877 // all Tasks, because they correspond to OS threads that are
1878 // now gone.
1879
1880 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1881 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1882 next = t->global_link;
1883 // don't allow threads to catch the ThreadKilled
1884 // exception, but we do want to raiseAsync() because these
1885 // threads may be evaluating thunks that we need later.
1886 deleteThread_(t->cap,t);
1887
1888 // stop the GC from updating the InCall to point to
1889 // the TSO. This is only necessary because the
1890 // OSThread bound to the TSO has been killed, and
1891 // won't get a chance to exit in the usual way (see
1892 // also scheduleHandleThreadFinished).
1893 t->bound = NULL;
1894 }
1895 }
1896
1897 discardTasksExcept(task);
1898
1899 for (i=0; i < n_capabilities; i++) {
1900 cap = capabilities[i];
1901
1902 // Empty the run queue. It seems tempting to let all the
1903 // killed threads stay on the run queue as zombies to be
1904 // cleaned up later, but some of them may correspond to
1905 // bound threads for which the corresponding Task does not
1906 // exist.
1907 truncateRunQueue(cap);
1908
1909 // Any suspended C-calling Tasks are no more, their OS threads
1910 // don't exist now:
1911 cap->suspended_ccalls = NULL;
1912
1913 #if defined(THREADED_RTS)
1914 // Wipe our spare workers list, they no longer exist. New
1915 // workers will be created if necessary.
1916 cap->spare_workers = NULL;
1917 cap->n_spare_workers = 0;
1918 cap->returning_tasks_hd = NULL;
1919 cap->returning_tasks_tl = NULL;
1920 #endif
1921
1922 // Release all caps except 0, we'll use that for starting
1923 // the IO manager and running the client action below.
1924 if (cap->no != 0) {
1925 task->cap = cap;
1926 releaseCapability(cap);
1927 }
1928 }
1929 cap = capabilities[0];
1930 task->cap = cap;
1931
1932 // Empty the threads lists. Otherwise, the garbage
1933 // collector may attempt to resurrect some of these threads.
1934 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1935 generations[g].threads = END_TSO_QUEUE;
1936 }
1937
1938 // On Unix, all timers are reset in the child, so we need to start
1939 // the timer again.
1940 initTimer();
1941 startTimer();
1942
1943 // TODO: need to trace various other things in the child
1944 // like startup event, capabilities, process info etc
1945 traceTaskCreate(task, cap);
1946
1947 #if defined(THREADED_RTS)
1948 ioManagerStartCap(&cap);
1949 #endif
1950
1951 rts_evalStableIO(&cap, entry, NULL); // run the action
1952 rts_checkSchedStatus("forkProcess",cap);
1953
1954 rts_unlock(cap);
1955 shutdownHaskellAndExit(EXIT_SUCCESS, 0 /* !fastExit */);
1956 }
1957 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1958 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1959 #endif
1960 }
1961
1962 /* ---------------------------------------------------------------------------
1963 * Changing the number of Capabilities
1964 *
1965 * Changing the number of Capabilities is very tricky! We can only do
1966 * it with the system fully stopped, so we do a full sync with
1967 * requestSync(SYNC_OTHER) and grab all the capabilities.
1968 *
1969 * Then we resize the appropriate data structures, and update all
1970 * references to the old data structures which have now moved.
1971 * Finally we release the Capabilities we are holding, and start
1972 * worker Tasks on the new Capabilities we created.
1973 *
1974 * ------------------------------------------------------------------------- */
1975
1976 void
1977 setNumCapabilities (nat new_n_capabilities USED_IF_THREADS)
1978 {
1979 #if !defined(THREADED_RTS)
1980 if (new_n_capabilities != 1) {
1981 errorBelch("setNumCapabilities: not supported in the non-threaded RTS");
1982 }
1983 return;
1984 #elif defined(NOSMP)
1985 if (new_n_capabilities != 1) {
1986 errorBelch("setNumCapabilities: not supported on this platform");
1987 }
1988 return;
1989 #else
1990 Task *task;
1991 Capability *cap;
1992 nat sync;
1993 nat n;
1994 Capability *old_capabilities = NULL;
1995 nat old_n_capabilities = n_capabilities;
1996
1997 if (new_n_capabilities == enabled_capabilities) return;
1998
1999 debugTrace(DEBUG_sched, "changing the number of Capabilities from %d to %d",
2000 enabled_capabilities, new_n_capabilities);
2001
2002 cap = rts_lock();
2003 task = cap->running_task;
2004
2005 do {
2006 sync = requestSync(&cap, task, SYNC_OTHER);
2007 } while (sync);
2008
2009 acquireAllCapabilities(cap,task);
2010
2011 pending_sync = 0;
2012
2013 if (new_n_capabilities < enabled_capabilities)
2014 {
2015 // Reducing the number of capabilities: we do not actually
2016 // remove the extra capabilities, we just mark them as
2017 // "disabled". This has the following effects:
2018 //
2019 // - threads on a disabled capability are migrated away by the
2020 // scheduler loop
2021 //
2022 // - disabled capabilities do not participate in GC
2023 // (see scheduleDoGC())
2024 //
2025 // - No spark threads are created on this capability
2026 // (see scheduleActivateSpark())
2027 //
2028 // - We do not attempt to migrate threads *to* a disabled
2029 // capability (see schedulePushWork()).
2030 //
2031 // but in other respects, a disabled capability remains
2032 // alive. Threads may be woken up on a disabled capability,
2033 // but they will be immediately migrated away.
2034 //
2035 // This approach is much easier than trying to actually remove
2036 // the capability; we don't have to worry about GC data
2037 // structures, the nursery, etc.
2038 //
2039 for (n = new_n_capabilities; n < enabled_capabilities; n++) {
2040 capabilities[n]->disabled = rtsTrue;
2041 traceCapDisable(capabilities[n]);
2042 }
2043 enabled_capabilities = new_n_capabilities;
2044 }
2045 else
2046 {
2047 // Increasing the number of enabled capabilities.
2048 //
2049 // enable any disabled capabilities, up to the required number
2050 for (n = enabled_capabilities;
2051 n < new_n_capabilities && n < n_capabilities; n++) {
2052 capabilities[n]->disabled = rtsFalse;
2053 traceCapEnable(capabilities[n]);
2054 }
2055 enabled_capabilities = n;
2056
2057 if (new_n_capabilities > n_capabilities) {
2058 #if defined(TRACING)
2059 // Allocate eventlog buffers for the new capabilities. Note this
2060 // must be done before calling moreCapabilities(), because that
2061 // will emit events about creating the new capabilities and adding
2062 // them to existing capsets.
2063 tracingAddCapapilities(n_capabilities, new_n_capabilities);
2064 #endif
2065
2066 // Resize the capabilities array
2067 // NB. after this, capabilities points somewhere new. Any pointers
2068 // of type (Capability *) are now invalid.
2069 moreCapabilities(n_capabilities, new_n_capabilities);
2070
2071 // Resize and update storage manager data structures
2072 storageAddCapabilities(n_capabilities, new_n_capabilities);
2073 }
2074 }
2075
2076 // update n_capabilities before things start running
2077 if (new_n_capabilities > n_capabilities) {
2078 n_capabilities = enabled_capabilities = new_n_capabilities;
2079 }
2080
2081 // Start worker tasks on the new Capabilities
2082 startWorkerTasks(old_n_capabilities, new_n_capabilities);
2083
2084 // We're done: release the original Capabilities
2085 releaseAllCapabilities(old_n_capabilities, cap,task);
2086
2087 // We can't free the old array until now, because we access it
2088 // while updating pointers in updateCapabilityRefs().
2089 if (old_capabilities) {
2090 stgFree(old_capabilities);
2091 }
2092
2093 // Notify IO manager that the number of capabilities has changed.
2094 rts_evalIO(&cap, ioManagerCapabilitiesChanged_closure, NULL);
2095
2096 rts_unlock(cap);
2097
2098 #endif // THREADED_RTS
2099 }
2100
2101
2102
2103 /* ---------------------------------------------------------------------------
2104 * Delete all the threads in the system
2105 * ------------------------------------------------------------------------- */
2106
2107 static void
2108 deleteAllThreads ( Capability *cap )
2109 {
2110 // NOTE: only safe to call if we own all capabilities.
2111
2112 StgTSO* t, *next;
2113 nat g;
2114
2115 debugTrace(DEBUG_sched,"deleting all threads");
2116 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
2117 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
2118 next = t->global_link;
2119 deleteThread(cap,t);
2120 }
2121 }
2122
2123 // The run queue now contains a bunch of ThreadKilled threads. We
2124 // must not throw these away: the main thread(s) will be in there
2125 // somewhere, and the main scheduler loop has to deal with it.
2126 // Also, the run queue is the only thing keeping these threads from
2127 // being GC'd, and we don't want the "main thread has been GC'd" panic.
2128
2129 #if !defined(THREADED_RTS)
2130 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
2131 ASSERT(sleeping_queue == END_TSO_QUEUE);
2132 #endif
2133 }
2134
2135 /* -----------------------------------------------------------------------------
2136 Managing the suspended_ccalls list.
2137 Locks required: sched_mutex
2138 -------------------------------------------------------------------------- */
2139
2140 STATIC_INLINE void
2141 suspendTask (Capability *cap, Task *task)
2142 {
2143 InCall *incall;
2144
2145 incall = task->incall;
2146 ASSERT(incall->next == NULL && incall->prev == NULL);
2147 incall->next = cap->suspended_ccalls;
2148 incall->prev = NULL;
2149 if (cap->suspended_ccalls) {
2150 cap->suspended_ccalls->prev = incall;
2151 }
2152 cap->suspended_ccalls = incall;
2153 }
2154
2155 STATIC_INLINE void
2156 recoverSuspendedTask (Capability *cap, Task *task)
2157 {
2158 InCall *incall;
2159
2160 incall = task->incall;
2161 if (incall->prev) {
2162 incall->prev->next = incall->next;
2163 } else {
2164 ASSERT(cap->suspended_ccalls == incall);
2165 cap->suspended_ccalls = incall->next;
2166 }
2167 if (incall->next) {
2168 incall->next->prev = incall->prev;
2169 }
2170 incall->next = incall->prev = NULL;
2171 }
2172
2173 /* ---------------------------------------------------------------------------
2174 * Suspending & resuming Haskell threads.
2175 *
2176 * When making a "safe" call to C (aka _ccall_GC), the task gives back
2177 * its capability before calling the C function. This allows another
2178 * task to pick up the capability and carry on running Haskell
2179 * threads. It also means that if the C call blocks, it won't lock
2180 * the whole system.
2181 *
2182 * The Haskell thread making the C call is put to sleep for the
2183 * duration of the call, on the suspended_ccalling_threads queue. We
2184 * give out a token to the task, which it can use to resume the thread
2185 * on return from the C function.
2186 *
2187 * If this is an interruptible C call, this means that the FFI call may be
2188 * unceremoniously terminated and should be scheduled on an
2189 * unbound worker thread.
2190 * ------------------------------------------------------------------------- */
2191
2192 void *
2193 suspendThread (StgRegTable *reg, rtsBool interruptible)
2194 {
2195 Capability *cap;
2196 int saved_errno;
2197 StgTSO *tso;
2198 Task *task;
2199 #if mingw32_HOST_OS
2200 StgWord32 saved_winerror;
2201 #endif
2202
2203 saved_errno = errno;
2204 #if mingw32_HOST_OS
2205 saved_winerror = GetLastError();
2206 #endif
2207
2208 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
2209 */
2210 cap = regTableToCapability(reg);
2211
2212 task = cap->running_task;
2213 tso = cap->r.rCurrentTSO;
2214
2215 traceEventStopThread(cap, tso, THREAD_SUSPENDED_FOREIGN_CALL, 0);
2216
2217 // XXX this might not be necessary --SDM
2218 tso->what_next = ThreadRunGHC;
2219
2220 threadPaused(cap,tso);
2221
2222 if (interruptible) {
2223 tso->why_blocked = BlockedOnCCall_Interruptible;
2224 } else {
2225 tso->why_blocked = BlockedOnCCall;
2226 }
2227
2228 // Hand back capability
2229 task->incall->suspended_tso = tso;
2230 task->incall->suspended_cap = cap;
2231
2232 // Otherwise allocate() will write to invalid memory.
2233 cap->r.rCurrentTSO = NULL;
2234
2235 ACQUIRE_LOCK(&cap->lock);
2236
2237 suspendTask(cap,task);
2238 cap->in_haskell = rtsFalse;
2239 releaseCapability_(cap,rtsFalse);
2240
2241 RELEASE_LOCK(&cap->lock);
2242
2243 errno = saved_errno;
2244 #if mingw32_HOST_OS
2245 SetLastError(saved_winerror);
2246 #endif
2247 return task;
2248 }
2249
2250 StgRegTable *
2251 resumeThread (void *task_)
2252 {
2253 StgTSO *tso;
2254 InCall *incall;
2255 Capability *cap;
2256 Task *task = task_;
2257 int saved_errno;
2258 #if mingw32_HOST_OS
2259 StgWord32 saved_winerror;
2260 #endif
2261
2262 saved_errno = errno;
2263 #if mingw32_HOST_OS
2264 saved_winerror = GetLastError();
2265 #endif
2266
2267 incall = task->incall;
2268 cap = incall->suspended_cap;
2269 task->cap = cap;
2270
2271 // Wait for permission to re-enter the RTS with the result.
2272 waitForReturnCapability(&cap,task);
2273 // we might be on a different capability now... but if so, our
2274 // entry on the suspended_ccalls list will also have been
2275 // migrated.
2276
2277 // Remove the thread from the suspended list
2278 recoverSuspendedTask(cap,task);
2279
2280 tso = incall->suspended_tso;
2281 incall->suspended_tso = NULL;
2282 incall->suspended_cap = NULL;
2283 tso->_link = END_TSO_QUEUE; // no write barrier reqd
2284
2285 traceEventRunThread(cap, tso);
2286
2287 /* Reset blocking status */
2288 tso->why_blocked = NotBlocked;
2289
2290 if ((tso->flags & TSO_BLOCKEX) == 0) {
2291 // avoid locking the TSO if we don't have to
2292 if (tso->blocked_exceptions != END_BLOCKED_EXCEPTIONS_QUEUE) {
2293 maybePerformBlockedException(cap,tso);
2294 }
2295 }
2296
2297 cap->r.rCurrentTSO = tso;
2298 cap->in_haskell = rtsTrue;
2299 errno = saved_errno;
2300 #if mingw32_HOST_OS
2301 SetLastError(saved_winerror);
2302 #endif
2303
2304 /* We might have GC'd, mark the TSO dirty again */
2305 dirty_TSO(cap,tso);
2306 dirty_STACK(cap,tso->stackobj);
2307
2308 IF_DEBUG(sanity, checkTSO(tso));
2309
2310 return &cap->r;
2311 }
2312
2313 /* ---------------------------------------------------------------------------
2314 * scheduleThread()
2315 *
2316 * scheduleThread puts a thread on the end of the runnable queue.
2317 * This will usually be done immediately after a thread is created.
2318 * The caller of scheduleThread must create the thread using e.g.
2319 * createThread and push an appropriate closure
2320 * on this thread's stack before the scheduler is invoked.
2321 * ------------------------------------------------------------------------ */
2322
2323 void
2324 scheduleThread(Capability *cap, StgTSO *tso)
2325 {
2326 // The thread goes at the *end* of the run-queue, to avoid possible
2327 // starvation of any threads already on the queue.
2328 appendToRunQueue(cap,tso);
2329 }
2330
2331 void
2332 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
2333 {
2334 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
2335 // move this thread from now on.
2336 #if defined(THREADED_RTS)
2337 cpu %= enabled_capabilities;
2338 if (cpu == cap->no) {
2339 appendToRunQueue(cap,tso);
2340 } else {
2341 migrateThread(cap, tso, capabilities[cpu]);
2342 }
2343 #else
2344 appendToRunQueue(cap,tso);
2345 #endif
2346 }
2347
2348 void
2349 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability **pcap)
2350 {
2351 Task *task;
2352 DEBUG_ONLY( StgThreadID id );
2353 Capability *cap;
2354
2355 cap = *pcap;
2356
2357 // We already created/initialised the Task
2358 task = cap->running_task;
2359
2360 // This TSO is now a bound thread; make the Task and TSO
2361 // point to each other.
2362 tso->bound = task->incall;
2363 tso->cap = cap;
2364
2365 task->incall->tso = tso;
2366 task->incall->ret = ret;
2367 task->incall->stat = NoStatus;
2368
2369 appendToRunQueue(cap,tso);
2370
2371 DEBUG_ONLY( id = tso->id );
2372 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)id);
2373
2374 cap = schedule(cap,task);
2375
2376 ASSERT(task->incall->stat != NoStatus);
2377 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
2378
2379 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)id);
2380 *pcap = cap;
2381 }
2382
2383 /* ----------------------------------------------------------------------------
2384 * Starting Tasks
2385 * ------------------------------------------------------------------------- */
2386
2387 #if defined(THREADED_RTS)
2388 void scheduleWorker (Capability *cap, Task *task)
2389 {
2390 // schedule() runs without a lock.
2391 cap = schedule(cap,task);
2392
2393 // On exit from schedule(), we have a Capability, but possibly not
2394 // the same one we started with.
2395
2396 // During shutdown, the requirement is that after all the
2397 // Capabilities are shut down, all workers that are shutting down
2398 // have finished workerTaskStop(). This is why we hold on to
2399 // cap->lock until we've finished workerTaskStop() below.
2400 //
2401 // There may be workers still involved in foreign calls; those
2402 // will just block in waitForReturnCapability() because the
2403 // Capability has been shut down.
2404 //
2405 ACQUIRE_LOCK(&cap->lock);
2406 releaseCapability_(cap,rtsFalse);
2407 workerTaskStop(task);
2408 RELEASE_LOCK(&cap->lock);
2409 }
2410 #endif
2411
2412 /* ---------------------------------------------------------------------------
2413 * Start new worker tasks on Capabilities from--to
2414 * -------------------------------------------------------------------------- */
2415
2416 static void
2417 startWorkerTasks (nat from USED_IF_THREADS, nat to USED_IF_THREADS)
2418 {
2419 #if defined(THREADED_RTS)
2420 nat i;
2421 Capability *cap;
2422
2423 for (i = from; i < to; i++) {
2424 cap = capabilities[i];
2425 ACQUIRE_LOCK(&cap->lock);
2426 startWorkerTask(cap);
2427 RELEASE_LOCK(&cap->lock);
2428 }
2429 #endif
2430 }
2431
2432 /* ---------------------------------------------------------------------------
2433 * initScheduler()
2434 *
2435 * Initialise the scheduler. This resets all the queues - if the
2436 * queues contained any threads, they'll be garbage collected at the
2437 * next pass.
2438 *
2439 * ------------------------------------------------------------------------ */
2440
2441 void
2442 initScheduler(void)
2443 {
2444 #if !defined(THREADED_RTS)
2445 blocked_queue_hd = END_TSO_QUEUE;
2446 blocked_queue_tl = END_TSO_QUEUE;
2447 sleeping_queue = END_TSO_QUEUE;
2448 #endif
2449
2450 sched_state = SCHED_RUNNING;
2451 recent_activity = ACTIVITY_YES;
2452
2453 #if defined(THREADED_RTS)
2454 /* Initialise the mutex and condition variables used by
2455 * the scheduler. */
2456 initMutex(&sched_mutex);
2457 #endif
2458
2459 ACQUIRE_LOCK(&sched_mutex);
2460
2461 /* A capability holds the state a native thread needs in
2462 * order to execute STG code. At least one capability is
2463 * floating around (only THREADED_RTS builds have more than one).
2464 */
2465 initCapabilities();
2466
2467 initTaskManager();
2468
2469 /*
2470 * Eagerly start one worker to run each Capability, except for
2471 * Capability 0. The idea is that we're probably going to start a
2472 * bound thread on Capability 0 pretty soon, so we don't want a
2473 * worker task hogging it.
2474 */
2475 startWorkerTasks(1, n_capabilities);
2476
2477 RELEASE_LOCK(&sched_mutex);
2478
2479 }
2480
2481 void
2482 exitScheduler (rtsBool wait_foreign USED_IF_THREADS)
2483 /* see Capability.c, shutdownCapability() */
2484 {
2485 Task *task = NULL;
2486
2487 task = newBoundTask();
2488
2489 // If we haven't killed all the threads yet, do it now.
2490 if (sched_state < SCHED_SHUTTING_DOWN) {
2491 sched_state = SCHED_INTERRUPTING;
2492 Capability *cap = task->cap;
2493 waitForReturnCapability(&cap,task);
2494 scheduleDoGC(&cap,task,rtsTrue);
2495 ASSERT(task->incall->tso == NULL);
2496 releaseCapability(cap);
2497 }
2498 sched_state = SCHED_SHUTTING_DOWN;
2499
2500 shutdownCapabilities(task, wait_foreign);
2501
2502 // debugBelch("n_failed_trygrab_idles = %d, n_idle_caps = %d\n",
2503 // n_failed_trygrab_idles, n_idle_caps);
2504
2505 boundTaskExiting(task);
2506 }
2507
2508 void
2509 freeScheduler( void )
2510 {
2511 nat still_running;
2512
2513 ACQUIRE_LOCK(&sched_mutex);
2514 still_running = freeTaskManager();
2515 // We can only free the Capabilities if there are no Tasks still
2516 // running. We might have a Task about to return from a foreign
2517 // call into waitForReturnCapability(), for example (actually,
2518 // this should be the *only* thing that a still-running Task can
2519 // do at this point, and it will block waiting for the
2520 // Capability).
2521 if (still_running == 0) {
2522 freeCapabilities();
2523 }
2524 RELEASE_LOCK(&sched_mutex);
2525 #if defined(THREADED_RTS)
2526 closeMutex(&sched_mutex);
2527 #endif
2528 }
2529
2530 void markScheduler (evac_fn evac USED_IF_NOT_THREADS,
2531 void *user USED_IF_NOT_THREADS)
2532 {
2533 #if !defined(THREADED_RTS)
2534 evac(user, (StgClosure **)(void *)&blocked_queue_hd);
2535 evac(user, (StgClosure **)(void *)&blocked_queue_tl);
2536 evac(user, (StgClosure **)(void *)&sleeping_queue);
2537 #endif
2538 }
2539
2540 /* -----------------------------------------------------------------------------
2541 performGC
2542
2543 This is the interface to the garbage collector from Haskell land.
2544 We provide this so that external C code can allocate and garbage
2545 collect when called from Haskell via _ccall_GC.
2546 -------------------------------------------------------------------------- */
2547
2548 static void
2549 performGC_(rtsBool force_major)
2550 {
2551 Task *task;
2552 Capability *cap = NULL;
2553
2554 // We must grab a new Task here, because the existing Task may be
2555 // associated with a particular Capability, and chained onto the
2556 // suspended_ccalls queue.
2557 task = newBoundTask();
2558
2559 // TODO: do we need to traceTask*() here?
2560
2561 waitForReturnCapability(&cap,task);
2562 scheduleDoGC(&cap,task,force_major);
2563 releaseCapability(cap);
2564 boundTaskExiting(task);
2565 }
2566
2567 void
2568 performGC(void)
2569 {
2570 performGC_(rtsFalse);
2571 }
2572
2573 void
2574 performMajorGC(void)
2575 {
2576 performGC_(rtsTrue);
2577 }
2578
2579 /* ---------------------------------------------------------------------------
2580 Interrupt execution
2581 - usually called inside a signal handler so it mustn't do anything fancy.
2582 ------------------------------------------------------------------------ */
2583
2584 void
2585 interruptStgRts(void)
2586 {
2587 sched_state = SCHED_INTERRUPTING;
2588 interruptAllCapabilities();
2589 #if defined(THREADED_RTS)
2590 wakeUpRts();
2591 #endif
2592 }
2593
2594 /* -----------------------------------------------------------------------------
2595 Wake up the RTS
2596
2597 This function causes at least one OS thread to wake up and run the
2598 scheduler loop. It is invoked when the RTS might be deadlocked, or
2599 an external event has arrived that may need servicing (eg. a
2600 keyboard interrupt).
2601
2602 In the single-threaded RTS we don't do anything here; we only have
2603 one thread anyway, and the event that caused us to want to wake up
2604 will have interrupted any blocking system call in progress anyway.
2605 -------------------------------------------------------------------------- */
2606
2607 #if defined(THREADED_RTS)
2608 void wakeUpRts(void)
2609 {
2610 // This forces the IO Manager thread to wakeup, which will
2611 // in turn ensure that some OS thread wakes up and runs the
2612 // scheduler loop, which will cause a GC and deadlock check.
2613 ioManagerWakeup();
2614 }
2615 #endif
2616
2617 /* -----------------------------------------------------------------------------
2618 Deleting threads
2619
2620 This is used for interruption (^C) and forking, and corresponds to
2621 raising an exception but without letting the thread catch the
2622 exception.
2623 -------------------------------------------------------------------------- */
2624
2625 static void
2626 deleteThread (Capability *cap STG_UNUSED, StgTSO *tso)
2627 {
2628 // NOTE: must only be called on a TSO that we have exclusive
2629 // access to, because we will call throwToSingleThreaded() below.
2630 // The TSO must be on the run queue of the Capability we own, or
2631 // we must own all Capabilities.
2632
2633 if (tso->why_blocked != BlockedOnCCall &&
2634 tso->why_blocked != BlockedOnCCall_Interruptible) {
2635 throwToSingleThreaded(tso->cap,tso,NULL);
2636 }
2637 }
2638
2639 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2640 static void
2641 deleteThread_(Capability *cap, StgTSO *tso)
2642 { // for forkProcess only:
2643 // like deleteThread(), but we delete threads in foreign calls, too.
2644
2645 if (tso->why_blocked == BlockedOnCCall ||
2646 tso->why_blocked == BlockedOnCCall_Interruptible) {
2647 tso->what_next = ThreadKilled;
2648 appendToRunQueue(tso->cap, tso);
2649 } else {
2650 deleteThread(cap,tso);
2651 }
2652 }
2653 #endif
2654
2655 /* -----------------------------------------------------------------------------
2656 raiseExceptionHelper
2657
2658 This function is called by the raise# primitve, just so that we can
2659 move some of the tricky bits of raising an exception from C-- into
2660 C. Who knows, it might be a useful re-useable thing here too.
2661 -------------------------------------------------------------------------- */
2662
2663 StgWord
2664 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2665 {
2666 Capability *cap = regTableToCapability(reg);
2667 StgThunk *raise_closure = NULL;
2668 StgPtr p, next;
2669 StgRetInfoTable *info;
2670 //
2671 // This closure represents the expression 'raise# E' where E
2672 // is the exception raise. It is used to overwrite all the
2673 // thunks which are currently under evaluataion.
2674 //
2675
2676 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2677 // LDV profiling: stg_raise_info has THUNK as its closure
2678 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2679 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2680 // 1 does not cause any problem unless profiling is performed.
2681 // However, when LDV profiling goes on, we need to linearly scan
2682 // small object pool, where raise_closure is stored, so we should
2683 // use MIN_UPD_SIZE.
2684 //
2685 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2686 // sizeofW(StgClosure)+1);
2687 //
2688
2689 //
2690 // Walk up the stack, looking for the catch frame. On the way,
2691 // we update any closures pointed to from update frames with the
2692 // raise closure that we just built.
2693 //
2694 p = tso->stackobj->sp;
2695 while(1) {
2696 info = get_ret_itbl((StgClosure *)p);
2697 next = p + stack_frame_sizeW((StgClosure *)p);
2698 switch (info->i.type) {
2699
2700 case UPDATE_FRAME:
2701 // Only create raise_closure if we need to.
2702 if (raise_closure == NULL) {
2703 raise_closure =
2704 (StgThunk *)allocate(cap,sizeofW(StgThunk)+1);
2705 SET_HDR(raise_closure, &stg_raise_info, cap->r.rCCCS);
2706 raise_closure->payload[0] = exception;
2707 }
2708 updateThunk(cap, tso, ((StgUpdateFrame *)p)->updatee,
2709 (StgClosure *)raise_closure);
2710 p = next;
2711 continue;
2712
2713 case ATOMICALLY_FRAME:
2714 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2715 tso->stackobj->sp = p;
2716 return ATOMICALLY_FRAME;
2717
2718 case CATCH_FRAME:
2719 tso->stackobj->sp = p;
2720 return CATCH_FRAME;
2721
2722 case CATCH_STM_FRAME:
2723 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2724 tso->stackobj->sp = p;
2725 return CATCH_STM_FRAME;
2726
2727 case UNDERFLOW_FRAME:
2728 tso->stackobj->sp = p;
2729 threadStackUnderflow(cap,tso);
2730 p = tso->stackobj->sp;
2731 continue;
2732
2733 case STOP_FRAME:
2734 tso->stackobj->sp = p;
2735 return STOP_FRAME;
2736
2737 case CATCH_RETRY_FRAME: {
2738 StgTRecHeader *trec = tso -> trec;
2739 StgTRecHeader *outer = trec -> enclosing_trec;
2740 debugTrace(DEBUG_stm,
2741 "found CATCH_RETRY_FRAME at %p during raise", p);
2742 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2743 stmAbortTransaction(cap, trec);
2744 stmFreeAbortedTRec(cap, trec);
2745 tso -> trec = outer;
2746 p = next;
2747 continue;
2748 }
2749
2750 default:
2751 p = next;
2752 continue;
2753 }
2754 }
2755 }
2756
2757
2758 /* -----------------------------------------------------------------------------
2759 findRetryFrameHelper
2760
2761 This function is called by the retry# primitive. It traverses the stack
2762 leaving tso->sp referring to the frame which should handle the retry.
2763
2764 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2765 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2766
2767 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2768 create) because retries are not considered to be exceptions, despite the
2769 similar implementation.
2770
2771 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2772 not be created within memory transactions.
2773 -------------------------------------------------------------------------- */
2774
2775 StgWord
2776 findRetryFrameHelper (Capability *cap, StgTSO *tso)
2777 {
2778 StgPtr p, next;
2779 StgRetInfoTable *info;
2780
2781 p = tso->stackobj->sp;
2782 while (1) {
2783 info = get_ret_itbl((StgClosure *)p);
2784 next = p + stack_frame_sizeW((StgClosure *)p);
2785 switch (info->i.type) {
2786
2787 case ATOMICALLY_FRAME:
2788 debugTrace(DEBUG_stm,
2789 "found ATOMICALLY_FRAME at %p during retry", p);
2790 tso->stackobj->sp = p;
2791 return ATOMICALLY_FRAME;
2792
2793 case CATCH_RETRY_FRAME:
2794 debugTrace(DEBUG_stm,
2795 "found CATCH_RETRY_FRAME at %p during retry", p);
2796 tso->stackobj->sp = p;
2797 return CATCH_RETRY_FRAME;
2798
2799 case CATCH_STM_FRAME: {
2800 StgTRecHeader *trec = tso -> trec;
2801 StgTRecHeader *outer = trec -> enclosing_trec;
2802 debugTrace(DEBUG_stm,
2803 "found CATCH_STM_FRAME at %p during retry", p);
2804 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2805 stmAbortTransaction(cap, trec);
2806 stmFreeAbortedTRec(cap, trec);
2807 tso -> trec = outer;
2808 p = next;
2809 continue;
2810 }
2811
2812 case UNDERFLOW_FRAME:
2813 tso->stackobj->sp = p;
2814 threadStackUnderflow(cap,tso);
2815 p = tso->stackobj->sp;
2816 continue;
2817
2818 default:
2819 ASSERT(info->i.type != CATCH_FRAME);
2820 ASSERT(info->i.type != STOP_FRAME);
2821 p = next;
2822 continue;
2823 }
2824 }
2825 }
2826
2827 /* -----------------------------------------------------------------------------
2828 resurrectThreads is called after garbage collection on the list of
2829 threads found to be garbage. Each of these threads will be woken
2830 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2831 on an MVar, or NonTermination if the thread was blocked on a Black
2832 Hole.
2833
2834 Locks: assumes we hold *all* the capabilities.
2835 -------------------------------------------------------------------------- */
2836
2837 void
2838 resurrectThreads (StgTSO *threads)
2839 {
2840 StgTSO *tso, *next;
2841 Capability *cap;
2842 generation *gen;
2843
2844 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2845 next = tso->global_link;
2846
2847 gen = Bdescr((P_)tso)->gen;
2848 tso->global_link = gen->threads;
2849 gen->threads = tso;
2850
2851 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2852
2853 // Wake up the thread on the Capability it was last on
2854 cap = tso->cap;
2855
2856 switch (tso->why_blocked) {
2857 case BlockedOnMVar:
2858 case BlockedOnMVarRead:
2859 /* Called by GC - sched_mutex lock is currently held. */
2860 throwToSingleThreaded(cap, tso,
2861 (StgClosure *)blockedIndefinitelyOnMVar_closure);
2862 break;
2863 case BlockedOnBlackHole:
2864 throwToSingleThreaded(cap, tso,
2865 (StgClosure *)nonTermination_closure);
2866 break;
2867 case BlockedOnSTM:
2868 throwToSingleThreaded(cap, tso,
2869 (StgClosure *)blockedIndefinitelyOnSTM_closure);
2870 break;
2871 case NotBlocked:
2872 /* This might happen if the thread was blocked on a black hole
2873 * belonging to a thread that we've just woken up (raiseAsync
2874 * can wake up threads, remember...).
2875 */
2876 continue;
2877 case BlockedOnMsgThrowTo:
2878 // This can happen if the target is masking, blocks on a
2879 // black hole, and then is found to be unreachable. In
2880 // this case, we want to let the target wake up and carry
2881 // on, and do nothing to this thread.
2882 continue;
2883 default:
2884 barf("resurrectThreads: thread blocked in a strange way: %d",
2885 tso->why_blocked);
2886 }
2887 }
2888 }