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