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