Make tidyProgram discard speculative specialisation rules
[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 #endif
130 // Total words allocated by this cap since rts start
131 W_ total_allocated;
132
133 // Per-capability STM-related data
134 StgTVarWatchQueue *free_tvar_watch_queues;
135 StgInvariantCheckQueue *free_invariant_check_queues;
136 StgTRecChunk *free_trec_chunks;
137 StgTRecHeader *free_trec_headers;
138 nat transaction_tokens;
139 } // typedef Capability is defined in RtsAPI.h
140 // We never want a Capability to overlap a cache line with anything
141 // else, so round it up to a cache line size:
142 #ifndef mingw32_HOST_OS
143 ATTRIBUTE_ALIGNED(64)
144 #endif
145 ;
146
147
148 #if defined(THREADED_RTS)
149 #define ASSERT_TASK_ID(task) ASSERT(task->id == osThreadId())
150 #else
151 #define ASSERT_TASK_ID(task) /*empty*/
152 #endif
153
154 // These properties should be true when a Task is holding a Capability
155 #define ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task) \
156 ASSERT(cap->running_task != NULL && cap->running_task == task); \
157 ASSERT(task->cap == cap); \
158 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task)
159
160 // Sometimes a Task holds a Capability, but the Task is not associated
161 // with that Capability (ie. task->cap != cap). This happens when
162 // (a) a Task holds multiple Capabilities, and (b) when the current
163 // Task is bound, its thread has just blocked, and it may have been
164 // moved to another Capability.
165 #define ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task) \
166 ASSERT(cap->run_queue_hd == END_TSO_QUEUE ? \
167 cap->run_queue_tl == END_TSO_QUEUE : 1); \
168 ASSERT(myTask() == task); \
169 ASSERT_TASK_ID(task);
170
171 #if defined(THREADED_RTS)
172 rtsBool checkSparkCountInvariant (void);
173 #endif
174
175 // Converts a *StgRegTable into a *Capability.
176 //
177 INLINE_HEADER Capability *
178 regTableToCapability (StgRegTable *reg)
179 {
180 return (Capability *)((void *)((unsigned char*)reg - STG_FIELD_OFFSET(Capability,r)));
181 }
182
183 // Initialise the available capabilities.
184 //
185 void initCapabilities (void);
186
187 // Add and initialise more Capabilities
188 //
189 void moreCapabilities (nat from, nat to);
190
191 // Release a capability. This is called by a Task that is exiting
192 // Haskell to make a foreign call, or in various other cases when we
193 // want to relinquish a Capability that we currently hold.
194 //
195 // ASSUMES: cap->running_task is the current Task.
196 //
197 #if defined(THREADED_RTS)
198 void releaseCapability (Capability* cap);
199 void releaseAndWakeupCapability (Capability* cap);
200 void releaseCapability_ (Capability* cap, rtsBool always_wakeup);
201 // assumes cap->lock is held
202 #else
203 // releaseCapability() is empty in non-threaded RTS
204 INLINE_HEADER void releaseCapability (Capability* cap STG_UNUSED) {};
205 INLINE_HEADER void releaseAndWakeupCapability (Capability* cap STG_UNUSED) {};
206 INLINE_HEADER void releaseCapability_ (Capability* cap STG_UNUSED,
207 rtsBool always_wakeup STG_UNUSED) {};
208 #endif
209
210 // declared in includes/rts/Threads.h:
211 // extern Capability MainCapability;
212
213 // declared in includes/rts/Threads.h:
214 // extern nat n_capabilities;
215 // extern nat enabled_capabilities;
216
217 // Array of all the capabilities
218 //
219 extern Capability **capabilities;
220
221 // The Capability that was last free. Used as a good guess for where
222 // to assign new threads.
223 //
224 extern Capability *last_free_capability;
225
226 //
227 // Indicates that the RTS wants to synchronise all the Capabilities
228 // for some reason. All Capabilities should stop and return to the
229 // scheduler.
230 //
231 #define SYNC_GC_SEQ 1
232 #define SYNC_GC_PAR 2
233 #define SYNC_OTHER 3
234 extern volatile StgWord pending_sync;
235
236 // Acquires a capability at a return point. If *cap is non-NULL, then
237 // this is taken as a preference for the Capability we wish to
238 // acquire.
239 //
240 // OS threads waiting in this function get priority over those waiting
241 // in waitForCapability().
242 //
243 // On return, *cap is non-NULL, and points to the Capability acquired.
244 //
245 void waitForReturnCapability (Capability **cap/*in/out*/, Task *task);
246
247 EXTERN_INLINE void recordMutableCap (StgClosure *p, Capability *cap, nat gen);
248
249 EXTERN_INLINE void recordClosureMutated (Capability *cap, StgClosure *p);
250
251 #if defined(THREADED_RTS)
252
253 // Gives up the current capability IFF there is a higher-priority
254 // thread waiting for it. This happens in one of two ways:
255 //
256 // (a) we are passing the capability to another OS thread, so
257 // that it can run a bound Haskell thread, or
258 //
259 // (b) there is an OS thread waiting to return from a foreign call
260 //
261 // On return: *pCap is NULL if the capability was released. The
262 // current task should then re-acquire it using waitForCapability().
263 //
264 rtsBool yieldCapability (Capability** pCap, Task *task, rtsBool gcAllowed);
265
266 // Acquires a capability for doing some work.
267 //
268 // On return: pCap points to the capability.
269 //
270 void waitForCapability (Task *task, Mutex *mutex, Capability **pCap);
271
272 // Wakes up a worker thread on just one Capability, used when we
273 // need to service some global event.
274 //
275 void prodOneCapability (void);
276 void prodCapability (Capability *cap, Task *task);
277
278 // Similar to prodOneCapability(), but prods all of them.
279 //
280 void prodAllCapabilities (void);
281
282 // Attempt to gain control of a Capability if it is free.
283 //
284 rtsBool tryGrabCapability (Capability *cap, Task *task);
285
286 // Try to find a spark to run
287 //
288 StgClosure *findSpark (Capability *cap);
289
290 // True if any capabilities have sparks
291 //
292 rtsBool anySparks (void);
293
294 INLINE_HEADER rtsBool emptySparkPoolCap (Capability *cap);
295 INLINE_HEADER nat sparkPoolSizeCap (Capability *cap);
296 INLINE_HEADER void discardSparksCap (Capability *cap);
297
298 #else // !THREADED_RTS
299
300 // Grab a capability. (Only in the non-threaded RTS; in the threaded
301 // RTS one of the waitFor*Capability() functions must be used).
302 //
303 extern void grabCapability (Capability **pCap);
304
305 #endif /* !THREADED_RTS */
306
307 // Waits for a capability to drain of runnable threads and workers,
308 // and then acquires it. Used at shutdown time.
309 //
310 void shutdownCapability (Capability *cap, Task *task, rtsBool wait_foreign);
311
312 // Shut down all capabilities.
313 //
314 void shutdownCapabilities(Task *task, rtsBool wait_foreign);
315
316 // cause all capabilities to context switch as soon as possible.
317 void contextSwitchAllCapabilities(void);
318 INLINE_HEADER void contextSwitchCapability(Capability *cap);
319
320 // cause all capabilities to stop running Haskell code and return to
321 // the scheduler as soon as possible.
322 void interruptAllCapabilities(void);
323 INLINE_HEADER void interruptCapability(Capability *cap);
324
325 // Free all capabilities
326 void freeCapabilities (void);
327
328 // For the GC:
329 void markCapability (evac_fn evac, void *user, Capability *cap,
330 rtsBool no_mark_sparks USED_IF_THREADS);
331
332 void markCapabilities (evac_fn evac, void *user);
333
334 void traverseSparkQueues (evac_fn evac, void *user);
335
336 /* -----------------------------------------------------------------------------
337 Messages
338 -------------------------------------------------------------------------- */
339
340 #ifdef THREADED_RTS
341
342 INLINE_HEADER rtsBool emptyInbox(Capability *cap);
343
344 #endif // THREADED_RTS
345
346 /* -----------------------------------------------------------------------------
347 * INLINE functions... private below here
348 * -------------------------------------------------------------------------- */
349
350 EXTERN_INLINE void
351 recordMutableCap (StgClosure *p, Capability *cap, nat gen)
352 {
353 bdescr *bd;
354
355 // We must own this Capability in order to modify its mutable list.
356 // ASSERT(cap->running_task == myTask());
357 // NO: assertion is violated by performPendingThrowTos()
358 bd = cap->mut_lists[gen];
359 if (bd->free >= bd->start + BLOCK_SIZE_W) {
360 bdescr *new_bd;
361 new_bd = allocBlock_lock();
362 new_bd->link = bd;
363 bd = new_bd;
364 cap->mut_lists[gen] = bd;
365 }
366 *bd->free++ = (StgWord)p;
367 }
368
369 EXTERN_INLINE void
370 recordClosureMutated (Capability *cap, StgClosure *p)
371 {
372 bdescr *bd;
373 bd = Bdescr((StgPtr)p);
374 if (bd->gen_no != 0) recordMutableCap(p,cap,bd->gen_no);
375 }
376
377
378 #if defined(THREADED_RTS)
379 INLINE_HEADER rtsBool
380 emptySparkPoolCap (Capability *cap)
381 { return looksEmpty(cap->sparks); }
382
383 INLINE_HEADER nat
384 sparkPoolSizeCap (Capability *cap)
385 { return sparkPoolSize(cap->sparks); }
386
387 INLINE_HEADER void
388 discardSparksCap (Capability *cap)
389 { discardSparks(cap->sparks); }
390 #endif
391
392 INLINE_HEADER void
393 stopCapability (Capability *cap)
394 {
395 // setting HpLim to NULL tries to make the next heap check will
396 // fail, which will cause the thread to return to the scheduler.
397 // It may not work - the thread might be updating HpLim itself
398 // at the same time - so we also have the context_switch/interrupted
399 // flags as a sticky way to tell the thread to stop.
400 cap->r.rHpLim = NULL;
401 }
402
403 INLINE_HEADER void
404 interruptCapability (Capability *cap)
405 {
406 stopCapability(cap);
407 cap->interrupt = 1;
408 }
409
410 INLINE_HEADER void
411 contextSwitchCapability (Capability *cap)
412 {
413 stopCapability(cap);
414 cap->context_switch = 1;
415 }
416
417 #ifdef THREADED_RTS
418
419 INLINE_HEADER rtsBool emptyInbox(Capability *cap)
420 {
421 return (cap->inbox == (Message*)END_TSO_QUEUE);
422 }
423
424 #endif
425
426 #include "EndPrivate.h"
427
428 #endif /* CAPABILITY_H */
429
430 // Local Variables:
431 // mode: C
432 // fill-column: 80
433 // indent-tabs-mode: nil
434 // c-basic-offset: 4
435 // buffer-file-coding-system: utf-8-unix
436 // End: