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