update submodules for GHC.HetMet.GArrow -> Control.GArrow renaming
[ghc-hetmet.git] / rts / Capability.h
1 /* ---------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 2001-2006
4  *
5  * Capabilities
6  *
7  * For details on the high-level design, see
8  *   http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Scheduler
9  *
10  * A Capability holds all the state an OS thread/task needs to run
11  * Haskell code: its STG registers, a pointer to its TSO, a nursery
12  * etc. During STG execution, a pointer to the Capabilitity is kept in
13  * a register (BaseReg).
14  *
15  * Only in a THREADED_RTS build will there be multiple capabilities,
16  * in the non-threaded RTS there is one global capability, called
17  * MainCapability.
18  *
19  * --------------------------------------------------------------------------*/
20
21 #ifndef CAPABILITY_H
22 #define CAPABILITY_H
23
24 #include "sm/GC.h" // for evac_fn
25 #include "Task.h"
26 #include "Sparks.h"
27
28 #include "BeginPrivate.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     InCall *suspended_ccalls;
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     // block for allocating pinned objects into
73     bdescr *pinned_object_block;
74
75     // Context switch flag. We used to have one global flag, now one 
76     // per capability. Locks required  : none (conflicts are harmless)
77     int context_switch;
78
79 #if defined(THREADED_RTS)
80     // Worker Tasks waiting in the wings.  Singly-linked.
81     Task *spare_workers;
82     nat n_spare_workers; // count of above
83
84     // This lock protects running_task, returning_tasks_{hd,tl}, wakeup_queue.
85     Mutex lock;
86
87     // Tasks waiting to return from a foreign call, or waiting to make
88     // a new call-in using this Capability (NULL if empty).
89     // NB. this field needs to be modified by tasks other than the
90     // running_task, so it requires cap->lock to modify.  A task can
91     // check whether it is NULL without taking the lock, however.
92     Task *returning_tasks_hd; // Singly-linked, with head/tail
93     Task *returning_tasks_tl;
94
95     // Messages, or END_TSO_QUEUE.
96     Message *inbox;
97
98     SparkPool *sparks;
99
100     // Stats on spark creation/conversion
101     nat sparks_created;
102     nat sparks_dud;
103     nat sparks_converted;
104     nat sparks_gcd;
105     nat sparks_fizzled;
106 #endif
107
108     // Per-capability STM-related data
109     StgTVarWatchQueue *free_tvar_watch_queues;
110     StgInvariantCheckQueue *free_invariant_check_queues;
111     StgTRecChunk *free_trec_chunks;
112     StgTRecHeader *free_trec_headers;
113     nat transaction_tokens;
114 } // typedef Capability is defined in RtsAPI.h
115   // Capabilities are stored in an array, so make sure that adjacent
116   // Capabilities don't share any cache-lines:
117 #ifndef mingw32_HOST_OS
118   ATTRIBUTE_ALIGNED(64)
119 #endif
120   ;
121
122
123 #if defined(THREADED_RTS)
124 #define ASSERT_TASK_ID(task) ASSERT(task->id == osThreadId())
125 #else
126 #define ASSERT_TASK_ID(task) /*empty*/
127 #endif
128
129 // These properties should be true when a Task is holding a Capability
130 #define ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task)                     \
131   ASSERT(cap->running_task != NULL && cap->running_task == task);       \
132   ASSERT(task->cap == cap);                                             \
133   ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task)
134
135 // Sometimes a Task holds a Capability, but the Task is not associated
136 // with that Capability (ie. task->cap != cap).  This happens when
137 // (a) a Task holds multiple Capabilities, and (b) when the current
138 // Task is bound, its thread has just blocked, and it may have been
139 // moved to another Capability.
140 #define ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task)  \
141   ASSERT(cap->run_queue_hd == END_TSO_QUEUE ?           \
142             cap->run_queue_tl == END_TSO_QUEUE : 1);    \
143   ASSERT(myTask() == task);                             \
144   ASSERT_TASK_ID(task);
145
146 // Converts a *StgRegTable into a *Capability.
147 //
148 INLINE_HEADER Capability *
149 regTableToCapability (StgRegTable *reg)
150 {
151     return (Capability *)((void *)((unsigned char*)reg - STG_FIELD_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 // declared in includes/rts/Threads.h:
178 // extern Capability MainCapability; 
179
180 // declared in includes/rts/Threads.h:
181 // extern nat n_capabilities;
182
183 // Array of all the capabilities
184 //
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 EXTERN_INLINE void recordMutableCap (StgClosure *p, Capability *cap, nat gen);
209
210 EXTERN_INLINE void recordClosureMutated (Capability *cap, StgClosure *p);
211
212 #if defined(THREADED_RTS)
213
214 // Gives up the current capability IFF there is a higher-priority
215 // thread waiting for it.  This happens in one of two ways:
216 //
217 //   (a) we are passing the capability to another OS thread, so
218 //       that it can run a bound Haskell thread, or
219 //
220 //   (b) there is an OS thread waiting to return from a foreign call
221 //
222 // On return: *pCap is NULL if the capability was released.  The
223 // current task should then re-acquire it using waitForCapability().
224 //
225 void yieldCapability (Capability** pCap, Task *task);
226
227 // Acquires a capability for doing some work.
228 //
229 // On return: pCap points to the capability.
230 //
231 void waitForCapability (Task *task, Mutex *mutex, Capability **pCap);
232
233 // Wakes up a worker thread on just one Capability, used when we
234 // need to service some global event.
235 //
236 void prodOneCapability (void);
237 void prodCapability (Capability *cap, Task *task);
238
239 // Similar to prodOneCapability(), but prods all of them.
240 //
241 void prodAllCapabilities (void);
242
243 // Attempt to gain control of a Capability if it is free.
244 //
245 rtsBool tryGrabCapability (Capability *cap, Task *task);
246
247 // Try to find a spark to run
248 //
249 StgClosure *findSpark (Capability *cap);
250
251 // True if any capabilities have sparks
252 //
253 rtsBool anySparks (void);
254
255 INLINE_HEADER rtsBool emptySparkPoolCap (Capability *cap);
256 INLINE_HEADER nat     sparkPoolSizeCap  (Capability *cap);
257 INLINE_HEADER void    discardSparksCap  (Capability *cap);
258
259 #else // !THREADED_RTS
260
261 // Grab a capability.  (Only in the non-threaded RTS; in the threaded
262 // RTS one of the waitFor*Capability() functions must be used).
263 //
264 extern void grabCapability (Capability **pCap);
265
266 #endif /* !THREADED_RTS */
267
268 // Waits for a capability to drain of runnable threads and workers,
269 // and then acquires it.  Used at shutdown time.
270 //
271 void shutdownCapability (Capability *cap, Task *task, rtsBool wait_foreign);
272
273 // Shut down all capabilities.
274 //
275 void shutdownCapabilities(Task *task, rtsBool wait_foreign);
276
277 // cause all capabilities to context switch as soon as possible.
278 void setContextSwitches(void);
279 INLINE_HEADER void contextSwitchCapability(Capability *cap);
280
281 // Free all capabilities
282 void freeCapabilities (void);
283
284 // For the GC:
285 void markCapability (evac_fn evac, void *user, Capability *cap,
286                      rtsBool no_mark_sparks USED_IF_THREADS);
287
288 void markCapabilities (evac_fn evac, void *user);
289
290 void traverseSparkQueues (evac_fn evac, void *user);
291
292 /* -----------------------------------------------------------------------------
293    Messages
294    -------------------------------------------------------------------------- */
295
296 #ifdef THREADED_RTS
297
298 INLINE_HEADER rtsBool emptyInbox(Capability *cap);;
299
300 #endif // THREADED_RTS
301
302 /* -----------------------------------------------------------------------------
303  * INLINE functions... private below here
304  * -------------------------------------------------------------------------- */
305
306 EXTERN_INLINE void
307 recordMutableCap (StgClosure *p, Capability *cap, nat gen)
308 {
309     bdescr *bd;
310
311     // We must own this Capability in order to modify its mutable list.
312     //    ASSERT(cap->running_task == myTask());
313     // NO: assertion is violated by performPendingThrowTos()
314     bd = cap->mut_lists[gen];
315     if (bd->free >= bd->start + BLOCK_SIZE_W) {
316         bdescr *new_bd;
317         new_bd = allocBlock_lock();
318         new_bd->link = bd;
319         bd = new_bd;
320         cap->mut_lists[gen] = bd;
321     }
322     *bd->free++ = (StgWord)p;
323 }
324
325 EXTERN_INLINE void
326 recordClosureMutated (Capability *cap, StgClosure *p)
327 {
328     bdescr *bd;
329     bd = Bdescr((StgPtr)p);
330     if (bd->gen_no != 0) recordMutableCap(p,cap,bd->gen_no);
331 }
332
333
334 #if defined(THREADED_RTS)
335 INLINE_HEADER rtsBool
336 emptySparkPoolCap (Capability *cap) 
337 { return looksEmpty(cap->sparks); }
338
339 INLINE_HEADER nat
340 sparkPoolSizeCap (Capability *cap) 
341 { return sparkPoolSize(cap->sparks); }
342
343 INLINE_HEADER void
344 discardSparksCap (Capability *cap) 
345 { return discardSparks(cap->sparks); }
346 #endif
347
348 INLINE_HEADER void
349 contextSwitchCapability (Capability *cap)
350 {
351     // setting HpLim to NULL ensures that the next heap check will
352     // fail, and the thread will return to the scheduler.
353     cap->r.rHpLim = NULL;
354     // But just in case it didn't work (the target thread might be
355     // modifying HpLim at the same time), we set the end-of-block
356     // context-switch flag too:
357     cap->context_switch = 1;
358 }
359
360 #ifdef THREADED_RTS
361
362 INLINE_HEADER rtsBool emptyInbox(Capability *cap)
363 {
364     return (cap->inbox == (Message*)END_TSO_QUEUE);
365 }
366
367 #endif
368
369 #include "EndPrivate.h"
370
371 #endif /* CAPABILITY_H */