Fix regTableToCapability() if gcc introduces padding
[ghc-hetmet.git] / rts / Capability.h
1 /* ---------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 2001-2006
4  *
5  * Capabilities
6  *
7  * The notion of a capability is used when operating in multi-threaded
8  * environments (which the THREADED_RTS build of the RTS does), to
9  * hold all the state an OS thread/task needs to run Haskell code:
10  * its STG registers, a pointer to its  TSO, a nursery etc. During
11  * STG execution, a pointer to the capabilitity is kept in a 
12  * register (BaseReg).
13  *
14  * Only in an THREADED_RTS build will there be multiple capabilities,
15  * in the non-threaded builds there is one global capability, namely
16  * MainCapability.
17  *
18  * This header file contains the functions for working with capabilities.
19  * (the main, and only, consumer of this interface is the scheduler).
20  * 
21  * --------------------------------------------------------------------------*/
22
23 #ifndef CAPABILITY_H
24 #define CAPABILITY_H
25
26 #include "RtsFlags.h"
27 #include "Task.h"
28 #include "Sparks.h"
29
30 struct Capability_ {
31     // State required by the STG virtual machine when running Haskell
32     // code.  During STG execution, the BaseReg register always points
33     // to the StgRegTable of the current Capability (&cap->r).
34     StgFunTable f;
35     StgRegTable r GNU_ATTRIBUTE(packed);
36        // packed eliminates any padding between f and r.  Not strictly
37        // necessary, but it means the negative offsets for accessing
38        // the fields of f when we are in STG code are as small as
39        // possible.
40
41     nat no;  // capability number.
42
43     // The Task currently holding this Capability.  This task has
44     // exclusive access to the contents of this Capability (apart from
45     // returning_tasks_hd/returning_tasks_tl).
46     // Locks required: cap->lock.
47     Task *running_task;
48
49     // true if this Capability is running Haskell code, used for
50     // catching unsafe call-ins.
51     rtsBool in_haskell;
52
53     // The run queue.  The Task owning this Capability has exclusive
54     // access to its run queue, so can wake up threads without
55     // taking a lock, and the common path through the scheduler is
56     // also lock-free.
57     StgTSO *run_queue_hd;
58     StgTSO *run_queue_tl;
59
60     // Tasks currently making safe foreign calls.  Doubly-linked.
61     // When returning, a task first acquires the Capability before
62     // removing itself from this list, so that the GC can find all
63     // the suspended TSOs easily.  Hence, when migrating a Task from
64     // the returning_tasks list, we must also migrate its entry from
65     // this list.
66     Task *suspended_ccalling_tasks;
67
68     // One mutable list per generation, so we don't need to take any
69     // locks when updating an old-generation thunk.  These
70     // mini-mut-lists are moved onto the respective gen->mut_list at
71     // each GC.
72     bdescr **mut_lists;
73
74     // Context switch flag. We used to have one global flag, now one 
75     // per capability. Locks required  : none (conflicts are harmless)
76     int context_switch;
77
78 #if defined(THREADED_RTS)
79     // Worker Tasks waiting in the wings.  Singly-linked.
80     Task *spare_workers;
81
82     // This lock protects running_task, returning_tasks_{hd,tl}, wakeup_queue.
83     Mutex lock;
84
85     // Tasks waiting to return from a foreign call, or waiting to make
86     // a new call-in using this Capability (NULL if empty).
87     // NB. this field needs to be modified by tasks other than the
88     // running_task, so it requires cap->lock to modify.  A task can
89     // check whether it is NULL without taking the lock, however.
90     Task *returning_tasks_hd; // Singly-linked, with head/tail
91     Task *returning_tasks_tl;
92
93     // A list of threads to append to this Capability's run queue at
94     // the earliest opportunity.  These are threads that have been
95     // woken up by another Capability.
96     StgTSO *wakeup_queue_hd;
97     StgTSO *wakeup_queue_tl;
98
99     SparkPool *sparks;
100
101     // Stats on spark creation/conversion
102     nat sparks_created;
103     nat sparks_converted;
104     nat sparks_pruned;
105 #endif
106
107     // Per-capability STM-related data
108     StgTVarWatchQueue *free_tvar_watch_queues;
109     StgInvariantCheckQueue *free_invariant_check_queues;
110     StgTRecChunk *free_trec_chunks;
111     StgTRecHeader *free_trec_headers;
112     nat transaction_tokens;
113 } // typedef Capability is defined in RtsAPI.h
114   // Capabilities are stored in an array, so make sure that adjacent
115   // Capabilities don't share any cache-lines:
116 #ifndef mingw32_HOST_OS
117   ATTRIBUTE_ALIGNED(64)
118 #endif
119   ;
120
121
122 #if defined(THREADED_RTS)
123 #define ASSERT_TASK_ID(task) ASSERT(task->id == osThreadId())
124 #else
125 #define ASSERT_TASK_ID(task) /*empty*/
126 #endif
127
128 // These properties should be true when a Task is holding a Capability
129 #define ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task)                     \
130   ASSERT(cap->running_task != NULL && cap->running_task == task);       \
131   ASSERT(task->cap == cap);                                             \
132   ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task)
133
134 // Sometimes a Task holds a Capability, but the Task is not associated
135 // with that Capability (ie. task->cap != cap).  This happens when
136 // (a) a Task holds multiple Capabilities, and (b) when the current
137 // Task is bound, its thread has just blocked, and it may have been
138 // moved to another Capability.
139 #define ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task)  \
140   ASSERT(cap->run_queue_hd == END_TSO_QUEUE ?           \
141             cap->run_queue_tl == END_TSO_QUEUE : 1);    \
142   ASSERT(myTask() == task);                             \
143   ASSERT_TASK_ID(task);
144
145 // Converts a *StgRegTable into a *Capability.
146 //
147 #define OFFSET(s_type, field) ((size_t)&(((s_type*)0)->field))
148
149 INLINE_HEADER Capability *
150 regTableToCapability (StgRegTable *reg)
151 {
152     return (Capability *)((void *)((unsigned char*)reg - OFFSET(Capability,r)));
153 }
154
155 // Initialise the available capabilities.
156 //
157 void initCapabilities (void);
158
159 // Release a capability.  This is called by a Task that is exiting
160 // Haskell to make a foreign call, or in various other cases when we
161 // want to relinquish a Capability that we currently hold.
162 //
163 // ASSUMES: cap->running_task is the current Task.
164 //
165 #if defined(THREADED_RTS)
166 void releaseCapability           (Capability* cap);
167 void releaseAndWakeupCapability  (Capability* cap);
168 void releaseCapability_ (Capability* cap, rtsBool always_wakeup); 
169 // assumes cap->lock is held
170 #else
171 // releaseCapability() is empty in non-threaded RTS
172 INLINE_HEADER void releaseCapability  (Capability* cap STG_UNUSED) {};
173 INLINE_HEADER void releaseAndWakeupCapability  (Capability* cap STG_UNUSED) {};
174 INLINE_HEADER void releaseCapability_ (Capability* cap STG_UNUSED, 
175                                        rtsBool always_wakeup STG_UNUSED) {};
176 #endif
177
178 #if !IN_STG_CODE
179 // one global capability
180 extern Capability MainCapability; 
181 #endif
182
183 // Array of all the capabilities
184 //
185 extern nat n_capabilities;
186 extern Capability *capabilities;
187
188 // The Capability that was last free.  Used as a good guess for where
189 // to assign new threads.
190 //
191 extern Capability *last_free_capability;
192
193 // GC indicator, in scope for the scheduler
194 extern volatile StgWord waiting_for_gc;
195
196 // Acquires a capability at a return point.  If *cap is non-NULL, then
197 // this is taken as a preference for the Capability we wish to
198 // acquire.
199 //
200 // OS threads waiting in this function get priority over those waiting
201 // in waitForCapability().
202 //
203 // On return, *cap is non-NULL, and points to the Capability acquired.
204 //
205 void waitForReturnCapability (Capability **cap/*in/out*/, Task *task);
206
207 INLINE_HEADER void recordMutableCap (StgClosure *p, Capability *cap, nat gen);
208
209 #if defined(THREADED_RTS)
210
211 // Gives up the current capability IFF there is a higher-priority
212 // thread waiting for it.  This happens in one of two ways:
213 //
214 //   (a) we are passing the capability to another OS thread, so
215 //       that it can run a bound Haskell thread, or
216 //
217 //   (b) there is an OS thread waiting to return from a foreign call
218 //
219 // On return: *pCap is NULL if the capability was released.  The
220 // current task should then re-acquire it using waitForCapability().
221 //
222 void yieldCapability (Capability** pCap, Task *task);
223
224 // Acquires a capability for doing some work.
225 //
226 // On return: pCap points to the capability.
227 //
228 void waitForCapability (Task *task, Mutex *mutex, Capability **pCap);
229
230 // Wakes up a thread on a Capability (probably a different Capability
231 // from the one held by the current Task).
232 //
233 void wakeupThreadOnCapability (Capability *my_cap, Capability *other_cap,
234                                StgTSO *tso);
235
236 // Wakes up a worker thread on just one Capability, used when we
237 // need to service some global event.
238 //
239 void prodOneCapability (void);
240
241 // Similar to prodOneCapability(), but prods all of them.
242 //
243 void prodAllCapabilities (void);
244
245 // Waits for a capability to drain of runnable threads and workers,
246 // and then acquires it.  Used at shutdown time.
247 //
248 void shutdownCapability (Capability *cap, Task *task, rtsBool wait_foreign);
249
250 // Attempt to gain control of a Capability if it is free.
251 //
252 rtsBool tryGrabCapability (Capability *cap, Task *task);
253
254 // Try to find a spark to run
255 //
256 StgClosure *findSpark (Capability *cap);
257
258 // True if any capabilities have sparks
259 //
260 rtsBool anySparks (void);
261
262 INLINE_HEADER rtsBool emptySparkPoolCap (Capability *cap);
263 INLINE_HEADER nat     sparkPoolSizeCap  (Capability *cap);
264 INLINE_HEADER void    discardSparksCap  (Capability *cap);
265
266 #else // !THREADED_RTS
267
268 // Grab a capability.  (Only in the non-threaded RTS; in the threaded
269 // RTS one of the waitFor*Capability() functions must be used).
270 //
271 extern void grabCapability (Capability **pCap);
272
273 #endif /* !THREADED_RTS */
274
275 // cause all capabilities to context switch as soon as possible.
276 void setContextSwitches(void);
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 #endif /* CAPABILITY_H */