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