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