Refactoring and reorganisation of the scheduler
[ghc-hetmet.git] / rts / Sparks.c
1 /* ---------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 2000-2008
4  *
5  * Sparking support for PARALLEL_HASKELL and THREADED_RTS versions of the RTS.
6  *
7  * The implementation uses Double-Ended Queues with lock-free access
8  * (thereby often called "deque") as described in
9  *
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
13  *
14  * Author: Jost Berthold MSRC 07-09/2008
15  *
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.
21  * 
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
27  * just one element).
28  * 
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
32  * failure.
33  * 
34  * Both popBottom and steal also return NULL when the queue is empty.
35  * 
36  -------------------------------------------------------------------------*/
37
38 #include "PosixSource.h"
39 #include "Rts.h"
40 #include "Storage.h"
41 #include "Schedule.h"
42 #include "SchedAPI.h"
43 #include "RtsFlags.h"
44 #include "RtsUtils.h"
45 #include "ParTicky.h"
46 #include "Trace.h"
47
48 #include "SMP.h" // for cas
49
50 #include "Sparks.h"
51
52 #if defined(THREADED_RTS) || defined(PARALLEL_HASKELL)
53
54 /* internal helpers ... */
55
56 static StgWord
57 roundUp2(StgWord val)
58 {
59   StgWord rounded = 1;
60
61   /* StgWord is unsigned anyway, only catch 0 */
62   if (val == 0) {
63     barf("DeQue,roundUp2: invalid size 0 requested");
64   }
65   /* at least 1 bit set, shift up to its place */
66   do {
67     rounded = rounded << 1;
68   } while (0 != (val = val>>1));
69   return rounded;
70 }
71
72 #define CASTOP(addr,old,new) ((old) == cas(((StgPtr)addr),(old),(new)))
73
74 /* -----------------------------------------------------------------------------
75  * 
76  * Initialising spark pools.
77  *
78  * -------------------------------------------------------------------------- */
79
80 /* constructor */
81 static SparkPool*
82 initPool(StgWord size)
83 {
84   StgWord realsize; 
85   SparkPool *q;
86
87   realsize = roundUp2(size); /* to compute modulo as a bitwise & */
88
89   q = (SparkPool*) stgMallocBytes(sizeof(SparkPool),   /* admin fields */
90                               "newSparkPool");
91   q->elements = (StgClosurePtr*) 
92                 stgMallocBytes(realsize * sizeof(StgClosurePtr), /* dataspace */
93                                "newSparkPool:data space");
94   q->top=0;
95   q->bottom=0;
96   q->topBound=0; /* read by writer, updated each time top is read */
97
98   q->size = realsize;  /* power of 2 */
99   q->moduloSize = realsize - 1; /* n % size == n & moduloSize  */
100
101   ASSERT_SPARK_POOL_INVARIANTS(q); 
102   return q;
103 }
104
105 void
106 initSparkPools( void )
107 {
108 #ifdef THREADED_RTS
109     /* walk over the capabilities, allocating a spark pool for each one */
110     nat i;
111     for (i = 0; i < n_capabilities; i++) {
112       capabilities[i].sparks = initPool(RtsFlags.ParFlags.maxLocalSparks);
113     }
114 #else
115     /* allocate a single spark pool */
116     MainCapability->sparks = initPool(RtsFlags.ParFlags.maxLocalSparks);
117 #endif
118 }
119
120 void
121 freeSparkPool (SparkPool *pool)
122 {
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);
126   stgFree(pool);
127 }
128
129 /* -----------------------------------------------------------------------------
130  * 
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
133  * empty.
134  *
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?
139  *
140  * -------------------------------------------------------------------------- */
141
142 StgClosure *
143 reclaimSpark (SparkPool *deque)
144 {
145   /* also a bit tricky, has to avoid concurrent steal() calls by
146      accessing top with cas, when there is only one element left */
147   StgWord t, b;
148   StgClosurePtr* pos;
149   long  currSize;
150   StgClosurePtr removed;
151
152   ASSERT_SPARK_POOL_INVARIANTS(deque); 
153
154   b = deque->bottom;
155   /* "decrement b as a test, see what happens" */
156   deque->bottom = --b; 
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 */
161   deque->topBound = t;
162   currSize = b - t;
163   if (currSize < 0) { /* was empty before decrementing b, set b
164                          consistently and abort */
165     deque->bottom = t;
166     return NULL;
167   }
168   removed = *pos;
169   if (currSize > 0) { /* no danger, still elements in buffer after b-- */
170     return removed;
171   } 
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 */
176   }
177   deque->bottom = t+1; /* anyway, empty now. Adjust bottom consistently. */
178   deque->topBound = t+1; /* ...and cached top value as well */
179
180   ASSERT_SPARK_POOL_INVARIANTS(deque); 
181
182   return removed;
183 }
184
185 /* -----------------------------------------------------------------------------
186  * 
187  * tryStealSpark: try to steal a spark from a Capability.
188  *
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.
192  *
193  -------------------------------------------------------------------------- */
194
195 static StgClosurePtr
196 steal(SparkPool *deque)
197 {
198   StgClosurePtr* pos;
199   StgClosurePtr* arraybase;
200   StgWord sz;
201   StgClosurePtr stolen;
202   StgWord b,t; 
203
204   ASSERT_SPARK_POOL_INVARIANTS(deque); 
205
206   b = deque->bottom;
207   t = deque->top;
208   if (b - t <= 0 ) { 
209     return NULL; /* already looks empty, abort */
210   }
211
212   /* now access array, see pushBottom() */
213   arraybase = deque->elements;
214   sz = deque->moduloSize;
215   pos = arraybase + (t & sz);  
216   stolen = *pos;
217
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 */
221       return NULL;
222   }  /* else: OK, top has been incremented by the cas call */
223
224   ASSERT_SPARK_POOL_INVARIANTS(deque); 
225   /* return stolen element */
226   return stolen;
227 }
228
229 StgClosure *
230 tryStealSpark (SparkPool *pool)
231 {
232   StgClosure *stolen;
233
234   do { 
235       stolen = steal(pool);
236   } while (stolen != NULL && !closure_SHOULD_SPARK(stolen));
237
238   return stolen;
239 }
240
241
242 /* -----------------------------------------------------------------------------
243  * 
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().
247  *
248  * -------------------------------------------------------------------------- */
249
250 rtsBool
251 looksEmpty(SparkPool* deque)
252 {
253   StgWord t = deque->top;
254   StgWord b = deque->bottom;
255   /* try to prefer false negatives by reading top first */
256   return (b - t <= 0);
257   /* => array is *never* completely filled, always 1 place free! */
258 }
259
260 /* -----------------------------------------------------------------------------
261  * 
262  * Turn a spark into a real thread
263  *
264  * -------------------------------------------------------------------------- */
265
266 void
267 createSparkThread (Capability *cap, StgClosure *p)
268 {
269     StgTSO *tso;
270
271     tso = createGenThread (cap, RtsFlags.GcFlags.initialStkSize, p);
272     appendToRunQueue(cap,tso);
273     cap->sparks_converted++;
274 }
275
276 /* -----------------------------------------------------------------------------
277  * 
278  * Create a new spark
279  *
280  * -------------------------------------------------------------------------- */
281
282 #define DISCARD_NEW
283
284 /* enqueue an element. Should always succeed by resizing the array
285    (not implemented yet, silently fails in that case). */
286 static void
287 pushBottom (SparkPool* deque, StgClosurePtr elem)
288 {
289   StgWord t;
290   StgClosurePtr* pos;
291   StgWord sz = deque->moduloSize; 
292   StgWord b = deque->bottom;
293
294   ASSERT_SPARK_POOL_INVARIANTS(deque); 
295
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.
299   */
300   t = deque->topBound;
301   if ( b - t >= sz ) { /* nota bene: sz == deque->size - 1, thus ">=" */
302     /* could be full, check the real top value in this case */
303     t = deque->top;
304     deque->topBound = t;
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...
310
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().
314       */
315 #if defined(DISCARD_NEW)
316       ASSERT_SPARK_POOL_INVARIANTS(deque); 
317       return; /* for now, silently fail */
318 #else
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.
322        */
323       ASSERT_SPARK_POOL_INVARIANTS(deque); 
324 #endif
325     }
326   }
327   pos = (deque->elements) + (b & sz);
328   *pos = elem;
329   (deque->bottom)++;
330
331   ASSERT_SPARK_POOL_INVARIANTS(deque); 
332   return;
333 }
334
335
336 /* --------------------------------------------------------------------------
337  * newSpark: create a new spark, as a result of calling "par"
338  * Called directly from STG.
339  * -------------------------------------------------------------------------- */
340
341 StgInt
342 newSpark (StgRegTable *reg, StgClosure *p)
343 {
344     Capability *cap = regTableToCapability(reg);
345     SparkPool *pool = cap->sparks;
346
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?
350      */
351     p = UNTAG_CLOSURE(p);
352
353     ASSERT_SPARK_POOL_INVARIANTS(pool);
354
355     if (closure_SHOULD_SPARK(p)) {
356       pushBottom(pool,p);
357     }   
358
359     cap->sparks_created++;
360
361     ASSERT_SPARK_POOL_INVARIANTS(pool);
362     return 1;
363 }
364
365
366
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  * -------------------------------------------------------------------------- */
373
374 static void
375 pruneSparkQueue (Capability *cap)
376
377     SparkPool *pool;
378     StgClosurePtr spark, *elements;
379     nat n, pruned_sparks; // stats only
380     StgWord botInd,oldBotInd,currInd; // indices in array (always < size)
381     
382     PAR_TICKY_MARK_SPARK_QUEUE_START();
383     
384     n = 0;
385     pruned_sparks = 0;
386     
387     pool = cap->sparks;
388     
389     debugTrace(DEBUG_sched,
390                "markSparkQueue: current spark queue len=%d; (hd=%ld; tl=%ld)",
391                sparkPoolSize(pool), pool->bottom, pool->top);
392     ASSERT_SPARK_POOL_INVARIANTS(pool);
393
394     elements = pool->elements;
395
396     /* We have exclusive access to the structure here, so we can reset
397        bottom and top counters, and prune invalid sparks. Contents are
398        copied in-place if they are valuable, otherwise discarded. The
399        routine uses "real" indices t and b, starts by computing them
400        as the modulus size of top and bottom,
401
402        Copying:
403
404        At the beginning, the pool structure can look like this:
405        ( bottom % size >= top % size , no wrap-around)
406                   t          b
407        ___________***********_________________
408
409        or like this ( bottom % size < top % size, wrap-around )
410                   b         t
411        ***********__________******************
412        As we need to remove useless sparks anyway, we make one pass
413        between t and b, moving valuable content to b and subsequent
414        cells (wrapping around when the size is reached).
415
416                      b      t
417        ***********OOO_______XX_X__X?**********
418                      ^____move?____/
419
420        After this movement, botInd becomes the new bottom, and old
421        bottom becomes the new top index, both as indices in the array
422        size range.
423     */
424     // starting here
425     currInd = (pool->top) & (pool->moduloSize); // mod
426
427     // copies of evacuated closures go to space from botInd on
428     // we keep oldBotInd to know when to stop
429     oldBotInd = botInd = (pool->bottom) & (pool->moduloSize); // mod
430
431     // on entry to loop, we are within the bounds
432     ASSERT( currInd < pool->size && botInd  < pool->size );
433
434     while (currInd != oldBotInd ) {
435       /* must use != here, wrap-around at size
436          subtle: loop not entered if queue empty
437        */
438
439       /* check element at currInd. if valuable, evacuate and move to
440          botInd, otherwise move on */
441       spark = elements[currInd];
442
443       /* if valuable work: shift inside the pool */
444       if ( closure_SHOULD_SPARK(spark) ) {
445         elements[botInd] = spark; // keep entry (new address)
446         botInd++;
447         n++;
448       } else { 
449         pruned_sparks++; // discard spark
450         cap->sparks_pruned++;
451       }
452       currInd++;
453
454       // in the loop, we may reach the bounds, and instantly wrap around
455       ASSERT( currInd <= pool->size && botInd <= pool->size );
456       if ( currInd == pool->size ) { currInd = 0; }
457       if ( botInd == pool->size )  { botInd = 0;  }
458
459     } // while-loop over spark pool elements
460
461     ASSERT(currInd == oldBotInd);
462
463     pool->top = oldBotInd; // where we started writing
464     pool->topBound = pool->top;
465
466     pool->bottom = (oldBotInd <= botInd) ? botInd : (botInd + pool->size); 
467     // first free place we did not use (corrected by wraparound)
468
469     PAR_TICKY_MARK_SPARK_QUEUE_END(n);
470
471     debugTrace(DEBUG_sched, "pruned %d sparks", pruned_sparks);
472     
473     debugTrace(DEBUG_sched,
474                "new spark queue len=%d; (hd=%ld; tl=%ld)",
475                sparkPoolSize(pool), pool->bottom, pool->top);
476
477     ASSERT_SPARK_POOL_INVARIANTS(pool);
478 }
479
480 void
481 pruneSparkQueues (void)
482 {
483     nat i;
484     for (i = 0; i < n_capabilities; i++) {
485         pruneSparkQueue(&capabilities[i]);
486     }
487 }
488
489 /* GC for the spark pool, called inside Capability.c for all
490    capabilities in turn. Blindly "evac"s complete spark pool. */
491 void
492 traverseSparkQueue (evac_fn evac, void *user, Capability *cap)
493 {
494     StgClosure **sparkp;
495     SparkPool *pool;
496     StgWord top,bottom, modMask;
497     
498     pool = cap->sparks;
499
500     ASSERT_SPARK_POOL_INVARIANTS(pool);
501
502     top = pool->top;
503     bottom = pool->bottom;
504     sparkp = pool->elements;
505     modMask = pool->moduloSize;
506
507     while (top < bottom) {
508     /* call evac for all closures in range (wrap-around via modulo)
509      * In GHC-6.10, evac takes an additional 1st argument to hold a
510      * GC-specific register, see rts/sm/GC.c::mark_root()
511      */
512       evac( user , sparkp + (top & modMask) ); 
513       top++;
514     }
515
516     debugTrace(DEBUG_sched,
517                "traversed spark queue, len=%d; (hd=%ld; tl=%ld)",
518                sparkPoolSize(pool), pool->bottom, pool->top);
519 }
520
521 /* ----------------------------------------------------------------------------
522  * balanceSparkPoolsCaps: takes an array of capabilities (usually: all
523  * capabilities) and its size. Accesses all spark pools and equally
524  * distributes the sparks among them.
525  *
526  * Could be called after GC, before Cap. release, from scheduler. 
527  * -------------------------------------------------------------------------- */
528 void balanceSparkPoolsCaps(nat n_caps, Capability caps[]);
529
530 void balanceSparkPoolsCaps(nat n_caps STG_UNUSED, 
531                            Capability caps[] STG_UNUSED) {
532   barf("not implemented");
533 }
534
535 #else
536
537 StgInt
538 newSpark (StgRegTable *reg STG_UNUSED, StgClosure *p STG_UNUSED)
539 {
540     /* nothing */
541     return 1;
542 }
543
544
545 #endif /* PARALLEL_HASKELL || THREADED_RTS */
546
547
548 /* -----------------------------------------------------------------------------
549  * 
550  * GRAN & PARALLEL_HASKELL stuff beyond here.
551  *
552  *  TODO "nuke" this!
553  *
554  * -------------------------------------------------------------------------- */
555
556 #if defined(PARALLEL_HASKELL) || defined(GRAN)
557
558 static void slide_spark_pool( StgSparkPool *pool );
559
560 rtsBool
561 add_to_spark_queue( StgClosure *closure, StgSparkPool *pool )
562 {
563   if (pool->tl == pool->lim)
564     slide_spark_pool(pool);
565
566   if (closure_SHOULD_SPARK(closure) && 
567       pool->tl < pool->lim) {
568     *(pool->tl++) = closure;
569
570 #if defined(PARALLEL_HASKELL)
571     // collect parallel global statistics (currently done together with GC stats)
572     if (RtsFlags.ParFlags.ParStats.Global &&
573         RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
574       // debugBelch("Creating spark for %x @ %11.2f\n", closure, usertime()); 
575       globalParStats.tot_sparks_created++;
576     }
577 #endif
578     return rtsTrue;
579   } else {
580 #if defined(PARALLEL_HASKELL)
581     // collect parallel global statistics (currently done together with GC stats)
582     if (RtsFlags.ParFlags.ParStats.Global &&
583         RtsFlags.GcFlags.giveStats > NO_GC_STATS) {
584       //debugBelch("Ignoring spark for %x @ %11.2f\n", closure, usertime()); 
585       globalParStats.tot_sparks_ignored++;
586     }
587 #endif
588     return rtsFalse;
589   }
590 }
591
592 static void
593 slide_spark_pool( StgSparkPool *pool )
594 {
595   StgClosure **sparkp, **to_sparkp;
596
597   sparkp = pool->hd;
598   to_sparkp = pool->base;
599   while (sparkp < pool->tl) {
600     ASSERT(to_sparkp<=sparkp);
601     ASSERT(*sparkp!=NULL);
602     ASSERT(LOOKS_LIKE_GHC_INFO((*sparkp)->header.info));
603
604     if (closure_SHOULD_SPARK(*sparkp)) {
605       *to_sparkp++ = *sparkp++;
606     } else {
607       sparkp++;
608     }
609   }
610   pool->hd = pool->base;
611   pool->tl = to_sparkp;
612 }
613
614 void
615 disposeSpark(spark)
616 StgClosure *spark;
617 {
618 #if !defined(THREADED_RTS)
619   Capability *cap;
620   StgSparkPool *pool;
621
622   cap = &MainRegTable;
623   pool = &(cap->rSparks);
624   ASSERT(pool->hd <= pool->tl && pool->tl <= pool->lim);
625 #endif
626   ASSERT(spark != (StgClosure *)NULL);
627   /* Do nothing */
628 }
629
630
631 #elif defined(GRAN)
632
633 /* 
634    Search the spark queue of the proc in event for a spark that's worth
635    turning into a thread 
636    (was gimme_spark in the old RTS)
637 */
638 void
639 findLocalSpark (rtsEvent *event, rtsBool *found_res, rtsSparkQ *spark_res)
640 {
641    PEs proc = event->proc,       /* proc to search for work */
642        creator = event->creator; /* proc that requested work */
643    StgClosure* node;
644    rtsBool found;
645    rtsSparkQ spark_of_non_local_node = NULL, 
646              spark_of_non_local_node_prev = NULL, 
647              low_priority_spark = NULL, 
648              low_priority_spark_prev = NULL,
649              spark = NULL, prev = NULL;
650   
651    /* Choose a spark from the local spark queue */
652    prev = (rtsSpark*)NULL;
653    spark = pending_sparks_hds[proc];
654    found = rtsFalse;
655
656    // ToDo: check this code & implement local sparking !! -- HWL  
657    while (!found && spark != (rtsSpark*)NULL)
658      {
659        ASSERT((prev!=(rtsSpark*)NULL || spark==pending_sparks_hds[proc]) &&
660               (prev==(rtsSpark*)NULL || prev->next==spark) &&
661               (spark->prev==prev));
662        node = spark->node;
663        if (!closure_SHOULD_SPARK(node)) 
664          {
665            IF_GRAN_DEBUG(checkSparkQ,
666                          debugBelch("^^ pruning spark %p (node %p) in gimme_spark",
667                                spark, node));
668
669            if (RtsFlags.GranFlags.GranSimStats.Sparks)
670              DumpRawGranEvent(proc, (PEs)0, SP_PRUNED,(StgTSO*)NULL,
671                               spark->node, spark->name, spark_queue_len(proc));
672   
673            ASSERT(spark != (rtsSpark*)NULL);
674            ASSERT(SparksAvail>0);
675            --SparksAvail;
676
677            ASSERT(prev==(rtsSpark*)NULL || prev->next==spark);
678            spark = delete_from_sparkq (spark, proc, rtsTrue);
679            if (spark != (rtsSpark*)NULL)
680              prev = spark->prev;
681            continue;
682          }
683        /* -- node should eventually be sparked */
684        else if (RtsFlags.GranFlags.PreferSparksOfLocalNodes && 
685                !IS_LOCAL_TO(PROCS(node),CurrentProc)) 
686          {
687            barf("Local sparking not yet implemented");
688
689            /* Remember first low priority spark */
690            if (spark_of_non_local_node==(rtsSpark*)NULL) {
691              spark_of_non_local_node_prev = prev;
692              spark_of_non_local_node = spark;
693               }
694   
695            if (spark->next == (rtsSpark*)NULL) { 
696              /* ASSERT(spark==SparkQueueTl);  just for testing */
697              prev = spark_of_non_local_node_prev;
698              spark = spark_of_non_local_node;
699              found = rtsTrue;
700              break;
701            }
702   
703 # if defined(GRAN) && defined(GRAN_CHECK)
704            /* Should never happen; just for testing 
705            if (spark==pending_sparks_tl) {
706              debugBelch("ReSchedule: Last spark != SparkQueueTl\n");
707                 stg_exit(EXIT_FAILURE);
708                 } */
709 # endif
710            prev = spark; 
711            spark = spark->next;
712            ASSERT(SparksAvail>0);
713            --SparksAvail;
714            continue;
715          }
716        else if ( RtsFlags.GranFlags.DoPrioritySparking || 
717                  (spark->gran_info >= RtsFlags.GranFlags.SparkPriority2) )
718          {
719            if (RtsFlags.GranFlags.DoPrioritySparking)
720              barf("Priority sparking not yet implemented");
721
722            found = rtsTrue;
723          }
724 #if 0      
725        else /* only used if SparkPriority2 is defined */
726          {
727            /* ToDo: fix the code below and re-integrate it */
728            /* Remember first low priority spark */
729            if (low_priority_spark==(rtsSpark*)NULL) { 
730              low_priority_spark_prev = prev;
731              low_priority_spark = spark;
732            }
733   
734            if (spark->next == (rtsSpark*)NULL) { 
735                 /* ASSERT(spark==spark_queue_tl);  just for testing */
736              prev = low_priority_spark_prev;
737              spark = low_priority_spark;
738              found = rtsTrue;       /* take low pri spark => rc is 2  */
739              break;
740            }
741   
742            /* Should never happen; just for testing 
743            if (spark==pending_sparks_tl) {
744              debugBelch("ReSchedule: Last spark != SparkQueueTl\n");
745                 stg_exit(EXIT_FAILURE);
746              break;
747            } */                
748            prev = spark; 
749            spark = spark->next;
750
751            IF_GRAN_DEBUG(pri,
752                          debugBelch("++ Ignoring spark of priority %u (SparkPriority=%u); node=%p; name=%u\n", 
753                                spark->gran_info, RtsFlags.GranFlags.SparkPriority, 
754                                spark->node, spark->name);)
755            }
756 #endif
757    }  /* while (spark!=NULL && !found) */
758
759    *spark_res = spark;
760    *found_res = found;
761 }
762
763 /*
764   Turn the spark into a thread.
765   In GranSim this basically means scheduling a StartThread event for the
766   node pointed to by the spark at some point in the future.
767   (was munch_spark in the old RTS)
768 */
769 rtsBool
770 activateSpark (rtsEvent *event, rtsSparkQ spark) 
771 {
772   PEs proc = event->proc,       /* proc to search for work */
773       creator = event->creator; /* proc that requested work */
774   StgTSO* tso;
775   StgClosure* node;
776   rtsTime spark_arrival_time;
777
778   /* 
779      We've found a node on PE proc requested by PE creator.
780      If proc==creator we can turn the spark into a thread immediately;
781      otherwise we schedule a MoveSpark event on the requesting PE
782   */
783      
784   /* DaH Qu' yIchen */
785   if (proc!=creator) { 
786
787     /* only possible if we simulate GUM style fishing */
788     ASSERT(RtsFlags.GranFlags.Fishing);
789
790     /* Message packing costs for sending a Fish; qeq jabbI'ID */
791     CurrentTime[proc] += RtsFlags.GranFlags.Costs.mpacktime;
792   
793     if (RtsFlags.GranFlags.GranSimStats.Sparks)
794       DumpRawGranEvent(proc, (PEs)0, SP_EXPORTED,
795                        (StgTSO*)NULL, spark->node,
796                        spark->name, spark_queue_len(proc));
797
798     /* time of the spark arrival on the remote PE */
799     spark_arrival_time = CurrentTime[proc] + RtsFlags.GranFlags.Costs.latency;
800
801     new_event(creator, proc, spark_arrival_time,
802               MoveSpark,
803               (StgTSO*)NULL, spark->node, spark);
804
805     CurrentTime[proc] += RtsFlags.GranFlags.Costs.mtidytime;
806             
807   } else { /* proc==creator i.e. turn the spark into a thread */
808
809     if ( RtsFlags.GranFlags.GranSimStats.Global && 
810          spark->gran_info < RtsFlags.GranFlags.SparkPriority2 ) {
811
812       globalGranStats.tot_low_pri_sparks++;
813       IF_GRAN_DEBUG(pri,
814                     debugBelch("++ No high priority spark available; low priority (%u) spark chosen: node=%p; name=%u\n",
815                           spark->gran_info, 
816                           spark->node, spark->name));
817     } 
818     
819     CurrentTime[proc] += RtsFlags.GranFlags.Costs.threadcreatetime;
820     
821     node = spark->node;
822     
823 # if 0
824     /* ToDo: fix the GC interface and move to StartThread handling-- HWL */
825     if (GARBAGE COLLECTION IS NECESSARY) {
826       /* Some kind of backoff needed here in case there's too little heap */
827 #  if defined(GRAN_CHECK) && defined(GRAN)
828       if (RtsFlags.GcFlags.giveStats)
829         fprintf(RtsFlags.GcFlags.statsFile,"***** vIS Qu' chen veQ boSwI'; spark=%p, node=%p;  name=%u\n", 
830                 /* (found==2 ? "no hi pri spark" : "hi pri spark"), */
831                 spark, node, spark->name);
832 #  endif
833       new_event(CurrentProc, CurrentProc, CurrentTime[CurrentProc]+1,
834                   FindWork,
835                   (StgTSO*)NULL, (StgClosure*)NULL, (rtsSpark*)NULL);
836       barf("//// activateSpark: out of heap ; ToDo: call GarbageCollect()");
837       GarbageCollect(GetRoots, rtsFalse);
838       // HWL old: ReallyPerformThreadGC(TSO_HS+TSO_CTS_SIZE,rtsFalse);
839       // HWL old: SAVE_Hp -= TSO_HS+TSO_CTS_SIZE;
840       spark = NULL;
841       return; /* was: continue; */ /* to the next event, eventually */
842     }
843 # endif
844     
845     if (RtsFlags.GranFlags.GranSimStats.Sparks)
846       DumpRawGranEvent(CurrentProc,(PEs)0,SP_USED,(StgTSO*)NULL,
847                        spark->node, spark->name,
848                        spark_queue_len(CurrentProc));
849     
850     new_event(proc, proc, CurrentTime[proc],
851               StartThread, 
852               END_TSO_QUEUE, node, spark); // (rtsSpark*)NULL);
853     
854     procStatus[proc] = Starting;
855   }
856 }
857
858 /* -------------------------------------------------------------------------
859    This is the main point where handling granularity information comes into
860    play. 
861    ------------------------------------------------------------------------- */
862
863 #define MAX_RAND_PRI    100
864
865 /* 
866    Granularity info transformers. 
867    Applied to the GRAN_INFO field of a spark.
868 */
869 STATIC_INLINE nat  ID(nat x) { return(x); };
870 STATIC_INLINE nat  INV(nat x) { return(-x); };
871 STATIC_INLINE nat  IGNORE(nat x) { return (0); };
872 STATIC_INLINE nat  RAND(nat x) { return ((random() % MAX_RAND_PRI) + 1); }
873
874 /* NB: size_info and par_info are currently unused (what a shame!) -- HWL */
875 rtsSpark *
876 newSpark(node,name,gran_info,size_info,par_info,local)
877 StgClosure *node;
878 nat name, gran_info, size_info, par_info, local;
879 {
880   nat pri;
881   rtsSpark *newspark;
882
883   pri = RtsFlags.GranFlags.RandomPriorities ? RAND(gran_info) :
884         RtsFlags.GranFlags.InversePriorities ? INV(gran_info) :
885         RtsFlags.GranFlags.IgnorePriorities ? IGNORE(gran_info) :
886                            ID(gran_info);
887
888   if ( RtsFlags.GranFlags.SparkPriority!=0 && 
889        pri<RtsFlags.GranFlags.SparkPriority ) {
890     IF_GRAN_DEBUG(pri,
891       debugBelch(",, NewSpark: Ignoring spark of priority %u (SparkPriority=%u); node=%#x; name=%u\n", 
892               pri, RtsFlags.GranFlags.SparkPriority, node, name));
893     return ((rtsSpark*)NULL);
894   }
895
896   newspark = (rtsSpark*) stgMallocBytes(sizeof(rtsSpark), "NewSpark");
897   newspark->prev = newspark->next = (rtsSpark*)NULL;
898   newspark->node = node;
899   newspark->name = (name==1) ? CurrentTSO->gran.sparkname : name;
900   newspark->gran_info = pri;
901   newspark->global = !local;      /* Check that with parAt, parAtAbs !!*/
902
903   if (RtsFlags.GranFlags.GranSimStats.Global) {
904     globalGranStats.tot_sparks_created++;
905     globalGranStats.sparks_created_on_PE[CurrentProc]++;
906   }
907
908   return(newspark);
909 }
910
911 void
912 disposeSpark(spark)
913 rtsSpark *spark;
914 {
915   ASSERT(spark!=NULL);
916   stgFree(spark);
917 }
918
919 void 
920 disposeSparkQ(spark)
921 rtsSparkQ spark;
922 {
923   if (spark==NULL) 
924     return;
925
926   disposeSparkQ(spark->next);
927
928 # ifdef GRAN_CHECK
929   if (SparksAvail < 0) {
930     debugBelch("disposeSparkQ: SparksAvail<0 after disposing sparkq @ %p\n", &spark);
931     print_spark(spark);
932   }
933 # endif
934
935   stgFree(spark);
936 }
937
938 /*
939    With PrioritySparking add_to_spark_queue performs an insert sort to keep
940    the spark queue sorted. Otherwise the spark is just added to the end of
941    the queue. 
942 */
943
944 void
945 add_to_spark_queue(spark)
946 rtsSpark *spark;
947 {
948   rtsSpark *prev = NULL, *next = NULL;
949   nat count = 0;
950   rtsBool found = rtsFalse;
951
952   if ( spark == (rtsSpark *)NULL ) {
953     return;
954   }
955
956   if (RtsFlags.GranFlags.DoPrioritySparking && (spark->gran_info != 0) ) {
957     /* Priority sparking is enabled i.e. spark queues must be sorted */
958
959     for (prev = NULL, next = pending_sparks_hd, count=0;
960          (next != NULL) && 
961          !(found = (spark->gran_info >= next->gran_info));
962          prev = next, next = next->next, count++) 
963      {}
964
965   } else {   /* 'utQo' */
966     /* Priority sparking is disabled */
967     
968     found = rtsFalse;   /* to add it at the end */
969
970   }
971
972   if (found) {
973     /* next points to the first spark with a gran_info smaller than that
974        of spark; therefore, add spark before next into the spark queue */
975     spark->next = next;
976     if ( next == NULL ) {
977       pending_sparks_tl = spark;
978     } else {
979       next->prev = spark;
980     }
981     spark->prev = prev;
982     if ( prev == NULL ) {
983       pending_sparks_hd = spark;
984     } else {
985       prev->next = spark;
986     }
987   } else {  /* (RtsFlags.GranFlags.DoPrioritySparking && !found) || !DoPrioritySparking */
988     /* add the spark at the end of the spark queue */
989     spark->next = NULL;                        
990     spark->prev = pending_sparks_tl;
991     if (pending_sparks_hd == NULL)
992       pending_sparks_hd = spark;
993     else
994       pending_sparks_tl->next = spark;
995     pending_sparks_tl = spark;    
996   } 
997   ++SparksAvail;
998
999   /* add costs for search in priority sparking */
1000   if (RtsFlags.GranFlags.DoPrioritySparking) {
1001     CurrentTime[CurrentProc] += count * RtsFlags.GranFlags.Costs.pri_spark_overhead;
1002   }
1003
1004   IF_GRAN_DEBUG(checkSparkQ,
1005                 debugBelch("++ Spark stats after adding spark %p (node %p) to queue on PE %d",
1006                       spark, spark->node, CurrentProc);
1007                 print_sparkq_stats());
1008
1009 #  if defined(GRAN_CHECK)
1010   if (RtsFlags.GranFlags.Debug.checkSparkQ) {
1011     for (prev = NULL, next =  pending_sparks_hd;
1012          (next != NULL);
1013          prev = next, next = next->next) 
1014       {}
1015     if ( (prev!=NULL) && (prev!=pending_sparks_tl) )
1016       debugBelch("SparkQ inconsistency after adding spark %p: (PE %u) pending_sparks_tl (%p) not end of queue (%p)\n",
1017               spark,CurrentProc, 
1018               pending_sparks_tl, prev);
1019   }
1020 #  endif
1021
1022 #  if defined(GRAN_CHECK)
1023   /* Check if the sparkq is still sorted. Just for testing, really!  */
1024   if ( RtsFlags.GranFlags.Debug.checkSparkQ &&
1025        RtsFlags.GranFlags.Debug.pri ) {
1026     rtsBool sorted = rtsTrue;
1027     rtsSpark *prev, *next;
1028
1029     if (pending_sparks_hd == NULL ||
1030         pending_sparks_hd->next == NULL ) {
1031       /* just 1 elem => ok */
1032     } else {
1033       for (prev = pending_sparks_hd,
1034            next = pending_sparks_hd->next;
1035            (next != NULL) ;
1036            prev = next, next = next->next) {
1037         sorted = sorted && 
1038                  (prev->gran_info >= next->gran_info);
1039       }
1040     }
1041     if (!sorted) {
1042       debugBelch("ghuH: SPARKQ on PE %d is not sorted:\n",
1043               CurrentProc);
1044       print_sparkq(CurrentProc);
1045     }
1046   }
1047 #  endif
1048 }
1049
1050 nat
1051 spark_queue_len(proc) 
1052 PEs proc;
1053 {
1054  rtsSpark *prev, *spark;                     /* prev only for testing !! */
1055  nat len;
1056
1057  for (len = 0, prev = NULL, spark = pending_sparks_hds[proc]; 
1058       spark != NULL; 
1059       len++, prev = spark, spark = spark->next)
1060    {}
1061
1062 #  if defined(GRAN_CHECK)
1063   if ( RtsFlags.GranFlags.Debug.checkSparkQ ) 
1064     if ( (prev!=NULL) && (prev!=pending_sparks_tls[proc]) )
1065       debugBelch("ERROR in spark_queue_len: (PE %u) pending_sparks_tl (%p) not end of queue (%p)\n",
1066               proc, pending_sparks_tls[proc], prev);
1067 #  endif
1068
1069  return (len);
1070 }
1071
1072 /* 
1073    Take spark out of the spark queue on PE p and nuke the spark. Adjusts
1074    hd and tl pointers of the spark queue. Returns a pointer to the next
1075    spark in the queue.
1076 */
1077 rtsSpark *
1078 delete_from_sparkq (spark, p, dispose_too)     /* unlink and dispose spark */
1079 rtsSpark *spark;
1080 PEs p;
1081 rtsBool dispose_too;
1082 {
1083   rtsSpark *new_spark;
1084
1085   if (spark==NULL) 
1086     barf("delete_from_sparkq: trying to delete NULL spark\n");
1087
1088 #  if defined(GRAN_CHECK)
1089   if ( RtsFlags.GranFlags.Debug.checkSparkQ ) {
1090     debugBelch("## |%p:%p| (%p)<-spark=%p->(%p) <-(%p)\n",
1091             pending_sparks_hd, pending_sparks_tl,
1092             spark->prev, spark, spark->next, 
1093             (spark->next==NULL ? 0 : spark->next->prev));
1094   }
1095 #  endif
1096
1097   if (spark->prev==NULL) {
1098     /* spark is first spark of queue => adjust hd pointer */
1099     ASSERT(pending_sparks_hds[p]==spark);
1100     pending_sparks_hds[p] = spark->next;
1101   } else {
1102     spark->prev->next = spark->next;
1103   }
1104   if (spark->next==NULL) {
1105     ASSERT(pending_sparks_tls[p]==spark);
1106     /* spark is first spark of queue => adjust tl pointer */
1107     pending_sparks_tls[p] = spark->prev;
1108   } else {
1109     spark->next->prev = spark->prev;
1110   }
1111   new_spark = spark->next;
1112   
1113 #  if defined(GRAN_CHECK)
1114   if ( RtsFlags.GranFlags.Debug.checkSparkQ ) {
1115     debugBelch("## |%p:%p| (%p)<-spark=%p->(%p) <-(%p); spark=%p will be deleted NOW \n",
1116             pending_sparks_hd, pending_sparks_tl,
1117             spark->prev, spark, spark->next, 
1118             (spark->next==NULL ? 0 : spark->next->prev), spark);
1119   }
1120 #  endif
1121
1122   if (dispose_too)
1123     disposeSpark(spark);
1124                   
1125   return new_spark;
1126 }
1127
1128 /* Mark all nodes pointed to by sparks in the spark queues (for GC) */
1129 void
1130 markSparkQueue(void)
1131
1132   StgClosure *MarkRoot(StgClosure *root); // prototype
1133   PEs p;
1134   rtsSpark *sp;
1135
1136   for (p=0; p<RtsFlags.GranFlags.proc; p++)
1137     for (sp=pending_sparks_hds[p]; sp!=NULL; sp=sp->next) {
1138       ASSERT(sp->node!=NULL);
1139       ASSERT(LOOKS_LIKE_GHC_INFO(sp->node->header.info));
1140       // ToDo?: statistics gathering here (also for GUM!)
1141       sp->node = (StgClosure *)MarkRoot(sp->node);
1142     }
1143
1144   IF_DEBUG(gc,
1145            debugBelch("markSparkQueue: spark statistics at start of GC:");
1146            print_sparkq_stats());
1147 }
1148
1149 void
1150 print_spark(spark)
1151 rtsSpark *spark;
1152
1153   char str[16];
1154
1155   if (spark==NULL) {
1156     debugBelch("Spark: NIL\n");
1157     return;
1158   } else {
1159     sprintf(str,
1160             ((spark->node==NULL) ? "______" : "%#6lx"), 
1161             stgCast(StgPtr,spark->node));
1162
1163     debugBelch("Spark: Node %8s, Name %#6x, Global %5s, Creator %5x, Prev %6p, Next %6p\n",
1164             str, spark->name, 
1165             ((spark->global)==rtsTrue?"True":"False"), spark->creator, 
1166             spark->prev, spark->next);
1167   }
1168 }
1169
1170 void
1171 print_sparkq(proc)
1172 PEs proc;
1173 // rtsSpark *hd;
1174 {
1175   rtsSpark *x = pending_sparks_hds[proc];
1176
1177   debugBelch("Spark Queue of PE %d with root at %p:\n", proc, x);
1178   for (; x!=(rtsSpark*)NULL; x=x->next) {
1179     print_spark(x);
1180   }
1181 }
1182
1183 /* 
1184    Print a statistics of all spark queues.
1185 */
1186 void
1187 print_sparkq_stats(void)
1188 {
1189   PEs p;
1190
1191   debugBelch("SparkQs: [");
1192   for (p=0; p<RtsFlags.GranFlags.proc; p++)
1193     debugBelch(", PE %d: %d", p, spark_queue_len(p));
1194   debugBelch("\n");
1195 }
1196
1197 #endif