1 /* ---------------------------------------------------------------------------
3 * (c) The GHC Team, 2000-2008
5 * Sparking support for PARALLEL_HASKELL and THREADED_RTS versions of the RTS.
7 * The implementation uses Double-Ended Queues with lock-free access
8 * (thereby often called "deque") as described in
10 * D.Chase and Y.Lev, Dynamic Circular Work-Stealing Deque.
11 * SPAA'05, July 2005, Las Vegas, USA.
12 * ACM 1-58113-986-1/05/0007
14 * Author: Jost Berthold MSRC 07-09/2008
16 * The DeQue is held as a circular array with known length. Positions
17 * of top (read-end) and bottom (write-end) always increase, and the
18 * array is accessed with indices modulo array-size. While this bears
19 * the risk of overflow, we assume that (with 64 bit indices), a
20 * program must run very long to reach that point.
22 * The write end of the queue (position bottom) can only be used with
23 * mutual exclusion, i.e. by exactly one caller at a time. At this
24 * end, new items can be enqueued using pushBottom()/newSpark(), and
25 * removed using popBottom()/reclaimSpark() (the latter implying a cas
26 * synchronisation with potential concurrent readers for the case of
29 * Multiple readers can steal()/findSpark() from the read end
30 * (position top), and are synchronised without a lock, based on a cas
31 * of the top position. One reader wins, the others return NULL for a
34 * Both popBottom and steal also return NULL when the queue is empty.
36 -------------------------------------------------------------------------*/
38 #include "PosixSource.h"
48 #include "SMP.h" // for cas
52 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
54 /* internal helpers ... */
61 /* StgWord is unsigned anyway, only catch 0 */
63 barf("DeQue,roundUp2: invalid size 0 requested");
65 /* at least 1 bit set, shift up to its place */
67 rounded = rounded << 1;
68 } while (0 != (val = val>>1));
72 #define CASTOP(addr,old,new) ((old) == cas(((StgPtr)addr),(old),(new)))
74 /* -----------------------------------------------------------------------------
76 * Initialising spark pools.
78 * -------------------------------------------------------------------------- */
82 initPool(StgWord size)
87 realsize = roundUp2(size); /* to compute modulo as a bitwise & */
89 q = (SparkPool*) stgMallocBytes(sizeof(SparkPool), /* admin fields */
91 q->elements = (StgClosurePtr*)
92 stgMallocBytes(realsize * sizeof(StgClosurePtr), /* dataspace */
93 "newSparkPool:data space");
96 q->topBound=0; /* read by writer, updated each time top is read */
98 q->size = realsize; /* power of 2 */
99 q->moduloSize = realsize - 1; /* n % size == n & moduloSize */
101 ASSERT_SPARK_POOL_INVARIANTS(q);
106 initSparkPools( void )
109 /* walk over the capabilities, allocating a spark pool for each one */
111 for (i = 0; i < n_capabilities; i++) {
112 capabilities[i].sparks = initPool(RtsFlags.ParFlags.maxLocalSparks);
115 /* allocate a single spark pool */
116 MainCapability->sparks = initPool(RtsFlags.ParFlags.maxLocalSparks);
121 freeSparkPool (SparkPool *pool)
123 /* should not interfere with concurrent findSpark() calls! And
124 nobody should use the pointer any more. We cross our fingers...*/
125 stgFree(pool->elements);
129 /* -----------------------------------------------------------------------------
131 * reclaimSpark: remove a spark from the write end of the queue.
132 * Returns the removed spark, and NULL if a race is lost or the pool
135 * If only one spark is left in the pool, we synchronise with
136 * concurrently stealing threads by using cas to modify the top field.
137 * This routine should NEVER be called by a task which does not own
138 * the capability. Can this be checked here?
140 * -------------------------------------------------------------------------- */
143 reclaimSpark (SparkPool *deque)
145 /* also a bit tricky, has to avoid concurrent steal() calls by
146 accessing top with cas, when there is only one element left */
150 StgClosurePtr removed;
152 ASSERT_SPARK_POOL_INVARIANTS(deque);
155 /* "decrement b as a test, see what happens" */
157 pos = (deque->elements) + (b & (deque->moduloSize));
158 t = deque->top; /* using topBound would give an *upper* bound, we
159 need a lower bound. We use the real top here, but
160 can update the topBound value */
163 if (currSize < 0) { /* was empty before decrementing b, set b
164 consistently and abort */
169 if (currSize > 0) { /* no danger, still elements in buffer after b-- */
172 /* otherwise, has someone meanwhile stolen the same (last) element?
173 Check and increment top value to know */
174 if ( !(CASTOP(&(deque->top),t,t+1)) ) {
175 removed = NULL; /* no success, but continue adjusting bottom */
177 deque->bottom = t+1; /* anyway, empty now. Adjust bottom consistently. */
178 deque->topBound = t+1; /* ...and cached top value as well */
180 ASSERT_SPARK_POOL_INVARIANTS(deque);
185 /* -----------------------------------------------------------------------------
187 * tryStealSpark: try to steal a spark from a Capability.
189 * Returns a valid spark, or NULL if the pool was empty, and can
190 * occasionally return NULL if there was a race with another thread
191 * stealing from the same pool. In this case, try again later.
193 -------------------------------------------------------------------------- */
196 steal(SparkPool *deque)
199 StgClosurePtr* arraybase;
201 StgClosurePtr stolen;
204 ASSERT_SPARK_POOL_INVARIANTS(deque);
209 return NULL; /* already looks empty, abort */
212 /* now access array, see pushBottom() */
213 arraybase = deque->elements;
214 sz = deque->moduloSize;
215 pos = arraybase + (t & sz);
218 /* now decide whether we have won */
219 if ( !(CASTOP(&(deque->top),t,t+1)) ) {
220 /* lost the race, someon else has changed top in the meantime */
222 } /* else: OK, top has been incremented by the cas call */
224 ASSERT_SPARK_POOL_INVARIANTS(deque);
225 /* return stolen element */
230 tryStealSpark (SparkPool *pool)
235 stolen = steal(pool);
236 } while (stolen != NULL && !closure_SHOULD_SPARK(stolen));
242 /* -----------------------------------------------------------------------------
244 * "guesses" whether a deque is empty. Can return false negatives in
245 * presence of concurrent steal() calls, and false positives in
246 * presence of a concurrent pushBottom().
248 * -------------------------------------------------------------------------- */
251 looksEmpty(SparkPool* deque)
253 StgWord t = deque->top;
254 StgWord b = deque->bottom;
255 /* try to prefer false negatives by reading top first */
257 /* => array is *never* completely filled, always 1 place free! */
260 /* -----------------------------------------------------------------------------
262 * Turn a spark into a real thread
264 * -------------------------------------------------------------------------- */
267 createSparkThread (Capability *cap, StgClosure *p)
271 tso = createGenThread (cap, RtsFlags.GcFlags.initialStkSize, p);
272 appendToRunQueue(cap,tso);
273 cap->sparks_converted++;
276 /* -----------------------------------------------------------------------------
280 * -------------------------------------------------------------------------- */
284 /* enqueue an element. Should always succeed by resizing the array
285 (not implemented yet, silently fails in that case). */
287 pushBottom (SparkPool* deque, StgClosurePtr elem)
291 StgWord sz = deque->moduloSize;
292 StgWord b = deque->bottom;
294 ASSERT_SPARK_POOL_INVARIANTS(deque);
296 /* we try to avoid reading deque->top (accessed by all) and use
297 deque->topBound (accessed only by writer) instead.
298 This is why we do not just call empty(deque) here.
301 if ( b - t >= sz ) { /* nota bene: sz == deque->size - 1, thus ">=" */
302 /* could be full, check the real top value in this case */
305 if (b - t >= sz) { /* really no space left :-( */
306 /* reallocate the array, copying the values. Concurrent steal()s
307 will in the meantime use the old one and modify only top.
308 This means: we cannot safely free the old space! Can keep it
309 on a free list internally here...
311 Potential bug in combination with steal(): if array is
312 replaced, it is unclear which one concurrent steal operations
313 use. Must read the array base address in advance in steal().
315 #if defined(DISCARD_NEW)
316 ASSERT_SPARK_POOL_INVARIANTS(deque);
317 return; /* for now, silently fail */
319 /* could make room by incrementing the top position here. In
320 * this case, should use CASTOP. If this fails, someone else has
321 * removed something, and new room will be available.
323 ASSERT_SPARK_POOL_INVARIANTS(deque);
327 pos = (deque->elements) + (b & sz);
331 ASSERT_SPARK_POOL_INVARIANTS(deque);
336 /* --------------------------------------------------------------------------
337 * newSpark: create a new spark, as a result of calling "par"
338 * Called directly from STG.
339 * -------------------------------------------------------------------------- */
342 newSpark (StgRegTable *reg, StgClosure *p)
344 Capability *cap = regTableToCapability(reg);
345 SparkPool *pool = cap->sparks;
347 /* I am not sure whether this is the right thing to do.
348 * Maybe it is better to exploit the tag information
349 * instead of throwing it away?
351 p = UNTAG_CLOSURE(p);
353 ASSERT_SPARK_POOL_INVARIANTS(pool);
355 if (closure_SHOULD_SPARK(p)) {
359 cap->sparks_created++;
361 ASSERT_SPARK_POOL_INVARIANTS(pool);
367 /* --------------------------------------------------------------------------
368 * Remove all sparks from the spark queues which should not spark any
369 * more. Called after GC. We assume exclusive access to the structure
370 * and replace all sparks in the queue, see explanation below. At exit,
371 * the spark pool only contains sparkable closures.
372 * -------------------------------------------------------------------------- */
375 pruneSparkQueue (evac_fn evac, void *user, Capability *cap)
378 StgClosurePtr spark, tmp, *elements;
379 nat n, pruned_sparks; // stats only
380 StgWord botInd,oldBotInd,currInd; // indices in array (always < size)
381 const StgInfoTable *info;
383 PAR_TICKY_MARK_SPARK_QUEUE_START();
390 debugTrace(DEBUG_sched,
391 "markSparkQueue: current spark queue len=%d; (hd=%ld; tl=%ld)",
392 sparkPoolSize(pool), pool->bottom, pool->top);
393 ASSERT_SPARK_POOL_INVARIANTS(pool);
395 elements = pool->elements;
397 /* We have exclusive access to the structure here, so we can reset
398 bottom and top counters, and prune invalid sparks. Contents are
399 copied in-place if they are valuable, otherwise discarded. The
400 routine uses "real" indices t and b, starts by computing them
401 as the modulus size of top and bottom,
405 At the beginning, the pool structure can look like this:
406 ( bottom % size >= top % size , no wrap-around)
408 ___________***********_________________
410 or like this ( bottom % size < top % size, wrap-around )
412 ***********__________******************
413 As we need to remove useless sparks anyway, we make one pass
414 between t and b, moving valuable content to b and subsequent
415 cells (wrapping around when the size is reached).
418 ***********OOO_______XX_X__X?**********
421 After this movement, botInd becomes the new bottom, and old
422 bottom becomes the new top index, both as indices in the array
426 currInd = (pool->top) & (pool->moduloSize); // mod
428 // copies of evacuated closures go to space from botInd on
429 // we keep oldBotInd to know when to stop
430 oldBotInd = botInd = (pool->bottom) & (pool->moduloSize); // mod
432 // on entry to loop, we are within the bounds
433 ASSERT( currInd < pool->size && botInd < pool->size );
435 while (currInd != oldBotInd ) {
436 /* must use != here, wrap-around at size
437 subtle: loop not entered if queue empty
440 /* check element at currInd. if valuable, evacuate and move to
441 botInd, otherwise move on */
442 spark = elements[currInd];
444 // We have to be careful here: in the parallel GC, another
445 // thread might evacuate this closure while we're looking at it,
446 // so grab the info pointer just once.
447 info = spark->header.info;
448 if (IS_FORWARDING_PTR(info)) {
449 tmp = (StgClosure*)UN_FORWARDING_PTR(info);
450 /* if valuable work: shift inside the pool */
451 if (closure_SHOULD_SPARK(tmp)) {
452 elements[botInd] = tmp; // keep entry (new address)
456 pruned_sparks++; // discard spark
457 cap->sparks_pruned++;
460 if (!(closure_flags[INFO_PTR_TO_STRUCT(info)->type] & _NS)) {
461 elements[botInd] = spark; // keep entry (new address)
462 evac (user, &elements[botInd]);
466 pruned_sparks++; // discard spark
467 cap->sparks_pruned++;
472 // in the loop, we may reach the bounds, and instantly wrap around
473 ASSERT( currInd <= pool->size && botInd <= pool->size );
474 if ( currInd == pool->size ) { currInd = 0; }
475 if ( botInd == pool->size ) { botInd = 0; }
477 } // while-loop over spark pool elements
479 ASSERT(currInd == oldBotInd);
481 pool->top = oldBotInd; // where we started writing
482 pool->topBound = pool->top;
484 pool->bottom = (oldBotInd <= botInd) ? botInd : (botInd + pool->size);
485 // first free place we did not use (corrected by wraparound)
487 PAR_TICKY_MARK_SPARK_QUEUE_END(n);
489 debugTrace(DEBUG_sched, "pruned %d sparks", pruned_sparks);
491 debugTrace(DEBUG_sched,
492 "new spark queue len=%d; (hd=%ld; tl=%ld)",
493 sparkPoolSize(pool), pool->bottom, pool->top);
495 ASSERT_SPARK_POOL_INVARIANTS(pool);
498 /* GC for the spark pool, called inside Capability.c for all
499 capabilities in turn. Blindly "evac"s complete spark pool. */
501 traverseSparkQueue (evac_fn evac, void *user, Capability *cap)
505 StgWord top,bottom, modMask;
509 ASSERT_SPARK_POOL_INVARIANTS(pool);
512 bottom = pool->bottom;
513 sparkp = pool->elements;
514 modMask = pool->moduloSize;
516 while (top < bottom) {
517 /* call evac for all closures in range (wrap-around via modulo)
518 * In GHC-6.10, evac takes an additional 1st argument to hold a
519 * GC-specific register, see rts/sm/GC.c::mark_root()
521 evac( user , sparkp + (top & modMask) );
525 debugTrace(DEBUG_sched,
526 "traversed spark queue, len=%d; (hd=%ld; tl=%ld)",
527 sparkPoolSize(pool), pool->bottom, pool->top);
530 /* ----------------------------------------------------------------------------
531 * balanceSparkPoolsCaps: takes an array of capabilities (usually: all
532 * capabilities) and its size. Accesses all spark pools and equally
533 * distributes the sparks among them.
535 * Could be called after GC, before Cap. release, from scheduler.
536 * -------------------------------------------------------------------------- */
537 void balanceSparkPoolsCaps(nat n_caps, Capability caps[]);
539 void balanceSparkPoolsCaps(nat n_caps STG_UNUSED,
540 Capability caps[] STG_UNUSED) {
541 barf("not implemented");
547 newSpark (StgRegTable *reg STG_UNUSED, StgClosure *p STG_UNUSED)
554 #endif /* PARALLEL_HASKELL || THREADED_RTS */
557 /* -----------------------------------------------------------------------------
559 * GRAN & PARALLEL_HASKELL stuff beyond here.
563 * -------------------------------------------------------------------------- */
565 #if defined(PARALLEL_HASKELL) || defined(GRAN)
567 static void slide_spark_pool( StgSparkPool *pool );
570 add_to_spark_queue( StgClosure *closure, StgSparkPool *pool )
572 if (pool->tl == pool->lim)
573 slide_spark_pool(pool);
575 if (closure_SHOULD_SPARK(closure) &&
576 pool->tl < pool->lim) {
577 *(pool->tl++) = closure;
579 #if defined(PARALLEL_HASKELL)
580 // collect parallel global statistics (currently done together with GC stats)
581 if (RtsFlags.ParFlags.ParStats.Global &&
582 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
583 // debugBelch("Creating spark for %x @ %11.2f\n", closure, usertime());
584 globalParStats.tot_sparks_created++;
589 #if defined(PARALLEL_HASKELL)
590 // collect parallel global statistics (currently done together with GC stats)
591 if (RtsFlags.ParFlags.ParStats.Global &&
592 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
593 //debugBelch("Ignoring spark for %x @ %11.2f\n", closure, usertime());
594 globalParStats.tot_sparks_ignored++;
602 slide_spark_pool( StgSparkPool *pool )
604 StgClosure **sparkp, **to_sparkp;
607 to_sparkp = pool->base;
608 while (sparkp < pool->tl) {
609 ASSERT(to_sparkp<=sparkp);
610 ASSERT(*sparkp!=NULL);
611 ASSERT(LOOKS_LIKE_GHC_INFO((*sparkp)->header.info));
613 if (closure_SHOULD_SPARK(*sparkp)) {
614 *to_sparkp++ = *sparkp++;
619 pool->hd = pool->base;
620 pool->tl = to_sparkp;
627 #if !defined(THREADED_RTS)
632 pool = &(cap->rSparks);
633 ASSERT(pool->hd <= pool->tl && pool->tl <= pool->lim);
635 ASSERT(spark != (StgClosure *)NULL);
643 Search the spark queue of the proc in event for a spark that's worth
644 turning into a thread
645 (was gimme_spark in the old RTS)
648 findLocalSpark (rtsEvent *event, rtsBool *found_res, rtsSparkQ *spark_res)
650 PEs proc = event->proc, /* proc to search for work */
651 creator = event->creator; /* proc that requested work */
654 rtsSparkQ spark_of_non_local_node = NULL,
655 spark_of_non_local_node_prev = NULL,
656 low_priority_spark = NULL,
657 low_priority_spark_prev = NULL,
658 spark = NULL, prev = NULL;
660 /* Choose a spark from the local spark queue */
661 prev = (rtsSpark*)NULL;
662 spark = pending_sparks_hds[proc];
665 // ToDo: check this code & implement local sparking !! -- HWL
666 while (!found && spark != (rtsSpark*)NULL)
668 ASSERT((prev!=(rtsSpark*)NULL || spark==pending_sparks_hds[proc]) &&
669 (prev==(rtsSpark*)NULL || prev->next==spark) &&
670 (spark->prev==prev));
672 if (!closure_SHOULD_SPARK(node))
674 IF_GRAN_DEBUG(checkSparkQ,
675 debugBelch("^^ pruning spark %p (node %p) in gimme_spark",
678 if (RtsFlags.GranFlags.GranSimStats.Sparks)
679 DumpRawGranEvent(proc, (PEs)0, SP_PRUNED,(StgTSO*)NULL,
680 spark->node, spark->name, spark_queue_len(proc));
682 ASSERT(spark != (rtsSpark*)NULL);
683 ASSERT(SparksAvail>0);
686 ASSERT(prev==(rtsSpark*)NULL || prev->next==spark);
687 spark = delete_from_sparkq (spark, proc, rtsTrue);
688 if (spark != (rtsSpark*)NULL)
692 /* -- node should eventually be sparked */
693 else if (RtsFlags.GranFlags.PreferSparksOfLocalNodes &&
694 !IS_LOCAL_TO(PROCS(node),CurrentProc))
696 barf("Local sparking not yet implemented");
698 /* Remember first low priority spark */
699 if (spark_of_non_local_node==(rtsSpark*)NULL) {
700 spark_of_non_local_node_prev = prev;
701 spark_of_non_local_node = spark;
704 if (spark->next == (rtsSpark*)NULL) {
705 /* ASSERT(spark==SparkQueueTl); just for testing */
706 prev = spark_of_non_local_node_prev;
707 spark = spark_of_non_local_node;
712 # if defined(GRAN) && defined(GRAN_CHECK)
713 /* Should never happen; just for testing
714 if (spark==pending_sparks_tl) {
715 debugBelch("ReSchedule: Last spark != SparkQueueTl\n");
716 stg_exit(EXIT_FAILURE);
721 ASSERT(SparksAvail>0);
725 else if ( RtsFlags.GranFlags.DoPrioritySparking ||
726 (spark->gran_info >= RtsFlags.GranFlags.SparkPriority2) )
728 if (RtsFlags.GranFlags.DoPrioritySparking)
729 barf("Priority sparking not yet implemented");
734 else /* only used if SparkPriority2 is defined */
736 /* ToDo: fix the code below and re-integrate it */
737 /* Remember first low priority spark */
738 if (low_priority_spark==(rtsSpark*)NULL) {
739 low_priority_spark_prev = prev;
740 low_priority_spark = spark;
743 if (spark->next == (rtsSpark*)NULL) {
744 /* ASSERT(spark==spark_queue_tl); just for testing */
745 prev = low_priority_spark_prev;
746 spark = low_priority_spark;
747 found = rtsTrue; /* take low pri spark => rc is 2 */
751 /* Should never happen; just for testing
752 if (spark==pending_sparks_tl) {
753 debugBelch("ReSchedule: Last spark != SparkQueueTl\n");
754 stg_exit(EXIT_FAILURE);
761 debugBelch("++ Ignoring spark of priority %u (SparkPriority=%u); node=%p; name=%u\n",
762 spark->gran_info, RtsFlags.GranFlags.SparkPriority,
763 spark->node, spark->name);)
766 } /* while (spark!=NULL && !found) */
773 Turn the spark into a thread.
774 In GranSim this basically means scheduling a StartThread event for the
775 node pointed to by the spark at some point in the future.
776 (was munch_spark in the old RTS)
779 activateSpark (rtsEvent *event, rtsSparkQ spark)
781 PEs proc = event->proc, /* proc to search for work */
782 creator = event->creator; /* proc that requested work */
785 rtsTime spark_arrival_time;
788 We've found a node on PE proc requested by PE creator.
789 If proc==creator we can turn the spark into a thread immediately;
790 otherwise we schedule a MoveSpark event on the requesting PE
796 /* only possible if we simulate GUM style fishing */
797 ASSERT(RtsFlags.GranFlags.Fishing);
799 /* Message packing costs for sending a Fish; qeq jabbI'ID */
800 CurrentTime[proc] += RtsFlags.GranFlags.Costs.mpacktime;
802 if (RtsFlags.GranFlags.GranSimStats.Sparks)
803 DumpRawGranEvent(proc, (PEs)0, SP_EXPORTED,
804 (StgTSO*)NULL, spark->node,
805 spark->name, spark_queue_len(proc));
807 /* time of the spark arrival on the remote PE */
808 spark_arrival_time = CurrentTime[proc] + RtsFlags.GranFlags.Costs.latency;
810 new_event(creator, proc, spark_arrival_time,
812 (StgTSO*)NULL, spark->node, spark);
814 CurrentTime[proc] += RtsFlags.GranFlags.Costs.mtidytime;
816 } else { /* proc==creator i.e. turn the spark into a thread */
818 if ( RtsFlags.GranFlags.GranSimStats.Global &&
819 spark->gran_info < RtsFlags.GranFlags.SparkPriority2 ) {
821 globalGranStats.tot_low_pri_sparks++;
823 debugBelch("++ No high priority spark available; low priority (%u) spark chosen: node=%p; name=%u\n",
825 spark->node, spark->name));
828 CurrentTime[proc] += RtsFlags.GranFlags.Costs.threadcreatetime;
833 /* ToDo: fix the GC interface and move to StartThread handling-- HWL */
834 if (GARBAGE COLLECTION IS NECESSARY) {
835 /* Some kind of backoff needed here in case there's too little heap */
836 # if defined(GRAN_CHECK) && defined(GRAN)
837 if (RtsFlags.GcFlags.giveStats)
838 fprintf(RtsFlags.GcFlags.statsFile,"***** vIS Qu' chen veQ boSwI'; spark=%p, node=%p; name=%u\n",
839 /* (found==2 ? "no hi pri spark" : "hi pri spark"), */
840 spark, node, spark->name);
842 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc]+1,
844 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
845 barf("//// activateSpark: out of heap ; ToDo: call GarbageCollect()");
846 GarbageCollect(GetRoots, rtsFalse);
847 // HWL old: ReallyPerformThreadGC(TSO_HS+TSO_CTS_SIZE,rtsFalse);
848 // HWL old: SAVE_Hp -= TSO_HS+TSO_CTS_SIZE;
850 return; /* was: continue; */ /* to the next event, eventually */
854 if (RtsFlags.GranFlags.GranSimStats.Sparks)
855 DumpRawGranEvent(CurrentProc,(PEs)0,SP_USED,(StgTSO*)NULL,
856 spark->node, spark->name,
857 spark_queue_len(CurrentProc));
859 new_event(proc, proc, CurrentTime[proc],
861 END_TSO_QUEUE, node, spark); // (rtsSpark*)NULL);
863 procStatus[proc] = Starting;
867 /* -------------------------------------------------------------------------
868 This is the main point where handling granularity information comes into
870 ------------------------------------------------------------------------- */
872 #define MAX_RAND_PRI 100
875 Granularity info transformers.
876 Applied to the GRAN_INFO field of a spark.
878 STATIC_INLINE nat ID(nat x) { return(x); };
879 STATIC_INLINE nat INV(nat x) { return(-x); };
880 STATIC_INLINE nat IGNORE(nat x) { return (0); };
881 STATIC_INLINE nat RAND(nat x) { return ((random() % MAX_RAND_PRI) + 1); }
883 /* NB: size_info and par_info are currently unused (what a shame!) -- HWL */
885 newSpark(node,name,gran_info,size_info,par_info,local)
887 nat name, gran_info, size_info, par_info, local;
892 pri = RtsFlags.GranFlags.RandomPriorities ? RAND(gran_info) :
893 RtsFlags.GranFlags.InversePriorities ? INV(gran_info) :
894 RtsFlags.GranFlags.IgnorePriorities ? IGNORE(gran_info) :
897 if ( RtsFlags.GranFlags.SparkPriority!=0 &&
898 pri<RtsFlags.GranFlags.SparkPriority ) {
900 debugBelch(",, NewSpark: Ignoring spark of priority %u (SparkPriority=%u); node=%#x; name=%u\n",
901 pri, RtsFlags.GranFlags.SparkPriority, node, name));
902 return ((rtsSpark*)NULL);
905 newspark = (rtsSpark*) stgMallocBytes(sizeof(rtsSpark), "NewSpark");
906 newspark->prev = newspark->next = (rtsSpark*)NULL;
907 newspark->node = node;
908 newspark->name = (name==1) ? CurrentTSO->gran.sparkname : name;
909 newspark->gran_info = pri;
910 newspark->global = !local; /* Check that with parAt, parAtAbs !!*/
912 if (RtsFlags.GranFlags.GranSimStats.Global) {
913 globalGranStats.tot_sparks_created++;
914 globalGranStats.sparks_created_on_PE[CurrentProc]++;
935 disposeSparkQ(spark->next);
938 if (SparksAvail < 0) {
939 debugBelch("disposeSparkQ: SparksAvail<0 after disposing sparkq @ %p\n", &spark);
948 With PrioritySparking add_to_spark_queue performs an insert sort to keep
949 the spark queue sorted. Otherwise the spark is just added to the end of
954 add_to_spark_queue(spark)
957 rtsSpark *prev = NULL, *next = NULL;
959 rtsBool found = rtsFalse;
961 if ( spark == (rtsSpark *)NULL ) {
965 if (RtsFlags.GranFlags.DoPrioritySparking && (spark->gran_info != 0) ) {
966 /* Priority sparking is enabled i.e. spark queues must be sorted */
968 for (prev = NULL, next = pending_sparks_hd, count=0;
970 !(found = (spark->gran_info >= next->gran_info));
971 prev = next, next = next->next, count++)
974 } else { /* 'utQo' */
975 /* Priority sparking is disabled */
977 found = rtsFalse; /* to add it at the end */
982 /* next points to the first spark with a gran_info smaller than that
983 of spark; therefore, add spark before next into the spark queue */
985 if ( next == NULL ) {
986 pending_sparks_tl = spark;
991 if ( prev == NULL ) {
992 pending_sparks_hd = spark;
996 } else { /* (RtsFlags.GranFlags.DoPrioritySparking && !found) || !DoPrioritySparking */
997 /* add the spark at the end of the spark queue */
999 spark->prev = pending_sparks_tl;
1000 if (pending_sparks_hd == NULL)
1001 pending_sparks_hd = spark;
1003 pending_sparks_tl->next = spark;
1004 pending_sparks_tl = spark;
1008 /* add costs for search in priority sparking */
1009 if (RtsFlags.GranFlags.DoPrioritySparking) {
1010 CurrentTime[CurrentProc] += count * RtsFlags.GranFlags.Costs.pri_spark_overhead;
1013 IF_GRAN_DEBUG(checkSparkQ,
1014 debugBelch("++ Spark stats after adding spark %p (node %p) to queue on PE %d",
1015 spark, spark->node, CurrentProc);
1016 print_sparkq_stats());
1018 # if defined(GRAN_CHECK)
1019 if (RtsFlags.GranFlags.Debug.checkSparkQ) {
1020 for (prev = NULL, next = pending_sparks_hd;
1022 prev = next, next = next->next)
1024 if ( (prev!=NULL) && (prev!=pending_sparks_tl) )
1025 debugBelch("SparkQ inconsistency after adding spark %p: (PE %u) pending_sparks_tl (%p) not end of queue (%p)\n",
1027 pending_sparks_tl, prev);
1031 # if defined(GRAN_CHECK)
1032 /* Check if the sparkq is still sorted. Just for testing, really! */
1033 if ( RtsFlags.GranFlags.Debug.checkSparkQ &&
1034 RtsFlags.GranFlags.Debug.pri ) {
1035 rtsBool sorted = rtsTrue;
1036 rtsSpark *prev, *next;
1038 if (pending_sparks_hd == NULL ||
1039 pending_sparks_hd->next == NULL ) {
1040 /* just 1 elem => ok */
1042 for (prev = pending_sparks_hd,
1043 next = pending_sparks_hd->next;
1045 prev = next, next = next->next) {
1047 (prev->gran_info >= next->gran_info);
1051 debugBelch("ghuH: SPARKQ on PE %d is not sorted:\n",
1053 print_sparkq(CurrentProc);
1060 spark_queue_len(proc)
1063 rtsSpark *prev, *spark; /* prev only for testing !! */
1066 for (len = 0, prev = NULL, spark = pending_sparks_hds[proc];
1068 len++, prev = spark, spark = spark->next)
1071 # if defined(GRAN_CHECK)
1072 if ( RtsFlags.GranFlags.Debug.checkSparkQ )
1073 if ( (prev!=NULL) && (prev!=pending_sparks_tls[proc]) )
1074 debugBelch("ERROR in spark_queue_len: (PE %u) pending_sparks_tl (%p) not end of queue (%p)\n",
1075 proc, pending_sparks_tls[proc], prev);
1082 Take spark out of the spark queue on PE p and nuke the spark. Adjusts
1083 hd and tl pointers of the spark queue. Returns a pointer to the next
1087 delete_from_sparkq (spark, p, dispose_too) /* unlink and dispose spark */
1090 rtsBool dispose_too;
1092 rtsSpark *new_spark;
1095 barf("delete_from_sparkq: trying to delete NULL spark\n");
1097 # if defined(GRAN_CHECK)
1098 if ( RtsFlags.GranFlags.Debug.checkSparkQ ) {
1099 debugBelch("## |%p:%p| (%p)<-spark=%p->(%p) <-(%p)\n",
1100 pending_sparks_hd, pending_sparks_tl,
1101 spark->prev, spark, spark->next,
1102 (spark->next==NULL ? 0 : spark->next->prev));
1106 if (spark->prev==NULL) {
1107 /* spark is first spark of queue => adjust hd pointer */
1108 ASSERT(pending_sparks_hds[p]==spark);
1109 pending_sparks_hds[p] = spark->next;
1111 spark->prev->next = spark->next;
1113 if (spark->next==NULL) {
1114 ASSERT(pending_sparks_tls[p]==spark);
1115 /* spark is first spark of queue => adjust tl pointer */
1116 pending_sparks_tls[p] = spark->prev;
1118 spark->next->prev = spark->prev;
1120 new_spark = spark->next;
1122 # if defined(GRAN_CHECK)
1123 if ( RtsFlags.GranFlags.Debug.checkSparkQ ) {
1124 debugBelch("## |%p:%p| (%p)<-spark=%p->(%p) <-(%p); spark=%p will be deleted NOW \n",
1125 pending_sparks_hd, pending_sparks_tl,
1126 spark->prev, spark, spark->next,
1127 (spark->next==NULL ? 0 : spark->next->prev), spark);
1132 disposeSpark(spark);
1137 /* Mark all nodes pointed to by sparks in the spark queues (for GC) */
1139 markSparkQueue(void)
1141 StgClosure *MarkRoot(StgClosure *root); // prototype
1145 for (p=0; p<RtsFlags.GranFlags.proc; p++)
1146 for (sp=pending_sparks_hds[p]; sp!=NULL; sp=sp->next) {
1147 ASSERT(sp->node!=NULL);
1148 ASSERT(LOOKS_LIKE_GHC_INFO(sp->node->header.info));
1149 // ToDo?: statistics gathering here (also for GUM!)
1150 sp->node = (StgClosure *)MarkRoot(sp->node);
1154 debugBelch("markSparkQueue: spark statistics at start of GC:");
1155 print_sparkq_stats());
1165 debugBelch("Spark: NIL\n");
1169 ((spark->node==NULL) ? "______" : "%#6lx"),
1170 stgCast(StgPtr,spark->node));
1172 debugBelch("Spark: Node %8s, Name %#6x, Global %5s, Creator %5x, Prev %6p, Next %6p\n",
1174 ((spark->global)==rtsTrue?"True":"False"), spark->creator,
1175 spark->prev, spark->next);
1184 rtsSpark *x = pending_sparks_hds[proc];
1186 debugBelch("Spark Queue of PE %d with root at %p:\n", proc, x);
1187 for (; x!=(rtsSpark*)NULL; x=x->next) {
1193 Print a statistics of all spark queues.
1196 print_sparkq_stats(void)
1200 debugBelch("SparkQs: [");
1201 for (p=0; p<RtsFlags.GranFlags.proc; p++)
1202 debugBelch(", PE %d: %d", p, spark_queue_len(p));