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
66 rtsBool success = rtsFalse;
70 debugTrace(DEBUG_sched,
71 "cap %d: Trying to steal work from other capabilities",
74 if (n_capabilities == 1) { return rtsFalse; } // makes no sense...
79 /* visit cap.s 0..n-1 in sequence until a theft succeeds. We could
80 start at a random place instead of 0 as well. */
81 for ( i=0 ; i < n_capabilities ; i++ ) {
82 robbed = &capabilities[i];
83 if (cap == robbed) // ourselves...
86 if (emptySparkPoolCap(robbed)) // nothing to steal here
89 spark = tryStealSpark(robbed->sparks);
90 if (spark == NULL && !emptySparkPoolCap(robbed)) {
91 // we conflicted with another thread while trying to steal;
97 debugTrace(DEBUG_sched,
98 "cap %d: Stole a spark from capability %d",
101 createSparkThread(cap,spark);
104 // otherwise: no success, try next one
108 debugTrace(DEBUG_sched, "No sparks stolen");
113 /* -----------------------------------------------------------------------------
114 * Manage the returning_tasks lists.
116 * These functions require cap->lock
117 * -------------------------------------------------------------------------- */
119 #if defined(THREADED_RTS)
121 newReturningTask (Capability *cap, Task *task)
123 ASSERT_LOCK_HELD(&cap->lock);
124 ASSERT(task->return_link == NULL);
125 if (cap->returning_tasks_hd) {
126 ASSERT(cap->returning_tasks_tl->return_link == NULL);
127 cap->returning_tasks_tl->return_link = task;
129 cap->returning_tasks_hd = task;
131 cap->returning_tasks_tl = task;
135 popReturningTask (Capability *cap)
137 ASSERT_LOCK_HELD(&cap->lock);
139 task = cap->returning_tasks_hd;
141 cap->returning_tasks_hd = task->return_link;
142 if (!cap->returning_tasks_hd) {
143 cap->returning_tasks_tl = NULL;
145 task->return_link = NULL;
150 /* ----------------------------------------------------------------------------
153 * The Capability is initially marked not free.
154 * ------------------------------------------------------------------------- */
157 initCapability( Capability *cap, nat i )
162 cap->in_haskell = rtsFalse;
164 cap->run_queue_hd = END_TSO_QUEUE;
165 cap->run_queue_tl = END_TSO_QUEUE;
167 #if defined(THREADED_RTS)
168 initMutex(&cap->lock);
169 cap->running_task = NULL; // indicates cap is free
170 cap->spare_workers = NULL;
171 cap->suspended_ccalling_tasks = NULL;
172 cap->returning_tasks_hd = NULL;
173 cap->returning_tasks_tl = NULL;
174 cap->wakeup_queue_hd = END_TSO_QUEUE;
175 cap->wakeup_queue_tl = END_TSO_QUEUE;
176 cap->sparks_created = 0;
177 cap->sparks_converted = 0;
178 cap->sparks_pruned = 0;
181 cap->f.stgGCEnter1 = (F_)__stg_gc_enter_1;
182 cap->f.stgGCFun = (F_)__stg_gc_fun;
184 cap->mut_lists = stgMallocBytes(sizeof(bdescr *) *
185 RtsFlags.GcFlags.generations,
188 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
189 cap->mut_lists[g] = NULL;
192 cap->free_tvar_watch_queues = END_STM_WATCH_QUEUE;
193 cap->free_invariant_check_queues = END_INVARIANT_CHECK_QUEUE;
194 cap->free_trec_chunks = END_STM_CHUNK_LIST;
195 cap->free_trec_headers = NO_TREC;
196 cap->transaction_tokens = 0;
197 cap->context_switch = 0;
200 /* ---------------------------------------------------------------------------
201 * Function: initCapabilities()
203 * Purpose: set up the Capability handling. For the THREADED_RTS build,
204 * we keep a table of them, the size of which is
205 * controlled by the user via the RTS flag -N.
207 * ------------------------------------------------------------------------- */
209 initCapabilities( void )
211 #if defined(THREADED_RTS)
215 // We can't support multiple CPUs if BaseReg is not a register
216 if (RtsFlags.ParFlags.nNodes > 1) {
217 errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
218 RtsFlags.ParFlags.nNodes = 1;
222 n_capabilities = RtsFlags.ParFlags.nNodes;
224 if (n_capabilities == 1) {
225 capabilities = &MainCapability;
226 // THREADED_RTS must work on builds that don't have a mutable
227 // BaseReg (eg. unregisterised), so in this case
228 // capabilities[0] must coincide with &MainCapability.
230 capabilities = stgMallocBytes(n_capabilities * sizeof(Capability),
234 for (i = 0; i < n_capabilities; i++) {
235 initCapability(&capabilities[i], i);
238 debugTrace(DEBUG_sched, "allocated %d capabilities", n_capabilities);
240 #else /* !THREADED_RTS */
243 capabilities = &MainCapability;
244 initCapability(&MainCapability, 0);
248 // There are no free capabilities to begin with. We will start
249 // a worker Task to each Capability, which will quickly put the
250 // Capability on the free list when it finds nothing to do.
251 last_free_capability = &capabilities[0];
254 /* ----------------------------------------------------------------------------
255 * setContextSwitches: cause all capabilities to context switch as
257 * ------------------------------------------------------------------------- */
259 void setContextSwitches(void)
262 for (i=0; i < n_capabilities; i++) {
263 capabilities[i].context_switch = 1;
267 /* ----------------------------------------------------------------------------
268 * Give a Capability to a Task. The task must currently be sleeping
269 * on its condition variable.
271 * Requires cap->lock (modifies cap->running_task).
273 * When migrating a Task, the migrater must take task->lock before
274 * modifying task->cap, to synchronise with the waking up Task.
275 * Additionally, the migrater should own the Capability (when
276 * migrating the run queue), or cap->lock (when migrating
277 * returning_workers).
279 * ------------------------------------------------------------------------- */
281 #if defined(THREADED_RTS)
283 giveCapabilityToTask (Capability *cap USED_IF_DEBUG, Task *task)
285 ASSERT_LOCK_HELD(&cap->lock);
286 ASSERT(task->cap == cap);
287 trace(TRACE_sched | DEBUG_sched,
288 "passing capability %d to %s %p",
289 cap->no, task->tso ? "bound task" : "worker",
291 ACQUIRE_LOCK(&task->lock);
292 task->wakeup = rtsTrue;
293 // the wakeup flag is needed because signalCondition() doesn't
294 // flag the condition if the thread is already runniing, but we want
296 signalCondition(&task->cond);
297 RELEASE_LOCK(&task->lock);
301 /* ----------------------------------------------------------------------------
302 * Function: releaseCapability(Capability*)
304 * Purpose: Letting go of a capability. Causes a
305 * 'returning worker' thread or a 'waiting worker'
306 * to wake up, in that order.
307 * ------------------------------------------------------------------------- */
309 #if defined(THREADED_RTS)
311 releaseCapability_ (Capability* cap,
312 rtsBool always_wakeup)
316 task = cap->running_task;
318 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task);
320 cap->running_task = NULL;
322 // Check to see whether a worker thread can be given
323 // the go-ahead to return the result of an external call..
324 if (cap->returning_tasks_hd != NULL) {
325 giveCapabilityToTask(cap,cap->returning_tasks_hd);
326 // The Task pops itself from the queue (see waitForReturnCapability())
330 /* if waiting_for_gc was the reason to release the cap: thread
331 comes from yieldCap->releaseAndQueueWorker. Unconditionally set
332 cap. free and return (see default after the if-protected other
333 special cases). Thread will wait on cond.var and re-acquire the
334 same cap after GC (GC-triggering cap. calls releaseCap and
335 enters the spare_workers case)
337 if (waiting_for_gc) {
338 last_free_capability = cap; // needed?
339 trace(TRACE_sched | DEBUG_sched,
340 "GC pending, set capability %d free", cap->no);
345 // If the next thread on the run queue is a bound thread,
346 // give this Capability to the appropriate Task.
347 if (!emptyRunQueue(cap) && cap->run_queue_hd->bound) {
348 // Make sure we're not about to try to wake ourselves up
349 ASSERT(task != cap->run_queue_hd->bound);
350 task = cap->run_queue_hd->bound;
351 giveCapabilityToTask(cap,task);
355 if (!cap->spare_workers) {
356 // Create a worker thread if we don't have one. If the system
357 // is interrupted, we only create a worker task if there
358 // are threads that need to be completed. If the system is
359 // shutting down, we never create a new worker.
360 if (sched_state < SCHED_SHUTTING_DOWN || !emptyRunQueue(cap)) {
361 debugTrace(DEBUG_sched,
362 "starting new worker on capability %d", cap->no);
363 startWorkerTask(cap, workerStart);
368 // If we have an unbound thread on the run queue, or if there's
369 // anything else to do, give the Capability to a worker thread.
371 !emptyRunQueue(cap) || !emptyWakeupQueue(cap) ||
372 !emptySparkPoolCap(cap) || globalWorkToDo()) {
373 if (cap->spare_workers) {
374 giveCapabilityToTask(cap,cap->spare_workers);
375 // The worker Task pops itself from the queue;
380 last_free_capability = cap;
381 trace(TRACE_sched | DEBUG_sched, "freeing capability %d", cap->no);
385 releaseCapability (Capability* cap USED_IF_THREADS)
387 ACQUIRE_LOCK(&cap->lock);
388 releaseCapability_(cap, rtsFalse);
389 RELEASE_LOCK(&cap->lock);
393 releaseAndWakeupCapability (Capability* cap USED_IF_THREADS)
395 ACQUIRE_LOCK(&cap->lock);
396 releaseCapability_(cap, rtsTrue);
397 RELEASE_LOCK(&cap->lock);
401 releaseCapabilityAndQueueWorker (Capability* cap USED_IF_THREADS)
405 ACQUIRE_LOCK(&cap->lock);
407 task = cap->running_task;
409 // If the current task is a worker, save it on the spare_workers
410 // list of this Capability. A worker can mark itself as stopped,
411 // in which case it is not replaced on the spare_worker queue.
412 // This happens when the system is shutting down (see
413 // Schedule.c:workerStart()).
414 // Also, be careful to check that this task hasn't just exited
415 // Haskell to do a foreign call (task->suspended_tso).
416 if (!isBoundTask(task) && !task->stopped && !task->suspended_tso) {
417 task->next = cap->spare_workers;
418 cap->spare_workers = task;
420 // Bound tasks just float around attached to their TSOs.
422 releaseCapability_(cap,rtsFalse);
424 RELEASE_LOCK(&cap->lock);
428 /* ----------------------------------------------------------------------------
429 * waitForReturnCapability( Task *task )
431 * Purpose: when an OS thread returns from an external call,
432 * it calls waitForReturnCapability() (via Schedule.resumeThread())
433 * to wait for permission to enter the RTS & communicate the
434 * result of the external call back to the Haskell thread that
437 * ------------------------------------------------------------------------- */
439 waitForReturnCapability (Capability **pCap, Task *task)
441 #if !defined(THREADED_RTS)
443 MainCapability.running_task = task;
444 task->cap = &MainCapability;
445 *pCap = &MainCapability;
448 Capability *cap = *pCap;
451 // Try last_free_capability first
452 cap = last_free_capability;
453 if (!cap->running_task) {
455 // otherwise, search for a free capability
456 for (i = 0; i < n_capabilities; i++) {
457 cap = &capabilities[i];
458 if (!cap->running_task) {
462 // Can't find a free one, use last_free_capability.
463 cap = last_free_capability;
466 // record the Capability as the one this Task is now assocated with.
470 ASSERT(task->cap == cap);
473 ACQUIRE_LOCK(&cap->lock);
475 debugTrace(DEBUG_sched, "returning; I want capability %d", cap->no);
477 if (!cap->running_task) {
478 // It's free; just grab it
479 cap->running_task = task;
480 RELEASE_LOCK(&cap->lock);
482 newReturningTask(cap,task);
483 RELEASE_LOCK(&cap->lock);
486 ACQUIRE_LOCK(&task->lock);
487 // task->lock held, cap->lock not held
488 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
490 task->wakeup = rtsFalse;
491 RELEASE_LOCK(&task->lock);
493 // now check whether we should wake up...
494 ACQUIRE_LOCK(&cap->lock);
495 if (cap->running_task == NULL) {
496 if (cap->returning_tasks_hd != task) {
497 giveCapabilityToTask(cap,cap->returning_tasks_hd);
498 RELEASE_LOCK(&cap->lock);
501 cap->running_task = task;
502 popReturningTask(cap);
503 RELEASE_LOCK(&cap->lock);
506 RELEASE_LOCK(&cap->lock);
511 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
513 trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
519 #if defined(THREADED_RTS)
520 /* ----------------------------------------------------------------------------
522 * ------------------------------------------------------------------------- */
525 yieldCapability (Capability** pCap, Task *task)
527 Capability *cap = *pCap;
529 debugTrace(DEBUG_sched, "giving up capability %d", cap->no);
531 // We must now release the capability and wait to be woken up
533 task->wakeup = rtsFalse;
534 releaseCapabilityAndQueueWorker(cap);
537 ACQUIRE_LOCK(&task->lock);
538 // task->lock held, cap->lock not held
539 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
541 task->wakeup = rtsFalse;
542 RELEASE_LOCK(&task->lock);
544 debugTrace(DEBUG_sched, "woken up on capability %d", cap->no);
546 ACQUIRE_LOCK(&cap->lock);
547 if (cap->running_task != NULL) {
548 debugTrace(DEBUG_sched,
549 "capability %d is owned by another task", cap->no);
550 RELEASE_LOCK(&cap->lock);
554 if (task->tso == NULL) {
555 ASSERT(cap->spare_workers != NULL);
556 // if we're not at the front of the queue, release it
557 // again. This is unlikely to happen.
558 if (cap->spare_workers != task) {
559 giveCapabilityToTask(cap,cap->spare_workers);
560 RELEASE_LOCK(&cap->lock);
563 cap->spare_workers = task->next;
566 cap->running_task = task;
567 RELEASE_LOCK(&cap->lock);
571 trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
572 ASSERT(cap->running_task == task);
576 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
581 /* ----------------------------------------------------------------------------
582 * Wake up a thread on a Capability.
584 * This is used when the current Task is running on a Capability and
585 * wishes to wake up a thread on a different Capability.
586 * ------------------------------------------------------------------------- */
589 wakeupThreadOnCapability (Capability *my_cap,
590 Capability *other_cap,
593 ACQUIRE_LOCK(&other_cap->lock);
595 // ASSUMES: cap->lock is held (asserted in wakeupThreadOnCapability)
597 ASSERT(tso->bound->cap == tso->cap);
598 tso->bound->cap = other_cap;
600 tso->cap = other_cap;
602 ASSERT(tso->bound ? tso->bound->cap == other_cap : 1);
604 if (other_cap->running_task == NULL) {
605 // nobody is running this Capability, we can add our thread
606 // directly onto the run queue and start up a Task to run it.
608 other_cap->running_task = myTask();
609 // precond for releaseCapability_() and appendToRunQueue()
611 appendToRunQueue(other_cap,tso);
613 trace(TRACE_sched, "resuming capability %d", other_cap->no);
614 releaseCapability_(other_cap,rtsFalse);
616 appendToWakeupQueue(my_cap,other_cap,tso);
617 other_cap->context_switch = 1;
618 // someone is running on this Capability, so it cannot be
619 // freed without first checking the wakeup queue (see
620 // releaseCapability_).
623 RELEASE_LOCK(&other_cap->lock);
626 /* ----------------------------------------------------------------------------
629 * Used to indicate that the interrupted flag is now set, or some
630 * other global condition that might require waking up a Task on each
632 * ------------------------------------------------------------------------- */
635 prodCapabilities(rtsBool all)
641 for (i=0; i < n_capabilities; i++) {
642 cap = &capabilities[i];
643 ACQUIRE_LOCK(&cap->lock);
644 if (!cap->running_task) {
645 if (cap->spare_workers) {
646 trace(TRACE_sched, "resuming capability %d", cap->no);
647 task = cap->spare_workers;
648 ASSERT(!task->stopped);
649 giveCapabilityToTask(cap,task);
651 RELEASE_LOCK(&cap->lock);
656 RELEASE_LOCK(&cap->lock);
662 prodAllCapabilities (void)
664 prodCapabilities(rtsTrue);
667 /* ----------------------------------------------------------------------------
670 * Like prodAllCapabilities, but we only require a single Task to wake
671 * up in order to service some global event, such as checking for
672 * deadlock after some idle time has passed.
673 * ------------------------------------------------------------------------- */
676 prodOneCapability (void)
678 prodCapabilities(rtsFalse);
681 /* ----------------------------------------------------------------------------
684 * At shutdown time, we want to let everything exit as cleanly as
685 * possible. For each capability, we let its run queue drain, and
686 * allow the workers to stop.
688 * This function should be called when interrupted and
689 * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
690 * will exit the scheduler and call taskStop(), and any bound thread
691 * that wakes up will return to its caller. Runnable threads are
694 * ------------------------------------------------------------------------- */
697 shutdownCapability (Capability *cap, Task *task, rtsBool safe)
701 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
705 // Loop indefinitely until all the workers have exited and there
706 // are no Haskell threads left. We used to bail out after 50
707 // iterations of this loop, but that occasionally left a worker
708 // running which caused problems later (the closeMutex() below
709 // isn't safe, for one thing).
711 for (i = 0; /* i < 50 */; i++) {
712 debugTrace(DEBUG_sched,
713 "shutting down capability %d, attempt %d", cap->no, i);
714 ACQUIRE_LOCK(&cap->lock);
715 if (cap->running_task) {
716 RELEASE_LOCK(&cap->lock);
717 debugTrace(DEBUG_sched, "not owner, yielding");
721 cap->running_task = task;
723 if (cap->spare_workers) {
724 // Look for workers that have died without removing
725 // themselves from the list; this could happen if the OS
726 // summarily killed the thread, for example. This
727 // actually happens on Windows when the system is
728 // terminating the program, and the RTS is running in a
732 for (t = cap->spare_workers; t != NULL; t = t->next) {
733 if (!osThreadIsAlive(t->id)) {
734 debugTrace(DEBUG_sched,
735 "worker thread %p has died unexpectedly", (void *)t->id);
737 cap->spare_workers = t->next;
739 prev->next = t->next;
746 if (!emptyRunQueue(cap) || cap->spare_workers) {
747 debugTrace(DEBUG_sched,
748 "runnable threads or workers still alive, yielding");
749 releaseCapability_(cap,rtsFalse); // this will wake up a worker
750 RELEASE_LOCK(&cap->lock);
755 // If "safe", then busy-wait for any threads currently doing
756 // foreign calls. If we're about to unload this DLL, for
757 // example, we need to be sure that there are no OS threads
758 // that will try to return to code that has been unloaded.
759 // We can be a bit more relaxed when this is a standalone
760 // program that is about to terminate, and let safe=false.
761 if (cap->suspended_ccalling_tasks && safe) {
762 debugTrace(DEBUG_sched,
763 "thread(s) are involved in foreign calls, yielding");
764 cap->running_task = NULL;
765 RELEASE_LOCK(&cap->lock);
770 debugTrace(DEBUG_sched, "capability %d is stopped.", cap->no);
772 RELEASE_LOCK(&cap->lock);
775 // we now have the Capability, its run queue and spare workers
776 // list are both empty.
778 // ToDo: we can't drop this mutex, because there might still be
779 // threads performing foreign calls that will eventually try to
780 // return via resumeThread() and attempt to grab cap->lock.
781 // closeMutex(&cap->lock);
784 /* ----------------------------------------------------------------------------
787 * Attempt to gain control of a Capability if it is free.
789 * ------------------------------------------------------------------------- */
792 tryGrabCapability (Capability *cap, Task *task)
794 if (cap->running_task != NULL) return rtsFalse;
795 ACQUIRE_LOCK(&cap->lock);
796 if (cap->running_task != NULL) {
797 RELEASE_LOCK(&cap->lock);
801 cap->running_task = task;
802 RELEASE_LOCK(&cap->lock);
807 #endif /* THREADED_RTS */
810 freeCapability (Capability *cap) {
811 stgFree(cap->mut_lists);
812 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
813 freeSparkPool(cap->sparks);
817 /* ---------------------------------------------------------------------------
818 Mark everything directly reachable from the Capabilities. When
819 using multiple GC threads, each GC thread marks all Capabilities
820 for which (c `mod` n == 0), for Capability c and thread n.
821 ------------------------------------------------------------------------ */
824 markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta,
825 rtsBool prune_sparks USED_IF_THREADS)
831 // Each GC thread is responsible for following roots from the
832 // Capability of the same number. There will usually be the same
833 // or fewer Capabilities as GC threads, but just in case there
834 // are more, we mark every Capability whose number is the GC
835 // thread's index plus a multiple of the number of GC threads.
836 for (i = i0; i < n_capabilities; i += delta) {
837 cap = &capabilities[i];
838 evac(user, (StgClosure **)(void *)&cap->run_queue_hd);
839 evac(user, (StgClosure **)(void *)&cap->run_queue_tl);
840 #if defined(THREADED_RTS)
841 evac(user, (StgClosure **)(void *)&cap->wakeup_queue_hd);
842 evac(user, (StgClosure **)(void *)&cap->wakeup_queue_tl);
844 for (task = cap->suspended_ccalling_tasks; task != NULL;
846 debugTrace(DEBUG_sched,
847 "evac'ing suspended TSO %lu", (unsigned long)task->suspended_tso->id);
848 evac(user, (StgClosure **)(void *)&task->suspended_tso);
851 #if defined(THREADED_RTS)
853 pruneSparkQueue (evac, user, cap);
855 traverseSparkQueue (evac, user, cap);
860 #if !defined(THREADED_RTS)
861 evac(user, (StgClosure **)(void *)&blocked_queue_hd);
862 evac(user, (StgClosure **)(void *)&blocked_queue_tl);
863 evac(user, (StgClosure **)(void *)&sleeping_queue);
868 markCapabilities (evac_fn evac, void *user)
870 markSomeCapabilities(evac, user, 0, 1, rtsFalse);