rts: Don't use strndup
[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 // Total words allocated by this cap since rts start
102 // See [Note allocation accounting] in Storage.c
103 W_ total_allocated;
104
105 #if defined(THREADED_RTS)
106 // Worker Tasks waiting in the wings. Singly-linked.
107 Task *spare_workers;
108 nat n_spare_workers; // count of above
109
110 // This lock protects:
111 // running_task
112 // returning_tasks_{hd,tl}
113 // wakeup_queue
114 // inbox
115 Mutex lock;
116
117 // Tasks waiting to return from a foreign call, or waiting to make
118 // a new call-in using this Capability (NULL if empty).
119 // NB. this field needs to be modified by tasks other than the
120 // running_task, so it requires cap->lock to modify. A task can
121 // check whether it is NULL without taking the lock, however.
122 Task *returning_tasks_hd; // Singly-linked, with head/tail
123 Task *returning_tasks_tl;
124
125 // Messages, or END_TSO_QUEUE.
126 // Locks required: cap->lock
127 Message *inbox;
128
129 SparkPool *sparks;
130
131 // Stats on spark creation/conversion
132 SparkCounters spark_stats;
133 #if !defined(mingw32_HOST_OS)
134 // IO manager for this cap
135 int io_manager_control_wr_fd;
136 #endif
137 #endif
138
139 // Per-capability STM-related data
140 StgTVarWatchQueue *free_tvar_watch_queues;
141 StgInvariantCheckQueue *free_invariant_check_queues;
142 StgTRecChunk *free_trec_chunks;
143 StgTRecHeader *free_trec_headers;
144 nat transaction_tokens;
145 } // typedef Capability is defined in RtsAPI.h
146 // We never want a Capability to overlap a cache line with anything
147 // else, so round it up to a cache line size:
148 #ifndef mingw32_HOST_OS
149 ATTRIBUTE_ALIGNED(64)
150 #endif
151 ;
152
153
154 #if defined(THREADED_RTS)
155 #define ASSERT_TASK_ID(task) ASSERT(task->id == osThreadId())
156 #else
157 #define ASSERT_TASK_ID(task) /*empty*/
158 #endif
159
160 // These properties should be true when a Task is holding a Capability
161 #define ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task) \
162 ASSERT(cap->running_task != NULL && cap->running_task == task); \
163 ASSERT(task->cap == cap); \
164 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task)
165
166 // Sometimes a Task holds a Capability, but the Task is not associated
167 // with that Capability (ie. task->cap != cap). This happens when
168 // (a) a Task holds multiple Capabilities, and (b) when the current
169 // Task is bound, its thread has just blocked, and it may have been
170 // moved to another Capability.
171 #define ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task) \
172 ASSERT(cap->run_queue_hd == END_TSO_QUEUE ? \
173 cap->run_queue_tl == END_TSO_QUEUE : 1); \
174 ASSERT(myTask() == task); \
175 ASSERT_TASK_ID(task);
176
177 #if defined(THREADED_RTS)
178 rtsBool checkSparkCountInvariant (void);
179 #endif
180
181 // Converts a *StgRegTable into a *Capability.
182 //
183 INLINE_HEADER Capability *
184 regTableToCapability (StgRegTable *reg)
185 {
186 return (Capability *)((void *)((unsigned char*)reg - STG_FIELD_OFFSET(Capability,r)));
187 }
188
189 // Initialise the available capabilities.
190 //
191 void initCapabilities (void);
192
193 // Add and initialise more Capabilities
194 //
195 void moreCapabilities (nat from, nat to);
196
197 // Release a capability. This is called by a Task that is exiting
198 // Haskell to make a foreign call, or in various other cases when we
199 // want to relinquish a Capability that we currently hold.
200 //
201 // ASSUMES: cap->running_task is the current Task.
202 //
203 #if defined(THREADED_RTS)
204 void releaseCapability (Capability* cap);
205 void releaseAndWakeupCapability (Capability* cap);
206 void releaseCapability_ (Capability* cap, rtsBool always_wakeup);
207 // assumes cap->lock is held
208 #else
209 // releaseCapability() is empty in non-threaded RTS
210 INLINE_HEADER void releaseCapability (Capability* cap STG_UNUSED) {};
211 INLINE_HEADER void releaseAndWakeupCapability (Capability* cap STG_UNUSED) {};
212 INLINE_HEADER void releaseCapability_ (Capability* cap STG_UNUSED,
213 rtsBool always_wakeup STG_UNUSED) {};
214 #endif
215
216 // declared in includes/rts/Threads.h:
217 // extern Capability MainCapability;
218
219 // declared in includes/rts/Threads.h:
220 // extern nat n_capabilities;
221 // extern nat enabled_capabilities;
222
223 // Array of all the capabilities
224 //
225 extern Capability **capabilities;
226
227 // The Capability that was last free. Used as a good guess for where
228 // to assign new threads.
229 //
230 extern Capability *last_free_capability;
231
232 //
233 // Indicates that the RTS wants to synchronise all the Capabilities
234 // for some reason. All Capabilities should stop and return to the
235 // scheduler.
236 //
237 #define SYNC_GC_SEQ 1
238 #define SYNC_GC_PAR 2
239 #define SYNC_OTHER 3
240 extern volatile StgWord pending_sync;
241
242 // Acquires a capability at a return point. If *cap is non-NULL, then
243 // this is taken as a preference for the Capability we wish to
244 // acquire.
245 //
246 // OS threads waiting in this function get priority over those waiting
247 // in waitForCapability().
248 //
249 // On return, *cap is non-NULL, and points to the Capability acquired.
250 //
251 void waitForCapability (Capability **cap/*in/out*/, Task *task);
252
253 EXTERN_INLINE void recordMutableCap (StgClosure *p, Capability *cap, nat gen);
254
255 EXTERN_INLINE void recordClosureMutated (Capability *cap, StgClosure *p);
256
257 #if defined(THREADED_RTS)
258
259 // Gives up the current capability IFF there is a higher-priority
260 // thread waiting for it. This happens in one of two ways:
261 //
262 // (a) we are passing the capability to another OS thread, so
263 // that it can run a bound Haskell thread, or
264 //
265 // (b) there is an OS thread waiting to return from a foreign call
266 //
267 // On return: *pCap is NULL if the capability was released. The
268 // current task should then re-acquire it using waitForCapability().
269 //
270 rtsBool yieldCapability (Capability** pCap, Task *task, rtsBool gcAllowed);
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 */