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