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