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