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