1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 2001-2006
7 * For details on the high-level design, see
8 * http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Scheduler
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).
15 * Only in a THREADED_RTS build will there be multiple capabilities,
16 * in the non-threaded RTS there is one global capability, called
19 * --------------------------------------------------------------------------*/
24 #include "sm/GC.h" // for evac_fn
28 #include "BeginPrivate.h"
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).
37 nat no; // capability number.
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.
45 // true if this Capability is running Haskell code, used for
46 // catching unsafe call-ins.
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
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
62 InCall *suspended_ccalls;
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.
70 bdescr **saved_mut_lists; // tmp use during GC
72 // block for allocating pinned objects into
73 bdescr *pinned_object_block;
75 // Context switch flag. We used to have one global flag, now one
76 // per capability. Locks required : none (conflicts are harmless)
79 #if defined(THREADED_RTS)
80 // Worker Tasks waiting in the wings. Singly-linked.
82 nat n_spare_workers; // count of above
84 // This lock protects running_task, returning_tasks_{hd,tl}, wakeup_queue.
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;
95 // Messages, or END_TSO_QUEUE.
100 // Stats on spark creation/conversion
103 nat sparks_converted;
107 // Per-capability STM-related data
108 StgTVarWatchQueue *free_tvar_watch_queues;
109 StgInvariantCheckQueue *free_invariant_check_queues;
110 StgTRecChunk *free_trec_chunks;
111 StgTRecHeader *free_trec_headers;
112 nat transaction_tokens;
113 } // typedef Capability is defined in RtsAPI.h
114 // Capabilities are stored in an array, so make sure that adjacent
115 // Capabilities don't share any cache-lines:
116 #ifndef mingw32_HOST_OS
117 ATTRIBUTE_ALIGNED(64)
122 #if defined(THREADED_RTS)
123 #define ASSERT_TASK_ID(task) ASSERT(task->id == osThreadId())
125 #define ASSERT_TASK_ID(task) /*empty*/
128 // These properties should be true when a Task is holding a Capability
129 #define ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task) \
130 ASSERT(cap->running_task != NULL && cap->running_task == task); \
131 ASSERT(task->cap == cap); \
132 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task)
134 // Sometimes a Task holds a Capability, but the Task is not associated
135 // with that Capability (ie. task->cap != cap). This happens when
136 // (a) a Task holds multiple Capabilities, and (b) when the current
137 // Task is bound, its thread has just blocked, and it may have been
138 // moved to another Capability.
139 #define ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task) \
140 ASSERT(cap->run_queue_hd == END_TSO_QUEUE ? \
141 cap->run_queue_tl == END_TSO_QUEUE : 1); \
142 ASSERT(myTask() == task); \
143 ASSERT_TASK_ID(task);
145 // Converts a *StgRegTable into a *Capability.
147 INLINE_HEADER Capability *
148 regTableToCapability (StgRegTable *reg)
150 return (Capability *)((void *)((unsigned char*)reg - STG_FIELD_OFFSET(Capability,r)));
153 // Initialise the available capabilities.
155 void initCapabilities (void);
157 // Release a capability. This is called by a Task that is exiting
158 // Haskell to make a foreign call, or in various other cases when we
159 // want to relinquish a Capability that we currently hold.
161 // ASSUMES: cap->running_task is the current Task.
163 #if defined(THREADED_RTS)
164 void releaseCapability (Capability* cap);
165 void releaseAndWakeupCapability (Capability* cap);
166 void releaseCapability_ (Capability* cap, rtsBool always_wakeup);
167 // assumes cap->lock is held
169 // releaseCapability() is empty in non-threaded RTS
170 INLINE_HEADER void releaseCapability (Capability* cap STG_UNUSED) {};
171 INLINE_HEADER void releaseAndWakeupCapability (Capability* cap STG_UNUSED) {};
172 INLINE_HEADER void releaseCapability_ (Capability* cap STG_UNUSED,
173 rtsBool always_wakeup STG_UNUSED) {};
176 // declared in includes/rts/Threads.h:
177 // extern Capability MainCapability;
179 // declared in includes/rts/Threads.h:
180 // extern nat n_capabilities;
182 // Array of all the capabilities
184 extern Capability *capabilities;
186 // The Capability that was last free. Used as a good guess for where
187 // to assign new threads.
189 extern Capability *last_free_capability;
191 // GC indicator, in scope for the scheduler
192 #define PENDING_GC_SEQ 1
193 #define PENDING_GC_PAR 2
194 extern volatile StgWord waiting_for_gc;
196 // Acquires a capability at a return point. If *cap is non-NULL, then
197 // this is taken as a preference for the Capability we wish to
200 // OS threads waiting in this function get priority over those waiting
201 // in waitForCapability().
203 // On return, *cap is non-NULL, and points to the Capability acquired.
205 void waitForReturnCapability (Capability **cap/*in/out*/, Task *task);
207 EXTERN_INLINE void recordMutableCap (StgClosure *p, Capability *cap, nat gen);
209 EXTERN_INLINE void recordClosureMutated (Capability *cap, StgClosure *p);
211 #if defined(THREADED_RTS)
213 // Gives up the current capability IFF there is a higher-priority
214 // thread waiting for it. This happens in one of two ways:
216 // (a) we are passing the capability to another OS thread, so
217 // that it can run a bound Haskell thread, or
219 // (b) there is an OS thread waiting to return from a foreign call
221 // On return: *pCap is NULL if the capability was released. The
222 // current task should then re-acquire it using waitForCapability().
224 void yieldCapability (Capability** pCap, Task *task);
226 // Acquires a capability for doing some work.
228 // On return: pCap points to the capability.
230 void waitForCapability (Task *task, Mutex *mutex, Capability **pCap);
232 // Wakes up a worker thread on just one Capability, used when we
233 // need to service some global event.
235 void prodOneCapability (void);
236 void prodCapability (Capability *cap, Task *task);
238 // Similar to prodOneCapability(), but prods all of them.
240 void prodAllCapabilities (void);
242 // Waits for a capability to drain of runnable threads and workers,
243 // and then acquires it. Used at shutdown time.
245 void shutdownCapability (Capability *cap, Task *task, rtsBool wait_foreign);
247 // Attempt to gain control of a Capability if it is free.
249 rtsBool tryGrabCapability (Capability *cap, Task *task);
251 // Try to find a spark to run
253 StgClosure *findSpark (Capability *cap);
255 // True if any capabilities have sparks
257 rtsBool anySparks (void);
259 INLINE_HEADER rtsBool emptySparkPoolCap (Capability *cap);
260 INLINE_HEADER nat sparkPoolSizeCap (Capability *cap);
261 INLINE_HEADER void discardSparksCap (Capability *cap);
263 #else // !THREADED_RTS
265 // Grab a capability. (Only in the non-threaded RTS; in the threaded
266 // RTS one of the waitFor*Capability() functions must be used).
268 extern void grabCapability (Capability **pCap);
270 #endif /* !THREADED_RTS */
272 // cause all capabilities to context switch as soon as possible.
273 void setContextSwitches(void);
274 INLINE_HEADER void contextSwitchCapability(Capability *cap);
276 // Free all capabilities
277 void freeCapabilities (void);
280 void markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta,
281 rtsBool no_mark_sparks);
282 void markCapabilities (evac_fn evac, void *user);
283 void traverseSparkQueues (evac_fn evac, void *user);
285 /* -----------------------------------------------------------------------------
287 -------------------------------------------------------------------------- */
291 INLINE_HEADER rtsBool emptyInbox(Capability *cap);;
293 #endif // THREADED_RTS
295 /* -----------------------------------------------------------------------------
296 * INLINE functions... private below here
297 * -------------------------------------------------------------------------- */
300 recordMutableCap (StgClosure *p, Capability *cap, nat gen)
304 // We must own this Capability in order to modify its mutable list.
305 // ASSERT(cap->running_task == myTask());
306 // NO: assertion is violated by performPendingThrowTos()
307 bd = cap->mut_lists[gen];
308 if (bd->free >= bd->start + BLOCK_SIZE_W) {
310 new_bd = allocBlock_lock();
313 cap->mut_lists[gen] = bd;
315 *bd->free++ = (StgWord)p;
319 recordClosureMutated (Capability *cap, StgClosure *p)
322 bd = Bdescr((StgPtr)p);
323 if (bd->gen_no != 0) recordMutableCap(p,cap,bd->gen_no);
327 #if defined(THREADED_RTS)
328 INLINE_HEADER rtsBool
329 emptySparkPoolCap (Capability *cap)
330 { return looksEmpty(cap->sparks); }
333 sparkPoolSizeCap (Capability *cap)
334 { return sparkPoolSize(cap->sparks); }
337 discardSparksCap (Capability *cap)
338 { return discardSparks(cap->sparks); }
342 contextSwitchCapability (Capability *cap)
344 // setting HpLim to NULL ensures that the next heap check will
345 // fail, and the thread will return to the scheduler.
346 cap->r.rHpLim = NULL;
347 // But just in case it didn't work (the target thread might be
348 // modifying HpLim at the same time), we set the end-of-block
349 // context-switch flag too:
350 cap->context_switch = 1;
355 INLINE_HEADER rtsBool emptyInbox(Capability *cap)
357 return (cap->inbox == (Message*)END_TSO_QUEUE);
362 #include "EndPrivate.h"
364 #endif /* CAPABILITY_H */