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