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