[project @ 2004-08-22 15:50:39 by panne]
[ghc-hetmet.git] / ghc / rts / Stable.c
1 /* -----------------------------------------------------------------------------
2  * $Id: Stable.c,v 1.29 2004/08/22 15:50:42 panne Exp $
3  *
4  * (c) The GHC Team, 1998-2002
5  *
6  * Stable names and stable pointers.
7  *
8  * ---------------------------------------------------------------------------*/
9
10 // Make static versions of inline functions in Stable.h:
11 #define RTS_STABLE_C
12
13 #include "PosixSource.h"
14 #include "Rts.h"
15 #include "Hash.h"
16 #include "RtsUtils.h"
17 #include "Storage.h"
18 #include "RtsAPI.h"
19 #include "RtsFlags.h"
20
21 /* Comment from ADR's implementation in old RTS:
22
23   This files (together with @ghc/runtime/storage/PerformIO.lhc@ and a
24   small change in @HpOverflow.lc@) consists of the changes in the
25   runtime system required to implement "Stable Pointers". But we're
26   getting a bit ahead of ourselves --- what is a stable pointer and what
27   is it used for?
28
29   When Haskell calls C, it normally just passes over primitive integers,
30   floats, bools, strings, etc.  This doesn't cause any problems at all
31   for garbage collection because the act of passing them makes a copy
32   from the heap, stack or wherever they are onto the C-world stack.
33   However, if we were to pass a heap object such as a (Haskell) @String@
34   and a garbage collection occured before we finished using it, we'd run
35   into problems since the heap object might have been moved or even
36   deleted.
37
38   So, if a C call is able to cause a garbage collection or we want to
39   store a pointer to a heap object between C calls, we must be careful
40   when passing heap objects. Our solution is to keep a table of all
41   objects we've given to the C-world and to make sure that the garbage
42   collector collects these objects --- updating the table as required to
43   make sure we can still find the object.
44
45
46   Of course, all this rather begs the question: why would we want to
47   pass a boxed value?
48
49   One very good reason is to preserve laziness across the language
50   interface. Rather than evaluating an integer or a string because it
51   {\em might\/} be required by the C function, we can wait until the C
52   function actually wants the value and then force an evaluation.
53
54   Another very good reason (the motivating reason!) is that the C code
55   might want to execute an object of sort $IO ()$ for the side-effects
56   it will produce. For example, this is used when interfacing to an X
57   widgets library to allow a direct implementation of callbacks.
58
59
60   The @makeStablePointer :: a -> IO (StablePtr a)@ function
61   converts a value into a stable pointer.  It is part of the @PrimIO@
62   monad, because we want to be sure we don't allocate one twice by
63   accident, and then only free one of the copies.
64
65   \begin{verbatim}
66   makeStablePtr#  :: a -> State# RealWorld -> (# RealWorld, a #)
67   freeStablePtr#  :: StablePtr# a -> State# RealWorld -> State# RealWorld
68   deRefStablePtr# :: StablePtr# a -> State# RealWorld -> 
69         (# State# RealWorld, a #)
70   \end{verbatim}
71
72   There may be additional functions on the C side to allow evaluation,
73   application, etc of a stable pointer.
74
75 */
76
77 snEntry *stable_ptr_table = NULL;
78 static snEntry *stable_ptr_free = NULL;
79
80 static unsigned int SPT_size = 0;
81
82 /* This hash table maps Haskell objects to stable names, so that every
83  * call to lookupStableName on a given object will return the same
84  * stable name.
85  *
86  * OLD COMMENTS about reference counting follow.  The reference count
87  * in a stable name entry is now just a counter.
88  *
89  * Reference counting
90  * ------------------
91  * A plain stable name entry has a zero reference count, which means
92  * the entry will dissappear when the object it points to is
93  * unreachable.  For stable pointers, we need an entry that sticks
94  * around and keeps the object it points to alive, so each stable name
95  * entry has an associated reference count.
96  *
97  * A stable pointer has a weighted reference count N attached to it
98  * (actually in its upper 5 bits), which represents the weight
99  * 2^(N-1).  The stable name entry keeps a 32-bit reference count, which
100  * represents any weight between 1 and 2^32 (represented as zero).
101  * When the weight is 2^32, the stable name table owns "all" of the
102  * stable pointers to this object, and the entry can be garbage
103  * collected if the object isn't reachable.
104  *
105  * A new stable pointer is given the weight log2(W/2), where W is the
106  * weight stored in the table entry.  The new weight in the table is W
107  * - 2^log2(W/2).
108  *
109  * A stable pointer can be "split" into two stable pointers, by
110  * dividing the weight by 2 and giving each pointer half.
111  * When freeing a stable pointer, the weight of the pointer is added
112  * to the weight stored in the table entry.
113  * */
114
115 static HashTable *addrToStableHash = NULL;
116
117 #define INIT_SPT_SIZE 64
118
119 STATIC_INLINE void
120 initFreeList(snEntry *table, nat n, snEntry *free)
121 {
122   snEntry *p;
123
124   for (p = table + n - 1; p >= table; p--) {
125     p->addr   = (P_)free;
126     p->old    = NULL;
127     p->ref    = 0;
128     p->sn_obj = NULL;
129     free = p;
130   }
131   stable_ptr_free = table;
132 }
133
134 void
135 initStablePtrTable(void)
136 {
137     // Nothing to do:
138     // the table will be allocated the first time makeStablePtr is
139     // called, and we want the table to persist through multiple inits.
140 }
141
142 /*
143  * get at the real stuff...remove indirections.
144  *
145  * ToDo: move to a better home.
146  */
147 static
148 StgClosure*
149 removeIndirections(StgClosure* p)
150 {
151   StgClosure* q = p;
152
153   while (get_itbl(q)->type == IND ||
154          get_itbl(q)->type == IND_STATIC ||
155          get_itbl(q)->type == IND_OLDGEN ||
156          get_itbl(q)->type == IND_PERM ||
157          get_itbl(q)->type == IND_OLDGEN_PERM ) {
158       q = ((StgInd *)q)->indirectee;
159   }
160   return q;
161 }
162
163 StgWord
164 lookupStableName(StgPtr p)
165 {
166   StgWord sn;
167   void* sn_tmp;
168
169   if (stable_ptr_free == NULL) {
170     enlargeStablePtrTable();
171   }
172
173   /* removing indirections increases the likelihood
174    * of finding a match in the stable name hash table.
175    */
176   p = (StgPtr)removeIndirections((StgClosure*)p);
177
178   sn_tmp = lookupHashTable(addrToStableHash,(W_)p);
179   sn = (StgWord)sn_tmp;
180   
181   if (sn != 0) {
182     ASSERT(stable_ptr_table[sn].addr == p);
183     IF_DEBUG(stable,fprintf(stderr,"cached stable name %d at %p\n",sn,p));
184     return sn;
185   } else {
186     sn = stable_ptr_free - stable_ptr_table;
187     stable_ptr_free  = (snEntry*)(stable_ptr_free->addr);
188     stable_ptr_table[sn].ref = 0;
189     stable_ptr_table[sn].addr = p;
190     stable_ptr_table[sn].sn_obj = NULL;
191     /* IF_DEBUG(stable,fprintf(stderr,"new stable name %d at
192        %p\n",sn,p)); */
193     
194     /* add the new stable name to the hash table */
195     insertHashTable(addrToStableHash, (W_)p, (void *)sn);
196
197     return sn;
198   }
199 }
200
201 STATIC_INLINE void
202 freeStableName(snEntry *sn)
203 {
204   ASSERT(sn->sn_obj == NULL);
205   if (sn->addr != NULL) {
206       removeHashTable(addrToStableHash, (W_)sn->addr, NULL);
207   }
208   sn->addr = (P_)stable_ptr_free;
209   stable_ptr_free = sn;
210 }
211
212 StgStablePtr
213 getStablePtr(StgPtr p)
214 {
215   StgWord sn;
216
217   sn = lookupStableName(p);
218   stable_ptr_table[sn].ref++;
219   return (StgStablePtr)(sn);
220 }
221
222 void
223 freeStablePtr(StgStablePtr sp)
224 {
225     snEntry *sn = &stable_ptr_table[(StgWord)sp];
226     
227     ASSERT((StgWord)sp < SPT_size  &&  sn->addr != NULL  &&  sn->ref > 0);
228
229     sn->ref--;
230
231     // If this entry has no StableName attached, then just free it
232     // immediately.  This is important; it might be a while before the
233     // next major GC which actually collects the entry.
234     if (sn->sn_obj == NULL && sn->ref == 0) {
235         freeStableName(sn);
236     }
237 }
238
239 void
240 enlargeStablePtrTable(void)
241 {
242   nat old_SPT_size = SPT_size;
243   
244   if (SPT_size == 0) {
245     // 1st time
246     SPT_size = INIT_SPT_SIZE;
247     stable_ptr_table = stgMallocBytes(SPT_size * sizeof(snEntry), 
248                                       "enlargeStablePtrTable");
249     
250     /* we don't use index 0 in the stable name table, because that
251      * would conflict with the hash table lookup operations which
252      * return NULL if an entry isn't found in the hash table.
253      */
254     initFreeList(stable_ptr_table+1,INIT_SPT_SIZE-1,NULL);
255     addrToStableHash = allocHashTable();
256   }
257   else {
258     // 2nd and subsequent times
259     SPT_size *= 2;
260     stable_ptr_table = 
261       stgReallocBytes(stable_ptr_table, 
262                       SPT_size * sizeof(snEntry),
263                       "enlargeStablePtrTable");
264
265     initFreeList(stable_ptr_table + old_SPT_size, old_SPT_size, NULL);
266   }
267 }
268
269 /* -----------------------------------------------------------------------------
270  * Treat stable pointers as roots for the garbage collector.
271  *
272  * A stable pointer is any stable name entry with a ref > 0.  We'll
273  * take the opportunity to zero the "keep" flags at the same time.
274  * -------------------------------------------------------------------------- */
275
276 void
277 markStablePtrTable(evac_fn evac)
278 {
279     snEntry *p, *end_stable_ptr_table;
280     StgPtr q;
281     
282     end_stable_ptr_table = &stable_ptr_table[SPT_size];
283     
284     // Mark all the stable *pointers* (not stable names).
285     // _starting_ at index 1; index 0 is unused.
286     for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
287         q = p->addr;
288
289         // Internal pointers are free slots.  If q == NULL, it's a
290         // stable name where the object has been GC'd, but the
291         // StableName object (sn_obj) is still alive.
292         if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
293
294             // save the current addr away: we need to be able to tell
295             // whether the objects moved in order to be able to update
296             // the hash table later.
297             p->old = p->addr;
298
299             // if the ref is non-zero, treat addr as a root
300             if (p->ref != 0) {
301                 evac((StgClosure **)&p->addr);
302             }
303         }
304     }
305 }
306
307 /* -----------------------------------------------------------------------------
308  * Thread the stable pointer table for compacting GC.
309  * 
310  * Here we must call the supplied evac function for each pointer into
311  * the heap from the stable pointer table, because the compacting
312  * collector may move the object it points to.
313  * -------------------------------------------------------------------------- */
314
315 void
316 threadStablePtrTable( evac_fn evac )
317 {
318     snEntry *p, *end_stable_ptr_table;
319     StgPtr q;
320     
321     end_stable_ptr_table = &stable_ptr_table[SPT_size];
322     
323     for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
324         
325         if (p->sn_obj != NULL) {
326             evac((StgClosure **)&p->sn_obj);
327         }
328
329         q = p->addr;
330         if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
331             evac((StgClosure **)&p->addr);
332         }
333     }
334 }
335
336 /* -----------------------------------------------------------------------------
337  * Garbage collect any dead entries in the stable pointer table.
338  *
339  * A dead entry has:
340  *
341  *          - a zero reference count
342  *          - a dead sn_obj
343  *
344  * Both of these conditions must be true in order to re-use the stable
345  * name table entry.  We can re-use stable name table entries for live
346  * heap objects, as long as the program has no StableName objects that
347  * refer to the entry.
348  * -------------------------------------------------------------------------- */
349
350 void
351 gcStablePtrTable( void )
352 {
353     snEntry *p, *end_stable_ptr_table;
354     StgPtr q;
355     
356     end_stable_ptr_table = &stable_ptr_table[SPT_size];
357     
358     // NOTE: _starting_ at index 1; index 0 is unused.
359     for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
360         
361         // Update the pointer to the StableName object, if there is one
362         if (p->sn_obj != NULL) {
363             p->sn_obj = isAlive(p->sn_obj);
364         }
365         
366         // Internal pointers are free slots.  If q == NULL, it's a
367         // stable name where the object has been GC'd, but the
368         // StableName object (sn_obj) is still alive.
369         q = p->addr;
370         if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
371
372             // StableNames only:
373             if (p->ref == 0) {
374                 if (p->sn_obj == NULL) {
375                     // StableName object is dead
376                     freeStableName(p);
377                     IF_DEBUG(stable, fprintf(stderr,"GC'd Stable name %d\n", 
378                                              p - stable_ptr_table));
379                     continue;
380                     
381                 } else {
382                   p->addr = (StgPtr)isAlive((StgClosure *)p->addr);
383                     IF_DEBUG(stable, fprintf(stderr,"Stable name %d still alive at %p, ref %d\n", p - stable_ptr_table, p->addr, p->ref));
384                 }
385             }
386         }
387     }
388 }
389
390 /* -----------------------------------------------------------------------------
391  * Update the StablePtr/StableName hash table
392  *
393  * The boolean argument 'full' indicates that a major collection is
394  * being done, so we might as well throw away the hash table and build
395  * a new one.  For a minor collection, we just re-hash the elements
396  * that changed.
397  * -------------------------------------------------------------------------- */
398
399 void
400 updateStablePtrTable(rtsBool full)
401 {
402     snEntry *p, *end_stable_ptr_table;
403     
404     if (full && addrToStableHash != NULL) {
405         freeHashTable(addrToStableHash,NULL);
406         addrToStableHash = allocHashTable();
407     }
408     
409     end_stable_ptr_table = &stable_ptr_table[SPT_size];
410     
411     // NOTE: _starting_ at index 1; index 0 is unused.
412     for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
413         
414         if (p->addr == NULL) {
415             if (p->old != NULL) {
416                 // The target has been garbage collected.  Remove its
417                 // entry from the hash table.
418                 removeHashTable(addrToStableHash, (W_)p->old, NULL);
419                 p->old = NULL;
420             }
421         }
422         else if (p->addr < (P_)stable_ptr_table 
423                  || p->addr >= (P_)end_stable_ptr_table) {
424             // Target still alive, Re-hash this stable name 
425             if (full) {
426                 insertHashTable(addrToStableHash, (W_)p->addr, 
427                                 (void *)(p - stable_ptr_table));
428             } else if (p->addr != p->old) {
429                 removeHashTable(addrToStableHash, (W_)p->old, NULL);
430                 insertHashTable(addrToStableHash, (W_)p->addr, 
431                                 (void *)(p - stable_ptr_table));
432             }
433         }
434     }
435 }