1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 2003-2006
7 * A Capability represent 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 Capability
*capabilities
= NULL
;
39 // Holds the Capability which last became free. This is used so that
40 // an in-call has a chance of quickly finding a free Capability.
41 // Maintaining a global free list of Capabilities would require global
42 // locking, so we don't do that.
43 Capability
*last_free_capability
= NULL
;
46 * Indicates that the RTS wants to synchronise all the Capabilities
47 * for some reason. All Capabilities should stop and return to the
50 volatile StgWord pending_sync
= 0;
52 /* Let foreign code get the current Capability -- assuming there is one!
53 * This is useful for unsafe foreign calls because they are called with
54 * the current Capability held, but they are not passed it. For example,
55 * see see the integer-gmp package which calls allocate() in its
56 * stgAllocForGMP() function (which gets called by gmp functions).
58 Capability
* rts_unsafeGetMyCapability (void)
60 #if defined(THREADED_RTS)
63 return &MainCapability
;
67 #if defined(THREADED_RTS)
71 return sched_state
>= SCHED_INTERRUPTING
72 || recent_activity
== ACTIVITY_INACTIVE
; // need to check for deadlock
76 #if defined(THREADED_RTS)
78 findSpark (Capability
*cap
)
85 if (!emptyRunQueue(cap
) || cap
->returning_tasks_hd
!= NULL
) {
86 // If there are other threads, don't try to run any new
87 // sparks: sparks might be speculative, we don't want to take
88 // resources away from the main computation.
95 // first try to get a spark from our own pool.
96 // We should be using reclaimSpark(), because it works without
97 // needing any atomic instructions:
98 // spark = reclaimSpark(cap->sparks);
99 // However, measurements show that this makes at least one benchmark
100 // slower (prsa) and doesn't affect the others.
101 spark
= tryStealSpark(cap
->sparks
);
102 while (spark
!= NULL
&& fizzledSpark(spark
)) {
103 cap
->spark_stats
.fizzled
++;
104 traceEventSparkFizzle(cap
);
105 spark
= tryStealSpark(cap
->sparks
);
108 cap
->spark_stats
.converted
++;
110 // Post event for running a spark from capability's own pool.
111 traceEventSparkRun(cap
);
115 if (!emptySparkPoolCap(cap
)) {
119 if (n_capabilities
== 1) { return NULL
; } // makes no sense...
121 debugTrace(DEBUG_sched
,
122 "cap %d: Trying to steal work from other capabilities",
125 /* visit cap.s 0..n-1 in sequence until a theft succeeds. We could
126 start at a random place instead of 0 as well. */
127 for ( i
=0 ; i
< n_capabilities
; i
++ ) {
128 robbed
= &capabilities
[i
];
129 if (cap
== robbed
) // ourselves...
132 if (emptySparkPoolCap(robbed
)) // nothing to steal here
135 spark
= tryStealSpark(robbed
->sparks
);
136 while (spark
!= NULL
&& fizzledSpark(spark
)) {
137 cap
->spark_stats
.fizzled
++;
138 traceEventSparkFizzle(cap
);
139 spark
= tryStealSpark(robbed
->sparks
);
141 if (spark
== NULL
&& !emptySparkPoolCap(robbed
)) {
142 // we conflicted with another thread while trying to steal;
148 cap
->spark_stats
.converted
++;
149 traceEventSparkSteal(cap
, robbed
->no
);
153 // otherwise: no success, try next one
157 debugTrace(DEBUG_sched
, "No sparks stolen");
161 // Returns True if any spark pool is non-empty at this moment in time
162 // The result is only valid for an instant, of course, so in a sense
163 // is immediately invalid, and should not be relied upon for
170 for (i
=0; i
< n_capabilities
; i
++) {
171 if (!emptySparkPoolCap(&capabilities
[i
])) {
179 /* -----------------------------------------------------------------------------
180 * Manage the returning_tasks lists.
182 * These functions require cap->lock
183 * -------------------------------------------------------------------------- */
185 #if defined(THREADED_RTS)
187 newReturningTask (Capability
*cap
, Task
*task
)
189 ASSERT_LOCK_HELD(&cap
->lock
);
190 ASSERT(task
->next
== NULL
);
191 if (cap
->returning_tasks_hd
) {
192 ASSERT(cap
->returning_tasks_tl
->next
== NULL
);
193 cap
->returning_tasks_tl
->next
= task
;
195 cap
->returning_tasks_hd
= task
;
197 cap
->returning_tasks_tl
= task
;
201 popReturningTask (Capability
*cap
)
203 ASSERT_LOCK_HELD(&cap
->lock
);
205 task
= cap
->returning_tasks_hd
;
207 cap
->returning_tasks_hd
= task
->next
;
208 if (!cap
->returning_tasks_hd
) {
209 cap
->returning_tasks_tl
= NULL
;
216 /* ----------------------------------------------------------------------------
219 * The Capability is initially marked not free.
220 * ------------------------------------------------------------------------- */
223 initCapability( Capability
*cap
, nat i
)
228 cap
->in_haskell
= rtsFalse
;
231 cap
->run_queue_hd
= END_TSO_QUEUE
;
232 cap
->run_queue_tl
= END_TSO_QUEUE
;
234 #if defined(THREADED_RTS)
235 initMutex(&cap
->lock
);
236 cap
->running_task
= NULL
; // indicates cap is free
237 cap
->spare_workers
= NULL
;
238 cap
->n_spare_workers
= 0;
239 cap
->suspended_ccalls
= NULL
;
240 cap
->returning_tasks_hd
= NULL
;
241 cap
->returning_tasks_tl
= NULL
;
242 cap
->inbox
= (Message
*)END_TSO_QUEUE
;
243 cap
->sparks
= allocSparkPool();
244 cap
->spark_stats
.created
= 0;
245 cap
->spark_stats
.dud
= 0;
246 cap
->spark_stats
.overflowed
= 0;
247 cap
->spark_stats
.converted
= 0;
248 cap
->spark_stats
.gcd
= 0;
249 cap
->spark_stats
.fizzled
= 0;
252 cap
->f
.stgEagerBlackholeInfo
= (W_
)&__stg_EAGER_BLACKHOLE_info
;
253 cap
->f
.stgGCEnter1
= (StgFunPtr
)__stg_gc_enter_1
;
254 cap
->f
.stgGCFun
= (StgFunPtr
)__stg_gc_fun
;
256 cap
->mut_lists
= stgMallocBytes(sizeof(bdescr
*) *
257 RtsFlags
.GcFlags
.generations
,
259 cap
->saved_mut_lists
= stgMallocBytes(sizeof(bdescr
*) *
260 RtsFlags
.GcFlags
.generations
,
263 for (g
= 0; g
< RtsFlags
.GcFlags
.generations
; g
++) {
264 cap
->mut_lists
[g
] = NULL
;
267 cap
->free_tvar_watch_queues
= END_STM_WATCH_QUEUE
;
268 cap
->free_invariant_check_queues
= END_INVARIANT_CHECK_QUEUE
;
269 cap
->free_trec_chunks
= END_STM_CHUNK_LIST
;
270 cap
->free_trec_headers
= NO_TREC
;
271 cap
->transaction_tokens
= 0;
272 cap
->context_switch
= 0;
273 cap
->pinned_object_block
= NULL
;
276 cap
->r
.rCCCS
= CCS_SYSTEM
;
281 traceCapsetAssignCap(CAPSET_OSPROCESS_DEFAULT
, i
);
282 traceCapsetAssignCap(CAPSET_CLOCKDOMAIN_DEFAULT
, i
);
283 #if defined(THREADED_RTS)
284 traceSparkCounters(cap
);
288 /* ---------------------------------------------------------------------------
289 * Function: initCapabilities()
291 * Purpose: set up the Capability handling. For the THREADED_RTS build,
292 * we keep a table of them, the size of which is
293 * controlled by the user via the RTS flag -N.
295 * ------------------------------------------------------------------------- */
297 initCapabilities( void )
299 /* Declare a couple capability sets representing the process and
300 clock domain. Each capability will get added to these capsets. */
301 traceCapsetCreate(CAPSET_OSPROCESS_DEFAULT
, CapsetTypeOsProcess
);
302 traceCapsetCreate(CAPSET_CLOCKDOMAIN_DEFAULT
, CapsetTypeClockdomain
);
304 #if defined(THREADED_RTS)
307 // We can't support multiple CPUs if BaseReg is not a register
308 if (RtsFlags
.ParFlags
.nNodes
> 1) {
309 errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
310 RtsFlags
.ParFlags
.nNodes
= 1;
315 moreCapabilities(0, RtsFlags
.ParFlags
.nNodes
);
316 n_capabilities
= RtsFlags
.ParFlags
.nNodes
;
318 #else /* !THREADED_RTS */
321 capabilities
= &MainCapability
;
322 initCapability(&MainCapability
, 0);
326 // There are no free capabilities to begin with. We will start
327 // a worker Task to each Capability, which will quickly put the
328 // Capability on the free list when it finds nothing to do.
329 last_free_capability
= &capabilities
[0];
333 moreCapabilities (nat from USED_IF_THREADS
, nat to USED_IF_THREADS
)
335 #if defined(THREADED_RTS)
337 Capability
*old_capabilities
= capabilities
;
340 // THREADED_RTS must work on builds that don't have a mutable
341 // BaseReg (eg. unregisterised), so in this case
342 // capabilities[0] must coincide with &MainCapability.
343 capabilities
= &MainCapability
;
345 capabilities
= stgMallocBytes(to
* sizeof(Capability
),
349 memcpy(capabilities
, old_capabilities
, from
* sizeof(Capability
));
353 for (i
= from
; i
< to
; i
++) {
354 initCapability(&capabilities
[i
], i
);
357 last_free_capability
= NULL
;
359 debugTrace(DEBUG_sched
, "allocated %d more capabilities", to
- from
);
361 // Return the old array to free later.
363 return old_capabilities
;
372 /* ----------------------------------------------------------------------------
373 * setContextSwitches: cause all capabilities to context switch as
375 * ------------------------------------------------------------------------- */
377 void contextSwitchAllCapabilities(void)
380 for (i
=0; i
< n_capabilities
; i
++) {
381 contextSwitchCapability(&capabilities
[i
]);
385 void interruptAllCapabilities(void)
388 for (i
=0; i
< n_capabilities
; i
++) {
389 interruptCapability(&capabilities
[i
]);
393 /* ----------------------------------------------------------------------------
394 * Give a Capability to a Task. The task must currently be sleeping
395 * on its condition variable.
397 * Requires cap->lock (modifies cap->running_task).
399 * When migrating a Task, the migrater must take task->lock before
400 * modifying task->cap, to synchronise with the waking up Task.
401 * Additionally, the migrater should own the Capability (when
402 * migrating the run queue), or cap->lock (when migrating
403 * returning_workers).
405 * ------------------------------------------------------------------------- */
407 #if defined(THREADED_RTS)
409 giveCapabilityToTask (Capability
*cap USED_IF_DEBUG
, Task
*task
)
411 ASSERT_LOCK_HELD(&cap
->lock
);
412 ASSERT(task
->cap
== cap
);
413 debugTrace(DEBUG_sched
, "passing capability %d to %s %p",
414 cap
->no
, task
->incall
->tso ?
"bound task" : "worker",
416 ACQUIRE_LOCK(&task
->lock
);
417 if (task
->wakeup
== rtsFalse
) {
418 task
->wakeup
= rtsTrue
;
419 // the wakeup flag is needed because signalCondition() doesn't
420 // flag the condition if the thread is already runniing, but we want
422 signalCondition(&task
->cond
);
424 RELEASE_LOCK(&task
->lock
);
428 /* ----------------------------------------------------------------------------
429 * Function: releaseCapability(Capability*)
431 * Purpose: Letting go of a capability. Causes a
432 * 'returning worker' thread or a 'waiting worker'
433 * to wake up, in that order.
434 * ------------------------------------------------------------------------- */
436 #if defined(THREADED_RTS)
438 releaseCapability_ (Capability
* cap
,
439 rtsBool always_wakeup
)
443 task
= cap
->running_task
;
445 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap
,task
);
447 cap
->running_task
= NULL
;
449 // Check to see whether a worker thread can be given
450 // the go-ahead to return the result of an external call..
451 if (cap
->returning_tasks_hd
!= NULL
) {
452 giveCapabilityToTask(cap
,cap
->returning_tasks_hd
);
453 // The Task pops itself from the queue (see waitForReturnCapability())
457 // If there is a pending sync, then we should just leave the
458 // Capability free. The thread trying to sync will be about to
459 // call waitForReturnCapability().
460 if (pending_sync
!= 0 && pending_sync
!= SYNC_GC_PAR
) {
461 last_free_capability
= cap
; // needed?
462 debugTrace(DEBUG_sched
, "sync pending, set capability %d free", cap
->no
);
466 // If the next thread on the run queue is a bound thread,
467 // give this Capability to the appropriate Task.
468 if (!emptyRunQueue(cap
) && cap
->run_queue_hd
->bound
) {
469 // Make sure we're not about to try to wake ourselves up
470 // ASSERT(task != cap->run_queue_hd->bound);
471 // assertion is false: in schedule() we force a yield after
472 // ThreadBlocked, but the thread may be back on the run queue
474 task
= cap
->run_queue_hd
->bound
->task
;
475 giveCapabilityToTask(cap
,task
);
479 if (!cap
->spare_workers
) {
480 // Create a worker thread if we don't have one. If the system
481 // is interrupted, we only create a worker task if there
482 // are threads that need to be completed. If the system is
483 // shutting down, we never create a new worker.
484 if (sched_state
< SCHED_SHUTTING_DOWN
|| !emptyRunQueue(cap
)) {
485 debugTrace(DEBUG_sched
,
486 "starting new worker on capability %d", cap
->no
);
487 startWorkerTask(cap
);
492 // If we have an unbound thread on the run queue, or if there's
493 // anything else to do, give the Capability to a worker thread.
495 !emptyRunQueue(cap
) || !emptyInbox(cap
) ||
496 !emptySparkPoolCap(cap
) || globalWorkToDo()) {
497 if (cap
->spare_workers
) {
498 giveCapabilityToTask(cap
,cap
->spare_workers
);
499 // The worker Task pops itself from the queue;
505 cap
->r
.rCCCS
= CCS_IDLE
;
507 last_free_capability
= cap
;
508 debugTrace(DEBUG_sched
, "freeing capability %d", cap
->no
);
512 releaseCapability (Capability
* cap USED_IF_THREADS
)
514 ACQUIRE_LOCK(&cap
->lock
);
515 releaseCapability_(cap
, rtsFalse
);
516 RELEASE_LOCK(&cap
->lock
);
520 releaseAndWakeupCapability (Capability
* cap USED_IF_THREADS
)
522 ACQUIRE_LOCK(&cap
->lock
);
523 releaseCapability_(cap
, rtsTrue
);
524 RELEASE_LOCK(&cap
->lock
);
528 releaseCapabilityAndQueueWorker (Capability
* cap USED_IF_THREADS
)
532 ACQUIRE_LOCK(&cap
->lock
);
534 task
= cap
->running_task
;
536 // If the Task is stopped, we shouldn't be yielding, we should
538 ASSERT(!task
->stopped
);
540 // If the current task is a worker, save it on the spare_workers
541 // list of this Capability. A worker can mark itself as stopped,
542 // in which case it is not replaced on the spare_worker queue.
543 // This happens when the system is shutting down (see
544 // Schedule.c:workerStart()).
545 if (!isBoundTask(task
))
547 if (cap
->n_spare_workers
< MAX_SPARE_WORKERS
)
549 task
->next
= cap
->spare_workers
;
550 cap
->spare_workers
= task
;
551 cap
->n_spare_workers
++;
555 debugTrace(DEBUG_sched
, "%d spare workers already, exiting",
556 cap
->n_spare_workers
);
557 releaseCapability_(cap
,rtsFalse
);
558 // hold the lock until after workerTaskStop; c.f. scheduleWorker()
559 workerTaskStop(task
);
560 RELEASE_LOCK(&cap
->lock
);
564 // Bound tasks just float around attached to their TSOs.
566 releaseCapability_(cap
,rtsFalse
);
568 RELEASE_LOCK(&cap
->lock
);
572 /* ----------------------------------------------------------------------------
573 * waitForReturnCapability (Capability **pCap, Task *task)
575 * Purpose: when an OS thread returns from an external call,
576 * it calls waitForReturnCapability() (via Schedule.resumeThread())
577 * to wait for permission to enter the RTS & communicate the
578 * result of the external call back to the Haskell thread that
581 * ------------------------------------------------------------------------- */
583 waitForReturnCapability (Capability
**pCap
, Task
*task
)
585 #if !defined(THREADED_RTS)
587 MainCapability
.running_task
= task
;
588 task
->cap
= &MainCapability
;
589 *pCap
= &MainCapability
;
592 Capability
*cap
= *pCap
;
595 // Try last_free_capability first
596 cap
= last_free_capability
;
597 if (cap
->running_task
) {
599 // otherwise, search for a free capability
601 for (i
= 0; i
< n_capabilities
; i
++) {
602 if (!capabilities
[i
].running_task
) {
603 cap
= &capabilities
[i
];
608 // Can't find a free one, use last_free_capability.
609 cap
= last_free_capability
;
613 // record the Capability as the one this Task is now assocated with.
617 ASSERT(task
->cap
== cap
);
620 ACQUIRE_LOCK(&cap
->lock
);
622 debugTrace(DEBUG_sched
, "returning; I want capability %d", cap
->no
);
624 if (!cap
->running_task
) {
625 // It's free; just grab it
626 cap
->running_task
= task
;
627 RELEASE_LOCK(&cap
->lock
);
629 newReturningTask(cap
,task
);
630 RELEASE_LOCK(&cap
->lock
);
633 ACQUIRE_LOCK(&task
->lock
);
634 // task->lock held, cap->lock not held
635 if (!task
->wakeup
) waitCondition(&task
->cond
, &task
->lock
);
637 task
->wakeup
= rtsFalse
;
638 RELEASE_LOCK(&task
->lock
);
640 // now check whether we should wake up...
641 ACQUIRE_LOCK(&cap
->lock
);
642 if (cap
->running_task
== NULL
) {
643 if (cap
->returning_tasks_hd
!= task
) {
644 giveCapabilityToTask(cap
,cap
->returning_tasks_hd
);
645 RELEASE_LOCK(&cap
->lock
);
648 cap
->running_task
= task
;
649 popReturningTask(cap
);
650 RELEASE_LOCK(&cap
->lock
);
653 RELEASE_LOCK(&cap
->lock
);
659 cap
->r
.rCCCS
= CCS_SYSTEM
;
662 ASSERT_FULL_CAPABILITY_INVARIANTS(cap
,task
);
664 debugTrace(DEBUG_sched
, "resuming capability %d", cap
->no
);
670 #if defined(THREADED_RTS)
671 /* ----------------------------------------------------------------------------
673 * ------------------------------------------------------------------------- */
676 yieldCapability (Capability
** pCap
, Task
*task
)
678 Capability
*cap
= *pCap
;
680 if (pending_sync
== SYNC_GC_PAR
) {
681 traceEventGcStart(cap
);
683 traceEventGcEnd(cap
);
684 traceSparkCounters(cap
);
688 debugTrace(DEBUG_sched
, "giving up capability %d", cap
->no
);
690 // We must now release the capability and wait to be woken up
692 task
->wakeup
= rtsFalse
;
693 releaseCapabilityAndQueueWorker(cap
);
696 ACQUIRE_LOCK(&task
->lock
);
697 // task->lock held, cap->lock not held
698 if (!task
->wakeup
) waitCondition(&task
->cond
, &task
->lock
);
700 task
->wakeup
= rtsFalse
;
701 RELEASE_LOCK(&task
->lock
);
703 debugTrace(DEBUG_sched
, "woken up on capability %d", cap
->no
);
705 ACQUIRE_LOCK(&cap
->lock
);
706 if (cap
->running_task
!= NULL
) {
707 debugTrace(DEBUG_sched
,
708 "capability %d is owned by another task", cap
->no
);
709 RELEASE_LOCK(&cap
->lock
);
713 if (task
->cap
!= cap
) {
714 // see Note [migrated bound threads]
715 debugTrace(DEBUG_sched
,
716 "task has been migrated to cap %d", task
->cap
->no
);
717 RELEASE_LOCK(&cap
->lock
);
721 if (task
->incall
->tso
== NULL
) {
722 ASSERT(cap
->spare_workers
!= NULL
);
723 // if we're not at the front of the queue, release it
724 // again. This is unlikely to happen.
725 if (cap
->spare_workers
!= task
) {
726 giveCapabilityToTask(cap
,cap
->spare_workers
);
727 RELEASE_LOCK(&cap
->lock
);
730 cap
->spare_workers
= task
->next
;
732 cap
->n_spare_workers
--;
735 cap
->running_task
= task
;
736 RELEASE_LOCK(&cap
->lock
);
740 debugTrace(DEBUG_sched
, "resuming capability %d", cap
->no
);
741 ASSERT(cap
->running_task
== task
);
744 cap
->r
.rCCCS
= CCS_SYSTEM
;
749 ASSERT_FULL_CAPABILITY_INVARIANTS(cap
,task
);
754 // Note [migrated bound threads]
756 // There's a tricky case where:
757 // - cap A is running an unbound thread T1
758 // - there is a bound thread T2 at the head of the run queue on cap A
759 // - T1 makes a safe foreign call, the task bound to T2 is woken up on cap A
760 // - T1 returns quickly grabbing A again (T2 is still waking up on A)
761 // - T1 blocks, the scheduler migrates T2 to cap B
762 // - the task bound to T2 wakes up on cap B
764 // We take advantage of the following invariant:
766 // - A bound thread can only be migrated by the holder of the
767 // Capability on which the bound thread currently lives. So, if we
768 // hold Capabilty C, and task->cap == C, then task cannot be
769 // migrated under our feet.
771 /* ----------------------------------------------------------------------------
774 * If a Capability is currently idle, wake up a Task on it. Used to
775 * get every Capability into the GC.
776 * ------------------------------------------------------------------------- */
779 prodCapability (Capability
*cap
, Task
*task
)
781 ACQUIRE_LOCK(&cap
->lock
);
782 if (!cap
->running_task
) {
783 cap
->running_task
= task
;
784 releaseCapability_(cap
,rtsTrue
);
786 RELEASE_LOCK(&cap
->lock
);
789 /* ----------------------------------------------------------------------------
792 * Attempt to gain control of a Capability if it is free.
794 * ------------------------------------------------------------------------- */
797 tryGrabCapability (Capability
*cap
, Task
*task
)
799 if (cap
->running_task
!= NULL
) return rtsFalse
;
800 ACQUIRE_LOCK(&cap
->lock
);
801 if (cap
->running_task
!= NULL
) {
802 RELEASE_LOCK(&cap
->lock
);
806 cap
->running_task
= task
;
807 RELEASE_LOCK(&cap
->lock
);
812 #endif /* THREADED_RTS */
814 /* ----------------------------------------------------------------------------
817 * At shutdown time, we want to let everything exit as cleanly as
818 * possible. For each capability, we let its run queue drain, and
819 * allow the workers to stop.
821 * This function should be called when interrupted and
822 * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
823 * will exit the scheduler and call taskStop(), and any bound thread
824 * that wakes up will return to its caller. Runnable threads are
827 * ------------------------------------------------------------------------- */
830 shutdownCapability (Capability
*cap
,
831 Task
*task USED_IF_THREADS
,
832 rtsBool safe USED_IF_THREADS
)
834 #if defined(THREADED_RTS)
839 // Loop indefinitely until all the workers have exited and there
840 // are no Haskell threads left. We used to bail out after 50
841 // iterations of this loop, but that occasionally left a worker
842 // running which caused problems later (the closeMutex() below
843 // isn't safe, for one thing).
845 for (i
= 0; /* i < 50 */; i
++) {
846 ASSERT(sched_state
== SCHED_SHUTTING_DOWN
);
848 debugTrace(DEBUG_sched
,
849 "shutting down capability %d, attempt %d", cap
->no
, i
);
850 ACQUIRE_LOCK(&cap
->lock
);
851 if (cap
->running_task
) {
852 RELEASE_LOCK(&cap
->lock
);
853 debugTrace(DEBUG_sched
, "not owner, yielding");
857 cap
->running_task
= task
;
859 if (cap
->spare_workers
) {
860 // Look for workers that have died without removing
861 // themselves from the list; this could happen if the OS
862 // summarily killed the thread, for example. This
863 // actually happens on Windows when the system is
864 // terminating the program, and the RTS is running in a
868 for (t
= cap
->spare_workers
; t
!= NULL
; t
= t
->next
) {
869 if (!osThreadIsAlive(t
->id
)) {
870 debugTrace(DEBUG_sched
,
871 "worker thread %p has died unexpectedly", (void *)t
->id
);
872 cap
->n_spare_workers
--;
874 cap
->spare_workers
= t
->next
;
876 prev
->next
= t
->next
;
883 if (!emptyRunQueue(cap
) || cap
->spare_workers
) {
884 debugTrace(DEBUG_sched
,
885 "runnable threads or workers still alive, yielding");
886 releaseCapability_(cap
,rtsFalse
); // this will wake up a worker
887 RELEASE_LOCK(&cap
->lock
);
892 // If "safe", then busy-wait for any threads currently doing
893 // foreign calls. If we're about to unload this DLL, for
894 // example, we need to be sure that there are no OS threads
895 // that will try to return to code that has been unloaded.
896 // We can be a bit more relaxed when this is a standalone
897 // program that is about to terminate, and let safe=false.
898 if (cap
->suspended_ccalls
&& safe
) {
899 debugTrace(DEBUG_sched
,
900 "thread(s) are involved in foreign calls, yielding");
901 cap
->running_task
= NULL
;
902 RELEASE_LOCK(&cap
->lock
);
903 // The IO manager thread might have been slow to start up,
904 // so the first attempt to kill it might not have
905 // succeeded. Just in case, try again - the kill message
906 // will only be sent once.
908 // To reproduce this deadlock: run ffi002(threaded1)
909 // repeatedly on a loaded machine.
915 traceEventShutdown(cap
);
916 RELEASE_LOCK(&cap
->lock
);
919 // we now have the Capability, its run queue and spare workers
920 // list are both empty.
922 // ToDo: we can't drop this mutex, because there might still be
923 // threads performing foreign calls that will eventually try to
924 // return via resumeThread() and attempt to grab cap->lock.
925 // closeMutex(&cap->lock);
927 traceSparkCounters(cap
);
929 #endif /* THREADED_RTS */
931 traceCapsetRemoveCap(CAPSET_OSPROCESS_DEFAULT
, cap
->no
);
932 traceCapsetRemoveCap(CAPSET_CLOCKDOMAIN_DEFAULT
, cap
->no
);
936 shutdownCapabilities(Task
*task
, rtsBool safe
)
939 for (i
=0; i
< n_capabilities
; i
++) {
940 ASSERT(task
->incall
->tso
== NULL
);
941 shutdownCapability(&capabilities
[i
], task
, safe
);
943 traceCapsetDelete(CAPSET_OSPROCESS_DEFAULT
);
944 traceCapsetDelete(CAPSET_CLOCKDOMAIN_DEFAULT
);
946 #if defined(THREADED_RTS)
947 ASSERT(checkSparkCountInvariant());
952 freeCapability (Capability
*cap
)
954 stgFree(cap
->mut_lists
);
955 stgFree(cap
->saved_mut_lists
);
956 #if defined(THREADED_RTS)
957 freeSparkPool(cap
->sparks
);
962 freeCapabilities (void)
964 #if defined(THREADED_RTS)
966 for (i
=0; i
< n_capabilities
; i
++) {
967 freeCapability(&capabilities
[i
]);
970 freeCapability(&MainCapability
);
974 /* ---------------------------------------------------------------------------
975 Mark everything directly reachable from the Capabilities. When
976 using multiple GC threads, each GC thread marks all Capabilities
977 for which (c `mod` n == 0), for Capability c and thread n.
978 ------------------------------------------------------------------------ */
981 markCapability (evac_fn evac
, void *user
, Capability
*cap
,
982 rtsBool no_mark_sparks USED_IF_THREADS
)
986 // Each GC thread is responsible for following roots from the
987 // Capability of the same number. There will usually be the same
988 // or fewer Capabilities as GC threads, but just in case there
989 // are more, we mark every Capability whose number is the GC
990 // thread's index plus a multiple of the number of GC threads.
991 evac(user
, (StgClosure
**)(void *)&cap
->run_queue_hd
);
992 evac(user
, (StgClosure
**)(void *)&cap
->run_queue_tl
);
993 #if defined(THREADED_RTS)
994 evac(user
, (StgClosure
**)(void *)&cap
->inbox
);
996 for (incall
= cap
->suspended_ccalls
; incall
!= NULL
;
997 incall
=incall
->next
) {
998 evac(user
, (StgClosure
**)(void *)&incall
->suspended_tso
);
1001 #if defined(THREADED_RTS)
1002 if (!no_mark_sparks
) {
1003 traverseSparkQueue (evac
, user
, cap
);
1007 // Free STM structures for this Capability
1012 markCapabilities (evac_fn evac
, void *user
)
1015 for (n
= 0; n
< n_capabilities
; n
++) {
1016 markCapability(evac
, user
, &capabilities
[n
], rtsFalse
);
1020 #if defined(THREADED_RTS)
1021 rtsBool
checkSparkCountInvariant (void)
1023 SparkCounters sparks
= { 0, 0, 0, 0, 0, 0 };
1024 StgWord64 remaining
= 0;
1027 for (i
= 0; i
< n_capabilities
; i
++) {
1028 sparks
.created
+= capabilities
[i
].spark_stats
.created
;
1029 sparks
.dud
+= capabilities
[i
].spark_stats
.dud
;
1030 sparks
.overflowed
+= capabilities
[i
].spark_stats
.overflowed
;
1031 sparks
.converted
+= capabilities
[i
].spark_stats
.converted
;
1032 sparks
.gcd
+= capabilities
[i
].spark_stats
.gcd
;
1033 sparks
.fizzled
+= capabilities
[i
].spark_stats
.fizzled
;
1034 remaining
+= sparkPoolSize(capabilities
[i
].sparks
);
1038 * created = converted + remaining + gcd + fizzled
1040 debugTrace(DEBUG_sparks
,"spark invariant: %ld == %ld + %ld + %ld + %ld "
1041 "(created == converted + remaining + gcd + fizzled)",
1042 sparks
.created
, sparks
.converted
, remaining
,
1043 sparks
.gcd
, sparks
.fizzled
);
1045 return (sparks
.created
==
1046 sparks
.converted
+ remaining
+ sparks
.gcd
+ sparks
.fizzled
);