1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 2000-2006
5 * Sparking support for PARALLEL_HASKELL and THREADED_RTS versions of the RTS.
7 * -------------------------------------------------------------------------*/
9 #include "PosixSource.h"
17 # if defined(PARALLEL_HASKELL)
18 # include "ParallelRts.h"
19 # include "GranSimRts.h" // for GR_...
21 # include "GranSimRts.h"
26 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
28 static INLINE_ME void bump_hd (StgSparkPool *p)
29 { p->hd++; if (p->hd == p->lim) p->hd = p->base; }
31 static INLINE_ME void bump_tl (StgSparkPool *p)
32 { p->tl++; if (p->tl == p->lim) p->tl = p->base; }
34 /* -----------------------------------------------------------------------------
36 * Initialising spark pools.
38 * -------------------------------------------------------------------------- */
41 initSparkPool(StgSparkPool *pool)
43 pool->base = stgMallocBytes(RtsFlags.ParFlags.maxLocalSparks
44 * sizeof(StgClosure *),
46 pool->lim = pool->base + RtsFlags.ParFlags.maxLocalSparks;
47 pool->hd = pool->base;
48 pool->tl = pool->base;
52 initSparkPools( void )
55 /* walk over the capabilities, allocating a spark pool for each one */
57 for (i = 0; i < n_capabilities; i++) {
58 initSparkPool(&capabilities[i].r.rSparks);
61 /* allocate a single spark pool */
62 initSparkPool(&MainCapability.r.rSparks);
67 freeSparkPool(StgSparkPool *pool) {
71 /* -----------------------------------------------------------------------------
73 * findSpark: find a spark on the current Capability that we can fork
76 * -------------------------------------------------------------------------- */
79 findSpark (Capability *cap)
84 pool = &(cap->r.rSparks);
85 ASSERT_SPARK_POOL_INVARIANTS(pool);
87 while (pool->hd != pool->tl) {
90 if (closure_SHOULD_SPARK(spark)) {
92 if (RtsFlags.ParFlags.ParStats.Sparks)
93 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
94 GR_STEALING, ((StgTSO *)NULL), spark,
95 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
100 // spark pool is now empty
104 /* -----------------------------------------------------------------------------
106 * Turn a spark into a real thread
108 * -------------------------------------------------------------------------- */
111 createSparkThread (Capability *cap, StgClosure *p)
115 tso = createGenThread (cap, RtsFlags.GcFlags.initialStkSize, p);
116 appendToRunQueue(cap,tso);
119 /* -----------------------------------------------------------------------------
123 * -------------------------------------------------------------------------- */
128 newSpark (StgRegTable *reg, StgClosure *p)
130 StgSparkPool *pool = &(reg->rSparks);
132 /* I am not sure whether this is the right thing to do.
133 * Maybe it is better to exploit the tag information
134 * instead of throwing it away?
136 p = UNTAG_CLOSURE(p);
138 ASSERT_SPARK_POOL_INVARIANTS(pool);
140 if (closure_SHOULD_SPARK(p)) {
143 new_tl = pool->tl + 1;
144 if (new_tl == pool->lim) { new_tl = pool->base; }
145 if (new_tl != pool->hd) {
148 } else if (!closure_SHOULD_SPARK(*pool->hd)) {
149 // if the old closure is not sparkable, discard it and
150 // keep the new one. Otherwise, keep the old one.
154 #else /* DISCARD OLD */
157 if (pool->tl == pool->hd) { bump_hd(pool); }
161 ASSERT_SPARK_POOL_INVARIANTS(pool);
165 /* -----------------------------------------------------------------------------
166 * Mark all nodes pointed to by sparks in the spark queues (for GC) Does an
167 * implicit slide i.e. after marking all sparks are at the beginning of the
168 * spark pool and the spark pool only contains sparkable closures
169 * -------------------------------------------------------------------------- */
172 markSparkQueue (evac_fn evac, void *user, Capability *cap)
174 StgClosure **sparkp, **to_sparkp;
175 nat n, pruned_sparks; // stats only
178 PAR_TICKY_MARK_SPARK_QUEUE_START();
183 pool = &(cap->r.rSparks);
185 ASSERT_SPARK_POOL_INVARIANTS(pool);
187 #if defined(PARALLEL_HASKELL)
194 to_sparkp = pool->hd;
195 while (sparkp != pool->tl) {
196 ASSERT(*sparkp!=NULL);
197 ASSERT(LOOKS_LIKE_CLOSURE_PTR(((StgClosure *)*sparkp)));
198 // ToDo?: statistics gathering here (also for GUM!)
199 if (closure_SHOULD_SPARK(*sparkp)) {
201 *to_sparkp++ = *sparkp;
202 if (to_sparkp == pool->lim) {
203 to_sparkp = pool->base;
210 if (sparkp == pool->lim) {
214 pool->tl = to_sparkp;
216 PAR_TICKY_MARK_SPARK_QUEUE_END(n);
218 #if defined(PARALLEL_HASKELL)
219 debugTrace(DEBUG_sched,
220 "marked %d sparks and pruned %d sparks on [%x]",
221 n, pruned_sparks, mytid);
223 debugTrace(DEBUG_sched,
224 "marked %d sparks and pruned %d sparks",
228 debugTrace(DEBUG_sched,
229 "new spark queue len=%d; (hd=%p; tl=%p)\n",
230 sparkPoolSize(pool), pool->hd, pool->tl);
236 newSpark (StgRegTable *reg STG_UNUSED, StgClosure *p STG_UNUSED)
243 #endif /* PARALLEL_HASKELL || THREADED_RTS */
246 /* -----------------------------------------------------------------------------
248 * GRAN & PARALLEL_HASKELL stuff beyond here.
250 * -------------------------------------------------------------------------- */
252 #if defined(PARALLEL_HASKELL) || defined(GRAN)
254 static void slide_spark_pool( StgSparkPool *pool );
257 add_to_spark_queue( StgClosure *closure, StgSparkPool *pool )
259 if (pool->tl == pool->lim)
260 slide_spark_pool(pool);
262 if (closure_SHOULD_SPARK(closure) &&
263 pool->tl < pool->lim) {
264 *(pool->tl++) = closure;
266 #if defined(PARALLEL_HASKELL)
267 // collect parallel global statistics (currently done together with GC stats)
268 if (RtsFlags.ParFlags.ParStats.Global &&
269 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
270 // debugBelch("Creating spark for %x @ %11.2f\n", closure, usertime());
271 globalParStats.tot_sparks_created++;
276 #if defined(PARALLEL_HASKELL)
277 // collect parallel global statistics (currently done together with GC stats)
278 if (RtsFlags.ParFlags.ParStats.Global &&
279 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
280 //debugBelch("Ignoring spark for %x @ %11.2f\n", closure, usertime());
281 globalParStats.tot_sparks_ignored++;
289 slide_spark_pool( StgSparkPool *pool )
291 StgClosure **sparkp, **to_sparkp;
294 to_sparkp = pool->base;
295 while (sparkp < pool->tl) {
296 ASSERT(to_sparkp<=sparkp);
297 ASSERT(*sparkp!=NULL);
298 ASSERT(LOOKS_LIKE_GHC_INFO((*sparkp)->header.info));
300 if (closure_SHOULD_SPARK(*sparkp)) {
301 *to_sparkp++ = *sparkp++;
306 pool->hd = pool->base;
307 pool->tl = to_sparkp;
314 #if !defined(THREADED_RTS)
319 pool = &(cap->rSparks);
320 ASSERT(pool->hd <= pool->tl && pool->tl <= pool->lim);
322 ASSERT(spark != (StgClosure *)NULL);
330 Search the spark queue of the proc in event for a spark that's worth
331 turning into a thread
332 (was gimme_spark in the old RTS)
335 findLocalSpark (rtsEvent *event, rtsBool *found_res, rtsSparkQ *spark_res)
337 PEs proc = event->proc, /* proc to search for work */
338 creator = event->creator; /* proc that requested work */
341 rtsSparkQ spark_of_non_local_node = NULL,
342 spark_of_non_local_node_prev = NULL,
343 low_priority_spark = NULL,
344 low_priority_spark_prev = NULL,
345 spark = NULL, prev = NULL;
347 /* Choose a spark from the local spark queue */
348 prev = (rtsSpark*)NULL;
349 spark = pending_sparks_hds[proc];
352 // ToDo: check this code & implement local sparking !! -- HWL
353 while (!found && spark != (rtsSpark*)NULL)
355 ASSERT((prev!=(rtsSpark*)NULL || spark==pending_sparks_hds[proc]) &&
356 (prev==(rtsSpark*)NULL || prev->next==spark) &&
357 (spark->prev==prev));
359 if (!closure_SHOULD_SPARK(node))
361 IF_GRAN_DEBUG(checkSparkQ,
362 debugBelch("^^ pruning spark %p (node %p) in gimme_spark",
365 if (RtsFlags.GranFlags.GranSimStats.Sparks)
366 DumpRawGranEvent(proc, (PEs)0, SP_PRUNED,(StgTSO*)NULL,
367 spark->node, spark->name, spark_queue_len(proc));
369 ASSERT(spark != (rtsSpark*)NULL);
370 ASSERT(SparksAvail>0);
373 ASSERT(prev==(rtsSpark*)NULL || prev->next==spark);
374 spark = delete_from_sparkq (spark, proc, rtsTrue);
375 if (spark != (rtsSpark*)NULL)
379 /* -- node should eventually be sparked */
380 else if (RtsFlags.GranFlags.PreferSparksOfLocalNodes &&
381 !IS_LOCAL_TO(PROCS(node),CurrentProc))
383 barf("Local sparking not yet implemented");
385 /* Remember first low priority spark */
386 if (spark_of_non_local_node==(rtsSpark*)NULL) {
387 spark_of_non_local_node_prev = prev;
388 spark_of_non_local_node = spark;
391 if (spark->next == (rtsSpark*)NULL) {
392 /* ASSERT(spark==SparkQueueTl); just for testing */
393 prev = spark_of_non_local_node_prev;
394 spark = spark_of_non_local_node;
399 # if defined(GRAN) && defined(GRAN_CHECK)
400 /* Should never happen; just for testing
401 if (spark==pending_sparks_tl) {
402 debugBelch("ReSchedule: Last spark != SparkQueueTl\n");
403 stg_exit(EXIT_FAILURE);
408 ASSERT(SparksAvail>0);
412 else if ( RtsFlags.GranFlags.DoPrioritySparking ||
413 (spark->gran_info >= RtsFlags.GranFlags.SparkPriority2) )
415 if (RtsFlags.GranFlags.DoPrioritySparking)
416 barf("Priority sparking not yet implemented");
421 else /* only used if SparkPriority2 is defined */
423 /* ToDo: fix the code below and re-integrate it */
424 /* Remember first low priority spark */
425 if (low_priority_spark==(rtsSpark*)NULL) {
426 low_priority_spark_prev = prev;
427 low_priority_spark = spark;
430 if (spark->next == (rtsSpark*)NULL) {
431 /* ASSERT(spark==spark_queue_tl); just for testing */
432 prev = low_priority_spark_prev;
433 spark = low_priority_spark;
434 found = rtsTrue; /* take low pri spark => rc is 2 */
438 /* Should never happen; just for testing
439 if (spark==pending_sparks_tl) {
440 debugBelch("ReSchedule: Last spark != SparkQueueTl\n");
441 stg_exit(EXIT_FAILURE);
448 debugBelch("++ Ignoring spark of priority %u (SparkPriority=%u); node=%p; name=%u\n",
449 spark->gran_info, RtsFlags.GranFlags.SparkPriority,
450 spark->node, spark->name);)
453 } /* while (spark!=NULL && !found) */
460 Turn the spark into a thread.
461 In GranSim this basically means scheduling a StartThread event for the
462 node pointed to by the spark at some point in the future.
463 (was munch_spark in the old RTS)
466 activateSpark (rtsEvent *event, rtsSparkQ spark)
468 PEs proc = event->proc, /* proc to search for work */
469 creator = event->creator; /* proc that requested work */
472 rtsTime spark_arrival_time;
475 We've found a node on PE proc requested by PE creator.
476 If proc==creator we can turn the spark into a thread immediately;
477 otherwise we schedule a MoveSpark event on the requesting PE
483 /* only possible if we simulate GUM style fishing */
484 ASSERT(RtsFlags.GranFlags.Fishing);
486 /* Message packing costs for sending a Fish; qeq jabbI'ID */
487 CurrentTime[proc] += RtsFlags.GranFlags.Costs.mpacktime;
489 if (RtsFlags.GranFlags.GranSimStats.Sparks)
490 DumpRawGranEvent(proc, (PEs)0, SP_EXPORTED,
491 (StgTSO*)NULL, spark->node,
492 spark->name, spark_queue_len(proc));
494 /* time of the spark arrival on the remote PE */
495 spark_arrival_time = CurrentTime[proc] + RtsFlags.GranFlags.Costs.latency;
497 new_event(creator, proc, spark_arrival_time,
499 (StgTSO*)NULL, spark->node, spark);
501 CurrentTime[proc] += RtsFlags.GranFlags.Costs.mtidytime;
503 } else { /* proc==creator i.e. turn the spark into a thread */
505 if ( RtsFlags.GranFlags.GranSimStats.Global &&
506 spark->gran_info < RtsFlags.GranFlags.SparkPriority2 ) {
508 globalGranStats.tot_low_pri_sparks++;
510 debugBelch("++ No high priority spark available; low priority (%u) spark chosen: node=%p; name=%u\n",
512 spark->node, spark->name));
515 CurrentTime[proc] += RtsFlags.GranFlags.Costs.threadcreatetime;
520 /* ToDo: fix the GC interface and move to StartThread handling-- HWL */
521 if (GARBAGE COLLECTION IS NECESSARY) {
522 /* Some kind of backoff needed here in case there's too little heap */
523 # if defined(GRAN_CHECK) && defined(GRAN)
524 if (RtsFlags.GcFlags.giveStats)
525 fprintf(RtsFlags.GcFlags.statsFile,"***** vIS Qu' chen veQ boSwI'; spark=%p, node=%p; name=%u\n",
526 /* (found==2 ? "no hi pri spark" : "hi pri spark"), */
527 spark, node, spark->name);
529 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc]+1,
531 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
532 barf("//// activateSpark: out of heap ; ToDo: call GarbageCollect()");
533 GarbageCollect(GetRoots, rtsFalse);
534 // HWL old: ReallyPerformThreadGC(TSO_HS+TSO_CTS_SIZE,rtsFalse);
535 // HWL old: SAVE_Hp -= TSO_HS+TSO_CTS_SIZE;
537 return; /* was: continue; */ /* to the next event, eventually */
541 if (RtsFlags.GranFlags.GranSimStats.Sparks)
542 DumpRawGranEvent(CurrentProc,(PEs)0,SP_USED,(StgTSO*)NULL,
543 spark->node, spark->name,
544 spark_queue_len(CurrentProc));
546 new_event(proc, proc, CurrentTime[proc],
548 END_TSO_QUEUE, node, spark); // (rtsSpark*)NULL);
550 procStatus[proc] = Starting;
554 /* -------------------------------------------------------------------------
555 This is the main point where handling granularity information comes into
557 ------------------------------------------------------------------------- */
559 #define MAX_RAND_PRI 100
562 Granularity info transformers.
563 Applied to the GRAN_INFO field of a spark.
565 STATIC_INLINE nat ID(nat x) { return(x); };
566 STATIC_INLINE nat INV(nat x) { return(-x); };
567 STATIC_INLINE nat IGNORE(nat x) { return (0); };
568 STATIC_INLINE nat RAND(nat x) { return ((random() % MAX_RAND_PRI) + 1); }
570 /* NB: size_info and par_info are currently unused (what a shame!) -- HWL */
572 newSpark(node,name,gran_info,size_info,par_info,local)
574 nat name, gran_info, size_info, par_info, local;
579 pri = RtsFlags.GranFlags.RandomPriorities ? RAND(gran_info) :
580 RtsFlags.GranFlags.InversePriorities ? INV(gran_info) :
581 RtsFlags.GranFlags.IgnorePriorities ? IGNORE(gran_info) :
584 if ( RtsFlags.GranFlags.SparkPriority!=0 &&
585 pri<RtsFlags.GranFlags.SparkPriority ) {
587 debugBelch(",, NewSpark: Ignoring spark of priority %u (SparkPriority=%u); node=%#x; name=%u\n",
588 pri, RtsFlags.GranFlags.SparkPriority, node, name));
589 return ((rtsSpark*)NULL);
592 newspark = (rtsSpark*) stgMallocBytes(sizeof(rtsSpark), "NewSpark");
593 newspark->prev = newspark->next = (rtsSpark*)NULL;
594 newspark->node = node;
595 newspark->name = (name==1) ? CurrentTSO->gran.sparkname : name;
596 newspark->gran_info = pri;
597 newspark->global = !local; /* Check that with parAt, parAtAbs !!*/
599 if (RtsFlags.GranFlags.GranSimStats.Global) {
600 globalGranStats.tot_sparks_created++;
601 globalGranStats.sparks_created_on_PE[CurrentProc]++;
622 disposeSparkQ(spark->next);
625 if (SparksAvail < 0) {
626 debugBelch("disposeSparkQ: SparksAvail<0 after disposing sparkq @ %p\n", &spark);
635 With PrioritySparking add_to_spark_queue performs an insert sort to keep
636 the spark queue sorted. Otherwise the spark is just added to the end of
641 add_to_spark_queue(spark)
644 rtsSpark *prev = NULL, *next = NULL;
646 rtsBool found = rtsFalse;
648 if ( spark == (rtsSpark *)NULL ) {
652 if (RtsFlags.GranFlags.DoPrioritySparking && (spark->gran_info != 0) ) {
653 /* Priority sparking is enabled i.e. spark queues must be sorted */
655 for (prev = NULL, next = pending_sparks_hd, count=0;
657 !(found = (spark->gran_info >= next->gran_info));
658 prev = next, next = next->next, count++)
661 } else { /* 'utQo' */
662 /* Priority sparking is disabled */
664 found = rtsFalse; /* to add it at the end */
669 /* next points to the first spark with a gran_info smaller than that
670 of spark; therefore, add spark before next into the spark queue */
672 if ( next == NULL ) {
673 pending_sparks_tl = spark;
678 if ( prev == NULL ) {
679 pending_sparks_hd = spark;
683 } else { /* (RtsFlags.GranFlags.DoPrioritySparking && !found) || !DoPrioritySparking */
684 /* add the spark at the end of the spark queue */
686 spark->prev = pending_sparks_tl;
687 if (pending_sparks_hd == NULL)
688 pending_sparks_hd = spark;
690 pending_sparks_tl->next = spark;
691 pending_sparks_tl = spark;
695 /* add costs for search in priority sparking */
696 if (RtsFlags.GranFlags.DoPrioritySparking) {
697 CurrentTime[CurrentProc] += count * RtsFlags.GranFlags.Costs.pri_spark_overhead;
700 IF_GRAN_DEBUG(checkSparkQ,
701 debugBelch("++ Spark stats after adding spark %p (node %p) to queue on PE %d",
702 spark, spark->node, CurrentProc);
703 print_sparkq_stats());
705 # if defined(GRAN_CHECK)
706 if (RtsFlags.GranFlags.Debug.checkSparkQ) {
707 for (prev = NULL, next = pending_sparks_hd;
709 prev = next, next = next->next)
711 if ( (prev!=NULL) && (prev!=pending_sparks_tl) )
712 debugBelch("SparkQ inconsistency after adding spark %p: (PE %u) pending_sparks_tl (%p) not end of queue (%p)\n",
714 pending_sparks_tl, prev);
718 # if defined(GRAN_CHECK)
719 /* Check if the sparkq is still sorted. Just for testing, really! */
720 if ( RtsFlags.GranFlags.Debug.checkSparkQ &&
721 RtsFlags.GranFlags.Debug.pri ) {
722 rtsBool sorted = rtsTrue;
723 rtsSpark *prev, *next;
725 if (pending_sparks_hd == NULL ||
726 pending_sparks_hd->next == NULL ) {
727 /* just 1 elem => ok */
729 for (prev = pending_sparks_hd,
730 next = pending_sparks_hd->next;
732 prev = next, next = next->next) {
734 (prev->gran_info >= next->gran_info);
738 debugBelch("ghuH: SPARKQ on PE %d is not sorted:\n",
740 print_sparkq(CurrentProc);
747 spark_queue_len(proc)
750 rtsSpark *prev, *spark; /* prev only for testing !! */
753 for (len = 0, prev = NULL, spark = pending_sparks_hds[proc];
755 len++, prev = spark, spark = spark->next)
758 # if defined(GRAN_CHECK)
759 if ( RtsFlags.GranFlags.Debug.checkSparkQ )
760 if ( (prev!=NULL) && (prev!=pending_sparks_tls[proc]) )
761 debugBelch("ERROR in spark_queue_len: (PE %u) pending_sparks_tl (%p) not end of queue (%p)\n",
762 proc, pending_sparks_tls[proc], prev);
769 Take spark out of the spark queue on PE p and nuke the spark. Adjusts
770 hd and tl pointers of the spark queue. Returns a pointer to the next
774 delete_from_sparkq (spark, p, dispose_too) /* unlink and dispose spark */
782 barf("delete_from_sparkq: trying to delete NULL spark\n");
784 # if defined(GRAN_CHECK)
785 if ( RtsFlags.GranFlags.Debug.checkSparkQ ) {
786 debugBelch("## |%p:%p| (%p)<-spark=%p->(%p) <-(%p)\n",
787 pending_sparks_hd, pending_sparks_tl,
788 spark->prev, spark, spark->next,
789 (spark->next==NULL ? 0 : spark->next->prev));
793 if (spark->prev==NULL) {
794 /* spark is first spark of queue => adjust hd pointer */
795 ASSERT(pending_sparks_hds[p]==spark);
796 pending_sparks_hds[p] = spark->next;
798 spark->prev->next = spark->next;
800 if (spark->next==NULL) {
801 ASSERT(pending_sparks_tls[p]==spark);
802 /* spark is first spark of queue => adjust tl pointer */
803 pending_sparks_tls[p] = spark->prev;
805 spark->next->prev = spark->prev;
807 new_spark = spark->next;
809 # if defined(GRAN_CHECK)
810 if ( RtsFlags.GranFlags.Debug.checkSparkQ ) {
811 debugBelch("## |%p:%p| (%p)<-spark=%p->(%p) <-(%p); spark=%p will be deleted NOW \n",
812 pending_sparks_hd, pending_sparks_tl,
813 spark->prev, spark, spark->next,
814 (spark->next==NULL ? 0 : spark->next->prev), spark);
824 /* Mark all nodes pointed to by sparks in the spark queues (for GC) */
828 StgClosure *MarkRoot(StgClosure *root); // prototype
832 for (p=0; p<RtsFlags.GranFlags.proc; p++)
833 for (sp=pending_sparks_hds[p]; sp!=NULL; sp=sp->next) {
834 ASSERT(sp->node!=NULL);
835 ASSERT(LOOKS_LIKE_GHC_INFO(sp->node->header.info));
836 // ToDo?: statistics gathering here (also for GUM!)
837 sp->node = (StgClosure *)MarkRoot(sp->node);
841 debugBelch("markSparkQueue: spark statistics at start of GC:");
842 print_sparkq_stats());
852 debugBelch("Spark: NIL\n");
856 ((spark->node==NULL) ? "______" : "%#6lx"),
857 stgCast(StgPtr,spark->node));
859 debugBelch("Spark: Node %8s, Name %#6x, Global %5s, Creator %5x, Prev %6p, Next %6p\n",
861 ((spark->global)==rtsTrue?"True":"False"), spark->creator,
862 spark->prev, spark->next);
871 rtsSpark *x = pending_sparks_hds[proc];
873 debugBelch("Spark Queue of PE %d with root at %p:\n", proc, x);
874 for (; x!=(rtsSpark*)NULL; x=x->next) {
880 Print a statistics of all spark queues.
883 print_sparkq_stats(void)
887 debugBelch("SparkQs: [");
888 for (p=0; p<RtsFlags.GranFlags.proc; p++)
889 debugBelch(", PE %d: %d", p, spark_queue_len(p));