1 /* ---------------------------------------------------------------------------
2 * (c) The GHC Team, 2003
6 * A Capability represent the token required to execute STG code,
7 * and all the state an OS thread/task needs to run Haskell code:
8 * its STG registers, a pointer to its TSO, a nursery etc. During
9 * STG execution, a pointer to the capabilitity is kept in a
12 * Only in an SMP build will there be multiple capabilities, for
13 * the threaded RTS and other non-threaded builds, there is only
14 * one global capability, namely MainCapability.
16 * --------------------------------------------------------------------------*/
18 #include "PosixSource.h"
22 #include "OSThreads.h"
23 #include "Capability.h"
24 #include "Schedule.h" /* to get at EMPTY_RUN_QUEUE() */
27 Capability MainCapability; /* for non-SMP, we have one global capability */
30 Capability *capabilities = NULL;
31 nat rts_n_free_capabilities;
33 #if defined(RTS_SUPPORTS_THREADS)
35 /* returning_worker_cond: when a worker thread returns from executing an
36 * external call, it needs to wait for an RTS Capability before passing
37 * on the result of the call to the Haskell thread that made it.
39 * returning_worker_cond is signalled in Capability.releaseCapability().
42 Condition returning_worker_cond = INIT_COND_VAR;
45 * To avoid starvation of threads blocked on worker_thread_cond,
46 * the task(s) that enter the Scheduler will check to see whether
47 * there are one or more worker threads blocked waiting on
48 * returning_worker_cond.
50 nat rts_n_waiting_workers = 0;
52 /* thread_ready_cond: when signalled, a thread has become runnable for a
55 * In the non-SMP case, it also implies that the thread that is woken up has
56 * exclusive access to the RTS and all its data structures (that are not
57 * locked by the Scheduler's mutex).
59 * thread_ready_cond is signalled whenever
60 * !noCapabilities && !EMPTY_RUN_QUEUE().
62 Condition thread_ready_cond = INIT_COND_VAR;
65 * To be able to make an informed decision about whether or not
66 * to create a new task when making an external call, keep track of
67 * the number of tasks currently blocked waiting on thread_ready_cond.
68 * (if > 0 => no need for a new task, just unblock an existing one).
70 * waitForWorkCapability() takes care of keeping it up-to-date;
71 * Task.startTask() uses its current value.
73 nat rts_n_waiting_tasks = 0;
75 static Condition *passTarget = NULL;
76 static rtsBool passingCapability = rtsFalse;
81 * Free capability list.
83 Capability *free_capabilities;
87 #define UNUSED_IF_NOT_SMP
89 #define UNUSED_IF_NOT_SMP STG_UNUSED
92 #if defined(RTS_USER_SIGNALS)
93 #define ANY_WORK_TO_DO() (!EMPTY_RUN_QUEUE() || interrupted || blackholes_need_checking || signals_pending())
95 #define ANY_WORK_TO_DO() (!EMPTY_RUN_QUEUE() || interrupted || blackholes_need_checking)
98 /* ----------------------------------------------------------------------------
100 ------------------------------------------------------------------------- */
103 initCapability( Capability *cap )
105 cap->f.stgGCEnter1 = (F_)__stg_gc_enter_1;
106 cap->f.stgGCFun = (F_)__stg_gc_fun;
109 /* ---------------------------------------------------------------------------
110 * Function: initCapabilities()
112 * Purpose: set up the Capability handling. For the SMP build,
113 * we keep a table of them, the size of which is
114 * controlled by the user via the RTS flag RtsFlags.ParFlags.nNodes
116 * ------------------------------------------------------------------------- */
118 initCapabilities( void )
123 n = RtsFlags.ParFlags.nNodes;
124 capabilities = stgMallocBytes(n * sizeof(Capability), "initCapabilities");
126 for (i = 0; i < n; i++) {
127 initCapability(&capabilities[i]);
128 capabilities[i].link = &capabilities[i+1];
130 capabilities[n-1].link = NULL;
132 free_capabilities = &capabilities[0];
133 rts_n_free_capabilities = n;
135 IF_DEBUG(scheduler, sched_belch("allocated %d capabilities", n));
137 capabilities = &MainCapability;
138 initCapability(&MainCapability);
139 rts_n_free_capabilities = 1;
142 #if defined(RTS_SUPPORTS_THREADS)
143 initCondition(&returning_worker_cond);
144 initCondition(&thread_ready_cond);
148 /* ----------------------------------------------------------------------------
149 grabCapability( Capability** )
151 (only externally visible when !RTS_SUPPORTS_THREADS. In the
152 threaded RTS, clients must use waitFor*Capability()).
153 ------------------------------------------------------------------------- */
155 #if defined(RTS_SUPPORTS_THREADS)
159 grabCapability( Capability** cap )
162 ASSERT(rts_n_free_capabilities > 0);
163 *cap = free_capabilities;
164 free_capabilities = (*cap)->link;
165 rts_n_free_capabilities--;
167 # if defined(RTS_SUPPORTS_THREADS)
168 ASSERT(rts_n_free_capabilities == 1);
169 rts_n_free_capabilities = 0;
171 *cap = &MainCapability;
173 #if defined(RTS_SUPPORTS_THREADS)
174 IF_DEBUG(scheduler, sched_belch("worker: got capability"));
178 /* ----------------------------------------------------------------------------
179 * Function: releaseCapability(Capability*)
181 * Purpose: Letting go of a capability. Causes a
182 * 'returning worker' thread or a 'waiting worker'
183 * to wake up, in that order.
184 * ------------------------------------------------------------------------- */
187 releaseCapability( Capability* cap UNUSED_IF_NOT_SMP )
189 // Precondition: sched_mutex is held.
190 #if defined(RTS_SUPPORTS_THREADS)
192 ASSERT(rts_n_free_capabilities == 0);
195 cap->link = free_capabilities;
196 free_capabilities = cap;
198 // Check to see whether a worker thread can be given
199 // the go-ahead to return the result of an external call..
200 if (rts_n_waiting_workers > 0) {
201 // Decrement the counter here to avoid livelock where the
202 // thread that is yielding its capability will repeatedly
203 // signal returning_worker_cond.
205 rts_n_waiting_workers--;
206 signalCondition(&returning_worker_cond);
207 IF_DEBUG(scheduler, sched_belch("worker: released capability to returning worker"));
208 } else if (passingCapability) {
209 if (passTarget == NULL) {
210 signalCondition(&thread_ready_cond);
211 startSchedulerTaskIfNecessary();
213 signalCondition(passTarget);
215 rts_n_free_capabilities++;
216 IF_DEBUG(scheduler, sched_belch("worker: released capability, passing it"));
219 rts_n_free_capabilities++;
220 // Signal that a capability is available
221 if (rts_n_waiting_tasks > 0 && ANY_WORK_TO_DO()) {
222 signalCondition(&thread_ready_cond);
224 startSchedulerTaskIfNecessary();
225 IF_DEBUG(scheduler, sched_belch("worker: released capability"));
231 #if defined(RTS_SUPPORTS_THREADS)
233 * When a native thread has completed the execution of an external
234 * call, it needs to communicate the result back. This is done
237 * - in resumeThread(), the thread calls waitForReturnCapability().
238 * - If no capabilities are readily available, waitForReturnCapability()
239 * increments a counter rts_n_waiting_workers, and blocks
240 * waiting for the condition returning_worker_cond to become
242 * - upon entry to the Scheduler, a worker thread checks the
243 * value of rts_n_waiting_workers. If > 0, the worker thread
244 * will yield its capability to let a returning worker thread
245 * proceed with returning its result -- this is done via
246 * yieldToReturningWorker().
247 * - the worker thread that yielded its capability then tries
248 * to re-grab a capability and re-enter the Scheduler.
251 /* ----------------------------------------------------------------------------
252 * waitForReturnCapability( Mutext *pMutex, Capability** )
254 * Purpose: when an OS thread returns from an external call,
255 * it calls grabReturnCapability() (via Schedule.resumeThread())
256 * to wait for permissions to enter the RTS & communicate the
257 * result of the external call back to the Haskell thread that
260 * ------------------------------------------------------------------------- */
263 waitForReturnCapability( Mutex* pMutex, Capability** pCap )
265 // Pre-condition: pMutex is held.
268 sched_belch("worker: returning; workers waiting: %d",
269 rts_n_waiting_workers));
271 if ( noCapabilities() || passingCapability ) {
272 rts_n_waiting_workers++;
273 context_switch = 1; // make sure it's our turn soon
274 waitCondition(&returning_worker_cond, pMutex);
276 *pCap = free_capabilities;
277 free_capabilities = (*pCap)->link;
278 ASSERT(pCap != NULL);
280 *pCap = &MainCapability;
281 ASSERT(rts_n_free_capabilities == 0);
284 grabCapability(pCap);
287 // Post-condition: pMutex is held, pCap points to a capability
288 // which is now held by the current thread.
293 /* ----------------------------------------------------------------------------
294 * yieldCapability( Mutex* pMutex, Capability** pCap )
295 * ------------------------------------------------------------------------- */
298 yieldCapability( Capability** pCap )
300 // Pre-condition: pMutex is assumed held, the current thread
301 // holds the capability pointed to by pCap.
303 if ( rts_n_waiting_workers > 0 || passingCapability || !ANY_WORK_TO_DO()) {
305 if (rts_n_waiting_workers > 0) {
306 sched_belch("worker: giving up capability (returning wkr)");
307 } else if (passingCapability) {
308 sched_belch("worker: giving up capability (passing capability)");
310 sched_belch("worker: giving up capability (no threads to run)");
313 releaseCapability(*pCap);
317 // Post-condition: either:
319 // 1. *pCap is NULL, in which case the current thread does not
320 // hold a capability now, or
321 // 2. *pCap is not NULL, in which case the current thread still
322 // holds the capability.
328 /* ----------------------------------------------------------------------------
329 * waitForCapability( Mutex*, Capability**, Condition* )
331 * Purpose: wait for a Capability to become available. In
332 * the process of doing so, updates the number
333 * of tasks currently blocked waiting for a capability/more
334 * work. That counter is used when deciding whether or
335 * not to create a new worker thread when an external
337 * If pThreadCond is not NULL, a capability can be specifically
338 * passed to this thread using passCapability.
339 * ------------------------------------------------------------------------- */
342 waitForCapability( Mutex* pMutex, Capability** pCap, Condition* pThreadCond )
344 // Pre-condition: pMutex is held.
346 while ( noCapabilities() ||
347 (passingCapability && passTarget != pThreadCond) ||
350 sched_belch("worker: wait for capability (cond: %p)",
353 if (pThreadCond != NULL) {
354 waitCondition(pThreadCond, pMutex);
355 IF_DEBUG(scheduler, sched_belch("worker: get passed capability"));
357 rts_n_waiting_tasks++;
358 waitCondition(&thread_ready_cond, pMutex);
359 rts_n_waiting_tasks--;
360 IF_DEBUG(scheduler, sched_belch("worker: get normal capability"));
363 passingCapability = rtsFalse;
364 grabCapability(pCap);
366 // Post-condition: pMutex is held and *pCap is held by the current thread
370 /* ----------------------------------------------------------------------------
371 passCapability, passCapabilityToWorker
372 ------------------------------------------------------------------------- */
375 passCapability( Condition *pTargetThreadCond )
377 // Pre-condition: pMutex is held and cap is held by the current thread
379 passTarget = pTargetThreadCond;
380 passingCapability = rtsTrue;
381 IF_DEBUG(scheduler, sched_belch("worker: passCapability"));
383 // Post-condition: pMutex is held; cap is still held, but will be
384 // passed to the target thread when next released.
388 passCapabilityToWorker( void )
390 // Pre-condition: pMutex is held and cap is held by the current thread
393 passingCapability = rtsTrue;
394 IF_DEBUG(scheduler, sched_belch("worker: passCapabilityToWorker"));
396 // Post-condition: pMutex is held; cap is still held, but will be
397 // passed to a worker thread when next released.
400 #endif /* RTS_SUPPORTS_THREADS */
402 /* ----------------------------------------------------------------------------
405 Signals that a thread has been placed on the run queue, so a worker
406 might need to be woken up to run it.
408 ToDo: should check whether the thread at the front of the queue is
409 bound, and if so wake up the appropriate worker.
410 -------------------------------------------------------------------------- */
412 threadRunnable ( void )
414 #if defined(RTS_SUPPORTS_THREADS)
415 if ( !noCapabilities() && ANY_WORK_TO_DO() && rts_n_waiting_tasks > 0 ) {
416 signalCondition(&thread_ready_cond);
418 startSchedulerTaskIfNecessary();
423 /* ----------------------------------------------------------------------------
426 Wake up... time to die.
427 -------------------------------------------------------------------------- */
431 #if defined(RTS_SUPPORTS_THREADS)
432 signalCondition(&thread_ready_cond);