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