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