1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 2000-2005
5 * Sparking support for PARALLEL_HASKELL and SMP 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"
25 #if defined(SMP) || defined(PARALLEL_HASKELL)
27 static INLINE_ME void bump_hd (StgSparkPool *p)
28 { p->hd++; if (p->hd == p->lim) p->hd = p->base; }
30 static INLINE_ME void bump_tl (StgSparkPool *p)
31 { p->tl++; if (p->tl == p->lim) p->tl = p->base; }
33 /* -----------------------------------------------------------------------------
35 * Initialising spark pools.
37 * -------------------------------------------------------------------------- */
40 initSparkPool(StgSparkPool *pool)
42 pool->base = stgMallocBytes(RtsFlags.ParFlags.maxLocalSparks
43 * sizeof(StgClosure *),
45 pool->lim = pool->base + RtsFlags.ParFlags.maxLocalSparks;
46 pool->hd = pool->base;
47 pool->tl = pool->base;
51 initSparkPools( void )
54 /* walk over the capabilities, allocating a spark pool for each one */
56 for (i = 0; i < n_capabilities; i++) {
57 initSparkPool(&capabilities[i].r.rSparks);
60 /* allocate a single spark pool */
61 initSparkPool(&MainCapability.r.rSparks);
65 /* -----------------------------------------------------------------------------
67 * findSpark: find a spark on the current Capability that we can fork
70 * -------------------------------------------------------------------------- */
73 findSpark (Capability *cap)
78 pool = &(cap->r.rSparks);
79 ASSERT_SPARK_POOL_INVARIANTS(pool);
81 while (pool->hd != pool->tl) {
84 if (closure_SHOULD_SPARK(spark)) {
86 if (RtsFlags.ParFlags.ParStats.Sparks)
87 DumpRawGranEvent(CURRENT_PROC, CURRENT_PROC,
88 GR_STEALING, ((StgTSO *)NULL), spark,
89 0, 0 /* spark_queue_len(ADVISORY_POOL) */);
94 // spark pool is now empty
98 /* -----------------------------------------------------------------------------
99 * Mark all nodes pointed to by sparks in the spark queues (for GC) Does an
100 * implicit slide i.e. after marking all sparks are at the beginning of the
101 * spark pool and the spark pool only contains sparkable closures
102 * -------------------------------------------------------------------------- */
105 markSparkQueue (evac_fn evac)
107 StgClosure **sparkp, **to_sparkp;
108 nat i, n, pruned_sparks; // stats only
112 PAR_TICKY_MARK_SPARK_QUEUE_START();
116 for (i = 0; i < n_capabilities; i++) {
117 cap = &capabilities[i];
118 pool = &(cap->r.rSparks);
120 ASSERT_SPARK_POOL_INVARIANTS(pool);
122 #if defined(PARALLEL_HASKELL)
129 to_sparkp = pool->hd;
130 while (sparkp != pool->tl) {
131 ASSERT(to_sparkp<=sparkp);
132 ASSERT(*sparkp!=NULL);
133 ASSERT(LOOKS_LIKE_CLOSURE_PTR(((StgClosure *)*sparkp)));
134 // ToDo?: statistics gathering here (also for GUM!)
135 if (closure_SHOULD_SPARK(*sparkp)) {
137 *to_sparkp++ = *sparkp;
143 if (sparkp == pool->lim) {
147 pool->tl = to_sparkp;
149 PAR_TICKY_MARK_SPARK_QUEUE_END(n);
151 #if defined(PARALLEL_HASKELL)
153 debugBelch("markSparkQueue: marked %d sparks and pruned %d sparks on [%x]",
154 n, pruned_sparks, mytid));
157 debugBelch("markSparkQueue: marked %d sparks and pruned %d sparks\n",
162 debugBelch("markSparkQueue: new spark queue len=%d; (hd=%p; tl=%p)\n",
163 sparkPoolSize(pool), pool->hd, pool->tl));
168 /* -----------------------------------------------------------------------------
170 * Turn a spark into a real thread
172 * -------------------------------------------------------------------------- */
175 createSparkThread (Capability *cap, StgClosure *p)
179 tso = createGenThread (cap, RtsFlags.GcFlags.initialStkSize, p);
180 appendToRunQueue(cap,tso);
183 /* -----------------------------------------------------------------------------
187 * -------------------------------------------------------------------------- */
192 newSpark (StgRegTable *reg, StgClosure *p)
194 StgSparkPool *pool = &(reg->rSparks);
196 ASSERT_SPARK_POOL_INVARIANTS(pool);
198 if (closure_SHOULD_SPARK(p)) {
201 new_tl = pool->tl + 1;
202 if (new_tl == pool->lim) { new_tl = pool->base; }
203 if (new_tl != pool->hd) {
206 } else if (!closure_SHOULD_SPARK(*pool->hd)) {
207 // if the old closure is not sparkable, discard it and
208 // keep the new one. Otherwise, keep the old one.
212 #else /* DISCARD OLD */
215 if (pool->tl == pool->hd) { bump_hd(pool); }
219 ASSERT_SPARK_POOL_INVARIANTS(pool);
223 #endif /* PARALLEL_HASKELL || SMP */
225 /* -----------------------------------------------------------------------------
227 * GRAN & PARALLEL_HASKELL stuff beyond here.
229 * -------------------------------------------------------------------------- */
231 #if defined(PARALLEL_HASKELL) || defined(GRAN)
233 static void slide_spark_pool( StgSparkPool *pool );
236 add_to_spark_queue( StgClosure *closure, StgSparkPool *pool )
238 if (pool->tl == pool->lim)
239 slide_spark_pool(pool);
241 if (closure_SHOULD_SPARK(closure) &&
242 pool->tl < pool->lim) {
243 *(pool->tl++) = closure;
245 #if defined(PARALLEL_HASKELL)
246 // collect parallel global statistics (currently done together with GC stats)
247 if (RtsFlags.ParFlags.ParStats.Global &&
248 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
249 // debugBelch("Creating spark for %x @ %11.2f\n", closure, usertime());
250 globalParStats.tot_sparks_created++;
255 #if defined(PARALLEL_HASKELL)
256 // collect parallel global statistics (currently done together with GC stats)
257 if (RtsFlags.ParFlags.ParStats.Global &&
258 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
259 //debugBelch("Ignoring spark for %x @ %11.2f\n", closure, usertime());
260 globalParStats.tot_sparks_ignored++;
268 slide_spark_pool( StgSparkPool *pool )
270 StgClosure **sparkp, **to_sparkp;
273 to_sparkp = pool->base;
274 while (sparkp < pool->tl) {
275 ASSERT(to_sparkp<=sparkp);
276 ASSERT(*sparkp!=NULL);
277 ASSERT(LOOKS_LIKE_GHC_INFO((*sparkp)->header.info));
279 if (closure_SHOULD_SPARK(*sparkp)) {
280 *to_sparkp++ = *sparkp++;
285 pool->hd = pool->base;
286 pool->tl = to_sparkp;
298 pool = &(cap->rSparks);
299 ASSERT(pool->hd <= pool->tl && pool->tl <= pool->lim);
301 ASSERT(spark != (StgClosure *)NULL);
309 Search the spark queue of the proc in event for a spark that's worth
310 turning into a thread
311 (was gimme_spark in the old RTS)
314 findLocalSpark (rtsEvent *event, rtsBool *found_res, rtsSparkQ *spark_res)
316 PEs proc = event->proc, /* proc to search for work */
317 creator = event->creator; /* proc that requested work */
320 rtsSparkQ spark_of_non_local_node = NULL,
321 spark_of_non_local_node_prev = NULL,
322 low_priority_spark = NULL,
323 low_priority_spark_prev = NULL,
324 spark = NULL, prev = NULL;
326 /* Choose a spark from the local spark queue */
327 prev = (rtsSpark*)NULL;
328 spark = pending_sparks_hds[proc];
331 // ToDo: check this code & implement local sparking !! -- HWL
332 while (!found && spark != (rtsSpark*)NULL)
334 ASSERT((prev!=(rtsSpark*)NULL || spark==pending_sparks_hds[proc]) &&
335 (prev==(rtsSpark*)NULL || prev->next==spark) &&
336 (spark->prev==prev));
338 if (!closure_SHOULD_SPARK(node))
340 IF_GRAN_DEBUG(checkSparkQ,
341 debugBelch("^^ pruning spark %p (node %p) in gimme_spark",
344 if (RtsFlags.GranFlags.GranSimStats.Sparks)
345 DumpRawGranEvent(proc, (PEs)0, SP_PRUNED,(StgTSO*)NULL,
346 spark->node, spark->name, spark_queue_len(proc));
348 ASSERT(spark != (rtsSpark*)NULL);
349 ASSERT(SparksAvail>0);
352 ASSERT(prev==(rtsSpark*)NULL || prev->next==spark);
353 spark = delete_from_sparkq (spark, proc, rtsTrue);
354 if (spark != (rtsSpark*)NULL)
358 /* -- node should eventually be sparked */
359 else if (RtsFlags.GranFlags.PreferSparksOfLocalNodes &&
360 !IS_LOCAL_TO(PROCS(node),CurrentProc))
362 barf("Local sparking not yet implemented");
364 /* Remember first low priority spark */
365 if (spark_of_non_local_node==(rtsSpark*)NULL) {
366 spark_of_non_local_node_prev = prev;
367 spark_of_non_local_node = spark;
370 if (spark->next == (rtsSpark*)NULL) {
371 /* ASSERT(spark==SparkQueueTl); just for testing */
372 prev = spark_of_non_local_node_prev;
373 spark = spark_of_non_local_node;
378 # if defined(GRAN) && defined(GRAN_CHECK)
379 /* Should never happen; just for testing
380 if (spark==pending_sparks_tl) {
381 debugBelch("ReSchedule: Last spark != SparkQueueTl\n");
382 stg_exit(EXIT_FAILURE);
387 ASSERT(SparksAvail>0);
391 else if ( RtsFlags.GranFlags.DoPrioritySparking ||
392 (spark->gran_info >= RtsFlags.GranFlags.SparkPriority2) )
394 if (RtsFlags.GranFlags.DoPrioritySparking)
395 barf("Priority sparking not yet implemented");
400 else /* only used if SparkPriority2 is defined */
402 /* ToDo: fix the code below and re-integrate it */
403 /* Remember first low priority spark */
404 if (low_priority_spark==(rtsSpark*)NULL) {
405 low_priority_spark_prev = prev;
406 low_priority_spark = spark;
409 if (spark->next == (rtsSpark*)NULL) {
410 /* ASSERT(spark==spark_queue_tl); just for testing */
411 prev = low_priority_spark_prev;
412 spark = low_priority_spark;
413 found = rtsTrue; /* take low pri spark => rc is 2 */
417 /* Should never happen; just for testing
418 if (spark==pending_sparks_tl) {
419 debugBelch("ReSchedule: Last spark != SparkQueueTl\n");
420 stg_exit(EXIT_FAILURE);
427 debugBelch("++ Ignoring spark of priority %u (SparkPriority=%u); node=%p; name=%u\n",
428 spark->gran_info, RtsFlags.GranFlags.SparkPriority,
429 spark->node, spark->name);)
432 } /* while (spark!=NULL && !found) */
439 Turn the spark into a thread.
440 In GranSim this basically means scheduling a StartThread event for the
441 node pointed to by the spark at some point in the future.
442 (was munch_spark in the old RTS)
445 activateSpark (rtsEvent *event, rtsSparkQ spark)
447 PEs proc = event->proc, /* proc to search for work */
448 creator = event->creator; /* proc that requested work */
451 rtsTime spark_arrival_time;
454 We've found a node on PE proc requested by PE creator.
455 If proc==creator we can turn the spark into a thread immediately;
456 otherwise we schedule a MoveSpark event on the requesting PE
462 /* only possible if we simulate GUM style fishing */
463 ASSERT(RtsFlags.GranFlags.Fishing);
465 /* Message packing costs for sending a Fish; qeq jabbI'ID */
466 CurrentTime[proc] += RtsFlags.GranFlags.Costs.mpacktime;
468 if (RtsFlags.GranFlags.GranSimStats.Sparks)
469 DumpRawGranEvent(proc, (PEs)0, SP_EXPORTED,
470 (StgTSO*)NULL, spark->node,
471 spark->name, spark_queue_len(proc));
473 /* time of the spark arrival on the remote PE */
474 spark_arrival_time = CurrentTime[proc] + RtsFlags.GranFlags.Costs.latency;
476 new_event(creator, proc, spark_arrival_time,
478 (StgTSO*)NULL, spark->node, spark);
480 CurrentTime[proc] += RtsFlags.GranFlags.Costs.mtidytime;
482 } else { /* proc==creator i.e. turn the spark into a thread */
484 if ( RtsFlags.GranFlags.GranSimStats.Global &&
485 spark->gran_info < RtsFlags.GranFlags.SparkPriority2 ) {
487 globalGranStats.tot_low_pri_sparks++;
489 debugBelch("++ No high priority spark available; low priority (%u) spark chosen: node=%p; name=%u\n",
491 spark->node, spark->name));
494 CurrentTime[proc] += RtsFlags.GranFlags.Costs.threadcreatetime;
499 /* ToDo: fix the GC interface and move to StartThread handling-- HWL */
500 if (GARBAGE COLLECTION IS NECESSARY) {
501 /* Some kind of backoff needed here in case there's too little heap */
502 # if defined(GRAN_CHECK) && defined(GRAN)
503 if (RtsFlags.GcFlags.giveStats)
504 fprintf(RtsFlags.GcFlags.statsFile,"***** vIS Qu' chen veQ boSwI'; spark=%p, node=%p; name=%u\n",
505 /* (found==2 ? "no hi pri spark" : "hi pri spark"), */
506 spark, node, spark->name);
508 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc]+1,
510 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
511 barf("//// activateSpark: out of heap ; ToDo: call GarbageCollect()");
512 GarbageCollect(GetRoots, rtsFalse);
513 // HWL old: ReallyPerformThreadGC(TSO_HS+TSO_CTS_SIZE,rtsFalse);
514 // HWL old: SAVE_Hp -= TSO_HS+TSO_CTS_SIZE;
516 return; /* was: continue; */ /* to the next event, eventually */
520 if (RtsFlags.GranFlags.GranSimStats.Sparks)
521 DumpRawGranEvent(CurrentProc,(PEs)0,SP_USED,(StgTSO*)NULL,
522 spark->node, spark->name,
523 spark_queue_len(CurrentProc));
525 new_event(proc, proc, CurrentTime[proc],
527 END_TSO_QUEUE, node, spark); // (rtsSpark*)NULL);
529 procStatus[proc] = Starting;
533 /* -------------------------------------------------------------------------
534 This is the main point where handling granularity information comes into
536 ------------------------------------------------------------------------- */
538 #define MAX_RAND_PRI 100
541 Granularity info transformers.
542 Applied to the GRAN_INFO field of a spark.
544 STATIC_INLINE nat ID(nat x) { return(x); };
545 STATIC_INLINE nat INV(nat x) { return(-x); };
546 STATIC_INLINE nat IGNORE(nat x) { return (0); };
547 STATIC_INLINE nat RAND(nat x) { return ((random() % MAX_RAND_PRI) + 1); }
549 /* NB: size_info and par_info are currently unused (what a shame!) -- HWL */
551 newSpark(node,name,gran_info,size_info,par_info,local)
553 nat name, gran_info, size_info, par_info, local;
558 pri = RtsFlags.GranFlags.RandomPriorities ? RAND(gran_info) :
559 RtsFlags.GranFlags.InversePriorities ? INV(gran_info) :
560 RtsFlags.GranFlags.IgnorePriorities ? IGNORE(gran_info) :
563 if ( RtsFlags.GranFlags.SparkPriority!=0 &&
564 pri<RtsFlags.GranFlags.SparkPriority ) {
566 debugBelch(",, NewSpark: Ignoring spark of priority %u (SparkPriority=%u); node=%#x; name=%u\n",
567 pri, RtsFlags.GranFlags.SparkPriority, node, name));
568 return ((rtsSpark*)NULL);
571 newspark = (rtsSpark*) stgMallocBytes(sizeof(rtsSpark), "NewSpark");
572 newspark->prev = newspark->next = (rtsSpark*)NULL;
573 newspark->node = node;
574 newspark->name = (name==1) ? CurrentTSO->gran.sparkname : name;
575 newspark->gran_info = pri;
576 newspark->global = !local; /* Check that with parAt, parAtAbs !!*/
578 if (RtsFlags.GranFlags.GranSimStats.Global) {
579 globalGranStats.tot_sparks_created++;
580 globalGranStats.sparks_created_on_PE[CurrentProc]++;
601 disposeSparkQ(spark->next);
604 if (SparksAvail < 0) {
605 debugBelch("disposeSparkQ: SparksAvail<0 after disposing sparkq @ %p\n", &spark);
614 With PrioritySparking add_to_spark_queue performs an insert sort to keep
615 the spark queue sorted. Otherwise the spark is just added to the end of
620 add_to_spark_queue(spark)
623 rtsSpark *prev = NULL, *next = NULL;
625 rtsBool found = rtsFalse;
627 if ( spark == (rtsSpark *)NULL ) {
631 if (RtsFlags.GranFlags.DoPrioritySparking && (spark->gran_info != 0) ) {
632 /* Priority sparking is enabled i.e. spark queues must be sorted */
634 for (prev = NULL, next = pending_sparks_hd, count=0;
636 !(found = (spark->gran_info >= next->gran_info));
637 prev = next, next = next->next, count++)
640 } else { /* 'utQo' */
641 /* Priority sparking is disabled */
643 found = rtsFalse; /* to add it at the end */
648 /* next points to the first spark with a gran_info smaller than that
649 of spark; therefore, add spark before next into the spark queue */
651 if ( next == NULL ) {
652 pending_sparks_tl = spark;
657 if ( prev == NULL ) {
658 pending_sparks_hd = spark;
662 } else { /* (RtsFlags.GranFlags.DoPrioritySparking && !found) || !DoPrioritySparking */
663 /* add the spark at the end of the spark queue */
665 spark->prev = pending_sparks_tl;
666 if (pending_sparks_hd == NULL)
667 pending_sparks_hd = spark;
669 pending_sparks_tl->next = spark;
670 pending_sparks_tl = spark;
674 /* add costs for search in priority sparking */
675 if (RtsFlags.GranFlags.DoPrioritySparking) {
676 CurrentTime[CurrentProc] += count * RtsFlags.GranFlags.Costs.pri_spark_overhead;
679 IF_GRAN_DEBUG(checkSparkQ,
680 debugBelch("++ Spark stats after adding spark %p (node %p) to queue on PE %d",
681 spark, spark->node, CurrentProc);
682 print_sparkq_stats());
684 # if defined(GRAN_CHECK)
685 if (RtsFlags.GranFlags.Debug.checkSparkQ) {
686 for (prev = NULL, next = pending_sparks_hd;
688 prev = next, next = next->next)
690 if ( (prev!=NULL) && (prev!=pending_sparks_tl) )
691 debugBelch("SparkQ inconsistency after adding spark %p: (PE %u) pending_sparks_tl (%p) not end of queue (%p)\n",
693 pending_sparks_tl, prev);
697 # if defined(GRAN_CHECK)
698 /* Check if the sparkq is still sorted. Just for testing, really! */
699 if ( RtsFlags.GranFlags.Debug.checkSparkQ &&
700 RtsFlags.GranFlags.Debug.pri ) {
701 rtsBool sorted = rtsTrue;
702 rtsSpark *prev, *next;
704 if (pending_sparks_hd == NULL ||
705 pending_sparks_hd->next == NULL ) {
706 /* just 1 elem => ok */
708 for (prev = pending_sparks_hd,
709 next = pending_sparks_hd->next;
711 prev = next, next = next->next) {
713 (prev->gran_info >= next->gran_info);
717 debugBelch("ghuH: SPARKQ on PE %d is not sorted:\n",
719 print_sparkq(CurrentProc);
726 spark_queue_len(proc)
729 rtsSpark *prev, *spark; /* prev only for testing !! */
732 for (len = 0, prev = NULL, spark = pending_sparks_hds[proc];
734 len++, prev = spark, spark = spark->next)
737 # if defined(GRAN_CHECK)
738 if ( RtsFlags.GranFlags.Debug.checkSparkQ )
739 if ( (prev!=NULL) && (prev!=pending_sparks_tls[proc]) )
740 debugBelch("ERROR in spark_queue_len: (PE %u) pending_sparks_tl (%p) not end of queue (%p)\n",
741 proc, pending_sparks_tls[proc], prev);
748 Take spark out of the spark queue on PE p and nuke the spark. Adjusts
749 hd and tl pointers of the spark queue. Returns a pointer to the next
753 delete_from_sparkq (spark, p, dispose_too) /* unlink and dispose spark */
761 barf("delete_from_sparkq: trying to delete NULL spark\n");
763 # if defined(GRAN_CHECK)
764 if ( RtsFlags.GranFlags.Debug.checkSparkQ ) {
765 debugBelch("## |%p:%p| (%p)<-spark=%p->(%p) <-(%p)\n",
766 pending_sparks_hd, pending_sparks_tl,
767 spark->prev, spark, spark->next,
768 (spark->next==NULL ? 0 : spark->next->prev));
772 if (spark->prev==NULL) {
773 /* spark is first spark of queue => adjust hd pointer */
774 ASSERT(pending_sparks_hds[p]==spark);
775 pending_sparks_hds[p] = spark->next;
777 spark->prev->next = spark->next;
779 if (spark->next==NULL) {
780 ASSERT(pending_sparks_tls[p]==spark);
781 /* spark is first spark of queue => adjust tl pointer */
782 pending_sparks_tls[p] = spark->prev;
784 spark->next->prev = spark->prev;
786 new_spark = spark->next;
788 # if defined(GRAN_CHECK)
789 if ( RtsFlags.GranFlags.Debug.checkSparkQ ) {
790 debugBelch("## |%p:%p| (%p)<-spark=%p->(%p) <-(%p); spark=%p will be deleted NOW \n",
791 pending_sparks_hd, pending_sparks_tl,
792 spark->prev, spark, spark->next,
793 (spark->next==NULL ? 0 : spark->next->prev), spark);
803 /* Mark all nodes pointed to by sparks in the spark queues (for GC) */
807 StgClosure *MarkRoot(StgClosure *root); // prototype
811 for (p=0; p<RtsFlags.GranFlags.proc; p++)
812 for (sp=pending_sparks_hds[p]; sp!=NULL; sp=sp->next) {
813 ASSERT(sp->node!=NULL);
814 ASSERT(LOOKS_LIKE_GHC_INFO(sp->node->header.info));
815 // ToDo?: statistics gathering here (also for GUM!)
816 sp->node = (StgClosure *)MarkRoot(sp->node);
819 debugBelch("@@ markSparkQueue: spark statistics at start of GC:");
820 print_sparkq_stats());
830 debugBelch("Spark: NIL\n");
834 ((spark->node==NULL) ? "______" : "%#6lx"),
835 stgCast(StgPtr,spark->node));
837 debugBelch("Spark: Node %8s, Name %#6x, Global %5s, Creator %5x, Prev %6p, Next %6p\n",
839 ((spark->global)==rtsTrue?"True":"False"), spark->creator,
840 spark->prev, spark->next);
849 rtsSpark *x = pending_sparks_hds[proc];
851 debugBelch("Spark Queue of PE %d with root at %p:\n", proc, x);
852 for (; x!=(rtsSpark*)NULL; x=x->next) {
858 Print a statistics of all spark queues.
861 print_sparkq_stats(void)
865 debugBelch("SparkQs: [");
866 for (p=0; p<RtsFlags.GranFlags.proc; p++)
867 debugBelch(", PE %d: %d", p, spark_queue_len(p));