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