MERGE: Fix bug exposed by conc052.
[ghc-hetmet.git] / rts / sm / MarkWeak.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team 1998-2006
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 "Evac.h"
19 #include "Trace.h"
20 #include "Schedule.h"
21
22 /* -----------------------------------------------------------------------------
23    Weak Pointers
24
25    traverse_weak_ptr_list is called possibly many times during garbage
26    collection.  It returns a flag indicating whether it did any work
27    (i.e. called evacuate on any live pointers).
28
29    Invariant: traverse_weak_ptr_list is called when the heap is in an
30    idempotent state.  That means that there are no pending
31    evacuate/scavenge operations.  This invariant helps the weak
32    pointer code decide which weak pointers are dead - if there are no
33    new live weak pointers, then all the currently unreachable ones are
34    dead.
35
36    For generational GC: we just don't try to finalize weak pointers in
37    older generations than the one we're collecting.  This could
38    probably be optimised by keeping per-generation lists of weak
39    pointers, but for a few weak pointers this scheme will work.
40
41    There are three distinct stages to processing weak pointers:
42
43    - weak_stage == WeakPtrs
44
45      We process all the weak pointers whos keys are alive (evacuate
46      their values and finalizers), and repeat until we can find no new
47      live keys.  If no live keys are found in this pass, then we
48      evacuate the finalizers of all the dead weak pointers in order to
49      run them.
50
51    - weak_stage == WeakThreads
52
53      Now, we discover which *threads* are still alive.  Pointers to
54      threads from the all_threads and main thread lists are the
55      weakest of all: a pointers from the finalizer of a dead weak
56      pointer can keep a thread alive.  Any threads found to be unreachable
57      are evacuated and placed on the resurrected_threads list so we 
58      can send them a signal later.
59
60    - weak_stage == WeakDone
61
62      No more evacuation is done.
63
64    -------------------------------------------------------------------------- */
65
66 /* Which stage of processing various kinds of weak pointer are we at?
67  * (see traverse_weak_ptr_list() below for discussion).
68  */
69 typedef enum { WeakPtrs, WeakThreads, WeakDone } WeakStage;
70 static WeakStage weak_stage;
71
72 /* Weak pointers
73  */
74 StgWeak *old_weak_ptr_list; // also pending finaliser list
75
76 /* List of all threads during GC
77  */
78 StgTSO *resurrected_threads;
79 static StgTSO *old_all_threads;
80
81 void
82 initWeakForGC(void)
83 {
84     old_weak_ptr_list = weak_ptr_list;
85     weak_ptr_list = NULL;
86     weak_stage = WeakPtrs;
87
88     /* The all_threads list is like the weak_ptr_list.  
89      * See traverseWeakPtrList() for the details.
90      */
91     old_all_threads = all_threads;
92     all_threads = END_TSO_QUEUE;
93     resurrected_threads = END_TSO_QUEUE;
94 }
95
96 rtsBool 
97 traverseWeakPtrList(void)
98 {
99   StgWeak *w, **last_w, *next_w;
100   StgClosure *new;
101   rtsBool flag = rtsFalse;
102
103   switch (weak_stage) {
104
105   case WeakDone:
106       return rtsFalse;
107
108   case WeakPtrs:
109       /* doesn't matter where we evacuate values/finalizers to, since
110        * these pointers are treated as roots (iff the keys are alive).
111        */
112       evac_gen = 0;
113       
114       last_w = &old_weak_ptr_list;
115       for (w = old_weak_ptr_list; w != NULL; w = next_w) {
116           
117           /* There might be a DEAD_WEAK on the list if finalizeWeak# was
118            * called on a live weak pointer object.  Just remove it.
119            */
120           if (w->header.info == &stg_DEAD_WEAK_info) {
121               next_w = ((StgDeadWeak *)w)->link;
122               *last_w = next_w;
123               continue;
124           }
125           
126           switch (get_itbl(w)->type) {
127
128           case EVACUATED:
129               next_w = (StgWeak *)((StgEvacuated *)w)->evacuee;
130               *last_w = next_w;
131               continue;
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                   w->value = evacuate(w->value);
141                   w->finalizer = 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               w->finalizer = 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           
190           prev = &old_all_threads;
191           for (t = old_all_threads; t != END_TSO_QUEUE; t = next) {
192               
193               tmp = (StgTSO *)isAlive((StgClosure *)t);
194               
195               if (tmp != NULL) {
196                   t = tmp;
197               }
198               
199               ASSERT(get_itbl(t)->type == TSO);
200               switch (t->what_next) {
201               case ThreadRelocated:
202                   next = t->link;
203                   *prev = next;
204                   continue;
205               case ThreadKilled:
206               case ThreadComplete:
207                   // finshed or died.  The thread might still be alive, but we
208                   // don't keep it on the all_threads list.  Don't forget to
209                   // stub out its global_link field.
210                   next = t->global_link;
211                   t->global_link = END_TSO_QUEUE;
212                   *prev = next;
213                   continue;
214               default:
215                   ;
216               }
217               
218               if (tmp == NULL) {
219                   // not alive (yet): leave this thread on the
220                   // old_all_threads list.
221                   prev = &(t->global_link);
222                   next = t->global_link;
223               } 
224               else {
225                   // alive: move this thread onto the all_threads list.
226                   next = t->global_link;
227                   t->global_link = all_threads;
228                   all_threads  = t;
229                   *prev = next;
230               }
231           }
232       }
233       
234       /* If we evacuated any threads, we need to go back to the scavenger.
235        */
236       if (flag) return rtsTrue;
237
238       /* And resurrect any threads which were about to become garbage.
239        */
240       {
241           StgTSO *t, *tmp, *next;
242           for (t = old_all_threads; t != END_TSO_QUEUE; t = next) {
243               next = t->global_link;
244               tmp = (StgTSO *)evacuate((StgClosure *)t);
245               tmp->global_link = resurrected_threads;
246               resurrected_threads = tmp;
247           }
248       }
249       
250       /* Finally, we can update the blackhole_queue.  This queue
251        * simply strings together TSOs blocked on black holes, it is
252        * not intended to keep anything alive.  Hence, we do not follow
253        * pointers on the blackhole_queue until now, when we have
254        * determined which TSOs are otherwise reachable.  We know at
255        * this point that all TSOs have been evacuated, however.
256        */
257       { 
258           StgTSO **pt;
259           for (pt = &blackhole_queue; *pt != END_TSO_QUEUE; pt = &((*pt)->link)) {
260               *pt = (StgTSO *)isAlive((StgClosure *)*pt);
261               ASSERT(*pt != NULL);
262           }
263       }
264
265       weak_stage = WeakDone;  // *now* we're done,
266       return rtsTrue;         // but one more round of scavenging, please
267
268   default:
269       barf("traverse_weak_ptr_list");
270       return rtsTrue;
271   }
272
273 }
274
275 /* -----------------------------------------------------------------------------
276    The blackhole queue
277    
278    Threads on this list behave like weak pointers during the normal
279    phase of garbage collection: if the blackhole is reachable, then
280    the thread is reachable too.
281    -------------------------------------------------------------------------- */
282 rtsBool
283 traverseBlackholeQueue (void)
284 {
285     StgTSO *prev, *t, *tmp;
286     rtsBool flag;
287     nat type;
288
289     flag = rtsFalse;
290     prev = NULL;
291
292     for (t = blackhole_queue; t != END_TSO_QUEUE; prev=t, t = t->link) {
293         // if the thread is not yet alive...
294         if (! (tmp = (StgTSO *)isAlive((StgClosure*)t))) {
295             // if the closure it is blocked on is either (a) a
296             // reachable BLAKCHOLE or (b) not a BLACKHOLE, then we
297             // make the thread alive.
298             if (!isAlive(t->block_info.closure)) {
299                 type = get_itbl(t->block_info.closure)->type;
300                 if (type == BLACKHOLE || type == CAF_BLACKHOLE) {
301                     continue;
302                 }
303             }
304             t = (StgTSO *)evacuate((StgClosure *)t);
305             if (prev) prev->link = t;
306             flag = rtsTrue;
307         }
308     }
309     return flag;
310 }
311
312 /* -----------------------------------------------------------------------------
313    After GC, the live weak pointer list may have forwarding pointers
314    on it, because a weak pointer object was evacuated after being
315    moved to the live weak pointer list.  We remove those forwarding
316    pointers here.
317
318    Also, we don't consider weak pointer objects to be reachable, but
319    we must nevertheless consider them to be "live" and retain them.
320    Therefore any weak pointer objects which haven't as yet been
321    evacuated need to be evacuated now.
322    -------------------------------------------------------------------------- */
323
324 void
325 markWeakPtrList ( void )
326 {
327   StgWeak *w, **last_w;
328
329   last_w = &weak_ptr_list;
330   for (w = weak_ptr_list; w; w = w->link) {
331       // w might be WEAK, EVACUATED, or DEAD_WEAK (actually CON_STATIC) here
332       ASSERT(w->header.info == &stg_DEAD_WEAK_info 
333              || get_itbl(w)->type == WEAK || get_itbl(w)->type == EVACUATED);
334       w = (StgWeak *)evacuate((StgClosure *)w);
335       *last_w = w;
336       last_w = &(w->link);
337   }
338 }
339