Fix a bug introduced with allocation counters
[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 infinite loop
1129 // if the nursery has only one block.
1130
1131 bd = allocGroup_lock(blocks);
1132 cap->r.rNursery->n_blocks += blocks;
1133
1134 // link the new group into the list
1135 bd->link = cap->r.rCurrentNursery;
1136 bd->u.back = cap->r.rCurrentNursery->u.back;
1137 if (cap->r.rCurrentNursery->u.back != NULL) {
1138 cap->r.rCurrentNursery->u.back->link = bd;
1139 } else {
1140 cap->r.rNursery->blocks = bd;
1141 }
1142 cap->r.rCurrentNursery->u.back = bd;
1143
1144 // initialise it as a nursery block. We initialise the
1145 // step, gen_no, and flags field of *every* sub-block in
1146 // this large block, because this is easier than making
1147 // sure that we always find the block head of a large
1148 // block whenever we call Bdescr() (eg. evacuate() and
1149 // isAlive() in the GC would both have to do this, at
1150 // least).
1151 {
1152 bdescr *x;
1153 for (x = bd; x < bd + blocks; x++) {
1154 initBdescr(x,g0,g0);
1155 x->free = x->start;
1156 x->flags = 0;
1157 }
1158 }
1159
1160 // This assert can be a killer if the app is doing lots
1161 // of large block allocations.
1162 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
1163
1164 // now update the nursery to point to the new block
1165 cap->r.rCurrentNursery = bd;
1166
1167 // we might be unlucky and have another thread get on the
1168 // run queue before us and steal the large block, but in that
1169 // case the thread will just end up requesting another large
1170 // block.
1171 pushOnRunQueue(cap,t);
1172 return rtsFalse; /* not actually GC'ing */
1173 }
1174 }
1175
1176 if (cap->r.rHpLim == NULL || cap->context_switch) {
1177 // Sometimes we miss a context switch, e.g. when calling
1178 // primitives in a tight loop, MAYBE_GC() doesn't check the
1179 // context switch flag, and we end up waiting for a GC.
1180 // See #1984, and concurrent/should_run/1984
1181 cap->context_switch = 0;
1182 appendToRunQueue(cap,t);
1183 } else {
1184 pushOnRunQueue(cap,t);
1185 }
1186 return rtsTrue;
1187 /* actual GC is done at the end of the while loop in schedule() */
1188 }
1189
1190 /* -----------------------------------------------------------------------------
1191 * Handle a thread that returned to the scheduler with ThreadYielding
1192 * -------------------------------------------------------------------------- */
1193
1194 static rtsBool
1195 scheduleHandleYield( Capability *cap, StgTSO *t, nat prev_what_next )
1196 {
1197 /* put the thread back on the run queue. Then, if we're ready to
1198 * GC, check whether this is the last task to stop. If so, wake
1199 * up the GC thread. getThread will block during a GC until the
1200 * GC is finished.
1201 */
1202
1203 ASSERT(t->_link == END_TSO_QUEUE);
1204
1205 // Shortcut if we're just switching evaluators: don't bother
1206 // doing stack squeezing (which can be expensive), just run the
1207 // thread.
1208 if (cap->context_switch == 0 && t->what_next != prev_what_next) {
1209 debugTrace(DEBUG_sched,
1210 "--<< thread %ld (%s) stopped to switch evaluators",
1211 (long)t->id, what_next_strs[t->what_next]);
1212 return rtsTrue;
1213 }
1214
1215 // Reset the context switch flag. We don't do this just before
1216 // running the thread, because that would mean we would lose ticks
1217 // during GC, which can lead to unfair scheduling (a thread hogs
1218 // the CPU because the tick always arrives during GC). This way
1219 // penalises threads that do a lot of allocation, but that seems
1220 // better than the alternative.
1221 if (cap->context_switch != 0) {
1222 cap->context_switch = 0;
1223 appendToRunQueue(cap,t);
1224 } else {
1225 pushOnRunQueue(cap,t);
1226 }
1227
1228 IF_DEBUG(sanity,
1229 //debugBelch("&& Doing sanity check on yielding TSO %ld.", t->id);
1230 checkTSO(t));
1231
1232 return rtsFalse;
1233 }
1234
1235 /* -----------------------------------------------------------------------------
1236 * Handle a thread that returned to the scheduler with ThreadBlocked
1237 * -------------------------------------------------------------------------- */
1238
1239 static void
1240 scheduleHandleThreadBlocked( StgTSO *t
1241 #if !defined(DEBUG)
1242 STG_UNUSED
1243 #endif
1244 )
1245 {
1246
1247 // We don't need to do anything. The thread is blocked, and it
1248 // has tidied up its stack and placed itself on whatever queue
1249 // it needs to be on.
1250
1251 // ASSERT(t->why_blocked != NotBlocked);
1252 // Not true: for example,
1253 // - the thread may have woken itself up already, because
1254 // threadPaused() might have raised a blocked throwTo
1255 // exception, see maybePerformBlockedException().
1256
1257 #ifdef DEBUG
1258 traceThreadStatus(DEBUG_sched, t);
1259 #endif
1260 }
1261
1262 /* -----------------------------------------------------------------------------
1263 * Handle a thread that returned to the scheduler with ThreadFinished
1264 * -------------------------------------------------------------------------- */
1265
1266 static rtsBool
1267 scheduleHandleThreadFinished (Capability *cap STG_UNUSED, Task *task, StgTSO *t)
1268 {
1269 /* Need to check whether this was a main thread, and if so,
1270 * return with the return value.
1271 *
1272 * We also end up here if the thread kills itself with an
1273 * uncaught exception, see Exception.cmm.
1274 */
1275
1276 // blocked exceptions can now complete, even if the thread was in
1277 // blocked mode (see #2910).
1278 awakenBlockedExceptionQueue (cap, t);
1279
1280 //
1281 // Check whether the thread that just completed was a bound
1282 // thread, and if so return with the result.
1283 //
1284 // There is an assumption here that all thread completion goes
1285 // through this point; we need to make sure that if a thread
1286 // ends up in the ThreadKilled state, that it stays on the run
1287 // queue so it can be dealt with here.
1288 //
1289
1290 if (t->bound) {
1291
1292 if (t->bound != task->incall) {
1293 #if !defined(THREADED_RTS)
1294 // Must be a bound thread that is not the topmost one. Leave
1295 // it on the run queue until the stack has unwound to the
1296 // point where we can deal with this. Leaving it on the run
1297 // queue also ensures that the garbage collector knows about
1298 // this thread and its return value (it gets dropped from the
1299 // step->threads list so there's no other way to find it).
1300 appendToRunQueue(cap,t);
1301 return rtsFalse;
1302 #else
1303 // this cannot happen in the threaded RTS, because a
1304 // bound thread can only be run by the appropriate Task.
1305 barf("finished bound thread that isn't mine");
1306 #endif
1307 }
1308
1309 ASSERT(task->incall->tso == t);
1310
1311 if (t->what_next == ThreadComplete) {
1312 if (task->incall->ret) {
1313 // NOTE: return val is stack->sp[1] (see StgStartup.hc)
1314 *(task->incall->ret) = (StgClosure *)task->incall->tso->stackobj->sp[1];
1315 }
1316 task->incall->stat = Success;
1317 } else {
1318 if (task->incall->ret) {
1319 *(task->incall->ret) = NULL;
1320 }
1321 if (sched_state >= SCHED_INTERRUPTING) {
1322 if (heap_overflow) {
1323 task->incall->stat = HeapExhausted;
1324 } else {
1325 task->incall->stat = Interrupted;
1326 }
1327 } else {
1328 task->incall->stat = Killed;
1329 }
1330 }
1331 #ifdef DEBUG
1332 removeThreadLabel((StgWord)task->incall->tso->id);
1333 #endif
1334
1335 // We no longer consider this thread and task to be bound to
1336 // each other. The TSO lives on until it is GC'd, but the
1337 // task is about to be released by the caller, and we don't
1338 // want anyone following the pointer from the TSO to the
1339 // defunct task (which might have already been
1340 // re-used). This was a real bug: the GC updated
1341 // tso->bound->tso which lead to a deadlock.
1342 t->bound = NULL;
1343 task->incall->tso = NULL;
1344
1345 return rtsTrue; // tells schedule() to return
1346 }
1347
1348 return rtsFalse;
1349 }
1350
1351 /* -----------------------------------------------------------------------------
1352 * Perform a heap census
1353 * -------------------------------------------------------------------------- */
1354
1355 static rtsBool
1356 scheduleNeedHeapProfile( rtsBool ready_to_gc STG_UNUSED )
1357 {
1358 // When we have +RTS -i0 and we're heap profiling, do a census at
1359 // every GC. This lets us get repeatable runs for debugging.
1360 if (performHeapProfile ||
1361 (RtsFlags.ProfFlags.heapProfileInterval==0 &&
1362 RtsFlags.ProfFlags.doHeapProfile && ready_to_gc)) {
1363 return rtsTrue;
1364 } else {
1365 return rtsFalse;
1366 }
1367 }
1368
1369 /* -----------------------------------------------------------------------------
1370 * Start a synchronisation of all capabilities
1371 * -------------------------------------------------------------------------- */
1372
1373 // Returns:
1374 // 0 if we successfully got a sync
1375 // non-0 if there was another sync request in progress,
1376 // and we yielded to it. The value returned is the
1377 // type of the other sync request.
1378 //
1379 #if defined(THREADED_RTS)
1380 static nat requestSync (Capability **pcap, Task *task, nat sync_type)
1381 {
1382 nat prev_pending_sync;
1383
1384 prev_pending_sync = cas(&pending_sync, 0, sync_type);
1385
1386 if (prev_pending_sync)
1387 {
1388 do {
1389 debugTrace(DEBUG_sched, "someone else is trying to sync (%d)...",
1390 prev_pending_sync);
1391 ASSERT(*pcap);
1392 yieldCapability(pcap,task,rtsTrue);
1393 } while (pending_sync);
1394 return prev_pending_sync; // NOTE: task->cap might have changed now
1395 }
1396 else
1397 {
1398 return 0;
1399 }
1400 }
1401
1402 //
1403 // Grab all the capabilities except the one we already hold. Used
1404 // when synchronising before a single-threaded GC (SYNC_SEQ_GC), and
1405 // before a fork (SYNC_OTHER).
1406 //
1407 // Only call this after requestSync(), otherwise a deadlock might
1408 // ensue if another thread is trying to synchronise.
1409 //
1410 static void acquireAllCapabilities(Capability *cap, Task *task)
1411 {
1412 Capability *tmpcap;
1413 nat i;
1414
1415 for (i=0; i < n_capabilities; i++) {
1416 debugTrace(DEBUG_sched, "grabbing all the capabilies (%d/%d)", i, n_capabilities);
1417 tmpcap = capabilities[i];
1418 if (tmpcap != cap) {
1419 // we better hope this task doesn't get migrated to
1420 // another Capability while we're waiting for this one.
1421 // It won't, because load balancing happens while we have
1422 // all the Capabilities, but even so it's a slightly
1423 // unsavoury invariant.
1424 task->cap = tmpcap;
1425 waitForReturnCapability(&tmpcap, task);
1426 if (tmpcap->no != i) {
1427 barf("acquireAllCapabilities: got the wrong capability");
1428 }
1429 }
1430 }
1431 task->cap = cap;
1432 }
1433
1434 static void releaseAllCapabilities(nat n, Capability *cap, Task *task)
1435 {
1436 nat i;
1437
1438 for (i = 0; i < n; i++) {
1439 if (cap->no != i) {
1440 task->cap = capabilities[i];
1441 releaseCapability(capabilities[i]);
1442 }
1443 }
1444 task->cap = cap;
1445 }
1446 #endif
1447
1448 /* -----------------------------------------------------------------------------
1449 * Perform a garbage collection if necessary
1450 * -------------------------------------------------------------------------- */
1451
1452 static void
1453 scheduleDoGC (Capability **pcap, Task *task USED_IF_THREADS,
1454 rtsBool force_major)
1455 {
1456 Capability *cap = *pcap;
1457 rtsBool heap_census;
1458 nat collect_gen;
1459 #ifdef THREADED_RTS
1460 nat gc_type;
1461 nat i, sync;
1462 StgTSO *tso;
1463 #endif
1464
1465 if (sched_state == SCHED_SHUTTING_DOWN) {
1466 // The final GC has already been done, and the system is
1467 // shutting down. We'll probably deadlock if we try to GC
1468 // now.
1469 return;
1470 }
1471
1472 heap_census = scheduleNeedHeapProfile(rtsTrue);
1473
1474 // Figure out which generation we are collecting, so that we can
1475 // decide whether this is a parallel GC or not.
1476 collect_gen = calcNeeded(force_major || heap_census, NULL);
1477
1478 #ifdef THREADED_RTS
1479 if (sched_state < SCHED_INTERRUPTING
1480 && RtsFlags.ParFlags.parGcEnabled
1481 && collect_gen >= RtsFlags.ParFlags.parGcGen
1482 && ! oldest_gen->mark)
1483 {
1484 gc_type = SYNC_GC_PAR;
1485 } else {
1486 gc_type = SYNC_GC_SEQ;
1487 }
1488
1489 // In order to GC, there must be no threads running Haskell code.
1490 // Therefore, the GC thread needs to hold *all* the capabilities,
1491 // and release them after the GC has completed.
1492 //
1493 // This seems to be the simplest way: previous attempts involved
1494 // making all the threads with capabilities give up their
1495 // capabilities and sleep except for the *last* one, which
1496 // actually did the GC. But it's quite hard to arrange for all
1497 // the other tasks to sleep and stay asleep.
1498 //
1499
1500 /* Other capabilities are prevented from running yet more Haskell
1501 threads if pending_sync is set. Tested inside
1502 yieldCapability() and releaseCapability() in Capability.c */
1503
1504 do {
1505 sync = requestSync(pcap, task, gc_type);
1506 cap = *pcap;
1507 if (sync == SYNC_GC_SEQ || sync == SYNC_GC_PAR) {
1508 // someone else had a pending sync request for a GC, so
1509 // let's assume GC has been done and we don't need to GC
1510 // again.
1511 return;
1512 }
1513 if (sched_state == SCHED_SHUTTING_DOWN) {
1514 // The scheduler might now be shutting down. We tested
1515 // this above, but it might have become true since then as
1516 // we yielded the capability in requestSync().
1517 return;
1518 }
1519 } while (sync);
1520
1521 // don't declare this until after we have sync'd, because
1522 // n_capabilities may change.
1523 rtsBool idle_cap[n_capabilities];
1524 #ifdef DEBUG
1525 unsigned int old_n_capabilities = n_capabilities;
1526 #endif
1527
1528 interruptAllCapabilities();
1529
1530 // The final shutdown GC is always single-threaded, because it's
1531 // possible that some of the Capabilities have no worker threads.
1532
1533 if (gc_type == SYNC_GC_SEQ)
1534 {
1535 traceEventRequestSeqGc(cap);
1536 }
1537 else
1538 {
1539 traceEventRequestParGc(cap);
1540 debugTrace(DEBUG_sched, "ready_to_gc, grabbing GC threads");
1541 }
1542
1543 if (gc_type == SYNC_GC_SEQ)
1544 {
1545 // single-threaded GC: grab all the capabilities
1546 acquireAllCapabilities(cap,task);
1547 }
1548 else
1549 {
1550 // If we are load-balancing collections in this
1551 // generation, then we require all GC threads to participate
1552 // in the collection. Otherwise, we only require active
1553 // threads to participate, and we set gc_threads[i]->idle for
1554 // any idle capabilities. The rationale here is that waking
1555 // up an idle Capability takes much longer than just doing any
1556 // GC work on its behalf.
1557
1558 if (RtsFlags.ParFlags.parGcNoSyncWithIdle == 0
1559 || (RtsFlags.ParFlags.parGcLoadBalancingEnabled &&
1560 collect_gen >= RtsFlags.ParFlags.parGcLoadBalancingGen)) {
1561 for (i=0; i < n_capabilities; i++) {
1562 if (capabilities[i]->disabled) {
1563 idle_cap[i] = tryGrabCapability(capabilities[i], task);
1564 } else {
1565 idle_cap[i] = rtsFalse;
1566 }
1567 }
1568 } else {
1569 for (i=0; i < n_capabilities; i++) {
1570 if (capabilities[i]->disabled) {
1571 idle_cap[i] = tryGrabCapability(capabilities[i], task);
1572 } else if (i == cap->no ||
1573 capabilities[i]->idle < RtsFlags.ParFlags.parGcNoSyncWithIdle) {
1574 idle_cap[i] = rtsFalse;
1575 } else {
1576 idle_cap[i] = tryGrabCapability(capabilities[i], task);
1577 if (!idle_cap[i]) {
1578 n_failed_trygrab_idles++;
1579 } else {
1580 n_idle_caps++;
1581 }
1582 }
1583 }
1584 }
1585
1586 // We set the gc_thread[i]->idle flag if that
1587 // capability/thread is not participating in this collection.
1588 // We also keep a local record of which capabilities are idle
1589 // in idle_cap[], because scheduleDoGC() is re-entrant:
1590 // another thread might start a GC as soon as we've finished
1591 // this one, and thus the gc_thread[]->idle flags are invalid
1592 // as soon as we release any threads after GC. Getting this
1593 // wrong leads to a rare and hard to debug deadlock!
1594
1595 for (i=0; i < n_capabilities; i++) {
1596 gc_threads[i]->idle = idle_cap[i];
1597 capabilities[i]->idle++;
1598 }
1599
1600 // For all capabilities participating in this GC, wait until
1601 // they have stopped mutating and are standing by for GC.
1602 waitForGcThreads(cap);
1603
1604 #if defined(THREADED_RTS)
1605 // Stable point where we can do a global check on our spark counters
1606 ASSERT(checkSparkCountInvariant());
1607 #endif
1608 }
1609
1610 #endif
1611
1612 IF_DEBUG(scheduler, printAllThreads());
1613
1614 delete_threads_and_gc:
1615 /*
1616 * We now have all the capabilities; if we're in an interrupting
1617 * state, then we should take the opportunity to delete all the
1618 * threads in the system.
1619 */
1620 if (sched_state == SCHED_INTERRUPTING) {
1621 deleteAllThreads(cap);
1622 #if defined(THREADED_RTS)
1623 // Discard all the sparks from every Capability. Why?
1624 // They'll probably be GC'd anyway since we've killed all the
1625 // threads. It just avoids the GC having to do any work to
1626 // figure out that any remaining sparks are garbage.
1627 for (i = 0; i < n_capabilities; i++) {
1628 capabilities[i]->spark_stats.gcd +=
1629 sparkPoolSize(capabilities[i]->sparks);
1630 // No race here since all Caps are stopped.
1631 discardSparksCap(capabilities[i]);
1632 }
1633 #endif
1634 sched_state = SCHED_SHUTTING_DOWN;
1635 }
1636
1637 /*
1638 * When there are disabled capabilities, we want to migrate any
1639 * threads away from them. Normally this happens in the
1640 * scheduler's loop, but only for unbound threads - it's really
1641 * hard for a bound thread to migrate itself. So we have another
1642 * go here.
1643 */
1644 #if defined(THREADED_RTS)
1645 for (i = enabled_capabilities; i < n_capabilities; i++) {
1646 Capability *tmp_cap, *dest_cap;
1647 tmp_cap = capabilities[i];
1648 ASSERT(tmp_cap->disabled);
1649 if (i != cap->no) {
1650 dest_cap = capabilities[i % enabled_capabilities];
1651 while (!emptyRunQueue(tmp_cap)) {
1652 tso = popRunQueue(tmp_cap);
1653 migrateThread(tmp_cap, tso, dest_cap);
1654 if (tso->bound) {
1655 traceTaskMigrate(tso->bound->task,
1656 tso->bound->task->cap,
1657 dest_cap);
1658 tso->bound->task->cap = dest_cap;
1659 }
1660 }
1661 }
1662 }
1663 #endif
1664
1665 #if defined(THREADED_RTS)
1666 // reset pending_sync *before* GC, so that when the GC threads
1667 // emerge they don't immediately re-enter the GC.
1668 pending_sync = 0;
1669 GarbageCollect(collect_gen, heap_census, gc_type, cap);
1670 #else
1671 GarbageCollect(collect_gen, heap_census, 0, cap);
1672 #endif
1673
1674 traceSparkCounters(cap);
1675
1676 switch (recent_activity) {
1677 case ACTIVITY_INACTIVE:
1678 if (force_major) {
1679 // We are doing a GC because the system has been idle for a
1680 // timeslice and we need to check for deadlock. Record the
1681 // fact that we've done a GC and turn off the timer signal;
1682 // it will get re-enabled if we run any threads after the GC.
1683 recent_activity = ACTIVITY_DONE_GC;
1684 #ifndef PROFILING
1685 stopTimer();
1686 #endif
1687 break;
1688 }
1689 // fall through...
1690
1691 case ACTIVITY_MAYBE_NO:
1692 // the GC might have taken long enough for the timer to set
1693 // recent_activity = ACTIVITY_MAYBE_NO or ACTIVITY_INACTIVE,
1694 // but we aren't necessarily deadlocked:
1695 recent_activity = ACTIVITY_YES;
1696 break;
1697
1698 case ACTIVITY_DONE_GC:
1699 // If we are actually active, the scheduler will reset the
1700 // recent_activity flag and re-enable the timer.
1701 break;
1702 }
1703
1704 #if defined(THREADED_RTS)
1705 // Stable point where we can do a global check on our spark counters
1706 ASSERT(checkSparkCountInvariant());
1707 #endif
1708
1709 // The heap census itself is done during GarbageCollect().
1710 if (heap_census) {
1711 performHeapProfile = rtsFalse;
1712 }
1713
1714 #if defined(THREADED_RTS)
1715
1716 // If n_capabilities has changed during GC, we're in trouble.
1717 ASSERT(n_capabilities == old_n_capabilities);
1718
1719 if (gc_type == SYNC_GC_PAR)
1720 {
1721 releaseGCThreads(cap);
1722 for (i = 0; i < n_capabilities; i++) {
1723 if (i != cap->no) {
1724 if (idle_cap[i]) {
1725 ASSERT(capabilities[i]->running_task == task);
1726 task->cap = capabilities[i];
1727 releaseCapability(capabilities[i]);
1728 } else {
1729 ASSERT(capabilities[i]->running_task != task);
1730 }
1731 }
1732 }
1733 task->cap = cap;
1734 }
1735 #endif
1736
1737 if (heap_overflow && sched_state < SCHED_INTERRUPTING) {
1738 // GC set the heap_overflow flag, so we should proceed with
1739 // an orderly shutdown now. Ultimately we want the main
1740 // thread to return to its caller with HeapExhausted, at which
1741 // point the caller should call hs_exit(). The first step is
1742 // to delete all the threads.
1743 //
1744 // Another way to do this would be to raise an exception in
1745 // the main thread, which we really should do because it gives
1746 // the program a chance to clean up. But how do we find the
1747 // main thread? It should presumably be the same one that
1748 // gets ^C exceptions, but that's all done on the Haskell side
1749 // (GHC.TopHandler).
1750 sched_state = SCHED_INTERRUPTING;
1751 goto delete_threads_and_gc;
1752 }
1753
1754 #ifdef SPARKBALANCE
1755 /* JB
1756 Once we are all together... this would be the place to balance all
1757 spark pools. No concurrent stealing or adding of new sparks can
1758 occur. Should be defined in Sparks.c. */
1759 balanceSparkPoolsCaps(n_capabilities, capabilities);
1760 #endif
1761
1762 #if defined(THREADED_RTS)
1763 if (gc_type == SYNC_GC_SEQ) {
1764 // release our stash of capabilities.
1765 releaseAllCapabilities(n_capabilities, cap, task);
1766 }
1767 #endif
1768
1769 return;
1770 }
1771
1772 /* ---------------------------------------------------------------------------
1773 * Singleton fork(). Do not copy any running threads.
1774 * ------------------------------------------------------------------------- */
1775
1776 pid_t
1777 forkProcess(HsStablePtr *entry
1778 #ifndef FORKPROCESS_PRIMOP_SUPPORTED
1779 STG_UNUSED
1780 #endif
1781 )
1782 {
1783 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
1784 pid_t pid;
1785 StgTSO* t,*next;
1786 Capability *cap;
1787 nat g;
1788 Task *task = NULL;
1789 nat i;
1790 #ifdef THREADED_RTS
1791 nat sync;
1792 #endif
1793
1794 debugTrace(DEBUG_sched, "forking!");
1795
1796 task = newBoundTask();
1797
1798 cap = NULL;
1799 waitForReturnCapability(&cap, task);
1800
1801 #ifdef THREADED_RTS
1802 do {
1803 sync = requestSync(&cap, task, SYNC_OTHER);
1804 } while (sync);
1805
1806 acquireAllCapabilities(cap,task);
1807
1808 pending_sync = 0;
1809 #endif
1810
1811 // no funny business: hold locks while we fork, otherwise if some
1812 // other thread is holding a lock when the fork happens, the data
1813 // structure protected by the lock will forever be in an
1814 // inconsistent state in the child. See also #1391.
1815 ACQUIRE_LOCK(&sched_mutex);
1816 ACQUIRE_LOCK(&sm_mutex);
1817 ACQUIRE_LOCK(&stable_mutex);
1818 ACQUIRE_LOCK(&task->lock);
1819
1820 for (i=0; i < n_capabilities; i++) {
1821 ACQUIRE_LOCK(&capabilities[i]->lock);
1822 }
1823
1824 #ifdef THREADED_RTS
1825 ACQUIRE_LOCK(&all_tasks_mutex);
1826 #endif
1827
1828 stopTimer(); // See #4074
1829
1830 #if defined(TRACING)
1831 flushEventLog(); // so that child won't inherit dirty file buffers
1832 #endif
1833
1834 pid = fork();
1835
1836 if (pid) { // parent
1837
1838 startTimer(); // #4074
1839
1840 RELEASE_LOCK(&sched_mutex);
1841 RELEASE_LOCK(&sm_mutex);
1842 RELEASE_LOCK(&stable_mutex);
1843 RELEASE_LOCK(&task->lock);
1844
1845 for (i=0; i < n_capabilities; i++) {
1846 releaseCapability_(capabilities[i],rtsFalse);
1847 RELEASE_LOCK(&capabilities[i]->lock);
1848 }
1849
1850 #ifdef THREADED_RTS
1851 RELEASE_LOCK(&all_tasks_mutex);
1852 #endif
1853
1854 boundTaskExiting(task);
1855
1856 // just return the pid
1857 return pid;
1858
1859 } else { // child
1860
1861 #if defined(THREADED_RTS)
1862 initMutex(&sched_mutex);
1863 initMutex(&sm_mutex);
1864 initMutex(&stable_mutex);
1865 initMutex(&task->lock);
1866
1867 for (i=0; i < n_capabilities; i++) {
1868 initMutex(&capabilities[i]->lock);
1869 }
1870
1871 initMutex(&all_tasks_mutex);
1872 #endif
1873
1874 #ifdef TRACING
1875 resetTracing();
1876 #endif
1877
1878 // Now, all OS threads except the thread that forked are
1879 // stopped. We need to stop all Haskell threads, including
1880 // those involved in foreign calls. Also we need to delete
1881 // all Tasks, because they correspond to OS threads that are
1882 // now gone.
1883
1884 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1885 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
1886 next = t->global_link;
1887 // don't allow threads to catch the ThreadKilled
1888 // exception, but we do want to raiseAsync() because these
1889 // threads may be evaluating thunks that we need later.
1890 deleteThread_(t->cap,t);
1891
1892 // stop the GC from updating the InCall to point to
1893 // the TSO. This is only necessary because the
1894 // OSThread bound to the TSO has been killed, and
1895 // won't get a chance to exit in the usual way (see
1896 // also scheduleHandleThreadFinished).
1897 t->bound = NULL;
1898 }
1899 }
1900
1901 discardTasksExcept(task);
1902
1903 for (i=0; i < n_capabilities; i++) {
1904 cap = capabilities[i];
1905
1906 // Empty the run queue. It seems tempting to let all the
1907 // killed threads stay on the run queue as zombies to be
1908 // cleaned up later, but some of them may correspond to
1909 // bound threads for which the corresponding Task does not
1910 // exist.
1911 truncateRunQueue(cap);
1912
1913 // Any suspended C-calling Tasks are no more, their OS threads
1914 // don't exist now:
1915 cap->suspended_ccalls = NULL;
1916
1917 #if defined(THREADED_RTS)
1918 // Wipe our spare workers list, they no longer exist. New
1919 // workers will be created if necessary.
1920 cap->spare_workers = NULL;
1921 cap->n_spare_workers = 0;
1922 cap->returning_tasks_hd = NULL;
1923 cap->returning_tasks_tl = NULL;
1924 #endif
1925
1926 // Release all caps except 0, we'll use that for starting
1927 // the IO manager and running the client action below.
1928 if (cap->no != 0) {
1929 task->cap = cap;
1930 releaseCapability(cap);
1931 }
1932 }
1933 cap = capabilities[0];
1934 task->cap = cap;
1935
1936 // Empty the threads lists. Otherwise, the garbage
1937 // collector may attempt to resurrect some of these threads.
1938 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1939 generations[g].threads = END_TSO_QUEUE;
1940 }
1941
1942 // On Unix, all timers are reset in the child, so we need to start
1943 // the timer again.
1944 initTimer();
1945 startTimer();
1946
1947 // TODO: need to trace various other things in the child
1948 // like startup event, capabilities, process info etc
1949 traceTaskCreate(task, cap);
1950
1951 #if defined(THREADED_RTS)
1952 ioManagerStartCap(&cap);
1953 #endif
1954
1955 rts_evalStableIO(&cap, entry, NULL); // run the action
1956 rts_checkSchedStatus("forkProcess",cap);
1957
1958 rts_unlock(cap);
1959 shutdownHaskellAndExit(EXIT_SUCCESS, 0 /* !fastExit */);
1960 }
1961 #else /* !FORKPROCESS_PRIMOP_SUPPORTED */
1962 barf("forkProcess#: primop not supported on this platform, sorry!\n");
1963 #endif
1964 }
1965
1966 /* ---------------------------------------------------------------------------
1967 * Changing the number of Capabilities
1968 *
1969 * Changing the number of Capabilities is very tricky! We can only do
1970 * it with the system fully stopped, so we do a full sync with
1971 * requestSync(SYNC_OTHER) and grab all the capabilities.
1972 *
1973 * Then we resize the appropriate data structures, and update all
1974 * references to the old data structures which have now moved.
1975 * Finally we release the Capabilities we are holding, and start
1976 * worker Tasks on the new Capabilities we created.
1977 *
1978 * ------------------------------------------------------------------------- */
1979
1980 void
1981 setNumCapabilities (nat new_n_capabilities USED_IF_THREADS)
1982 {
1983 #if !defined(THREADED_RTS)
1984 if (new_n_capabilities != 1) {
1985 errorBelch("setNumCapabilities: not supported in the non-threaded RTS");
1986 }
1987 return;
1988 #elif defined(NOSMP)
1989 if (new_n_capabilities != 1) {
1990 errorBelch("setNumCapabilities: not supported on this platform");
1991 }
1992 return;
1993 #else
1994 Task *task;
1995 Capability *cap;
1996 nat sync;
1997 nat n;
1998 Capability *old_capabilities = NULL;
1999 nat old_n_capabilities = n_capabilities;
2000
2001 if (new_n_capabilities == enabled_capabilities) return;
2002
2003 debugTrace(DEBUG_sched, "changing the number of Capabilities from %d to %d",
2004 enabled_capabilities, new_n_capabilities);
2005
2006 cap = rts_lock();
2007 task = cap->running_task;
2008
2009 do {
2010 sync = requestSync(&cap, task, SYNC_OTHER);
2011 } while (sync);
2012
2013 acquireAllCapabilities(cap,task);
2014
2015 pending_sync = 0;
2016
2017 if (new_n_capabilities < enabled_capabilities)
2018 {
2019 // Reducing the number of capabilities: we do not actually
2020 // remove the extra capabilities, we just mark them as
2021 // "disabled". This has the following effects:
2022 //
2023 // - threads on a disabled capability are migrated away by the
2024 // scheduler loop
2025 //
2026 // - disabled capabilities do not participate in GC
2027 // (see scheduleDoGC())
2028 //
2029 // - No spark threads are created on this capability
2030 // (see scheduleActivateSpark())
2031 //
2032 // - We do not attempt to migrate threads *to* a disabled
2033 // capability (see schedulePushWork()).
2034 //
2035 // but in other respects, a disabled capability remains
2036 // alive. Threads may be woken up on a disabled capability,
2037 // but they will be immediately migrated away.
2038 //
2039 // This approach is much easier than trying to actually remove
2040 // the capability; we don't have to worry about GC data
2041 // structures, the nursery, etc.
2042 //
2043 for (n = new_n_capabilities; n < enabled_capabilities; n++) {
2044 capabilities[n]->disabled = rtsTrue;
2045 traceCapDisable(capabilities[n]);
2046 }
2047 enabled_capabilities = new_n_capabilities;
2048 }
2049 else
2050 {
2051 // Increasing the number of enabled capabilities.
2052 //
2053 // enable any disabled capabilities, up to the required number
2054 for (n = enabled_capabilities;
2055 n < new_n_capabilities && n < n_capabilities; n++) {
2056 capabilities[n]->disabled = rtsFalse;
2057 traceCapEnable(capabilities[n]);
2058 }
2059 enabled_capabilities = n;
2060
2061 if (new_n_capabilities > n_capabilities) {
2062 #if defined(TRACING)
2063 // Allocate eventlog buffers for the new capabilities. Note this
2064 // must be done before calling moreCapabilities(), because that
2065 // will emit events about creating the new capabilities and adding
2066 // them to existing capsets.
2067 tracingAddCapapilities(n_capabilities, new_n_capabilities);
2068 #endif
2069
2070 // Resize the capabilities array
2071 // NB. after this, capabilities points somewhere new. Any pointers
2072 // of type (Capability *) are now invalid.
2073 moreCapabilities(n_capabilities, new_n_capabilities);
2074
2075 // Resize and update storage manager data structures
2076 storageAddCapabilities(n_capabilities, new_n_capabilities);
2077 }
2078 }
2079
2080 // update n_capabilities before things start running
2081 if (new_n_capabilities > n_capabilities) {
2082 n_capabilities = enabled_capabilities = new_n_capabilities;
2083 }
2084
2085 // Start worker tasks on the new Capabilities
2086 startWorkerTasks(old_n_capabilities, new_n_capabilities);
2087
2088 // We're done: release the original Capabilities
2089 releaseAllCapabilities(old_n_capabilities, cap,task);
2090
2091 // We can't free the old array until now, because we access it
2092 // while updating pointers in updateCapabilityRefs().
2093 if (old_capabilities) {
2094 stgFree(old_capabilities);
2095 }
2096
2097 // Notify IO manager that the number of capabilities has changed.
2098 rts_evalIO(&cap, ioManagerCapabilitiesChanged_closure, NULL);
2099
2100 rts_unlock(cap);
2101
2102 #endif // THREADED_RTS
2103 }
2104
2105
2106
2107 /* ---------------------------------------------------------------------------
2108 * Delete all the threads in the system
2109 * ------------------------------------------------------------------------- */
2110
2111 static void
2112 deleteAllThreads ( Capability *cap )
2113 {
2114 // NOTE: only safe to call if we own all capabilities.
2115
2116 StgTSO* t, *next;
2117 nat g;
2118
2119 debugTrace(DEBUG_sched,"deleting all threads");
2120 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
2121 for (t = generations[g].threads; t != END_TSO_QUEUE; t = next) {
2122 next = t->global_link;
2123 deleteThread(cap,t);
2124 }
2125 }
2126
2127 // The run queue now contains a bunch of ThreadKilled threads. We
2128 // must not throw these away: the main thread(s) will be in there
2129 // somewhere, and the main scheduler loop has to deal with it.
2130 // Also, the run queue is the only thing keeping these threads from
2131 // being GC'd, and we don't want the "main thread has been GC'd" panic.
2132
2133 #if !defined(THREADED_RTS)
2134 ASSERT(blocked_queue_hd == END_TSO_QUEUE);
2135 ASSERT(sleeping_queue == END_TSO_QUEUE);
2136 #endif
2137 }
2138
2139 /* -----------------------------------------------------------------------------
2140 Managing the suspended_ccalls list.
2141 Locks required: sched_mutex
2142 -------------------------------------------------------------------------- */
2143
2144 STATIC_INLINE void
2145 suspendTask (Capability *cap, Task *task)
2146 {
2147 InCall *incall;
2148
2149 incall = task->incall;
2150 ASSERT(incall->next == NULL && incall->prev == NULL);
2151 incall->next = cap->suspended_ccalls;
2152 incall->prev = NULL;
2153 if (cap->suspended_ccalls) {
2154 cap->suspended_ccalls->prev = incall;
2155 }
2156 cap->suspended_ccalls = incall;
2157 }
2158
2159 STATIC_INLINE void
2160 recoverSuspendedTask (Capability *cap, Task *task)
2161 {
2162 InCall *incall;
2163
2164 incall = task->incall;
2165 if (incall->prev) {
2166 incall->prev->next = incall->next;
2167 } else {
2168 ASSERT(cap->suspended_ccalls == incall);
2169 cap->suspended_ccalls = incall->next;
2170 }
2171 if (incall->next) {
2172 incall->next->prev = incall->prev;
2173 }
2174 incall->next = incall->prev = NULL;
2175 }
2176
2177 /* ---------------------------------------------------------------------------
2178 * Suspending & resuming Haskell threads.
2179 *
2180 * When making a "safe" call to C (aka _ccall_GC), the task gives back
2181 * its capability before calling the C function. This allows another
2182 * task to pick up the capability and carry on running Haskell
2183 * threads. It also means that if the C call blocks, it won't lock
2184 * the whole system.
2185 *
2186 * The Haskell thread making the C call is put to sleep for the
2187 * duration of the call, on the suspended_ccalling_threads queue. We
2188 * give out a token to the task, which it can use to resume the thread
2189 * on return from the C function.
2190 *
2191 * If this is an interruptible C call, this means that the FFI call may be
2192 * unceremoniously terminated and should be scheduled on an
2193 * unbound worker thread.
2194 * ------------------------------------------------------------------------- */
2195
2196 void *
2197 suspendThread (StgRegTable *reg, rtsBool interruptible)
2198 {
2199 Capability *cap;
2200 int saved_errno;
2201 StgTSO *tso;
2202 Task *task;
2203 #if mingw32_HOST_OS
2204 StgWord32 saved_winerror;
2205 #endif
2206
2207 saved_errno = errno;
2208 #if mingw32_HOST_OS
2209 saved_winerror = GetLastError();
2210 #endif
2211
2212 /* assume that *reg is a pointer to the StgRegTable part of a Capability.
2213 */
2214 cap = regTableToCapability(reg);
2215
2216 task = cap->running_task;
2217 tso = cap->r.rCurrentTSO;
2218
2219 traceEventStopThread(cap, tso, THREAD_SUSPENDED_FOREIGN_CALL, 0);
2220
2221 // XXX this might not be necessary --SDM
2222 tso->what_next = ThreadRunGHC;
2223
2224 threadPaused(cap,tso);
2225
2226 if (interruptible) {
2227 tso->why_blocked = BlockedOnCCall_Interruptible;
2228 } else {
2229 tso->why_blocked = BlockedOnCCall;
2230 }
2231
2232 // Hand back capability
2233 task->incall->suspended_tso = tso;
2234 task->incall->suspended_cap = cap;
2235
2236 // Otherwise allocate() will write to invalid memory.
2237 cap->r.rCurrentTSO = NULL
2238
2239 ACQUIRE_LOCK(&cap->lock);
2240
2241 suspendTask(cap,task);
2242 cap->in_haskell = rtsFalse;
2243 releaseCapability_(cap,rtsFalse);
2244
2245 RELEASE_LOCK(&cap->lock);
2246
2247 errno = saved_errno;
2248 #if mingw32_HOST_OS
2249 SetLastError(saved_winerror);
2250 #endif
2251 return task;
2252 }
2253
2254 StgRegTable *
2255 resumeThread (void *task_)
2256 {
2257 StgTSO *tso;
2258 InCall *incall;
2259 Capability *cap;
2260 Task *task = task_;
2261 int saved_errno;
2262 #if mingw32_HOST_OS
2263 StgWord32 saved_winerror;
2264 #endif
2265
2266 saved_errno = errno;
2267 #if mingw32_HOST_OS
2268 saved_winerror = GetLastError();
2269 #endif
2270
2271 incall = task->incall;
2272 cap = incall->suspended_cap;
2273 task->cap = cap;
2274
2275 // Wait for permission to re-enter the RTS with the result.
2276 waitForReturnCapability(&cap,task);
2277 // we might be on a different capability now... but if so, our
2278 // entry on the suspended_ccalls list will also have been
2279 // migrated.
2280
2281 // Remove the thread from the suspended list
2282 recoverSuspendedTask(cap,task);
2283
2284 tso = incall->suspended_tso;
2285 incall->suspended_tso = NULL;
2286 incall->suspended_cap = NULL;
2287 tso->_link = END_TSO_QUEUE; // no write barrier reqd
2288
2289 traceEventRunThread(cap, tso);
2290
2291 /* Reset blocking status */
2292 tso->why_blocked = NotBlocked;
2293
2294 if ((tso->flags & TSO_BLOCKEX) == 0) {
2295 // avoid locking the TSO if we don't have to
2296 if (tso->blocked_exceptions != END_BLOCKED_EXCEPTIONS_QUEUE) {
2297 maybePerformBlockedException(cap,tso);
2298 }
2299 }
2300
2301 cap->r.rCurrentTSO = tso;
2302 cap->in_haskell = rtsTrue;
2303 errno = saved_errno;
2304 #if mingw32_HOST_OS
2305 SetLastError(saved_winerror);
2306 #endif
2307
2308 /* We might have GC'd, mark the TSO dirty again */
2309 dirty_TSO(cap,tso);
2310 dirty_STACK(cap,tso->stackobj);
2311
2312 IF_DEBUG(sanity, checkTSO(tso));
2313
2314 return &cap->r;
2315 }
2316
2317 /* ---------------------------------------------------------------------------
2318 * scheduleThread()
2319 *
2320 * scheduleThread puts a thread on the end of the runnable queue.
2321 * This will usually be done immediately after a thread is created.
2322 * The caller of scheduleThread must create the thread using e.g.
2323 * createThread and push an appropriate closure
2324 * on this thread's stack before the scheduler is invoked.
2325 * ------------------------------------------------------------------------ */
2326
2327 void
2328 scheduleThread(Capability *cap, StgTSO *tso)
2329 {
2330 // The thread goes at the *end* of the run-queue, to avoid possible
2331 // starvation of any threads already on the queue.
2332 appendToRunQueue(cap,tso);
2333 }
2334
2335 void
2336 scheduleThreadOn(Capability *cap, StgWord cpu USED_IF_THREADS, StgTSO *tso)
2337 {
2338 tso->flags |= TSO_LOCKED; // we requested explicit affinity; don't
2339 // move this thread from now on.
2340 #if defined(THREADED_RTS)
2341 cpu %= enabled_capabilities;
2342 if (cpu == cap->no) {
2343 appendToRunQueue(cap,tso);
2344 } else {
2345 migrateThread(cap, tso, capabilities[cpu]);
2346 }
2347 #else
2348 appendToRunQueue(cap,tso);
2349 #endif
2350 }
2351
2352 void
2353 scheduleWaitThread (StgTSO* tso, /*[out]*/HaskellObj* ret, Capability **pcap)
2354 {
2355 Task *task;
2356 DEBUG_ONLY( StgThreadID id );
2357 Capability *cap;
2358
2359 cap = *pcap;
2360
2361 // We already created/initialised the Task
2362 task = cap->running_task;
2363
2364 // This TSO is now a bound thread; make the Task and TSO
2365 // point to each other.
2366 tso->bound = task->incall;
2367 tso->cap = cap;
2368
2369 task->incall->tso = tso;
2370 task->incall->ret = ret;
2371 task->incall->stat = NoStatus;
2372
2373 appendToRunQueue(cap,tso);
2374
2375 DEBUG_ONLY( id = tso->id );
2376 debugTrace(DEBUG_sched, "new bound thread (%lu)", (unsigned long)id);
2377
2378 cap = schedule(cap,task);
2379
2380 ASSERT(task->incall->stat != NoStatus);
2381 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
2382
2383 debugTrace(DEBUG_sched, "bound thread (%lu) finished", (unsigned long)id);
2384 *pcap = cap;
2385 }
2386
2387 /* ----------------------------------------------------------------------------
2388 * Starting Tasks
2389 * ------------------------------------------------------------------------- */
2390
2391 #if defined(THREADED_RTS)
2392 void scheduleWorker (Capability *cap, Task *task)
2393 {
2394 // schedule() runs without a lock.
2395 cap = schedule(cap,task);
2396
2397 // On exit from schedule(), we have a Capability, but possibly not
2398 // the same one we started with.
2399
2400 // During shutdown, the requirement is that after all the
2401 // Capabilities are shut down, all workers that are shutting down
2402 // have finished workerTaskStop(). This is why we hold on to
2403 // cap->lock until we've finished workerTaskStop() below.
2404 //
2405 // There may be workers still involved in foreign calls; those
2406 // will just block in waitForReturnCapability() because the
2407 // Capability has been shut down.
2408 //
2409 ACQUIRE_LOCK(&cap->lock);
2410 releaseCapability_(cap,rtsFalse);
2411 workerTaskStop(task);
2412 RELEASE_LOCK(&cap->lock);
2413 }
2414 #endif
2415
2416 /* ---------------------------------------------------------------------------
2417 * Start new worker tasks on Capabilities from--to
2418 * -------------------------------------------------------------------------- */
2419
2420 static void
2421 startWorkerTasks (nat from USED_IF_THREADS, nat to USED_IF_THREADS)
2422 {
2423 #if defined(THREADED_RTS)
2424 nat i;
2425 Capability *cap;
2426
2427 for (i = from; i < to; i++) {
2428 cap = capabilities[i];
2429 ACQUIRE_LOCK(&cap->lock);
2430 startWorkerTask(cap);
2431 RELEASE_LOCK(&cap->lock);
2432 }
2433 #endif
2434 }
2435
2436 /* ---------------------------------------------------------------------------
2437 * initScheduler()
2438 *
2439 * Initialise the scheduler. This resets all the queues - if the
2440 * queues contained any threads, they'll be garbage collected at the
2441 * next pass.
2442 *
2443 * ------------------------------------------------------------------------ */
2444
2445 void
2446 initScheduler(void)
2447 {
2448 #if !defined(THREADED_RTS)
2449 blocked_queue_hd = END_TSO_QUEUE;
2450 blocked_queue_tl = END_TSO_QUEUE;
2451 sleeping_queue = END_TSO_QUEUE;
2452 #endif
2453
2454 sched_state = SCHED_RUNNING;
2455 recent_activity = ACTIVITY_YES;
2456
2457 #if defined(THREADED_RTS)
2458 /* Initialise the mutex and condition variables used by
2459 * the scheduler. */
2460 initMutex(&sched_mutex);
2461 #endif
2462
2463 ACQUIRE_LOCK(&sched_mutex);
2464
2465 /* A capability holds the state a native thread needs in
2466 * order to execute STG code. At least one capability is
2467 * floating around (only THREADED_RTS builds have more than one).
2468 */
2469 initCapabilities();
2470
2471 initTaskManager();
2472
2473 /*
2474 * Eagerly start one worker to run each Capability, except for
2475 * Capability 0. The idea is that we're probably going to start a
2476 * bound thread on Capability 0 pretty soon, so we don't want a
2477 * worker task hogging it.
2478 */
2479 startWorkerTasks(1, n_capabilities);
2480
2481 RELEASE_LOCK(&sched_mutex);
2482
2483 }
2484
2485 void
2486 exitScheduler (rtsBool wait_foreign USED_IF_THREADS)
2487 /* see Capability.c, shutdownCapability() */
2488 {
2489 Task *task = NULL;
2490
2491 task = newBoundTask();
2492
2493 // If we haven't killed all the threads yet, do it now.
2494 if (sched_state < SCHED_SHUTTING_DOWN) {
2495 sched_state = SCHED_INTERRUPTING;
2496 Capability *cap = task->cap;
2497 waitForReturnCapability(&cap,task);
2498 scheduleDoGC(&cap,task,rtsTrue);
2499 ASSERT(task->incall->tso == NULL);
2500 releaseCapability(cap);
2501 }
2502 sched_state = SCHED_SHUTTING_DOWN;
2503
2504 shutdownCapabilities(task, wait_foreign);
2505
2506 // debugBelch("n_failed_trygrab_idles = %d, n_idle_caps = %d\n",
2507 // n_failed_trygrab_idles, n_idle_caps);
2508
2509 boundTaskExiting(task);
2510 }
2511
2512 void
2513 freeScheduler( void )
2514 {
2515 nat still_running;
2516
2517 ACQUIRE_LOCK(&sched_mutex);
2518 still_running = freeTaskManager();
2519 // We can only free the Capabilities if there are no Tasks still
2520 // running. We might have a Task about to return from a foreign
2521 // call into waitForReturnCapability(), for example (actually,
2522 // this should be the *only* thing that a still-running Task can
2523 // do at this point, and it will block waiting for the
2524 // Capability).
2525 if (still_running == 0) {
2526 freeCapabilities();
2527 }
2528 RELEASE_LOCK(&sched_mutex);
2529 #if defined(THREADED_RTS)
2530 closeMutex(&sched_mutex);
2531 #endif
2532 }
2533
2534 void markScheduler (evac_fn evac USED_IF_NOT_THREADS,
2535 void *user USED_IF_NOT_THREADS)
2536 {
2537 #if !defined(THREADED_RTS)
2538 evac(user, (StgClosure **)(void *)&blocked_queue_hd);
2539 evac(user, (StgClosure **)(void *)&blocked_queue_tl);
2540 evac(user, (StgClosure **)(void *)&sleeping_queue);
2541 #endif
2542 }
2543
2544 /* -----------------------------------------------------------------------------
2545 performGC
2546
2547 This is the interface to the garbage collector from Haskell land.
2548 We provide this so that external C code can allocate and garbage
2549 collect when called from Haskell via _ccall_GC.
2550 -------------------------------------------------------------------------- */
2551
2552 static void
2553 performGC_(rtsBool force_major)
2554 {
2555 Task *task;
2556 Capability *cap = NULL;
2557
2558 // We must grab a new Task here, because the existing Task may be
2559 // associated with a particular Capability, and chained onto the
2560 // suspended_ccalls queue.
2561 task = newBoundTask();
2562
2563 // TODO: do we need to traceTask*() here?
2564
2565 waitForReturnCapability(&cap,task);
2566 scheduleDoGC(&cap,task,force_major);
2567 releaseCapability(cap);
2568 boundTaskExiting(task);
2569 }
2570
2571 void
2572 performGC(void)
2573 {
2574 performGC_(rtsFalse);
2575 }
2576
2577 void
2578 performMajorGC(void)
2579 {
2580 performGC_(rtsTrue);
2581 }
2582
2583 /* ---------------------------------------------------------------------------
2584 Interrupt execution
2585 - usually called inside a signal handler so it mustn't do anything fancy.
2586 ------------------------------------------------------------------------ */
2587
2588 void
2589 interruptStgRts(void)
2590 {
2591 sched_state = SCHED_INTERRUPTING;
2592 interruptAllCapabilities();
2593 #if defined(THREADED_RTS)
2594 wakeUpRts();
2595 #endif
2596 }
2597
2598 /* -----------------------------------------------------------------------------
2599 Wake up the RTS
2600
2601 This function causes at least one OS thread to wake up and run the
2602 scheduler loop. It is invoked when the RTS might be deadlocked, or
2603 an external event has arrived that may need servicing (eg. a
2604 keyboard interrupt).
2605
2606 In the single-threaded RTS we don't do anything here; we only have
2607 one thread anyway, and the event that caused us to want to wake up
2608 will have interrupted any blocking system call in progress anyway.
2609 -------------------------------------------------------------------------- */
2610
2611 #if defined(THREADED_RTS)
2612 void wakeUpRts(void)
2613 {
2614 // This forces the IO Manager thread to wakeup, which will
2615 // in turn ensure that some OS thread wakes up and runs the
2616 // scheduler loop, which will cause a GC and deadlock check.
2617 ioManagerWakeup();
2618 }
2619 #endif
2620
2621 /* -----------------------------------------------------------------------------
2622 Deleting threads
2623
2624 This is used for interruption (^C) and forking, and corresponds to
2625 raising an exception but without letting the thread catch the
2626 exception.
2627 -------------------------------------------------------------------------- */
2628
2629 static void
2630 deleteThread (Capability *cap STG_UNUSED, StgTSO *tso)
2631 {
2632 // NOTE: must only be called on a TSO that we have exclusive
2633 // access to, because we will call throwToSingleThreaded() below.
2634 // The TSO must be on the run queue of the Capability we own, or
2635 // we must own all Capabilities.
2636
2637 if (tso->why_blocked != BlockedOnCCall &&
2638 tso->why_blocked != BlockedOnCCall_Interruptible) {
2639 throwToSingleThreaded(tso->cap,tso,NULL);
2640 }
2641 }
2642
2643 #ifdef FORKPROCESS_PRIMOP_SUPPORTED
2644 static void
2645 deleteThread_(Capability *cap, StgTSO *tso)
2646 { // for forkProcess only:
2647 // like deleteThread(), but we delete threads in foreign calls, too.
2648
2649 if (tso->why_blocked == BlockedOnCCall ||
2650 tso->why_blocked == BlockedOnCCall_Interruptible) {
2651 tso->what_next = ThreadKilled;
2652 appendToRunQueue(tso->cap, tso);
2653 } else {
2654 deleteThread(cap,tso);
2655 }
2656 }
2657 #endif
2658
2659 /* -----------------------------------------------------------------------------
2660 raiseExceptionHelper
2661
2662 This function is called by the raise# primitve, just so that we can
2663 move some of the tricky bits of raising an exception from C-- into
2664 C. Who knows, it might be a useful re-useable thing here too.
2665 -------------------------------------------------------------------------- */
2666
2667 StgWord
2668 raiseExceptionHelper (StgRegTable *reg, StgTSO *tso, StgClosure *exception)
2669 {
2670 Capability *cap = regTableToCapability(reg);
2671 StgThunk *raise_closure = NULL;
2672 StgPtr p, next;
2673 StgRetInfoTable *info;
2674 //
2675 // This closure represents the expression 'raise# E' where E
2676 // is the exception raise. It is used to overwrite all the
2677 // thunks which are currently under evaluataion.
2678 //
2679
2680 // OLD COMMENT (we don't have MIN_UPD_SIZE now):
2681 // LDV profiling: stg_raise_info has THUNK as its closure
2682 // type. Since a THUNK takes at least MIN_UPD_SIZE words in its
2683 // payload, MIN_UPD_SIZE is more approprate than 1. It seems that
2684 // 1 does not cause any problem unless profiling is performed.
2685 // However, when LDV profiling goes on, we need to linearly scan
2686 // small object pool, where raise_closure is stored, so we should
2687 // use MIN_UPD_SIZE.
2688 //
2689 // raise_closure = (StgClosure *)RET_STGCALL1(P_,allocate,
2690 // sizeofW(StgClosure)+1);
2691 //
2692
2693 //
2694 // Walk up the stack, looking for the catch frame. On the way,
2695 // we update any closures pointed to from update frames with the
2696 // raise closure that we just built.
2697 //
2698 p = tso->stackobj->sp;
2699 while(1) {
2700 info = get_ret_itbl((StgClosure *)p);
2701 next = p + stack_frame_sizeW((StgClosure *)p);
2702 switch (info->i.type) {
2703
2704 case UPDATE_FRAME:
2705 // Only create raise_closure if we need to.
2706 if (raise_closure == NULL) {
2707 raise_closure =
2708 (StgThunk *)allocate(cap,sizeofW(StgThunk)+1);
2709 SET_HDR(raise_closure, &stg_raise_info, cap->r.rCCCS);
2710 raise_closure->payload[0] = exception;
2711 }
2712 updateThunk(cap, tso, ((StgUpdateFrame *)p)->updatee,
2713 (StgClosure *)raise_closure);
2714 p = next;
2715 continue;
2716
2717 case ATOMICALLY_FRAME:
2718 debugTrace(DEBUG_stm, "found ATOMICALLY_FRAME at %p", p);
2719 tso->stackobj->sp = p;
2720 return ATOMICALLY_FRAME;
2721
2722 case CATCH_FRAME:
2723 tso->stackobj->sp = p;
2724 return CATCH_FRAME;
2725
2726 case CATCH_STM_FRAME:
2727 debugTrace(DEBUG_stm, "found CATCH_STM_FRAME at %p", p);
2728 tso->stackobj->sp = p;
2729 return CATCH_STM_FRAME;
2730
2731 case UNDERFLOW_FRAME:
2732 tso->stackobj->sp = p;
2733 threadStackUnderflow(cap,tso);
2734 p = tso->stackobj->sp;
2735 continue;
2736
2737 case STOP_FRAME:
2738 tso->stackobj->sp = p;
2739 return STOP_FRAME;
2740
2741 case CATCH_RETRY_FRAME: {
2742 StgTRecHeader *trec = tso -> trec;
2743 StgTRecHeader *outer = trec -> enclosing_trec;
2744 debugTrace(DEBUG_stm,
2745 "found CATCH_RETRY_FRAME at %p during raise", p);
2746 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2747 stmAbortTransaction(cap, trec);
2748 stmFreeAbortedTRec(cap, trec);
2749 tso -> trec = outer;
2750 p = next;
2751 continue;
2752 }
2753
2754 default:
2755 p = next;
2756 continue;
2757 }
2758 }
2759 }
2760
2761
2762 /* -----------------------------------------------------------------------------
2763 findRetryFrameHelper
2764
2765 This function is called by the retry# primitive. It traverses the stack
2766 leaving tso->sp referring to the frame which should handle the retry.
2767
2768 This should either be a CATCH_RETRY_FRAME (if the retry# is within an orElse#)
2769 or should be a ATOMICALLY_FRAME (if the retry# reaches the top level).
2770
2771 We skip CATCH_STM_FRAMEs (aborting and rolling back the nested tx that they
2772 create) because retries are not considered to be exceptions, despite the
2773 similar implementation.
2774
2775 We should not expect to see CATCH_FRAME or STOP_FRAME because those should
2776 not be created within memory transactions.
2777 -------------------------------------------------------------------------- */
2778
2779 StgWord
2780 findRetryFrameHelper (Capability *cap, StgTSO *tso)
2781 {
2782 StgPtr p, next;
2783 StgRetInfoTable *info;
2784
2785 p = tso->stackobj->sp;
2786 while (1) {
2787 info = get_ret_itbl((StgClosure *)p);
2788 next = p + stack_frame_sizeW((StgClosure *)p);
2789 switch (info->i.type) {
2790
2791 case ATOMICALLY_FRAME:
2792 debugTrace(DEBUG_stm,
2793 "found ATOMICALLY_FRAME at %p during retry", p);
2794 tso->stackobj->sp = p;
2795 return ATOMICALLY_FRAME;
2796
2797 case CATCH_RETRY_FRAME:
2798 debugTrace(DEBUG_stm,
2799 "found CATCH_RETRY_FRAME at %p during retry", p);
2800 tso->stackobj->sp = p;
2801 return CATCH_RETRY_FRAME;
2802
2803 case CATCH_STM_FRAME: {
2804 StgTRecHeader *trec = tso -> trec;
2805 StgTRecHeader *outer = trec -> enclosing_trec;
2806 debugTrace(DEBUG_stm,
2807 "found CATCH_STM_FRAME at %p during retry", p);
2808 debugTrace(DEBUG_stm, "trec=%p outer=%p", trec, outer);
2809 stmAbortTransaction(cap, trec);
2810 stmFreeAbortedTRec(cap, trec);
2811 tso -> trec = outer;
2812 p = next;
2813 continue;
2814 }
2815
2816 case UNDERFLOW_FRAME:
2817 tso->stackobj->sp = p;
2818 threadStackUnderflow(cap,tso);
2819 p = tso->stackobj->sp;
2820 continue;
2821
2822 default:
2823 ASSERT(info->i.type != CATCH_FRAME);
2824 ASSERT(info->i.type != STOP_FRAME);
2825 p = next;
2826 continue;
2827 }
2828 }
2829 }
2830
2831 /* -----------------------------------------------------------------------------
2832 resurrectThreads is called after garbage collection on the list of
2833 threads found to be garbage. Each of these threads will be woken
2834 up and sent a signal: BlockedOnDeadMVar if the thread was blocked
2835 on an MVar, or NonTermination if the thread was blocked on a Black
2836 Hole.
2837
2838 Locks: assumes we hold *all* the capabilities.
2839 -------------------------------------------------------------------------- */
2840
2841 void
2842 resurrectThreads (StgTSO *threads)
2843 {
2844 StgTSO *tso, *next;
2845 Capability *cap;
2846 generation *gen;
2847
2848 for (tso = threads; tso != END_TSO_QUEUE; tso = next) {
2849 next = tso->global_link;
2850
2851 gen = Bdescr((P_)tso)->gen;
2852 tso->global_link = gen->threads;
2853 gen->threads = tso;
2854
2855 debugTrace(DEBUG_sched, "resurrecting thread %lu", (unsigned long)tso->id);
2856
2857 // Wake up the thread on the Capability it was last on
2858 cap = tso->cap;
2859
2860 switch (tso->why_blocked) {
2861 case BlockedOnMVar:
2862 case BlockedOnMVarRead:
2863 /* Called by GC - sched_mutex lock is currently held. */
2864 throwToSingleThreaded(cap, tso,
2865 (StgClosure *)blockedIndefinitelyOnMVar_closure);
2866 break;
2867 case BlockedOnBlackHole:
2868 throwToSingleThreaded(cap, tso,
2869 (StgClosure *)nonTermination_closure);
2870 break;
2871 case BlockedOnSTM:
2872 throwToSingleThreaded(cap, tso,
2873 (StgClosure *)blockedIndefinitelyOnSTM_closure);
2874 break;
2875 case NotBlocked:
2876 /* This might happen if the thread was blocked on a black hole
2877 * belonging to a thread that we've just woken up (raiseAsync
2878 * can wake up threads, remember...).
2879 */
2880 continue;
2881 case BlockedOnMsgThrowTo:
2882 // This can happen if the target is masking, blocks on a
2883 // black hole, and then is found to be unreachable. In
2884 // this case, we want to let the target wake up and carry
2885 // on, and do nothing to this thread.
2886 continue;
2887 default:
2888 barf("resurrectThreads: thread blocked in a strange way: %d",
2889 tso->why_blocked);
2890 }
2891 }
2892 }