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