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