3f01bf3d8898af3f86993b486e7479f73a0a3966
[ghc-hetmet.git] / rts / Capability.h
1 /* ---------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 2001-2006
4  *
5  * Capabilities
6  *
7  * A Capability holds all the state an OS thread/task needs to run
8  * Haskell code: its STG registers, a pointer to its TSO, a nursery
9  * etc. During STG execution, a pointer to the Capabilitity is kept in
10  * a register (BaseReg).
11  *
12  * Only in a THREADED_RTS build will there be multiple capabilities,
13  * in the non-threaded RTS there is one global capability, called
14  * MainCapability.
15  *
16  * --------------------------------------------------------------------------*/
17
18 #ifndef CAPABILITY_H
19 #define CAPABILITY_H
20
21 #include "sm/GC.h" // for evac_fn
22 #include "Task.h"
23 #include "Sparks.h"
24
25 BEGIN_RTS_PRIVATE
26
27 struct Capability_ {
28     // State required by the STG virtual machine when running Haskell
29     // code.  During STG execution, the BaseReg register always points
30     // to the StgRegTable of the current Capability (&cap->r).
31     StgFunTable f;
32     StgRegTable r;
33
34     nat no;  // capability number.
35
36     // The Task currently holding this Capability.  This task has
37     // exclusive access to the contents of this Capability (apart from
38     // returning_tasks_hd/returning_tasks_tl).
39     // Locks required: cap->lock.
40     Task *running_task;
41
42     // true if this Capability is running Haskell code, used for
43     // catching unsafe call-ins.
44     rtsBool in_haskell;
45
46     // true if this Capability is currently in the GC
47     rtsBool in_gc;
48
49     // The run queue.  The Task owning this Capability has exclusive
50     // access to its run queue, so can wake up threads without
51     // taking a lock, and the common path through the scheduler is
52     // also lock-free.
53     StgTSO *run_queue_hd;
54     StgTSO *run_queue_tl;
55
56     // Tasks currently making safe foreign calls.  Doubly-linked.
57     // When returning, a task first acquires the Capability before
58     // removing itself from this list, so that the GC can find all
59     // the suspended TSOs easily.  Hence, when migrating a Task from
60     // the returning_tasks list, we must also migrate its entry from
61     // this list.
62     Task *suspended_ccalling_tasks;
63
64     // One mutable list per generation, so we don't need to take any
65     // locks when updating an old-generation thunk.  This also lets us
66     // keep track of which closures this CPU has been mutating, so we
67     // can traverse them using the right thread during GC and avoid
68     // unnecessarily moving the data from one cache to another.
69     bdescr **mut_lists;
70     bdescr **saved_mut_lists; // tmp use during GC
71
72     // Context switch flag. We used to have one global flag, now one 
73     // per capability. Locks required  : none (conflicts are harmless)
74     int context_switch;
75
76 #if defined(THREADED_RTS)
77     // Worker Tasks waiting in the wings.  Singly-linked.
78     Task *spare_workers;
79
80     // This lock protects running_task, returning_tasks_{hd,tl}, wakeup_queue.
81     Mutex lock;
82
83     // Tasks waiting to return from a foreign call, or waiting to make
84     // a new call-in using this Capability (NULL if empty).
85     // NB. this field needs to be modified by tasks other than the
86     // running_task, so it requires cap->lock to modify.  A task can
87     // check whether it is NULL without taking the lock, however.
88     Task *returning_tasks_hd; // Singly-linked, with head/tail
89     Task *returning_tasks_tl;
90
91     // A list of threads to append to this Capability's run queue at
92     // the earliest opportunity.  These are threads that have been
93     // woken up by another Capability.
94     StgTSO *wakeup_queue_hd;
95     StgTSO *wakeup_queue_tl;
96
97     SparkPool *sparks;
98
99     // Stats on spark creation/conversion
100     nat sparks_created;
101     nat sparks_converted;
102     nat sparks_pruned;
103 #endif
104
105     // Per-capability STM-related data
106     StgTVarWatchQueue *free_tvar_watch_queues;
107     StgInvariantCheckQueue *free_invariant_check_queues;
108     StgTRecChunk *free_trec_chunks;
109     StgTRecHeader *free_trec_headers;
110     nat transaction_tokens;
111 } // typedef Capability is defined in RtsAPI.h
112   // Capabilities are stored in an array, so make sure that adjacent
113   // Capabilities don't share any cache-lines:
114 #ifndef mingw32_HOST_OS
115   ATTRIBUTE_ALIGNED(64)
116 #endif
117   ;
118
119
120 #if defined(THREADED_RTS)
121 #define ASSERT_TASK_ID(task) ASSERT(task->id == osThreadId())
122 #else
123 #define ASSERT_TASK_ID(task) /*empty*/
124 #endif
125
126 // These properties should be true when a Task is holding a Capability
127 #define ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task)                     \
128   ASSERT(cap->running_task != NULL && cap->running_task == task);       \
129   ASSERT(task->cap == cap);                                             \
130   ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task)
131
132 // Sometimes a Task holds a Capability, but the Task is not associated
133 // with that Capability (ie. task->cap != cap).  This happens when
134 // (a) a Task holds multiple Capabilities, and (b) when the current
135 // Task is bound, its thread has just blocked, and it may have been
136 // moved to another Capability.
137 #define ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task)  \
138   ASSERT(cap->run_queue_hd == END_TSO_QUEUE ?           \
139             cap->run_queue_tl == END_TSO_QUEUE : 1);    \
140   ASSERT(myTask() == task);                             \
141   ASSERT_TASK_ID(task);
142
143 // Converts a *StgRegTable into a *Capability.
144 //
145 INLINE_HEADER Capability *
146 regTableToCapability (StgRegTable *reg)
147 {
148     return (Capability *)((void *)((unsigned char*)reg - STG_FIELD_OFFSET(Capability,r)));
149 }
150
151 // Initialise the available capabilities.
152 //
153 void initCapabilities (void);
154
155 // Release a capability.  This is called by a Task that is exiting
156 // Haskell to make a foreign call, or in various other cases when we
157 // want to relinquish a Capability that we currently hold.
158 //
159 // ASSUMES: cap->running_task is the current Task.
160 //
161 #if defined(THREADED_RTS)
162 void releaseCapability           (Capability* cap);
163 void releaseAndWakeupCapability  (Capability* cap);
164 void releaseCapability_ (Capability* cap, rtsBool always_wakeup); 
165 // assumes cap->lock is held
166 #else
167 // releaseCapability() is empty in non-threaded RTS
168 INLINE_HEADER void releaseCapability  (Capability* cap STG_UNUSED) {};
169 INLINE_HEADER void releaseAndWakeupCapability  (Capability* cap STG_UNUSED) {};
170 INLINE_HEADER void releaseCapability_ (Capability* cap STG_UNUSED, 
171                                        rtsBool always_wakeup STG_UNUSED) {};
172 #endif
173
174 // declared in includes/rts/Threads.h:
175 // extern Capability MainCapability; 
176
177 // declared in includes/rts/Threads.h:
178 // extern nat n_capabilities;
179
180 // Array of all the capabilities
181 //
182 extern Capability *capabilities;
183
184 // The Capability that was last free.  Used as a good guess for where
185 // to assign new threads.
186 //
187 extern Capability *last_free_capability;
188
189 // GC indicator, in scope for the scheduler
190 #define PENDING_GC_SEQ 1
191 #define PENDING_GC_PAR 2
192 extern volatile StgWord waiting_for_gc;
193
194 // Acquires a capability at a return point.  If *cap is non-NULL, then
195 // this is taken as a preference for the Capability we wish to
196 // acquire.
197 //
198 // OS threads waiting in this function get priority over those waiting
199 // in waitForCapability().
200 //
201 // On return, *cap is non-NULL, and points to the Capability acquired.
202 //
203 void waitForReturnCapability (Capability **cap/*in/out*/, Task *task);
204
205 INLINE_HEADER void recordMutableCap (StgClosure *p, Capability *cap, nat gen);
206
207 #if defined(THREADED_RTS)
208
209 // Gives up the current capability IFF there is a higher-priority
210 // thread waiting for it.  This happens in one of two ways:
211 //
212 //   (a) we are passing the capability to another OS thread, so
213 //       that it can run a bound Haskell thread, or
214 //
215 //   (b) there is an OS thread waiting to return from a foreign call
216 //
217 // On return: *pCap is NULL if the capability was released.  The
218 // current task should then re-acquire it using waitForCapability().
219 //
220 void yieldCapability (Capability** pCap, Task *task);
221
222 // Acquires a capability for doing some work.
223 //
224 // On return: pCap points to the capability.
225 //
226 void waitForCapability (Task *task, Mutex *mutex, Capability **pCap);
227
228 // Wakes up a thread on a Capability (probably a different Capability
229 // from the one held by the current Task).
230 //
231 void wakeupThreadOnCapability (Capability *my_cap, Capability *other_cap,
232                                StgTSO *tso);
233
234 // Wakes up a worker thread on just one Capability, used when we
235 // need to service some global event.
236 //
237 void prodOneCapability (void);
238 void prodCapability (Capability *cap, Task *task);
239
240 // Similar to prodOneCapability(), but prods all of them.
241 //
242 void prodAllCapabilities (void);
243
244 // Waits for a capability to drain of runnable threads and workers,
245 // and then acquires it.  Used at shutdown time.
246 //
247 void shutdownCapability (Capability *cap, Task *task, rtsBool wait_foreign);
248
249 // Attempt to gain control of a Capability if it is free.
250 //
251 rtsBool tryGrabCapability (Capability *cap, Task *task);
252
253 // Try to find a spark to run
254 //
255 StgClosure *findSpark (Capability *cap);
256
257 // True if any capabilities have sparks
258 //
259 rtsBool anySparks (void);
260
261 INLINE_HEADER rtsBool emptySparkPoolCap (Capability *cap);
262 INLINE_HEADER nat     sparkPoolSizeCap  (Capability *cap);
263 INLINE_HEADER void    discardSparksCap  (Capability *cap);
264
265 #else // !THREADED_RTS
266
267 // Grab a capability.  (Only in the non-threaded RTS; in the threaded
268 // RTS one of the waitFor*Capability() functions must be used).
269 //
270 extern void grabCapability (Capability **pCap);
271
272 #endif /* !THREADED_RTS */
273
274 // cause all capabilities to context switch as soon as possible.
275 void setContextSwitches(void);
276 INLINE_HEADER void contextSwitchCapability(Capability *cap);
277
278 // Free all capabilities
279 void freeCapabilities (void);
280
281 // For the GC:
282 void markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta, 
283                            rtsBool prune_sparks);
284 void markCapabilities (evac_fn evac, void *user);
285 void traverseSparkQueues (evac_fn evac, void *user);
286
287 /* -----------------------------------------------------------------------------
288  * INLINE functions... private below here
289  * -------------------------------------------------------------------------- */
290
291 INLINE_HEADER void
292 recordMutableCap (StgClosure *p, Capability *cap, nat gen)
293 {
294     bdescr *bd;
295
296     // We must own this Capability in order to modify its mutable list.
297     ASSERT(cap->running_task == myTask());
298     bd = cap->mut_lists[gen];
299     if (bd->free >= bd->start + BLOCK_SIZE_W) {
300         bdescr *new_bd;
301         new_bd = allocBlock_lock();
302         new_bd->link = bd;
303         bd = new_bd;
304         cap->mut_lists[gen] = bd;
305     }
306     *bd->free++ = (StgWord)p;
307 }
308
309 #if defined(THREADED_RTS)
310 INLINE_HEADER rtsBool
311 emptySparkPoolCap (Capability *cap) 
312 { return looksEmpty(cap->sparks); }
313
314 INLINE_HEADER nat
315 sparkPoolSizeCap (Capability *cap) 
316 { return sparkPoolSize(cap->sparks); }
317
318 INLINE_HEADER void
319 discardSparksCap (Capability *cap) 
320 { return discardSparks(cap->sparks); }
321 #endif
322
323 INLINE_HEADER void
324 contextSwitchCapability (Capability *cap)
325 {
326     // setting HpLim to NULL ensures that the next heap check will
327     // fail, and the thread will return to the scheduler.
328     cap->r.rHpLim = NULL;
329     // But just in case it didn't work (the target thread might be
330     // modifying HpLim at the same time), we set the end-of-block
331     // context-switch flag too:
332     cap->context_switch = 1;
333 }
334
335 END_RTS_PRIVATE
336
337 #endif /* CAPABILITY_H */