95050baaa98af5e645869366540b768b705a2a99
[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           traceSchedEvent(cap, EVENT_RUN_SPARK, cap->r.rCurrentTSO, 0);
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               traceSchedEvent(cap, EVENT_STEAL_SPARK, 
136                               cap->r.rCurrentTSO, robbed->no);
137               
138               return spark;
139           }
140           // otherwise: no success, try next one
141       }
142   } while (retry);
143
144   debugTrace(DEBUG_sched, "No sparks stolen");
145   return NULL;
146 }
147
148 // Returns True if any spark pool is non-empty at this moment in time
149 // The result is only valid for an instant, of course, so in a sense
150 // is immediately invalid, and should not be relied upon for
151 // correctness.
152 rtsBool
153 anySparks (void)
154 {
155     nat i;
156
157     for (i=0; i < n_capabilities; i++) {
158         if (!emptySparkPoolCap(&capabilities[i])) {
159             return rtsTrue;
160         }
161     }
162     return rtsFalse;
163 }
164 #endif
165
166 /* -----------------------------------------------------------------------------
167  * Manage the returning_tasks lists.
168  *
169  * These functions require cap->lock
170  * -------------------------------------------------------------------------- */
171
172 #if defined(THREADED_RTS)
173 STATIC_INLINE void
174 newReturningTask (Capability *cap, Task *task)
175 {
176     ASSERT_LOCK_HELD(&cap->lock);
177     ASSERT(task->return_link == NULL);
178     if (cap->returning_tasks_hd) {
179         ASSERT(cap->returning_tasks_tl->return_link == NULL);
180         cap->returning_tasks_tl->return_link = task;
181     } else {
182         cap->returning_tasks_hd = task;
183     }
184     cap->returning_tasks_tl = task;
185 }
186
187 STATIC_INLINE Task *
188 popReturningTask (Capability *cap)
189 {
190     ASSERT_LOCK_HELD(&cap->lock);
191     Task *task;
192     task = cap->returning_tasks_hd;
193     ASSERT(task);
194     cap->returning_tasks_hd = task->return_link;
195     if (!cap->returning_tasks_hd) {
196         cap->returning_tasks_tl = NULL;
197     }
198     task->return_link = NULL;
199     return task;
200 }
201 #endif
202
203 /* ----------------------------------------------------------------------------
204  * Initialisation
205  *
206  * The Capability is initially marked not free.
207  * ------------------------------------------------------------------------- */
208
209 static void
210 initCapability( Capability *cap, nat i )
211 {
212     nat g;
213
214     cap->no = i;
215     cap->in_haskell        = rtsFalse;
216     cap->in_gc             = rtsFalse;
217
218     cap->run_queue_hd      = END_TSO_QUEUE;
219     cap->run_queue_tl      = END_TSO_QUEUE;
220
221 #if defined(THREADED_RTS)
222     initMutex(&cap->lock);
223     cap->running_task      = NULL; // indicates cap is free
224     cap->spare_workers     = NULL;
225     cap->suspended_ccalling_tasks = NULL;
226     cap->returning_tasks_hd = NULL;
227     cap->returning_tasks_tl = NULL;
228     cap->wakeup_queue_hd    = END_TSO_QUEUE;
229     cap->wakeup_queue_tl    = END_TSO_QUEUE;
230     cap->sparks_created     = 0;
231     cap->sparks_converted   = 0;
232     cap->sparks_pruned      = 0;
233 #endif
234
235     cap->f.stgEagerBlackholeInfo = (W_)&__stg_EAGER_BLACKHOLE_info;
236     cap->f.stgGCEnter1     = (StgFunPtr)__stg_gc_enter_1;
237     cap->f.stgGCFun        = (StgFunPtr)__stg_gc_fun;
238
239     cap->mut_lists  = stgMallocBytes(sizeof(bdescr *) *
240                                      RtsFlags.GcFlags.generations,
241                                      "initCapability");
242     cap->saved_mut_lists = stgMallocBytes(sizeof(bdescr *) *
243                                           RtsFlags.GcFlags.generations,
244                                           "initCapability");
245
246     for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
247         cap->mut_lists[g] = NULL;
248     }
249
250     cap->free_tvar_watch_queues = END_STM_WATCH_QUEUE;
251     cap->free_invariant_check_queues = END_INVARIANT_CHECK_QUEUE;
252     cap->free_trec_chunks = END_STM_CHUNK_LIST;
253     cap->free_trec_headers = NO_TREC;
254     cap->transaction_tokens = 0;
255     cap->context_switch = 0;
256 }
257
258 /* ---------------------------------------------------------------------------
259  * Function:  initCapabilities()
260  *
261  * Purpose:   set up the Capability handling. For the THREADED_RTS build,
262  *            we keep a table of them, the size of which is
263  *            controlled by the user via the RTS flag -N.
264  *
265  * ------------------------------------------------------------------------- */
266 void
267 initCapabilities( void )
268 {
269 #if defined(THREADED_RTS)
270     nat i;
271
272 #ifndef REG_Base
273     // We can't support multiple CPUs if BaseReg is not a register
274     if (RtsFlags.ParFlags.nNodes > 1) {
275         errorBelch("warning: multiple CPUs not supported in this build, reverting to 1");
276         RtsFlags.ParFlags.nNodes = 1;
277     }
278 #endif
279
280     n_capabilities = RtsFlags.ParFlags.nNodes;
281
282     if (n_capabilities == 1) {
283         capabilities = &MainCapability;
284         // THREADED_RTS must work on builds that don't have a mutable
285         // BaseReg (eg. unregisterised), so in this case
286         // capabilities[0] must coincide with &MainCapability.
287     } else {
288         capabilities = stgMallocBytes(n_capabilities * sizeof(Capability),
289                                       "initCapabilities");
290     }
291
292     for (i = 0; i < n_capabilities; i++) {
293         initCapability(&capabilities[i], i);
294     }
295
296     debugTrace(DEBUG_sched, "allocated %d capabilities", n_capabilities);
297
298 #else /* !THREADED_RTS */
299
300     n_capabilities = 1;
301     capabilities = &MainCapability;
302     initCapability(&MainCapability, 0);
303
304 #endif
305
306     // There are no free capabilities to begin with.  We will start
307     // a worker Task to each Capability, which will quickly put the
308     // Capability on the free list when it finds nothing to do.
309     last_free_capability = &capabilities[0];
310 }
311
312 /* ----------------------------------------------------------------------------
313  * setContextSwitches: cause all capabilities to context switch as
314  * soon as possible.
315  * ------------------------------------------------------------------------- */
316
317 void setContextSwitches(void)
318 {
319     nat i;
320     for (i=0; i < n_capabilities; i++) {
321         contextSwitchCapability(&capabilities[i]);
322     }
323 }
324
325 /* ----------------------------------------------------------------------------
326  * Give a Capability to a Task.  The task must currently be sleeping
327  * on its condition variable.
328  *
329  * Requires cap->lock (modifies cap->running_task).
330  *
331  * When migrating a Task, the migrater must take task->lock before
332  * modifying task->cap, to synchronise with the waking up Task.
333  * Additionally, the migrater should own the Capability (when
334  * migrating the run queue), or cap->lock (when migrating
335  * returning_workers).
336  *
337  * ------------------------------------------------------------------------- */
338
339 #if defined(THREADED_RTS)
340 STATIC_INLINE void
341 giveCapabilityToTask (Capability *cap USED_IF_DEBUG, Task *task)
342 {
343     ASSERT_LOCK_HELD(&cap->lock);
344     ASSERT(task->cap == cap);
345     debugTrace(DEBUG_sched, "passing capability %d to %s %p",
346                cap->no, task->tso ? "bound task" : "worker",
347                (void *)task->id);
348     ACQUIRE_LOCK(&task->lock);
349     task->wakeup = rtsTrue;
350     // the wakeup flag is needed because signalCondition() doesn't
351     // flag the condition if the thread is already runniing, but we want
352     // it to be sticky.
353     signalCondition(&task->cond);
354     RELEASE_LOCK(&task->lock);
355 }
356 #endif
357
358 /* ----------------------------------------------------------------------------
359  * Function:  releaseCapability(Capability*)
360  *
361  * Purpose:   Letting go of a capability. Causes a
362  *            'returning worker' thread or a 'waiting worker'
363  *            to wake up, in that order.
364  * ------------------------------------------------------------------------- */
365
366 #if defined(THREADED_RTS)
367 void
368 releaseCapability_ (Capability* cap, 
369                     rtsBool always_wakeup)
370 {
371     Task *task;
372
373     task = cap->running_task;
374
375     ASSERT_PARTIAL_CAPABILITY_INVARIANTS(cap,task);
376
377     cap->running_task = NULL;
378
379     // Check to see whether a worker thread can be given
380     // the go-ahead to return the result of an external call..
381     if (cap->returning_tasks_hd != NULL) {
382         giveCapabilityToTask(cap,cap->returning_tasks_hd);
383         // The Task pops itself from the queue (see waitForReturnCapability())
384         return;
385     }
386
387     if (waiting_for_gc == PENDING_GC_SEQ) {
388       last_free_capability = cap; // needed?
389       debugTrace(DEBUG_sched, "GC pending, set capability %d free", cap->no);
390       return;
391     } 
392
393
394     // If the next thread on the run queue is a bound thread,
395     // give this Capability to the appropriate Task.
396     if (!emptyRunQueue(cap) && cap->run_queue_hd->bound) {
397         // Make sure we're not about to try to wake ourselves up
398         ASSERT(task != cap->run_queue_hd->bound);
399         task = cap->run_queue_hd->bound;
400         giveCapabilityToTask(cap,task);
401         return;
402     }
403
404     if (!cap->spare_workers) {
405         // Create a worker thread if we don't have one.  If the system
406         // is interrupted, we only create a worker task if there
407         // are threads that need to be completed.  If the system is
408         // shutting down, we never create a new worker.
409         if (sched_state < SCHED_SHUTTING_DOWN || !emptyRunQueue(cap)) {
410             debugTrace(DEBUG_sched,
411                        "starting new worker on capability %d", cap->no);
412             startWorkerTask(cap, workerStart);
413             return;
414         }
415     }
416
417     // If we have an unbound thread on the run queue, or if there's
418     // anything else to do, give the Capability to a worker thread.
419     if (always_wakeup || 
420         !emptyRunQueue(cap) || !emptyWakeupQueue(cap) ||
421         !emptySparkPoolCap(cap) || globalWorkToDo()) {
422         if (cap->spare_workers) {
423             giveCapabilityToTask(cap,cap->spare_workers);
424             // The worker Task pops itself from the queue;
425             return;
426         }
427     }
428
429     last_free_capability = cap;
430     debugTrace(DEBUG_sched, "freeing capability %d", cap->no);
431 }
432
433 void
434 releaseCapability (Capability* cap USED_IF_THREADS)
435 {
436     ACQUIRE_LOCK(&cap->lock);
437     releaseCapability_(cap, rtsFalse);
438     RELEASE_LOCK(&cap->lock);
439 }
440
441 void
442 releaseAndWakeupCapability (Capability* cap USED_IF_THREADS)
443 {
444     ACQUIRE_LOCK(&cap->lock);
445     releaseCapability_(cap, rtsTrue);
446     RELEASE_LOCK(&cap->lock);
447 }
448
449 static void
450 releaseCapabilityAndQueueWorker (Capability* cap USED_IF_THREADS)
451 {
452     Task *task;
453
454     ACQUIRE_LOCK(&cap->lock);
455
456     task = cap->running_task;
457
458     // If the current task is a worker, save it on the spare_workers
459     // list of this Capability.  A worker can mark itself as stopped,
460     // in which case it is not replaced on the spare_worker queue.
461     // This happens when the system is shutting down (see
462     // Schedule.c:workerStart()).
463     // Also, be careful to check that this task hasn't just exited
464     // Haskell to do a foreign call (task->suspended_tso).
465     if (!isBoundTask(task) && !task->stopped && !task->suspended_tso) {
466         task->next = cap->spare_workers;
467         cap->spare_workers = task;
468     }
469     // Bound tasks just float around attached to their TSOs.
470
471     releaseCapability_(cap,rtsFalse);
472
473     RELEASE_LOCK(&cap->lock);
474 }
475 #endif
476
477 /* ----------------------------------------------------------------------------
478  * waitForReturnCapability( Task *task )
479  *
480  * Purpose:  when an OS thread returns from an external call,
481  * it calls waitForReturnCapability() (via Schedule.resumeThread())
482  * to wait for permission to enter the RTS & communicate the
483  * result of the external call back to the Haskell thread that
484  * made it.
485  *
486  * ------------------------------------------------------------------------- */
487 void
488 waitForReturnCapability (Capability **pCap, Task *task)
489 {
490 #if !defined(THREADED_RTS)
491
492     MainCapability.running_task = task;
493     task->cap = &MainCapability;
494     *pCap = &MainCapability;
495
496 #else
497     Capability *cap = *pCap;
498
499     if (cap == NULL) {
500         // Try last_free_capability first
501         cap = last_free_capability;
502         if (cap->running_task) {
503             nat i;
504             // otherwise, search for a free capability
505             cap = NULL;
506             for (i = 0; i < n_capabilities; i++) {
507                 if (!capabilities[i].running_task) {
508                     cap = &capabilities[i];
509                     break;
510                 }
511             }
512             if (cap == NULL) {
513                 // Can't find a free one, use last_free_capability.
514                 cap = last_free_capability;
515             }
516         }
517
518         // record the Capability as the one this Task is now assocated with.
519         task->cap = cap;
520
521     } else {
522         ASSERT(task->cap == cap);
523     }
524
525     ACQUIRE_LOCK(&cap->lock);
526
527     debugTrace(DEBUG_sched, "returning; I want capability %d", cap->no);
528
529     if (!cap->running_task) {
530         // It's free; just grab it
531         cap->running_task = task;
532         RELEASE_LOCK(&cap->lock);
533     } else {
534         newReturningTask(cap,task);
535         RELEASE_LOCK(&cap->lock);
536
537         for (;;) {
538             ACQUIRE_LOCK(&task->lock);
539             // task->lock held, cap->lock not held
540             if (!task->wakeup) waitCondition(&task->cond, &task->lock);
541             cap = task->cap;
542             task->wakeup = rtsFalse;
543             RELEASE_LOCK(&task->lock);
544
545             // now check whether we should wake up...
546             ACQUIRE_LOCK(&cap->lock);
547             if (cap->running_task == NULL) {
548                 if (cap->returning_tasks_hd != task) {
549                     giveCapabilityToTask(cap,cap->returning_tasks_hd);
550                     RELEASE_LOCK(&cap->lock);
551                     continue;
552                 }
553                 cap->running_task = task;
554                 popReturningTask(cap);
555                 RELEASE_LOCK(&cap->lock);
556                 break;
557             }
558             RELEASE_LOCK(&cap->lock);
559         }
560
561     }
562
563     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
564
565     debugTrace(DEBUG_sched, "resuming capability %d", cap->no);
566
567     *pCap = cap;
568 #endif
569 }
570
571 #if defined(THREADED_RTS)
572 /* ----------------------------------------------------------------------------
573  * yieldCapability
574  * ------------------------------------------------------------------------- */
575
576 void
577 yieldCapability (Capability** pCap, Task *task)
578 {
579     Capability *cap = *pCap;
580
581     if (waiting_for_gc == PENDING_GC_PAR) {
582         traceSchedEvent(cap, EVENT_GC_START, 0, 0);
583         gcWorkerThread(cap);
584         traceSchedEvent(cap, EVENT_GC_END, 0, 0);
585         return;
586     }
587
588         debugTrace(DEBUG_sched, "giving up capability %d", cap->no);
589
590         // We must now release the capability and wait to be woken up
591         // again.
592         task->wakeup = rtsFalse;
593         releaseCapabilityAndQueueWorker(cap);
594
595         for (;;) {
596             ACQUIRE_LOCK(&task->lock);
597             // task->lock held, cap->lock not held
598             if (!task->wakeup) waitCondition(&task->cond, &task->lock);
599             cap = task->cap;
600             task->wakeup = rtsFalse;
601             RELEASE_LOCK(&task->lock);
602
603             debugTrace(DEBUG_sched, "woken up on capability %d", cap->no);
604
605             ACQUIRE_LOCK(&cap->lock);
606             if (cap->running_task != NULL) {
607                 debugTrace(DEBUG_sched, 
608                            "capability %d is owned by another task", cap->no);
609                 RELEASE_LOCK(&cap->lock);
610                 continue;
611             }
612
613             if (task->tso == NULL) {
614                 ASSERT(cap->spare_workers != NULL);
615                 // if we're not at the front of the queue, release it
616                 // again.  This is unlikely to happen.
617                 if (cap->spare_workers != task) {
618                     giveCapabilityToTask(cap,cap->spare_workers);
619                     RELEASE_LOCK(&cap->lock);
620                     continue;
621                 }
622                 cap->spare_workers = task->next;
623                 task->next = NULL;
624             }
625             cap->running_task = task;
626             RELEASE_LOCK(&cap->lock);
627             break;
628         }
629
630         debugTrace(DEBUG_sched, "resuming capability %d", cap->no);
631         ASSERT(cap->running_task == task);
632
633     *pCap = cap;
634
635     ASSERT_FULL_CAPABILITY_INVARIANTS(cap,task);
636
637     return;
638 }
639
640 /* ----------------------------------------------------------------------------
641  * Wake up a thread on a Capability.
642  *
643  * This is used when the current Task is running on a Capability and
644  * wishes to wake up a thread on a different Capability.
645  * ------------------------------------------------------------------------- */
646
647 void
648 wakeupThreadOnCapability (Capability *my_cap, 
649                           Capability *other_cap, 
650                           StgTSO *tso)
651 {
652     ACQUIRE_LOCK(&other_cap->lock);
653
654     // ASSUMES: cap->lock is held (asserted in wakeupThreadOnCapability)
655     if (tso->bound) {
656         ASSERT(tso->bound->cap == tso->cap);
657         tso->bound->cap = other_cap;
658     }
659     tso->cap = other_cap;
660
661     ASSERT(tso->bound ? tso->bound->cap == other_cap : 1);
662
663     if (other_cap->running_task == NULL) {
664         // nobody is running this Capability, we can add our thread
665         // directly onto the run queue and start up a Task to run it.
666
667         other_cap->running_task = myTask(); 
668             // precond for releaseCapability_() and appendToRunQueue()
669
670         appendToRunQueue(other_cap,tso);
671
672         releaseCapability_(other_cap,rtsFalse);
673     } else {
674         appendToWakeupQueue(my_cap,other_cap,tso);
675         other_cap->context_switch = 1;
676         // someone is running on this Capability, so it cannot be
677         // freed without first checking the wakeup queue (see
678         // releaseCapability_).
679     }
680
681     RELEASE_LOCK(&other_cap->lock);
682 }
683
684 /* ----------------------------------------------------------------------------
685  * prodCapability
686  *
687  * If a Capability is currently idle, wake up a Task on it.  Used to 
688  * get every Capability into the GC.
689  * ------------------------------------------------------------------------- */
690
691 void
692 prodCapability (Capability *cap, Task *task)
693 {
694     ACQUIRE_LOCK(&cap->lock);
695     if (!cap->running_task) {
696         cap->running_task = task;
697         releaseCapability_(cap,rtsTrue);
698     }
699     RELEASE_LOCK(&cap->lock);
700 }
701
702 /* ----------------------------------------------------------------------------
703  * shutdownCapability
704  *
705  * At shutdown time, we want to let everything exit as cleanly as
706  * possible.  For each capability, we let its run queue drain, and
707  * allow the workers to stop.
708  *
709  * This function should be called when interrupted and
710  * shutting_down_scheduler = rtsTrue, thus any worker that wakes up
711  * will exit the scheduler and call taskStop(), and any bound thread
712  * that wakes up will return to its caller.  Runnable threads are
713  * killed.
714  *
715  * ------------------------------------------------------------------------- */
716
717 void
718 shutdownCapability (Capability *cap, Task *task, rtsBool safe)
719 {
720     nat i;
721
722     task->cap = cap;
723
724     // Loop indefinitely until all the workers have exited and there
725     // are no Haskell threads left.  We used to bail out after 50
726     // iterations of this loop, but that occasionally left a worker
727     // running which caused problems later (the closeMutex() below
728     // isn't safe, for one thing).
729
730     for (i = 0; /* i < 50 */; i++) {
731         ASSERT(sched_state == SCHED_SHUTTING_DOWN);
732
733         debugTrace(DEBUG_sched, 
734                    "shutting down capability %d, attempt %d", cap->no, i);
735         ACQUIRE_LOCK(&cap->lock);
736         if (cap->running_task) {
737             RELEASE_LOCK(&cap->lock);
738             debugTrace(DEBUG_sched, "not owner, yielding");
739             yieldThread();
740             continue;
741         }
742         cap->running_task = task;
743
744         if (cap->spare_workers) {
745             // Look for workers that have died without removing
746             // themselves from the list; this could happen if the OS
747             // summarily killed the thread, for example.  This
748             // actually happens on Windows when the system is
749             // terminating the program, and the RTS is running in a
750             // DLL.
751             Task *t, *prev;
752             prev = NULL;
753             for (t = cap->spare_workers; t != NULL; t = t->next) {
754                 if (!osThreadIsAlive(t->id)) {
755                     debugTrace(DEBUG_sched, 
756                                "worker thread %p has died unexpectedly", (void *)t->id);
757                         if (!prev) {
758                             cap->spare_workers = t->next;
759                         } else {
760                             prev->next = t->next;
761                         }
762                         prev = t;
763                 }
764             }
765         }
766
767         if (!emptyRunQueue(cap) || cap->spare_workers) {
768             debugTrace(DEBUG_sched, 
769                        "runnable threads or workers still alive, yielding");
770             releaseCapability_(cap,rtsFalse); // this will wake up a worker
771             RELEASE_LOCK(&cap->lock);
772             yieldThread();
773             continue;
774         }
775
776         // If "safe", then busy-wait for any threads currently doing
777         // foreign calls.  If we're about to unload this DLL, for
778         // example, we need to be sure that there are no OS threads
779         // that will try to return to code that has been unloaded.
780         // We can be a bit more relaxed when this is a standalone
781         // program that is about to terminate, and let safe=false.
782         if (cap->suspended_ccalling_tasks && safe) {
783             debugTrace(DEBUG_sched, 
784                        "thread(s) are involved in foreign calls, yielding");
785             cap->running_task = NULL;
786             RELEASE_LOCK(&cap->lock);
787             yieldThread();
788             continue;
789         }
790             
791         traceSchedEvent(cap, EVENT_SHUTDOWN, 0, 0);
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     Task *task;
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->wakeup_queue_hd);
877         evac(user, (StgClosure **)(void *)&cap->wakeup_queue_tl);
878 #endif
879         for (task = cap->suspended_ccalling_tasks; task != NULL; 
880              task=task->next) {
881             evac(user, (StgClosure **)(void *)&task->suspended_tso);
882         }
883
884 #if defined(THREADED_RTS)
885         if (prune_sparks) {
886             pruneSparkQueue (evac, user, cap);
887         } else {
888             traverseSparkQueue (evac, user, cap);
889         }
890 #endif
891     }
892
893 #if !defined(THREADED_RTS)
894     evac(user, (StgClosure **)(void *)&blocked_queue_hd);
895     evac(user, (StgClosure **)(void *)&blocked_queue_tl);
896     evac(user, (StgClosure **)(void *)&sleeping_queue);
897 #endif 
898 }
899
900 void
901 markCapabilities (evac_fn evac, void *user)
902 {
903     markSomeCapabilities(evac, user, 0, 1, rtsFalse);
904 }