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