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