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 anyWorkForMe( Capability *cap, Task *task )
60 if (task->tso != NULL) {
61 // A bound task only runs if its thread is on the run queue of
62 // the capability on which it was woken up. Otherwise, we
63 // can't be sure that we have the right capability: the thread
64 // might be woken up on some other capability, and task->cap
65 // could change under our feet.
66 return !emptyRunQueue(cap) && cap->run_queue_hd->bound == task;
68 // A vanilla worker task runs if either there is a lightweight
69 // thread at the head of the run queue, or the run queue is
70 // empty and (there are sparks to execute, or there is some
71 // other global condition to check, such as threads blocked on
73 if (emptyRunQueue(cap)) {
74 return !emptySparkPoolCap(cap)
75 || !emptyWakeupQueue(cap)
78 return cap->run_queue_hd->bound == NULL;
83 /* -----------------------------------------------------------------------------
84 * Manage the returning_tasks lists.
86 * These functions require cap->lock
87 * -------------------------------------------------------------------------- */
89 #if defined(THREADED_RTS)
91 newReturningTask (Capability *cap, Task *task)
93 ASSERT_LOCK_HELD(&cap->lock);
94 ASSERT(task->return_link == NULL);
95 if (cap->returning_tasks_hd) {
96 ASSERT(cap->returning_tasks_tl->return_link == NULL);
97 cap->returning_tasks_tl->return_link = task;
99 cap->returning_tasks_hd = task;
101 cap->returning_tasks_tl = task;
105 popReturningTask (Capability *cap)
107 ASSERT_LOCK_HELD(&cap->lock);
109 task = cap->returning_tasks_hd;
111 cap->returning_tasks_hd = task->return_link;
112 if (!cap->returning_tasks_hd) {
113 cap->returning_tasks_tl = NULL;
115 task->return_link = NULL;
120 /* ----------------------------------------------------------------------------
123 * The Capability is initially marked not free.
124 * ------------------------------------------------------------------------- */
127 initCapability( Capability *cap, nat i )
132 cap->in_haskell = rtsFalse;
134 cap->run_queue_hd = END_TSO_QUEUE;
135 cap->run_queue_tl = END_TSO_QUEUE;
137 #if defined(THREADED_RTS)
138 initMutex(&cap->lock);
139 cap->running_task = NULL; // indicates cap is free
140 cap->spare_workers = NULL;
141 cap->suspended_ccalling_tasks = NULL;
142 cap->returning_tasks_hd = NULL;
143 cap->returning_tasks_tl = NULL;
144 cap->wakeup_queue_hd = END_TSO_QUEUE;
145 cap->wakeup_queue_tl = END_TSO_QUEUE;
148 cap->f.stgGCEnter1 = (F_)__stg_gc_enter_1;
149 cap->f.stgGCFun = (F_)__stg_gc_fun;
151 cap->mut_lists = stgMallocBytes(sizeof(bdescr *) *
152 RtsFlags.GcFlags.generations,
155 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
156 cap->mut_lists[g] = NULL;
159 cap->free_tvar_watch_queues = END_STM_WATCH_QUEUE;
160 cap->free_invariant_check_queues = END_INVARIANT_CHECK_QUEUE;
161 cap->free_trec_chunks = END_STM_CHUNK_LIST;
162 cap->free_trec_headers = NO_TREC;
163 cap->transaction_tokens = 0;
166 /* ---------------------------------------------------------------------------
167 * Function: initCapabilities()
169 * Purpose: set up the Capability handling. For the THREADED_RTS build,
170 * we keep a table of them, the size of which is
171 * controlled by the user via the RTS flag -N.
173 * ------------------------------------------------------------------------- */
175 initCapabilities( void )
177 #if defined(THREADED_RTS)
181 // We can't support multiple CPUs if BaseReg is not a register
182 if (RtsFlags.ParFlags.nNodes > 1) {
183 errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
184 RtsFlags.ParFlags.nNodes = 1;
188 n_capabilities = RtsFlags.ParFlags.nNodes;
190 if (n_capabilities == 1) {
191 capabilities = &MainCapability;
192 // THREADED_RTS must work on builds that don't have a mutable
193 // BaseReg (eg. unregisterised), so in this case
194 // capabilities[0] must coincide with &MainCapability.
196 capabilities = stgMallocBytes(n_capabilities * sizeof(Capability),
200 for (i = 0; i < n_capabilities; i++) {
201 initCapability(&capabilities[i], i);
204 debugTrace(DEBUG_sched, "allocated %d capabilities", n_capabilities);
206 #else /* !THREADED_RTS */
209 capabilities = &MainCapability;
210 initCapability(&MainCapability, 0);
214 // There are no free capabilities to begin with. We will start
215 // a worker Task to each Capability, which will quickly put the
216 // Capability on the free list when it finds nothing to do.
217 last_free_capability = &capabilities[0];
220 /* ----------------------------------------------------------------------------
221 * Give a Capability to a Task. The task must currently be sleeping
222 * on its condition variable.
224 * Requires cap->lock (modifies cap->running_task).
226 * When migrating a Task, the migrater must take task->lock before
227 * modifying task->cap, to synchronise with the waking up Task.
228 * Additionally, the migrater should own the Capability (when
229 * migrating the run queue), or cap->lock (when migrating
230 * returning_workers).
232 * ------------------------------------------------------------------------- */
234 #if defined(THREADED_RTS)
236 giveCapabilityToTask (Capability *cap USED_IF_DEBUG, Task *task)
238 ASSERT_LOCK_HELD(&cap->lock);
239 ASSERT(task->cap == cap);
240 trace(TRACE_sched | DEBUG_sched,
241 "passing capability %d to %s %p",
242 cap->no, task->tso ? "bound task" : "worker",
244 ACQUIRE_LOCK(&task->lock);
245 task->wakeup = rtsTrue;
246 // the wakeup flag is needed because signalCondition() doesn't
247 // flag the condition if the thread is already runniing, but we want
249 signalCondition(&task->cond);
250 RELEASE_LOCK(&task->lock);
254 /* ----------------------------------------------------------------------------
255 * Function: releaseCapability(Capability*)
257 * Purpose: Letting go of a capability. Causes a
258 * 'returning worker' thread or a 'waiting worker'
259 * to wake up, in that order.
260 * ------------------------------------------------------------------------- */
262 #if defined(THREADED_RTS)
264 releaseCapability_ (Capability* cap)
268 task = cap->running_task;
270 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task);
272 cap->running_task = NULL;
274 // Check to see whether a worker thread can be given
275 // the go-ahead to return the result of an external call..
276 if (cap->returning_tasks_hd != NULL) {
277 giveCapabilityToTask(cap,cap->returning_tasks_hd);
278 // The Task pops itself from the queue (see waitForReturnCapability())
282 /* if waiting_for_gc was the reason to release the cap: thread
283 comes from yieldCap->releaseAndQueueWorker. Unconditionally set
284 cap. free and return (see default after the if-protected other
285 special cases). Thread will wait on cond.var and re-acquire the
286 same cap after GC (GC-triggering cap. calls releaseCap and
287 enters the spare_workers case)
289 if (waiting_for_gc) {
290 last_free_capability = cap; // needed?
291 trace(TRACE_sched | DEBUG_sched,
292 "GC pending, set capability %d free", cap->no);
297 // If the next thread on the run queue is a bound thread,
298 // give this Capability to the appropriate Task.
299 if (!emptyRunQueue(cap) && cap->run_queue_hd->bound) {
300 // Make sure we're not about to try to wake ourselves up
301 ASSERT(task != cap->run_queue_hd->bound);
302 task = cap->run_queue_hd->bound;
303 giveCapabilityToTask(cap,task);
307 if (!cap->spare_workers) {
308 // Create a worker thread if we don't have one. If the system
309 // is interrupted, we only create a worker task if there
310 // are threads that need to be completed. If the system is
311 // shutting down, we never create a new worker.
312 if (sched_state < SCHED_SHUTTING_DOWN || !emptyRunQueue(cap)) {
313 debugTrace(DEBUG_sched,
314 "starting new worker on capability %d", cap->no);
315 startWorkerTask(cap, workerStart);
320 // If we have an unbound thread on the run queue, or if there's
321 // anything else to do, give the Capability to a worker thread.
322 if (!emptyRunQueue(cap) || !emptyWakeupQueue(cap)
323 || !emptySparkPoolCap(cap) || globalWorkToDo()) {
324 if (cap->spare_workers) {
325 giveCapabilityToTask(cap,cap->spare_workers);
326 // The worker Task pops itself from the queue;
331 last_free_capability = cap;
332 trace(TRACE_sched | DEBUG_sched, "freeing capability %d", cap->no);
336 releaseCapability (Capability* cap USED_IF_THREADS)
338 ACQUIRE_LOCK(&cap->lock);
339 releaseCapability_(cap);
340 RELEASE_LOCK(&cap->lock);
344 releaseCapabilityAndQueueWorker (Capability* cap USED_IF_THREADS)
348 ACQUIRE_LOCK(&cap->lock);
350 task = cap->running_task;
352 // If the current task is a worker, save it on the spare_workers
353 // list of this Capability. A worker can mark itself as stopped,
354 // in which case it is not replaced on the spare_worker queue.
355 // This happens when the system is shutting down (see
356 // Schedule.c:workerStart()).
357 // Also, be careful to check that this task hasn't just exited
358 // Haskell to do a foreign call (task->suspended_tso).
359 if (!isBoundTask(task) && !task->stopped && !task->suspended_tso) {
360 task->next = cap->spare_workers;
361 cap->spare_workers = task;
363 // Bound tasks just float around attached to their TSOs.
365 releaseCapability_(cap);
367 RELEASE_LOCK(&cap->lock);
371 /* ----------------------------------------------------------------------------
372 * waitForReturnCapability( Task *task )
374 * Purpose: when an OS thread returns from an external call,
375 * it calls waitForReturnCapability() (via Schedule.resumeThread())
376 * to wait for permission to enter the RTS & communicate the
377 * result of the external call back to the Haskell thread that
380 * ------------------------------------------------------------------------- */
382 waitForReturnCapability (Capability **pCap, Task *task)
384 #if !defined(THREADED_RTS)
386 MainCapability.running_task = task;
387 task->cap = &MainCapability;
388 *pCap = &MainCapability;
391 Capability *cap = *pCap;
394 // Try last_free_capability first
395 cap = last_free_capability;
396 if (!cap->running_task) {
398 // otherwise, search for a free capability
399 for (i = 0; i < n_capabilities; i++) {
400 cap = &capabilities[i];
401 if (!cap->running_task) {
405 // Can't find a free one, use last_free_capability.
406 cap = last_free_capability;
409 // record the Capability as the one this Task is now assocated with.
413 ASSERT(task->cap == cap);
416 ACQUIRE_LOCK(&cap->lock);
418 debugTrace(DEBUG_sched, "returning; I want capability %d", cap->no);
420 if (!cap->running_task) {
421 // It's free; just grab it
422 cap->running_task = task;
423 RELEASE_LOCK(&cap->lock);
425 newReturningTask(cap,task);
426 RELEASE_LOCK(&cap->lock);
429 ACQUIRE_LOCK(&task->lock);
430 // task->lock held, cap->lock not held
431 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
433 task->wakeup = rtsFalse;
434 RELEASE_LOCK(&task->lock);
436 // now check whether we should wake up...
437 ACQUIRE_LOCK(&cap->lock);
438 if (cap->running_task == NULL) {
439 if (cap->returning_tasks_hd != task) {
440 giveCapabilityToTask(cap,cap->returning_tasks_hd);
441 RELEASE_LOCK(&cap->lock);
444 cap->running_task = task;
445 popReturningTask(cap);
446 RELEASE_LOCK(&cap->lock);
449 RELEASE_LOCK(&cap->lock);
454 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
456 trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
462 #if defined(THREADED_RTS)
463 /* ----------------------------------------------------------------------------
465 * ------------------------------------------------------------------------- */
468 yieldCapability (Capability** pCap, Task *task)
470 Capability *cap = *pCap;
472 // The fast path has no locking, if we don't enter this while loop
474 while ( waiting_for_gc
475 /* i.e. another capability triggered HeapOverflow, is busy
476 getting capabilities (stopping their owning tasks) */
477 || cap->returning_tasks_hd != NULL
478 /* cap reserved for another task */
479 || !anyWorkForMe(cap,task)
480 /* cap/task have no work */
482 debugTrace(DEBUG_sched, "giving up capability %d", cap->no);
484 // We must now release the capability and wait to be woken up
486 task->wakeup = rtsFalse;
487 releaseCapabilityAndQueueWorker(cap);
490 ACQUIRE_LOCK(&task->lock);
491 // task->lock held, cap->lock not held
492 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
494 task->wakeup = rtsFalse;
495 RELEASE_LOCK(&task->lock);
497 debugTrace(DEBUG_sched, "woken up on capability %d", cap->no);
499 ACQUIRE_LOCK(&cap->lock);
500 if (cap->running_task != NULL) {
501 debugTrace(DEBUG_sched,
502 "capability %d is owned by another task", cap->no);
503 RELEASE_LOCK(&cap->lock);
507 if (task->tso == NULL) {
508 ASSERT(cap->spare_workers != NULL);
509 // if we're not at the front of the queue, release it
510 // again. This is unlikely to happen.
511 if (cap->spare_workers != task) {
512 giveCapabilityToTask(cap,cap->spare_workers);
513 RELEASE_LOCK(&cap->lock);
516 cap->spare_workers = task->next;
519 cap->running_task = task;
520 RELEASE_LOCK(&cap->lock);
524 trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
525 ASSERT(cap->running_task == task);
530 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
535 /* ----------------------------------------------------------------------------
536 * Wake up a thread on a Capability.
538 * This is used when the current Task is running on a Capability and
539 * wishes to wake up a thread on a different Capability.
540 * ------------------------------------------------------------------------- */
543 wakeupThreadOnCapability (Capability *my_cap,
544 Capability *other_cap,
547 ACQUIRE_LOCK(&other_cap->lock);
549 // ASSUMES: cap->lock is held (asserted in wakeupThreadOnCapability)
551 ASSERT(tso->bound->cap == tso->cap);
552 tso->bound->cap = other_cap;
554 tso->cap = other_cap;
556 ASSERT(tso->bound ? tso->bound->cap == other_cap : 1);
558 if (other_cap->running_task == NULL) {
559 // nobody is running this Capability, we can add our thread
560 // directly onto the run queue and start up a Task to run it.
562 other_cap->running_task = myTask();
563 // precond for releaseCapability_() and appendToRunQueue()
565 appendToRunQueue(other_cap,tso);
567 trace(TRACE_sched, "resuming capability %d", other_cap->no);
568 releaseCapability_(other_cap);
570 appendToWakeupQueue(my_cap,other_cap,tso);
571 // someone is running on this Capability, so it cannot be
572 // freed without first checking the wakeup queue (see
573 // releaseCapability_).
576 RELEASE_LOCK(&other_cap->lock);
579 /* ----------------------------------------------------------------------------
582 * Used to indicate that the interrupted flag is now set, or some
583 * other global condition that might require waking up a Task on each
585 * ------------------------------------------------------------------------- */
588 prodCapabilities(rtsBool all)
594 for (i=0; i < n_capabilities; i++) {
595 cap = &capabilities[i];
596 ACQUIRE_LOCK(&cap->lock);
597 if (!cap->running_task) {
598 if (cap->spare_workers) {
599 trace(TRACE_sched, "resuming capability %d", cap->no);
600 task = cap->spare_workers;
601 ASSERT(!task->stopped);
602 giveCapabilityToTask(cap,task);
604 RELEASE_LOCK(&cap->lock);
609 RELEASE_LOCK(&cap->lock);
615 prodAllCapabilities (void)
617 prodCapabilities(rtsTrue);
620 /* ----------------------------------------------------------------------------
623 * Like prodAllCapabilities, but we only require a single Task to wake
624 * up in order to service some global event, such as checking for
625 * deadlock after some idle time has passed.
626 * ------------------------------------------------------------------------- */
629 prodOneCapability (void)
631 prodCapabilities(rtsFalse);
634 /* ----------------------------------------------------------------------------
637 * At shutdown time, we want to let everything exit as cleanly as
638 * possible. For each capability, we let its run queue drain, and
639 * allow the workers to stop.
641 * This function should be called when interrupted and
642 * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
643 * will exit the scheduler and call taskStop(), and any bound thread
644 * that wakes up will return to its caller. Runnable threads are
647 * ------------------------------------------------------------------------- */
650 shutdownCapability (Capability *cap, Task *task, rtsBool safe)
654 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
658 // Loop indefinitely until all the workers have exited and there
659 // are no Haskell threads left. We used to bail out after 50
660 // iterations of this loop, but that occasionally left a worker
661 // running which caused problems later (the closeMutex() below
662 // isn't safe, for one thing).
664 for (i = 0; /* i < 50 */; i++) {
665 debugTrace(DEBUG_sched,
666 "shutting down capability %d, attempt %d", cap->no, i);
667 ACQUIRE_LOCK(&cap->lock);
668 if (cap->running_task) {
669 RELEASE_LOCK(&cap->lock);
670 debugTrace(DEBUG_sched, "not owner, yielding");
674 cap->running_task = task;
676 if (cap->spare_workers) {
677 // Look for workers that have died without removing
678 // themselves from the list; this could happen if the OS
679 // summarily killed the thread, for example. This
680 // actually happens on Windows when the system is
681 // terminating the program, and the RTS is running in a
685 for (t = cap->spare_workers; t != NULL; t = t->next) {
686 if (!osThreadIsAlive(t->id)) {
687 debugTrace(DEBUG_sched,
688 "worker thread %p has died unexpectedly", (void *)t->id);
690 cap->spare_workers = t->next;
692 prev->next = t->next;
699 if (!emptyRunQueue(cap) || cap->spare_workers) {
700 debugTrace(DEBUG_sched,
701 "runnable threads or workers still alive, yielding");
702 releaseCapability_(cap); // this will wake up a worker
703 RELEASE_LOCK(&cap->lock);
708 // If "safe", then busy-wait for any threads currently doing
709 // foreign calls. If we're about to unload this DLL, for
710 // example, we need to be sure that there are no OS threads
711 // that will try to return to code that has been unloaded.
712 // We can be a bit more relaxed when this is a standalone
713 // program that is about to terminate, and let safe=false.
714 if (cap->suspended_ccalling_tasks && safe) {
715 debugTrace(DEBUG_sched,
716 "thread(s) are involved in foreign calls, yielding");
717 cap->running_task = NULL;
718 RELEASE_LOCK(&cap->lock);
723 debugTrace(DEBUG_sched, "capability %d is stopped.", cap->no);
725 RELEASE_LOCK(&cap->lock);
728 // we now have the Capability, its run queue and spare workers
729 // list are both empty.
731 // ToDo: we can't drop this mutex, because there might still be
732 // threads performing foreign calls that will eventually try to
733 // return via resumeThread() and attempt to grab cap->lock.
734 // closeMutex(&cap->lock);
737 /* ----------------------------------------------------------------------------
740 * Attempt to gain control of a Capability if it is free.
742 * ------------------------------------------------------------------------- */
745 tryGrabCapability (Capability *cap, Task *task)
747 if (cap->running_task != NULL) return rtsFalse;
748 ACQUIRE_LOCK(&cap->lock);
749 if (cap->running_task != NULL) {
750 RELEASE_LOCK(&cap->lock);
754 cap->running_task = task;
755 RELEASE_LOCK(&cap->lock);
760 #endif /* THREADED_RTS */
763 freeCapability (Capability *cap) {
764 stgFree(cap->mut_lists);
765 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
766 freeSparkPool(&cap->r.rSparks);
770 /* ---------------------------------------------------------------------------
771 Mark everything directly reachable from the Capabilities. When
772 using multiple GC threads, each GC thread marks all Capabilities
773 for which (c `mod` n == 0), for Capability c and thread n.
774 ------------------------------------------------------------------------ */
777 markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta)
783 // Each GC thread is responsible for following roots from the
784 // Capability of the same number. There will usually be the same
785 // or fewer Capabilities as GC threads, but just in case there
786 // are more, we mark every Capability whose number is the GC
787 // thread's index plus a multiple of the number of GC threads.
788 for (i = i0; i < n_capabilities; i += delta) {
789 cap = &capabilities[i];
790 evac(user, (StgClosure **)(void *)&cap->run_queue_hd);
791 evac(user, (StgClosure **)(void *)&cap->run_queue_tl);
792 #if defined(THREADED_RTS)
793 evac(user, (StgClosure **)(void *)&cap->wakeup_queue_hd);
794 evac(user, (StgClosure **)(void *)&cap->wakeup_queue_tl);
796 for (task = cap->suspended_ccalling_tasks; task != NULL;
798 debugTrace(DEBUG_sched,
799 "evac'ing suspended TSO %lu", (unsigned long)task->suspended_tso->id);
800 evac(user, (StgClosure **)(void *)&task->suspended_tso);
803 #if defined(THREADED_RTS)
804 traverseSparkQueue (evac, user, cap);
808 #if !defined(THREADED_RTS)
809 evac(user, (StgClosure **)(void *)&blocked_queue_hd);
810 evac(user, (StgClosure **)(void *)&blocked_queue_tl);
811 evac(user, (StgClosure **)(void *)&sleeping_queue);
815 // This function is used by the compacting GC to thread all the
816 // pointers from spark queues.
818 traverseSparkQueues (evac_fn evac USED_IF_THREADS, void *user USED_IF_THREADS)
820 #if defined(THREADED_RTS)
822 for (i = 0; i < n_capabilities; i++) {
823 traverseSparkQueue (evac, user, &capabilities[i]);
825 #endif // THREADED_RTS
830 markCapabilities (evac_fn evac, void *user)
832 markSomeCapabilities(evac, user, 0, 1);