Run sparks in batches, instead of creating a new thread for each one
[ghc-hetmet.git] / rts / Capability.c
1 /* ---------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 2003-2006
4  *
5  * Capabilities
6  *
7  * A Capability represent the token required to execute STG code,
8  * and all the state an OS thread/task needs to run Haskell code:
9  * its STG registers, a pointer to its TSO, a nursery etc. During
10  * STG execution, a pointer to the capabilitity is kept in a
11  * register (BaseReg; actually it is a pointer to cap->r).
12  *
13  * Only in an THREADED_RTS build will there be multiple capabilities,
14  * for non-threaded builds there is only one global capability, namely
15  * MainCapability.
16  *
17  * --------------------------------------------------------------------------*/
18
19 #include "PosixSource.h"
20 #include "Rts.h"
21 #include "RtsUtils.h"
22 #include "RtsFlags.h"
23 #include "STM.h"
24 #include "OSThreads.h"
25 #include "Capability.h"
26 #include "Schedule.h"
27 #include "Sparks.h"
28 #include "Trace.h"
29
30 // one global capability, this is the Capability for non-threaded
31 // builds, and for +RTS -N1
32 Capability MainCapability;
33
34 nat n_capabilities;
35 Capability *capabilities = NULL;
36
37 // Holds the Capability which last became free.  This is used so that
38 // an in-call has a chance of quickly finding a free Capability.
39 // Maintaining a global free list of Capabilities would require global
40 // locking, so we don't do that.
41 Capability *last_free_capability;
42
43 /* GC indicator, in scope for the scheduler, init'ed to false */
44 volatile StgWord waiting_for_gc = 0;
45
46 #if defined(THREADED_RTS)
47 STATIC_INLINE rtsBool
48 globalWorkToDo (void)
49 {
50     return blackholes_need_checking
51         || sched_state >= SCHED_INTERRUPTING
52         ;
53 }
54 #endif
55
56 #if defined(THREADED_RTS)
57 StgClosure *
58 stealWork (Capability *cap)
59 {
60   /* use the normal Sparks.h interface (internally modified to enable
61      concurrent stealing) 
62      and immediately turn the spark into a thread when successful
63   */
64   Capability *robbed;
65   StgClosurePtr spark;
66   rtsBool retry;
67   nat i = 0;
68
69   debugTrace(DEBUG_sched,
70              "cap %d: Trying to steal work from other capabilities", 
71              cap->no);
72
73   if (n_capabilities == 1) { return NULL; } // makes no sense...
74
75   do {
76       retry = rtsFalse;
77
78       /* visit cap.s 0..n-1 in sequence until a theft succeeds. We could
79       start at a random place instead of 0 as well.  */
80       for ( i=0 ; i < n_capabilities ; i++ ) {
81           robbed = &capabilities[i];
82           if (cap == robbed)  // ourselves...
83               continue;
84
85           if (emptySparkPoolCap(robbed)) // nothing to steal here
86               continue;
87
88           spark = tryStealSpark(robbed);
89           if (spark == NULL && !emptySparkPoolCap(robbed)) {
90               // we conflicted with another thread while trying to steal;
91               // try again later.
92               retry = rtsTrue;
93           }
94
95           if (spark != NULL) {
96               debugTrace(DEBUG_sched,
97                  "cap %d: Stole a spark from capability %d",
98                          cap->no, robbed->no);
99               return spark;
100           }
101           // otherwise: no success, try next one
102       }
103   } while (retry);
104
105   debugTrace(DEBUG_sched, "No sparks stolen");
106   return NULL;
107 }
108
109 // Returns True if any spark pool is non-empty at this moment in time
110 // The result is only valid for an instant, of course, so in a sense
111 // is immediately invalid, and should not be relied upon for
112 // correctness.
113 rtsBool
114 anySparks (void)
115 {
116     nat i;
117
118     for (i=0; i < n_capabilities; i++) {
119         if (!emptySparkPoolCap(&capabilities[i])) {
120             return rtsTrue;
121         }
122     }
123     return rtsFalse;
124 }
125 #endif
126
127 /* -----------------------------------------------------------------------------
128  * Manage the returning_tasks lists.
129  *
130  * These functions require cap->lock
131  * -------------------------------------------------------------------------- */
132
133 #if defined(THREADED_RTS)
134 STATIC_INLINE void
135 newReturningTask (Capability *cap, Task *task)
136 {
137     ASSERT_LOCK_HELD(&cap->lock);
138     ASSERT(task->return_link == NULL);
139     if (cap->returning_tasks_hd) {
140         ASSERT(cap->returning_tasks_tl->return_link == NULL);
141         cap->returning_tasks_tl->return_link = task;
142     } else {
143         cap->returning_tasks_hd = task;
144     }
145     cap->returning_tasks_tl = task;
146 }
147
148 STATIC_INLINE Task *
149 popReturningTask (Capability *cap)
150 {
151     ASSERT_LOCK_HELD(&cap->lock);
152     Task *task;
153     task = cap->returning_tasks_hd;
154     ASSERT(task);
155     cap->returning_tasks_hd = task->return_link;
156     if (!cap->returning_tasks_hd) {
157         cap->returning_tasks_tl = NULL;
158     }
159     task->return_link = NULL;
160     return task;
161 }
162 #endif
163
164 /* ----------------------------------------------------------------------------
165  * Initialisation
166  *
167  * The Capability is initially marked not free.
168  * ------------------------------------------------------------------------- */
169
170 static void
171 initCapability( Capability *cap, nat i )
172 {
173     nat g;
174
175     cap->no = i;
176     cap->in_haskell        = rtsFalse;
177
178     cap->run_queue_hd      = END_TSO_QUEUE;
179     cap->run_queue_tl      = END_TSO_QUEUE;
180
181 #if defined(THREADED_RTS)
182     initMutex(&cap->lock);
183     cap->running_task      = NULL; // indicates cap is free
184     cap->spare_workers     = NULL;
185     cap->suspended_ccalling_tasks = NULL;
186     cap->returning_tasks_hd = NULL;
187     cap->returning_tasks_tl = NULL;
188     cap->wakeup_queue_hd    = END_TSO_QUEUE;
189     cap->wakeup_queue_tl    = END_TSO_QUEUE;
190     cap->sparks_created     = 0;
191     cap->sparks_converted   = 0;
192     cap->sparks_pruned      = 0;
193 #endif
194
195     cap->f.stgGCEnter1     = (F_)__stg_gc_enter_1;
196     cap->f.stgGCFun        = (F_)__stg_gc_fun;
197
198     cap->mut_lists  = stgMallocBytes(sizeof(bdescr *) *
199                                      RtsFlags.GcFlags.generations,
200                                      "initCapability");
201
202     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
203         cap->mut_lists[g] = NULL;
204     }
205
206     cap->free_tvar_watch_queues = END_STM_WATCH_QUEUE;
207     cap->free_invariant_check_queues = END_INVARIANT_CHECK_QUEUE;
208     cap->free_trec_chunks = END_STM_CHUNK_LIST;
209     cap->free_trec_headers = NO_TREC;
210     cap->transaction_tokens = 0;
211     cap->context_switch = 0;
212 }
213
214 /* ---------------------------------------------------------------------------
215  * Function:  initCapabilities()
216  *
217  * Purpose:   set up the Capability handling. For the THREADED_RTS build,
218  *            we keep a table of them, the size of which is
219  *            controlled by the user via the RTS flag -N.
220  *
221  * ------------------------------------------------------------------------- */
222 void
223 initCapabilities( void )
224 {
225 #if defined(THREADED_RTS)
226     nat i;
227
228 #ifndef REG_Base
229     // We can't support multiple CPUs if BaseReg is not a register
230     if (RtsFlags.ParFlags.nNodes > 1) {
231         errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
232         RtsFlags.ParFlags.nNodes = 1;
233     }
234 #endif
235
236     n_capabilities = RtsFlags.ParFlags.nNodes;
237
238     if (n_capabilities == 1) {
239         capabilities = &MainCapability;
240         // THREADED_RTS must work on builds that don't have a mutable
241         // BaseReg (eg. unregisterised), so in this case
242         // capabilities[0] must coincide with &MainCapability.
243     } else {
244         capabilities = stgMallocBytes(n_capabilities * sizeof(Capability),
245                                       "initCapabilities");
246     }
247
248     for (i = 0; i < n_capabilities; i++) {
249         initCapability(&capabilities[i], i);
250     }
251
252     debugTrace(DEBUG_sched, "allocated %d capabilities", n_capabilities);
253
254 #else /* !THREADED_RTS */
255
256     n_capabilities = 1;
257     capabilities = &MainCapability;
258     initCapability(&MainCapability, 0);
259
260 #endif
261
262     // There are no free capabilities to begin with.  We will start
263     // a worker Task to each Capability, which will quickly put the
264     // Capability on the free list when it finds nothing to do.
265     last_free_capability = &capabilities[0];
266 }
267
268 /* ----------------------------------------------------------------------------
269  * setContextSwitches: cause all capabilities to context switch as
270  * soon as possible.
271  * ------------------------------------------------------------------------- */
272
273 void setContextSwitches(void)
274 {
275   nat i;
276   for (i=0; i < n_capabilities; i++) {
277     capabilities[i].context_switch = 1;
278   }
279 }
280
281 /* ----------------------------------------------------------------------------
282  * Give a Capability to a Task.  The task must currently be sleeping
283  * on its condition variable.
284  *
285  * Requires cap->lock (modifies cap->running_task).
286  *
287  * When migrating a Task, the migrater must take task->lock before
288  * modifying task->cap, to synchronise with the waking up Task.
289  * Additionally, the migrater should own the Capability (when
290  * migrating the run queue), or cap->lock (when migrating
291  * returning_workers).
292  *
293  * ------------------------------------------------------------------------- */
294
295 #if defined(THREADED_RTS)
296 STATIC_INLINE void
297 giveCapabilityToTask (Capability *cap USED_IF_DEBUG, Task *task)
298 {
299     ASSERT_LOCK_HELD(&cap->lock);
300     ASSERT(task->cap == cap);
301     trace(TRACE_sched | DEBUG_sched,
302           "passing capability %d to %s %p",
303           cap->no, task->tso ? "bound task" : "worker",
304           (void *)task->id);
305     ACQUIRE_LOCK(&task->lock);
306     task->wakeup = rtsTrue;
307     // the wakeup flag is needed because signalCondition() doesn't
308     // flag the condition if the thread is already runniing, but we want
309     // it to be sticky.
310     signalCondition(&task->cond);
311     RELEASE_LOCK(&task->lock);
312 }
313 #endif
314
315 /* ----------------------------------------------------------------------------
316  * Function:  releaseCapability(Capability*)
317  *
318  * Purpose:   Letting go of a capability. Causes a
319  *            'returning worker' thread or a 'waiting worker'
320  *            to wake up, in that order.
321  * ------------------------------------------------------------------------- */
322
323 #if defined(THREADED_RTS)
324 void
325 releaseCapability_ (Capability* cap, 
326                     rtsBool always_wakeup)
327 {
328     Task *task;
329
330     task = cap->running_task;
331
332     ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task);
333
334     cap->running_task = NULL;
335
336     // Check to see whether a worker thread can be given
337     // the go-ahead to return the result of an external call..
338     if (cap->returning_tasks_hd != NULL) {
339         giveCapabilityToTask(cap,cap->returning_tasks_hd);
340         // The Task pops itself from the queue (see waitForReturnCapability())
341         return;
342     }
343
344     /* if waiting_for_gc was the reason to release the cap: thread
345        comes from yieldCap->releaseAndQueueWorker. Unconditionally set
346        cap. free and return (see default after the if-protected other
347        special cases). Thread will wait on cond.var and re-acquire the
348        same cap after GC (GC-triggering cap. calls releaseCap and
349        enters the spare_workers case)
350     */
351     if (waiting_for_gc) {
352       last_free_capability = cap; // needed?
353       trace(TRACE_sched | DEBUG_sched, 
354             "GC pending, set capability %d free", cap->no);
355       return;
356     } 
357
358
359     // If the next thread on the run queue is a bound thread,
360     // give this Capability to the appropriate Task.
361     if (!emptyRunQueue(cap) && cap->run_queue_hd->bound) {
362         // Make sure we're not about to try to wake ourselves up
363         ASSERT(task != cap->run_queue_hd->bound);
364         task = cap->run_queue_hd->bound;
365         giveCapabilityToTask(cap,task);
366         return;
367     }
368
369     if (!cap->spare_workers) {
370         // Create a worker thread if we don't have one.  If the system
371         // is interrupted, we only create a worker task if there
372         // are threads that need to be completed.  If the system is
373         // shutting down, we never create a new worker.
374         if (sched_state < SCHED_SHUTTING_DOWN || !emptyRunQueue(cap)) {
375             debugTrace(DEBUG_sched,
376                        "starting new worker on capability %d", cap->no);
377             startWorkerTask(cap, workerStart);
378             return;
379         }
380     }
381
382     // If we have an unbound thread on the run queue, or if there's
383     // anything else to do, give the Capability to a worker thread.
384     if (always_wakeup || 
385         !emptyRunQueue(cap) || !emptyWakeupQueue(cap) ||
386         !emptySparkPoolCap(cap) || globalWorkToDo()) {
387         if (cap->spare_workers) {
388             giveCapabilityToTask(cap,cap->spare_workers);
389             // The worker Task pops itself from the queue;
390             return;
391         }
392     }
393
394     last_free_capability = cap;
395     trace(TRACE_sched | DEBUG_sched, "freeing capability %d", cap->no);
396 }
397
398 void
399 releaseCapability (Capability* cap USED_IF_THREADS)
400 {
401     ACQUIRE_LOCK(&cap->lock);
402     releaseCapability_(cap, rtsFalse);
403     RELEASE_LOCK(&cap->lock);
404 }
405
406 void
407 releaseAndWakeupCapability (Capability* cap USED_IF_THREADS)
408 {
409     ACQUIRE_LOCK(&cap->lock);
410     releaseCapability_(cap, rtsTrue);
411     RELEASE_LOCK(&cap->lock);
412 }
413
414 static void
415 releaseCapabilityAndQueueWorker (Capability* cap USED_IF_THREADS)
416 {
417     Task *task;
418
419     ACQUIRE_LOCK(&cap->lock);
420
421     task = cap->running_task;
422
423     // If the current task is a worker, save it on the spare_workers
424     // list of this Capability.  A worker can mark itself as stopped,
425     // in which case it is not replaced on the spare_worker queue.
426     // This happens when the system is shutting down (see
427     // Schedule.c:workerStart()).
428     // Also, be careful to check that this task hasn't just exited
429     // Haskell to do a foreign call (task->suspended_tso).
430     if (!isBoundTask(task) && !task->stopped && !task->suspended_tso) {
431         task->next = cap->spare_workers;
432         cap->spare_workers = task;
433     }
434     // Bound tasks just float around attached to their TSOs.
435
436     releaseCapability_(cap,rtsFalse);
437
438     RELEASE_LOCK(&cap->lock);
439 }
440 #endif
441
442 /* ----------------------------------------------------------------------------
443  * waitForReturnCapability( Task *task )
444  *
445  * Purpose:  when an OS thread returns from an external call,
446  * it calls waitForReturnCapability() (via Schedule.resumeThread())
447  * to wait for permission to enter the RTS & communicate the
448  * result of the external call back to the Haskell thread that
449  * made it.
450  *
451  * ------------------------------------------------------------------------- */
452 void
453 waitForReturnCapability (Capability **pCap, Task *task)
454 {
455 #if !defined(THREADED_RTS)
456
457     MainCapability.running_task = task;
458     task->cap = &MainCapability;
459     *pCap = &MainCapability;
460
461 #else
462     Capability *cap = *pCap;
463
464     if (cap == NULL) {
465         // Try last_free_capability first
466         cap = last_free_capability;
467         if (!cap->running_task) {
468             nat i;
469             // otherwise, search for a free capability
470             for (i = 0; i < n_capabilities; i++) {
471                 cap = &capabilities[i];
472                 if (!cap->running_task) {
473                     break;
474                 }
475             }
476             // Can't find a free one, use last_free_capability.
477             cap = last_free_capability;
478         }
479
480         // record the Capability as the one this Task is now assocated with.
481         task->cap = cap;
482
483     } else {
484         ASSERT(task->cap == cap);
485     }
486
487     ACQUIRE_LOCK(&cap->lock);
488
489     debugTrace(DEBUG_sched, "returning; I want capability %d", cap->no);
490
491     if (!cap->running_task) {
492         // It's free; just grab it
493         cap->running_task = task;
494         RELEASE_LOCK(&cap->lock);
495     } else {
496         newReturningTask(cap,task);
497         RELEASE_LOCK(&cap->lock);
498
499         for (;;) {
500             ACQUIRE_LOCK(&task->lock);
501             // task->lock held, cap->lock not held
502             if (!task->wakeup) waitCondition(&task->cond, &task->lock);
503             cap = task->cap;
504             task->wakeup = rtsFalse;
505             RELEASE_LOCK(&task->lock);
506
507             // now check whether we should wake up...
508             ACQUIRE_LOCK(&cap->lock);
509             if (cap->running_task == NULL) {
510                 if (cap->returning_tasks_hd != task) {
511                     giveCapabilityToTask(cap,cap->returning_tasks_hd);
512                     RELEASE_LOCK(&cap->lock);
513                     continue;
514                 }
515                 cap->running_task = task;
516                 popReturningTask(cap);
517                 RELEASE_LOCK(&cap->lock);
518                 break;
519             }
520             RELEASE_LOCK(&cap->lock);
521         }
522
523     }
524
525     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
526
527     trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
528
529     *pCap = cap;
530 #endif
531 }
532
533 #if defined(THREADED_RTS)
534 /* ----------------------------------------------------------------------------
535  * yieldCapability
536  * ------------------------------------------------------------------------- */
537
538 void
539 yieldCapability (Capability** pCap, Task *task)
540 {
541     Capability *cap = *pCap;
542
543         debugTrace(DEBUG_sched, "giving up capability %d", cap->no);
544
545         // We must now release the capability and wait to be woken up
546         // again.
547         task->wakeup = rtsFalse;
548         releaseCapabilityAndQueueWorker(cap);
549
550         for (;;) {
551             ACQUIRE_LOCK(&task->lock);
552             // task->lock held, cap->lock not held
553             if (!task->wakeup) waitCondition(&task->cond, &task->lock);
554             cap = task->cap;
555             task->wakeup = rtsFalse;
556             RELEASE_LOCK(&task->lock);
557
558             debugTrace(DEBUG_sched, "woken up on capability %d", cap->no);
559
560             ACQUIRE_LOCK(&cap->lock);
561             if (cap->running_task != NULL) {
562                 debugTrace(DEBUG_sched, 
563                            "capability %d is owned by another task", cap->no);
564                 RELEASE_LOCK(&cap->lock);
565                 continue;
566             }
567
568             if (task->tso == NULL) {
569                 ASSERT(cap->spare_workers != NULL);
570                 // if we're not at the front of the queue, release it
571                 // again.  This is unlikely to happen.
572                 if (cap->spare_workers != task) {
573                     giveCapabilityToTask(cap,cap->spare_workers);
574                     RELEASE_LOCK(&cap->lock);
575                     continue;
576                 }
577                 cap->spare_workers = task->next;
578                 task->next = NULL;
579             }
580             cap->running_task = task;
581             RELEASE_LOCK(&cap->lock);
582             break;
583         }
584
585         trace(TRACE_sched | DEBUG_sched, "resuming capability %d", cap->no);
586         ASSERT(cap->running_task == task);
587
588     *pCap = cap;
589
590     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
591
592     return;
593 }
594
595 /* ----------------------------------------------------------------------------
596  * Wake up a thread on a Capability.
597  *
598  * This is used when the current Task is running on a Capability and
599  * wishes to wake up a thread on a different Capability.
600  * ------------------------------------------------------------------------- */
601
602 void
603 wakeupThreadOnCapability (Capability *my_cap, 
604                           Capability *other_cap, 
605                           StgTSO *tso)
606 {
607     ACQUIRE_LOCK(&other_cap->lock);
608
609     // ASSUMES: cap->lock is held (asserted in wakeupThreadOnCapability)
610     if (tso->bound) {
611         ASSERT(tso->bound->cap == tso->cap);
612         tso->bound->cap = other_cap;
613     }
614     tso->cap = other_cap;
615
616     ASSERT(tso->bound ? tso->bound->cap == other_cap : 1);
617
618     if (other_cap->running_task == NULL) {
619         // nobody is running this Capability, we can add our thread
620         // directly onto the run queue and start up a Task to run it.
621
622         other_cap->running_task = myTask(); 
623             // precond for releaseCapability_() and appendToRunQueue()
624
625         appendToRunQueue(other_cap,tso);
626
627         trace(TRACE_sched, "resuming capability %d", other_cap->no);
628         releaseCapability_(other_cap,rtsFalse);
629     } else {
630         appendToWakeupQueue(my_cap,other_cap,tso);
631         other_cap->context_switch = 1;
632         // someone is running on this Capability, so it cannot be
633         // freed without first checking the wakeup queue (see
634         // releaseCapability_).
635     }
636
637     RELEASE_LOCK(&other_cap->lock);
638 }
639
640 /* ----------------------------------------------------------------------------
641  * prodCapabilities
642  *
643  * Used to indicate that the interrupted flag is now set, or some
644  * other global condition that might require waking up a Task on each
645  * Capability.
646  * ------------------------------------------------------------------------- */
647
648 static void
649 prodCapabilities(rtsBool all)
650 {
651     nat i;
652     Capability *cap;
653     Task *task;
654
655     for (i=0; i < n_capabilities; i++) {
656         cap = &capabilities[i];
657         ACQUIRE_LOCK(&cap->lock);
658         if (!cap->running_task) {
659             if (cap->spare_workers) {
660                 trace(TRACE_sched, "resuming capability %d", cap->no);
661                 task = cap->spare_workers;
662                 ASSERT(!task->stopped);
663                 giveCapabilityToTask(cap,task);
664                 if (!all) {
665                     RELEASE_LOCK(&cap->lock);
666                     return;
667                 }
668             }
669         }
670         RELEASE_LOCK(&cap->lock);
671     }
672     return;
673 }
674
675 void
676 prodAllCapabilities (void)
677 {
678     prodCapabilities(rtsTrue);
679 }
680
681 /* ----------------------------------------------------------------------------
682  * prodOneCapability
683  *
684  * Like prodAllCapabilities, but we only require a single Task to wake
685  * up in order to service some global event, such as checking for
686  * deadlock after some idle time has passed.
687  * ------------------------------------------------------------------------- */
688
689 void
690 prodOneCapability (void)
691 {
692     prodCapabilities(rtsFalse);
693 }
694
695 /* ----------------------------------------------------------------------------
696  * shutdownCapability
697  *
698  * At shutdown time, we want to let everything exit as cleanly as
699  * possible.  For each capability, we let its run queue drain, and
700  * allow the workers to stop.
701  *
702  * This function should be called when interrupted and
703  * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
704  * will exit the scheduler and call taskStop(), and any bound thread
705  * that wakes up will return to its caller.  Runnable threads are
706  * killed.
707  *
708  * ------------------------------------------------------------------------- */
709
710 void
711 shutdownCapability (Capability *cap, Task *task, rtsBool safe)
712 {
713     nat i;
714
715     ASSERT(sched_state == SCHED_SHUTTING_DOWN);
716
717     task->cap = cap;
718
719     // Loop indefinitely until all the workers have exited and there
720     // are no Haskell threads left.  We used to bail out after 50
721     // iterations of this loop, but that occasionally left a worker
722     // running which caused problems later (the closeMutex() below
723     // isn't safe, for one thing).
724
725     for (i = 0; /* i < 50 */; i++) {
726         debugTrace(DEBUG_sched, 
727                    "shutting down capability %d, attempt %d", cap->no, i);
728         ACQUIRE_LOCK(&cap->lock);
729         if (cap->running_task) {
730             RELEASE_LOCK(&cap->lock);
731             debugTrace(DEBUG_sched, "not owner, yielding");
732             yieldThread();
733             continue;
734         }
735         cap->running_task = task;
736
737         if (cap->spare_workers) {
738             // Look for workers that have died without removing
739             // themselves from the list; this could happen if the OS
740             // summarily killed the thread, for example.  This
741             // actually happens on Windows when the system is
742             // terminating the program, and the RTS is running in a
743             // DLL.
744             Task *t, *prev;
745             prev = NULL;
746             for (t = cap->spare_workers; t != NULL; t = t->next) {
747                 if (!osThreadIsAlive(t->id)) {
748                     debugTrace(DEBUG_sched, 
749                                "worker thread %p has died unexpectedly", (void *)t->id);
750                         if (!prev) {
751                             cap->spare_workers = t->next;
752                         } else {
753                             prev->next = t->next;
754                         }
755                         prev = t;
756                 }
757             }
758         }
759
760         if (!emptyRunQueue(cap) || cap->spare_workers) {
761             debugTrace(DEBUG_sched, 
762                        "runnable threads or workers still alive, yielding");
763             releaseCapability_(cap,rtsFalse); // this will wake up a worker
764             RELEASE_LOCK(&cap->lock);
765             yieldThread();
766             continue;
767         }
768
769         // If "safe", then busy-wait for any threads currently doing
770         // foreign calls.  If we're about to unload this DLL, for
771         // example, we need to be sure that there are no OS threads
772         // that will try to return to code that has been unloaded.
773         // We can be a bit more relaxed when this is a standalone
774         // program that is about to terminate, and let safe=false.
775         if (cap->suspended_ccalling_tasks && safe) {
776             debugTrace(DEBUG_sched, 
777                        "thread(s) are involved in foreign calls, yielding");
778             cap->running_task = NULL;
779             RELEASE_LOCK(&cap->lock);
780             yieldThread();
781             continue;
782         }
783             
784         debugTrace(DEBUG_sched, "capability %d is stopped.", cap->no);
785         RELEASE_LOCK(&cap->lock);
786         break;
787     }
788     // we now have the Capability, its run queue and spare workers
789     // list are both empty.
790
791     // ToDo: we can't drop this mutex, because there might still be
792     // threads performing foreign calls that will eventually try to 
793     // return via resumeThread() and attempt to grab cap->lock.
794     // closeMutex(&cap->lock);
795 }
796
797 /* ----------------------------------------------------------------------------
798  * tryGrabCapability
799  *
800  * Attempt to gain control of a Capability if it is free.
801  *
802  * ------------------------------------------------------------------------- */
803
804 rtsBool
805 tryGrabCapability (Capability *cap, Task *task)
806 {
807     if (cap->running_task != NULL) return rtsFalse;
808     ACQUIRE_LOCK(&cap->lock);
809     if (cap->running_task != NULL) {
810         RELEASE_LOCK(&cap->lock);
811         return rtsFalse;
812     }
813     task->cap = cap;
814     cap->running_task = task;
815     RELEASE_LOCK(&cap->lock);
816     return rtsTrue;
817 }
818
819
820 #endif /* THREADED_RTS */
821
822 static void
823 freeCapability (Capability *cap)
824 {
825     stgFree(cap->mut_lists);
826 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
827     freeSparkPool(cap->sparks);
828 #endif
829 }
830
831 void
832 freeCapabilities (void)
833 {
834 #if defined(THREADED_RTS)
835     nat i;
836     for (i=0; i < n_capabilities; i++) {
837         freeCapability(&capabilities[i]);
838     }
839 #else
840     freeCapability(&MainCapability);
841 #endif
842 }
843
844 /* ---------------------------------------------------------------------------
845    Mark everything directly reachable from the Capabilities.  When
846    using multiple GC threads, each GC thread marks all Capabilities
847    for which (c `mod` n == 0), for Capability c and thread n.
848    ------------------------------------------------------------------------ */
849
850 void
851 markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta, 
852                       rtsBool prune_sparks USED_IF_THREADS)
853 {
854     nat i;
855     Capability *cap;
856     Task *task;
857
858     // Each GC thread is responsible for following roots from the
859     // Capability of the same number.  There will usually be the same
860     // or fewer Capabilities as GC threads, but just in case there
861     // are more, we mark every Capability whose number is the GC
862     // thread's index plus a multiple of the number of GC threads.
863     for (i = i0; i < n_capabilities; i += delta) {
864         cap = &capabilities[i];
865         evac(user, (StgClosure **)(void *)&cap->run_queue_hd);
866         evac(user, (StgClosure **)(void *)&cap->run_queue_tl);
867 #if defined(THREADED_RTS)
868         evac(user, (StgClosure **)(void *)&cap->wakeup_queue_hd);
869         evac(user, (StgClosure **)(void *)&cap->wakeup_queue_tl);
870 #endif
871         for (task = cap->suspended_ccalling_tasks; task != NULL; 
872              task=task->next) {
873             debugTrace(DEBUG_sched,
874                        "evac'ing suspended TSO %lu", (unsigned long)task->suspended_tso->id);
875             evac(user, (StgClosure **)(void *)&task->suspended_tso);
876         }
877
878 #if defined(THREADED_RTS)
879         if (prune_sparks) {
880             pruneSparkQueue (evac, user, cap);
881         } else {
882             traverseSparkQueue (evac, user, cap);
883         }
884 #endif
885     }
886
887 #if !defined(THREADED_RTS)
888     evac(user, (StgClosure **)(void *)&blocked_queue_hd);
889     evac(user, (StgClosure **)(void *)&blocked_queue_tl);
890     evac(user, (StgClosure **)(void *)&sleeping_queue);
891 #endif 
892 }
893
894 void
895 markCapabilities (evac_fn evac, void *user)
896 {
897     markSomeCapabilities(evac, user, 0, 1, rtsFalse);
898 }