1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 2003-2012
7 * A Capability represents the token required to execute STG code,
8 * and all the state an OS thread/task needs to run Haskell code:
9 * its STG registers, a pointer to its TSO, a nursery etc. During
10 * STG execution, a pointer to the capabilitity is kept in a
11 * register (BaseReg; actually it is a pointer to cap->r).
13 * Only in an THREADED_RTS build will there be multiple capabilities,
14 * for non-threaded builds there is only one global capability, namely
17 * --------------------------------------------------------------------------*/
19 #include "PosixSource.h"
22 #include "Capability.h"
26 #include "sm/GC.h" // for gcWorkerThread()
32 // one global capability, this is the Capability for non-threaded
33 // builds, and for +RTS -N1
34 Capability MainCapability
;
36 nat n_capabilities
= 0;
37 nat enabled_capabilities
= 0;
38 Capability
*capabilities
= NULL
;
40 // Holds the Capability which last became free. This is used so that
41 // an in-call has a chance of quickly finding a free Capability.
42 // Maintaining a global free list of Capabilities would require global
43 // locking, so we don't do that.
44 Capability
*last_free_capability
= NULL
;
47 * Indicates that the RTS wants to synchronise all the Capabilities
48 * for some reason. All Capabilities should stop and return to the
51 volatile StgWord pending_sync
= 0;
53 /* Let foreign code get the current Capability -- assuming there is one!
54 * This is useful for unsafe foreign calls because they are called with
55 * the current Capability held, but they are not passed it. For example,
56 * see see the integer-gmp package which calls allocate() in its
57 * stgAllocForGMP() function (which gets called by gmp functions).
59 Capability
* rts_unsafeGetMyCapability (void)
61 #if defined(THREADED_RTS)
64 return &MainCapability
;
68 #if defined(THREADED_RTS)
72 return sched_state
>= SCHED_INTERRUPTING
73 || recent_activity
== ACTIVITY_INACTIVE
; // need to check for deadlock
77 #if defined(THREADED_RTS)
79 findSpark (Capability
*cap
)
86 if (!emptyRunQueue(cap
) || cap
->returning_tasks_hd
!= NULL
) {
87 // If there are other threads, don't try to run any new
88 // sparks: sparks might be speculative, we don't want to take
89 // resources away from the main computation.
96 // first try to get a spark from our own pool.
97 // We should be using reclaimSpark(), because it works without
98 // needing any atomic instructions:
99 // spark = reclaimSpark(cap->sparks);
100 // However, measurements show that this makes at least one benchmark
101 // slower (prsa) and doesn't affect the others.
102 spark
= tryStealSpark(cap
->sparks
);
103 while (spark
!= NULL
&& fizzledSpark(spark
)) {
104 cap
->spark_stats
.fizzled
++;
105 traceEventSparkFizzle(cap
);
106 spark
= tryStealSpark(cap
->sparks
);
109 cap
->spark_stats
.converted
++;
111 // Post event for running a spark from capability's own pool.
112 traceEventSparkRun(cap
);
116 if (!emptySparkPoolCap(cap
)) {
120 if (n_capabilities
== 1) { return NULL
; } // makes no sense...
122 debugTrace(DEBUG_sched
,
123 "cap %d: Trying to steal work from other capabilities",
126 /* visit cap.s 0..n-1 in sequence until a theft succeeds. We could
127 start at a random place instead of 0 as well. */
128 for ( i
=0 ; i
< n_capabilities
; i
++ ) {
129 robbed
= &capabilities
[i
];
130 if (cap
== robbed
) // ourselves...
133 if (emptySparkPoolCap(robbed
)) // nothing to steal here
136 spark
= tryStealSpark(robbed
->sparks
);
137 while (spark
!= NULL
&& fizzledSpark(spark
)) {
138 cap
->spark_stats
.fizzled
++;
139 traceEventSparkFizzle(cap
);
140 spark
= tryStealSpark(robbed
->sparks
);
142 if (spark
== NULL
&& !emptySparkPoolCap(robbed
)) {
143 // we conflicted with another thread while trying to steal;
149 cap
->spark_stats
.converted
++;
150 traceEventSparkSteal(cap
, robbed
->no
);
154 // otherwise: no success, try next one
158 debugTrace(DEBUG_sched
, "No sparks stolen");
162 // Returns True if any spark pool is non-empty at this moment in time
163 // The result is only valid for an instant, of course, so in a sense
164 // is immediately invalid, and should not be relied upon for
171 for (i
=0; i
< n_capabilities
; i
++) {
172 if (!emptySparkPoolCap(&capabilities
[i
])) {
180 /* -----------------------------------------------------------------------------
181 * Manage the returning_tasks lists.
183 * These functions require cap->lock
184 * -------------------------------------------------------------------------- */
186 #if defined(THREADED_RTS)
188 newReturningTask (Capability
*cap
, Task
*task
)
190 ASSERT_LOCK_HELD(&cap
->lock
);
191 ASSERT(task
->next
== NULL
);
192 if (cap
->returning_tasks_hd
) {
193 ASSERT(cap
->returning_tasks_tl
->next
== NULL
);
194 cap
->returning_tasks_tl
->next
= task
;
196 cap
->returning_tasks_hd
= task
;
198 cap
->returning_tasks_tl
= task
;
202 popReturningTask (Capability
*cap
)
204 ASSERT_LOCK_HELD(&cap
->lock
);
206 task
= cap
->returning_tasks_hd
;
208 cap
->returning_tasks_hd
= task
->next
;
209 if (!cap
->returning_tasks_hd
) {
210 cap
->returning_tasks_tl
= NULL
;
217 /* ----------------------------------------------------------------------------
220 * The Capability is initially marked not free.
221 * ------------------------------------------------------------------------- */
224 initCapability( Capability
*cap
, nat i
)
229 cap
->in_haskell
= rtsFalse
;
231 cap
->disabled
= rtsFalse
;
233 cap
->run_queue_hd
= END_TSO_QUEUE
;
234 cap
->run_queue_tl
= END_TSO_QUEUE
;
236 #if defined(THREADED_RTS)
237 initMutex(&cap
->lock
);
238 cap
->running_task
= NULL
; // indicates cap is free
239 cap
->spare_workers
= NULL
;
240 cap
->n_spare_workers
= 0;
241 cap
->suspended_ccalls
= NULL
;
242 cap
->returning_tasks_hd
= NULL
;
243 cap
->returning_tasks_tl
= NULL
;
244 cap
->inbox
= (Message
*)END_TSO_QUEUE
;
245 cap
->sparks
= allocSparkPool();
246 cap
->spark_stats
.created
= 0;
247 cap
->spark_stats
.dud
= 0;
248 cap
->spark_stats
.overflowed
= 0;
249 cap
->spark_stats
.converted
= 0;
250 cap
->spark_stats
.gcd
= 0;
251 cap
->spark_stats
.fizzled
= 0;
253 cap
->total_allocated
= 0;
255 cap
->f
.stgEagerBlackholeInfo
= (W_
)&__stg_EAGER_BLACKHOLE_info
;
256 cap
->f
.stgGCEnter1
= (StgFunPtr
)__stg_gc_enter_1
;
257 cap
->f
.stgGCFun
= (StgFunPtr
)__stg_gc_fun
;
259 cap
->mut_lists
= stgMallocBytes(sizeof(bdescr
*) *
260 RtsFlags
.GcFlags
.generations
,
262 cap
->saved_mut_lists
= stgMallocBytes(sizeof(bdescr
*) *
263 RtsFlags
.GcFlags
.generations
,
266 for (g
= 0; g
< RtsFlags
.GcFlags
.generations
; g
++) {
267 cap
->mut_lists
[g
] = NULL
;
270 cap
->free_tvar_watch_queues
= END_STM_WATCH_QUEUE
;
271 cap
->free_invariant_check_queues
= END_INVARIANT_CHECK_QUEUE
;
272 cap
->free_trec_chunks
= END_STM_CHUNK_LIST
;
273 cap
->free_trec_headers
= NO_TREC
;
274 cap
->transaction_tokens
= 0;
275 cap
->context_switch
= 0;
276 cap
->pinned_object_block
= NULL
;
277 cap
->pinned_object_blocks
= NULL
;
280 cap
->r
.rCCCS
= CCS_SYSTEM
;
286 traceCapsetAssignCap(CAPSET_OSPROCESS_DEFAULT
, i
);
287 traceCapsetAssignCap(CAPSET_CLOCKDOMAIN_DEFAULT
, i
);
288 #if defined(THREADED_RTS)
289 traceSparkCounters(cap
);
293 /* ---------------------------------------------------------------------------
294 * Function: initCapabilities()
296 * Purpose: set up the Capability handling. For the THREADED_RTS build,
297 * we keep a table of them, the size of which is
298 * controlled by the user via the RTS flag -N.
300 * ------------------------------------------------------------------------- */
302 initCapabilities( void )
304 /* Declare a couple capability sets representing the process and
305 clock domain. Each capability will get added to these capsets. */
306 traceCapsetCreate(CAPSET_OSPROCESS_DEFAULT
, CapsetTypeOsProcess
);
307 traceCapsetCreate(CAPSET_CLOCKDOMAIN_DEFAULT
, CapsetTypeClockdomain
);
309 #if defined(THREADED_RTS)
312 // We can't support multiple CPUs if BaseReg is not a register
313 if (RtsFlags
.ParFlags
.nNodes
> 1) {
314 errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
315 RtsFlags
.ParFlags
.nNodes
= 1;
320 moreCapabilities(0, RtsFlags
.ParFlags
.nNodes
);
321 n_capabilities
= RtsFlags
.ParFlags
.nNodes
;
323 #else /* !THREADED_RTS */
326 capabilities
= &MainCapability
;
327 initCapability(&MainCapability
, 0);
331 enabled_capabilities
= n_capabilities
;
333 // There are no free capabilities to begin with. We will start
334 // a worker Task to each Capability, which will quickly put the
335 // Capability on the free list when it finds nothing to do.
336 last_free_capability
= &capabilities
[0];
340 moreCapabilities (nat from USED_IF_THREADS
, nat to USED_IF_THREADS
)
342 #if defined(THREADED_RTS)
344 Capability
*old_capabilities
= capabilities
;
347 // THREADED_RTS must work on builds that don't have a mutable
348 // BaseReg (eg. unregisterised), so in this case
349 // capabilities[0] must coincide with &MainCapability.
350 capabilities
= &MainCapability
;
352 capabilities
= stgMallocBytes(to
* sizeof(Capability
),
356 memcpy(capabilities
, old_capabilities
, from
* sizeof(Capability
));
360 for (i
= from
; i
< to
; i
++) {
361 initCapability(&capabilities
[i
], i
);
364 last_free_capability
= &capabilities
[0];
366 debugTrace(DEBUG_sched
, "allocated %d more capabilities", to
- from
);
368 // Return the old array to free later.
370 return old_capabilities
;
379 /* ----------------------------------------------------------------------------
380 * setContextSwitches: cause all capabilities to context switch as
382 * ------------------------------------------------------------------------- */
384 void contextSwitchAllCapabilities(void)
387 for (i
=0; i
< n_capabilities
; i
++) {
388 contextSwitchCapability(&capabilities
[i
]);
392 void interruptAllCapabilities(void)
395 for (i
=0; i
< n_capabilities
; i
++) {
396 interruptCapability(&capabilities
[i
]);
400 /* ----------------------------------------------------------------------------
401 * Give a Capability to a Task. The task must currently be sleeping
402 * on its condition variable.
404 * Requires cap->lock (modifies cap->running_task).
406 * When migrating a Task, the migrater must take task->lock before
407 * modifying task->cap, to synchronise with the waking up Task.
408 * Additionally, the migrater should own the Capability (when
409 * migrating the run queue), or cap->lock (when migrating
410 * returning_workers).
412 * ------------------------------------------------------------------------- */
414 #if defined(THREADED_RTS)
416 giveCapabilityToTask (Capability
*cap USED_IF_DEBUG
, Task
*task
)
418 ASSERT_LOCK_HELD(&cap
->lock
);
419 ASSERT(task
->cap
== cap
);
420 debugTrace(DEBUG_sched
, "passing capability %d to %s %#" FMT_HexWord64
,
421 cap
->no
, task
->incall
->tso ?
"bound task" : "worker",
422 serialisableTaskId(task
));
423 ACQUIRE_LOCK(&task
->lock
);
424 if (task
->wakeup
== rtsFalse
) {
425 task
->wakeup
= rtsTrue
;
426 // the wakeup flag is needed because signalCondition() doesn't
427 // flag the condition if the thread is already runniing, but we want
429 signalCondition(&task
->cond
);
431 RELEASE_LOCK(&task
->lock
);
435 /* ----------------------------------------------------------------------------
436 * Function: releaseCapability(Capability*)
438 * Purpose: Letting go of a capability. Causes a
439 * 'returning worker' thread or a 'waiting worker'
440 * to wake up, in that order.
441 * ------------------------------------------------------------------------- */
443 #if defined(THREADED_RTS)
445 releaseCapability_ (Capability
* cap
,
446 rtsBool always_wakeup
)
450 task
= cap
->running_task
;
452 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap
,task
);
454 cap
->running_task
= NULL
;
456 // Check to see whether a worker thread can be given
457 // the go-ahead to return the result of an external call..
458 if (cap
->returning_tasks_hd
!= NULL
) {
459 giveCapabilityToTask(cap
,cap
->returning_tasks_hd
);
460 // The Task pops itself from the queue (see waitForReturnCapability())
464 // If there is a pending sync, then we should just leave the
465 // Capability free. The thread trying to sync will be about to
466 // call waitForReturnCapability().
467 if (pending_sync
!= 0 && pending_sync
!= SYNC_GC_PAR
) {
468 last_free_capability
= cap
; // needed?
469 debugTrace(DEBUG_sched
, "sync pending, set capability %d free", cap
->no
);
473 // If the next thread on the run queue is a bound thread,
474 // give this Capability to the appropriate Task.
475 if (!emptyRunQueue(cap
) && peekRunQueue(cap
)->bound
) {
476 // Make sure we're not about to try to wake ourselves up
477 // ASSERT(task != cap->run_queue_hd->bound);
478 // assertion is false: in schedule() we force a yield after
479 // ThreadBlocked, but the thread may be back on the run queue
481 task
= peekRunQueue(cap
)->bound
->task
;
482 giveCapabilityToTask(cap
, task
);
486 if (!cap
->spare_workers
) {
487 // Create a worker thread if we don't have one. If the system
488 // is interrupted, we only create a worker task if there
489 // are threads that need to be completed. If the system is
490 // shutting down, we never create a new worker.
491 if (sched_state
< SCHED_SHUTTING_DOWN
|| !emptyRunQueue(cap
)) {
492 debugTrace(DEBUG_sched
,
493 "starting new worker on capability %d", cap
->no
);
494 startWorkerTask(cap
);
499 // If we have an unbound thread on the run queue, or if there's
500 // anything else to do, give the Capability to a worker thread.
502 !emptyRunQueue(cap
) || !emptyInbox(cap
) ||
503 (!cap
->disabled
&& !emptySparkPoolCap(cap
)) || globalWorkToDo()) {
504 if (cap
->spare_workers
) {
505 giveCapabilityToTask(cap
, cap
->spare_workers
);
506 // The worker Task pops itself from the queue;
512 cap
->r
.rCCCS
= CCS_IDLE
;
514 last_free_capability
= cap
;
515 debugTrace(DEBUG_sched
, "freeing capability %d", cap
->no
);
519 releaseCapability (Capability
* cap USED_IF_THREADS
)
521 ACQUIRE_LOCK(&cap
->lock
);
522 releaseCapability_(cap
, rtsFalse
);
523 RELEASE_LOCK(&cap
->lock
);
527 releaseAndWakeupCapability (Capability
* cap USED_IF_THREADS
)
529 ACQUIRE_LOCK(&cap
->lock
);
530 releaseCapability_(cap
, rtsTrue
);
531 RELEASE_LOCK(&cap
->lock
);
535 releaseCapabilityAndQueueWorker (Capability
* cap USED_IF_THREADS
)
539 ACQUIRE_LOCK(&cap
->lock
);
541 task
= cap
->running_task
;
543 // If the Task is stopped, we shouldn't be yielding, we should
545 ASSERT(!task
->stopped
);
547 // If the current task is a worker, save it on the spare_workers
548 // list of this Capability. A worker can mark itself as stopped,
549 // in which case it is not replaced on the spare_worker queue.
550 // This happens when the system is shutting down (see
551 // Schedule.c:workerStart()).
552 if (!isBoundTask(task
))
554 if (cap
->n_spare_workers
< MAX_SPARE_WORKERS
)
556 task
->next
= cap
->spare_workers
;
557 cap
->spare_workers
= task
;
558 cap
->n_spare_workers
++;
562 debugTrace(DEBUG_sched
, "%d spare workers already, exiting",
563 cap
->n_spare_workers
);
564 releaseCapability_(cap
,rtsFalse
);
565 // hold the lock until after workerTaskStop; c.f. scheduleWorker()
566 workerTaskStop(task
);
567 RELEASE_LOCK(&cap
->lock
);
571 // Bound tasks just float around attached to their TSOs.
573 releaseCapability_(cap
,rtsFalse
);
575 RELEASE_LOCK(&cap
->lock
);
579 /* ----------------------------------------------------------------------------
580 * waitForReturnCapability (Capability **pCap, Task *task)
582 * Purpose: when an OS thread returns from an external call,
583 * it calls waitForReturnCapability() (via Schedule.resumeThread())
584 * to wait for permission to enter the RTS & communicate the
585 * result of the external call back to the Haskell thread that
588 * ------------------------------------------------------------------------- */
590 waitForReturnCapability (Capability
**pCap
, Task
*task
)
592 #if !defined(THREADED_RTS)
594 MainCapability
.running_task
= task
;
595 task
->cap
= &MainCapability
;
596 *pCap
= &MainCapability
;
599 Capability
*cap
= *pCap
;
602 // Try last_free_capability first
603 cap
= last_free_capability
;
604 if (cap
->running_task
) {
606 // otherwise, search for a free capability
608 for (i
= 0; i
< n_capabilities
; i
++) {
609 if (!capabilities
[i
].running_task
) {
610 cap
= &capabilities
[i
];
615 // Can't find a free one, use last_free_capability.
616 cap
= last_free_capability
;
620 // record the Capability as the one this Task is now assocated with.
624 ASSERT(task
->cap
== cap
);
627 ACQUIRE_LOCK(&cap
->lock
);
629 debugTrace(DEBUG_sched
, "returning; I want capability %d", cap
->no
);
631 if (!cap
->running_task
) {
632 // It's free; just grab it
633 cap
->running_task
= task
;
634 RELEASE_LOCK(&cap
->lock
);
636 newReturningTask(cap
,task
);
637 RELEASE_LOCK(&cap
->lock
);
640 ACQUIRE_LOCK(&task
->lock
);
641 // task->lock held, cap->lock not held
642 if (!task
->wakeup
) waitCondition(&task
->cond
, &task
->lock
);
644 task
->wakeup
= rtsFalse
;
645 RELEASE_LOCK(&task
->lock
);
647 // now check whether we should wake up...
648 ACQUIRE_LOCK(&cap
->lock
);
649 if (cap
->running_task
== NULL
) {
650 if (cap
->returning_tasks_hd
!= task
) {
651 giveCapabilityToTask(cap
,cap
->returning_tasks_hd
);
652 RELEASE_LOCK(&cap
->lock
);
655 cap
->running_task
= task
;
656 popReturningTask(cap
);
657 RELEASE_LOCK(&cap
->lock
);
660 RELEASE_LOCK(&cap
->lock
);
666 cap
->r
.rCCCS
= CCS_SYSTEM
;
669 ASSERT_FULL_CAPABILITY_INVARIANTS(cap
, task
);
671 debugTrace(DEBUG_sched
, "resuming capability %d", cap
->no
);
677 #if defined(THREADED_RTS)
678 /* ----------------------------------------------------------------------------
680 * ------------------------------------------------------------------------- */
682 /* See Note [GC livelock] in Schedule.c for why we have gcAllowed
683 and return the rtsBool */
684 rtsBool
/* Did we GC? */
685 yieldCapability (Capability
** pCap
, Task
*task
, rtsBool gcAllowed
)
687 Capability
*cap
= *pCap
;
689 if ((pending_sync
== SYNC_GC_PAR
) && gcAllowed
) {
690 traceEventGcStart(cap
);
692 traceEventGcEnd(cap
);
693 traceSparkCounters(cap
);
694 // See Note [migrated bound threads 2]
695 if (task
->cap
== cap
) {
700 debugTrace(DEBUG_sched
, "giving up capability %d", cap
->no
);
702 // We must now release the capability and wait to be woken up
704 task
->wakeup
= rtsFalse
;
705 releaseCapabilityAndQueueWorker(cap
);
708 ACQUIRE_LOCK(&task
->lock
);
709 // task->lock held, cap->lock not held
710 if (!task
->wakeup
) waitCondition(&task
->cond
, &task
->lock
);
712 task
->wakeup
= rtsFalse
;
713 RELEASE_LOCK(&task
->lock
);
715 debugTrace(DEBUG_sched
, "woken up on capability %d", cap
->no
);
717 ACQUIRE_LOCK(&cap
->lock
);
718 if (cap
->running_task
!= NULL
) {
719 debugTrace(DEBUG_sched
,
720 "capability %d is owned by another task", cap
->no
);
721 RELEASE_LOCK(&cap
->lock
);
725 if (task
->cap
!= cap
) {
726 // see Note [migrated bound threads]
727 debugTrace(DEBUG_sched
,
728 "task has been migrated to cap %d", task
->cap
->no
);
729 RELEASE_LOCK(&cap
->lock
);
733 if (task
->incall
->tso
== NULL
) {
734 ASSERT(cap
->spare_workers
!= NULL
);
735 // if we're not at the front of the queue, release it
736 // again. This is unlikely to happen.
737 if (cap
->spare_workers
!= task
) {
738 giveCapabilityToTask(cap
,cap
->spare_workers
);
739 RELEASE_LOCK(&cap
->lock
);
742 cap
->spare_workers
= task
->next
;
744 cap
->n_spare_workers
--;
747 cap
->running_task
= task
;
748 RELEASE_LOCK(&cap
->lock
);
752 debugTrace(DEBUG_sched
, "resuming capability %d", cap
->no
);
753 ASSERT(cap
->running_task
== task
);
756 cap
->r
.rCCCS
= CCS_SYSTEM
;
761 ASSERT_FULL_CAPABILITY_INVARIANTS(cap
,task
);
766 // Note [migrated bound threads]
768 // There's a tricky case where:
769 // - cap A is running an unbound thread T1
770 // - there is a bound thread T2 at the head of the run queue on cap A
771 // - T1 makes a safe foreign call, the task bound to T2 is woken up on cap A
772 // - T1 returns quickly grabbing A again (T2 is still waking up on A)
773 // - T1 blocks, the scheduler migrates T2 to cap B
774 // - the task bound to T2 wakes up on cap B
776 // We take advantage of the following invariant:
778 // - A bound thread can only be migrated by the holder of the
779 // Capability on which the bound thread currently lives. So, if we
780 // hold Capabilty C, and task->cap == C, then task cannot be
781 // migrated under our feet.
783 // Note [migrated bound threads 2]
785 // Second tricky case;
786 // - A bound Task becomes a GC thread
787 // - scheduleDoGC() migrates the thread belonging to this Task,
788 // because the Capability it is on is disabled
789 // - after GC, gcWorkerThread() returns, but now we are
790 // holding a Capability that is not the same as task->cap
791 // - Hence we must check for this case and immediately give up the
794 /* ----------------------------------------------------------------------------
797 * If a Capability is currently idle, wake up a Task on it. Used to
798 * get every Capability into the GC.
799 * ------------------------------------------------------------------------- */
802 prodCapability (Capability
*cap
, Task
*task
)
804 ACQUIRE_LOCK(&cap
->lock
);
805 if (!cap
->running_task
) {
806 cap
->running_task
= task
;
807 releaseCapability_(cap
,rtsTrue
);
809 RELEASE_LOCK(&cap
->lock
);
812 /* ----------------------------------------------------------------------------
815 * Attempt to gain control of a Capability if it is free.
817 * ------------------------------------------------------------------------- */
820 tryGrabCapability (Capability
*cap
, Task
*task
)
822 if (cap
->running_task
!= NULL
) return rtsFalse
;
823 ACQUIRE_LOCK(&cap
->lock
);
824 if (cap
->running_task
!= NULL
) {
825 RELEASE_LOCK(&cap
->lock
);
829 cap
->running_task
= task
;
830 RELEASE_LOCK(&cap
->lock
);
835 #endif /* THREADED_RTS */
837 /* ----------------------------------------------------------------------------
840 * At shutdown time, we want to let everything exit as cleanly as
841 * possible. For each capability, we let its run queue drain, and
842 * allow the workers to stop.
844 * This function should be called when interrupted and
845 * sched_state = SCHED_SHUTTING_DOWN, thus any worker that wakes up
846 * will exit the scheduler and call taskStop(), and any bound thread
847 * that wakes up will return to its caller. Runnable threads are
850 * ------------------------------------------------------------------------- */
853 shutdownCapability (Capability
*cap USED_IF_THREADS
,
854 Task
*task USED_IF_THREADS
,
855 rtsBool safe USED_IF_THREADS
)
857 #if defined(THREADED_RTS)
862 // Loop indefinitely until all the workers have exited and there
863 // are no Haskell threads left. We used to bail out after 50
864 // iterations of this loop, but that occasionally left a worker
865 // running which caused problems later (the closeMutex() below
866 // isn't safe, for one thing).
868 for (i
= 0; /* i < 50 */; i
++) {
869 ASSERT(sched_state
== SCHED_SHUTTING_DOWN
);
871 debugTrace(DEBUG_sched
,
872 "shutting down capability %d, attempt %d", cap
->no
, i
);
873 ACQUIRE_LOCK(&cap
->lock
);
874 if (cap
->running_task
) {
875 RELEASE_LOCK(&cap
->lock
);
876 debugTrace(DEBUG_sched
, "not owner, yielding");
880 cap
->running_task
= task
;
882 if (cap
->spare_workers
) {
883 // Look for workers that have died without removing
884 // themselves from the list; this could happen if the OS
885 // summarily killed the thread, for example. This
886 // actually happens on Windows when the system is
887 // terminating the program, and the RTS is running in a
891 for (t
= cap
->spare_workers
; t
!= NULL
; t
= t
->next
) {
892 if (!osThreadIsAlive(t
->id
)) {
893 debugTrace(DEBUG_sched
,
894 "worker thread %p has died unexpectedly", (void *)(size_t)t
->id
);
895 cap
->n_spare_workers
--;
897 cap
->spare_workers
= t
->next
;
899 prev
->next
= t
->next
;
906 if (!emptyRunQueue(cap
) || cap
->spare_workers
) {
907 debugTrace(DEBUG_sched
,
908 "runnable threads or workers still alive, yielding");
909 releaseCapability_(cap
,rtsFalse
); // this will wake up a worker
910 RELEASE_LOCK(&cap
->lock
);
915 // If "safe", then busy-wait for any threads currently doing
916 // foreign calls. If we're about to unload this DLL, for
917 // example, we need to be sure that there are no OS threads
918 // that will try to return to code that has been unloaded.
919 // We can be a bit more relaxed when this is a standalone
920 // program that is about to terminate, and let safe=false.
921 if (cap
->suspended_ccalls
&& safe
) {
922 debugTrace(DEBUG_sched
,
923 "thread(s) are involved in foreign calls, yielding");
924 cap
->running_task
= NULL
;
925 RELEASE_LOCK(&cap
->lock
);
926 // The IO manager thread might have been slow to start up,
927 // so the first attempt to kill it might not have
928 // succeeded. Just in case, try again - the kill message
929 // will only be sent once.
931 // To reproduce this deadlock: run ffi002(threaded1)
932 // repeatedly on a loaded machine.
938 traceSparkCounters(cap
);
939 RELEASE_LOCK(&cap
->lock
);
942 // we now have the Capability, its run queue and spare workers
943 // list are both empty.
945 // ToDo: we can't drop this mutex, because there might still be
946 // threads performing foreign calls that will eventually try to
947 // return via resumeThread() and attempt to grab cap->lock.
948 // closeMutex(&cap->lock);
953 shutdownCapabilities(Task
*task
, rtsBool safe
)
956 for (i
=0; i
< n_capabilities
; i
++) {
957 ASSERT(task
->incall
->tso
== NULL
);
958 shutdownCapability(&capabilities
[i
], task
, safe
);
960 #if defined(THREADED_RTS)
961 ASSERT(checkSparkCountInvariant());
966 freeCapability (Capability
*cap
)
968 stgFree(cap
->mut_lists
);
969 stgFree(cap
->saved_mut_lists
);
970 #if defined(THREADED_RTS)
971 freeSparkPool(cap
->sparks
);
973 traceCapsetRemoveCap(CAPSET_OSPROCESS_DEFAULT
, cap
->no
);
974 traceCapsetRemoveCap(CAPSET_CLOCKDOMAIN_DEFAULT
, cap
->no
);
979 freeCapabilities (void)
981 #if defined(THREADED_RTS)
983 for (i
=0; i
< n_capabilities
; i
++) {
984 freeCapability(&capabilities
[i
]);
987 freeCapability(&MainCapability
);
989 traceCapsetDelete(CAPSET_OSPROCESS_DEFAULT
);
990 traceCapsetDelete(CAPSET_CLOCKDOMAIN_DEFAULT
);
993 /* ---------------------------------------------------------------------------
994 Mark everything directly reachable from the Capabilities. When
995 using multiple GC threads, each GC thread marks all Capabilities
996 for which (c `mod` n == 0), for Capability c and thread n.
997 ------------------------------------------------------------------------ */
1000 markCapability (evac_fn evac
, void *user
, Capability
*cap
,
1001 rtsBool no_mark_sparks USED_IF_THREADS
)
1005 // Each GC thread is responsible for following roots from the
1006 // Capability of the same number. There will usually be the same
1007 // or fewer Capabilities as GC threads, but just in case there
1008 // are more, we mark every Capability whose number is the GC
1009 // thread's index plus a multiple of the number of GC threads.
1010 evac(user
, (StgClosure
**)(void *)&cap
->run_queue_hd
);
1011 evac(user
, (StgClosure
**)(void *)&cap
->run_queue_tl
);
1012 #if defined(THREADED_RTS)
1013 evac(user
, (StgClosure
**)(void *)&cap
->inbox
);
1015 for (incall
= cap
->suspended_ccalls
; incall
!= NULL
;
1016 incall
=incall
->next
) {
1017 evac(user
, (StgClosure
**)(void *)&incall
->suspended_tso
);
1020 #if defined(THREADED_RTS)
1021 if (!no_mark_sparks
) {
1022 traverseSparkQueue (evac
, user
, cap
);
1026 // Free STM structures for this Capability
1031 markCapabilities (evac_fn evac
, void *user
)
1034 for (n
= 0; n
< n_capabilities
; n
++) {
1035 markCapability(evac
, user
, &capabilities
[n
], rtsFalse
);
1039 #if defined(THREADED_RTS)
1040 rtsBool
checkSparkCountInvariant (void)
1042 SparkCounters sparks
= { 0, 0, 0, 0, 0, 0 };
1043 StgWord64 remaining
= 0;
1046 for (i
= 0; i
< n_capabilities
; i
++) {
1047 sparks
.created
+= capabilities
[i
].spark_stats
.created
;
1048 sparks
.dud
+= capabilities
[i
].spark_stats
.dud
;
1049 sparks
.overflowed
+= capabilities
[i
].spark_stats
.overflowed
;
1050 sparks
.converted
+= capabilities
[i
].spark_stats
.converted
;
1051 sparks
.gcd
+= capabilities
[i
].spark_stats
.gcd
;
1052 sparks
.fizzled
+= capabilities
[i
].spark_stats
.fizzled
;
1053 remaining
+= sparkPoolSize(capabilities
[i
].sparks
);
1057 * created = converted + remaining + gcd + fizzled
1059 debugTrace(DEBUG_sparks
,"spark invariant: %ld == %ld + %ld + %ld + %ld "
1060 "(created == converted + remaining + gcd + fizzled)",
1061 sparks
.created
, sparks
.converted
, remaining
,
1062 sparks
.gcd
, sparks
.fizzled
);
1064 return (sparks
.created
==
1065 sparks
.converted
+ remaining
+ sparks
.gcd
+ sparks
.fizzled
);