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 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
;
232 cap
->run_queue_hd
= END_TSO_QUEUE
;
233 cap
->run_queue_tl
= END_TSO_QUEUE
;
235 #if defined(THREADED_RTS)
236 initMutex(&cap
->lock
);
237 cap
->running_task
= NULL
; // indicates cap is free
238 cap
->spare_workers
= NULL
;
239 cap
->n_spare_workers
= 0;
240 cap
->suspended_ccalls
= NULL
;
241 cap
->returning_tasks_hd
= NULL
;
242 cap
->returning_tasks_tl
= NULL
;
243 cap
->inbox
= (Message
*)END_TSO_QUEUE
;
244 cap
->sparks
= allocSparkPool();
245 cap
->spark_stats
.created
= 0;
246 cap
->spark_stats
.dud
= 0;
247 cap
->spark_stats
.overflowed
= 0;
248 cap
->spark_stats
.converted
= 0;
249 cap
->spark_stats
.gcd
= 0;
250 cap
->spark_stats
.fizzled
= 0;
253 cap
->f
.stgEagerBlackholeInfo
= (W_
)&__stg_EAGER_BLACKHOLE_info
;
254 cap
->f
.stgGCEnter1
= (StgFunPtr
)__stg_gc_enter_1
;
255 cap
->f
.stgGCFun
= (StgFunPtr
)__stg_gc_fun
;
257 cap
->mut_lists
= stgMallocBytes(sizeof(bdescr
*) *
258 RtsFlags
.GcFlags
.generations
,
260 cap
->saved_mut_lists
= stgMallocBytes(sizeof(bdescr
*) *
261 RtsFlags
.GcFlags
.generations
,
264 for (g
= 0; g
< RtsFlags
.GcFlags
.generations
; g
++) {
265 cap
->mut_lists
[g
] = NULL
;
268 cap
->free_tvar_watch_queues
= END_STM_WATCH_QUEUE
;
269 cap
->free_invariant_check_queues
= END_INVARIANT_CHECK_QUEUE
;
270 cap
->free_trec_chunks
= END_STM_CHUNK_LIST
;
271 cap
->free_trec_headers
= NO_TREC
;
272 cap
->transaction_tokens
= 0;
273 cap
->context_switch
= 0;
274 cap
->pinned_object_block
= NULL
;
277 cap
->r
.rCCCS
= CCS_SYSTEM
;
282 traceCapsetAssignCap(CAPSET_OSPROCESS_DEFAULT
, i
);
283 traceCapsetAssignCap(CAPSET_CLOCKDOMAIN_DEFAULT
, i
);
284 #if defined(THREADED_RTS)
285 traceSparkCounters(cap
);
289 /* ---------------------------------------------------------------------------
290 * Function: initCapabilities()
292 * Purpose: set up the Capability handling. For the THREADED_RTS build,
293 * we keep a table of them, the size of which is
294 * controlled by the user via the RTS flag -N.
296 * ------------------------------------------------------------------------- */
298 initCapabilities( void )
300 /* Declare a couple capability sets representing the process and
301 clock domain. Each capability will get added to these capsets. */
302 traceCapsetCreate(CAPSET_OSPROCESS_DEFAULT
, CapsetTypeOsProcess
);
303 traceCapsetCreate(CAPSET_CLOCKDOMAIN_DEFAULT
, CapsetTypeClockdomain
);
305 #if defined(THREADED_RTS)
308 // We can't support multiple CPUs if BaseReg is not a register
309 if (RtsFlags
.ParFlags
.nNodes
> 1) {
310 errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
311 RtsFlags
.ParFlags
.nNodes
= 1;
316 moreCapabilities(0, RtsFlags
.ParFlags
.nNodes
);
317 n_capabilities
= RtsFlags
.ParFlags
.nNodes
;
319 #else /* !THREADED_RTS */
322 capabilities
= &MainCapability
;
323 initCapability(&MainCapability
, 0);
327 enabled_capabilities
= n_capabilities
;
329 // There are no free capabilities to begin with. We will start
330 // a worker Task to each Capability, which will quickly put the
331 // Capability on the free list when it finds nothing to do.
332 last_free_capability
= &capabilities
[0];
336 moreCapabilities (nat from USED_IF_THREADS
, nat to USED_IF_THREADS
)
338 #if defined(THREADED_RTS)
340 Capability
*old_capabilities
= capabilities
;
343 // THREADED_RTS must work on builds that don't have a mutable
344 // BaseReg (eg. unregisterised), so in this case
345 // capabilities[0] must coincide with &MainCapability.
346 capabilities
= &MainCapability
;
348 capabilities
= stgMallocBytes(to
* sizeof(Capability
),
352 memcpy(capabilities
, old_capabilities
, from
* sizeof(Capability
));
356 for (i
= from
; i
< to
; i
++) {
357 initCapability(&capabilities
[i
], i
);
360 last_free_capability
= NULL
;
362 debugTrace(DEBUG_sched
, "allocated %d more capabilities", to
- from
);
364 // Return the old array to free later.
366 return old_capabilities
;
375 /* ----------------------------------------------------------------------------
376 * setContextSwitches: cause all capabilities to context switch as
378 * ------------------------------------------------------------------------- */
380 void contextSwitchAllCapabilities(void)
383 for (i
=0; i
< n_capabilities
; i
++) {
384 contextSwitchCapability(&capabilities
[i
]);
388 void interruptAllCapabilities(void)
391 for (i
=0; i
< n_capabilities
; i
++) {
392 interruptCapability(&capabilities
[i
]);
396 /* ----------------------------------------------------------------------------
397 * Give a Capability to a Task. The task must currently be sleeping
398 * on its condition variable.
400 * Requires cap->lock (modifies cap->running_task).
402 * When migrating a Task, the migrater must take task->lock before
403 * modifying task->cap, to synchronise with the waking up Task.
404 * Additionally, the migrater should own the Capability (when
405 * migrating the run queue), or cap->lock (when migrating
406 * returning_workers).
408 * ------------------------------------------------------------------------- */
410 #if defined(THREADED_RTS)
412 giveCapabilityToTask (Capability
*cap USED_IF_DEBUG
, Task
*task
)
414 ASSERT_LOCK_HELD(&cap
->lock
);
415 ASSERT(task
->cap
== cap
);
416 debugTrace(DEBUG_sched
, "passing capability %d to %s %p",
417 cap
->no
, task
->incall
->tso ?
"bound task" : "worker",
419 ACQUIRE_LOCK(&task
->lock
);
420 if (task
->wakeup
== rtsFalse
) {
421 task
->wakeup
= rtsTrue
;
422 // the wakeup flag is needed because signalCondition() doesn't
423 // flag the condition if the thread is already runniing, but we want
425 signalCondition(&task
->cond
);
427 RELEASE_LOCK(&task
->lock
);
431 /* ----------------------------------------------------------------------------
432 * Function: releaseCapability(Capability*)
434 * Purpose: Letting go of a capability. Causes a
435 * 'returning worker' thread or a 'waiting worker'
436 * to wake up, in that order.
437 * ------------------------------------------------------------------------- */
439 #if defined(THREADED_RTS)
441 releaseCapability_ (Capability
* cap
,
442 rtsBool always_wakeup
)
446 task
= cap
->running_task
;
448 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap
,task
);
450 cap
->running_task
= NULL
;
452 // Check to see whether a worker thread can be given
453 // the go-ahead to return the result of an external call..
454 if (cap
->returning_tasks_hd
!= NULL
) {
455 giveCapabilityToTask(cap
,cap
->returning_tasks_hd
);
456 // The Task pops itself from the queue (see waitForReturnCapability())
460 // If there is a pending sync, then we should just leave the
461 // Capability free. The thread trying to sync will be about to
462 // call waitForReturnCapability().
463 if (pending_sync
!= 0 && pending_sync
!= SYNC_GC_PAR
) {
464 last_free_capability
= cap
; // needed?
465 debugTrace(DEBUG_sched
, "sync pending, set capability %d free", cap
->no
);
469 // If the next thread on the run queue is a bound thread,
470 // give this Capability to the appropriate Task.
471 if (!emptyRunQueue(cap
) && cap
->run_queue_hd
->bound
) {
472 // Make sure we're not about to try to wake ourselves up
473 // ASSERT(task != cap->run_queue_hd->bound);
474 // assertion is false: in schedule() we force a yield after
475 // ThreadBlocked, but the thread may be back on the run queue
477 task
= cap
->run_queue_hd
->bound
->task
;
478 giveCapabilityToTask(cap
,task
);
482 if (!cap
->spare_workers
) {
483 // Create a worker thread if we don't have one. If the system
484 // is interrupted, we only create a worker task if there
485 // are threads that need to be completed. If the system is
486 // shutting down, we never create a new worker.
487 if (sched_state
< SCHED_SHUTTING_DOWN
|| !emptyRunQueue(cap
)) {
488 debugTrace(DEBUG_sched
,
489 "starting new worker on capability %d", cap
->no
);
490 startWorkerTask(cap
);
495 // If we have an unbound thread on the run queue, or if there's
496 // anything else to do, give the Capability to a worker thread.
498 !emptyRunQueue(cap
) || !emptyInbox(cap
) ||
499 (!cap
->disabled
&& !emptySparkPoolCap(cap
)) || globalWorkToDo()) {
500 if (cap
->spare_workers
) {
501 giveCapabilityToTask(cap
,cap
->spare_workers
);
502 // The worker Task pops itself from the queue;
508 cap
->r
.rCCCS
= CCS_IDLE
;
510 last_free_capability
= cap
;
511 debugTrace(DEBUG_sched
, "freeing capability %d", cap
->no
);
515 releaseCapability (Capability
* cap USED_IF_THREADS
)
517 ACQUIRE_LOCK(&cap
->lock
);
518 releaseCapability_(cap
, rtsFalse
);
519 RELEASE_LOCK(&cap
->lock
);
523 releaseAndWakeupCapability (Capability
* cap USED_IF_THREADS
)
525 ACQUIRE_LOCK(&cap
->lock
);
526 releaseCapability_(cap
, rtsTrue
);
527 RELEASE_LOCK(&cap
->lock
);
531 releaseCapabilityAndQueueWorker (Capability
* cap USED_IF_THREADS
)
535 ACQUIRE_LOCK(&cap
->lock
);
537 task
= cap
->running_task
;
539 // If the Task is stopped, we shouldn't be yielding, we should
541 ASSERT(!task
->stopped
);
543 // If the current task is a worker, save it on the spare_workers
544 // list of this Capability. A worker can mark itself as stopped,
545 // in which case it is not replaced on the spare_worker queue.
546 // This happens when the system is shutting down (see
547 // Schedule.c:workerStart()).
548 if (!isBoundTask(task
))
550 if (cap
->n_spare_workers
< MAX_SPARE_WORKERS
)
552 task
->next
= cap
->spare_workers
;
553 cap
->spare_workers
= task
;
554 cap
->n_spare_workers
++;
558 debugTrace(DEBUG_sched
, "%d spare workers already, exiting",
559 cap
->n_spare_workers
);
560 releaseCapability_(cap
,rtsFalse
);
561 // hold the lock until after workerTaskStop; c.f. scheduleWorker()
562 workerTaskStop(task
);
563 RELEASE_LOCK(&cap
->lock
);
567 // Bound tasks just float around attached to their TSOs.
569 releaseCapability_(cap
,rtsFalse
);
571 RELEASE_LOCK(&cap
->lock
);
575 /* ----------------------------------------------------------------------------
576 * waitForReturnCapability (Capability **pCap, Task *task)
578 * Purpose: when an OS thread returns from an external call,
579 * it calls waitForReturnCapability() (via Schedule.resumeThread())
580 * to wait for permission to enter the RTS & communicate the
581 * result of the external call back to the Haskell thread that
584 * ------------------------------------------------------------------------- */
586 waitForReturnCapability (Capability
**pCap
, Task
*task
)
588 #if !defined(THREADED_RTS)
590 MainCapability
.running_task
= task
;
591 task
->cap
= &MainCapability
;
592 *pCap
= &MainCapability
;
595 Capability
*cap
= *pCap
;
598 // Try last_free_capability first
599 cap
= last_free_capability
;
600 if (cap
->running_task
) {
602 // otherwise, search for a free capability
604 for (i
= 0; i
< n_capabilities
; i
++) {
605 if (!capabilities
[i
].running_task
) {
606 cap
= &capabilities
[i
];
611 // Can't find a free one, use last_free_capability.
612 cap
= last_free_capability
;
616 // record the Capability as the one this Task is now assocated with.
620 ASSERT(task
->cap
== cap
);
623 ACQUIRE_LOCK(&cap
->lock
);
625 debugTrace(DEBUG_sched
, "returning; I want capability %d", cap
->no
);
627 if (!cap
->running_task
) {
628 // It's free; just grab it
629 cap
->running_task
= task
;
630 RELEASE_LOCK(&cap
->lock
);
632 newReturningTask(cap
,task
);
633 RELEASE_LOCK(&cap
->lock
);
636 ACQUIRE_LOCK(&task
->lock
);
637 // task->lock held, cap->lock not held
638 if (!task
->wakeup
) waitCondition(&task
->cond
, &task
->lock
);
640 task
->wakeup
= rtsFalse
;
641 RELEASE_LOCK(&task
->lock
);
643 // now check whether we should wake up...
644 ACQUIRE_LOCK(&cap
->lock
);
645 if (cap
->running_task
== NULL
) {
646 if (cap
->returning_tasks_hd
!= task
) {
647 giveCapabilityToTask(cap
,cap
->returning_tasks_hd
);
648 RELEASE_LOCK(&cap
->lock
);
651 cap
->running_task
= task
;
652 popReturningTask(cap
);
653 RELEASE_LOCK(&cap
->lock
);
656 RELEASE_LOCK(&cap
->lock
);
662 cap
->r
.rCCCS
= CCS_SYSTEM
;
665 ASSERT_FULL_CAPABILITY_INVARIANTS(cap
,task
);
667 debugTrace(DEBUG_sched
, "resuming capability %d", cap
->no
);
673 #if defined(THREADED_RTS)
674 /* ----------------------------------------------------------------------------
676 * ------------------------------------------------------------------------- */
679 yieldCapability (Capability
** pCap
, Task
*task
)
681 Capability
*cap
= *pCap
;
683 if (pending_sync
== SYNC_GC_PAR
) {
684 traceEventGcStart(cap
);
686 traceEventGcEnd(cap
);
687 traceSparkCounters(cap
);
688 // See Note [migrated bound threads 2]
689 if (task
->cap
== cap
) return;
692 debugTrace(DEBUG_sched
, "giving up capability %d", cap
->no
);
694 // We must now release the capability and wait to be woken up
696 task
->wakeup
= rtsFalse
;
697 releaseCapabilityAndQueueWorker(cap
);
700 ACQUIRE_LOCK(&task
->lock
);
701 // task->lock held, cap->lock not held
702 if (!task
->wakeup
) waitCondition(&task
->cond
, &task
->lock
);
704 task
->wakeup
= rtsFalse
;
705 RELEASE_LOCK(&task
->lock
);
707 debugTrace(DEBUG_sched
, "woken up on capability %d", cap
->no
);
709 ACQUIRE_LOCK(&cap
->lock
);
710 if (cap
->running_task
!= NULL
) {
711 debugTrace(DEBUG_sched
,
712 "capability %d is owned by another task", cap
->no
);
713 RELEASE_LOCK(&cap
->lock
);
717 if (task
->cap
!= cap
) {
718 // see Note [migrated bound threads]
719 debugTrace(DEBUG_sched
,
720 "task has been migrated to cap %d", task
->cap
->no
);
721 RELEASE_LOCK(&cap
->lock
);
725 if (task
->incall
->tso
== NULL
) {
726 ASSERT(cap
->spare_workers
!= NULL
);
727 // if we're not at the front of the queue, release it
728 // again. This is unlikely to happen.
729 if (cap
->spare_workers
!= task
) {
730 giveCapabilityToTask(cap
,cap
->spare_workers
);
731 RELEASE_LOCK(&cap
->lock
);
734 cap
->spare_workers
= task
->next
;
736 cap
->n_spare_workers
--;
739 cap
->running_task
= task
;
740 RELEASE_LOCK(&cap
->lock
);
744 debugTrace(DEBUG_sched
, "resuming capability %d", cap
->no
);
745 ASSERT(cap
->running_task
== task
);
748 cap
->r
.rCCCS
= CCS_SYSTEM
;
753 ASSERT_FULL_CAPABILITY_INVARIANTS(cap
,task
);
758 // Note [migrated bound threads]
760 // There's a tricky case where:
761 // - cap A is running an unbound thread T1
762 // - there is a bound thread T2 at the head of the run queue on cap A
763 // - T1 makes a safe foreign call, the task bound to T2 is woken up on cap A
764 // - T1 returns quickly grabbing A again (T2 is still waking up on A)
765 // - T1 blocks, the scheduler migrates T2 to cap B
766 // - the task bound to T2 wakes up on cap B
768 // We take advantage of the following invariant:
770 // - A bound thread can only be migrated by the holder of the
771 // Capability on which the bound thread currently lives. So, if we
772 // hold Capabilty C, and task->cap == C, then task cannot be
773 // migrated under our feet.
775 // Note [migrated bound threads 2]
777 // Second tricky case;
778 // - A bound Task becomes a GC thread
779 // - scheduleDoGC() migrates the thread belonging to this Task,
780 // because the Capability it is on is disabled
781 // - after GC, gcWorkerThread() returns, but now we are
782 // holding a Capability that is not the same as task->cap
783 // - Hence we must check for this case and immediately give up the
786 /* ----------------------------------------------------------------------------
789 * If a Capability is currently idle, wake up a Task on it. Used to
790 * get every Capability into the GC.
791 * ------------------------------------------------------------------------- */
794 prodCapability (Capability
*cap
, Task
*task
)
796 ACQUIRE_LOCK(&cap
->lock
);
797 if (!cap
->running_task
) {
798 cap
->running_task
= task
;
799 releaseCapability_(cap
,rtsTrue
);
801 RELEASE_LOCK(&cap
->lock
);
804 /* ----------------------------------------------------------------------------
807 * Attempt to gain control of a Capability if it is free.
809 * ------------------------------------------------------------------------- */
812 tryGrabCapability (Capability
*cap
, Task
*task
)
814 if (cap
->running_task
!= NULL
) return rtsFalse
;
815 ACQUIRE_LOCK(&cap
->lock
);
816 if (cap
->running_task
!= NULL
) {
817 RELEASE_LOCK(&cap
->lock
);
821 cap
->running_task
= task
;
822 RELEASE_LOCK(&cap
->lock
);
827 #endif /* THREADED_RTS */
829 /* ----------------------------------------------------------------------------
832 * At shutdown time, we want to let everything exit as cleanly as
833 * possible. For each capability, we let its run queue drain, and
834 * allow the workers to stop.
836 * This function should be called when interrupted and
837 * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
838 * will exit the scheduler and call taskStop(), and any bound thread
839 * that wakes up will return to its caller. Runnable threads are
842 * ------------------------------------------------------------------------- */
845 shutdownCapability (Capability
*cap
,
846 Task
*task USED_IF_THREADS
,
847 rtsBool safe USED_IF_THREADS
)
849 #if defined(THREADED_RTS)
854 // Loop indefinitely until all the workers have exited and there
855 // are no Haskell threads left. We used to bail out after 50
856 // iterations of this loop, but that occasionally left a worker
857 // running which caused problems later (the closeMutex() below
858 // isn't safe, for one thing).
860 for (i
= 0; /* i < 50 */; i
++) {
861 ASSERT(sched_state
== SCHED_SHUTTING_DOWN
);
863 debugTrace(DEBUG_sched
,
864 "shutting down capability %d, attempt %d", cap
->no
, i
);
865 ACQUIRE_LOCK(&cap
->lock
);
866 if (cap
->running_task
) {
867 RELEASE_LOCK(&cap
->lock
);
868 debugTrace(DEBUG_sched
, "not owner, yielding");
872 cap
->running_task
= task
;
874 if (cap
->spare_workers
) {
875 // Look for workers that have died without removing
876 // themselves from the list; this could happen if the OS
877 // summarily killed the thread, for example. This
878 // actually happens on Windows when the system is
879 // terminating the program, and the RTS is running in a
883 for (t
= cap
->spare_workers
; t
!= NULL
; t
= t
->next
) {
884 if (!osThreadIsAlive(t
->id
)) {
885 debugTrace(DEBUG_sched
,
886 "worker thread %p has died unexpectedly", (void *)t
->id
);
887 cap
->n_spare_workers
--;
889 cap
->spare_workers
= t
->next
;
891 prev
->next
= t
->next
;
898 if (!emptyRunQueue(cap
) || cap
->spare_workers
) {
899 debugTrace(DEBUG_sched
,
900 "runnable threads or workers still alive, yielding");
901 releaseCapability_(cap
,rtsFalse
); // this will wake up a worker
902 RELEASE_LOCK(&cap
->lock
);
907 // If "safe", then busy-wait for any threads currently doing
908 // foreign calls. If we're about to unload this DLL, for
909 // example, we need to be sure that there are no OS threads
910 // that will try to return to code that has been unloaded.
911 // We can be a bit more relaxed when this is a standalone
912 // program that is about to terminate, and let safe=false.
913 if (cap
->suspended_ccalls
&& safe
) {
914 debugTrace(DEBUG_sched
,
915 "thread(s) are involved in foreign calls, yielding");
916 cap
->running_task
= NULL
;
917 RELEASE_LOCK(&cap
->lock
);
918 // The IO manager thread might have been slow to start up,
919 // so the first attempt to kill it might not have
920 // succeeded. Just in case, try again - the kill message
921 // will only be sent once.
923 // To reproduce this deadlock: run ffi002(threaded1)
924 // repeatedly on a loaded machine.
930 traceEventShutdown(cap
);
931 RELEASE_LOCK(&cap
->lock
);
934 // we now have the Capability, its run queue and spare workers
935 // list are both empty.
937 // ToDo: we can't drop this mutex, because there might still be
938 // threads performing foreign calls that will eventually try to
939 // return via resumeThread() and attempt to grab cap->lock.
940 // closeMutex(&cap->lock);
942 traceSparkCounters(cap
);
944 #endif /* THREADED_RTS */
946 traceCapsetRemoveCap(CAPSET_OSPROCESS_DEFAULT
, cap
->no
);
947 traceCapsetRemoveCap(CAPSET_CLOCKDOMAIN_DEFAULT
, cap
->no
);
951 shutdownCapabilities(Task
*task
, rtsBool safe
)
954 for (i
=0; i
< n_capabilities
; i
++) {
955 ASSERT(task
->incall
->tso
== NULL
);
956 shutdownCapability(&capabilities
[i
], task
, safe
);
958 traceCapsetDelete(CAPSET_OSPROCESS_DEFAULT
);
959 traceCapsetDelete(CAPSET_CLOCKDOMAIN_DEFAULT
);
961 #if defined(THREADED_RTS)
962 ASSERT(checkSparkCountInvariant());
967 freeCapability (Capability
*cap
)
969 stgFree(cap
->mut_lists
);
970 stgFree(cap
->saved_mut_lists
);
971 #if defined(THREADED_RTS)
972 freeSparkPool(cap
->sparks
);
977 freeCapabilities (void)
979 #if defined(THREADED_RTS)
981 for (i
=0; i
< n_capabilities
; i
++) {
982 freeCapability(&capabilities
[i
]);
985 freeCapability(&MainCapability
);
989 /* ---------------------------------------------------------------------------
990 Mark everything directly reachable from the Capabilities. When
991 using multiple GC threads, each GC thread marks all Capabilities
992 for which (c `mod` n == 0), for Capability c and thread n.
993 ------------------------------------------------------------------------ */
996 markCapability (evac_fn evac
, void *user
, Capability
*cap
,
997 rtsBool no_mark_sparks USED_IF_THREADS
)
1001 // Each GC thread is responsible for following roots from the
1002 // Capability of the same number. There will usually be the same
1003 // or fewer Capabilities as GC threads, but just in case there
1004 // are more, we mark every Capability whose number is the GC
1005 // thread's index plus a multiple of the number of GC threads.
1006 evac(user
, (StgClosure
**)(void *)&cap
->run_queue_hd
);
1007 evac(user
, (StgClosure
**)(void *)&cap
->run_queue_tl
);
1008 #if defined(THREADED_RTS)
1009 evac(user
, (StgClosure
**)(void *)&cap
->inbox
);
1011 for (incall
= cap
->suspended_ccalls
; incall
!= NULL
;
1012 incall
=incall
->next
) {
1013 evac(user
, (StgClosure
**)(void *)&incall
->suspended_tso
);
1016 #if defined(THREADED_RTS)
1017 if (!no_mark_sparks
) {
1018 traverseSparkQueue (evac
, user
, cap
);
1022 // Free STM structures for this Capability
1027 markCapabilities (evac_fn evac
, void *user
)
1030 for (n
= 0; n
< n_capabilities
; n
++) {
1031 markCapability(evac
, user
, &capabilities
[n
], rtsFalse
);
1035 #if defined(THREADED_RTS)
1036 rtsBool
checkSparkCountInvariant (void)
1038 SparkCounters sparks
= { 0, 0, 0, 0, 0, 0 };
1039 StgWord64 remaining
= 0;
1042 for (i
= 0; i
< n_capabilities
; i
++) {
1043 sparks
.created
+= capabilities
[i
].spark_stats
.created
;
1044 sparks
.dud
+= capabilities
[i
].spark_stats
.dud
;
1045 sparks
.overflowed
+= capabilities
[i
].spark_stats
.overflowed
;
1046 sparks
.converted
+= capabilities
[i
].spark_stats
.converted
;
1047 sparks
.gcd
+= capabilities
[i
].spark_stats
.gcd
;
1048 sparks
.fizzled
+= capabilities
[i
].spark_stats
.fizzled
;
1049 remaining
+= sparkPoolSize(capabilities
[i
].sparks
);
1053 * created = converted + remaining + gcd + fizzled
1055 debugTrace(DEBUG_sparks
,"spark invariant: %ld == %ld + %ld + %ld + %ld "
1056 "(created == converted + remaining + gcd + fizzled)",
1057 sparks
.created
, sparks
.converted
, remaining
,
1058 sparks
.gcd
, sparks
.fizzled
);
1060 return (sparks
.created
==
1061 sparks
.converted
+ remaining
+ sparks
.gcd
+ sparks
.fizzled
);