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() */
24 #include "Signals.h" /* to get at handleSignalsInThisThread() */
27 Capability MainCapability; /* for non-SMP, we have one global capability */
30 nat rts_n_free_capabilities;
32 #if defined(RTS_SUPPORTS_THREADS)
33 /* returning_worker_cond: when a worker thread returns from executing an
34 * external call, it needs to wait for an RTS Capability before passing
35 * on the result of the call to the Haskell thread that made it.
37 * returning_worker_cond is signalled in Capability.releaseCapability().
40 Condition returning_worker_cond = INIT_COND_VAR;
43 * To avoid starvation of threads blocked on worker_thread_cond,
44 * the task(s) that enter the Scheduler will check to see whether
45 * there are one or more worker threads blocked waiting on
46 * returning_worker_cond.
48 nat rts_n_waiting_workers = 0;
50 /* thread_ready_cond: when signalled, a thread has become runnable for a
53 * In the non-SMP case, it also implies that the thread that is woken up has
54 * exclusive access to the RTS and all its data structures (that are not
55 * locked by the Scheduler's mutex).
57 * thread_ready_cond is signalled whenever noCapabilities doesn't hold.
60 Condition thread_ready_cond = INIT_COND_VAR;
63 * To be able to make an informed decision about whether or not
64 * to create a new task when making an external call, keep track of
65 * the number of tasks currently blocked waiting on thread_ready_cond.
66 * (if > 0 => no need for a new task, just unblock an existing one).
68 * waitForWorkCapability() takes care of keeping it up-to-date;
69 * Task.startTask() uses its current value.
71 nat rts_n_waiting_tasks = 0;
74 /* -----------------------------------------------------------------------------
76 -------------------------------------------------------------------------- */
79 initCapability( Capability *cap )
81 cap->f.stgGCEnter1 = (F_)__stg_gc_enter_1;
82 cap->f.stgGCFun = (F_)__stg_gc_fun;
86 static void initCapabilities_(nat n);
90 * Function: initCapabilities()
92 * Purpose: set up the Capability handling. For the SMP build,
93 * we keep a table of them, the size of which is
94 * controlled by the user via the RTS flag RtsFlags.ParFlags.nNodes
96 * Pre-conditions: no locks assumed held.
101 #if defined(RTS_SUPPORTS_THREADS)
102 initCondition(&returning_worker_cond);
103 initCondition(&thread_ready_cond);
107 initCapabilities_(RtsFlags.ParFlags.nNodes);
109 initCapability(&MainCapability);
110 rts_n_free_capabilities = 1;
117 /* Free capability list. */
118 static Capability *free_capabilities; /* Available capabilities for running threads */
119 static Capability *returning_capabilities;
120 /* Capabilities being passed to returning worker threads */
123 /* -----------------------------------------------------------------------------
124 Acquiring capabilities
125 -------------------------------------------------------------------------- */
128 * Function: grabCapability(Capability**)
130 * Purpose: the act of grabbing a capability is easy; just
131 * remove one from the free capabilities list (which
132 * may just have one entry). In threaded builds, worker
133 * threads are prevented from doing so willy-nilly
134 * via the condition variables thread_ready_cond and
135 * returning_worker_cond.
138 void grabCapability(Capability** cap)
140 #ifdef RTS_SUPPORTS_THREADS
141 ASSERT(rts_n_free_capabilities > 0);
144 rts_n_free_capabilities = 0;
145 *cap = &MainCapability;
146 handleSignalsInThisThread();
148 *cap = free_capabilities;
149 free_capabilities = (*cap)->link;
150 rts_n_free_capabilities--;
155 * Function: releaseCapability(Capability*)
157 * Purpose: Letting go of a capability. Causes a
158 * 'returning worker' thread or a 'waiting worker'
159 * to wake up, in that order.
162 void releaseCapability(Capability* cap
167 { // Precondition: sched_mutex must be held
168 #if defined(RTS_SUPPORTS_THREADS)
170 ASSERT(rts_n_free_capabilities == 0);
172 /* Check to see whether a worker thread can be given
173 the go-ahead to return the result of an external call..*/
174 if (rts_n_waiting_workers > 0) {
175 /* Decrement the counter here to avoid livelock where the
176 * thread that is yielding its capability will repeatedly
177 * signal returning_worker_cond.
180 // SMP variant untested
181 cap->link = returning_capabilities;
182 returning_capabilities = cap;
185 rts_n_waiting_workers--;
186 signalCondition(&returning_worker_cond);
187 } else /*if ( !EMPTY_RUN_QUEUE() )*/ {
189 cap->link = free_capabilities;
190 free_capabilities = cap;
191 rts_n_free_capabilities++;
193 rts_n_free_capabilities = 1;
195 /* Signal that a capability is available */
196 signalCondition(&thread_ready_cond);
202 #if defined(RTS_SUPPORTS_THREADS)
204 * When a native thread has completed the execution of an external
205 * call, it needs to communicate the result back. This is done
208 * - in resumeThread(), the thread calls grabReturnCapability().
209 * - If no capabilities are readily available, grabReturnCapability()
210 * increments a counter rts_n_waiting_workers, and blocks
211 * waiting for the condition returning_worker_cond to become
213 * - upon entry to the Scheduler, a worker thread checks the
214 * value of rts_n_waiting_workers. If > 0, the worker thread
215 * will yield its capability to let a returning worker thread
216 * proceed with returning its result -- this is done via
217 * yieldToReturningWorker().
218 * - the worker thread that yielded its capability then tries
219 * to re-grab a capability and re-enter the Scheduler.
223 * Function: grabReturnCapability(Capability**)
225 * Purpose: when an OS thread returns from an external call,
226 * it calls grabReturnCapability() (via Schedule.resumeThread())
227 * to wait for permissions to enter the RTS & communicate the
228 * result of the external call back to the Haskell thread that
231 * Pre-condition: pMutex is held.
232 * Post-condition: pMutex is still held and a capability has
233 * been assigned to the worker thread.
236 grabReturnCapability(Mutex* pMutex, Capability** pCap)
239 fprintf(stderr,"worker (%ld): returning, waiting for lock.\n", osThreadId()));
241 fprintf(stderr,"worker (%ld): returning; workers waiting: %d\n",
242 osThreadId(), rts_n_waiting_workers));
243 if ( noCapabilities() ) {
244 rts_n_waiting_workers++;
245 wakeBlockedWorkerThread();
246 context_switch = 1; // make sure it's our turn soon
247 waitCondition(&returning_worker_cond, pMutex);
249 *pCap = returning_capabilities;
250 returning_capabilities = (*pCap)->link;
252 *pCap = &MainCapability;
253 ASSERT(rts_n_free_capabilities == 0);
254 handleSignalsInThisThread();
257 grabCapability(pCap);
263 /* -----------------------------------------------------------------------------
264 Yielding/waiting for capabilities
265 -------------------------------------------------------------------------- */
268 * Function: yieldToReturningWorker(Mutex*,Capability*)
270 * Purpose: when, upon entry to the Scheduler, an OS worker thread
271 * spots that one or more threads are blocked waiting for
272 * permission to return back their result, it gives up
275 * Pre-condition: pMutex is assumed held and the thread possesses
277 * Post-condition: pMutex is held and the Capability has
281 yieldToReturningWorker(Mutex* pMutex, Capability** pCap)
283 if ( rts_n_waiting_workers > 0 ) {
285 fprintf(stderr,"worker thread (%p): giving up RTS token\n", osThreadId()));
286 releaseCapability(*pCap);
287 /* And wait for work */
288 waitForWorkCapability(pMutex, pCap, rtsFalse);
290 fprintf(stderr,"worker thread (%p): got back RTS token (after yieldToReturningWorker)\n",
298 * Function: waitForWorkCapability(Mutex*, Capability**, rtsBool)
300 * Purpose: wait for a Capability to become available. In
301 * the process of doing so, updates the number
302 * of tasks currently blocked waiting for a capability/more
303 * work. That counter is used when deciding whether or
304 * not to create a new worker thread when an external
307 * Pre-condition: pMutex is held.
308 * Post-condition: pMutex is held and *pCap is held by the current thread
311 waitForWorkCapability(Mutex* pMutex, Capability** pCap, rtsBool runnable)
313 while ( noCapabilities() || (runnable && EMPTY_RUN_QUEUE()) ) {
314 rts_n_waiting_tasks++;
315 waitCondition(&thread_ready_cond, pMutex);
316 rts_n_waiting_tasks--;
318 grabCapability(pCap);
322 #endif /* RTS_SUPPORTS_THREADS */
326 * Function: initCapabilities_(nat)
328 * Purpose: upon startup, allocate and fill in table
329 * holding 'n' Capabilities. Only for SMP, since
330 * it is the only build that supports multiple
331 * capabilities within the RTS.
334 initCapabilities_(nat n)
337 Capability *cap, *prev;
340 for (i = 0; i < n; i++) {
341 cap = stgMallocBytes(sizeof(Capability), "initCapabilities");
346 free_capabilities = cap;
347 rts_n_free_capabilities = n;
348 returning_capabilities = NULL;
349 IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Allocated %d capabilities\n", n_free_capabilities););