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