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