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