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"
31 // one global capability, this is the Capability for non-threaded
32 // builds, and for +RTS -N1
33 Capability MainCapability;
36 Capability *capabilities = NULL;
38 // Holds the Capability which last became free. This is used so that
39 // an in-call has a chance of quickly finding a free Capability.
40 // Maintaining a global free list of Capabilities would require global
41 // locking, so we don't do that.
42 Capability *last_free_capability;
44 /* GC indicator, in scope for the scheduler, init'ed to false */
45 volatile StgWord waiting_for_gc = 0;
47 #if defined(THREADED_RTS)
51 return blackholes_need_checking
52 || sched_state >= SCHED_INTERRUPTING
57 #if defined(THREADED_RTS)
59 findSpark (Capability *cap)
66 if (!emptyRunQueue(cap)) {
67 // If there are other threads, don't try to run any new
68 // sparks: sparks might be speculative, we don't want to take
69 // resources away from the main computation.
73 // first try to get a spark from our own pool.
74 // We should be using reclaimSpark(), because it works without
75 // needing any atomic instructions:
76 // spark = reclaimSpark(cap->sparks);
77 // However, measurements show that this makes at least one benchmark
78 // slower (prsa) and doesn't affect the others.
79 spark = tryStealSpark(cap);
81 cap->sparks_converted++;
85 if (n_capabilities == 1) { return NULL; } // makes no sense...
87 debugTrace(DEBUG_sched,
88 "cap %d: Trying to steal work from other capabilities",
94 /* visit cap.s 0..n-1 in sequence until a theft succeeds. We could
95 start at a random place instead of 0 as well. */
96 for ( i=0 ; i < n_capabilities ; i++ ) {
97 robbed = &capabilities[i];
98 if (cap == robbed) // ourselves...
101 if (emptySparkPoolCap(robbed)) // nothing to steal here
104 spark = tryStealSpark(robbed);
105 if (spark == NULL && !emptySparkPoolCap(robbed)) {
106 // we conflicted with another thread while trying to steal;
112 debugTrace(DEBUG_sched,
113 "cap %d: Stole a spark from capability %d",
114 cap->no, robbed->no);
115 cap->sparks_converted++;
118 // otherwise: no success, try next one
122 debugTrace(DEBUG_sched, "No sparks stolen");
126 // Returns True if any spark pool is non-empty at this moment in time
127 // The result is only valid for an instant, of course, so in a sense
128 // is immediately invalid, and should not be relied upon for
135 for (i=0; i < n_capabilities; i++) {
136 if (!emptySparkPoolCap(&capabilities[i])) {
144 /* -----------------------------------------------------------------------------
145 * Manage the returning_tasks lists.
147 * These functions require cap->lock
148 * -------------------------------------------------------------------------- */
150 #if defined(THREADED_RTS)
152 newReturningTask (Capability *cap, Task *task)
154 ASSERT_LOCK_HELD(&cap->lock);
155 ASSERT(task->return_link == NULL);
156 if (cap->returning_tasks_hd) {
157 ASSERT(cap->returning_tasks_tl->return_link == NULL);
158 cap->returning_tasks_tl->return_link = task;
160 cap->returning_tasks_hd = task;
162 cap->returning_tasks_tl = task;
166 popReturningTask (Capability *cap)
168 ASSERT_LOCK_HELD(&cap->lock);
170 task = cap->returning_tasks_hd;
172 cap->returning_tasks_hd = task->return_link;
173 if (!cap->returning_tasks_hd) {
174 cap->returning_tasks_tl = NULL;
176 task->return_link = NULL;
181 /* ----------------------------------------------------------------------------
184 * The Capability is initially marked not free.
185 * ------------------------------------------------------------------------- */
188 initCapability( Capability *cap, nat i )
193 cap->in_haskell = rtsFalse;
194 cap->in_gc = rtsFalse;
196 cap->run_queue_hd = END_TSO_QUEUE;
197 cap->run_queue_tl = END_TSO_QUEUE;
199 #if defined(THREADED_RTS)
200 initMutex(&cap->lock);
201 cap->running_task = NULL; // indicates cap is free
202 cap->spare_workers = NULL;
203 cap->suspended_ccalling_tasks = NULL;
204 cap->returning_tasks_hd = NULL;
205 cap->returning_tasks_tl = NULL;
206 cap->wakeup_queue_hd = END_TSO_QUEUE;
207 cap->wakeup_queue_tl = END_TSO_QUEUE;
208 cap->sparks_created = 0;
209 cap->sparks_converted = 0;
210 cap->sparks_pruned = 0;
213 cap->f.stgEagerBlackholeInfo = (W_)&__stg_EAGER_BLACKHOLE_info;
214 cap->f.stgGCEnter1 = (F_)__stg_gc_enter_1;
215 cap->f.stgGCFun = (F_)__stg_gc_fun;
217 cap->mut_lists = stgMallocBytes(sizeof(bdescr *) *
218 RtsFlags.GcFlags.generations,
220 cap->saved_mut_lists = stgMallocBytes(sizeof(bdescr *) *
221 RtsFlags.GcFlags.generations,
224 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
225 cap->mut_lists[g] = NULL;
228 cap->free_tvar_watch_queues = END_STM_WATCH_QUEUE;
229 cap->free_invariant_check_queues = END_INVARIANT_CHECK_QUEUE;
230 cap->free_trec_chunks = END_STM_CHUNK_LIST;
231 cap->free_trec_headers = NO_TREC;
232 cap->transaction_tokens = 0;
233 cap->context_switch = 0;
236 /* ---------------------------------------------------------------------------
237 * Function: initCapabilities()
239 * Purpose: set up the Capability handling. For the THREADED_RTS build,
240 * we keep a table of them, the size of which is
241 * controlled by the user via the RTS flag -N.
243 * ------------------------------------------------------------------------- */
245 initCapabilities( void )
247 #if defined(THREADED_RTS)
251 // We can't support multiple CPUs if BaseReg is not a register
252 if (RtsFlags.ParFlags.nNodes > 1) {
253 errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
254 RtsFlags.ParFlags.nNodes = 1;
258 n_capabilities = RtsFlags.ParFlags.nNodes;
260 if (n_capabilities == 1) {
261 capabilities = &MainCapability;
262 // THREADED_RTS must work on builds that don't have a mutable
263 // BaseReg (eg. unregisterised), so in this case
264 // capabilities[0] must coincide with &MainCapability.
266 capabilities = stgMallocBytes(n_capabilities * sizeof(Capability),
270 for (i = 0; i < n_capabilities; i++) {
271 initCapability(&capabilities[i], i);
274 debugTrace(DEBUG_sched, "allocated %d capabilities", n_capabilities);
276 #else /* !THREADED_RTS */
279 capabilities = &MainCapability;
280 initCapability(&MainCapability, 0);
284 // There are no free capabilities to begin with. We will start
285 // a worker Task to each Capability, which will quickly put the
286 // Capability on the free list when it finds nothing to do.
287 last_free_capability = &capabilities[0];
290 /* ----------------------------------------------------------------------------
291 * setContextSwitches: cause all capabilities to context switch as
293 * ------------------------------------------------------------------------- */
295 void setContextSwitches(void)
298 for (i=0; i < n_capabilities; i++) {
299 contextSwitchCapability(&capabilities[i]);
303 /* ----------------------------------------------------------------------------
304 * Give a Capability to a Task. The task must currently be sleeping
305 * on its condition variable.
307 * Requires cap->lock (modifies cap->running_task).
309 * When migrating a Task, the migrater must take task->lock before
310 * modifying task->cap, to synchronise with the waking up Task.
311 * Additionally, the migrater should own the Capability (when
312 * migrating the run queue), or cap->lock (when migrating
313 * returning_workers).
315 * ------------------------------------------------------------------------- */
317 #if defined(THREADED_RTS)
319 giveCapabilityToTask (Capability *cap USED_IF_DEBUG, Task *task)
321 ASSERT_LOCK_HELD(&cap->lock);
322 ASSERT(task->cap == cap);
323 trace(TRACE_sched | DEBUG_sched,
324 "passing capability %d to %s %p",
325 cap->no, task->tso ? "bound task" : "worker",
327 ACQUIRE_LOCK(&task->lock);
328 task->wakeup = rtsTrue;
329 // the wakeup flag is needed because signalCondition() doesn't
330 // flag the condition if the thread is already runniing, but we want
332 signalCondition(&task->cond);
333 RELEASE_LOCK(&task->lock);
337 /* ----------------------------------------------------------------------------
338 * Function: releaseCapability(Capability*)
340 * Purpose: Letting go of a capability. Causes a
341 * 'returning worker' thread or a 'waiting worker'
342 * to wake up, in that order.
343 * ------------------------------------------------------------------------- */
345 #if defined(THREADED_RTS)
347 releaseCapability_ (Capability* cap,
348 rtsBool always_wakeup)
352 task = cap->running_task;
354 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task);
356 cap->running_task = NULL;
358 // Check to see whether a worker thread can be given
359 // the go-ahead to return the result of an external call..
360 if (cap->returning_tasks_hd != NULL) {
361 giveCapabilityToTask(cap,cap->returning_tasks_hd);
362 // The Task pops itself from the queue (see waitForReturnCapability())
366 if (waiting_for_gc == PENDING_GC_SEQ) {
367 last_free_capability = cap; // needed?
368 trace(TRACE_sched | DEBUG_sched,
369 "GC pending, set capability %d free", cap->no);
374 // If the next thread on the run queue is a bound thread,
375 // give this Capability to the appropriate Task.
376 if (!emptyRunQueue(cap) && cap->run_queue_hd->bound) {
377 // Make sure we're not about to try to wake ourselves up
378 ASSERT(task != cap->run_queue_hd->bound);
379 task = cap->run_queue_hd->bound;
380 giveCapabilityToTask(cap,task);
384 if (!cap->spare_workers) {
385 // Create a worker thread if we don't have one. If the system
386 // is interrupted, we only create a worker task if there
387 // are threads that need to be completed. If the system is
388 // shutting down, we never create a new worker.
389 if (sched_state < SCHED_SHUTTING_DOWN || !emptyRunQueue(cap)) {
390 debugTrace(DEBUG_sched,
391 "starting new worker on capability %d", cap->no);
392 startWorkerTask(cap, workerStart);
397 // If we have an unbound thread on the run queue, or if there's
398 // anything else to do, give the Capability to a worker thread.
400 !emptyRunQueue(cap) || !emptyWakeupQueue(cap) ||
401 !emptySparkPoolCap(cap) || globalWorkToDo()) {
402 if (cap->spare_workers) {
403 giveCapabilityToTask(cap,cap->spare_workers);
404 // The worker Task pops itself from the queue;
409 last_free_capability = cap;
410 trace(TRACE_sched | DEBUG_sched, "freeing capability %d", cap->no);
414 releaseCapability (Capability* cap USED_IF_THREADS)
416 ACQUIRE_LOCK(&cap->lock);
417 releaseCapability_(cap, rtsFalse);
418 RELEASE_LOCK(&cap->lock);
422 releaseAndWakeupCapability (Capability* cap USED_IF_THREADS)
424 ACQUIRE_LOCK(&cap->lock);
425 releaseCapability_(cap, rtsTrue);
426 RELEASE_LOCK(&cap->lock);
430 releaseCapabilityAndQueueWorker (Capability* cap USED_IF_THREADS)
434 ACQUIRE_LOCK(&cap->lock);
436 task = cap->running_task;
438 // If the current task is a worker, save it on the spare_workers
439 // list of this Capability. A worker can mark itself as stopped,
440 // in which case it is not replaced on the spare_worker queue.
441 // This happens when the system is shutting down (see
442 // Schedule.c:workerStart()).
443 // Also, be careful to check that this task hasn't just exited
444 // Haskell to do a foreign call (task->suspended_tso).
445 if (!isBoundTask(task) && !task->stopped && !task->suspended_tso) {
446 task->next = cap->spare_workers;
447 cap->spare_workers = task;
449 // Bound tasks just float around attached to their TSOs.
451 releaseCapability_(cap,rtsFalse);
453 RELEASE_LOCK(&cap->lock);
457 /* ----------------------------------------------------------------------------
458 * waitForReturnCapability( Task *task )
460 * Purpose: when an OS thread returns from an external call,
461 * it calls waitForReturnCapability() (via Schedule.resumeThread())
462 * to wait for permission to enter the RTS & communicate the
463 * result of the external call back to the Haskell thread that
466 * ------------------------------------------------------------------------- */
468 waitForReturnCapability (Capability **pCap, Task *task)
470 #if !defined(THREADED_RTS)
472 MainCapability.running_task = task;
473 task->cap = &MainCapability;
474 *pCap = &MainCapability;
477 Capability *cap = *pCap;
480 // Try last_free_capability first
481 cap = last_free_capability;
482 if (!cap->running_task) {
484 // otherwise, search for a free capability
486 for (i = 0; i < n_capabilities; i++) {
487 if (!capabilities[i].running_task) {
488 cap = &capabilities[i];
493 // Can't find a free one, use last_free_capability.
494 cap = last_free_capability;
498 // record the Capability as the one this Task is now assocated with.
502 ASSERT(task->cap == cap);
505 ACQUIRE_LOCK(&cap->lock);
507 debugTrace(DEBUG_sched, "returning; I want capability %d", cap->no);
509 if (!cap->running_task) {
510 // It's free; just grab it
511 cap->running_task = task;
512 RELEASE_LOCK(&cap->lock);
514 newReturningTask(cap,task);
515 RELEASE_LOCK(&cap->lock);
518 ACQUIRE_LOCK(&task->lock);
519 // task->lock held, cap->lock not held
520 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
522 task->wakeup = rtsFalse;
523 RELEASE_LOCK(&task->lock);
525 // now check whether we should wake up...
526 ACQUIRE_LOCK(&cap->lock);
527 if (cap->running_task == NULL) {
528 if (cap->returning_tasks_hd != task) {
529 giveCapabilityToTask(cap,cap->returning_tasks_hd);
530 RELEASE_LOCK(&cap->lock);
533 cap->running_task = task;
534 popReturningTask(cap);
535 RELEASE_LOCK(&cap->lock);
538 RELEASE_LOCK(&cap->lock);
543 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
545 trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
551 #if defined(THREADED_RTS)
552 /* ----------------------------------------------------------------------------
554 * ------------------------------------------------------------------------- */
557 yieldCapability (Capability** pCap, Task *task)
559 Capability *cap = *pCap;
561 if (waiting_for_gc == PENDING_GC_PAR) {
562 debugTrace(DEBUG_sched, "capability %d: becoming a GC thread", cap->no);
567 debugTrace(DEBUG_sched, "giving up capability %d", cap->no);
569 // We must now release the capability and wait to be woken up
571 task->wakeup = rtsFalse;
572 releaseCapabilityAndQueueWorker(cap);
575 ACQUIRE_LOCK(&task->lock);
576 // task->lock held, cap->lock not held
577 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
579 task->wakeup = rtsFalse;
580 RELEASE_LOCK(&task->lock);
582 debugTrace(DEBUG_sched, "woken up on capability %d", cap->no);
584 ACQUIRE_LOCK(&cap->lock);
585 if (cap->running_task != NULL) {
586 debugTrace(DEBUG_sched,
587 "capability %d is owned by another task", cap->no);
588 RELEASE_LOCK(&cap->lock);
592 if (task->tso == NULL) {
593 ASSERT(cap->spare_workers != NULL);
594 // if we're not at the front of the queue, release it
595 // again. This is unlikely to happen.
596 if (cap->spare_workers != task) {
597 giveCapabilityToTask(cap,cap->spare_workers);
598 RELEASE_LOCK(&cap->lock);
601 cap->spare_workers = task->next;
604 cap->running_task = task;
605 RELEASE_LOCK(&cap->lock);
609 trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
610 ASSERT(cap->running_task == task);
614 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
619 /* ----------------------------------------------------------------------------
620 * Wake up a thread on a Capability.
622 * This is used when the current Task is running on a Capability and
623 * wishes to wake up a thread on a different Capability.
624 * ------------------------------------------------------------------------- */
627 wakeupThreadOnCapability (Capability *my_cap,
628 Capability *other_cap,
631 ACQUIRE_LOCK(&other_cap->lock);
633 // ASSUMES: cap->lock is held (asserted in wakeupThreadOnCapability)
635 ASSERT(tso->bound->cap == tso->cap);
636 tso->bound->cap = other_cap;
638 tso->cap = other_cap;
640 ASSERT(tso->bound ? tso->bound->cap == other_cap : 1);
642 if (other_cap->running_task == NULL) {
643 // nobody is running this Capability, we can add our thread
644 // directly onto the run queue and start up a Task to run it.
646 other_cap->running_task = myTask();
647 // precond for releaseCapability_() and appendToRunQueue()
649 appendToRunQueue(other_cap,tso);
651 trace(TRACE_sched, "resuming capability %d", other_cap->no);
652 releaseCapability_(other_cap,rtsFalse);
654 appendToWakeupQueue(my_cap,other_cap,tso);
655 other_cap->context_switch = 1;
656 // someone is running on this Capability, so it cannot be
657 // freed without first checking the wakeup queue (see
658 // releaseCapability_).
661 RELEASE_LOCK(&other_cap->lock);
664 /* ----------------------------------------------------------------------------
667 * If a Capability is currently idle, wake up a Task on it. Used to
668 * get every Capability into the GC.
669 * ------------------------------------------------------------------------- */
672 prodCapability (Capability *cap, Task *task)
674 ACQUIRE_LOCK(&cap->lock);
675 if (!cap->running_task) {
676 cap->running_task = task;
677 releaseCapability_(cap,rtsTrue);
679 RELEASE_LOCK(&cap->lock);
682 /* ----------------------------------------------------------------------------
685 * At shutdown time, we want to let everything exit as cleanly as
686 * possible. For each capability, we let its run queue drain, and
687 * allow the workers to stop.
689 * This function should be called when interrupted and
690 * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
691 * will exit the scheduler and call taskStop(), and any bound thread
692 * that wakes up will return to its caller. Runnable threads are
695 * ------------------------------------------------------------------------- */
698 shutdownCapability (Capability *cap, Task *task, rtsBool safe)
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 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
713 debugTrace(DEBUG_sched,
714 "shutting down capability %d, attempt %d", cap->no, i);
715 ACQUIRE_LOCK(&cap->lock);
716 if (cap->running_task) {
717 RELEASE_LOCK(&cap->lock);
718 debugTrace(DEBUG_sched, "not owner, yielding");
722 cap->running_task = task;
724 if (cap->spare_workers) {
725 // Look for workers that have died without removing
726 // themselves from the list; this could happen if the OS
727 // summarily killed the thread, for example. This
728 // actually happens on Windows when the system is
729 // terminating the program, and the RTS is running in a
733 for (t = cap->spare_workers; t != NULL; t = t->next) {
734 if (!osThreadIsAlive(t->id)) {
735 debugTrace(DEBUG_sched,
736 "worker thread %p has died unexpectedly", (void *)t->id);
738 cap->spare_workers = t->next;
740 prev->next = t->next;
747 if (!emptyRunQueue(cap) || cap->spare_workers) {
748 debugTrace(DEBUG_sched,
749 "runnable threads or workers still alive, yielding");
750 releaseCapability_(cap,rtsFalse); // this will wake up a worker
751 RELEASE_LOCK(&cap->lock);
756 // If "safe", then busy-wait for any threads currently doing
757 // foreign calls. If we're about to unload this DLL, for
758 // example, we need to be sure that there are no OS threads
759 // that will try to return to code that has been unloaded.
760 // We can be a bit more relaxed when this is a standalone
761 // program that is about to terminate, and let safe=false.
762 if (cap->suspended_ccalling_tasks && safe) {
763 debugTrace(DEBUG_sched,
764 "thread(s) are involved in foreign calls, yielding");
765 cap->running_task = NULL;
766 RELEASE_LOCK(&cap->lock);
771 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)
812 stgFree(cap->mut_lists);
813 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
814 freeSparkPool(cap->sparks);
819 freeCapabilities (void)
821 #if defined(THREADED_RTS)
823 for (i=0; i < n_capabilities; i++) {
824 freeCapability(&capabilities[i]);
827 freeCapability(&MainCapability);
831 /* ---------------------------------------------------------------------------
832 Mark everything directly reachable from the Capabilities. When
833 using multiple GC threads, each GC thread marks all Capabilities
834 for which (c `mod` n == 0), for Capability c and thread n.
835 ------------------------------------------------------------------------ */
838 markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta,
839 rtsBool prune_sparks USED_IF_THREADS)
845 // Each GC thread is responsible for following roots from the
846 // Capability of the same number. There will usually be the same
847 // or fewer Capabilities as GC threads, but just in case there
848 // are more, we mark every Capability whose number is the GC
849 // thread's index plus a multiple of the number of GC threads.
850 for (i = i0; i < n_capabilities; i += delta) {
851 cap = &capabilities[i];
852 evac(user, (StgClosure **)(void *)&cap->run_queue_hd);
853 evac(user, (StgClosure **)(void *)&cap->run_queue_tl);
854 #if defined(THREADED_RTS)
855 evac(user, (StgClosure **)(void *)&cap->wakeup_queue_hd);
856 evac(user, (StgClosure **)(void *)&cap->wakeup_queue_tl);
858 for (task = cap->suspended_ccalling_tasks; task != NULL;
860 debugTrace(DEBUG_sched,
861 "evac'ing suspended TSO %lu", (unsigned long)task->suspended_tso->id);
862 evac(user, (StgClosure **)(void *)&task->suspended_tso);
865 #if defined(THREADED_RTS)
867 pruneSparkQueue (evac, user, cap);
869 traverseSparkQueue (evac, user, cap);
874 #if !defined(THREADED_RTS)
875 evac(user, (StgClosure **)(void *)&blocked_queue_hd);
876 evac(user, (StgClosure **)(void *)&blocked_queue_tl);
877 evac(user, (StgClosure **)(void *)&sleeping_queue);
882 markCapabilities (evac_fn evac, void *user)
884 markSomeCapabilities(evac, user, 0, 1, rtsFalse);