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