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