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