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