count "dud" sparks (expressions that were already evaluated when sparked)
[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_pruned      = 0;
231 #endif
232
233     cap->f.stgEagerBlackholeInfo = (W_)&__stg_EAGER_BLACKHOLE_info;
234     cap->f.stgGCEnter1     = (StgFunPtr)__stg_gc_enter_1;
235     cap->f.stgGCFun        = (StgFunPtr)__stg_gc_fun;
236
237     cap->mut_lists  = stgMallocBytes(sizeof(bdescr *) *
238                                      RtsFlags.GcFlags.generations,
239                                      "initCapability");
240     cap->saved_mut_lists = stgMallocBytes(sizeof(bdescr *) *
241                                           RtsFlags.GcFlags.generations,
242                                           "initCapability");
243
244     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
245         cap->mut_lists[g] = NULL;
246     }
247
248     cap->free_tvar_watch_queues = END_STM_WATCH_QUEUE;
249     cap->free_invariant_check_queues = END_INVARIANT_CHECK_QUEUE;
250     cap->free_trec_chunks = END_STM_CHUNK_LIST;
251     cap->free_trec_headers = NO_TREC;
252     cap->transaction_tokens = 0;
253     cap->context_switch = 0;
254     cap->pinned_object_block = NULL;
255 }
256
257 /* ---------------------------------------------------------------------------
258  * Function:  initCapabilities()
259  *
260  * Purpose:   set up the Capability handling. For the THREADED_RTS build,
261  *            we keep a table of them, the size of which is
262  *            controlled by the user via the RTS flag -N.
263  *
264  * ------------------------------------------------------------------------- */
265 void
266 initCapabilities( void )
267 {
268 #if defined(THREADED_RTS)
269     nat i;
270
271 #ifndef REG_Base
272     // We can't support multiple CPUs if BaseReg is not a register
273     if (RtsFlags.ParFlags.nNodes > 1) {
274         errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
275         RtsFlags.ParFlags.nNodes = 1;
276     }
277 #endif
278
279     n_capabilities = RtsFlags.ParFlags.nNodes;
280
281     if (n_capabilities == 1) {
282         capabilities = &MainCapability;
283         // THREADED_RTS must work on builds that don't have a mutable
284         // BaseReg (eg. unregisterised), so in this case
285         // capabilities[0] must coincide with &MainCapability.
286     } else {
287         capabilities = stgMallocBytes(n_capabilities * sizeof(Capability),
288                                       "initCapabilities");
289     }
290
291     for (i = 0; i < n_capabilities; i++) {
292         initCapability(&capabilities[i], i);
293     }
294
295     debugTrace(DEBUG_sched, "allocated %d capabilities", n_capabilities);
296
297 #else /* !THREADED_RTS */
298
299     n_capabilities = 1;
300     capabilities = &MainCapability;
301     initCapability(&MainCapability, 0);
302
303 #endif
304
305     // There are no free capabilities to begin with.  We will start
306     // a worker Task to each Capability, which will quickly put the
307     // Capability on the free list when it finds nothing to do.
308     last_free_capability = &capabilities[0];
309 }
310
311 /* ----------------------------------------------------------------------------
312  * setContextSwitches: cause all capabilities to context switch as
313  * soon as possible.
314  * ------------------------------------------------------------------------- */
315
316 void setContextSwitches(void)
317 {
318     nat i;
319     for (i=0; i < n_capabilities; i++) {
320         contextSwitchCapability(&capabilities[i]);
321     }
322 }
323
324 /* ----------------------------------------------------------------------------
325  * Give a Capability to a Task.  The task must currently be sleeping
326  * on its condition variable.
327  *
328  * Requires cap->lock (modifies cap->running_task).
329  *
330  * When migrating a Task, the migrater must take task->lock before
331  * modifying task->cap, to synchronise with the waking up Task.
332  * Additionally, the migrater should own the Capability (when
333  * migrating the run queue), or cap->lock (when migrating
334  * returning_workers).
335  *
336  * ------------------------------------------------------------------------- */
337
338 #if defined(THREADED_RTS)
339 STATIC_INLINE void
340 giveCapabilityToTask (Capability *cap USED_IF_DEBUG, Task *task)
341 {
342     ASSERT_LOCK_HELD(&cap->lock);
343     ASSERT(task->cap == cap);
344     debugTrace(DEBUG_sched, "passing capability %d to %s %p",
345                cap->no, task->incall->tso ? "bound task" : "worker",
346                (void *)task->id);
347     ACQUIRE_LOCK(&task->lock);
348     task->wakeup = rtsTrue;
349     // the wakeup flag is needed because signalCondition() doesn't
350     // flag the condition if the thread is already runniing, but we want
351     // it to be sticky.
352     signalCondition(&task->cond);
353     RELEASE_LOCK(&task->lock);
354 }
355 #endif
356
357 /* ----------------------------------------------------------------------------
358  * Function:  releaseCapability(Capability*)
359  *
360  * Purpose:   Letting go of a capability. Causes a
361  *            'returning worker' thread or a 'waiting worker'
362  *            to wake up, in that order.
363  * ------------------------------------------------------------------------- */
364
365 #if defined(THREADED_RTS)
366 void
367 releaseCapability_ (Capability* cap, 
368                     rtsBool always_wakeup)
369 {
370     Task *task;
371
372     task = cap->running_task;
373
374     ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task);
375
376     cap->running_task = NULL;
377
378     // Check to see whether a worker thread can be given
379     // the go-ahead to return the result of an external call..
380     if (cap->returning_tasks_hd != NULL) {
381         giveCapabilityToTask(cap,cap->returning_tasks_hd);
382         // The Task pops itself from the queue (see waitForReturnCapability())
383         return;
384     }
385
386     if (waiting_for_gc == PENDING_GC_SEQ) {
387       last_free_capability = cap; // needed?
388       debugTrace(DEBUG_sched, "GC pending, set capability %d free", cap->no);
389       return;
390     } 
391
392
393     // If the next thread on the run queue is a bound thread,
394     // give this Capability to the appropriate Task.
395     if (!emptyRunQueue(cap) && cap->run_queue_hd->bound) {
396         // Make sure we're not about to try to wake ourselves up
397         // ASSERT(task != cap->run_queue_hd->bound);
398         // assertion is false: in schedule() we force a yield after
399         // ThreadBlocked, but the thread may be back on the run queue
400         // by now.
401         task = cap->run_queue_hd->bound->task;
402         giveCapabilityToTask(cap,task);
403         return;
404     }
405
406     if (!cap->spare_workers) {
407         // Create a worker thread if we don't have one.  If the system
408         // is interrupted, we only create a worker task if there
409         // are threads that need to be completed.  If the system is
410         // shutting down, we never create a new worker.
411         if (sched_state < SCHED_SHUTTING_DOWN || !emptyRunQueue(cap)) {
412             debugTrace(DEBUG_sched,
413                        "starting new worker on capability %d", cap->no);
414             startWorkerTask(cap);
415             return;
416         }
417     }
418
419     // If we have an unbound thread on the run queue, or if there's
420     // anything else to do, give the Capability to a worker thread.
421     if (always_wakeup || 
422         !emptyRunQueue(cap) || !emptyInbox(cap) ||
423         !emptySparkPoolCap(cap) || globalWorkToDo()) {
424         if (cap->spare_workers) {
425             giveCapabilityToTask(cap,cap->spare_workers);
426             // The worker Task pops itself from the queue;
427             return;
428         }
429     }
430
431     last_free_capability = cap;
432     debugTrace(DEBUG_sched, "freeing capability %d", cap->no);
433 }
434
435 void
436 releaseCapability (Capability* cap USED_IF_THREADS)
437 {
438     ACQUIRE_LOCK(&cap->lock);
439     releaseCapability_(cap, rtsFalse);
440     RELEASE_LOCK(&cap->lock);
441 }
442
443 void
444 releaseAndWakeupCapability (Capability* cap USED_IF_THREADS)
445 {
446     ACQUIRE_LOCK(&cap->lock);
447     releaseCapability_(cap, rtsTrue);
448     RELEASE_LOCK(&cap->lock);
449 }
450
451 static void
452 releaseCapabilityAndQueueWorker (Capability* cap USED_IF_THREADS)
453 {
454     Task *task;
455
456     ACQUIRE_LOCK(&cap->lock);
457
458     task = cap->running_task;
459
460     // If the Task is stopped, we shouldn't be yielding, we should
461     // be just exiting.
462     ASSERT(!task->stopped);
463
464     // If the current task is a worker, save it on the spare_workers
465     // list of this Capability.  A worker can mark itself as stopped,
466     // in which case it is not replaced on the spare_worker queue.
467     // This happens when the system is shutting down (see
468     // Schedule.c:workerStart()).
469     if (!isBoundTask(task))
470     {
471         if (cap->n_spare_workers < MAX_SPARE_WORKERS)
472         {
473             task->next = cap->spare_workers;
474             cap->spare_workers = task;
475             cap->n_spare_workers++;
476         }
477         else
478         {
479             debugTrace(DEBUG_sched, "%d spare workers already, exiting",
480                        cap->n_spare_workers);
481             releaseCapability_(cap,rtsFalse);
482             // hold the lock until after workerTaskStop; c.f. scheduleWorker()
483             workerTaskStop(task);
484             RELEASE_LOCK(&cap->lock);
485             shutdownThread();
486         }
487     }
488     // Bound tasks just float around attached to their TSOs.
489
490     releaseCapability_(cap,rtsFalse);
491
492     RELEASE_LOCK(&cap->lock);
493 }
494 #endif
495
496 /* ----------------------------------------------------------------------------
497  * waitForReturnCapability( Task *task )
498  *
499  * Purpose:  when an OS thread returns from an external call,
500  * it calls waitForReturnCapability() (via Schedule.resumeThread())
501  * to wait for permission to enter the RTS & communicate the
502  * result of the external call back to the Haskell thread that
503  * made it.
504  *
505  * ------------------------------------------------------------------------- */
506 void
507 waitForReturnCapability (Capability **pCap, Task *task)
508 {
509 #if !defined(THREADED_RTS)
510
511     MainCapability.running_task = task;
512     task->cap = &MainCapability;
513     *pCap = &MainCapability;
514
515 #else
516     Capability *cap = *pCap;
517
518     if (cap == NULL) {
519         // Try last_free_capability first
520         cap = last_free_capability;
521         if (cap->running_task) {
522             nat i;
523             // otherwise, search for a free capability
524             cap = NULL;
525             for (i = 0; i < n_capabilities; i++) {
526                 if (!capabilities[i].running_task) {
527                     cap = &capabilities[i];
528                     break;
529                 }
530             }
531             if (cap == NULL) {
532                 // Can't find a free one, use last_free_capability.
533                 cap = last_free_capability;
534             }
535         }
536
537         // record the Capability as the one this Task is now assocated with.
538         task->cap = cap;
539
540     } else {
541         ASSERT(task->cap == cap);
542     }
543
544     ACQUIRE_LOCK(&cap->lock);
545
546     debugTrace(DEBUG_sched, "returning; I want capability %d", cap->no);
547
548     if (!cap->running_task) {
549         // It's free; just grab it
550         cap->running_task = task;
551         RELEASE_LOCK(&cap->lock);
552     } else {
553         newReturningTask(cap,task);
554         RELEASE_LOCK(&cap->lock);
555
556         for (;;) {
557             ACQUIRE_LOCK(&task->lock);
558             // task->lock held, cap->lock not held
559             if (!task->wakeup) waitCondition(&task->cond, &task->lock);
560             cap = task->cap;
561             task->wakeup = rtsFalse;
562             RELEASE_LOCK(&task->lock);
563
564             // now check whether we should wake up...
565             ACQUIRE_LOCK(&cap->lock);
566             if (cap->running_task == NULL) {
567                 if (cap->returning_tasks_hd != task) {
568                     giveCapabilityToTask(cap,cap->returning_tasks_hd);
569                     RELEASE_LOCK(&cap->lock);
570                     continue;
571                 }
572                 cap->running_task = task;
573                 popReturningTask(cap);
574                 RELEASE_LOCK(&cap->lock);
575                 break;
576             }
577             RELEASE_LOCK(&cap->lock);
578         }
579
580     }
581
582     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
583
584     debugTrace(DEBUG_sched, "resuming capability %d", cap->no);
585
586     *pCap = cap;
587 #endif
588 }
589
590 #if defined(THREADED_RTS)
591 /* ----------------------------------------------------------------------------
592  * yieldCapability
593  * ------------------------------------------------------------------------- */
594
595 void
596 yieldCapability (Capability** pCap, Task *task)
597 {
598     Capability *cap = *pCap;
599
600     if (waiting_for_gc == PENDING_GC_PAR) {
601         traceEventGcStart(cap);
602         gcWorkerThread(cap);
603         traceEventGcEnd(cap);
604         return;
605     }
606
607         debugTrace(DEBUG_sched, "giving up capability %d", cap->no);
608
609         // We must now release the capability and wait to be woken up
610         // again.
611         task->wakeup = rtsFalse;
612         releaseCapabilityAndQueueWorker(cap);
613
614         for (;;) {
615             ACQUIRE_LOCK(&task->lock);
616             // task->lock held, cap->lock not held
617             if (!task->wakeup) waitCondition(&task->cond, &task->lock);
618             cap = task->cap;
619             task->wakeup = rtsFalse;
620             RELEASE_LOCK(&task->lock);
621
622             debugTrace(DEBUG_sched, "woken up on capability %d", cap->no);
623
624             ACQUIRE_LOCK(&cap->lock);
625             if (cap->running_task != NULL) {
626                 debugTrace(DEBUG_sched, 
627                            "capability %d is owned by another task", cap->no);
628                 RELEASE_LOCK(&cap->lock);
629                 continue;
630             }
631
632             if (task->incall->tso == NULL) {
633                 ASSERT(cap->spare_workers != NULL);
634                 // if we're not at the front of the queue, release it
635                 // again.  This is unlikely to happen.
636                 if (cap->spare_workers != task) {
637                     giveCapabilityToTask(cap,cap->spare_workers);
638                     RELEASE_LOCK(&cap->lock);
639                     continue;
640                 }
641                 cap->spare_workers = task->next;
642                 task->next = NULL;
643                 cap->n_spare_workers--;
644             }
645             cap->running_task = task;
646             RELEASE_LOCK(&cap->lock);
647             break;
648         }
649
650         debugTrace(DEBUG_sched, "resuming capability %d", cap->no);
651         ASSERT(cap->running_task == task);
652
653     *pCap = cap;
654
655     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
656
657     return;
658 }
659
660 /* ----------------------------------------------------------------------------
661  * prodCapability
662  *
663  * If a Capability is currently idle, wake up a Task on it.  Used to 
664  * get every Capability into the GC.
665  * ------------------------------------------------------------------------- */
666
667 void
668 prodCapability (Capability *cap, Task *task)
669 {
670     ACQUIRE_LOCK(&cap->lock);
671     if (!cap->running_task) {
672         cap->running_task = task;
673         releaseCapability_(cap,rtsTrue);
674     }
675     RELEASE_LOCK(&cap->lock);
676 }
677
678 /* ----------------------------------------------------------------------------
679  * shutdownCapability
680  *
681  * At shutdown time, we want to let everything exit as cleanly as
682  * possible.  For each capability, we let its run queue drain, and
683  * allow the workers to stop.
684  *
685  * This function should be called when interrupted and
686  * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
687  * will exit the scheduler and call taskStop(), and any bound thread
688  * that wakes up will return to its caller.  Runnable threads are
689  * killed.
690  *
691  * ------------------------------------------------------------------------- */
692
693 void
694 shutdownCapability (Capability *cap, Task *task, rtsBool safe)
695 {
696     nat i;
697
698     task->cap = cap;
699
700     // Loop indefinitely until all the workers have exited and there
701     // are no Haskell threads left.  We used to bail out after 50
702     // iterations of this loop, but that occasionally left a worker
703     // running which caused problems later (the closeMutex() below
704     // isn't safe, for one thing).
705
706     for (i = 0; /* i < 50 */; i++) {
707         ASSERT(sched_state == SCHED_SHUTTING_DOWN);
708
709         debugTrace(DEBUG_sched, 
710                    "shutting down capability %d, attempt %d", cap->no, i);
711         ACQUIRE_LOCK(&cap->lock);
712         if (cap->running_task) {
713             RELEASE_LOCK(&cap->lock);
714             debugTrace(DEBUG_sched, "not owner, yielding");
715             yieldThread();
716             continue;
717         }
718         cap->running_task = task;
719
720         if (cap->spare_workers) {
721             // Look for workers that have died without removing
722             // themselves from the list; this could happen if the OS
723             // summarily killed the thread, for example.  This
724             // actually happens on Windows when the system is
725             // terminating the program, and the RTS is running in a
726             // DLL.
727             Task *t, *prev;
728             prev = NULL;
729             for (t = cap->spare_workers; t != NULL; t = t->next) {
730                 if (!osThreadIsAlive(t->id)) {
731                     debugTrace(DEBUG_sched, 
732                                "worker thread %p has died unexpectedly", (void *)t->id);
733                     cap->n_spare_workers--;
734                     if (!prev) {
735                         cap->spare_workers = t->next;
736                     } else {
737                         prev->next = t->next;
738                     }
739                     prev = t;
740                 }
741             }
742         }
743
744         if (!emptyRunQueue(cap) || cap->spare_workers) {
745             debugTrace(DEBUG_sched, 
746                        "runnable threads or workers still alive, yielding");
747             releaseCapability_(cap,rtsFalse); // this will wake up a worker
748             RELEASE_LOCK(&cap->lock);
749             yieldThread();
750             continue;
751         }
752
753         // If "safe", then busy-wait for any threads currently doing
754         // foreign calls.  If we're about to unload this DLL, for
755         // example, we need to be sure that there are no OS threads
756         // that will try to return to code that has been unloaded.
757         // We can be a bit more relaxed when this is a standalone
758         // program that is about to terminate, and let safe=false.
759         if (cap->suspended_ccalls && safe) {
760             debugTrace(DEBUG_sched, 
761                        "thread(s) are involved in foreign calls, yielding");
762             cap->running_task = NULL;
763             RELEASE_LOCK(&cap->lock);
764             // The IO manager thread might have been slow to start up,
765             // so the first attempt to kill it might not have
766             // succeeded.  Just in case, try again - the kill message
767             // will only be sent once.
768             //
769             // To reproduce this deadlock: run ffi002(threaded1)
770             // repeatedly on a loaded machine.
771             ioManagerDie();
772             yieldThread();
773             continue;
774         }
775
776         traceEventShutdown(cap);
777         RELEASE_LOCK(&cap->lock);
778         break;
779     }
780     // we now have the Capability, its run queue and spare workers
781     // list are both empty.
782
783     // ToDo: we can't drop this mutex, because there might still be
784     // threads performing foreign calls that will eventually try to 
785     // return via resumeThread() and attempt to grab cap->lock.
786     // closeMutex(&cap->lock);
787 }
788
789 /* ----------------------------------------------------------------------------
790  * tryGrabCapability
791  *
792  * Attempt to gain control of a Capability if it is free.
793  *
794  * ------------------------------------------------------------------------- */
795
796 rtsBool
797 tryGrabCapability (Capability *cap, Task *task)
798 {
799     if (cap->running_task != NULL) return rtsFalse;
800     ACQUIRE_LOCK(&cap->lock);
801     if (cap->running_task != NULL) {
802         RELEASE_LOCK(&cap->lock);
803         return rtsFalse;
804     }
805     task->cap = cap;
806     cap->running_task = task;
807     RELEASE_LOCK(&cap->lock);
808     return rtsTrue;
809 }
810
811
812 #endif /* THREADED_RTS */
813
814 static void
815 freeCapability (Capability *cap)
816 {
817     stgFree(cap->mut_lists);
818     stgFree(cap->saved_mut_lists);
819 #if defined(THREADED_RTS)
820     freeSparkPool(cap->sparks);
821 #endif
822 }
823
824 void
825 freeCapabilities (void)
826 {
827 #if defined(THREADED_RTS)
828     nat i;
829     for (i=0; i < n_capabilities; i++) {
830         freeCapability(&capabilities[i]);
831     }
832 #else
833     freeCapability(&MainCapability);
834 #endif
835 }
836
837 /* ---------------------------------------------------------------------------
838    Mark everything directly reachable from the Capabilities.  When
839    using multiple GC threads, each GC thread marks all Capabilities
840    for which (c `mod` n == 0), for Capability c and thread n.
841    ------------------------------------------------------------------------ */
842
843 void
844 markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta, 
845                       rtsBool no_mark_sparks USED_IF_THREADS)
846 {
847     nat i;
848     Capability *cap;
849     InCall *incall;
850
851     // Each GC thread is responsible for following roots from the
852     // Capability of the same number.  There will usually be the same
853     // or fewer Capabilities as GC threads, but just in case there
854     // are more, we mark every Capability whose number is the GC
855     // thread's index plus a multiple of the number of GC threads.
856     for (i = i0; i < n_capabilities; i += delta) {
857         cap = &capabilities[i];
858         evac(user, (StgClosure **)(void *)&cap->run_queue_hd);
859         evac(user, (StgClosure **)(void *)&cap->run_queue_tl);
860 #if defined(THREADED_RTS)
861         evac(user, (StgClosure **)(void *)&cap->inbox);
862 #endif
863         for (incall = cap->suspended_ccalls; incall != NULL; 
864              incall=incall->next) {
865             evac(user, (StgClosure **)(void *)&incall->suspended_tso);
866         }
867
868 #if defined(THREADED_RTS)
869         if (!no_mark_sparks) {
870             traverseSparkQueue (evac, user, cap);
871         }
872 #endif
873     }
874
875 #if !defined(THREADED_RTS)
876     evac(user, (StgClosure **)(void *)&blocked_queue_hd);
877     evac(user, (StgClosure **)(void *)&blocked_queue_tl);
878     evac(user, (StgClosure **)(void *)&sleeping_queue);
879 #endif 
880 }
881
882 void
883 markCapabilities (evac_fn evac, void *user)
884 {
885     markSomeCapabilities(evac, user, 0, 1, rtsFalse);
886 }
887
888 /* -----------------------------------------------------------------------------
889    Messages
890    -------------------------------------------------------------------------- */
891