[project @ 2002-02-14 08:59:29 by sof]
[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, the threaded
14  * RTS and other non-threaded builds, there is one global capability,
15  * namely MainRegTable.
16  * 
17  * --------------------------------------------------------------------------*/
18 #include "PosixSource.h"
19 #include "Rts.h"
20 #include "Schedule.h"
21 #include "RtsUtils.h"
22 #include "Capability.h"
23
24 #if !defined(SMP)
25 Capability MainCapability;     /* for non-SMP, we have one global capability */
26 #endif
27
28 nat rts_n_free_capabilities;
29
30 #if defined(RTS_SUPPORTS_THREADS)
31 /* returning_worker_cond: when a worker thread returns from executing an
32  * external call, it needs to wait for an RTS Capability before passing
33  * on the result of the call to the Haskell thread that made it.
34  * 
35  * returning_worker_cond is signalled in Capability.releaseCapability().
36  *
37  */
38 Condition returning_worker_cond = INIT_COND_VAR;
39
40 /*
41  * To avoid starvation of threads blocked on worker_thread_cond,
42  * the task(s) that enter the Scheduler will check to see whether
43  * there are one or more worker threads blocked waiting on
44  * returning_worker_cond.
45  *
46  * Locks needed: sched_mutex
47  */
48 nat rts_n_waiting_workers = 0;
49 #endif
50
51 static
52 void
53 initCapability( Capability *cap )
54 {
55     cap->f.stgChk0         = (F_)__stg_chk_0;
56     cap->f.stgChk1         = (F_)__stg_chk_1;
57     cap->f.stgGCEnter1     = (F_)__stg_gc_enter_1;
58     cap->f.stgUpdatePAP    = (F_)__stg_update_PAP;
59 }
60
61 #ifdef SMP
62 static void initCapabilities_(nat n);
63 #endif
64
65 /* 
66  */
67 void
68 initCapabilities()
69 {
70 #if defined(RTS_SUPPORTS_THREADS)
71   initCondition(&returning_worker_cond);
72 #endif
73
74 #if defined(SMP)
75   initCapabilities_(RtsFlags.ParFlags.nNodes);
76 #else
77   initCapability(&MainCapability);
78   rts_n_free_capabilities = 1;
79 #endif
80
81   return;
82 }
83
84 /* Free capability list.
85  * Locks required: sched_mutex.
86  */
87 #if defined(SMP)
88 static Capability *free_capabilities; /* Available capabilities for running threads */
89 #endif
90
91 void grabCapability(Capability** cap)
92 {
93 #if !defined(SMP)
94   rts_n_free_capabilities = 0;
95   *cap = &MainCapability;
96 #else
97   *cap = free_capabilities;
98   free_capabilities = (*cap)->link;
99   rts_n_free_capabilities--;
100 #endif
101 }
102
103 /*
104  * Function:  releaseCapability(Capability*)
105  *
106  * Purpose:   Letting go of a capability.
107  *
108  * Pre-condition: sched_mutex is assumed held by current thread.
109  * Post-condition:
110  */
111 void releaseCapability(Capability* cap
112 #if !defined(SMP)
113                        STG_UNUSED
114 #endif
115 )
116 {
117 #if defined(SMP)
118   cap->link = free_capabilities;
119   free_capabilities = cap;
120   rts_n_free_capabilities++;
121 #else
122   rts_n_free_capabilities = 1;
123 #endif
124
125 #if defined(RTS_SUPPORTS_THREADS)
126   /* Check to see whether a worker thread can be given
127      the go-ahead to return the result of an external call..*/
128   if (rts_n_waiting_workers > 0) {
129     /* Decrement the counter here to avoid livelock where the
130      * thread that is yielding its capability will repeatedly
131      * signal returning_worker_cond.
132      */
133     rts_n_waiting_workers--;
134     signalCondition(&returning_worker_cond);
135   } else if ( !EMPTY_RUN_QUEUE() ) {
136     /* Signal that work is available */
137     signalCondition(&thread_ready_cond);
138   }
139 #endif
140   return;
141 }
142
143 #if defined(RTS_SUPPORTS_THREADS)
144 /*
145  * When a native thread has completed the execution of an external
146  * call, it needs to communicate the result back. This is done
147  * as follows:
148  *
149  *  - in resumeThread(), the thread calls grabReturnCapability().
150  *  - If no capabilities are readily available, grabReturnCapability()
151  *    increments a counter rts_n_waiting_workers, and blocks
152  *    waiting for the condition returning_worker_cond to become
153  *    signalled.
154  *  - upon entry to the Scheduler, a worker thread checks the
155  *    value of rts_n_waiting_workers. If > 0, the worker thread
156  *    will yield its capability to let a returning worker thread
157  *    proceed with returning its result -- this is done via
158  *    yieldCapability().
159  *  - the worker thread that yielded its capability then tries
160  *    to re-grab a capability and re-enter the Scheduler.
161  */
162
163 /*
164  * Function: grabReturnCapability(Capability**)
165  *
166  * Purpose:  when an OS thread returns from an external call,
167  * it calls grabReturningCapability() (via Schedule.resumeThread())
168  * to wait for permissions to enter the RTS & communicate the
169  * result of the ext. call back to the Haskell thread that
170  * made it.
171  *
172  * Pre-condition:  sched_mutex isn't held.
173  * Post-condition: sched_mutex is held and a capability has
174  *                 been assigned to the worker thread.
175  */
176 void
177 grabReturnCapability(Capability** pCap)
178 {
179   IF_DEBUG(scheduler,
180            fprintf(stderr,"worker (%ld): returning, waiting for sched. lock.\n", osThreadId()));
181   ACQUIRE_LOCK(&sched_mutex);
182   rts_n_waiting_workers++;
183   IF_DEBUG(scheduler,
184            fprintf(stderr,"worker (%ld): returning; workers waiting: %d\n",
185                    osThreadId(), rts_n_waiting_workers));
186   while ( noCapabilities() ) {
187     waitCondition(&returning_worker_cond, &sched_mutex);
188   }
189   
190   grabCapability(pCap);
191   return;
192 }
193
194 /*
195  * Function: yieldCapability(Capability**)
196  *
197  * Purpose:  when, upon entry to the Scheduler, an OS worker thread
198  *           spots that one or more threads are blocked waiting for
199  *           permission to return back their result, it gives up
200  *           its Capability. 
201  *
202  * Pre-condition:  sched_mutex is held and the thread possesses
203  *                 a Capability.
204  * Post-condition: sched_mutex isn't held and the Capability has
205  *                 been given back.
206  */
207 void
208 yieldCapability(Capability* cap)
209 {
210     IF_DEBUG(scheduler,
211              fprintf(stderr,"worker thread (%ld): giving up RTS token\n", osThreadId()));
212     releaseCapability(cap);
213     RELEASE_LOCK(&sched_mutex);
214     yieldThread();
215     /* At this point, sched_mutex has been given up & we've 
216      * forced a thread context switch. Guaranteed to be
217      * enough for the signalled worker thread to race
218      * ahead?
219      */
220     return;
221 }
222
223 #endif /* RTS_SUPPORTS_THREADS */
224
225 #if defined(SMP)
226 /*
227  * Function: initCapabilities_(nat)
228  *
229  * Purpose:  upon startup, allocate and fill in table
230  *           holding 'n' Capabilities. Only for SMP, since
231  *           it is the only build that supports multiple
232  *           capabilities within the RTS.
233  * 
234  * Pre-condition: sched_mutex is held.
235  *
236  */
237 static void
238 initCapabilities_(nat n)
239 {
240   nat i;
241   Capability *cap, *prev;
242   cap  = NULL;
243   prev = NULL;
244   for (i = 0; i < n; i++) {
245     cap = stgMallocBytes(sizeof(Capability), "initCapabilities");
246     initCapability(cap);
247     cap->link = prev;
248     prev = cap;
249   }
250   free_capabilities = cap;
251   rts_n_free_capabilities = n;
252   IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Allocated %d capabilities\n", n_free_capabilities););
253 }
254 #endif /* SMP */
255