[project @ 2003-01-25 15:54:48 by wolfgang]
[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   ASSERT(rts_n_free_capabilities > 0);
141 #if !defined(SMP)
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 }
151
152 /*
153  * Function:  releaseCapability(Capability*)
154  *
155  * Purpose:   Letting go of a capability. Causes a
156  *            'returning worker' thread or a 'waiting worker'
157  *            to wake up, in that order.
158  *
159  */
160 void releaseCapability(Capability* cap
161 #if !defined(SMP)
162                        STG_UNUSED
163 #endif
164 )
165 {       // Precondition: sched_mutex must be held
166 #if defined(RTS_SUPPORTS_THREADS)
167 #ifndef SMP
168   ASSERT(rts_n_free_capabilities == 0);
169 #endif
170   /* Check to see whether a worker thread can be given
171      the go-ahead to return the result of an external call..*/
172   if (rts_n_waiting_workers > 0) {
173     /* Decrement the counter here to avoid livelock where the
174      * thread that is yielding its capability will repeatedly
175      * signal returning_worker_cond.
176      */
177 #if defined(SMP)
178         // SMP variant untested
179     cap->link = returning_capabilities;
180     returning_capabilities = cap;
181 #else
182 #endif
183     rts_n_waiting_workers--;
184     signalCondition(&returning_worker_cond);
185   } else /*if ( !EMPTY_RUN_QUEUE() )*/ {
186 #if defined(SMP)
187     cap->link = free_capabilities;
188     free_capabilities = cap;
189     rts_n_free_capabilities++;
190 #else
191     rts_n_free_capabilities = 1;
192 #endif
193     /* Signal that a capability is available */
194     signalCondition(&thread_ready_cond);
195   }
196 #endif
197  return;
198 }
199
200 #if defined(RTS_SUPPORTS_THREADS)
201 /*
202  * When a native thread has completed the execution of an external
203  * call, it needs to communicate the result back. This is done
204  * as follows:
205  *
206  *  - in resumeThread(), the thread calls grabReturnCapability().
207  *  - If no capabilities are readily available, grabReturnCapability()
208  *    increments a counter rts_n_waiting_workers, and blocks
209  *    waiting for the condition returning_worker_cond to become
210  *    signalled.
211  *  - upon entry to the Scheduler, a worker thread checks the
212  *    value of rts_n_waiting_workers. If > 0, the worker thread
213  *    will yield its capability to let a returning worker thread
214  *    proceed with returning its result -- this is done via
215  *    yieldToReturningWorker().
216  *  - the worker thread that yielded its capability then tries
217  *    to re-grab a capability and re-enter the Scheduler.
218  */
219
220 /*
221  * Function: grabReturnCapability(Capability**)
222  *
223  * Purpose:  when an OS thread returns from an external call,
224  * it calls grabReturnCapability() (via Schedule.resumeThread())
225  * to wait for permissions to enter the RTS & communicate the
226  * result of the external call back to the Haskell thread that
227  * made it.
228  *
229  * Pre-condition:  pMutex is held.
230  * Post-condition: pMutex is still held and a capability has
231  *                 been assigned to the worker thread.
232  */
233 void
234 grabReturnCapability(Mutex* pMutex, Capability** pCap)
235 {
236   IF_DEBUG(scheduler,
237            fprintf(stderr,"worker (%ld): returning, waiting for lock.\n", osThreadId()));
238   IF_DEBUG(scheduler,
239            fprintf(stderr,"worker (%ld): returning; workers waiting: %d\n",
240                    osThreadId(), rts_n_waiting_workers));
241   if ( noCapabilities() ) {
242     rts_n_waiting_workers++;
243     wakeBlockedWorkerThread();
244     context_switch = 1; // make sure it's our turn soon
245     waitCondition(&returning_worker_cond, pMutex);
246 #if defined(SMP)
247     *pCap = returning_capabilities;
248     returning_capabilities = (*pCap)->link;
249 #else
250     *pCap = &MainCapability;
251     ASSERT(rts_n_free_capabilities == 0);
252     handleSignalsInThisThread();
253 #endif
254   } else {
255     grabCapability(pCap);
256   }
257   return;
258 }
259
260
261 /* -----------------------------------------------------------------------------
262    Yielding/waiting for capabilities
263    -------------------------------------------------------------------------- */
264
265 /*
266  * Function: yieldToReturningWorker(Mutex*,Capability*)
267  *
268  * Purpose:  when, upon entry to the Scheduler, an OS worker thread
269  *           spots that one or more threads are blocked waiting for
270  *           permission to return back their result, it gives up
271  *           its Capability. 
272  *
273  * Pre-condition:  pMutex is assumed held and the thread possesses
274  *                 a Capability.
275  * Post-condition: pMutex is held and the Capability has
276  *                 been given back.
277  */
278 void
279 yieldToReturningWorker(Mutex* pMutex, Capability** pCap)
280 {
281   if ( rts_n_waiting_workers > 0 ) {
282     IF_DEBUG(scheduler,
283              fprintf(stderr,"worker thread (%p): giving up RTS token\n", osThreadId()));
284     releaseCapability(*pCap);
285         /* And wait for work */
286     waitForWorkCapability(pMutex, pCap, rtsFalse);
287     IF_DEBUG(scheduler,
288              fprintf(stderr,"worker thread (%p): got back RTS token (after yieldToReturningWorker)\n",
289                 osThreadId()));
290   }
291   return;
292 }
293
294
295 /*
296  * Function: waitForWorkCapability(Mutex*, Capability**, rtsBool)
297  *
298  * Purpose:  wait for a Capability to become available. In
299  *           the process of doing so, updates the number
300  *           of tasks currently blocked waiting for a capability/more
301  *           work. That counter is used when deciding whether or
302  *           not to create a new worker thread when an external
303  *           call is made.
304  *
305  * Pre-condition: pMutex is held.
306  * Post-condition: pMutex is held and *pCap is held by the current thread
307  */
308 void 
309 waitForWorkCapability(Mutex* pMutex, Capability** pCap, rtsBool runnable)
310 {
311   while ( noCapabilities() || (runnable && EMPTY_RUN_QUEUE()) ) {
312     rts_n_waiting_tasks++;
313     waitCondition(&thread_ready_cond, pMutex);
314     rts_n_waiting_tasks--;
315   }
316   grabCapability(pCap);
317   return;
318 }
319
320 #endif /* RTS_SUPPORTS_THREADS */
321
322 #if defined(SMP)
323 /*
324  * Function: initCapabilities_(nat)
325  *
326  * Purpose:  upon startup, allocate and fill in table
327  *           holding 'n' Capabilities. Only for SMP, since
328  *           it is the only build that supports multiple
329  *           capabilities within the RTS.
330  */
331 static void
332 initCapabilities_(nat n)
333 {
334   nat i;
335   Capability *cap, *prev;
336   cap  = NULL;
337   prev = NULL;
338   for (i = 0; i < n; i++) {
339     cap = stgMallocBytes(sizeof(Capability), "initCapabilities");
340     initCapability(cap);
341     cap->link = prev;
342     prev = cap;
343   }
344   free_capabilities = cap;
345   rts_n_free_capabilities = n;
346   returning_capabilities = NULL;
347   IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Allocated %d capabilities\n", n_free_capabilities););
348 }
349 #endif /* SMP */
350