1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 2001-2006
7 * A Capability holds all the state an OS thread/task needs to run
8 * Haskell code: its STG registers, a pointer to its TSO, a nursery
9 * etc. During STG execution, a pointer to the Capabilitity is kept in
10 * a register (BaseReg).
12 * Only in a THREADED_RTS build will there be multiple capabilities,
13 * in the non-threaded RTS there is one global capability, called
16 * --------------------------------------------------------------------------*/
21 #include "sm/GC.h" // for evac_fn
26 // State required by the STG virtual machine when running Haskell
27 // code. During STG execution, the BaseReg register always points
28 // to the StgRegTable of the current Capability (&cap->r).
32 nat no; // capability number.
34 // The Task currently holding this Capability. This task has
35 // exclusive access to the contents of this Capability (apart from
36 // returning_tasks_hd/returning_tasks_tl).
37 // Locks required: cap->lock.
40 // true if this Capability is running Haskell code, used for
41 // catching unsafe call-ins.
44 // true if this Capability is currently in the GC
47 // The run queue. The Task owning this Capability has exclusive
48 // access to its run queue, so can wake up threads without
49 // taking a lock, and the common path through the scheduler is
54 // Tasks currently making safe foreign calls. Doubly-linked.
55 // When returning, a task first acquires the Capability before
56 // removing itself from this list, so that the GC can find all
57 // the suspended TSOs easily. Hence, when migrating a Task from
58 // the returning_tasks list, we must also migrate its entry from
60 Task *suspended_ccalling_tasks;
62 // One mutable list per generation, so we don't need to take any
63 // locks when updating an old-generation thunk. This also lets us
64 // keep track of which closures this CPU has been mutating, so we
65 // can traverse them using the right thread during GC and avoid
66 // unnecessarily moving the data from one cache to another.
68 bdescr **saved_mut_lists; // tmp use during GC
70 // Context switch flag. We used to have one global flag, now one
71 // per capability. Locks required : none (conflicts are harmless)
74 #if defined(THREADED_RTS)
75 // Worker Tasks waiting in the wings. Singly-linked.
78 // This lock protects running_task, returning_tasks_{hd,tl}, wakeup_queue.
81 // Tasks waiting to return from a foreign call, or waiting to make
82 // a new call-in using this Capability (NULL if empty).
83 // NB. this field needs to be modified by tasks other than the
84 // running_task, so it requires cap->lock to modify. A task can
85 // check whether it is NULL without taking the lock, however.
86 Task *returning_tasks_hd; // Singly-linked, with head/tail
87 Task *returning_tasks_tl;
89 // A list of threads to append to this Capability's run queue at
90 // the earliest opportunity. These are threads that have been
91 // woken up by another Capability.
92 StgTSO *wakeup_queue_hd;
93 StgTSO *wakeup_queue_tl;
97 // Stats on spark creation/conversion
103 // Per-capability STM-related data
104 StgTVarWatchQueue *free_tvar_watch_queues;
105 StgInvariantCheckQueue *free_invariant_check_queues;
106 StgTRecChunk *free_trec_chunks;
107 StgTRecHeader *free_trec_headers;
108 nat transaction_tokens;
109 } // typedef Capability is defined in RtsAPI.h
110 // Capabilities are stored in an array, so make sure that adjacent
111 // Capabilities don't share any cache-lines:
112 #ifndef mingw32_HOST_OS
113 ATTRIBUTE_ALIGNED(64)
118 #if defined(THREADED_RTS)
119 #define ASSERT_TASK_ID(task) ASSERT(task->id == osThreadId())
121 #define ASSERT_TASK_ID(task) /*empty*/
124 // These properties should be true when a Task is holding a Capability
125 #define ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task) \
126 ASSERT(cap->running_task != NULL && cap->running_task == task); \
127 ASSERT(task->cap == cap); \
128 ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task)
130 // Sometimes a Task holds a Capability, but the Task is not associated
131 // with that Capability (ie. task->cap != cap). This happens when
132 // (a) a Task holds multiple Capabilities, and (b) when the current
133 // Task is bound, its thread has just blocked, and it may have been
134 // moved to another Capability.
135 #define ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task) \
136 ASSERT(cap->run_queue_hd == END_TSO_QUEUE ? \
137 cap->run_queue_tl == END_TSO_QUEUE : 1); \
138 ASSERT(myTask() == task); \
139 ASSERT_TASK_ID(task);
141 // Converts a *StgRegTable into a *Capability.
143 INLINE_HEADER Capability *
144 regTableToCapability (StgRegTable *reg)
146 return (Capability *)((void *)((unsigned char*)reg - STG_FIELD_OFFSET(Capability,r)));
149 // Initialise the available capabilities.
151 void initCapabilities (void);
153 // Release a capability. This is called by a Task that is exiting
154 // Haskell to make a foreign call, or in various other cases when we
155 // want to relinquish a Capability that we currently hold.
157 // ASSUMES: cap->running_task is the current Task.
159 #if defined(THREADED_RTS)
160 void releaseCapability (Capability* cap);
161 void releaseAndWakeupCapability (Capability* cap);
162 void releaseCapability_ (Capability* cap, rtsBool always_wakeup);
163 // assumes cap->lock is held
165 // releaseCapability() is empty in non-threaded RTS
166 INLINE_HEADER void releaseCapability (Capability* cap STG_UNUSED) {};
167 INLINE_HEADER void releaseAndWakeupCapability (Capability* cap STG_UNUSED) {};
168 INLINE_HEADER void releaseCapability_ (Capability* cap STG_UNUSED,
169 rtsBool always_wakeup STG_UNUSED) {};
172 // declared in includes/rts/Threads.h:
173 // extern Capability MainCapability;
175 // declared in includes/rts/Threads.h:
176 // extern nat n_capabilities;
178 // Array of all the capabilities
180 extern Capability *capabilities;
182 // The Capability that was last free. Used as a good guess for where
183 // to assign new threads.
185 extern Capability *last_free_capability;
187 // GC indicator, in scope for the scheduler
188 #define PENDING_GC_SEQ 1
189 #define PENDING_GC_PAR 2
190 extern volatile StgWord waiting_for_gc;
192 // Acquires a capability at a return point. If *cap is non-NULL, then
193 // this is taken as a preference for the Capability we wish to
196 // OS threads waiting in this function get priority over those waiting
197 // in waitForCapability().
199 // On return, *cap is non-NULL, and points to the Capability acquired.
201 void waitForReturnCapability (Capability **cap/*in/out*/, Task *task);
203 INLINE_HEADER void recordMutableCap (StgClosure *p, Capability *cap, nat gen);
205 #if defined(THREADED_RTS)
207 // Gives up the current capability IFF there is a higher-priority
208 // thread waiting for it. This happens in one of two ways:
210 // (a) we are passing the capability to another OS thread, so
211 // that it can run a bound Haskell thread, or
213 // (b) there is an OS thread waiting to return from a foreign call
215 // On return: *pCap is NULL if the capability was released. The
216 // current task should then re-acquire it using waitForCapability().
218 void yieldCapability (Capability** pCap, Task *task);
220 // Acquires a capability for doing some work.
222 // On return: pCap points to the capability.
224 void waitForCapability (Task *task, Mutex *mutex, Capability **pCap);
226 // Wakes up a thread on a Capability (probably a different Capability
227 // from the one held by the current Task).
229 void wakeupThreadOnCapability (Capability *my_cap, Capability *other_cap,
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 prune_sparks);
282 void markCapabilities (evac_fn evac, void *user);
283 void traverseSparkQueues (evac_fn evac, void *user);
285 /* -----------------------------------------------------------------------------
286 * INLINE functions... private below here
287 * -------------------------------------------------------------------------- */
290 recordMutableCap (StgClosure *p, Capability *cap, nat gen)
294 // We must own this Capability in order to modify its mutable list.
295 ASSERT(cap->running_task == myTask());
296 bd = cap->mut_lists[gen];
297 if (bd->free >= bd->start + BLOCK_SIZE_W) {
299 new_bd = allocBlock_lock();
302 cap->mut_lists[gen] = bd;
304 *bd->free++ = (StgWord)p;
307 #if defined(THREADED_RTS)
308 INLINE_HEADER rtsBool
309 emptySparkPoolCap (Capability *cap)
310 { return looksEmpty(cap->sparks); }
313 sparkPoolSizeCap (Capability *cap)
314 { return sparkPoolSize(cap->sparks); }
317 discardSparksCap (Capability *cap)
318 { return discardSparks(cap->sparks); }
322 contextSwitchCapability (Capability *cap)
324 // setting HpLim to NULL ensures that the next heap check will
325 // fail, and the thread will return to the scheduler.
326 cap->r.rHpLim = NULL;
327 // But just in case it didn't work (the target thread might be
328 // modifying HpLim at the same time), we set the end-of-block
329 // context-switch flag too:
330 cap->context_switch = 1;
333 #endif /* CAPABILITY_H */