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