[project @ 2003-12-15 16:45:23 by simonmar]
[ghc-hetmet.git] / ghc / rts / Capability.c
1 /* ---------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 2002
4  *
5  * Capabilities
6  *
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).
12  *
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.
16  * 
17  * --------------------------------------------------------------------------*/
18 #include "PosixSource.h"
19 #include "Rts.h"
20 #include "RtsUtils.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() */
25
26 #if !defined(SMP)
27 Capability MainCapability;     /* for non-SMP, we have one global capability */
28 #endif
29
30 nat rts_n_free_capabilities;
31
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.
36  * 
37  * returning_worker_cond is signalled in Capability.releaseCapability().
38  *
39  */
40 Condition returning_worker_cond = INIT_COND_VAR;
41
42 /*
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.
47  */
48 nat rts_n_waiting_workers = 0;
49
50 /* thread_ready_cond: when signalled, a thread has become runnable for a
51  * task to execute.
52  *
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).
56  *
57  * thread_ready_cond is signalled whenever noCapabilities doesn't hold.
58  *
59  */
60 Condition thread_ready_cond = INIT_COND_VAR;
61
62 /*
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).
67  *
68  * waitForWorkCapability() takes care of keeping it up-to-date;
69  * Task.startTask() uses its current value.
70  */
71 nat rts_n_waiting_tasks = 0;
72
73 static Condition *passTarget = NULL;
74 static rtsBool passingCapability = rtsFalse;
75 #endif
76
77 /* -----------------------------------------------------------------------------
78    Initialisation
79    -------------------------------------------------------------------------- */
80 static
81 void
82 initCapability( Capability *cap )
83 {
84     cap->f.stgGCEnter1     = (F_)__stg_gc_enter_1;
85     cap->f.stgGCFun        = (F_)__stg_gc_fun;
86 }
87
88 #if defined(SMP)
89 static void initCapabilities_(nat n);
90 #endif
91
92 /* 
93  * Function:  initCapabilities()
94  *
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
98  *
99  * Pre-conditions: no locks assumed held.
100  */
101 void
102 initCapabilities()
103 {
104 #if defined(RTS_SUPPORTS_THREADS)
105   initCondition(&returning_worker_cond);
106   initCondition(&thread_ready_cond);
107 #endif
108
109 #if defined(SMP)
110   initCapabilities_(RtsFlags.ParFlags.nNodes);
111 #else
112   initCapability(&MainCapability);
113   rts_n_free_capabilities = 1;
114 #endif
115
116   return;
117 }
118
119 #if defined(SMP)
120 /* Free capability list. */
121 static Capability *free_capabilities; /* Available capabilities for running threads */
122 static Capability *returning_capabilities; 
123         /* Capabilities being passed to returning worker threads */
124 #endif
125
126 /* -----------------------------------------------------------------------------
127    Acquiring capabilities
128    -------------------------------------------------------------------------- */
129
130 /*
131  * Function:  grabCapability(Capability**)
132  * 
133  * Purpose:   the act of grabbing a capability is easy; just 
134  *            remove one from the free capabilities list (which
135  *            may just have one entry). In threaded builds, worker
136  *            threads are prevented from doing so willy-nilly
137  *            via the condition variables thread_ready_cond and
138  *            returning_worker_cond.
139  *
140  */ 
141 void grabCapability(Capability** cap)
142 {
143 #if !defined(SMP)
144   ASSERT(rts_n_free_capabilities == 1);
145   rts_n_free_capabilities = 0;
146   *cap = &MainCapability;
147   handleSignalsInThisThread();
148 #else
149   *cap = free_capabilities;
150   free_capabilities = (*cap)->link;
151   rts_n_free_capabilities--;
152 #endif
153   IF_DEBUG(scheduler, sched_belch("worker: got capability"));
154 }
155
156 /*
157  * Function:  releaseCapability(Capability*)
158  *
159  * Purpose:   Letting go of a capability. Causes a
160  *            'returning worker' thread or a 'waiting worker'
161  *            to wake up, in that order.
162  *
163  */
164 void releaseCapability(Capability* cap
165 #if !defined(SMP)
166                        STG_UNUSED
167 #endif
168 )
169 {       // Precondition: sched_mutex must be held
170 #if defined(RTS_SUPPORTS_THREADS)
171 #ifndef SMP
172   ASSERT(rts_n_free_capabilities == 0);
173 #endif
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.
180      */
181 #if defined(SMP)
182         // SMP variant untested
183     cap->link = returning_capabilities;
184     returning_capabilities = cap;
185 #else
186 #endif
187     rts_n_waiting_workers--;
188     signalCondition(&returning_worker_cond);
189     IF_DEBUG(scheduler, sched_belch("worker: released capability to returning worker"));
190   } else /*if ( !EMPTY_RUN_QUEUE() )*/ {
191 #if defined(SMP)
192     cap->link = free_capabilities;
193     free_capabilities = cap;
194     rts_n_free_capabilities++;
195 #else
196     rts_n_free_capabilities = 1;
197 #endif
198     /* Signal that a capability is available */
199     signalCondition(&thread_ready_cond);
200     startSchedulerTaskIfNecessary();  // if there is more work to be done,
201                                       // we'll need a new thread
202     IF_DEBUG(scheduler, sched_belch("worker: released capability"));
203   }
204 #endif
205   return;
206 }
207
208 #if defined(RTS_SUPPORTS_THREADS)
209 /*
210  * When a native thread has completed the execution of an external
211  * call, it needs to communicate the result back. This is done
212  * as follows:
213  *
214  *  - in resumeThread(), the thread calls grabReturnCapability().
215  *  - If no capabilities are readily available, grabReturnCapability()
216  *    increments a counter rts_n_waiting_workers, and blocks
217  *    waiting for the condition returning_worker_cond to become
218  *    signalled.
219  *  - upon entry to the Scheduler, a worker thread checks the
220  *    value of rts_n_waiting_workers. If > 0, the worker thread
221  *    will yield its capability to let a returning worker thread
222  *    proceed with returning its result -- this is done via
223  *    yieldToReturningWorker().
224  *  - the worker thread that yielded its capability then tries
225  *    to re-grab a capability and re-enter the Scheduler.
226  */
227
228 /*
229  * Function: grabReturnCapability(Capability**)
230  *
231  * Purpose:  when an OS thread returns from an external call,
232  * it calls grabReturnCapability() (via Schedule.resumeThread())
233  * to wait for permissions to enter the RTS & communicate the
234  * result of the external call back to the Haskell thread that
235  * made it.
236  *
237  * Pre-condition:  pMutex is held.
238  * Post-condition: pMutex is still held and a capability has
239  *                 been assigned to the worker thread.
240  */
241 void
242 grabReturnCapability(Mutex* pMutex, Capability** pCap)
243 {
244   IF_DEBUG(scheduler, 
245            sched_belch("worker: returning; workers waiting: %d",
246                        rts_n_waiting_workers));
247   if ( noCapabilities() || passingCapability ) {
248     rts_n_waiting_workers++;
249     wakeBlockedWorkerThread();
250     context_switch = 1; // make sure it's our turn soon
251     waitCondition(&returning_worker_cond, pMutex);
252 #if defined(SMP)
253     *pCap = returning_capabilities;
254     returning_capabilities = (*pCap)->link;
255 #else
256     *pCap = &MainCapability;
257     ASSERT(rts_n_free_capabilities == 0);
258     handleSignalsInThisThread();
259 #endif
260   } else {
261     grabCapability(pCap);
262   }
263   return;
264 }
265
266
267 /* -----------------------------------------------------------------------------
268    Yielding/waiting for capabilities
269    -------------------------------------------------------------------------- */
270
271 /*
272  * Function: yieldToReturningWorker(Mutex*,Capability*,Condition*)
273  *
274  * Purpose:  when, upon entry to the Scheduler, an OS worker thread
275  *           spots that one or more threads are blocked waiting for
276  *           permission to return back their result, it gives up
277  *           its Capability.
278  *           Immediately afterwards, it tries to reaquire the Capabilty
279  *           using waitForWorkCapability.
280  *
281  *
282  * Pre-condition:  pMutex is assumed held and the thread possesses
283  *                 a Capability.
284  * Post-condition: pMutex is held and the thread possesses
285  *                 a Capability.
286  */
287 void
288 yieldToReturningWorker(Mutex* pMutex, Capability** pCap, Condition* pThreadCond)
289 {
290   if ( rts_n_waiting_workers > 0 ) {
291     IF_DEBUG(scheduler, sched_belch("worker: giving up capability"));
292     releaseCapability(*pCap);
293         /* And wait for work */
294     waitForWorkCapability(pMutex, pCap, pThreadCond);
295     IF_DEBUG(scheduler,
296              sched_belch("worker: got back capability (after yieldToReturningWorker)"));
297   }
298   return;
299 }
300
301
302 /*
303  * Function: waitForWorkCapability(Mutex*, Capability**, Condition*)
304  *
305  * Purpose:  wait for a Capability to become available. In
306  *           the process of doing so, updates the number
307  *           of tasks currently blocked waiting for a capability/more
308  *           work. That counter is used when deciding whether or
309  *           not to create a new worker thread when an external
310  *           call is made.
311  *           If pThreadCond is not NULL, a capability can be specifically
312  *           passed to this thread using passCapability.
313  *
314  * Pre-condition: pMutex is held.
315  * Post-condition: pMutex is held and *pCap is held by the current thread
316  */
317  
318 void 
319 waitForWorkCapability(Mutex* pMutex, Capability** pCap, Condition* pThreadCond)
320 {
321 #ifdef SMP
322   #error SMP version not implemented
323 #endif
324   while ( noCapabilities() || (passingCapability && passTarget != pThreadCond)) {
325     IF_DEBUG(scheduler,
326              sched_belch("worker: wait for capability (cond: %p)",
327                          pThreadCond));
328     if(pThreadCond)
329     {
330       waitCondition(pThreadCond, pMutex);
331       IF_DEBUG(scheduler, sched_belch("worker: get passed capability"));
332     }
333     else
334     {
335       rts_n_waiting_tasks++;
336       waitCondition(&thread_ready_cond, pMutex);
337       rts_n_waiting_tasks--;
338       IF_DEBUG(scheduler, sched_belch("worker: get normal capability"));
339     }
340   }
341   passingCapability = rtsFalse;
342   grabCapability(pCap);
343   return;
344 }
345
346 /*
347  * Function: passCapability(Mutex*, Capability*, Condition*)
348  *
349  * Purpose:  Let go of the capability and make sure the thread associated
350  *           with the Condition pTargetThreadCond gets it next.
351  *
352  * Pre-condition: pMutex is held and cap is held by the current thread
353  * Post-condition: pMutex is held; cap will be grabbed by the "target"
354  *                 thread when pMutex is released.
355  */
356
357 void
358 passCapability(Mutex* pMutex, Capability* cap, Condition *pTargetThreadCond)
359 {
360 #ifdef SMP
361   #error SMP version not implemented
362 #endif
363     ASSERT(rts_n_free_capabilities == 0);
364     rts_n_free_capabilities = 1;
365     signalCondition(pTargetThreadCond);
366     passTarget = pTargetThreadCond;
367     passingCapability = rtsTrue;
368     IF_DEBUG(scheduler, sched_belch("worker: passCapability"));
369 }
370
371 /*
372  * Function: passCapabilityToWorker(Mutex*, Capability*)
373  *
374  * Purpose:  Let go of the capability and make sure that a
375  *           "plain" worker thread (not a bound thread) gets it next.
376  *
377  * Pre-condition: pMutex is held and cap is held by the current thread
378  * Post-condition: pMutex is held; cap will be grabbed by the "target"
379  *                 thread when pMutex is released.
380  */
381
382 void
383 passCapabilityToWorker(Mutex* pMutex, Capability* cap)
384 {
385 #ifdef SMP
386   #error SMP version not implemented
387 #endif
388     rts_n_free_capabilities = 1;
389     signalCondition(&thread_ready_cond);
390     startSchedulerTaskIfNecessary();
391     passTarget = NULL;
392     passingCapability = rtsTrue;
393     IF_DEBUG(scheduler, sched_belch("worker: passCapabilityToWorker"));
394 }
395
396
397
398 #endif /* RTS_SUPPORTS_THREADS */
399
400 #if defined(SMP)
401 /*
402  * Function: initCapabilities_(nat)
403  *
404  * Purpose:  upon startup, allocate and fill in table
405  *           holding 'n' Capabilities. Only for SMP, since
406  *           it is the only build that supports multiple
407  *           capabilities within the RTS.
408  */
409 static void
410 initCapabilities_(nat n)
411 {
412   nat i;
413   Capability *cap, *prev;
414   cap  = NULL;
415   prev = NULL;
416   for (i = 0; i < n; i++) {
417     cap = stgMallocBytes(sizeof(Capability), "initCapabilities");
418     initCapability(cap);
419     cap->link = prev;
420     prev = cap;
421   }
422   free_capabilities = cap;
423   rts_n_free_capabilities = n;
424   returning_capabilities = NULL;
425   IF_DEBUG(scheduler,
426            sched_belch("allocated %d capabilities", n_free_capabilities));
427 }
428 #endif /* SMP */
429