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"
22 #include "Capability.h"
26 #include "sm/GC.h" // for gcWorkerThread()
30 // one global capability, this is the Capability for non-threaded
31 // builds, and for +RTS -N1
32 Capability MainCapability;
34 nat n_capabilities = 0;
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 = NULL;
43 /* GC indicator, in scope for the scheduler, init'ed to false */
44 volatile StgWord waiting_for_gc = 0;
46 /* Let foreign code get the current Capability -- assuming there is one!
47 * This is useful for unsafe foreign calls because they are called with
48 * the current Capability held, but they are not passed it. For example,
49 * see see the integer-gmp package which calls allocateLocal() in its
50 * stgAllocForGMP() function (which gets called by gmp functions).
52 Capability * rts_unsafeGetMyCapability (void)
54 #if defined(THREADED_RTS)
57 return &MainCapability;
61 #if defined(THREADED_RTS)
65 return sched_state >= SCHED_INTERRUPTING
66 || recent_activity == ACTIVITY_INACTIVE; // need to check for deadlock
70 #if defined(THREADED_RTS)
72 findSpark (Capability *cap)
79 if (!emptyRunQueue(cap) || cap->returning_tasks_hd != NULL) {
80 // If there are other threads, don't try to run any new
81 // sparks: sparks might be speculative, we don't want to take
82 // resources away from the main computation.
89 // first try to get a spark from our own pool.
90 // We should be using reclaimSpark(), because it works without
91 // needing any atomic instructions:
92 // spark = reclaimSpark(cap->sparks);
93 // However, measurements show that this makes at least one benchmark
94 // slower (prsa) and doesn't affect the others.
95 spark = tryStealSpark(cap);
97 cap->sparks_converted++;
99 // Post event for running a spark from capability's own pool.
100 traceEventRunSpark(cap, cap->r.rCurrentTSO);
104 if (!emptySparkPoolCap(cap)) {
108 if (n_capabilities == 1) { return NULL; } // makes no sense...
110 debugTrace(DEBUG_sched,
111 "cap %d: Trying to steal work from other capabilities",
114 /* visit cap.s 0..n-1 in sequence until a theft succeeds. We could
115 start at a random place instead of 0 as well. */
116 for ( i=0 ; i < n_capabilities ; i++ ) {
117 robbed = &capabilities[i];
118 if (cap == robbed) // ourselves...
121 if (emptySparkPoolCap(robbed)) // nothing to steal here
124 spark = tryStealSpark(robbed);
125 if (spark == NULL && !emptySparkPoolCap(robbed)) {
126 // we conflicted with another thread while trying to steal;
132 cap->sparks_converted++;
134 traceEventStealSpark(cap, cap->r.rCurrentTSO, robbed->no);
138 // otherwise: no success, try next one
142 debugTrace(DEBUG_sched, "No sparks stolen");
146 // Returns True if any spark pool is non-empty at this moment in time
147 // The result is only valid for an instant, of course, so in a sense
148 // is immediately invalid, and should not be relied upon for
155 for (i=0; i < n_capabilities; i++) {
156 if (!emptySparkPoolCap(&capabilities[i])) {
164 /* -----------------------------------------------------------------------------
165 * Manage the returning_tasks lists.
167 * These functions require cap->lock
168 * -------------------------------------------------------------------------- */
170 #if defined(THREADED_RTS)
172 newReturningTask (Capability *cap, Task *task)
174 ASSERT_LOCK_HELD(&cap->lock);
175 ASSERT(task->next == NULL);
176 if (cap->returning_tasks_hd) {
177 ASSERT(cap->returning_tasks_tl->next == NULL);
178 cap->returning_tasks_tl->next = task;
180 cap->returning_tasks_hd = task;
182 cap->returning_tasks_tl = task;
186 popReturningTask (Capability *cap)
188 ASSERT_LOCK_HELD(&cap->lock);
190 task = cap->returning_tasks_hd;
192 cap->returning_tasks_hd = task->next;
193 if (!cap->returning_tasks_hd) {
194 cap->returning_tasks_tl = NULL;
201 /* ----------------------------------------------------------------------------
204 * The Capability is initially marked not free.
205 * ------------------------------------------------------------------------- */
208 initCapability( Capability *cap, nat i )
213 cap->in_haskell = rtsFalse;
215 cap->run_queue_hd = END_TSO_QUEUE;
216 cap->run_queue_tl = END_TSO_QUEUE;
218 #if defined(THREADED_RTS)
219 initMutex(&cap->lock);
220 cap->running_task = NULL; // indicates cap is free
221 cap->spare_workers = NULL;
222 cap->n_spare_workers = 0;
223 cap->suspended_ccalls = NULL;
224 cap->returning_tasks_hd = NULL;
225 cap->returning_tasks_tl = NULL;
226 cap->inbox = (Message*)END_TSO_QUEUE;
227 cap->sparks_created = 0;
228 cap->sparks_converted = 0;
229 cap->sparks_pruned = 0;
232 cap->f.stgEagerBlackholeInfo = (W_)&__stg_EAGER_BLACKHOLE_info;
233 cap->f.stgGCEnter1 = (StgFunPtr)__stg_gc_enter_1;
234 cap->f.stgGCFun = (StgFunPtr)__stg_gc_fun;
236 cap->mut_lists = stgMallocBytes(sizeof(bdescr *) *
237 RtsFlags.GcFlags.generations,
239 cap->saved_mut_lists = stgMallocBytes(sizeof(bdescr *) *
240 RtsFlags.GcFlags.generations,
243 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
244 cap->mut_lists[g] = NULL;
247 cap->free_tvar_watch_queues = END_STM_WATCH_QUEUE;
248 cap->free_invariant_check_queues = END_INVARIANT_CHECK_QUEUE;
249 cap->free_trec_chunks = END_STM_CHUNK_LIST;
250 cap->free_trec_headers = NO_TREC;
251 cap->transaction_tokens = 0;
252 cap->context_switch = 0;
253 cap->pinned_object_block = NULL;
256 /* ---------------------------------------------------------------------------
257 * Function: initCapabilities()
259 * Purpose: set up the Capability handling. For the THREADED_RTS build,
260 * we keep a table of them, the size of which is
261 * controlled by the user via the RTS flag -N.
263 * ------------------------------------------------------------------------- */
265 initCapabilities( void )
267 #if defined(THREADED_RTS)
271 // We can't support multiple CPUs if BaseReg is not a register
272 if (RtsFlags.ParFlags.nNodes > 1) {
273 errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
274 RtsFlags.ParFlags.nNodes = 1;
278 n_capabilities = RtsFlags.ParFlags.nNodes;
280 if (n_capabilities == 1) {
281 capabilities = &MainCapability;
282 // THREADED_RTS must work on builds that don't have a mutable
283 // BaseReg (eg. unregisterised), so in this case
284 // capabilities[0] must coincide with &MainCapability.
286 capabilities = stgMallocBytes(n_capabilities * sizeof(Capability),
290 for (i = 0; i < n_capabilities; i++) {
291 initCapability(&capabilities[i], i);
294 debugTrace(DEBUG_sched, "allocated %d capabilities", n_capabilities);
296 #else /* !THREADED_RTS */
299 capabilities = &MainCapability;
300 initCapability(&MainCapability, 0);
304 // There are no free capabilities to begin with. We will start
305 // a worker Task to each Capability, which will quickly put the
306 // Capability on the free list when it finds nothing to do.
307 last_free_capability = &capabilities[0];
310 /* ----------------------------------------------------------------------------
311 * setContextSwitches: cause all capabilities to context switch as
313 * ------------------------------------------------------------------------- */
315 void setContextSwitches(void)
318 for (i=0; i < n_capabilities; i++) {
319 contextSwitchCapability(&capabilities[i]);
323 /* ----------------------------------------------------------------------------
324 * Give a Capability to a Task. The task must currently be sleeping
325 * on its condition variable.
327 * Requires cap->lock (modifies cap->running_task).
329 * When migrating a Task, the migrater must take task->lock before
330 * modifying task->cap, to synchronise with the waking up Task.
331 * Additionally, the migrater should own the Capability (when
332 * migrating the run queue), or cap->lock (when migrating
333 * returning_workers).
335 * ------------------------------------------------------------------------- */
337 #if defined(THREADED_RTS)
339 giveCapabilityToTask (Capability *cap USED_IF_DEBUG, Task *task)
341 ASSERT_LOCK_HELD(&cap->lock);
342 ASSERT(task->cap == cap);
343 debugTrace(DEBUG_sched, "passing capability %d to %s %p",
344 cap->no, task->incall->tso ? "bound task" : "worker",
346 ACQUIRE_LOCK(&task->lock);
347 task->wakeup = rtsTrue;
348 // the wakeup flag is needed because signalCondition() doesn't
349 // flag the condition if the thread is already runniing, but we want
351 signalCondition(&task->cond);
352 RELEASE_LOCK(&task->lock);
356 /* ----------------------------------------------------------------------------
357 * Function: releaseCapability(Capability*)
359 * Purpose: Letting go of a capability. Causes a
360 * 'returning worker' thread or a 'waiting worker'
361 * to wake up, in that order.
362 * ------------------------------------------------------------------------- */
364 #if defined(THREADED_RTS)
366 releaseCapability_ (Capability* cap,
367 rtsBool always_wakeup)
371 task = cap->running_task;
373 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task);
375 cap->running_task = NULL;
377 // Check to see whether a worker thread can be given
378 // the go-ahead to return the result of an external call..
379 if (cap->returning_tasks_hd != NULL) {
380 giveCapabilityToTask(cap,cap->returning_tasks_hd);
381 // The Task pops itself from the queue (see waitForReturnCapability())
385 if (waiting_for_gc == PENDING_GC_SEQ) {
386 last_free_capability = cap; // needed?
387 debugTrace(DEBUG_sched, "GC pending, set capability %d free", cap->no);
392 // If the next thread on the run queue is a bound thread,
393 // give this Capability to the appropriate Task.
394 if (!emptyRunQueue(cap) && cap->run_queue_hd->bound) {
395 // Make sure we're not about to try to wake ourselves up
396 // ASSERT(task != cap->run_queue_hd->bound);
397 // assertion is false: in schedule() we force a yield after
398 // ThreadBlocked, but the thread may be back on the run queue
400 task = cap->run_queue_hd->bound->task;
401 giveCapabilityToTask(cap,task);
405 if (!cap->spare_workers) {
406 // Create a worker thread if we don't have one. If the system
407 // is interrupted, we only create a worker task if there
408 // are threads that need to be completed. If the system is
409 // shutting down, we never create a new worker.
410 if (sched_state < SCHED_SHUTTING_DOWN || !emptyRunQueue(cap)) {
411 debugTrace(DEBUG_sched,
412 "starting new worker on capability %d", cap->no);
413 startWorkerTask(cap);
418 // If we have an unbound thread on the run queue, or if there's
419 // anything else to do, give the Capability to a worker thread.
421 !emptyRunQueue(cap) || !emptyInbox(cap) ||
422 !emptySparkPoolCap(cap) || globalWorkToDo()) {
423 if (cap->spare_workers) {
424 giveCapabilityToTask(cap,cap->spare_workers);
425 // The worker Task pops itself from the queue;
430 last_free_capability = cap;
431 debugTrace(DEBUG_sched, "freeing capability %d", cap->no);
435 releaseCapability (Capability* cap USED_IF_THREADS)
437 ACQUIRE_LOCK(&cap->lock);
438 releaseCapability_(cap, rtsFalse);
439 RELEASE_LOCK(&cap->lock);
443 releaseAndWakeupCapability (Capability* cap USED_IF_THREADS)
445 ACQUIRE_LOCK(&cap->lock);
446 releaseCapability_(cap, rtsTrue);
447 RELEASE_LOCK(&cap->lock);
451 releaseCapabilityAndQueueWorker (Capability* cap USED_IF_THREADS)
455 ACQUIRE_LOCK(&cap->lock);
457 task = cap->running_task;
459 // If the current task is a worker, save it on the spare_workers
460 // list of this Capability. A worker can mark itself as stopped,
461 // in which case it is not replaced on the spare_worker queue.
462 // This happens when the system is shutting down (see
463 // Schedule.c:workerStart()).
464 if (!isBoundTask(task) && !task->stopped)
466 if (cap->n_spare_workers < MAX_SPARE_WORKERS)
468 task->next = cap->spare_workers;
469 cap->spare_workers = task;
470 cap->n_spare_workers++;
474 debugTrace(DEBUG_sched, "%d spare workers already, exiting",
475 cap->n_spare_workers);
476 releaseCapability_(cap,rtsFalse);
477 // hold the lock until after workerTaskStop; c.f. scheduleWorker()
478 workerTaskStop(task);
479 RELEASE_LOCK(&cap->lock);
483 // Bound tasks just float around attached to their TSOs.
485 releaseCapability_(cap,rtsFalse);
487 RELEASE_LOCK(&cap->lock);
491 /* ----------------------------------------------------------------------------
492 * waitForReturnCapability( Task *task )
494 * Purpose: when an OS thread returns from an external call,
495 * it calls waitForReturnCapability() (via Schedule.resumeThread())
496 * to wait for permission to enter the RTS & communicate the
497 * result of the external call back to the Haskell thread that
500 * ------------------------------------------------------------------------- */
502 waitForReturnCapability (Capability **pCap, Task *task)
504 #if !defined(THREADED_RTS)
506 MainCapability.running_task = task;
507 task->cap = &MainCapability;
508 *pCap = &MainCapability;
511 Capability *cap = *pCap;
514 // Try last_free_capability first
515 cap = last_free_capability;
516 if (cap->running_task) {
518 // otherwise, search for a free capability
520 for (i = 0; i < n_capabilities; i++) {
521 if (!capabilities[i].running_task) {
522 cap = &capabilities[i];
527 // Can't find a free one, use last_free_capability.
528 cap = last_free_capability;
532 // record the Capability as the one this Task is now assocated with.
536 ASSERT(task->cap == cap);
539 ACQUIRE_LOCK(&cap->lock);
541 debugTrace(DEBUG_sched, "returning; I want capability %d", cap->no);
543 if (!cap->running_task) {
544 // It's free; just grab it
545 cap->running_task = task;
546 RELEASE_LOCK(&cap->lock);
548 newReturningTask(cap,task);
549 RELEASE_LOCK(&cap->lock);
552 ACQUIRE_LOCK(&task->lock);
553 // task->lock held, cap->lock not held
554 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
556 task->wakeup = rtsFalse;
557 RELEASE_LOCK(&task->lock);
559 // now check whether we should wake up...
560 ACQUIRE_LOCK(&cap->lock);
561 if (cap->running_task == NULL) {
562 if (cap->returning_tasks_hd != task) {
563 giveCapabilityToTask(cap,cap->returning_tasks_hd);
564 RELEASE_LOCK(&cap->lock);
567 cap->running_task = task;
568 popReturningTask(cap);
569 RELEASE_LOCK(&cap->lock);
572 RELEASE_LOCK(&cap->lock);
577 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
579 debugTrace(DEBUG_sched, "resuming capability %d", cap->no);
585 #if defined(THREADED_RTS)
586 /* ----------------------------------------------------------------------------
588 * ------------------------------------------------------------------------- */
591 yieldCapability (Capability** pCap, Task *task)
593 Capability *cap = *pCap;
595 if (waiting_for_gc == PENDING_GC_PAR) {
596 traceEventGcStart(cap);
598 traceEventGcEnd(cap);
602 debugTrace(DEBUG_sched, "giving up capability %d", cap->no);
604 // We must now release the capability and wait to be woken up
606 task->wakeup = rtsFalse;
607 releaseCapabilityAndQueueWorker(cap);
610 ACQUIRE_LOCK(&task->lock);
611 // task->lock held, cap->lock not held
612 if (!task->wakeup) waitCondition(&task->cond, &task->lock);
614 task->wakeup = rtsFalse;
615 RELEASE_LOCK(&task->lock);
617 debugTrace(DEBUG_sched, "woken up on capability %d", cap->no);
619 ACQUIRE_LOCK(&cap->lock);
620 if (cap->running_task != NULL) {
621 debugTrace(DEBUG_sched,
622 "capability %d is owned by another task", cap->no);
623 RELEASE_LOCK(&cap->lock);
627 if (task->incall->tso == NULL) {
628 ASSERT(cap->spare_workers != NULL);
629 // if we're not at the front of the queue, release it
630 // again. This is unlikely to happen.
631 if (cap->spare_workers != task) {
632 giveCapabilityToTask(cap,cap->spare_workers);
633 RELEASE_LOCK(&cap->lock);
636 cap->spare_workers = task->next;
638 cap->n_spare_workers--;
640 cap->running_task = task;
641 RELEASE_LOCK(&cap->lock);
645 debugTrace(DEBUG_sched, "resuming capability %d", cap->no);
646 ASSERT(cap->running_task == task);
650 ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
655 /* ----------------------------------------------------------------------------
658 * If a Capability is currently idle, wake up a Task on it. Used to
659 * get every Capability into the GC.
660 * ------------------------------------------------------------------------- */
663 prodCapability (Capability *cap, Task *task)
665 ACQUIRE_LOCK(&cap->lock);
666 if (!cap->running_task) {
667 cap->running_task = task;
668 releaseCapability_(cap,rtsTrue);
670 RELEASE_LOCK(&cap->lock);
673 /* ----------------------------------------------------------------------------
676 * At shutdown time, we want to let everything exit as cleanly as
677 * possible. For each capability, we let its run queue drain, and
678 * allow the workers to stop.
680 * This function should be called when interrupted and
681 * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
682 * will exit the scheduler and call taskStop(), and any bound thread
683 * that wakes up will return to its caller. Runnable threads are
686 * ------------------------------------------------------------------------- */
689 shutdownCapability (Capability *cap, Task *task, rtsBool safe)
695 // Loop indefinitely until all the workers have exited and there
696 // are no Haskell threads left. We used to bail out after 50
697 // iterations of this loop, but that occasionally left a worker
698 // running which caused problems later (the closeMutex() below
699 // isn't safe, for one thing).
701 for (i = 0; /* i < 50 */; i++) {
702 ASSERT(sched_state == SCHED_SHUTTING_DOWN);
704 debugTrace(DEBUG_sched,
705 "shutting down capability %d, attempt %d", cap->no, i);
706 ACQUIRE_LOCK(&cap->lock);
707 if (cap->running_task) {
708 RELEASE_LOCK(&cap->lock);
709 debugTrace(DEBUG_sched, "not owner, yielding");
713 cap->running_task = task;
715 if (cap->spare_workers) {
716 // Look for workers that have died without removing
717 // themselves from the list; this could happen if the OS
718 // summarily killed the thread, for example. This
719 // actually happens on Windows when the system is
720 // terminating the program, and the RTS is running in a
724 for (t = cap->spare_workers; t != NULL; t = t->next) {
725 if (!osThreadIsAlive(t->id)) {
726 debugTrace(DEBUG_sched,
727 "worker thread %p has died unexpectedly", (void *)t->id);
728 cap->n_spare_workers--;
730 cap->spare_workers = t->next;
732 prev->next = t->next;
739 if (!emptyRunQueue(cap) || cap->spare_workers) {
740 debugTrace(DEBUG_sched,
741 "runnable threads or workers still alive, yielding");
742 releaseCapability_(cap,rtsFalse); // this will wake up a worker
743 RELEASE_LOCK(&cap->lock);
748 // If "safe", then busy-wait for any threads currently doing
749 // foreign calls. If we're about to unload this DLL, for
750 // example, we need to be sure that there are no OS threads
751 // that will try to return to code that has been unloaded.
752 // We can be a bit more relaxed when this is a standalone
753 // program that is about to terminate, and let safe=false.
754 if (cap->suspended_ccalls && safe) {
755 debugTrace(DEBUG_sched,
756 "thread(s) are involved in foreign calls, yielding");
757 cap->running_task = NULL;
758 RELEASE_LOCK(&cap->lock);
759 // The IO manager thread might have been slow to start up,
760 // so the first attempt to kill it might not have
761 // succeeded. Just in case, try again - the kill message
762 // will only be sent once.
764 // To reproduce this deadlock: run ffi002(threaded1)
765 // repeatedly on a loaded machine.
771 traceEventShutdown(cap);
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 stgFree(cap->saved_mut_lists);
814 #if defined(THREADED_RTS)
815 freeSparkPool(cap->sparks);
820 freeCapabilities (void)
822 #if defined(THREADED_RTS)
824 for (i=0; i < n_capabilities; i++) {
825 freeCapability(&capabilities[i]);
828 freeCapability(&MainCapability);
832 /* ---------------------------------------------------------------------------
833 Mark everything directly reachable from the Capabilities. When
834 using multiple GC threads, each GC thread marks all Capabilities
835 for which (c `mod` n == 0), for Capability c and thread n.
836 ------------------------------------------------------------------------ */
839 markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta,
840 rtsBool no_mark_sparks USED_IF_THREADS)
846 // Each GC thread is responsible for following roots from the
847 // Capability of the same number. There will usually be the same
848 // or fewer Capabilities as GC threads, but just in case there
849 // are more, we mark every Capability whose number is the GC
850 // thread's index plus a multiple of the number of GC threads.
851 for (i = i0; i < n_capabilities; i += delta) {
852 cap = &capabilities[i];
853 evac(user, (StgClosure **)(void *)&cap->run_queue_hd);
854 evac(user, (StgClosure **)(void *)&cap->run_queue_tl);
855 #if defined(THREADED_RTS)
856 evac(user, (StgClosure **)(void *)&cap->inbox);
858 for (incall = cap->suspended_ccalls; incall != NULL;
859 incall=incall->next) {
860 evac(user, (StgClosure **)(void *)&incall->suspended_tso);
863 #if defined(THREADED_RTS)
864 if (!no_mark_sparks) {
865 traverseSparkQueue (evac, user, cap);
870 #if !defined(THREADED_RTS)
871 evac(user, (StgClosure **)(void *)&blocked_queue_hd);
872 evac(user, (StgClosure **)(void *)&blocked_queue_tl);
873 evac(user, (StgClosure **)(void *)&sleeping_queue);
878 markCapabilities (evac_fn evac, void *user)
880 markSomeCapabilities(evac, user, 0, 1, rtsFalse);
883 /* -----------------------------------------------------------------------------
885 -------------------------------------------------------------------------- */