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"
24 #include "OSThreads.h"
25 #include "Capability.h"
30 // one global capability, this is the Capability for non-threaded
31 // builds, and for +RTS -N1
32 Capability MainCapability;
35 Capability *capabilities = NULL;
37 // Holds the Capability which last became free. This is used so that
38 // an in-call has a chance of quickly finding a free Capability.
39 // Maintaining a global free list of Capabilities would require global
40 // locking, so we don't do that.
41 Capability *last_free_capability;
43 /* GC indicator, in scope for the scheduler, init'ed to false */
44 volatile StgWord waiting_for_gc = 0;
46 #if defined(THREADED_RTS)
50 return blackholes_need_checking
51 || sched_state >= SCHED_INTERRUPTING
56 #if defined(THREADED_RTS)
58 stealWork (Capability *cap)
60 /* use the normal Sparks.h interface (internally modified to enable
62 and immediately turn the spark into a thread when successful
69 debugTrace(DEBUG_sched,
70 "cap %d: Trying to steal work from other capabilities",
73 if (n_capabilities == 1) { return NULL; } // makes no sense...
78 /* visit cap.s 0..n-1 in sequence until a theft succeeds. We could
79 start at a random place instead of 0 as well. */
80 for ( i=0 ; i < n_capabilities ; i++ ) {
81 robbed = &capabilities[i];
82 if (cap == robbed) // ourselves...
85 if (emptySparkPoolCap(robbed)) // nothing to steal here
88 spark = tryStealSpark(robbed);
89 if (spark == NULL && !emptySparkPoolCap(robbed)) {
90 // we conflicted with another thread while trying to steal;
96 debugTrace(DEBUG_sched,
97 "cap %d: Stole a spark from capability %d",
101 // otherwise: no success, try next one
105 debugTrace(DEBUG_sched, "No sparks stolen");
109 // Returns True if any spark pool is non-empty at this moment in time
110 // The result is only valid for an instant, of course, so in a sense
111 // is immediately invalid, and should not be relied upon for
118 for (i=0; i < n_capabilities; i++) {
119 if (!emptySparkPoolCap(&capabilities[i])) {
127 /* -----------------------------------------------------------------------------
128 * Manage the returning_tasks lists.
130 * These functions require cap->lock
131 * -------------------------------------------------------------------------- */
133 #if defined(THREADED_RTS)
135 newReturningTask (Capability *cap, Task *task)
137 ASSERT_LOCK_HELD(&cap->lock);
138 ASSERT(task->return_link == NULL);
139 if (cap->returning_tasks_hd) {
140 ASSERT(cap->returning_tasks_tl->return_link == NULL);
141 cap->returning_tasks_tl->return_link = task;
143 cap->returning_tasks_hd = task;
145 cap->returning_tasks_tl = task;
149 popReturningTask (Capability *cap)
151 ASSERT_LOCK_HELD(&cap->lock);
153 task = cap->returning_tasks_hd;
155 cap->returning_tasks_hd = task->return_link;
156 if (!cap->returning_tasks_hd) {
157 cap->returning_tasks_tl = NULL;
159 task->return_link = NULL;
164 /* ----------------------------------------------------------------------------
167 * The Capability is initially marked not free.
168 * ------------------------------------------------------------------------- */
171 initCapability( Capability *cap, nat i )
176 cap->in_haskell = rtsFalse;
178 cap->run_queue_hd = END_TSO_QUEUE;
179 cap->run_queue_tl = END_TSO_QUEUE;
181 #if defined(THREADED_RTS)
182 initMutex(&cap->lock);
183 cap->running_task = NULL; // indicates cap is free
184 cap->spare_workers = NULL;
185 cap->suspended_ccalling_tasks = NULL;
186 cap->returning_tasks_hd = NULL;
187 cap->returning_tasks_tl = NULL;
188 cap->wakeup_queue_hd = END_TSO_QUEUE;
189 cap->wakeup_queue_tl = END_TSO_QUEUE;
190 cap->sparks_created = 0;
191 cap->sparks_converted = 0;
192 cap->sparks_pruned = 0;
195 cap->f.stgGCEnter1 = (F_)__stg_gc_enter_1;
196 cap->f.stgGCFun = (F_)__stg_gc_fun;
198 cap->mut_lists = stgMallocBytes(sizeof(bdescr *) *
199 RtsFlags.GcFlags.generations,
202 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
203 cap->mut_lists[g] = NULL;
206 cap->free_tvar_watch_queues = END_STM_WATCH_QUEUE;
207 cap->free_invariant_check_queues = END_INVARIANT_CHECK_QUEUE;
208 cap->free_trec_chunks = END_STM_CHUNK_LIST;
209 cap->free_trec_headers = NO_TREC;
210 cap->transaction_tokens = 0;
211 cap->context_switch = 0;
214 /* ---------------------------------------------------------------------------
215 * Function: initCapabilities()
217 * Purpose: set up the Capability handling. For the THREADED_RTS build,
218 * we keep a table of them, the size of which is
219 * controlled by the user via the RTS flag -N.
221 * ------------------------------------------------------------------------- */
223 initCapabilities( void )
225 #if defined(THREADED_RTS)
229 // We can't support multiple CPUs if BaseReg is not a register
230 if (RtsFlags.ParFlags.nNodes > 1) {
231 errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
232 RtsFlags.ParFlags.nNodes = 1;
236 n_capabilities = RtsFlags.ParFlags.nNodes;
238 if (n_capabilities == 1) {
239 capabilities = &MainCapability;
240 // THREADED_RTS must work on builds that don't have a mutable
241 // BaseReg (eg. unregisterised), so in this case
242 // capabilities[0] must coincide with &MainCapability.
244 capabilities = stgMallocBytes(n_capabilities * sizeof(Capability),
248 for (i = 0; i < n_capabilities; i++) {
249 initCapability(&capabilities[i], i);
252 debugTrace(DEBUG_sched, "allocated %d capabilities", n_capabilities);
254 #else /* !THREADED_RTS */
257 capabilities = &MainCapability;
258 initCapability(&MainCapability, 0);
262 // There are no free capabilities to begin with. We will start
263 // a worker Task to each Capability, which will quickly put the
264 // Capability on the free list when it finds nothing to do.
265 last_free_capability = &capabilities[0];
268 /* ----------------------------------------------------------------------------
269 * setContextSwitches: cause all capabilities to context switch as
271 * ------------------------------------------------------------------------- */
273 void setContextSwitches(void)
276 for (i=0; i < n_capabilities; i++) {
277 capabilities[i].context_switch = 1;
281 /* ----------------------------------------------------------------------------
282 * Give a Capability to a Task. The task must currently be sleeping
283 * on its condition variable.
285 * Requires cap->lock (modifies cap->running_task).
287 * When migrating a Task, the migrater must take task->lock before
288 * modifying task->cap, to synchronise with the waking up Task.
289 * Additionally, the migrater should own the Capability (when
290 * migrating the run queue), or cap->lock (when migrating
291 * returning_workers).
293 * ------------------------------------------------------------------------- */
295 #if defined(THREADED_RTS)
297 giveCapabilityToTask (Capability *cap USED_IF_DEBUG, Task *task)
299 ASSERT_LOCK_HELD(&cap->lock);
300 ASSERT(task->cap == cap);
301 trace(TRACE_sched | DEBUG_sched,
302 "passing capability %d to %s %p",
303 cap->no, task->tso ? "bound task" : "worker",
305 ACQUIRE_LOCK(&task->lock);
306 task->wakeup = rtsTrue;
307 // the wakeup flag is needed because signalCondition() doesn't
308 // flag the condition if the thread is already runniing, but we want
310 signalCondition(&task->cond);
311 RELEASE_LOCK(&task->lock);
315 /* ----------------------------------------------------------------------------
316 * Function: releaseCapability(Capability*)
318 * Purpose: Letting go of a capability. Causes a
319 * 'returning worker' thread or a 'waiting worker'
320 * to wake up, in that order.
321 * ------------------------------------------------------------------------- */
323 #if defined(THREADED_RTS)
325 releaseCapability_ (Capability* cap,
326 rtsBool always_wakeup)
330 task = cap->running_task;
332 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task);
334 cap->running_task = NULL;
336 // Check to see whether a worker thread can be given
337 // the go-ahead to return the result of an external call..
338 if (cap->returning_tasks_hd != NULL) {
339 giveCapabilityToTask(cap,cap->returning_tasks_hd);
340 // The Task pops itself from the queue (see waitForReturnCapability())
344 /* if waiting_for_gc was the reason to release the cap: thread
345 comes from yieldCap->releaseAndQueueWorker. Unconditionally set
346 cap. free and return (see default after the if-protected other
347 special cases). Thread will wait on cond.var and re-acquire the
348 same cap after GC (GC-triggering cap. calls releaseCap and
349 enters the spare_workers case)
351 if (waiting_for_gc) {
352 last_free_capability = cap; // needed?
353 trace(TRACE_sched | DEBUG_sched,
354 "GC pending, set capability %d free", cap->no);
359 // If the next thread on the run queue is a bound thread,
360 // give this Capability to the appropriate Task.
361 if (!emptyRunQueue(cap) && cap->run_queue_hd->bound) {
362 // Make sure we're not about to try to wake ourselves up
363 ASSERT(task != cap->run_queue_hd->bound);
364 task = cap->run_queue_hd->bound;
365 giveCapabilityToTask(cap,task);
369 if (!cap->spare_workers) {
370 // Create a worker thread if we don't have one. If the system
371 // is interrupted, we only create a worker task if there
372 // are threads that need to be completed. If the system is
373 // shutting down, we never create a new worker.
374 if (sched_state < SCHED_SHUTTING_DOWN || !emptyRunQueue(cap)) {
375 debugTrace(DEBUG_sched,
376 "starting new worker on capability %d", cap->no);
377 startWorkerTask(cap, workerStart);
382 // If we have an unbound thread on the run queue, or if there's
383 // anything else to do, give the Capability to a worker thread.
385 !emptyRunQueue(cap) || !emptyWakeupQueue(cap) ||
386 !emptySparkPoolCap(cap) || globalWorkToDo()) {
387 if (cap->spare_workers) {
388 giveCapabilityToTask(cap,cap->spare_workers);
389 // The worker Task pops itself from the queue;
394 last_free_capability = cap;
395 trace(TRACE_sched | DEBUG_sched, "freeing capability %d", cap->no);
399 releaseCapability (Capability* cap USED_IF_THREADS)
401 ACQUIRE_LOCK(&cap->lock);
402 releaseCapability_(cap, rtsFalse);
403 RELEASE_LOCK(&cap->lock);
407 releaseAndWakeupCapability (Capability* cap USED_IF_THREADS)
409 ACQUIRE_LOCK(&cap->lock);
410 releaseCapability_(cap, rtsTrue);
411 RELEASE_LOCK(&cap->lock);
415 releaseCapabilityAndQueueWorker (Capability* cap USED_IF_THREADS)
419 ACQUIRE_LOCK(&cap->lock);
421 task = cap->running_task;
423 // If the current task is a worker, save it on the spare_workers
424 // list of this Capability. A worker can mark itself as stopped,
425 // in which case it is not replaced on the spare_worker queue.
426 // This happens when the system is shutting down (see
427 // Schedule.c:workerStart()).
428 // Also, be careful to check that this task hasn't just exited
429 // Haskell to do a foreign call (task->suspended_tso).
430 if (!isBoundTask(task) && !task->stopped && !task->suspended_tso) {
431 task->next = cap->spare_workers;
432 cap->spare_workers = task;
434 // Bound tasks just float around attached to their TSOs.
436 releaseCapability_(cap,rtsFalse);
438 RELEASE_LOCK(&cap->lock);
442 /* ----------------------------------------------------------------------------
443 * waitForReturnCapability( Task *task )
445 * Purpose: when an OS thread returns from an external call,
446 * it calls waitForReturnCapability() (via Schedule.resumeThread())
447 * to wait for permission to enter the RTS & communicate the
448 * result of the external call back to the Haskell thread that
451 * ------------------------------------------------------------------------- */
453 waitForReturnCapability (Capability **pCap, Task *task)
455 #if !defined(THREADED_RTS)
457 MainCapability.running_task = task;
458 task->cap = &MainCapability;
459 *pCap = &MainCapability;
462 Capability *cap = *pCap;
465 // Try last_free_capability first
466 cap = last_free_capability;
467 if (!cap->running_task) {
469 // otherwise, search for a free capability
470 for (i = 0; i < n_capabilities; i++) {
471 cap = &capabilities[i];
472 if (!cap->running_task) {
476 // Can't find a free one, use last_free_capability.
477 cap = last_free_capability;
480 // record the Capability as the one this Task is now assocated with.
484 ASSERT(task->cap == cap);
487 ACQUIRE_LOCK(&cap->lock);
489 debugTrace(DEBUG_sched, "returning; I want capability %d", cap->no);
491 if (!cap->running_task) {
492 // It's free; just grab it
493 cap->running_task = task;
494 RELEASE_LOCK(&cap->lock);
496 newReturningTask(cap,task);
497 RELEASE_LOCK(&cap->lock);
500 ACQUIRE_LOCK(&task->lock);
501 // task->lock held, cap->lock not held
502 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
504 task->wakeup = rtsFalse;
505 RELEASE_LOCK(&task->lock);
507 // now check whether we should wake up...
508 ACQUIRE_LOCK(&cap->lock);
509 if (cap->running_task == NULL) {
510 if (cap->returning_tasks_hd != task) {
511 giveCapabilityToTask(cap,cap->returning_tasks_hd);
512 RELEASE_LOCK(&cap->lock);
515 cap->running_task = task;
516 popReturningTask(cap);
517 RELEASE_LOCK(&cap->lock);
520 RELEASE_LOCK(&cap->lock);
525 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
527 trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
533 #if defined(THREADED_RTS)
534 /* ----------------------------------------------------------------------------
536 * ------------------------------------------------------------------------- */
539 yieldCapability (Capability** pCap, Task *task)
541 Capability *cap = *pCap;
543 debugTrace(DEBUG_sched, "giving up capability %d", cap->no);
545 // We must now release the capability and wait to be woken up
547 task->wakeup = rtsFalse;
548 releaseCapabilityAndQueueWorker(cap);
551 ACQUIRE_LOCK(&task->lock);
552 // task->lock held, cap->lock not held
553 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
555 task->wakeup = rtsFalse;
556 RELEASE_LOCK(&task->lock);
558 debugTrace(DEBUG_sched, "woken up on capability %d", cap->no);
560 ACQUIRE_LOCK(&cap->lock);
561 if (cap->running_task != NULL) {
562 debugTrace(DEBUG_sched,
563 "capability %d is owned by another task", cap->no);
564 RELEASE_LOCK(&cap->lock);
568 if (task->tso == NULL) {
569 ASSERT(cap->spare_workers != NULL);
570 // if we're not at the front of the queue, release it
571 // again. This is unlikely to happen.
572 if (cap->spare_workers != task) {
573 giveCapabilityToTask(cap,cap->spare_workers);
574 RELEASE_LOCK(&cap->lock);
577 cap->spare_workers = task->next;
580 cap->running_task = task;
581 RELEASE_LOCK(&cap->lock);
585 trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
586 ASSERT(cap->running_task == task);
590 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
595 /* ----------------------------------------------------------------------------
596 * Wake up a thread on a Capability.
598 * This is used when the current Task is running on a Capability and
599 * wishes to wake up a thread on a different Capability.
600 * ------------------------------------------------------------------------- */
603 wakeupThreadOnCapability (Capability *my_cap,
604 Capability *other_cap,
607 ACQUIRE_LOCK(&other_cap->lock);
609 // ASSUMES: cap->lock is held (asserted in wakeupThreadOnCapability)
611 ASSERT(tso->bound->cap == tso->cap);
612 tso->bound->cap = other_cap;
614 tso->cap = other_cap;
616 ASSERT(tso->bound ? tso->bound->cap == other_cap : 1);
618 if (other_cap->running_task == NULL) {
619 // nobody is running this Capability, we can add our thread
620 // directly onto the run queue and start up a Task to run it.
622 other_cap->running_task = myTask();
623 // precond for releaseCapability_() and appendToRunQueue()
625 appendToRunQueue(other_cap,tso);
627 trace(TRACE_sched, "resuming capability %d", other_cap->no);
628 releaseCapability_(other_cap,rtsFalse);
630 appendToWakeupQueue(my_cap,other_cap,tso);
631 other_cap->context_switch = 1;
632 // someone is running on this Capability, so it cannot be
633 // freed without first checking the wakeup queue (see
634 // releaseCapability_).
637 RELEASE_LOCK(&other_cap->lock);
640 /* ----------------------------------------------------------------------------
643 * Used to indicate that the interrupted flag is now set, or some
644 * other global condition that might require waking up a Task on each
646 * ------------------------------------------------------------------------- */
649 prodCapabilities(rtsBool all)
655 for (i=0; i < n_capabilities; i++) {
656 cap = &capabilities[i];
657 ACQUIRE_LOCK(&cap->lock);
658 if (!cap->running_task) {
659 if (cap->spare_workers) {
660 trace(TRACE_sched, "resuming capability %d", cap->no);
661 task = cap->spare_workers;
662 ASSERT(!task->stopped);
663 giveCapabilityToTask(cap,task);
665 RELEASE_LOCK(&cap->lock);
670 RELEASE_LOCK(&cap->lock);
676 prodAllCapabilities (void)
678 prodCapabilities(rtsTrue);
681 /* ----------------------------------------------------------------------------
684 * Like prodAllCapabilities, but we only require a single Task to wake
685 * up in order to service some global event, such as checking for
686 * deadlock after some idle time has passed.
687 * ------------------------------------------------------------------------- */
690 prodOneCapability (void)
692 prodCapabilities(rtsFalse);
695 /* ----------------------------------------------------------------------------
698 * At shutdown time, we want to let everything exit as cleanly as
699 * possible. For each capability, we let its run queue drain, and
700 * allow the workers to stop.
702 * This function should be called when interrupted and
703 * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
704 * will exit the scheduler and call taskStop(), and any bound thread
705 * that wakes up will return to its caller. Runnable threads are
708 * ------------------------------------------------------------------------- */
711 shutdownCapability (Capability *cap, Task *task, rtsBool safe)
715 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
719 // Loop indefinitely until all the workers have exited and there
720 // are no Haskell threads left. We used to bail out after 50
721 // iterations of this loop, but that occasionally left a worker
722 // running which caused problems later (the closeMutex() below
723 // isn't safe, for one thing).
725 for (i = 0; /* i < 50 */; i++) {
726 debugTrace(DEBUG_sched,
727 "shutting down capability %d, attempt %d", cap->no, i);
728 ACQUIRE_LOCK(&cap->lock);
729 if (cap->running_task) {
730 RELEASE_LOCK(&cap->lock);
731 debugTrace(DEBUG_sched, "not owner, yielding");
735 cap->running_task = task;
737 if (cap->spare_workers) {
738 // Look for workers that have died without removing
739 // themselves from the list; this could happen if the OS
740 // summarily killed the thread, for example. This
741 // actually happens on Windows when the system is
742 // terminating the program, and the RTS is running in a
746 for (t = cap->spare_workers; t != NULL; t = t->next) {
747 if (!osThreadIsAlive(t->id)) {
748 debugTrace(DEBUG_sched,
749 "worker thread %p has died unexpectedly", (void *)t->id);
751 cap->spare_workers = t->next;
753 prev->next = t->next;
760 if (!emptyRunQueue(cap) || cap->spare_workers) {
761 debugTrace(DEBUG_sched,
762 "runnable threads or workers still alive, yielding");
763 releaseCapability_(cap,rtsFalse); // this will wake up a worker
764 RELEASE_LOCK(&cap->lock);
769 // If "safe", then busy-wait for any threads currently doing
770 // foreign calls. If we're about to unload this DLL, for
771 // example, we need to be sure that there are no OS threads
772 // that will try to return to code that has been unloaded.
773 // We can be a bit more relaxed when this is a standalone
774 // program that is about to terminate, and let safe=false.
775 if (cap->suspended_ccalling_tasks && safe) {
776 debugTrace(DEBUG_sched,
777 "thread(s) are involved in foreign calls, yielding");
778 cap->running_task = NULL;
779 RELEASE_LOCK(&cap->lock);
784 debugTrace(DEBUG_sched, "capability %d is stopped.", cap->no);
785 RELEASE_LOCK(&cap->lock);
788 // we now have the Capability, its run queue and spare workers
789 // list are both empty.
791 // ToDo: we can't drop this mutex, because there might still be
792 // threads performing foreign calls that will eventually try to
793 // return via resumeThread() and attempt to grab cap->lock.
794 // closeMutex(&cap->lock);
797 /* ----------------------------------------------------------------------------
800 * Attempt to gain control of a Capability if it is free.
802 * ------------------------------------------------------------------------- */
805 tryGrabCapability (Capability *cap, Task *task)
807 if (cap->running_task != NULL) return rtsFalse;
808 ACQUIRE_LOCK(&cap->lock);
809 if (cap->running_task != NULL) {
810 RELEASE_LOCK(&cap->lock);
814 cap->running_task = task;
815 RELEASE_LOCK(&cap->lock);
820 #endif /* THREADED_RTS */
823 freeCapability (Capability *cap)
825 stgFree(cap->mut_lists);
826 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
827 freeSparkPool(cap->sparks);
832 freeCapabilities (void)
834 #if defined(THREADED_RTS)
836 for (i=0; i < n_capabilities; i++) {
837 freeCapability(&capabilities[i]);
840 freeCapability(&MainCapability);
844 /* ---------------------------------------------------------------------------
845 Mark everything directly reachable from the Capabilities. When
846 using multiple GC threads, each GC thread marks all Capabilities
847 for which (c `mod` n == 0), for Capability c and thread n.
848 ------------------------------------------------------------------------ */
851 markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta,
852 rtsBool prune_sparks USED_IF_THREADS)
858 // Each GC thread is responsible for following roots from the
859 // Capability of the same number. There will usually be the same
860 // or fewer Capabilities as GC threads, but just in case there
861 // are more, we mark every Capability whose number is the GC
862 // thread's index plus a multiple of the number of GC threads.
863 for (i = i0; i < n_capabilities; i += delta) {
864 cap = &capabilities[i];
865 evac(user, (StgClosure **)(void *)&cap->run_queue_hd);
866 evac(user, (StgClosure **)(void *)&cap->run_queue_tl);
867 #if defined(THREADED_RTS)
868 evac(user, (StgClosure **)(void *)&cap->wakeup_queue_hd);
869 evac(user, (StgClosure **)(void *)&cap->wakeup_queue_tl);
871 for (task = cap->suspended_ccalling_tasks; task != NULL;
873 debugTrace(DEBUG_sched,
874 "evac'ing suspended TSO %lu", (unsigned long)task->suspended_tso->id);
875 evac(user, (StgClosure **)(void *)&task->suspended_tso);
878 #if defined(THREADED_RTS)
880 pruneSparkQueue (evac, user, cap);
882 traverseSparkQueue (evac, user, cap);
887 #if !defined(THREADED_RTS)
888 evac(user, (StgClosure **)(void *)&blocked_queue_hd);
889 evac(user, (StgClosure **)(void *)&blocked_queue_tl);
890 evac(user, (StgClosure **)(void *)&sleeping_queue);
895 markCapabilities (evac_fn evac, void *user)
897 markSomeCapabilities(evac, user, 0, 1, rtsFalse);