Comments about the let/app invariant
[ghc.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://ghc.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 // Has there been any activity on this Capability since the last GC?
50 nat idle;
51
52 rtsBool disabled;
53
54 // The run queue. The Task owning this Capability has exclusive
55 // access to its run queue, so can wake up threads without
56 // taking a lock, and the common path through the scheduler is
57 // also lock-free.
58 StgTSO *run_queue_hd;
59 StgTSO *run_queue_tl;
60
61 // Tasks currently making safe foreign calls. Doubly-linked.
62 // When returning, a task first acquires the Capability before
63 // removing itself from this list, so that the GC can find all
64 // the suspended TSOs easily. Hence, when migrating a Task from
65 // the returning_tasks list, we must also migrate its entry from
66 // this list.
67 InCall *suspended_ccalls;
68
69 // One mutable list per generation, so we don't need to take any
70 // locks when updating an old-generation thunk. This also lets us
71 // keep track of which closures this CPU has been mutating, so we
72 // can traverse them using the right thread during GC and avoid
73 // unnecessarily moving the data from one cache to another.
74 bdescr **mut_lists;
75 bdescr **saved_mut_lists; // tmp use during GC
76
77 // block for allocating pinned objects into
78 bdescr *pinned_object_block;
79 // full pinned object blocks allocated since the last GC
80 bdescr *pinned_object_blocks;
81
82 // per-capability weak pointer list associated with nursery (older
83 // lists stored in generation object)
84 StgWeak *weak_ptr_list_hd;
85 StgWeak *weak_ptr_list_tl;
86
87 // Context switch flag. When non-zero, this means: stop running
88 // Haskell code, and switch threads.
89 int context_switch;
90
91 // Interrupt flag. Like the context_switch flag, this also
92 // indicates that we should stop running Haskell code, but we do
93 // *not* switch threads. This is used to stop a Capability in
94 // order to do GC, for example.
95 //
96 // The interrupt flag is always reset before we start running
97 // Haskell code, unlike the context_switch flag which is only
98 // reset after we have executed the context switch.
99 int interrupt;
100
101 #if defined(THREADED_RTS)
102 // Worker Tasks waiting in the wings. Singly-linked.
103 Task *spare_workers;
104 nat n_spare_workers; // count of above
105
106 // This lock protects:
107 // running_task
108 // returning_tasks_{hd,tl}
109 // wakeup_queue
110 // inbox
111 Mutex lock;
112
113 // Tasks waiting to return from a foreign call, or waiting to make
114 // a new call-in using this Capability (NULL if empty).
115 // NB. this field needs to be modified by tasks other than the
116 // running_task, so it requires cap->lock to modify. A task can
117 // check whether it is NULL without taking the lock, however.
118 Task *returning_tasks_hd; // Singly-linked, with head/tail
119 Task *returning_tasks_tl;
120
121 // Messages, or END_TSO_QUEUE.
122 // Locks required: cap->lock
123 Message *inbox;
124
125 SparkPool *sparks;
126
127 // Stats on spark creation/conversion
128 SparkCounters spark_stats;
129 #if !defined(mingw32_HOST_OS)
130 // IO manager for this cap
131 int io_manager_control_wr_fd;
132 #endif
133 #endif
134 // Total words allocated by this cap since rts start
135 W_ total_allocated;
136
137 // Per-capability STM-related data
138 StgTVarWatchQueue *free_tvar_watch_queues;
139 StgInvariantCheckQueue *free_invariant_check_queues;
140 StgTRecChunk *free_trec_chunks;
141 StgTRecHeader *free_trec_headers;
142 nat transaction_tokens;
143 } // typedef Capability is defined in RtsAPI.h
144 // We never want a Capability to overlap a cache line with anything
145 // else, so round it up to a cache line size:
146 #ifndef mingw32_HOST_OS
147 ATTRIBUTE_ALIGNED(64)
148 #endif
149 ;
150
151
152 #if defined(THREADED_RTS)
153 #define ASSERT_TASK_ID(task) ASSERT(task->id == osThreadId())
154 #else
155 #define ASSERT_TASK_ID(task) /*empty*/
156 #endif
157
158 // These properties should be true when a Task is holding a Capability
159 #define ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task) \
160 ASSERT(cap->running_task != NULL && cap->running_task == task); \
161 ASSERT(task->cap == cap); \
162 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task)
163
164 // Sometimes a Task holds a Capability, but the Task is not associated
165 // with that Capability (ie. task->cap != cap). This happens when
166 // (a) a Task holds multiple Capabilities, and (b) when the current
167 // Task is bound, its thread has just blocked, and it may have been
168 // moved to another Capability.
169 #define ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task) \
170 ASSERT(cap->run_queue_hd == END_TSO_QUEUE ? \
171 cap->run_queue_tl == END_TSO_QUEUE : 1); \
172 ASSERT(myTask() == task); \
173 ASSERT_TASK_ID(task);
174
175 #if defined(THREADED_RTS)
176 rtsBool checkSparkCountInvariant (void);
177 #endif
178
179 // Converts a *StgRegTable into a *Capability.
180 //
181 INLINE_HEADER Capability *
182 regTableToCapability (StgRegTable *reg)
183 {
184 return (Capability *)((void *)((unsigned char*)reg - STG_FIELD_OFFSET(Capability,r)));
185 }
186
187 // Initialise the available capabilities.
188 //
189 void initCapabilities (void);
190
191 // Add and initialise more Capabilities
192 //
193 void moreCapabilities (nat from, nat to);
194
195 // Release a capability. This is called by a Task that is exiting
196 // Haskell to make a foreign call, or in various other cases when we
197 // want to relinquish a Capability that we currently hold.
198 //
199 // ASSUMES: cap->running_task is the current Task.
200 //
201 #if defined(THREADED_RTS)
202 void releaseCapability (Capability* cap);
203 void releaseAndWakeupCapability (Capability* cap);
204 void releaseCapability_ (Capability* cap, rtsBool always_wakeup);
205 // assumes cap->lock is held
206 #else
207 // releaseCapability() is empty in non-threaded RTS
208 INLINE_HEADER void releaseCapability (Capability* cap STG_UNUSED) {};
209 INLINE_HEADER void releaseAndWakeupCapability (Capability* cap STG_UNUSED) {};
210 INLINE_HEADER void releaseCapability_ (Capability* cap STG_UNUSED,
211 rtsBool always_wakeup STG_UNUSED) {};
212 #endif
213
214 // declared in includes/rts/Threads.h:
215 // extern Capability MainCapability;
216
217 // declared in includes/rts/Threads.h:
218 // extern nat n_capabilities;
219 // extern nat enabled_capabilities;
220
221 // Array of all the capabilities
222 //
223 extern Capability **capabilities;
224
225 // The Capability that was last free. Used as a good guess for where
226 // to assign new threads.
227 //
228 extern Capability *last_free_capability;
229
230 //
231 // Indicates that the RTS wants to synchronise all the Capabilities
232 // for some reason. All Capabilities should stop and return to the
233 // scheduler.
234 //
235 #define SYNC_GC_SEQ 1
236 #define SYNC_GC_PAR 2
237 #define SYNC_OTHER 3
238 extern volatile StgWord pending_sync;
239
240 // Acquires a capability at a return point. If *cap is non-NULL, then
241 // this is taken as a preference for the Capability we wish to
242 // acquire.
243 //
244 // OS threads waiting in this function get priority over those waiting
245 // in waitForCapability().
246 //
247 // On return, *cap is non-NULL, and points to the Capability acquired.
248 //
249 void waitForReturnCapability (Capability **cap/*in/out*/, Task *task);
250
251 EXTERN_INLINE void recordMutableCap (StgClosure *p, Capability *cap, nat gen);
252
253 EXTERN_INLINE void recordClosureMutated (Capability *cap, StgClosure *p);
254
255 #if defined(THREADED_RTS)
256
257 // Gives up the current capability IFF there is a higher-priority
258 // thread waiting for it. This happens in one of two ways:
259 //
260 // (a) we are passing the capability to another OS thread, so
261 // that it can run a bound Haskell thread, or
262 //
263 // (b) there is an OS thread waiting to return from a foreign call
264 //
265 // On return: *pCap is NULL if the capability was released. The
266 // current task should then re-acquire it using waitForCapability().
267 //
268 rtsBool yieldCapability (Capability** pCap, Task *task, rtsBool gcAllowed);
269
270 // Acquires a capability for doing some work.
271 //
272 // On return: pCap points to the capability.
273 //
274 void waitForCapability (Task *task, Mutex *mutex, Capability **pCap);
275
276 // Wakes up a worker thread on just one Capability, used when we
277 // need to service some global event.
278 //
279 void prodOneCapability (void);
280 void prodCapability (Capability *cap, Task *task);
281
282 // Similar to prodOneCapability(), but prods all of them.
283 //
284 void prodAllCapabilities (void);
285
286 // Attempt to gain control of a Capability if it is free.
287 //
288 rtsBool tryGrabCapability (Capability *cap, Task *task);
289
290 // Try to find a spark to run
291 //
292 StgClosure *findSpark (Capability *cap);
293
294 // True if any capabilities have sparks
295 //
296 rtsBool anySparks (void);
297
298 INLINE_HEADER rtsBool emptySparkPoolCap (Capability *cap);
299 INLINE_HEADER nat sparkPoolSizeCap (Capability *cap);
300 INLINE_HEADER void discardSparksCap (Capability *cap);
301
302 #else // !THREADED_RTS
303
304 // Grab a capability. (Only in the non-threaded RTS; in the threaded
305 // RTS one of the waitFor*Capability() functions must be used).
306 //
307 extern void grabCapability (Capability **pCap);
308
309 #endif /* !THREADED_RTS */
310
311 // Waits for a capability to drain of runnable threads and workers,
312 // and then acquires it. Used at shutdown time.
313 //
314 void shutdownCapability (Capability *cap, Task *task, rtsBool wait_foreign);
315
316 // Shut down all capabilities.
317 //
318 void shutdownCapabilities(Task *task, rtsBool wait_foreign);
319
320 // cause all capabilities to context switch as soon as possible.
321 void contextSwitchAllCapabilities(void);
322 INLINE_HEADER void contextSwitchCapability(Capability *cap);
323
324 // cause all capabilities to stop running Haskell code and return to
325 // the scheduler as soon as possible.
326 void interruptAllCapabilities(void);
327 INLINE_HEADER void interruptCapability(Capability *cap);
328
329 // Free all capabilities
330 void freeCapabilities (void);
331
332 // For the GC:
333 void markCapability (evac_fn evac, void *user, Capability *cap,
334 rtsBool no_mark_sparks USED_IF_THREADS);
335
336 void markCapabilities (evac_fn evac, void *user);
337
338 void traverseSparkQueues (evac_fn evac, void *user);
339
340 /* -----------------------------------------------------------------------------
341 Messages
342 -------------------------------------------------------------------------- */
343
344 #ifdef THREADED_RTS
345
346 INLINE_HEADER rtsBool emptyInbox(Capability *cap);
347
348 #endif // THREADED_RTS
349
350 /* -----------------------------------------------------------------------------
351 * INLINE functions... private below here
352 * -------------------------------------------------------------------------- */
353
354 EXTERN_INLINE void
355 recordMutableCap (StgClosure *p, Capability *cap, nat gen)
356 {
357 bdescr *bd;
358
359 // We must own this Capability in order to modify its mutable list.
360 // ASSERT(cap->running_task == myTask());
361 // NO: assertion is violated by performPendingThrowTos()
362 bd = cap->mut_lists[gen];
363 if (bd->free >= bd->start + BLOCK_SIZE_W) {
364 bdescr *new_bd;
365 new_bd = allocBlock_lock();
366 new_bd->link = bd;
367 bd = new_bd;
368 cap->mut_lists[gen] = bd;
369 }
370 *bd->free++ = (StgWord)p;
371 }
372
373 EXTERN_INLINE void
374 recordClosureMutated (Capability *cap, StgClosure *p)
375 {
376 bdescr *bd;
377 bd = Bdescr((StgPtr)p);
378 if (bd->gen_no != 0) recordMutableCap(p,cap,bd->gen_no);
379 }
380
381
382 #if defined(THREADED_RTS)
383 INLINE_HEADER rtsBool
384 emptySparkPoolCap (Capability *cap)
385 { return looksEmpty(cap->sparks); }
386
387 INLINE_HEADER nat
388 sparkPoolSizeCap (Capability *cap)
389 { return sparkPoolSize(cap->sparks); }
390
391 INLINE_HEADER void
392 discardSparksCap (Capability *cap)
393 { discardSparks(cap->sparks); }
394 #endif
395
396 INLINE_HEADER void
397 stopCapability (Capability *cap)
398 {
399 // setting HpLim to NULL tries to make the next heap check will
400 // fail, which will cause the thread to return to the scheduler.
401 // It may not work - the thread might be updating HpLim itself
402 // at the same time - so we also have the context_switch/interrupted
403 // flags as a sticky way to tell the thread to stop.
404 cap->r.rHpLim = NULL;
405 }
406
407 INLINE_HEADER void
408 interruptCapability (Capability *cap)
409 {
410 stopCapability(cap);
411 cap->interrupt = 1;
412 }
413
414 INLINE_HEADER void
415 contextSwitchCapability (Capability *cap)
416 {
417 stopCapability(cap);
418 cap->context_switch = 1;
419 }
420
421 #ifdef THREADED_RTS
422
423 INLINE_HEADER rtsBool emptyInbox(Capability *cap)
424 {
425 return (cap->inbox == (Message*)END_TSO_QUEUE);
426 }
427
428 #endif
429
430 #include "EndPrivate.h"
431
432 #endif /* CAPABILITY_H */