[project @ 1999-08-04 10:04:31 by simonmar]
[ghc-hetmet.git] / ghc / rts / Stable.c
1 /* -----------------------------------------------------------------------------
2  * $Id: Stable.c,v 1.6 1999/08/04 10:04:31 simonmar Exp $
3  *
4  * (c) The GHC Team, 1998-1999
5  *
6  * Stable names and stable pointers.
7  *
8  * ---------------------------------------------------------------------------*/
9
10 #include "Rts.h"
11 #include "Hash.h"
12 #include "StablePriv.h"
13 #include "GC.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   There is also a C procedure @FreeStablePtr@ which frees a stable pointer.
70
71   There may be additional functions on the C side to allow evaluation,
72   application, etc of a stable pointer.
73
74   When Haskell calls C, it normally just passes over primitive integers,
75   floats, bools, strings, etc.  This doesn't cause any problems at all
76   for garbage collection because the act of passing them makes a copy
77   from the heap, stack or wherever they are onto the C-world stack.
78   However, if we were to pass a heap object such as a (Haskell) @String@
79   and a garbage collection occured before we finished using it, we'd run
80   into problems since the heap object might have been moved or even
81   deleted.
82
83   So, if a C call is able to cause a garbage collection or we want to
84   store a pointer to a heap object between C calls, we must be careful
85   when passing heap objects. Our solution is to keep a table of all
86   objects we've given to the C-world and to make sure that the garbage
87   collector collects these objects --- updating the table as required to
88   make sure we can still find the object.
89 */
90
91 snEntry *stable_ptr_table;
92 snEntry *stable_ptr_free;
93
94 unsigned int SPT_size;
95
96 /* This hash table maps Haskell objects to stable names, so that every
97  * call to lookupStableName on a given object will return the same
98  * stable name.
99  *
100  * Reference counting
101  * ------------------
102  * A plain stable name entry has a zero reference count, which means
103  * the entry will dissappear when the object it points to is
104  * unreachable.  For stable pointers, we need an entry that sticks
105  * around and keeps the object it points to alive, so each stable name
106  * entry has an associated reference count.
107  *
108  * A stable pointer has a weighted reference count N attached to it
109  * (actually in its upper 5 bits), which represents the weight
110  * 2^N.  The stable name entry keeps a 32-bit reference count, which
111  * represents any weight between 1 and 2^32 (represented as zero).
112  * When the weight is 2^32, the stable name table owns "all" of the
113  * stable pointers to this object, and the entry can be garbage
114  * collected if the object isn't reachable.
115  *
116  * A new stable pointer is given the weight log2(W/2), where W is the
117  * weight stored in the table entry.  The new weight in the table is W
118  * - 2^log2(W/2).
119  *
120  * A stable pointer can be "split" into two stable pointers, by
121  * dividing the weight by 2 and giving each pointer half.
122  * When freeing a stable pointer, the weight of the pointer is added
123  * to the weight stored in the table entry.
124  * */
125
126 HashTable *addrToStableHash;
127
128 #define INIT_SPT_SIZE 64
129
130 static inline void
131 initFreeList(snEntry *table, nat n, snEntry *free)
132 {
133   snEntry *p;
134
135   for (p = table + n - 1; p >= table; p--) {
136     p->addr   = (P_)free;
137     p->weight = 0;
138     p->sn_obj = NULL;
139     free = p;
140   }
141   stable_ptr_free = table;
142 }
143
144 void
145 initStablePtrTable(void)
146 {
147   /* the table will be allocated the first time makeStablePtr is
148    * called */
149   stable_ptr_table = NULL;
150   stable_ptr_free  = NULL;
151   addrToStableHash = NULL;
152   SPT_size = 0;
153 }
154
155 StgWord
156 lookupStableName(StgPtr p)
157 {
158   StgWord sn;
159
160   if (stable_ptr_free == NULL) {
161     enlargeStablePtrTable();
162   }
163     
164   (void *)sn = lookupHashTable(addrToStableHash,(W_)p);
165   
166   if (sn != 0) {
167     ASSERT(stable_ptr_table[sn].addr == p);
168     IF_DEBUG(stable,fprintf(stderr,"cached stable name %d at %p\n",sn,p));
169     return sn;
170   } else {
171     sn = stable_ptr_free - stable_ptr_table;
172     (P_)stable_ptr_free  = stable_ptr_free->addr;
173     stable_ptr_table[sn].weight = 0;
174     stable_ptr_table[sn].addr = p;
175     stable_ptr_table[sn].sn_obj = NULL;
176     /* IF_DEBUG(stable,fprintf(stderr,"new stable name %d at
177        %p\n",sn,p)); */
178     
179     /* add the new stable name to the hash table */
180     insertHashTable(addrToStableHash, (W_)p, (void *)sn);
181
182     return sn;
183   }
184 }
185
186 static inline void
187 freeStableName(snEntry *sn)
188 {
189   ASSERT(sn->sn_obj == NULL);
190   if (sn->addr != NULL) {
191     removeHashTable(addrToStableHash, (W_)sn->addr, NULL);
192   }
193   sn->addr = (P_)stable_ptr_free;
194   stable_ptr_free = sn;
195 }
196
197 StgStablePtr
198 getStablePtr(StgPtr p)
199 {
200   StgWord sn = lookupStableName(p);
201   StgWord weight, weight_2;
202
203   weight = stable_ptr_table[sn].weight;
204   if (weight == 0) {
205     weight = (StgWord)1 << (BITS_IN(StgWord)-1);
206     stable_ptr_table[sn].weight = weight;
207     return (StgStablePtr)(sn + ((BITS_IN(StgWord)-1) << STABLEPTR_WEIGHT_SHIFT));
208   } 
209   else if (weight == 1) {
210     barf("getStablePtr: too light");
211   } 
212   else {
213     weight /= 2;
214     /* find log2(weight) */
215     for (weight_2 = 1; weight != 1; weight_2++) {
216       weight >>= 1;
217     }
218     stable_ptr_table[sn].weight -= 2^weight_2;
219     return (StgStablePtr)(sn + (weight_2 << STABLEPTR_WEIGHT_SHIFT));
220   }
221 }
222
223 void
224 enlargeStablePtrTable(void)
225 {
226   nat old_SPT_size = SPT_size;
227   
228   if (SPT_size == 0) {
229     /* 1st time */
230     SPT_size = INIT_SPT_SIZE;
231     stable_ptr_table = stgMallocWords(SPT_size * sizeof(snEntry), 
232                                       "initStablePtrTable");
233     
234     initFreeList(stable_ptr_table,INIT_SPT_SIZE,NULL);
235     addrToStableHash = allocHashTable();
236   }
237   else {
238     /* 2nd and subsequent times */
239     SPT_size *= 2;
240     stable_ptr_table = 
241       stgReallocWords(stable_ptr_table, SPT_size * sizeof(snEntry),
242                       "enlargeStablePtrTable");
243     
244     initFreeList(stable_ptr_table + old_SPT_size, old_SPT_size, NULL);
245   }
246 }
247
248 /* -----------------------------------------------------------------------------
249  * Treat stable pointers as roots for the garbage collector.
250  *
251  * A stable pointer is any stable name entry with a weight > 0.  We'll
252  * take the opportunity to zero the "keep" flags at the same time.
253  * -------------------------------------------------------------------------- */
254
255 void
256 markStablePtrTable(rtsBool full)
257 {
258   snEntry *p, *end_stable_ptr_table;
259   StgPtr q;
260   StgClosure *new;
261
262   if (SPT_size == 0)
263     return;
264
265   if (full) {
266     freeHashTable(addrToStableHash,NULL);
267     addrToStableHash = allocHashTable();
268   }
269
270   end_stable_ptr_table = &stable_ptr_table[SPT_size];
271
272   /* Mark all the stable *pointers* (not stable names) 
273    */
274   for (p = stable_ptr_table; p < end_stable_ptr_table; p++) {
275     q = p->addr;
276     /* internal pointers or NULL are free slots 
277      */
278     if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
279       if (p->weight != 0) {
280         new = MarkRoot((StgClosure *)q);
281         /* Update the hash table */
282         if (full) {
283           insertHashTable(addrToStableHash, (W_)new, 
284                           (void *)(p - stable_ptr_table));
285           (StgClosure *)p->addr = new;
286         } else if ((P_)new != q) {
287           removeHashTable(addrToStableHash, (W_)q, NULL);
288           insertHashTable(addrToStableHash, (W_)new, 
289                           (void *)(p - stable_ptr_table));
290           (StgClosure *)p->addr = new;
291         }
292         IF_DEBUG(stable, fprintf(stderr,"Stable ptr %d still alive at %p, weight %d\n", p - stable_ptr_table, new, p->weight));
293       }
294     }
295   }
296 }
297
298 /* -----------------------------------------------------------------------------
299  * Garbage collect any dead entries in the stable pointer table.
300  *
301  * A dead entry has:
302  *
303  *          - a weight of zero (i.e. 2^32)
304  *          - a dead sn_obj
305  *
306  * Both of these conditions must be true in order to re-use the stable
307  * name table entry.  We can re-use stable name table entries for live
308  * heap objects, as long as the program has no StableName objects that
309  * refer to the entry.
310  *
311  * The boolean argument 'full' indicates that a major collection is
312  * being done, so we might as well throw away the hash table and build
313  * a new one.  For a minor collection, we just re-hash the elements
314  * that changed.
315  * -------------------------------------------------------------------------- */
316
317 void
318 gcStablePtrTable(rtsBool full)
319 {
320   snEntry *p, *end_stable_ptr_table;
321   StgPtr q, new;
322
323   if (SPT_size == 0) {
324     return;
325   }
326
327   end_stable_ptr_table = &stable_ptr_table[SPT_size];
328
329   for (p = stable_ptr_table; p < end_stable_ptr_table; p++) {
330
331     /* Update the pointer to the StableName object, if there is one */
332     if (p->sn_obj != NULL) {
333       p->sn_obj = isAlive(p->sn_obj);
334     }
335
336     q = p->addr;
337     if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
338
339       /* We're only interested in Stable Names here.  The weight != 0
340        * case is handled in markStablePtrTable above.
341        */
342       if (p->weight == 0) {
343         
344         if (p->sn_obj == NULL) {
345           /* StableName object is dead */
346           freeStableName(p);
347           IF_DEBUG(stable, fprintf(stderr,"GC'd Stable name %d\n", p - stable_ptr_table));
348         } 
349         else {
350           (StgClosure *)new = isAlive((StgClosure *)q);
351           IF_DEBUG(stable, fprintf(stderr,"Stable name %d still alive at %p, weight %d\n", p - stable_ptr_table, new, p->weight));
352
353           if (new == NULL) {
354             /* The target has been garbage collected.  Remove its
355              * entry from the hash table.
356              */
357             removeHashTable(addrToStableHash, (W_)q, NULL);
358
359           } else {
360             /* Target still alive, Re-hash this stable name 
361              */
362             if (full) {
363               insertHashTable(addrToStableHash, (W_)new, (void *)(p - stable_ptr_table));
364             } else if (new != q) {
365               removeHashTable(addrToStableHash, (W_)q, NULL);
366               insertHashTable(addrToStableHash, (W_)new, (void *)(p - stable_ptr_table));
367             }
368           }
369
370           /* finally update the address of the target to point to its
371            * new location.
372            */
373           p->addr = new;
374         }
375       }
376     }
377   }
378 }