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