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