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