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 rtsFalse; } // 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->sparks);
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",
100 createSparkThread(cap,spark);
103 // otherwise: no success, try next one
107 debugTrace(DEBUG_sched, "No sparks stolen");
112 /* -----------------------------------------------------------------------------
113 * Manage the returning_tasks lists.
115 * These functions require cap->lock
116 * -------------------------------------------------------------------------- */
118 #if defined(THREADED_RTS)
120 newReturningTask (Capability *cap, Task *task)
122 ASSERT_LOCK_HELD(&cap->lock);
123 ASSERT(task->return_link == NULL);
124 if (cap->returning_tasks_hd) {
125 ASSERT(cap->returning_tasks_tl->return_link == NULL);
126 cap->returning_tasks_tl->return_link = task;
128 cap->returning_tasks_hd = task;
130 cap->returning_tasks_tl = task;
134 popReturningTask (Capability *cap)
136 ASSERT_LOCK_HELD(&cap->lock);
138 task = cap->returning_tasks_hd;
140 cap->returning_tasks_hd = task->return_link;
141 if (!cap->returning_tasks_hd) {
142 cap->returning_tasks_tl = NULL;
144 task->return_link = NULL;
149 /* ----------------------------------------------------------------------------
152 * The Capability is initially marked not free.
153 * ------------------------------------------------------------------------- */
156 initCapability( Capability *cap, nat i )
161 cap->in_haskell = rtsFalse;
163 cap->run_queue_hd = END_TSO_QUEUE;
164 cap->run_queue_tl = END_TSO_QUEUE;
166 #if defined(THREADED_RTS)
167 initMutex(&cap->lock);
168 cap->running_task = NULL; // indicates cap is free
169 cap->spare_workers = NULL;
170 cap->suspended_ccalling_tasks = NULL;
171 cap->returning_tasks_hd = NULL;
172 cap->returning_tasks_tl = NULL;
173 cap->wakeup_queue_hd = END_TSO_QUEUE;
174 cap->wakeup_queue_tl = END_TSO_QUEUE;
175 cap->sparks_created = 0;
176 cap->sparks_converted = 0;
177 cap->sparks_pruned = 0;
180 cap->f.stgGCEnter1 = (F_)__stg_gc_enter_1;
181 cap->f.stgGCFun = (F_)__stg_gc_fun;
183 cap->mut_lists = stgMallocBytes(sizeof(bdescr *) *
184 RtsFlags.GcFlags.generations,
187 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
188 cap->mut_lists[g] = NULL;
191 cap->free_tvar_watch_queues = END_STM_WATCH_QUEUE;
192 cap->free_invariant_check_queues = END_INVARIANT_CHECK_QUEUE;
193 cap->free_trec_chunks = END_STM_CHUNK_LIST;
194 cap->free_trec_headers = NO_TREC;
195 cap->transaction_tokens = 0;
196 cap->context_switch = 0;
199 /* ---------------------------------------------------------------------------
200 * Function: initCapabilities()
202 * Purpose: set up the Capability handling. For the THREADED_RTS build,
203 * we keep a table of them, the size of which is
204 * controlled by the user via the RTS flag -N.
206 * ------------------------------------------------------------------------- */
208 initCapabilities( void )
210 #if defined(THREADED_RTS)
214 // We can't support multiple CPUs if BaseReg is not a register
215 if (RtsFlags.ParFlags.nNodes > 1) {
216 errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
217 RtsFlags.ParFlags.nNodes = 1;
221 n_capabilities = RtsFlags.ParFlags.nNodes;
223 if (n_capabilities == 1) {
224 capabilities = &MainCapability;
225 // THREADED_RTS must work on builds that don't have a mutable
226 // BaseReg (eg. unregisterised), so in this case
227 // capabilities[0] must coincide with &MainCapability.
229 capabilities = stgMallocBytes(n_capabilities * sizeof(Capability),
233 for (i = 0; i < n_capabilities; i++) {
234 initCapability(&capabilities[i], i);
237 debugTrace(DEBUG_sched, "allocated %d capabilities", n_capabilities);
239 #else /* !THREADED_RTS */
242 capabilities = &MainCapability;
243 initCapability(&MainCapability, 0);
247 // There are no free capabilities to begin with. We will start
248 // a worker Task to each Capability, which will quickly put the
249 // Capability on the free list when it finds nothing to do.
250 last_free_capability = &capabilities[0];
253 /* ----------------------------------------------------------------------------
254 * setContextSwitches: cause all capabilities to context switch as
256 * ------------------------------------------------------------------------- */
258 void setContextSwitches(void)
261 for (i=0; i < n_capabilities; i++) {
262 capabilities[i].context_switch = 1;
266 /* ----------------------------------------------------------------------------
267 * Give a Capability to a Task. The task must currently be sleeping
268 * on its condition variable.
270 * Requires cap->lock (modifies cap->running_task).
272 * When migrating a Task, the migrater must take task->lock before
273 * modifying task->cap, to synchronise with the waking up Task.
274 * Additionally, the migrater should own the Capability (when
275 * migrating the run queue), or cap->lock (when migrating
276 * returning_workers).
278 * ------------------------------------------------------------------------- */
280 #if defined(THREADED_RTS)
282 giveCapabilityToTask (Capability *cap USED_IF_DEBUG, Task *task)
284 ASSERT_LOCK_HELD(&cap->lock);
285 ASSERT(task->cap == cap);
286 trace(TRACE_sched | DEBUG_sched,
287 "passing capability %d to %s %p",
288 cap->no, task->tso ? "bound task" : "worker",
290 ACQUIRE_LOCK(&task->lock);
291 task->wakeup = rtsTrue;
292 // the wakeup flag is needed because signalCondition() doesn't
293 // flag the condition if the thread is already runniing, but we want
295 signalCondition(&task->cond);
296 RELEASE_LOCK(&task->lock);
300 /* ----------------------------------------------------------------------------
301 * Function: releaseCapability(Capability*)
303 * Purpose: Letting go of a capability. Causes a
304 * 'returning worker' thread or a 'waiting worker'
305 * to wake up, in that order.
306 * ------------------------------------------------------------------------- */
308 #if defined(THREADED_RTS)
310 releaseCapability_ (Capability* cap,
311 rtsBool always_wakeup)
315 task = cap->running_task;
317 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task);
319 cap->running_task = NULL;
321 // Check to see whether a worker thread can be given
322 // the go-ahead to return the result of an external call..
323 if (cap->returning_tasks_hd != NULL) {
324 giveCapabilityToTask(cap,cap->returning_tasks_hd);
325 // The Task pops itself from the queue (see waitForReturnCapability())
329 /* if waiting_for_gc was the reason to release the cap: thread
330 comes from yieldCap->releaseAndQueueWorker. Unconditionally set
331 cap. free and return (see default after the if-protected other
332 special cases). Thread will wait on cond.var and re-acquire the
333 same cap after GC (GC-triggering cap. calls releaseCap and
334 enters the spare_workers case)
336 if (waiting_for_gc) {
337 last_free_capability = cap; // needed?
338 trace(TRACE_sched | DEBUG_sched,
339 "GC pending, set capability %d free", cap->no);
344 // If the next thread on the run queue is a bound thread,
345 // give this Capability to the appropriate Task.
346 if (!emptyRunQueue(cap) && cap->run_queue_hd->bound) {
347 // Make sure we're not about to try to wake ourselves up
348 ASSERT(task != cap->run_queue_hd->bound);
349 task = cap->run_queue_hd->bound;
350 giveCapabilityToTask(cap,task);
354 if (!cap->spare_workers) {
355 // Create a worker thread if we don't have one. If the system
356 // is interrupted, we only create a worker task if there
357 // are threads that need to be completed. If the system is
358 // shutting down, we never create a new worker.
359 if (sched_state < SCHED_SHUTTING_DOWN || !emptyRunQueue(cap)) {
360 debugTrace(DEBUG_sched,
361 "starting new worker on capability %d", cap->no);
362 startWorkerTask(cap, workerStart);
367 // If we have an unbound thread on the run queue, or if there's
368 // anything else to do, give the Capability to a worker thread.
370 !emptyRunQueue(cap) || !emptyWakeupQueue(cap) ||
371 !emptySparkPoolCap(cap) || globalWorkToDo()) {
372 if (cap->spare_workers) {
373 giveCapabilityToTask(cap,cap->spare_workers);
374 // The worker Task pops itself from the queue;
379 last_free_capability = cap;
380 trace(TRACE_sched | DEBUG_sched, "freeing capability %d", cap->no);
384 releaseCapability (Capability* cap USED_IF_THREADS)
386 ACQUIRE_LOCK(&cap->lock);
387 releaseCapability_(cap, rtsFalse);
388 RELEASE_LOCK(&cap->lock);
392 releaseAndWakeupCapability (Capability* cap USED_IF_THREADS)
394 ACQUIRE_LOCK(&cap->lock);
395 releaseCapability_(cap, rtsTrue);
396 RELEASE_LOCK(&cap->lock);
400 releaseCapabilityAndQueueWorker (Capability* cap USED_IF_THREADS)
404 ACQUIRE_LOCK(&cap->lock);
406 task = cap->running_task;
408 // If the current task is a worker, save it on the spare_workers
409 // list of this Capability. A worker can mark itself as stopped,
410 // in which case it is not replaced on the spare_worker queue.
411 // This happens when the system is shutting down (see
412 // Schedule.c:workerStart()).
413 // Also, be careful to check that this task hasn't just exited
414 // Haskell to do a foreign call (task->suspended_tso).
415 if (!isBoundTask(task) && !task->stopped && !task->suspended_tso) {
416 task->next = cap->spare_workers;
417 cap->spare_workers = task;
419 // Bound tasks just float around attached to their TSOs.
421 releaseCapability_(cap,rtsFalse);
423 RELEASE_LOCK(&cap->lock);
427 /* ----------------------------------------------------------------------------
428 * waitForReturnCapability( Task *task )
430 * Purpose: when an OS thread returns from an external call,
431 * it calls waitForReturnCapability() (via Schedule.resumeThread())
432 * to wait for permission to enter the RTS & communicate the
433 * result of the external call back to the Haskell thread that
436 * ------------------------------------------------------------------------- */
438 waitForReturnCapability (Capability **pCap, Task *task)
440 #if !defined(THREADED_RTS)
442 MainCapability.running_task = task;
443 task->cap = &MainCapability;
444 *pCap = &MainCapability;
447 Capability *cap = *pCap;
450 // Try last_free_capability first
451 cap = last_free_capability;
452 if (!cap->running_task) {
454 // otherwise, search for a free capability
455 for (i = 0; i < n_capabilities; i++) {
456 cap = &capabilities[i];
457 if (!cap->running_task) {
461 // Can't find a free one, use last_free_capability.
462 cap = last_free_capability;
465 // record the Capability as the one this Task is now assocated with.
469 ASSERT(task->cap == cap);
472 ACQUIRE_LOCK(&cap->lock);
474 debugTrace(DEBUG_sched, "returning; I want capability %d", cap->no);
476 if (!cap->running_task) {
477 // It's free; just grab it
478 cap->running_task = task;
479 RELEASE_LOCK(&cap->lock);
481 newReturningTask(cap,task);
482 RELEASE_LOCK(&cap->lock);
485 ACQUIRE_LOCK(&task->lock);
486 // task->lock held, cap->lock not held
487 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
489 task->wakeup = rtsFalse;
490 RELEASE_LOCK(&task->lock);
492 // now check whether we should wake up...
493 ACQUIRE_LOCK(&cap->lock);
494 if (cap->running_task == NULL) {
495 if (cap->returning_tasks_hd != task) {
496 giveCapabilityToTask(cap,cap->returning_tasks_hd);
497 RELEASE_LOCK(&cap->lock);
500 cap->running_task = task;
501 popReturningTask(cap);
502 RELEASE_LOCK(&cap->lock);
505 RELEASE_LOCK(&cap->lock);
510 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
512 trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
518 #if defined(THREADED_RTS)
519 /* ----------------------------------------------------------------------------
521 * ------------------------------------------------------------------------- */
524 yieldCapability (Capability** pCap, Task *task)
526 Capability *cap = *pCap;
528 debugTrace(DEBUG_sched, "giving up capability %d", cap->no);
530 // We must now release the capability and wait to be woken up
532 task->wakeup = rtsFalse;
533 releaseCapabilityAndQueueWorker(cap);
536 ACQUIRE_LOCK(&task->lock);
537 // task->lock held, cap->lock not held
538 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
540 task->wakeup = rtsFalse;
541 RELEASE_LOCK(&task->lock);
543 debugTrace(DEBUG_sched, "woken up on capability %d", cap->no);
545 ACQUIRE_LOCK(&cap->lock);
546 if (cap->running_task != NULL) {
547 debugTrace(DEBUG_sched,
548 "capability %d is owned by another task", cap->no);
549 RELEASE_LOCK(&cap->lock);
553 if (task->tso == NULL) {
554 ASSERT(cap->spare_workers != NULL);
555 // if we're not at the front of the queue, release it
556 // again. This is unlikely to happen.
557 if (cap->spare_workers != task) {
558 giveCapabilityToTask(cap,cap->spare_workers);
559 RELEASE_LOCK(&cap->lock);
562 cap->spare_workers = task->next;
565 cap->running_task = task;
566 RELEASE_LOCK(&cap->lock);
570 trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
571 ASSERT(cap->running_task == task);
575 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
580 /* ----------------------------------------------------------------------------
581 * Wake up a thread on a Capability.
583 * This is used when the current Task is running on a Capability and
584 * wishes to wake up a thread on a different Capability.
585 * ------------------------------------------------------------------------- */
588 wakeupThreadOnCapability (Capability *my_cap,
589 Capability *other_cap,
592 ACQUIRE_LOCK(&other_cap->lock);
594 // ASSUMES: cap->lock is held (asserted in wakeupThreadOnCapability)
596 ASSERT(tso->bound->cap == tso->cap);
597 tso->bound->cap = other_cap;
599 tso->cap = other_cap;
601 ASSERT(tso->bound ? tso->bound->cap == other_cap : 1);
603 if (other_cap->running_task == NULL) {
604 // nobody is running this Capability, we can add our thread
605 // directly onto the run queue and start up a Task to run it.
607 other_cap->running_task = myTask();
608 // precond for releaseCapability_() and appendToRunQueue()
610 appendToRunQueue(other_cap,tso);
612 trace(TRACE_sched, "resuming capability %d", other_cap->no);
613 releaseCapability_(other_cap,rtsFalse);
615 appendToWakeupQueue(my_cap,other_cap,tso);
616 other_cap->context_switch = 1;
617 // someone is running on this Capability, so it cannot be
618 // freed without first checking the wakeup queue (see
619 // releaseCapability_).
622 RELEASE_LOCK(&other_cap->lock);
625 /* ----------------------------------------------------------------------------
628 * Used to indicate that the interrupted flag is now set, or some
629 * other global condition that might require waking up a Task on each
631 * ------------------------------------------------------------------------- */
634 prodCapabilities(rtsBool all)
640 for (i=0; i < n_capabilities; i++) {
641 cap = &capabilities[i];
642 ACQUIRE_LOCK(&cap->lock);
643 if (!cap->running_task) {
644 if (cap->spare_workers) {
645 trace(TRACE_sched, "resuming capability %d", cap->no);
646 task = cap->spare_workers;
647 ASSERT(!task->stopped);
648 giveCapabilityToTask(cap,task);
650 RELEASE_LOCK(&cap->lock);
655 RELEASE_LOCK(&cap->lock);
661 prodAllCapabilities (void)
663 prodCapabilities(rtsTrue);
666 /* ----------------------------------------------------------------------------
669 * Like prodAllCapabilities, but we only require a single Task to wake
670 * up in order to service some global event, such as checking for
671 * deadlock after some idle time has passed.
672 * ------------------------------------------------------------------------- */
675 prodOneCapability (void)
677 prodCapabilities(rtsFalse);
680 /* ----------------------------------------------------------------------------
683 * At shutdown time, we want to let everything exit as cleanly as
684 * possible. For each capability, we let its run queue drain, and
685 * allow the workers to stop.
687 * This function should be called when interrupted and
688 * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
689 * will exit the scheduler and call taskStop(), and any bound thread
690 * that wakes up will return to its caller. Runnable threads are
693 * ------------------------------------------------------------------------- */
696 shutdownCapability (Capability *cap, Task *task, rtsBool safe)
700 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
704 // Loop indefinitely until all the workers have exited and there
705 // are no Haskell threads left. We used to bail out after 50
706 // iterations of this loop, but that occasionally left a worker
707 // running which caused problems later (the closeMutex() below
708 // isn't safe, for one thing).
710 for (i = 0; /* i < 50 */; i++) {
711 debugTrace(DEBUG_sched,
712 "shutting down capability %d, attempt %d", cap->no, i);
713 ACQUIRE_LOCK(&cap->lock);
714 if (cap->running_task) {
715 RELEASE_LOCK(&cap->lock);
716 debugTrace(DEBUG_sched, "not owner, yielding");
720 cap->running_task = task;
722 if (cap->spare_workers) {
723 // Look for workers that have died without removing
724 // themselves from the list; this could happen if the OS
725 // summarily killed the thread, for example. This
726 // actually happens on Windows when the system is
727 // terminating the program, and the RTS is running in a
731 for (t = cap->spare_workers; t != NULL; t = t->next) {
732 if (!osThreadIsAlive(t->id)) {
733 debugTrace(DEBUG_sched,
734 "worker thread %p has died unexpectedly", (void *)t->id);
736 cap->spare_workers = t->next;
738 prev->next = t->next;
745 if (!emptyRunQueue(cap) || cap->spare_workers) {
746 debugTrace(DEBUG_sched,
747 "runnable threads or workers still alive, yielding");
748 releaseCapability_(cap,rtsFalse); // this will wake up a worker
749 RELEASE_LOCK(&cap->lock);
754 // If "safe", then busy-wait for any threads currently doing
755 // foreign calls. If we're about to unload this DLL, for
756 // example, we need to be sure that there are no OS threads
757 // that will try to return to code that has been unloaded.
758 // We can be a bit more relaxed when this is a standalone
759 // program that is about to terminate, and let safe=false.
760 if (cap->suspended_ccalling_tasks && safe) {
761 debugTrace(DEBUG_sched,
762 "thread(s) are involved in foreign calls, yielding");
763 cap->running_task = NULL;
764 RELEASE_LOCK(&cap->lock);
769 debugTrace(DEBUG_sched, "capability %d is stopped.", cap->no);
770 RELEASE_LOCK(&cap->lock);
773 // we now have the Capability, its run queue and spare workers
774 // list are both empty.
776 // ToDo: we can't drop this mutex, because there might still be
777 // threads performing foreign calls that will eventually try to
778 // return via resumeThread() and attempt to grab cap->lock.
779 // closeMutex(&cap->lock);
782 /* ----------------------------------------------------------------------------
785 * Attempt to gain control of a Capability if it is free.
787 * ------------------------------------------------------------------------- */
790 tryGrabCapability (Capability *cap, Task *task)
792 if (cap->running_task != NULL) return rtsFalse;
793 ACQUIRE_LOCK(&cap->lock);
794 if (cap->running_task != NULL) {
795 RELEASE_LOCK(&cap->lock);
799 cap->running_task = task;
800 RELEASE_LOCK(&cap->lock);
805 #endif /* THREADED_RTS */
808 freeCapability (Capability *cap)
810 stgFree(cap->mut_lists);
811 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
812 freeSparkPool(cap->sparks);
817 freeCapabilities (void)
819 #if defined(THREADED_RTS)
821 for (i=0; i < n_capabilities; i++) {
822 freeCapability(&capabilities[i]);
825 freeCapability(&MainCapability);
829 /* ---------------------------------------------------------------------------
830 Mark everything directly reachable from the Capabilities. When
831 using multiple GC threads, each GC thread marks all Capabilities
832 for which (c `mod` n == 0), for Capability c and thread n.
833 ------------------------------------------------------------------------ */
836 markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta,
837 rtsBool prune_sparks USED_IF_THREADS)
843 // Each GC thread is responsible for following roots from the
844 // Capability of the same number. There will usually be the same
845 // or fewer Capabilities as GC threads, but just in case there
846 // are more, we mark every Capability whose number is the GC
847 // thread's index plus a multiple of the number of GC threads.
848 for (i = i0; i < n_capabilities; i += delta) {
849 cap = &capabilities[i];
850 evac(user, (StgClosure **)(void *)&cap->run_queue_hd);
851 evac(user, (StgClosure **)(void *)&cap->run_queue_tl);
852 #if defined(THREADED_RTS)
853 evac(user, (StgClosure **)(void *)&cap->wakeup_queue_hd);
854 evac(user, (StgClosure **)(void *)&cap->wakeup_queue_tl);
856 for (task = cap->suspended_ccalling_tasks; task != NULL;
858 debugTrace(DEBUG_sched,
859 "evac'ing suspended TSO %lu", (unsigned long)task->suspended_tso->id);
860 evac(user, (StgClosure **)(void *)&task->suspended_tso);
863 #if defined(THREADED_RTS)
865 pruneSparkQueue (evac, user, cap);
867 traverseSparkQueue (evac, user, cap);
872 #if !defined(THREADED_RTS)
873 evac(user, (StgClosure **)(void *)&blocked_queue_hd);
874 evac(user, (StgClosure **)(void *)&blocked_queue_tl);
875 evac(user, (StgClosure **)(void *)&sleeping_queue);
880 markCapabilities (evac_fn evac, void *user)
882 markSomeCapabilities(evac, user, 0, 1, rtsFalse);