bffb7356127700cd21f5066bc27563c89b60b7ba
[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
22 #include "Capability.h"
23 #include "Schedule.h"
24 #include "Sparks.h"
25 #include "Trace.h"
26 #include "sm/GC.h" // for gcWorkerThread()
27 #include "STM.h"
28 #include "RtsUtils.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 = 0;
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 = NULL;
42
43 /* GC indicator, in scope for the scheduler, init'ed to false */
44 volatile StgWord waiting_for_gc = 0;
45
46 /* Let foreign code get the current Capability -- assuming there is one!
47  * This is useful for unsafe foreign calls because they are called with
48  * the current Capability held, but they are not passed it. For example,
49  * see see the integer-gmp package which calls allocateLocal() in its
50  * stgAllocForGMP() function (which gets called by gmp functions).
51  * */
52 Capability * rts_unsafeGetMyCapability (void)
53 {
54 #if defined(THREADED_RTS)
55   return myTask()->cap;
56 #else
57   return &MainCapability;
58 #endif
59 }
60
61 #if defined(THREADED_RTS)
62 STATIC_INLINE rtsBool
63 globalWorkToDo (void)
64 {
65     return sched_state >= SCHED_INTERRUPTING
66         || recent_activity == ACTIVITY_INACTIVE; // need to check for deadlock
67 }
68 #endif
69
70 #if defined(THREADED_RTS)
71 StgClosure *
72 findSpark (Capability *cap)
73 {
74   Capability *robbed;
75   StgClosurePtr spark;
76   rtsBool retry;
77   nat i = 0;
78
79   if (!emptyRunQueue(cap) || cap->returning_tasks_hd != NULL) {
80       // If there are other threads, don't try to run any new
81       // sparks: sparks might be speculative, we don't want to take
82       // resources away from the main computation.
83       return 0;
84   }
85
86   do {
87       retry = rtsFalse;
88
89       // first try to get a spark from our own pool.
90       // We should be using reclaimSpark(), because it works without
91       // needing any atomic instructions:
92       //   spark = reclaimSpark(cap->sparks);
93       // However, measurements show that this makes at least one benchmark
94       // slower (prsa) and doesn't affect the others.
95       spark = tryStealSpark(cap);
96       if (spark != NULL) {
97           cap->sparks_converted++;
98
99           // Post event for running a spark from capability's own pool.
100           traceEventRunSpark(cap, cap->r.rCurrentTSO);
101
102           return spark;
103       }
104       if (!emptySparkPoolCap(cap)) {
105           retry = rtsTrue;
106       }
107
108       if (n_capabilities == 1) { return NULL; } // makes no sense...
109
110       debugTrace(DEBUG_sched,
111                  "cap %d: Trying to steal work from other capabilities", 
112                  cap->no);
113
114       /* visit cap.s 0..n-1 in sequence until a theft succeeds. We could
115       start at a random place instead of 0 as well.  */
116       for ( i=0 ; i < n_capabilities ; i++ ) {
117           robbed = &capabilities[i];
118           if (cap == robbed)  // ourselves...
119               continue;
120
121           if (emptySparkPoolCap(robbed)) // nothing to steal here
122               continue;
123
124           spark = tryStealSpark(robbed);
125           if (spark == NULL && !emptySparkPoolCap(robbed)) {
126               // we conflicted with another thread while trying to steal;
127               // try again later.
128               retry = rtsTrue;
129           }
130
131           if (spark != NULL) {
132               cap->sparks_converted++;
133
134               traceEventStealSpark(cap, cap->r.rCurrentTSO, robbed->no);
135               
136               return spark;
137           }
138           // otherwise: no success, try next one
139       }
140   } while (retry);
141
142   debugTrace(DEBUG_sched, "No sparks stolen");
143   return NULL;
144 }
145
146 // Returns True if any spark pool is non-empty at this moment in time
147 // The result is only valid for an instant, of course, so in a sense
148 // is immediately invalid, and should not be relied upon for
149 // correctness.
150 rtsBool
151 anySparks (void)
152 {
153     nat i;
154
155     for (i=0; i < n_capabilities; i++) {
156         if (!emptySparkPoolCap(&capabilities[i])) {
157             return rtsTrue;
158         }
159     }
160     return rtsFalse;
161 }
162 #endif
163
164 /* -----------------------------------------------------------------------------
165  * Manage the returning_tasks lists.
166  *
167  * These functions require cap->lock
168  * -------------------------------------------------------------------------- */
169
170 #if defined(THREADED_RTS)
171 STATIC_INLINE void
172 newReturningTask (Capability *cap, Task *task)
173 {
174     ASSERT_LOCK_HELD(&cap->lock);
175     ASSERT(task->next == NULL);
176     if (cap->returning_tasks_hd) {
177         ASSERT(cap->returning_tasks_tl->next == NULL);
178         cap->returning_tasks_tl->next = task;
179     } else {
180         cap->returning_tasks_hd = task;
181     }
182     cap->returning_tasks_tl = task;
183 }
184
185 STATIC_INLINE Task *
186 popReturningTask (Capability *cap)
187 {
188     ASSERT_LOCK_HELD(&cap->lock);
189     Task *task;
190     task = cap->returning_tasks_hd;
191     ASSERT(task);
192     cap->returning_tasks_hd = task->next;
193     if (!cap->returning_tasks_hd) {
194         cap->returning_tasks_tl = NULL;
195     }
196     task->next = NULL;
197     return task;
198 }
199 #endif
200
201 /* ----------------------------------------------------------------------------
202  * Initialisation
203  *
204  * The Capability is initially marked not free.
205  * ------------------------------------------------------------------------- */
206
207 static void
208 initCapability( Capability *cap, nat i )
209 {
210     nat g;
211
212     cap->no = i;
213     cap->in_haskell        = rtsFalse;
214
215     cap->run_queue_hd      = END_TSO_QUEUE;
216     cap->run_queue_tl      = END_TSO_QUEUE;
217
218 #if defined(THREADED_RTS)
219     initMutex(&cap->lock);
220     cap->running_task      = NULL; // indicates cap is free
221     cap->spare_workers     = NULL;
222     cap->n_spare_workers   = 0;
223     cap->suspended_ccalls  = NULL;
224     cap->returning_tasks_hd = NULL;
225     cap->returning_tasks_tl = NULL;
226     cap->inbox              = (Message*)END_TSO_QUEUE;
227     cap->sparks_created     = 0;
228     cap->sparks_dud         = 0;
229     cap->sparks_converted   = 0;
230     cap->sparks_gcd         = 0;
231     cap->sparks_fizzled     = 0;
232 #endif
233
234     cap->f.stgEagerBlackholeInfo = (W_)&__stg_EAGER_BLACKHOLE_info;
235     cap->f.stgGCEnter1     = (StgFunPtr)__stg_gc_enter_1;
236     cap->f.stgGCFun        = (StgFunPtr)__stg_gc_fun;
237
238     cap->mut_lists  = stgMallocBytes(sizeof(bdescr *) *
239                                      RtsFlags.GcFlags.generations,
240                                      "initCapability");
241     cap->saved_mut_lists = stgMallocBytes(sizeof(bdescr *) *
242                                           RtsFlags.GcFlags.generations,
243                                           "initCapability");
244
245     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
246         cap->mut_lists[g] = NULL;
247     }
248
249     cap->free_tvar_watch_queues = END_STM_WATCH_QUEUE;
250     cap->free_invariant_check_queues = END_INVARIANT_CHECK_QUEUE;
251     cap->free_trec_chunks = END_STM_CHUNK_LIST;
252     cap->free_trec_headers = NO_TREC;
253     cap->transaction_tokens = 0;
254     cap->context_switch = 0;
255     cap->pinned_object_block = NULL;
256 }
257
258 /* ---------------------------------------------------------------------------
259  * Function:  initCapabilities()
260  *
261  * Purpose:   set up the Capability handling. For the THREADED_RTS build,
262  *            we keep a table of them, the size of which is
263  *            controlled by the user via the RTS flag -N.
264  *
265  * ------------------------------------------------------------------------- */
266 void
267 initCapabilities( void )
268 {
269 #if defined(THREADED_RTS)
270     nat i;
271
272 #ifndef REG_Base
273     // We can't support multiple CPUs if BaseReg is not a register
274     if (RtsFlags.ParFlags.nNodes > 1) {
275         errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
276         RtsFlags.ParFlags.nNodes = 1;
277     }
278 #endif
279
280     n_capabilities = RtsFlags.ParFlags.nNodes;
281
282     if (n_capabilities == 1) {
283         capabilities = &MainCapability;
284         // THREADED_RTS must work on builds that don't have a mutable
285         // BaseReg (eg. unregisterised), so in this case
286         // capabilities[0] must coincide with &MainCapability.
287     } else {
288         capabilities = stgMallocBytes(n_capabilities * sizeof(Capability),
289                                       "initCapabilities");
290     }
291
292     for (i = 0; i < n_capabilities; i++) {
293         initCapability(&capabilities[i], i);
294     }
295
296     debugTrace(DEBUG_sched, "allocated %d capabilities", n_capabilities);
297
298 #else /* !THREADED_RTS */
299
300     n_capabilities = 1;
301     capabilities = &MainCapability;
302     initCapability(&MainCapability, 0);
303
304 #endif
305
306     // There are no free capabilities to begin with.  We will start
307     // a worker Task to each Capability, which will quickly put the
308     // Capability on the free list when it finds nothing to do.
309     last_free_capability = &capabilities[0];
310 }
311
312 /* ----------------------------------------------------------------------------
313  * setContextSwitches: cause all capabilities to context switch as
314  * soon as possible.
315  * ------------------------------------------------------------------------- */
316
317 void setContextSwitches(void)
318 {
319     nat i;
320     for (i=0; i < n_capabilities; i++) {
321         contextSwitchCapability(&capabilities[i]);
322     }
323 }
324
325 /* ----------------------------------------------------------------------------
326  * Give a Capability to a Task.  The task must currently be sleeping
327  * on its condition variable.
328  *
329  * Requires cap->lock (modifies cap->running_task).
330  *
331  * When migrating a Task, the migrater must take task->lock before
332  * modifying task->cap, to synchronise with the waking up Task.
333  * Additionally, the migrater should own the Capability (when
334  * migrating the run queue), or cap->lock (when migrating
335  * returning_workers).
336  *
337  * ------------------------------------------------------------------------- */
338
339 #if defined(THREADED_RTS)
340 STATIC_INLINE void
341 giveCapabilityToTask (Capability *cap USED_IF_DEBUG, Task *task)
342 {
343     ASSERT_LOCK_HELD(&cap->lock);
344     ASSERT(task->cap == cap);
345     debugTrace(DEBUG_sched, "passing capability %d to %s %p",
346                cap->no, task->incall->tso ? "bound task" : "worker",
347                (void *)task->id);
348     ACQUIRE_LOCK(&task->lock);
349     task->wakeup = rtsTrue;
350     // the wakeup flag is needed because signalCondition() doesn't
351     // flag the condition if the thread is already runniing, but we want
352     // it to be sticky.
353     signalCondition(&task->cond);
354     RELEASE_LOCK(&task->lock);
355 }
356 #endif
357
358 /* ----------------------------------------------------------------------------
359  * Function:  releaseCapability(Capability*)
360  *
361  * Purpose:   Letting go of a capability. Causes a
362  *            'returning worker' thread or a 'waiting worker'
363  *            to wake up, in that order.
364  * ------------------------------------------------------------------------- */
365
366 #if defined(THREADED_RTS)
367 void
368 releaseCapability_ (Capability* cap, 
369                     rtsBool always_wakeup)
370 {
371     Task *task;
372
373     task = cap->running_task;
374
375     ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task);
376
377     cap->running_task = NULL;
378
379     // Check to see whether a worker thread can be given
380     // the go-ahead to return the result of an external call..
381     if (cap->returning_tasks_hd != NULL) {
382         giveCapabilityToTask(cap,cap->returning_tasks_hd);
383         // The Task pops itself from the queue (see waitForReturnCapability())
384         return;
385     }
386
387     if (waiting_for_gc == PENDING_GC_SEQ) {
388       last_free_capability = cap; // needed?
389       debugTrace(DEBUG_sched, "GC pending, set capability %d free", cap->no);
390       return;
391     } 
392
393
394     // If the next thread on the run queue is a bound thread,
395     // give this Capability to the appropriate Task.
396     if (!emptyRunQueue(cap) && cap->run_queue_hd->bound) {
397         // Make sure we're not about to try to wake ourselves up
398         // ASSERT(task != cap->run_queue_hd->bound);
399         // assertion is false: in schedule() we force a yield after
400         // ThreadBlocked, but the thread may be back on the run queue
401         // by now.
402         task = cap->run_queue_hd->bound->task;
403         giveCapabilityToTask(cap,task);
404         return;
405     }
406
407     if (!cap->spare_workers) {
408         // Create a worker thread if we don't have one.  If the system
409         // is interrupted, we only create a worker task if there
410         // are threads that need to be completed.  If the system is
411         // shutting down, we never create a new worker.
412         if (sched_state < SCHED_SHUTTING_DOWN || !emptyRunQueue(cap)) {
413             debugTrace(DEBUG_sched,
414                        "starting new worker on capability %d", cap->no);
415             startWorkerTask(cap);
416             return;
417         }
418     }
419
420     // If we have an unbound thread on the run queue, or if there's
421     // anything else to do, give the Capability to a worker thread.
422     if (always_wakeup || 
423         !emptyRunQueue(cap) || !emptyInbox(cap) ||
424         !emptySparkPoolCap(cap) || globalWorkToDo()) {
425         if (cap->spare_workers) {
426             giveCapabilityToTask(cap,cap->spare_workers);
427             // The worker Task pops itself from the queue;
428             return;
429         }
430     }
431
432     last_free_capability = cap;
433     debugTrace(DEBUG_sched, "freeing capability %d", cap->no);
434 }
435
436 void
437 releaseCapability (Capability* cap USED_IF_THREADS)
438 {
439     ACQUIRE_LOCK(&cap->lock);
440     releaseCapability_(cap, rtsFalse);
441     RELEASE_LOCK(&cap->lock);
442 }
443
444 void
445 releaseAndWakeupCapability (Capability* cap USED_IF_THREADS)
446 {
447     ACQUIRE_LOCK(&cap->lock);
448     releaseCapability_(cap, rtsTrue);
449     RELEASE_LOCK(&cap->lock);
450 }
451
452 static void
453 releaseCapabilityAndQueueWorker (Capability* cap USED_IF_THREADS)
454 {
455     Task *task;
456
457     ACQUIRE_LOCK(&cap->lock);
458
459     task = cap->running_task;
460
461     // If the Task is stopped, we shouldn't be yielding, we should
462     // be just exiting.
463     ASSERT(!task->stopped);
464
465     // If the current task is a worker, save it on the spare_workers
466     // list of this Capability.  A worker can mark itself as stopped,
467     // in which case it is not replaced on the spare_worker queue.
468     // This happens when the system is shutting down (see
469     // Schedule.c:workerStart()).
470     if (!isBoundTask(task))
471     {
472         if (cap->n_spare_workers < MAX_SPARE_WORKERS)
473         {
474             task->next = cap->spare_workers;
475             cap->spare_workers = task;
476             cap->n_spare_workers++;
477         }
478         else
479         {
480             debugTrace(DEBUG_sched, "%d spare workers already, exiting",
481                        cap->n_spare_workers);
482             releaseCapability_(cap,rtsFalse);
483             // hold the lock until after workerTaskStop; c.f. scheduleWorker()
484             workerTaskStop(task);
485             RELEASE_LOCK(&cap->lock);
486             shutdownThread();
487         }
488     }
489     // Bound tasks just float around attached to their TSOs.
490
491     releaseCapability_(cap,rtsFalse);
492
493     RELEASE_LOCK(&cap->lock);
494 }
495 #endif
496
497 /* ----------------------------------------------------------------------------
498  * waitForReturnCapability( Task *task )
499  *
500  * Purpose:  when an OS thread returns from an external call,
501  * it calls waitForReturnCapability() (via Schedule.resumeThread())
502  * to wait for permission to enter the RTS & communicate the
503  * result of the external call back to the Haskell thread that
504  * made it.
505  *
506  * ------------------------------------------------------------------------- */
507 void
508 waitForReturnCapability (Capability **pCap, Task *task)
509 {
510 #if !defined(THREADED_RTS)
511
512     MainCapability.running_task = task;
513     task->cap = &MainCapability;
514     *pCap = &MainCapability;
515
516 #else
517     Capability *cap = *pCap;
518
519     if (cap == NULL) {
520         // Try last_free_capability first
521         cap = last_free_capability;
522         if (cap->running_task) {
523             nat i;
524             // otherwise, search for a free capability
525             cap = NULL;
526             for (i = 0; i < n_capabilities; i++) {
527                 if (!capabilities[i].running_task) {
528                     cap = &capabilities[i];
529                     break;
530                 }
531             }
532             if (cap == NULL) {
533                 // Can't find a free one, use last_free_capability.
534                 cap = last_free_capability;
535             }
536         }
537
538         // record the Capability as the one this Task is now assocated with.
539         task->cap = cap;
540
541     } else {
542         ASSERT(task->cap == cap);
543     }
544
545     ACQUIRE_LOCK(&cap->lock);
546
547     debugTrace(DEBUG_sched, "returning; I want capability %d", cap->no);
548
549     if (!cap->running_task) {
550         // It's free; just grab it
551         cap->running_task = task;
552         RELEASE_LOCK(&cap->lock);
553     } else {
554         newReturningTask(cap,task);
555         RELEASE_LOCK(&cap->lock);
556
557         for (;;) {
558             ACQUIRE_LOCK(&task->lock);
559             // task->lock held, cap->lock not held
560             if (!task->wakeup) waitCondition(&task->cond, &task->lock);
561             cap = task->cap;
562             task->wakeup = rtsFalse;
563             RELEASE_LOCK(&task->lock);
564
565             // now check whether we should wake up...
566             ACQUIRE_LOCK(&cap->lock);
567             if (cap->running_task == NULL) {
568                 if (cap->returning_tasks_hd != task) {
569                     giveCapabilityToTask(cap,cap->returning_tasks_hd);
570                     RELEASE_LOCK(&cap->lock);
571                     continue;
572                 }
573                 cap->running_task = task;
574                 popReturningTask(cap);
575                 RELEASE_LOCK(&cap->lock);
576                 break;
577             }
578             RELEASE_LOCK(&cap->lock);
579         }
580
581     }
582
583     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
584
585     debugTrace(DEBUG_sched, "resuming capability %d", cap->no);
586
587     *pCap = cap;
588 #endif
589 }
590
591 #if defined(THREADED_RTS)
592 /* ----------------------------------------------------------------------------
593  * yieldCapability
594  * ------------------------------------------------------------------------- */
595
596 void
597 yieldCapability (Capability** pCap, Task *task)
598 {
599     Capability *cap = *pCap;
600
601     if (waiting_for_gc == PENDING_GC_PAR) {
602         traceEventGcStart(cap);
603         gcWorkerThread(cap);
604         traceEventGcEnd(cap);
605         return;
606     }
607
608         debugTrace(DEBUG_sched, "giving up capability %d", cap->no);
609
610         // We must now release the capability and wait to be woken up
611         // again.
612         task->wakeup = rtsFalse;
613         releaseCapabilityAndQueueWorker(cap);
614
615         for (;;) {
616             ACQUIRE_LOCK(&task->lock);
617             // task->lock held, cap->lock not held
618             if (!task->wakeup) waitCondition(&task->cond, &task->lock);
619             cap = task->cap;
620             task->wakeup = rtsFalse;
621             RELEASE_LOCK(&task->lock);
622
623             debugTrace(DEBUG_sched, "woken up on capability %d", cap->no);
624
625             ACQUIRE_LOCK(&cap->lock);
626             if (cap->running_task != NULL) {
627                 debugTrace(DEBUG_sched, 
628                            "capability %d is owned by another task", cap->no);
629                 RELEASE_LOCK(&cap->lock);
630                 continue;
631             }
632
633             if (task->incall->tso == NULL) {
634                 ASSERT(cap->spare_workers != NULL);
635                 // if we're not at the front of the queue, release it
636                 // again.  This is unlikely to happen.
637                 if (cap->spare_workers != task) {
638                     giveCapabilityToTask(cap,cap->spare_workers);
639                     RELEASE_LOCK(&cap->lock);
640                     continue;
641                 }
642                 cap->spare_workers = task->next;
643                 task->next = NULL;
644                 cap->n_spare_workers--;
645             }
646             cap->running_task = task;
647             RELEASE_LOCK(&cap->lock);
648             break;
649         }
650
651         debugTrace(DEBUG_sched, "resuming capability %d", cap->no);
652         ASSERT(cap->running_task == task);
653
654     *pCap = cap;
655
656     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
657
658     return;
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                     cap->n_spare_workers--;
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_ccalls && 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             // The IO manager thread might have been slow to start up,
766             // so the first attempt to kill it might not have
767             // succeeded.  Just in case, try again - the kill message
768             // will only be sent once.
769             //
770             // To reproduce this deadlock: run ffi002(threaded1)
771             // repeatedly on a loaded machine.
772             ioManagerDie();
773             yieldThread();
774             continue;
775         }
776
777         traceEventShutdown(cap);
778         RELEASE_LOCK(&cap->lock);
779         break;
780     }
781     // we now have the Capability, its run queue and spare workers
782     // list are both empty.
783
784     // ToDo: we can't drop this mutex, because there might still be
785     // threads performing foreign calls that will eventually try to 
786     // return via resumeThread() and attempt to grab cap->lock.
787     // closeMutex(&cap->lock);
788 }
789
790 /* ----------------------------------------------------------------------------
791  * tryGrabCapability
792  *
793  * Attempt to gain control of a Capability if it is free.
794  *
795  * ------------------------------------------------------------------------- */
796
797 rtsBool
798 tryGrabCapability (Capability *cap, Task *task)
799 {
800     if (cap->running_task != NULL) return rtsFalse;
801     ACQUIRE_LOCK(&cap->lock);
802     if (cap->running_task != NULL) {
803         RELEASE_LOCK(&cap->lock);
804         return rtsFalse;
805     }
806     task->cap = cap;
807     cap->running_task = task;
808     RELEASE_LOCK(&cap->lock);
809     return rtsTrue;
810 }
811
812
813 #endif /* THREADED_RTS */
814
815 static void
816 freeCapability (Capability *cap)
817 {
818     stgFree(cap->mut_lists);
819     stgFree(cap->saved_mut_lists);
820 #if defined(THREADED_RTS)
821     freeSparkPool(cap->sparks);
822 #endif
823 }
824
825 void
826 freeCapabilities (void)
827 {
828 #if defined(THREADED_RTS)
829     nat i;
830     for (i=0; i < n_capabilities; i++) {
831         freeCapability(&capabilities[i]);
832     }
833 #else
834     freeCapability(&MainCapability);
835 #endif
836 }
837
838 /* ---------------------------------------------------------------------------
839    Mark everything directly reachable from the Capabilities.  When
840    using multiple GC threads, each GC thread marks all Capabilities
841    for which (c `mod` n == 0), for Capability c and thread n.
842    ------------------------------------------------------------------------ */
843
844 void
845 markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta, 
846                       rtsBool no_mark_sparks USED_IF_THREADS)
847 {
848     nat i;
849     Capability *cap;
850     InCall *incall;
851
852     // Each GC thread is responsible for following roots from the
853     // Capability of the same number.  There will usually be the same
854     // or fewer Capabilities as GC threads, but just in case there
855     // are more, we mark every Capability whose number is the GC
856     // thread's index plus a multiple of the number of GC threads.
857     for (i = i0; i < n_capabilities; i += delta) {
858         cap = &capabilities[i];
859         evac(user, (StgClosure **)(void *)&cap->run_queue_hd);
860         evac(user, (StgClosure **)(void *)&cap->run_queue_tl);
861 #if defined(THREADED_RTS)
862         evac(user, (StgClosure **)(void *)&cap->inbox);
863 #endif
864         for (incall = cap->suspended_ccalls; incall != NULL; 
865              incall=incall->next) {
866             evac(user, (StgClosure **)(void *)&incall->suspended_tso);
867         }
868
869 #if defined(THREADED_RTS)
870         if (!no_mark_sparks) {
871             traverseSparkQueue (evac, user, cap);
872         }
873 #endif
874     }
875
876 #if !defined(THREADED_RTS)
877     evac(user, (StgClosure **)(void *)&blocked_queue_hd);
878     evac(user, (StgClosure **)(void *)&blocked_queue_tl);
879     evac(user, (StgClosure **)(void *)&sleeping_queue);
880 #endif 
881 }
882
883 void
884 markCapabilities (evac_fn evac, void *user)
885 {
886     markSomeCapabilities(evac, user, 0, 1, rtsFalse);
887 }
888
889 /* -----------------------------------------------------------------------------
890    Messages
891    -------------------------------------------------------------------------- */
892