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