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