1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 2002
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
13 * Only in an SMP build will there be multiple capabilities, for
14 * the threaded RTS and other non-threaded builds, there is only
15 * one global capability, namely MainCapability.
17 * --------------------------------------------------------------------------*/
18 #include "PosixSource.h"
21 #include "OSThreads.h"
22 #include "Capability.h"
23 #include "Schedule.h" /* to get at EMPTY_RUN_QUEUE() */
26 Capability MainCapability; /* for non-SMP, we have one global capability */
29 nat rts_n_free_capabilities;
31 #if defined(RTS_SUPPORTS_THREADS)
32 /* returning_worker_cond: when a worker thread returns from executing an
33 * external call, it needs to wait for an RTS Capability before passing
34 * on the result of the call to the Haskell thread that made it.
36 * returning_worker_cond is signalled in Capability.releaseCapability().
39 Condition returning_worker_cond = INIT_COND_VAR;
42 * To avoid starvation of threads blocked on worker_thread_cond,
43 * the task(s) that enter the Scheduler will check to see whether
44 * there are one or more worker threads blocked waiting on
45 * returning_worker_cond.
47 static nat rts_n_waiting_workers = 0;
49 /* thread_ready_cond: when signalled, a thread has become runnable for a
52 * In the non-SMP case, it also implies that the thread that is woken up has
53 * exclusive access to the RTS and all its data structures (that are not
54 * locked by the Scheduler's mutex).
56 * thread_ready_cond is signalled whenever COND_NO_THREADS_READY doesn't hold.
59 Condition thread_ready_cond = INIT_COND_VAR;
61 /* For documentation purposes only */
62 #define COND_NO_THREADS_READY() (noCapabilities() || EMPTY_RUN_QUEUE())
66 * To be able to make an informed decision about whether or not
67 * to create a new task when making an external call, keep track of
68 * the number of tasks currently blocked waiting on thread_ready_cond.
69 * (if > 0 => no need for a new task, just unblock an existing one).
71 * waitForWorkCapability() takes care of keeping it up-to-date;
72 * Task.startTask() uses its current value.
74 nat rts_n_waiting_tasks = 0;
77 /* -----------------------------------------------------------------------------
79 -------------------------------------------------------------------------- */
82 initCapability( Capability *cap )
84 cap->f.stgGCEnter1 = (F_)__stg_gc_enter_1;
85 cap->f.stgGCFun = (F_)__stg_gc_fun;
89 static void initCapabilities_(nat n);
93 * Function: initCapabilities()
95 * Purpose: set up the Capability handling. For the SMP build,
96 * we keep a table of them, the size of which is
97 * controlled by the user via the RTS flag RtsFlags.ParFlags.nNodes
99 * Pre-conditions: no locks assumed held.
104 #if defined(RTS_SUPPORTS_THREADS)
105 initCondition(&returning_worker_cond);
106 initCondition(&thread_ready_cond);
110 initCapabilities_(RtsFlags.ParFlags.nNodes);
112 initCapability(&MainCapability);
113 rts_n_free_capabilities = 1;
120 /* Free capability list. */
121 static Capability *free_capabilities; /* Available capabilities for running threads */
124 /* -----------------------------------------------------------------------------
125 Acquiring capabilities
126 -------------------------------------------------------------------------- */
129 * Function: grabCapability(Capability**)
131 * Purpose: the act of grabbing a capability is easy; just
132 * remove one from the free capabilities list (which
133 * may just have one entry). In threaded builds, worker
134 * threads are prevented from doing so willy-nilly
135 * via the condition variables thread_ready_cond and
136 * returning_worker_cond.
139 void grabCapability(Capability** cap)
142 rts_n_free_capabilities = 0;
143 *cap = &MainCapability;
145 *cap = free_capabilities;
146 free_capabilities = (*cap)->link;
147 rts_n_free_capabilities--;
152 * Function: releaseCapability(Capability*)
154 * Purpose: Letting go of a capability. Causes a
155 * 'returning worker' thread or a 'waiting worker'
156 * to wake up, in that order.
159 void releaseCapability(Capability* cap
166 cap->link = free_capabilities;
167 free_capabilities = cap;
168 rts_n_free_capabilities++;
170 rts_n_free_capabilities = 1;
173 #if defined(RTS_SUPPORTS_THREADS)
174 /* Check to see whether a worker thread can be given
175 the go-ahead to return the result of an external call..*/
176 if (rts_n_waiting_workers > 0) {
177 /* Decrement the counter here to avoid livelock where the
178 * thread that is yielding its capability will repeatedly
179 * signal returning_worker_cond.
181 rts_n_waiting_workers--;
182 signalCondition(&returning_worker_cond);
183 } else if ( !EMPTY_RUN_QUEUE() ) {
184 /* Signal that work is available */
185 signalCondition(&thread_ready_cond);
191 #if defined(RTS_SUPPORTS_THREADS)
193 * When a native thread has completed the execution of an external
194 * call, it needs to communicate the result back. This is done
197 * - in resumeThread(), the thread calls grabReturnCapability().
198 * - If no capabilities are readily available, grabReturnCapability()
199 * increments a counter rts_n_waiting_workers, and blocks
200 * waiting for the condition returning_worker_cond to become
202 * - upon entry to the Scheduler, a worker thread checks the
203 * value of rts_n_waiting_workers. If > 0, the worker thread
204 * will yield its capability to let a returning worker thread
205 * proceed with returning its result -- this is done via
206 * yieldToReturningWorker().
207 * - the worker thread that yielded its capability then tries
208 * to re-grab a capability and re-enter the Scheduler.
212 * Function: grabReturnCapability(Capability**)
214 * Purpose: when an OS thread returns from an external call,
215 * it calls grabReturnCapability() (via Schedule.resumeThread())
216 * to wait for permissions to enter the RTS & communicate the
217 * result of the external call back to the Haskell thread that
220 * Pre-condition: pMutex is held.
221 * Post-condition: pMutex is still held and a capability has
222 * been assigned to the worker thread.
225 grabReturnCapability(Mutex* pMutex, Capability** pCap)
228 fprintf(stderr,"worker (%ld): returning, waiting for lock.\n", osThreadId()));
229 rts_n_waiting_workers++;
231 fprintf(stderr,"worker (%ld): returning; workers waiting: %d\n",
232 osThreadId(), rts_n_waiting_workers));
233 while ( noCapabilities() ) {
234 waitCondition(&returning_worker_cond, pMutex);
237 grabCapability(pCap);
242 /* -----------------------------------------------------------------------------
243 Yielding/waiting for capabilities
244 -------------------------------------------------------------------------- */
247 * Function: yieldToReturningWorker(Mutex*,Capability*)
249 * Purpose: when, upon entry to the Scheduler, an OS worker thread
250 * spots that one or more threads are blocked waiting for
251 * permission to return back their result, it gives up
254 * Pre-condition: pMutex is assumed held and the thread possesses
256 * Post-condition: pMutex isn't held and the Capability has
260 yieldToReturningWorker(Mutex* pMutex, Capability** pCap)
262 if ( rts_n_waiting_workers > 0 && noCapabilities() ) {
264 fprintf(stderr,"worker thread (%ld): giving up RTS token\n", osThreadId()));
265 releaseCapability(*pCap);
266 /* And wait for work */
267 waitForWorkCapability(pMutex, pCap, rtsFalse);
274 * Function: waitForWorkCapability(Mutex*, Capability**, rtsBool)
276 * Purpose: wait for a Capability to become available. In
277 * the process of doing so, updates the number
278 * of tasks currently blocked waiting for a capability/more
279 * work. That counter is used when deciding whether or
280 * not to create a new worker thread when an external
283 * Pre-condition: pMutex is held.
286 waitForWorkCapability(Mutex* pMutex, Capability** pCap, rtsBool runnable)
288 while ( noCapabilities() || (runnable && EMPTY_RUN_QUEUE()) ) {
289 rts_n_waiting_tasks++;
290 waitCondition(&thread_ready_cond, pMutex);
291 rts_n_waiting_tasks--;
293 grabCapability(pCap);
296 #endif /* RTS_SUPPORTS_THREADS */
300 * Function: initCapabilities_(nat)
302 * Purpose: upon startup, allocate and fill in table
303 * holding 'n' Capabilities. Only for SMP, since
304 * it is the only build that supports multiple
305 * capabilities within the RTS.
308 initCapabilities_(nat n)
311 Capability *cap, *prev;
314 for (i = 0; i < n; i++) {
315 cap = stgMallocBytes(sizeof(Capability), "initCapabilities");
320 free_capabilities = cap;
321 rts_n_free_capabilities = n;
322 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Allocated %d capabilities\n", n_free_capabilities););