5f54ecae4d034785344e1e74166115da93e693ba
[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 blackholes_need_checking
66         || sched_state >= SCHED_INTERRUPTING
67         ;
68 }
69 #endif
70
71 #if defined(THREADED_RTS)
72 StgClosure *
73 findSpark (Capability *cap)
74 {
75   Capability *robbed;
76   StgClosurePtr spark;
77   rtsBool retry;
78   nat i = 0;
79
80   if (!emptyRunQueue(cap) || cap->returning_tasks_hd != NULL) {
81       // If there are other threads, don't try to run any new
82       // sparks: sparks might be speculative, we don't want to take
83       // resources away from the main computation.
84       return 0;
85   }
86
87   do {
88       retry = rtsFalse;
89
90       // first try to get a spark from our own pool.
91       // We should be using reclaimSpark(), because it works without
92       // needing any atomic instructions:
93       //   spark = reclaimSpark(cap->sparks);
94       // However, measurements show that this makes at least one benchmark
95       // slower (prsa) and doesn't affect the others.
96       spark = tryStealSpark(cap);
97       if (spark != NULL) {
98           cap->sparks_converted++;
99
100           // Post event for running a spark from capability's own pool.
101           traceEventRunSpark(cap, cap->r.rCurrentTSO);
102
103           return spark;
104       }
105       if (!emptySparkPoolCap(cap)) {
106           retry = rtsTrue;
107       }
108
109       if (n_capabilities == 1) { return NULL; } // makes no sense...
110
111       debugTrace(DEBUG_sched,
112                  "cap %d: Trying to steal work from other capabilities", 
113                  cap->no);
114
115       /* visit cap.s 0..n-1 in sequence until a theft succeeds. We could
116       start at a random place instead of 0 as well.  */
117       for ( i=0 ; i < n_capabilities ; i++ ) {
118           robbed = &capabilities[i];
119           if (cap == robbed)  // ourselves...
120               continue;
121
122           if (emptySparkPoolCap(robbed)) // nothing to steal here
123               continue;
124
125           spark = tryStealSpark(robbed);
126           if (spark == NULL && !emptySparkPoolCap(robbed)) {
127               // we conflicted with another thread while trying to steal;
128               // try again later.
129               retry = rtsTrue;
130           }
131
132           if (spark != NULL) {
133               cap->sparks_converted++;
134
135               traceEventStealSpark(cap, cap->r.rCurrentTSO, robbed->no);
136               
137               return spark;
138           }
139           // otherwise: no success, try next one
140       }
141   } while (retry);
142
143   debugTrace(DEBUG_sched, "No sparks stolen");
144   return NULL;
145 }
146
147 // Returns True if any spark pool is non-empty at this moment in time
148 // The result is only valid for an instant, of course, so in a sense
149 // is immediately invalid, and should not be relied upon for
150 // correctness.
151 rtsBool
152 anySparks (void)
153 {
154     nat i;
155
156     for (i=0; i < n_capabilities; i++) {
157         if (!emptySparkPoolCap(&capabilities[i])) {
158             return rtsTrue;
159         }
160     }
161     return rtsFalse;
162 }
163 #endif
164
165 /* -----------------------------------------------------------------------------
166  * Manage the returning_tasks lists.
167  *
168  * These functions require cap->lock
169  * -------------------------------------------------------------------------- */
170
171 #if defined(THREADED_RTS)
172 STATIC_INLINE void
173 newReturningTask (Capability *cap, Task *task)
174 {
175     ASSERT_LOCK_HELD(&cap->lock);
176     ASSERT(task->next == NULL);
177     if (cap->returning_tasks_hd) {
178         ASSERT(cap->returning_tasks_tl->next == NULL);
179         cap->returning_tasks_tl->next = task;
180     } else {
181         cap->returning_tasks_hd = task;
182     }
183     cap->returning_tasks_tl = task;
184 }
185
186 STATIC_INLINE Task *
187 popReturningTask (Capability *cap)
188 {
189     ASSERT_LOCK_HELD(&cap->lock);
190     Task *task;
191     task = cap->returning_tasks_hd;
192     ASSERT(task);
193     cap->returning_tasks_hd = task->next;
194     if (!cap->returning_tasks_hd) {
195         cap->returning_tasks_tl = NULL;
196     }
197     task->next = NULL;
198     return task;
199 }
200 #endif
201
202 /* ----------------------------------------------------------------------------
203  * Initialisation
204  *
205  * The Capability is initially marked not free.
206  * ------------------------------------------------------------------------- */
207
208 static void
209 initCapability( Capability *cap, nat i )
210 {
211     nat g;
212
213     cap->no = i;
214     cap->in_haskell        = rtsFalse;
215
216     cap->run_queue_hd      = END_TSO_QUEUE;
217     cap->run_queue_tl      = END_TSO_QUEUE;
218
219 #if defined(THREADED_RTS)
220     initMutex(&cap->lock);
221     cap->running_task      = NULL; // indicates cap is free
222     cap->spare_workers     = NULL;
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 current task is a worker, save it on the spare_workers
460     // list of this Capability.  A worker can mark itself as stopped,
461     // in which case it is not replaced on the spare_worker queue.
462     // This happens when the system is shutting down (see
463     // Schedule.c:workerStart()).
464     if (!isBoundTask(task) && !task->stopped) {
465         task->next = cap->spare_workers;
466         cap->spare_workers = task;
467     }
468     // Bound tasks just float around attached to their TSOs.
469
470     releaseCapability_(cap,rtsFalse);
471
472     RELEASE_LOCK(&cap->lock);
473 }
474 #endif
475
476 /* ----------------------------------------------------------------------------
477  * waitForReturnCapability( Task *task )
478  *
479  * Purpose:  when an OS thread returns from an external call,
480  * it calls waitForReturnCapability() (via Schedule.resumeThread())
481  * to wait for permission to enter the RTS & communicate the
482  * result of the external call back to the Haskell thread that
483  * made it.
484  *
485  * ------------------------------------------------------------------------- */
486 void
487 waitForReturnCapability (Capability **pCap, Task *task)
488 {
489 #if !defined(THREADED_RTS)
490
491     MainCapability.running_task = task;
492     task->cap = &MainCapability;
493     *pCap = &MainCapability;
494
495 #else
496     Capability *cap = *pCap;
497
498     if (cap == NULL) {
499         // Try last_free_capability first
500         cap = last_free_capability;
501         if (cap->running_task) {
502             nat i;
503             // otherwise, search for a free capability
504             cap = NULL;
505             for (i = 0; i < n_capabilities; i++) {
506                 if (!capabilities[i].running_task) {
507                     cap = &capabilities[i];
508                     break;
509                 }
510             }
511             if (cap == NULL) {
512                 // Can't find a free one, use last_free_capability.
513                 cap = last_free_capability;
514             }
515         }
516
517         // record the Capability as the one this Task is now assocated with.
518         task->cap = cap;
519
520     } else {
521         ASSERT(task->cap == cap);
522     }
523
524     ACQUIRE_LOCK(&cap->lock);
525
526     debugTrace(DEBUG_sched, "returning; I want capability %d", cap->no);
527
528     if (!cap->running_task) {
529         // It's free; just grab it
530         cap->running_task = task;
531         RELEASE_LOCK(&cap->lock);
532     } else {
533         newReturningTask(cap,task);
534         RELEASE_LOCK(&cap->lock);
535
536         for (;;) {
537             ACQUIRE_LOCK(&task->lock);
538             // task->lock held, cap->lock not held
539             if (!task->wakeup) waitCondition(&task->cond, &task->lock);
540             cap = task->cap;
541             task->wakeup = rtsFalse;
542             RELEASE_LOCK(&task->lock);
543
544             // now check whether we should wake up...
545             ACQUIRE_LOCK(&cap->lock);
546             if (cap->running_task == NULL) {
547                 if (cap->returning_tasks_hd != task) {
548                     giveCapabilityToTask(cap,cap->returning_tasks_hd);
549                     RELEASE_LOCK(&cap->lock);
550                     continue;
551                 }
552                 cap->running_task = task;
553                 popReturningTask(cap);
554                 RELEASE_LOCK(&cap->lock);
555                 break;
556             }
557             RELEASE_LOCK(&cap->lock);
558         }
559
560     }
561
562     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
563
564     debugTrace(DEBUG_sched, "resuming capability %d", cap->no);
565
566     *pCap = cap;
567 #endif
568 }
569
570 #if defined(THREADED_RTS)
571 /* ----------------------------------------------------------------------------
572  * yieldCapability
573  * ------------------------------------------------------------------------- */
574
575 void
576 yieldCapability (Capability** pCap, Task *task)
577 {
578     Capability *cap = *pCap;
579
580     if (waiting_for_gc == PENDING_GC_PAR) {
581         traceEventGcStart(cap);
582         gcWorkerThread(cap);
583         traceEventGcEnd(cap);
584         return;
585     }
586
587         debugTrace(DEBUG_sched, "giving up capability %d", cap->no);
588
589         // We must now release the capability and wait to be woken up
590         // again.
591         task->wakeup = rtsFalse;
592         releaseCapabilityAndQueueWorker(cap);
593
594         for (;;) {
595             ACQUIRE_LOCK(&task->lock);
596             // task->lock held, cap->lock not held
597             if (!task->wakeup) waitCondition(&task->cond, &task->lock);
598             cap = task->cap;
599             task->wakeup = rtsFalse;
600             RELEASE_LOCK(&task->lock);
601
602             debugTrace(DEBUG_sched, "woken up on capability %d", cap->no);
603
604             ACQUIRE_LOCK(&cap->lock);
605             if (cap->running_task != NULL) {
606                 debugTrace(DEBUG_sched, 
607                            "capability %d is owned by another task", cap->no);
608                 RELEASE_LOCK(&cap->lock);
609                 continue;
610             }
611
612             if (task->incall->tso == NULL) {
613                 ASSERT(cap->spare_workers != NULL);
614                 // if we're not at the front of the queue, release it
615                 // again.  This is unlikely to happen.
616                 if (cap->spare_workers != task) {
617                     giveCapabilityToTask(cap,cap->spare_workers);
618                     RELEASE_LOCK(&cap->lock);
619                     continue;
620                 }
621                 cap->spare_workers = task->next;
622                 task->next = NULL;
623             }
624             cap->running_task = task;
625             RELEASE_LOCK(&cap->lock);
626             break;
627         }
628
629         debugTrace(DEBUG_sched, "resuming capability %d", cap->no);
630         ASSERT(cap->running_task == task);
631
632     *pCap = cap;
633
634     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
635
636     return;
637 }
638
639 /* ----------------------------------------------------------------------------
640  * Wake up a thread on a Capability.
641  *
642  * This is used when the current Task is running on a Capability and
643  * wishes to wake up a thread on a different Capability.
644  * ------------------------------------------------------------------------- */
645
646 void
647 wakeupThreadOnCapability (Capability *cap,
648                           Capability *other_cap, 
649                           StgTSO *tso)
650 {
651     MessageWakeup *msg;
652
653     // ASSUMES: cap->lock is held (asserted in wakeupThreadOnCapability)
654     if (tso->bound) {
655         ASSERT(tso->bound->task->cap == tso->cap);
656         tso->bound->task->cap = other_cap;
657     }
658     tso->cap = other_cap;
659
660     ASSERT(tso->why_blocked != BlockedOnMsgWakeup || 
661            tso->block_info.closure->header.info == &stg_IND_info);
662
663     ASSERT(tso->block_info.closure->header.info != &stg_MSG_WAKEUP_info);
664
665     msg = (MessageWakeup*) allocate(cap, sizeofW(MessageWakeup));
666     msg->header.info = &stg_MSG_WAKEUP_info;
667     msg->tso = tso;
668     tso->block_info.closure = (StgClosure *)msg;
669     dirty_TSO(cap, tso);
670     write_barrier();
671     tso->why_blocked = BlockedOnMsgWakeup;
672
673     sendMessage(other_cap, (Message*)msg);
674 }
675
676 /* ----------------------------------------------------------------------------
677  * prodCapability
678  *
679  * If a Capability is currently idle, wake up a Task on it.  Used to 
680  * get every Capability into the GC.
681  * ------------------------------------------------------------------------- */
682
683 void
684 prodCapability (Capability *cap, Task *task)
685 {
686     ACQUIRE_LOCK(&cap->lock);
687     if (!cap->running_task) {
688         cap->running_task = task;
689         releaseCapability_(cap,rtsTrue);
690     }
691     RELEASE_LOCK(&cap->lock);
692 }
693
694 /* ----------------------------------------------------------------------------
695  * shutdownCapability
696  *
697  * At shutdown time, we want to let everything exit as cleanly as
698  * possible.  For each capability, we let its run queue drain, and
699  * allow the workers to stop.
700  *
701  * This function should be called when interrupted and
702  * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
703  * will exit the scheduler and call taskStop(), and any bound thread
704  * that wakes up will return to its caller.  Runnable threads are
705  * killed.
706  *
707  * ------------------------------------------------------------------------- */
708
709 void
710 shutdownCapability (Capability *cap, Task *task, rtsBool safe)
711 {
712     nat i;
713
714     task->cap = cap;
715
716     // Loop indefinitely until all the workers have exited and there
717     // are no Haskell threads left.  We used to bail out after 50
718     // iterations of this loop, but that occasionally left a worker
719     // running which caused problems later (the closeMutex() below
720     // isn't safe, for one thing).
721
722     for (i = 0; /* i < 50 */; i++) {
723         ASSERT(sched_state == SCHED_SHUTTING_DOWN);
724
725         debugTrace(DEBUG_sched, 
726                    "shutting down capability %d, attempt %d", cap->no, i);
727         ACQUIRE_LOCK(&cap->lock);
728         if (cap->running_task) {
729             RELEASE_LOCK(&cap->lock);
730             debugTrace(DEBUG_sched, "not owner, yielding");
731             yieldThread();
732             continue;
733         }
734         cap->running_task = task;
735
736         if (cap->spare_workers) {
737             // Look for workers that have died without removing
738             // themselves from the list; this could happen if the OS
739             // summarily killed the thread, for example.  This
740             // actually happens on Windows when the system is
741             // terminating the program, and the RTS is running in a
742             // DLL.
743             Task *t, *prev;
744             prev = NULL;
745             for (t = cap->spare_workers; t != NULL; t = t->next) {
746                 if (!osThreadIsAlive(t->id)) {
747                     debugTrace(DEBUG_sched, 
748                                "worker thread %p has died unexpectedly", (void *)t->id);
749                         if (!prev) {
750                             cap->spare_workers = t->next;
751                         } else {
752                             prev->next = t->next;
753                         }
754                         prev = t;
755                 }
756             }
757         }
758
759         if (!emptyRunQueue(cap) || cap->spare_workers) {
760             debugTrace(DEBUG_sched, 
761                        "runnable threads or workers still alive, yielding");
762             releaseCapability_(cap,rtsFalse); // this will wake up a worker
763             RELEASE_LOCK(&cap->lock);
764             yieldThread();
765             continue;
766         }
767
768         // If "safe", then busy-wait for any threads currently doing
769         // foreign calls.  If we're about to unload this DLL, for
770         // example, we need to be sure that there are no OS threads
771         // that will try to return to code that has been unloaded.
772         // We can be a bit more relaxed when this is a standalone
773         // program that is about to terminate, and let safe=false.
774         if (cap->suspended_ccalls && safe) {
775             debugTrace(DEBUG_sched, 
776                        "thread(s) are involved in foreign calls, yielding");
777             cap->running_task = NULL;
778             RELEASE_LOCK(&cap->lock);
779             // The IO manager thread might have been slow to start up,
780             // so the first attempt to kill it might not have
781             // succeeded.  Just in case, try again - the kill message
782             // will only be sent once.
783             //
784             // To reproduce this deadlock: run ffi002(threaded1)
785             // repeatedly on a loaded machine.
786             ioManagerDie();
787             yieldThread();
788             continue;
789         }
790
791         traceEventShutdown(cap);
792         RELEASE_LOCK(&cap->lock);
793         break;
794     }
795     // we now have the Capability, its run queue and spare workers
796     // list are both empty.
797
798     // ToDo: we can't drop this mutex, because there might still be
799     // threads performing foreign calls that will eventually try to 
800     // return via resumeThread() and attempt to grab cap->lock.
801     // closeMutex(&cap->lock);
802 }
803
804 /* ----------------------------------------------------------------------------
805  * tryGrabCapability
806  *
807  * Attempt to gain control of a Capability if it is free.
808  *
809  * ------------------------------------------------------------------------- */
810
811 rtsBool
812 tryGrabCapability (Capability *cap, Task *task)
813 {
814     if (cap->running_task != NULL) return rtsFalse;
815     ACQUIRE_LOCK(&cap->lock);
816     if (cap->running_task != NULL) {
817         RELEASE_LOCK(&cap->lock);
818         return rtsFalse;
819     }
820     task->cap = cap;
821     cap->running_task = task;
822     RELEASE_LOCK(&cap->lock);
823     return rtsTrue;
824 }
825
826
827 #endif /* THREADED_RTS */
828
829 static void
830 freeCapability (Capability *cap)
831 {
832     stgFree(cap->mut_lists);
833     stgFree(cap->saved_mut_lists);
834 #if defined(THREADED_RTS)
835     freeSparkPool(cap->sparks);
836 #endif
837 }
838
839 void
840 freeCapabilities (void)
841 {
842 #if defined(THREADED_RTS)
843     nat i;
844     for (i=0; i < n_capabilities; i++) {
845         freeCapability(&capabilities[i]);
846     }
847 #else
848     freeCapability(&MainCapability);
849 #endif
850 }
851
852 /* ---------------------------------------------------------------------------
853    Mark everything directly reachable from the Capabilities.  When
854    using multiple GC threads, each GC thread marks all Capabilities
855    for which (c `mod` n == 0), for Capability c and thread n.
856    ------------------------------------------------------------------------ */
857
858 void
859 markSomeCapabilities (evac_fn evac, void *user, nat i0, nat delta, 
860                       rtsBool prune_sparks USED_IF_THREADS)
861 {
862     nat i;
863     Capability *cap;
864     InCall *incall;
865
866     // Each GC thread is responsible for following roots from the
867     // Capability of the same number.  There will usually be the same
868     // or fewer Capabilities as GC threads, but just in case there
869     // are more, we mark every Capability whose number is the GC
870     // thread's index plus a multiple of the number of GC threads.
871     for (i = i0; i < n_capabilities; i += delta) {
872         cap = &capabilities[i];
873         evac(user, (StgClosure **)(void *)&cap->run_queue_hd);
874         evac(user, (StgClosure **)(void *)&cap->run_queue_tl);
875 #if defined(THREADED_RTS)
876         evac(user, (StgClosure **)(void *)&cap->inbox);
877 #endif
878         for (incall = cap->suspended_ccalls; incall != NULL; 
879              incall=incall->next) {
880             evac(user, (StgClosure **)(void *)&incall->suspended_tso);
881         }
882
883 #if defined(THREADED_RTS)
884         if (prune_sparks) {
885             pruneSparkQueue (evac, user, cap);
886         } else {
887             traverseSparkQueue (evac, user, cap);
888         }
889 #endif
890     }
891
892 #if !defined(THREADED_RTS)
893     evac(user, (StgClosure **)(void *)&blocked_queue_hd);
894     evac(user, (StgClosure **)(void *)&blocked_queue_tl);
895     evac(user, (StgClosure **)(void *)&sleeping_queue);
896 #endif 
897 }
898
899 void
900 markCapabilities (evac_fn evac, void *user)
901 {
902     markSomeCapabilities(evac, user, 0, 1, rtsFalse);
903 }
904
905 /* -----------------------------------------------------------------------------
906    Messages
907    -------------------------------------------------------------------------- */
908
909 #ifdef THREADED_RTS
910
911 void sendMessage(Capability *cap, Message *msg)
912 {
913     ACQUIRE_LOCK(&cap->lock);
914
915     msg->link = cap->inbox;
916     cap->inbox = msg;
917
918     if (cap->running_task == NULL) {
919         cap->running_task = myTask(); 
920             // precond for releaseCapability_()
921         releaseCapability_(cap,rtsFalse);
922     } else {
923         contextSwitchCapability(cap);
924     }
925
926     RELEASE_LOCK(&cap->lock);
927 }
928
929 #endif // THREADED_RTS