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"
49 #include "SMP.h" // for cas
53 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
55 /* internal helpers ... */
62 /* StgWord is unsigned anyway, only catch 0 */
64 barf("DeQue,roundUp2: invalid size 0 requested");
66 /* at least 1 bit set, shift up to its place */
68 rounded = rounded << 1;
69 } while (0 != (val = val>>1));
73 #define CASTOP(addr,old,new) ((old) == cas(((StgPtr)addr),(old),(new)))
75 /* -----------------------------------------------------------------------------
77 * Initialising spark pools.
79 * -------------------------------------------------------------------------- */
83 initPool(StgWord size)
88 realsize = roundUp2(size); /* to compute modulo as a bitwise & */
90 q = (SparkPool*) stgMallocBytes(sizeof(SparkPool), /* admin fields */
92 q->elements = (StgClosurePtr*)
93 stgMallocBytes(realsize * sizeof(StgClosurePtr), /* dataspace */
94 "newSparkPool:data space");
97 q->topBound=0; /* read by writer, updated each time top is read */
99 q->size = realsize; /* power of 2 */
100 q->moduloSize = realsize - 1; /* n % size == n & moduloSize */
102 ASSERT_SPARK_POOL_INVARIANTS(q);
107 initSparkPools( void )
110 /* walk over the capabilities, allocating a spark pool for each one */
112 for (i = 0; i < n_capabilities; i++) {
113 capabilities[i].sparks = initPool(RtsFlags.ParFlags.maxLocalSparks);
116 /* allocate a single spark pool */
117 MainCapability->sparks = initPool(RtsFlags.ParFlags.maxLocalSparks);
122 freeSparkPool (SparkPool *pool)
124 /* should not interfere with concurrent findSpark() calls! And
125 nobody should use the pointer any more. We cross our fingers...*/
126 stgFree(pool->elements);
130 /* -----------------------------------------------------------------------------
132 * reclaimSpark: remove a spark from the write end of the queue.
133 * Returns the removed spark, and NULL if a race is lost or the pool
136 * If only one spark is left in the pool, we synchronise with
137 * concurrently stealing threads by using cas to modify the top field.
138 * This routine should NEVER be called by a task which does not own
139 * the capability. Can this be checked here?
141 * -------------------------------------------------------------------------- */
144 reclaimSpark (SparkPool *deque)
146 /* also a bit tricky, has to avoid concurrent steal() calls by
147 accessing top with cas, when there is only one element left */
151 StgClosurePtr removed;
153 ASSERT_SPARK_POOL_INVARIANTS(deque);
156 /* "decrement b as a test, see what happens" */
158 pos = (deque->elements) + (b & (deque->moduloSize));
159 t = deque->top; /* using topBound would give an *upper* bound, we
160 need a lower bound. We use the real top here, but
161 can update the topBound value */
164 if (currSize < 0) { /* was empty before decrementing b, set b
165 consistently and abort */
170 if (currSize > 0) { /* no danger, still elements in buffer after b-- */
173 /* otherwise, has someone meanwhile stolen the same (last) element?
174 Check and increment top value to know */
175 if ( !(CASTOP(&(deque->top),t,t+1)) ) {
176 removed = NULL; /* no success, but continue adjusting bottom */
178 deque->bottom = t+1; /* anyway, empty now. Adjust bottom consistently. */
179 deque->topBound = t+1; /* ...and cached top value as well */
181 ASSERT_SPARK_POOL_INVARIANTS(deque);
186 /* -----------------------------------------------------------------------------
188 * tryStealSpark: try to steal a spark from a Capability.
190 * Returns a valid spark, or NULL if the pool was empty, and can
191 * occasionally return NULL if there was a race with another thread
192 * stealing from the same pool. In this case, try again later.
194 -------------------------------------------------------------------------- */
197 steal(SparkPool *deque)
200 StgClosurePtr* arraybase;
202 StgClosurePtr stolen;
205 ASSERT_SPARK_POOL_INVARIANTS(deque);
210 return NULL; /* already looks empty, abort */
213 /* now access array, see pushBottom() */
214 arraybase = deque->elements;
215 sz = deque->moduloSize;
216 pos = arraybase + (t & sz);
219 /* now decide whether we have won */
220 if ( !(CASTOP(&(deque->top),t,t+1)) ) {
221 /* lost the race, someon else has changed top in the meantime */
223 } /* else: OK, top has been incremented by the cas call */
225 ASSERT_SPARK_POOL_INVARIANTS(deque);
226 /* return stolen element */
231 tryStealSpark (Capability *cap)
233 SparkPool *pool = cap->sparks;
237 stolen = steal(pool);
238 } while (stolen != NULL && !closure_SHOULD_SPARK(stolen));
244 /* -----------------------------------------------------------------------------
246 * "guesses" whether a deque is empty. Can return false negatives in
247 * presence of concurrent steal() calls, and false positives in
248 * presence of a concurrent pushBottom().
250 * -------------------------------------------------------------------------- */
253 looksEmpty(SparkPool* deque)
255 StgWord t = deque->top;
256 StgWord b = deque->bottom;
257 /* try to prefer false negatives by reading top first */
259 /* => array is *never* completely filled, always 1 place free! */
262 /* -----------------------------------------------------------------------------
264 * Turn a spark into a real thread
266 * -------------------------------------------------------------------------- */
269 createSparkThread (Capability *cap)
273 tso = createIOThread (cap, RtsFlags.GcFlags.initialStkSize,
274 &base_GHCziConc_runSparks_closure);
275 appendToRunQueue(cap,tso);
278 /* -----------------------------------------------------------------------------
282 * -------------------------------------------------------------------------- */
286 /* enqueue an element. Should always succeed by resizing the array
287 (not implemented yet, silently fails in that case). */
289 pushBottom (SparkPool* deque, StgClosurePtr elem)
293 StgWord sz = deque->moduloSize;
294 StgWord b = deque->bottom;
296 ASSERT_SPARK_POOL_INVARIANTS(deque);
298 /* we try to avoid reading deque->top (accessed by all) and use
299 deque->topBound (accessed only by writer) instead.
300 This is why we do not just call empty(deque) here.
303 if ( b - t >= sz ) { /* nota bene: sz == deque->size - 1, thus ">=" */
304 /* could be full, check the real top value in this case */
307 if (b - t >= sz) { /* really no space left :-( */
308 /* reallocate the array, copying the values. Concurrent steal()s
309 will in the meantime use the old one and modify only top.
310 This means: we cannot safely free the old space! Can keep it
311 on a free list internally here...
313 Potential bug in combination with steal(): if array is
314 replaced, it is unclear which one concurrent steal operations
315 use. Must read the array base address in advance in steal().
317 #if defined(DISCARD_NEW)
318 ASSERT_SPARK_POOL_INVARIANTS(deque);
319 return; /* for now, silently fail */
321 /* could make room by incrementing the top position here. In
322 * this case, should use CASTOP. If this fails, someone else has
323 * removed something, and new room will be available.
325 ASSERT_SPARK_POOL_INVARIANTS(deque);
329 pos = (deque->elements) + (b & sz);
333 ASSERT_SPARK_POOL_INVARIANTS(deque);
338 /* --------------------------------------------------------------------------
339 * newSpark: create a new spark, as a result of calling "par"
340 * Called directly from STG.
341 * -------------------------------------------------------------------------- */
344 newSpark (StgRegTable *reg, StgClosure *p)
346 Capability *cap = regTableToCapability(reg);
347 SparkPool *pool = cap->sparks;
349 /* I am not sure whether this is the right thing to do.
350 * Maybe it is better to exploit the tag information
351 * instead of throwing it away?
353 p = UNTAG_CLOSURE(p);
355 ASSERT_SPARK_POOL_INVARIANTS(pool);
357 if (closure_SHOULD_SPARK(p)) {
361 cap->sparks_created++;
363 ASSERT_SPARK_POOL_INVARIANTS(pool);
369 /* --------------------------------------------------------------------------
370 * Remove all sparks from the spark queues which should not spark any
371 * more. Called after GC. We assume exclusive access to the structure
372 * and replace all sparks in the queue, see explanation below. At exit,
373 * the spark pool only contains sparkable closures.
374 * -------------------------------------------------------------------------- */
377 pruneSparkQueue (evac_fn evac, void *user, Capability *cap)
380 StgClosurePtr spark, tmp, *elements;
381 nat n, pruned_sparks; // stats only
382 StgWord botInd,oldBotInd,currInd; // indices in array (always < size)
383 const StgInfoTable *info;
385 PAR_TICKY_MARK_SPARK_QUEUE_START();
392 // Take this opportunity to reset top/bottom modulo the size of
393 // the array, to avoid overflow. This is only possible because no
394 // stealing is happening during GC.
395 pool->bottom -= pool->top & ~pool->moduloSize;
396 pool->top &= pool->moduloSize;
397 pool->topBound = pool->top;
399 debugTrace(DEBUG_sched,
400 "markSparkQueue: current spark queue len=%d; (hd=%ld; tl=%ld)",
401 sparkPoolSize(pool), pool->bottom, pool->top);
402 ASSERT_SPARK_POOL_INVARIANTS(pool);
404 elements = pool->elements;
406 /* We have exclusive access to the structure here, so we can reset
407 bottom and top counters, and prune invalid sparks. Contents are
408 copied in-place if they are valuable, otherwise discarded. The
409 routine uses "real" indices t and b, starts by computing them
410 as the modulus size of top and bottom,
414 At the beginning, the pool structure can look like this:
415 ( bottom % size >= top % size , no wrap-around)
417 ___________***********_________________
419 or like this ( bottom % size < top % size, wrap-around )
421 ***********__________******************
422 As we need to remove useless sparks anyway, we make one pass
423 between t and b, moving valuable content to b and subsequent
424 cells (wrapping around when the size is reached).
427 ***********OOO_______XX_X__X?**********
430 After this movement, botInd becomes the new bottom, and old
431 bottom becomes the new top index, both as indices in the array
435 currInd = (pool->top) & (pool->moduloSize); // mod
437 // copies of evacuated closures go to space from botInd on
438 // we keep oldBotInd to know when to stop
439 oldBotInd = botInd = (pool->bottom) & (pool->moduloSize); // mod
441 // on entry to loop, we are within the bounds
442 ASSERT( currInd < pool->size && botInd < pool->size );
444 while (currInd != oldBotInd ) {
445 /* must use != here, wrap-around at size
446 subtle: loop not entered if queue empty
449 /* check element at currInd. if valuable, evacuate and move to
450 botInd, otherwise move on */
451 spark = elements[currInd];
453 // We have to be careful here: in the parallel GC, another
454 // thread might evacuate this closure while we're looking at it,
455 // so grab the info pointer just once.
456 info = spark->header.info;
457 if (IS_FORWARDING_PTR(info)) {
458 tmp = (StgClosure*)UN_FORWARDING_PTR(info);
459 /* if valuable work: shift inside the pool */
460 if (closure_SHOULD_SPARK(tmp)) {
461 elements[botInd] = tmp; // keep entry (new address)
465 pruned_sparks++; // discard spark
466 cap->sparks_pruned++;
469 if (!(closure_flags[INFO_PTR_TO_STRUCT(info)->type] & _NS)) {
470 elements[botInd] = spark; // keep entry (new address)
471 evac (user, &elements[botInd]);
475 pruned_sparks++; // discard spark
476 cap->sparks_pruned++;
481 // in the loop, we may reach the bounds, and instantly wrap around
482 ASSERT( currInd <= pool->size && botInd <= pool->size );
483 if ( currInd == pool->size ) { currInd = 0; }
484 if ( botInd == pool->size ) { botInd = 0; }
486 } // while-loop over spark pool elements
488 ASSERT(currInd == oldBotInd);
490 pool->top = oldBotInd; // where we started writing
491 pool->topBound = pool->top;
493 pool->bottom = (oldBotInd <= botInd) ? botInd : (botInd + pool->size);
494 // first free place we did not use (corrected by wraparound)
496 PAR_TICKY_MARK_SPARK_QUEUE_END(n);
498 debugTrace(DEBUG_sched, "pruned %d sparks", pruned_sparks);
500 debugTrace(DEBUG_sched,
501 "new spark queue len=%d; (hd=%ld; tl=%ld)",
502 sparkPoolSize(pool), pool->bottom, pool->top);
504 ASSERT_SPARK_POOL_INVARIANTS(pool);
507 /* GC for the spark pool, called inside Capability.c for all
508 capabilities in turn. Blindly "evac"s complete spark pool. */
510 traverseSparkQueue (evac_fn evac, void *user, Capability *cap)
514 StgWord top,bottom, modMask;
518 ASSERT_SPARK_POOL_INVARIANTS(pool);
521 bottom = pool->bottom;
522 sparkp = pool->elements;
523 modMask = pool->moduloSize;
525 while (top < bottom) {
526 /* call evac for all closures in range (wrap-around via modulo)
527 * In GHC-6.10, evac takes an additional 1st argument to hold a
528 * GC-specific register, see rts/sm/GC.c::mark_root()
530 evac( user , sparkp + (top & modMask) );
534 debugTrace(DEBUG_sched,
535 "traversed spark queue, len=%d; (hd=%ld; tl=%ld)",
536 sparkPoolSize(pool), pool->bottom, pool->top);
539 /* ----------------------------------------------------------------------------
540 * balanceSparkPoolsCaps: takes an array of capabilities (usually: all
541 * capabilities) and its size. Accesses all spark pools and equally
542 * distributes the sparks among them.
544 * Could be called after GC, before Cap. release, from scheduler.
545 * -------------------------------------------------------------------------- */
546 void balanceSparkPoolsCaps(nat n_caps, Capability caps[]);
548 void balanceSparkPoolsCaps(nat n_caps STG_UNUSED,
549 Capability caps[] STG_UNUSED) {
550 barf("not implemented");
556 newSpark (StgRegTable *reg STG_UNUSED, StgClosure *p STG_UNUSED)
563 #endif /* PARALLEL_HASKELL || THREADED_RTS */
566 /* -----------------------------------------------------------------------------
568 * GRAN & PARALLEL_HASKELL stuff beyond here.
572 * -------------------------------------------------------------------------- */
574 #if defined(PARALLEL_HASKELL) || defined(GRAN)
576 static void slide_spark_pool( StgSparkPool *pool );
579 add_to_spark_queue( StgClosure *closure, StgSparkPool *pool )
581 if (pool->tl == pool->lim)
582 slide_spark_pool(pool);
584 if (closure_SHOULD_SPARK(closure) &&
585 pool->tl < pool->lim) {
586 *(pool->tl++) = closure;
588 #if defined(PARALLEL_HASKELL)
589 // collect parallel global statistics (currently done together with GC stats)
590 if (RtsFlags.ParFlags.ParStats.Global &&
591 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
592 // debugBelch("Creating spark for %x @ %11.2f\n", closure, usertime());
593 globalParStats.tot_sparks_created++;
598 #if defined(PARALLEL_HASKELL)
599 // collect parallel global statistics (currently done together with GC stats)
600 if (RtsFlags.ParFlags.ParStats.Global &&
601 RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
602 //debugBelch("Ignoring spark for %x @ %11.2f\n", closure, usertime());
603 globalParStats.tot_sparks_ignored++;
611 slide_spark_pool( StgSparkPool *pool )
613 StgClosure **sparkp, **to_sparkp;
616 to_sparkp = pool->base;
617 while (sparkp < pool->tl) {
618 ASSERT(to_sparkp<=sparkp);
619 ASSERT(*sparkp!=NULL);
620 ASSERT(LOOKS_LIKE_GHC_INFO((*sparkp)->header.info));
622 if (closure_SHOULD_SPARK(*sparkp)) {
623 *to_sparkp++ = *sparkp++;
628 pool->hd = pool->base;
629 pool->tl = to_sparkp;
636 #if !defined(THREADED_RTS)
641 pool = &(cap->rSparks);
642 ASSERT(pool->hd <= pool->tl && pool->tl <= pool->lim);
644 ASSERT(spark != (StgClosure *)NULL);
652 Search the spark queue of the proc in event for a spark that's worth
653 turning into a thread
654 (was gimme_spark in the old RTS)
657 findLocalSpark (rtsEvent *event, rtsBool *found_res, rtsSparkQ *spark_res)
659 PEs proc = event->proc, /* proc to search for work */
660 creator = event->creator; /* proc that requested work */
663 rtsSparkQ spark_of_non_local_node = NULL,
664 spark_of_non_local_node_prev = NULL,
665 low_priority_spark = NULL,
666 low_priority_spark_prev = NULL,
667 spark = NULL, prev = NULL;
669 /* Choose a spark from the local spark queue */
670 prev = (rtsSpark*)NULL;
671 spark = pending_sparks_hds[proc];
674 // ToDo: check this code & implement local sparking !! -- HWL
675 while (!found && spark != (rtsSpark*)NULL)
677 ASSERT((prev!=(rtsSpark*)NULL || spark==pending_sparks_hds[proc]) &&
678 (prev==(rtsSpark*)NULL || prev->next==spark) &&
679 (spark->prev==prev));
681 if (!closure_SHOULD_SPARK(node))
683 IF_GRAN_DEBUG(checkSparkQ,
684 debugBelch("^^ pruning spark %p (node %p) in gimme_spark",
687 if (RtsFlags.GranFlags.GranSimStats.Sparks)
688 DumpRawGranEvent(proc, (PEs)0, SP_PRUNED,(StgTSO*)NULL,
689 spark->node, spark->name, spark_queue_len(proc));
691 ASSERT(spark != (rtsSpark*)NULL);
692 ASSERT(SparksAvail>0);
695 ASSERT(prev==(rtsSpark*)NULL || prev->next==spark);
696 spark = delete_from_sparkq (spark, proc, rtsTrue);
697 if (spark != (rtsSpark*)NULL)
701 /* -- node should eventually be sparked */
702 else if (RtsFlags.GranFlags.PreferSparksOfLocalNodes &&
703 !IS_LOCAL_TO(PROCS(node),CurrentProc))
705 barf("Local sparking not yet implemented");
707 /* Remember first low priority spark */
708 if (spark_of_non_local_node==(rtsSpark*)NULL) {
709 spark_of_non_local_node_prev = prev;
710 spark_of_non_local_node = spark;
713 if (spark->next == (rtsSpark*)NULL) {
714 /* ASSERT(spark==SparkQueueTl); just for testing */
715 prev = spark_of_non_local_node_prev;
716 spark = spark_of_non_local_node;
721 # if defined(GRAN) && defined(GRAN_CHECK)
722 /* Should never happen; just for testing
723 if (spark==pending_sparks_tl) {
724 debugBelch("ReSchedule: Last spark != SparkQueueTl\n");
725 stg_exit(EXIT_FAILURE);
730 ASSERT(SparksAvail>0);
734 else if ( RtsFlags.GranFlags.DoPrioritySparking ||
735 (spark->gran_info >= RtsFlags.GranFlags.SparkPriority2) )
737 if (RtsFlags.GranFlags.DoPrioritySparking)
738 barf("Priority sparking not yet implemented");
743 else /* only used if SparkPriority2 is defined */
745 /* ToDo: fix the code below and re-integrate it */
746 /* Remember first low priority spark */
747 if (low_priority_spark==(rtsSpark*)NULL) {
748 low_priority_spark_prev = prev;
749 low_priority_spark = spark;
752 if (spark->next == (rtsSpark*)NULL) {
753 /* ASSERT(spark==spark_queue_tl); just for testing */
754 prev = low_priority_spark_prev;
755 spark = low_priority_spark;
756 found = rtsTrue; /* take low pri spark => rc is 2 */
760 /* Should never happen; just for testing
761 if (spark==pending_sparks_tl) {
762 debugBelch("ReSchedule: Last spark != SparkQueueTl\n");
763 stg_exit(EXIT_FAILURE);
770 debugBelch("++ Ignoring spark of priority %u (SparkPriority=%u); node=%p; name=%u\n",
771 spark->gran_info, RtsFlags.GranFlags.SparkPriority,
772 spark->node, spark->name);)
775 } /* while (spark!=NULL && !found) */
782 Turn the spark into a thread.
783 In GranSim this basically means scheduling a StartThread event for the
784 node pointed to by the spark at some point in the future.
785 (was munch_spark in the old RTS)
788 activateSpark (rtsEvent *event, rtsSparkQ spark)
790 PEs proc = event->proc, /* proc to search for work */
791 creator = event->creator; /* proc that requested work */
794 rtsTime spark_arrival_time;
797 We've found a node on PE proc requested by PE creator.
798 If proc==creator we can turn the spark into a thread immediately;
799 otherwise we schedule a MoveSpark event on the requesting PE
805 /* only possible if we simulate GUM style fishing */
806 ASSERT(RtsFlags.GranFlags.Fishing);
808 /* Message packing costs for sending a Fish; qeq jabbI'ID */
809 CurrentTime[proc] += RtsFlags.GranFlags.Costs.mpacktime;
811 if (RtsFlags.GranFlags.GranSimStats.Sparks)
812 DumpRawGranEvent(proc, (PEs)0, SP_EXPORTED,
813 (StgTSO*)NULL, spark->node,
814 spark->name, spark_queue_len(proc));
816 /* time of the spark arrival on the remote PE */
817 spark_arrival_time = CurrentTime[proc] + RtsFlags.GranFlags.Costs.latency;
819 new_event(creator, proc, spark_arrival_time,
821 (StgTSO*)NULL, spark->node, spark);
823 CurrentTime[proc] += RtsFlags.GranFlags.Costs.mtidytime;
825 } else { /* proc==creator i.e. turn the spark into a thread */
827 if ( RtsFlags.GranFlags.GranSimStats.Global &&
828 spark->gran_info < RtsFlags.GranFlags.SparkPriority2 ) {
830 globalGranStats.tot_low_pri_sparks++;
832 debugBelch("++ No high priority spark available; low priority (%u) spark chosen: node=%p; name=%u\n",
834 spark->node, spark->name));
837 CurrentTime[proc] += RtsFlags.GranFlags.Costs.threadcreatetime;
842 /* ToDo: fix the GC interface and move to StartThread handling-- HWL */
843 if (GARBAGE COLLECTION IS NECESSARY) {
844 /* Some kind of backoff needed here in case there's too little heap */
845 # if defined(GRAN_CHECK) && defined(GRAN)
846 if (RtsFlags.GcFlags.giveStats)
847 fprintf(RtsFlags.GcFlags.statsFile,"***** vIS Qu' chen veQ boSwI'; spark=%p, node=%p; name=%u\n",
848 /* (found==2 ? "no hi pri spark" : "hi pri spark"), */
849 spark, node, spark->name);
851 new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc]+1,
853 (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
854 barf("//// activateSpark: out of heap ; ToDo: call GarbageCollect()");
855 GarbageCollect(GetRoots, rtsFalse);
856 // HWL old: ReallyPerformThreadGC(TSO_HS+TSO_CTS_SIZE,rtsFalse);
857 // HWL old: SAVE_Hp -= TSO_HS+TSO_CTS_SIZE;
859 return; /* was: continue; */ /* to the next event, eventually */
863 if (RtsFlags.GranFlags.GranSimStats.Sparks)
864 DumpRawGranEvent(CurrentProc,(PEs)0,SP_USED,(StgTSO*)NULL,
865 spark->node, spark->name,
866 spark_queue_len(CurrentProc));
868 new_event(proc, proc, CurrentTime[proc],
870 END_TSO_QUEUE, node, spark); // (rtsSpark*)NULL);
872 procStatus[proc] = Starting;
876 /* -------------------------------------------------------------------------
877 This is the main point where handling granularity information comes into
879 ------------------------------------------------------------------------- */
881 #define MAX_RAND_PRI 100
884 Granularity info transformers.
885 Applied to the GRAN_INFO field of a spark.
887 STATIC_INLINE nat ID(nat x) { return(x); };
888 STATIC_INLINE nat INV(nat x) { return(-x); };
889 STATIC_INLINE nat IGNORE(nat x) { return (0); };
890 STATIC_INLINE nat RAND(nat x) { return ((random() % MAX_RAND_PRI) + 1); }
892 /* NB: size_info and par_info are currently unused (what a shame!) -- HWL */
894 newSpark(node,name,gran_info,size_info,par_info,local)
896 nat name, gran_info, size_info, par_info, local;
901 pri = RtsFlags.GranFlags.RandomPriorities ? RAND(gran_info) :
902 RtsFlags.GranFlags.InversePriorities ? INV(gran_info) :
903 RtsFlags.GranFlags.IgnorePriorities ? IGNORE(gran_info) :
906 if ( RtsFlags.GranFlags.SparkPriority!=0 &&
907 pri<RtsFlags.GranFlags.SparkPriority ) {
909 debugBelch(",, NewSpark: Ignoring spark of priority %u (SparkPriority=%u); node=%#x; name=%u\n",
910 pri, RtsFlags.GranFlags.SparkPriority, node, name));
911 return ((rtsSpark*)NULL);
914 newspark = (rtsSpark*) stgMallocBytes(sizeof(rtsSpark), "NewSpark");
915 newspark->prev = newspark->next = (rtsSpark*)NULL;
916 newspark->node = node;
917 newspark->name = (name==1) ? CurrentTSO->gran.sparkname : name;
918 newspark->gran_info = pri;
919 newspark->global = !local; /* Check that with parAt, parAtAbs !!*/
921 if (RtsFlags.GranFlags.GranSimStats.Global) {
922 globalGranStats.tot_sparks_created++;
923 globalGranStats.sparks_created_on_PE[CurrentProc]++;
944 disposeSparkQ(spark->next);
947 if (SparksAvail < 0) {
948 debugBelch("disposeSparkQ: SparksAvail<0 after disposing sparkq @ %p\n", &spark);
957 With PrioritySparking add_to_spark_queue performs an insert sort to keep
958 the spark queue sorted. Otherwise the spark is just added to the end of
963 add_to_spark_queue(spark)
966 rtsSpark *prev = NULL, *next = NULL;
968 rtsBool found = rtsFalse;
970 if ( spark == (rtsSpark *)NULL ) {
974 if (RtsFlags.GranFlags.DoPrioritySparking && (spark->gran_info != 0) ) {
975 /* Priority sparking is enabled i.e. spark queues must be sorted */
977 for (prev = NULL, next = pending_sparks_hd, count=0;
979 !(found = (spark->gran_info >= next->gran_info));
980 prev = next, next = next->next, count++)
983 } else { /* 'utQo' */
984 /* Priority sparking is disabled */
986 found = rtsFalse; /* to add it at the end */
991 /* next points to the first spark with a gran_info smaller than that
992 of spark; therefore, add spark before next into the spark queue */
994 if ( next == NULL ) {
995 pending_sparks_tl = spark;
1000 if ( prev == NULL ) {
1001 pending_sparks_hd = spark;
1005 } else { /* (RtsFlags.GranFlags.DoPrioritySparking && !found) || !DoPrioritySparking */
1006 /* add the spark at the end of the spark queue */
1008 spark->prev = pending_sparks_tl;
1009 if (pending_sparks_hd == NULL)
1010 pending_sparks_hd = spark;
1012 pending_sparks_tl->next = spark;
1013 pending_sparks_tl = spark;
1017 /* add costs for search in priority sparking */
1018 if (RtsFlags.GranFlags.DoPrioritySparking) {
1019 CurrentTime[CurrentProc] += count * RtsFlags.GranFlags.Costs.pri_spark_overhead;
1022 IF_GRAN_DEBUG(checkSparkQ,
1023 debugBelch("++ Spark stats after adding spark %p (node %p) to queue on PE %d",
1024 spark, spark->node, CurrentProc);
1025 print_sparkq_stats());
1027 # if defined(GRAN_CHECK)
1028 if (RtsFlags.GranFlags.Debug.checkSparkQ) {
1029 for (prev = NULL, next = pending_sparks_hd;
1031 prev = next, next = next->next)
1033 if ( (prev!=NULL) && (prev!=pending_sparks_tl) )
1034 debugBelch("SparkQ inconsistency after adding spark %p: (PE %u) pending_sparks_tl (%p) not end of queue (%p)\n",
1036 pending_sparks_tl, prev);
1040 # if defined(GRAN_CHECK)
1041 /* Check if the sparkq is still sorted. Just for testing, really! */
1042 if ( RtsFlags.GranFlags.Debug.checkSparkQ &&
1043 RtsFlags.GranFlags.Debug.pri ) {
1044 rtsBool sorted = rtsTrue;
1045 rtsSpark *prev, *next;
1047 if (pending_sparks_hd == NULL ||
1048 pending_sparks_hd->next == NULL ) {
1049 /* just 1 elem => ok */
1051 for (prev = pending_sparks_hd,
1052 next = pending_sparks_hd->next;
1054 prev = next, next = next->next) {
1056 (prev->gran_info >= next->gran_info);
1060 debugBelch("ghuH: SPARKQ on PE %d is not sorted:\n",
1062 print_sparkq(CurrentProc);
1069 spark_queue_len(proc)
1072 rtsSpark *prev, *spark; /* prev only for testing !! */
1075 for (len = 0, prev = NULL, spark = pending_sparks_hds[proc];
1077 len++, prev = spark, spark = spark->next)
1080 # if defined(GRAN_CHECK)
1081 if ( RtsFlags.GranFlags.Debug.checkSparkQ )
1082 if ( (prev!=NULL) && (prev!=pending_sparks_tls[proc]) )
1083 debugBelch("ERROR in spark_queue_len: (PE %u) pending_sparks_tl (%p) not end of queue (%p)\n",
1084 proc, pending_sparks_tls[proc], prev);
1091 Take spark out of the spark queue on PE p and nuke the spark. Adjusts
1092 hd and tl pointers of the spark queue. Returns a pointer to the next
1096 delete_from_sparkq (spark, p, dispose_too) /* unlink and dispose spark */
1099 rtsBool dispose_too;
1101 rtsSpark *new_spark;
1104 barf("delete_from_sparkq: trying to delete NULL spark\n");
1106 # if defined(GRAN_CHECK)
1107 if ( RtsFlags.GranFlags.Debug.checkSparkQ ) {
1108 debugBelch("## |%p:%p| (%p)<-spark=%p->(%p) <-(%p)\n",
1109 pending_sparks_hd, pending_sparks_tl,
1110 spark->prev, spark, spark->next,
1111 (spark->next==NULL ? 0 : spark->next->prev));
1115 if (spark->prev==NULL) {
1116 /* spark is first spark of queue => adjust hd pointer */
1117 ASSERT(pending_sparks_hds[p]==spark);
1118 pending_sparks_hds[p] = spark->next;
1120 spark->prev->next = spark->next;
1122 if (spark->next==NULL) {
1123 ASSERT(pending_sparks_tls[p]==spark);
1124 /* spark is first spark of queue => adjust tl pointer */
1125 pending_sparks_tls[p] = spark->prev;
1127 spark->next->prev = spark->prev;
1129 new_spark = spark->next;
1131 # if defined(GRAN_CHECK)
1132 if ( RtsFlags.GranFlags.Debug.checkSparkQ ) {
1133 debugBelch("## |%p:%p| (%p)<-spark=%p->(%p) <-(%p); spark=%p will be deleted NOW \n",
1134 pending_sparks_hd, pending_sparks_tl,
1135 spark->prev, spark, spark->next,
1136 (spark->next==NULL ? 0 : spark->next->prev), spark);
1141 disposeSpark(spark);
1146 /* Mark all nodes pointed to by sparks in the spark queues (for GC) */
1148 markSparkQueue(void)
1150 StgClosure *MarkRoot(StgClosure *root); // prototype
1154 for (p=0; p<RtsFlags.GranFlags.proc; p++)
1155 for (sp=pending_sparks_hds[p]; sp!=NULL; sp=sp->next) {
1156 ASSERT(sp->node!=NULL);
1157 ASSERT(LOOKS_LIKE_GHC_INFO(sp->node->header.info));
1158 // ToDo?: statistics gathering here (also for GUM!)
1159 sp->node = (StgClosure *)MarkRoot(sp->node);
1163 debugBelch("markSparkQueue: spark statistics at start of GC:");
1164 print_sparkq_stats());
1174 debugBelch("Spark: NIL\n");
1178 ((spark->node==NULL) ? "______" : "%#6lx"),
1179 stgCast(StgPtr,spark->node));
1181 debugBelch("Spark: Node %8s, Name %#6x, Global %5s, Creator %5x, Prev %6p, Next %6p\n",
1183 ((spark->global)==rtsTrue?"True":"False"), spark->creator,
1184 spark->prev, spark->next);
1193 rtsSpark *x = pending_sparks_hds[proc];
1195 debugBelch("Spark Queue of PE %d with root at %p:\n", proc, x);
1196 for (; x!=(rtsSpark*)NULL; x=x->next) {
1202 Print a statistics of all spark queues.
1205 print_sparkq_stats(void)
1209 debugBelch("SparkQs: [");
1210 for (p=0; p<RtsFlags.GranFlags.proc; p++)
1211 debugBelch(", PE %d: %d", p, spark_queue_len(p));