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