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