e098cb2cbd84695a0352dbfa14fcb9a5f31081dc
[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
25 #if !defined(SMP)
26 Capability MainCapability;     /* for non-SMP, we have one global capability */
27 #endif
28
29 nat rts_n_free_capabilities;
30
31 #if defined(RTS_SUPPORTS_THREADS)
32 /* returning_worker_cond: when a worker thread returns from executing an
33  * external call, it needs to wait for an RTS Capability before passing
34  * on the result of the call to the Haskell thread that made it.
35  * 
36  * returning_worker_cond is signalled in Capability.releaseCapability().
37  *
38  */
39 Condition returning_worker_cond = INIT_COND_VAR;
40
41 /*
42  * To avoid starvation of threads blocked on worker_thread_cond,
43  * the task(s) that enter the Scheduler will check to see whether
44  * there are one or more worker threads blocked waiting on
45  * returning_worker_cond.
46  */
47 static nat rts_n_waiting_workers = 0;
48
49 /* thread_ready_cond: when signalled, a thread has become runnable for a
50  * task to execute.
51  *
52  * In the non-SMP case, it also implies that the thread that is woken up has
53  * exclusive access to the RTS and all its data structures (that are not
54  * locked by the Scheduler's mutex).
55  *
56  * thread_ready_cond is signalled whenever COND_NO_THREADS_READY doesn't hold.
57  *
58  */
59 Condition thread_ready_cond = INIT_COND_VAR;
60 #if 0
61 /* For documentation purposes only */
62 #define COND_NO_THREADS_READY() (noCapabilities() || EMPTY_RUN_QUEUE())
63 #endif
64
65 /*
66  * To be able to make an informed decision about whether or not 
67  * to create a new task when making an external call, keep track of
68  * the number of tasks currently blocked waiting on thread_ready_cond.
69  * (if > 0 => no need for a new task, just unblock an existing one).
70  *
71  * waitForWorkCapability() takes care of keeping it up-to-date;
72  * Task.startTask() uses its current value.
73  */
74 nat rts_n_waiting_tasks = 0;
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 #endif
123
124 /* -----------------------------------------------------------------------------
125    Acquiring capabilities
126    -------------------------------------------------------------------------- */
127
128 /*
129  * Function:  grabCapability(Capability**)
130  * 
131  * Purpose:   the act of grabbing a capability is easy; just 
132  *            remove one from the free capabilities list (which
133  *            may just have one entry). In threaded builds, worker
134  *            threads are prevented from doing so willy-nilly
135  *            via the condition variables thread_ready_cond and
136  *            returning_worker_cond.
137  *
138  */ 
139 void grabCapability(Capability** cap)
140 {
141 #if !defined(SMP)
142   rts_n_free_capabilities = 0;
143   *cap = &MainCapability;
144 #else
145   *cap = free_capabilities;
146   free_capabilities = (*cap)->link;
147   rts_n_free_capabilities--;
148 #endif
149 }
150
151 /*
152  * Function:  releaseCapability(Capability*)
153  *
154  * Purpose:   Letting go of a capability. Causes a
155  *            'returning worker' thread or a 'waiting worker'
156  *            to wake up, in that order.
157  *
158  */
159 void releaseCapability(Capability* cap
160 #if !defined(SMP)
161                        STG_UNUSED
162 #endif
163 )
164 {
165 #if defined(SMP)
166   cap->link = free_capabilities;
167   free_capabilities = cap;
168   rts_n_free_capabilities++;
169 #else
170   rts_n_free_capabilities = 1;
171 #endif
172
173 #if defined(RTS_SUPPORTS_THREADS)
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     rts_n_waiting_workers--;
182     signalCondition(&returning_worker_cond);
183   } else if ( !EMPTY_RUN_QUEUE() ) {
184     /* Signal that work is available */
185     signalCondition(&thread_ready_cond);
186   }
187 #endif
188   return;
189 }
190
191 #if defined(RTS_SUPPORTS_THREADS)
192 /*
193  * When a native thread has completed the execution of an external
194  * call, it needs to communicate the result back. This is done
195  * as follows:
196  *
197  *  - in resumeThread(), the thread calls grabReturnCapability().
198  *  - If no capabilities are readily available, grabReturnCapability()
199  *    increments a counter rts_n_waiting_workers, and blocks
200  *    waiting for the condition returning_worker_cond to become
201  *    signalled.
202  *  - upon entry to the Scheduler, a worker thread checks the
203  *    value of rts_n_waiting_workers. If > 0, the worker thread
204  *    will yield its capability to let a returning worker thread
205  *    proceed with returning its result -- this is done via
206  *    yieldToReturningWorker().
207  *  - the worker thread that yielded its capability then tries
208  *    to re-grab a capability and re-enter the Scheduler.
209  */
210
211 /*
212  * Function: grabReturnCapability(Capability**)
213  *
214  * Purpose:  when an OS thread returns from an external call,
215  * it calls grabReturnCapability() (via Schedule.resumeThread())
216  * to wait for permissions to enter the RTS & communicate the
217  * result of the external call back to the Haskell thread that
218  * made it.
219  *
220  * Pre-condition:  pMutex is held.
221  * Post-condition: pMutex is still held and a capability has
222  *                 been assigned to the worker thread.
223  */
224 void
225 grabReturnCapability(Mutex* pMutex, Capability** pCap)
226 {
227   IF_DEBUG(scheduler,
228            fprintf(stderr,"worker (%ld): returning, waiting for lock.\n", osThreadId()));
229   rts_n_waiting_workers++;
230   IF_DEBUG(scheduler,
231            fprintf(stderr,"worker (%ld): returning; workers waiting: %d\n",
232                    osThreadId(), rts_n_waiting_workers));
233   while ( noCapabilities() ) {
234     waitCondition(&returning_worker_cond, pMutex);
235   }
236   
237   grabCapability(pCap);
238   return;
239 }
240
241
242 /* -----------------------------------------------------------------------------
243    Yielding/waiting for capabilities
244    -------------------------------------------------------------------------- */
245
246 /*
247  * Function: yieldToReturningWorker(Mutex*,Capability*)
248  *
249  * Purpose:  when, upon entry to the Scheduler, an OS worker thread
250  *           spots that one or more threads are blocked waiting for
251  *           permission to return back their result, it gives up
252  *           its Capability. 
253  *
254  * Pre-condition:  pMutex is assumed held and the thread possesses
255  *                 a Capability.
256  * Post-condition: pMutex isn't held and the Capability has
257  *                 been given back.
258  */
259 void
260 yieldToReturningWorker(Mutex* pMutex, Capability** pCap)
261 {
262   if ( rts_n_waiting_workers > 0 && noCapabilities() ) {
263     IF_DEBUG(scheduler,
264              fprintf(stderr,"worker thread (%ld): giving up RTS token\n", osThreadId()));
265     releaseCapability(*pCap);
266     /* And wait for work */
267     waitForWorkCapability(pMutex, pCap, rtsFalse);
268   }
269   return;
270 }
271
272
273 /*
274  * Function: waitForWorkCapability(Mutex*, Capability**, rtsBool)
275  *
276  * Purpose:  wait for a Capability to become available. In
277  *           the process of doing so, updates the number
278  *           of tasks currently blocked waiting for a capability/more
279  *           work. That counter is used when deciding whether or
280  *           not to create a new worker thread when an external
281  *           call is made.
282  *
283  * Pre-condition: pMutex is held.
284  */
285 void 
286 waitForWorkCapability(Mutex* pMutex, Capability** pCap, rtsBool runnable)
287 {
288   while ( noCapabilities() || (runnable && EMPTY_RUN_QUEUE()) ) {
289     rts_n_waiting_tasks++;
290     waitCondition(&thread_ready_cond, pMutex);
291     rts_n_waiting_tasks--;
292   }
293   grabCapability(pCap);
294   return;
295 }
296 #endif /* RTS_SUPPORTS_THREADS */
297
298 #if defined(SMP)
299 /*
300  * Function: initCapabilities_(nat)
301  *
302  * Purpose:  upon startup, allocate and fill in table
303  *           holding 'n' Capabilities. Only for SMP, since
304  *           it is the only build that supports multiple
305  *           capabilities within the RTS.
306  */
307 static void
308 initCapabilities_(nat n)
309 {
310   nat i;
311   Capability *cap, *prev;
312   cap  = NULL;
313   prev = NULL;
314   for (i = 0; i < n; i++) {
315     cap = stgMallocBytes(sizeof(Capability), "initCapabilities");
316     initCapability(cap);
317     cap->link = prev;
318     prev = cap;
319   }
320   free_capabilities = cap;
321   rts_n_free_capabilities = n;
322   IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Allocated %d capabilities\n", n_free_capabilities););
323 }
324 #endif /* SMP */
325