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