Fix #2637: conc032(threaded2) failure
[ghc-hetmet.git] / rts / sm / MarkWeak.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team 1998-2008
4  *
5  * Weak pointers and weak-like things in the GC
6  *
7  * Documentation on the architecture of the Garbage Collector can be
8  * found in the online commentary:
9  * 
10  *   http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage/GC
11  *
12  * ---------------------------------------------------------------------------*/
13
14 #include "Rts.h"
15 #include "Storage.h"
16 #include "MarkWeak.h"
17 #include "GC.h"
18 #include "GCThread.h"
19 #include "Evac.h"
20 #include "Trace.h"
21 #include "Schedule.h"
22
23 /* -----------------------------------------------------------------------------
24    Weak Pointers
25
26    traverse_weak_ptr_list is called possibly many times during garbage
27    collection.  It returns a flag indicating whether it did any work
28    (i.e. called evacuate on any live pointers).
29
30    Invariant: traverse_weak_ptr_list is called when the heap is in an
31    idempotent state.  That means that there are no pending
32    evacuate/scavenge operations.  This invariant helps the weak
33    pointer code decide which weak pointers are dead - if there are no
34    new live weak pointers, then all the currently unreachable ones are
35    dead.
36
37    For generational GC: we just don't try to finalize weak pointers in
38    older generations than the one we're collecting.  This could
39    probably be optimised by keeping per-generation lists of weak
40    pointers, but for a few weak pointers this scheme will work.
41
42    There are three distinct stages to processing weak pointers:
43
44    - weak_stage == WeakPtrs
45
46      We process all the weak pointers whos keys are alive (evacuate
47      their values and finalizers), and repeat until we can find no new
48      live keys.  If no live keys are found in this pass, then we
49      evacuate the finalizers of all the dead weak pointers in order to
50      run them.
51
52    - weak_stage == WeakThreads
53
54      Now, we discover which *threads* are still alive.  Pointers to
55      threads from the all_threads and main thread lists are the
56      weakest of all: a pointers from the finalizer of a dead weak
57      pointer can keep a thread alive.  Any threads found to be unreachable
58      are evacuated and placed on the resurrected_threads list so we 
59      can send them a signal later.
60
61    - weak_stage == WeakDone
62
63      No more evacuation is done.
64
65    -------------------------------------------------------------------------- */
66
67 /* Which stage of processing various kinds of weak pointer are we at?
68  * (see traverse_weak_ptr_list() below for discussion).
69  */
70 typedef enum { WeakPtrs, WeakThreads, WeakDone } WeakStage;
71 static WeakStage weak_stage;
72
73 /* Weak pointers
74  */
75 StgWeak *old_weak_ptr_list; // also pending finaliser list
76
77 // List of threads found to be unreachable
78 StgTSO *resurrected_threads;
79
80 // List of blocked threads found to have pending throwTos
81 StgTSO *exception_threads;
82
83 void
84 initWeakForGC(void)
85 {
86     old_weak_ptr_list = weak_ptr_list;
87     weak_ptr_list = NULL;
88     weak_stage = WeakPtrs;
89     resurrected_threads = END_TSO_QUEUE;
90     exception_threads = END_TSO_QUEUE;
91 }
92
93 rtsBool 
94 traverseWeakPtrList(void)
95 {
96   StgWeak *w, **last_w, *next_w;
97   StgClosure *new;
98   rtsBool flag = rtsFalse;
99   const StgInfoTable *info;
100
101   switch (weak_stage) {
102
103   case WeakDone:
104       return rtsFalse;
105
106   case WeakPtrs:
107       /* doesn't matter where we evacuate values/finalizers to, since
108        * these pointers are treated as roots (iff the keys are alive).
109        */
110       gct->evac_step = 0;
111       
112       last_w = &old_weak_ptr_list;
113       for (w = old_weak_ptr_list; w != NULL; w = next_w) {
114           
115           /* There might be a DEAD_WEAK on the list if finalizeWeak# was
116            * called on a live weak pointer object.  Just remove it.
117            */
118           if (w->header.info == &stg_DEAD_WEAK_info) {
119               next_w = ((StgDeadWeak *)w)->link;
120               *last_w = next_w;
121               continue;
122           }
123           
124           info = w->header.info;
125           if (IS_FORWARDING_PTR(info)) {
126               next_w = (StgWeak *)UN_FORWARDING_PTR(info);
127               *last_w = next_w;
128               continue;
129           }
130
131           switch (INFO_PTR_TO_STRUCT(info)->type) {
132
133           case WEAK:
134               /* Now, check whether the key is reachable.
135                */
136               new = isAlive(w->key);
137               if (new != NULL) {
138                   w->key = new;
139                   // evacuate the value and finalizer 
140                   evacuate(&w->value);
141                   evacuate(&w->finalizer);
142                   // remove this weak ptr from the old_weak_ptr list 
143                   *last_w = w->link;
144                   // and put it on the new weak ptr list 
145                   next_w  = w->link;
146                   w->link = weak_ptr_list;
147                   weak_ptr_list = w;
148                   flag = rtsTrue;
149
150                   debugTrace(DEBUG_weak, 
151                              "weak pointer still alive at %p -> %p",
152                              w, w->key);
153                   continue;
154               }
155               else {
156                   last_w = &(w->link);
157                   next_w = w->link;
158                   continue;
159               }
160
161           default:
162               barf("traverseWeakPtrList: not WEAK");
163           }
164       }
165       
166       /* If we didn't make any changes, then we can go round and kill all
167        * the dead weak pointers.  The old_weak_ptr list is used as a list
168        * of pending finalizers later on.
169        */
170       if (flag == rtsFalse) {
171           for (w = old_weak_ptr_list; w; w = w->link) {
172               evacuate(&w->finalizer);
173           }
174
175           // Next, move to the WeakThreads stage after fully
176           // scavenging the finalizers we've just evacuated.
177           weak_stage = WeakThreads;
178       }
179
180       return rtsTrue;
181
182   case WeakThreads:
183       /* Now deal with the all_threads list, which behaves somewhat like
184        * the weak ptr list.  If we discover any threads that are about to
185        * become garbage, we wake them up and administer an exception.
186        */
187      {
188           StgTSO *t, *tmp, *next, **prev;
189           nat g, s;
190           step *stp;
191           
192           // Traverse thread lists for generations we collected...
193           for (g = 0; g <= N; g++) {
194               for (s = 0; s < generations[g].n_steps; s++) {
195                   stp = &generations[g].steps[s];
196
197                   prev = &stp->old_threads;
198
199                   for (t = stp->old_threads; t != END_TSO_QUEUE; t = next) {
200               
201                       tmp = (StgTSO *)isAlive((StgClosure *)t);
202               
203                       if (tmp != NULL) {
204                           t = tmp;
205                       }
206
207                       ASSERT(get_itbl(t)->type == TSO);
208                       if (t->what_next == ThreadRelocated) {
209                           next = t->_link;
210                           *prev = next;
211                           continue;
212                       }
213
214                       next = t->global_link;
215
216                       // This is a good place to check for blocked
217                       // exceptions.  It might be the case that a thread is
218                       // blocked on delivering an exception to a thread that
219                       // is also blocked - we try to ensure that this
220                       // doesn't happen in throwTo(), but it's too hard (or
221                       // impossible) to close all the race holes, so we
222                       // accept that some might get through and deal with
223                       // them here.  A GC will always happen at some point,
224                       // even if the system is otherwise deadlocked.
225                       //
226                       // If an unreachable thread has blocked
227                       // exceptions, we really want to perform the
228                       // blocked exceptions rather than throwing
229                       // BlockedIndefinitely exceptions.  This is the
230                       // only place we can discover such threads.
231                       // The target thread might even be
232                       // ThreadFinished or ThreadKilled.  Bugs here
233                       // will only be seen when running on a
234                       // multiprocessor.
235                       if (t->blocked_exceptions != END_TSO_QUEUE) {
236                           if (tmp == NULL) {
237                               evacuate((StgClosure **)&t);
238                               flag = rtsTrue;
239                           }
240                           t->global_link = exception_threads;
241                           exception_threads = t;
242                           *prev = next;
243                           continue;
244                       }
245
246                       if (tmp == NULL) {
247                           // not alive (yet): leave this thread on the
248                           // old_all_threads list.
249                           prev = &(t->global_link);
250                       } 
251                       else {
252                           // alive
253                           *prev = next;
254
255                           // move this thread onto the correct threads list.
256                           step *new_step;
257                           new_step = Bdescr((P_)t)->step;
258                           t->global_link = new_step->threads;
259                           new_step->threads  = t;
260                       }
261                   }
262               }
263           }
264       }
265
266       /* If we evacuated any threads, we need to go back to the scavenger.
267        */
268       if (flag) return rtsTrue;
269
270       /* And resurrect any threads which were about to become garbage.
271        */
272       {
273           nat g, s;
274           step *stp;
275           StgTSO *t, *tmp, *next;
276
277           for (g = 0; g <= N; g++) {
278               for (s = 0; s < generations[g].n_steps; s++) {
279                   stp = &generations[g].steps[s];
280
281                   for (t = stp->old_threads; t != END_TSO_QUEUE; t = next) {
282                       next = t->global_link;
283
284                       // ThreadFinished and ThreadComplete: we have to keep
285                       // these on the all_threads list until they
286                       // become garbage, because they might get
287                       // pending exceptions.
288                       switch (t->what_next) {
289                       case ThreadKilled:
290                       case ThreadComplete:
291                           continue;
292                       default:
293                           tmp = t;
294                           evacuate((StgClosure **)&tmp);
295                           tmp->global_link = resurrected_threads;
296                           resurrected_threads = tmp;
297                       }
298                   }
299               }
300           }
301       }
302       
303       /* Finally, we can update the blackhole_queue.  This queue
304        * simply strings together TSOs blocked on black holes, it is
305        * not intended to keep anything alive.  Hence, we do not follow
306        * pointers on the blackhole_queue until now, when we have
307        * determined which TSOs are otherwise reachable.  We know at
308        * this point that all TSOs have been evacuated, however.
309        */
310       { 
311           StgTSO **pt;
312           for (pt = &blackhole_queue; *pt != END_TSO_QUEUE; pt = &((*pt)->_link)) {
313               *pt = (StgTSO *)isAlive((StgClosure *)*pt);
314               ASSERT(*pt != NULL);
315           }
316       }
317
318       weak_stage = WeakDone;  // *now* we're done,
319       return rtsTrue;         // but one more round of scavenging, please
320
321   default:
322       barf("traverse_weak_ptr_list");
323       return rtsTrue;
324   }
325
326 }
327
328 /* -----------------------------------------------------------------------------
329    The blackhole queue
330    
331    Threads on this list behave like weak pointers during the normal
332    phase of garbage collection: if the blackhole is reachable, then
333    the thread is reachable too.
334    -------------------------------------------------------------------------- */
335 rtsBool
336 traverseBlackholeQueue (void)
337 {
338     StgTSO *prev, *t, *tmp;
339     rtsBool flag;
340     nat type;
341
342     flag = rtsFalse;
343     prev = NULL;
344
345     for (t = blackhole_queue; t != END_TSO_QUEUE; prev=t, t = t->_link) {
346         // if the thread is not yet alive...
347         if (! (tmp = (StgTSO *)isAlive((StgClosure*)t))) {
348             // if the closure it is blocked on is either (a) a
349             // reachable BLAKCHOLE or (b) not a BLACKHOLE, then we
350             // make the thread alive.
351             if (!isAlive(t->block_info.closure)) {
352                 type = get_itbl(t->block_info.closure)->type;
353                 if (type == BLACKHOLE || type == CAF_BLACKHOLE) {
354                     continue;
355                 }
356             }
357             evacuate((StgClosure **)&t);
358             if (prev) {
359                 prev->_link = t;
360             } else {
361                 blackhole_queue = t;
362             }
363                  // no write barrier when on the blackhole queue,
364                  // because we traverse the whole queue on every GC.
365             flag = rtsTrue;
366         }
367     }
368     return flag;
369 }
370
371 /* -----------------------------------------------------------------------------
372    After GC, the live weak pointer list may have forwarding pointers
373    on it, because a weak pointer object was evacuated after being
374    moved to the live weak pointer list.  We remove those forwarding
375    pointers here.
376
377    Also, we don't consider weak pointer objects to be reachable, but
378    we must nevertheless consider them to be "live" and retain them.
379    Therefore any weak pointer objects which haven't as yet been
380    evacuated need to be evacuated now.
381    -------------------------------------------------------------------------- */
382
383 void
384 markWeakPtrList ( void )
385 {
386   StgWeak *w, **last_w, *tmp;
387
388   last_w = &weak_ptr_list;
389   for (w = weak_ptr_list; w; w = w->link) {
390       // w might be WEAK, EVACUATED, or DEAD_WEAK (actually CON_STATIC) here
391       ASSERT(IS_FORWARDING_PTR(w->header.info)
392              || w->header.info == &stg_DEAD_WEAK_info 
393              || get_itbl(w)->type == WEAK);
394       tmp = w;
395       evacuate((StgClosure **)&tmp);
396       *last_w = w;
397       last_w = &(w->link);
398   }
399 }
400