[project @ 2001-07-13 13:41:42 by rrt]
[ghc-hetmet.git] / ghc / rts / Stable.c
1 /* -----------------------------------------------------------------------------
2  * $Id: Stable.c,v 1.14 2001/07/13 13:41:42 rrt 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
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  * Reference counting
100  * ------------------
101  * A plain stable name entry has a zero reference count, which means
102  * the entry will dissappear when the object it points to is
103  * unreachable.  For stable pointers, we need an entry that sticks
104  * around and keeps the object it points to alive, so each stable name
105  * entry has an associated reference count.
106  *
107  * A stable pointer has a weighted reference count N attached to it
108  * (actually in its upper 5 bits), which represents the weight
109  * 2^(N-1).  The stable name entry keeps a 32-bit reference count, which
110  * represents any weight between 1 and 2^32 (represented as zero).
111  * When the weight is 2^32, the stable name table owns "all" of the
112  * stable pointers to this object, and the entry can be garbage
113  * collected if the object isn't reachable.
114  *
115  * A new stable pointer is given the weight log2(W/2), where W is the
116  * weight stored in the table entry.  The new weight in the table is W
117  * - 2^log2(W/2).
118  *
119  * A stable pointer can be "split" into two stable pointers, by
120  * dividing the weight by 2 and giving each pointer half.
121  * When freeing a stable pointer, the weight of the pointer is added
122  * to the weight stored in the table entry.
123  * */
124
125 HashTable *addrToStableHash;
126
127 #define INIT_SPT_SIZE 64
128
129 static inline void
130 initFreeList(snEntry *table, nat n, snEntry *free)
131 {
132   snEntry *p;
133
134   for (p = table + n - 1; p >= table; p--) {
135     p->addr   = (P_)free;
136     p->weight = 0;
137     p->sn_obj = NULL;
138     free = p;
139   }
140   stable_ptr_free = table;
141 }
142
143 void
144 initStablePtrTable(void)
145 {
146   /* the table will be allocated the first time makeStablePtr is
147    * called */
148   stable_ptr_table = NULL;
149   stable_ptr_free  = NULL;
150   addrToStableHash = NULL;
151   SPT_size = 0;
152 }
153
154 /*
155  * get at the real stuff...remove indirections.
156  *
157  * ToDo: move to a better home.
158  */
159 static
160 StgClosure*
161 removeIndirections(StgClosure* p)
162 {
163   StgClosure* q = p;
164
165   while (get_itbl(q)->type == IND ||
166          get_itbl(q)->type == IND_STATIC ||
167          get_itbl(q)->type == IND_OLDGEN ||
168          get_itbl(q)->type == IND_PERM ||
169          get_itbl(q)->type == IND_OLDGEN_PERM ) {
170       q = ((StgInd *)q)->indirectee;
171   }
172   return q;
173 }
174
175 StgWord
176 lookupStableName(StgPtr p)
177 {
178   StgWord sn;
179
180   if (stable_ptr_free == NULL) {
181     enlargeStablePtrTable();
182   }
183
184   /* removing indirections increases the likelihood
185    * of finding a match in the stable name
186    * hash table.
187    */
188   p = (StgPtr)removeIndirections((StgClosure*)p);
189
190   (void *)sn = lookupHashTable(addrToStableHash,(W_)p);
191   
192   if (sn != 0) {
193     ASSERT(stable_ptr_table[sn].addr == p);
194     IF_DEBUG(stable,fprintf(stderr,"cached stable name %d at %p\n",sn,p));
195     return sn;
196   } else {
197     sn = stable_ptr_free - stable_ptr_table;
198     (P_)stable_ptr_free  = stable_ptr_free->addr;
199     stable_ptr_table[sn].weight = 0;
200     stable_ptr_table[sn].addr = p;
201     stable_ptr_table[sn].sn_obj = NULL;
202     /* IF_DEBUG(stable,fprintf(stderr,"new stable name %d at
203        %p\n",sn,p)); */
204     
205     /* add the new stable name to the hash table */
206     insertHashTable(addrToStableHash, (W_)p, (void *)sn);
207
208     return sn;
209   }
210 }
211
212 static inline void
213 freeStableName(snEntry *sn)
214 {
215   ASSERT(sn->sn_obj == NULL);
216   if (sn->addr != NULL) {
217     removeHashTable(addrToStableHash, (W_)sn->addr, NULL);
218   }
219   sn->addr = (P_)stable_ptr_free;
220   stable_ptr_free = sn;
221 }
222
223 StgStablePtr
224 getStablePtr(StgPtr p)
225 {
226   StgWord sn = lookupStableName(p);
227   StgWord weight, n;
228   weight = stable_ptr_table[sn].weight;
229   if (weight == 0) {
230     weight = (StgWord)1 << (BITS_IN(StgWord)-1);
231     stable_ptr_table[sn].weight = weight;
232     return (StgStablePtr)(sn + (BITS_IN(StgWord) << STABLEPTR_WEIGHT_SHIFT));
233   } 
234   else if (weight == 1) {
235     barf("getStablePtr: too light");
236   } 
237   else {
238     weight /= 2;
239     /* find log2(weight) */
240     for (n = 0; weight != 1; n++) {
241       weight >>= 1;
242     }
243     stable_ptr_table[sn].weight -= 1 << n;
244     return (StgStablePtr)(sn + ((n+1) << STABLEPTR_WEIGHT_SHIFT));
245   }
246 }
247
248 void
249 enlargeStablePtrTable(void)
250 {
251   nat old_SPT_size = SPT_size;
252   
253   if (SPT_size == 0) {
254     /* 1st time */
255     SPT_size = INIT_SPT_SIZE;
256     stable_ptr_table = stgMallocWords(SPT_size * sizeof(snEntry), 
257                                       "initStablePtrTable");
258     
259     /* we don't use index 0 in the stable name table, because that
260      * would conflict with the hash table lookup operations which
261      * return NULL if an entry isn't found in the hash table.
262      */
263     initFreeList(stable_ptr_table+1,INIT_SPT_SIZE-1,NULL);
264     addrToStableHash = allocHashTable();
265   }
266   else {
267     /* 2nd and subsequent times */
268     SPT_size *= 2;
269     stable_ptr_table = 
270       stgReallocWords(stable_ptr_table, SPT_size * sizeof(snEntry),
271                       "enlargeStablePtrTable");
272     
273     initFreeList(stable_ptr_table + old_SPT_size, old_SPT_size, NULL);
274   }
275 }
276
277 /* -----------------------------------------------------------------------------
278  * Treat stable pointers as roots for the garbage collector.
279  *
280  * A stable pointer is any stable name entry with a weight > 0.  We'll
281  * take the opportunity to zero the "keep" flags at the same time.
282  * -------------------------------------------------------------------------- */
283
284 void
285 markStablePtrTable(rtsBool full)
286 {
287   snEntry *p, *end_stable_ptr_table;
288   StgPtr q;
289   StgClosure *new;
290
291   if (SPT_size == 0)
292     return;
293
294   if (full) {
295     freeHashTable(addrToStableHash,NULL);
296     addrToStableHash = allocHashTable();
297   }
298
299   end_stable_ptr_table = &stable_ptr_table[SPT_size];
300
301   /* Mark all the stable *pointers* (not stable names).
302    * _starting_ at index 1; index 0 is unused.
303    */
304   for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
305     q = p->addr;
306     /* internal pointers or NULL are free slots 
307      */
308     if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
309       if (p->weight != 0) {
310         new = MarkRoot((StgClosure *)q);
311         /* Update the hash table */
312         if (full) {
313           insertHashTable(addrToStableHash, (W_)new, 
314                           (void *)(p - stable_ptr_table));
315           (StgClosure *)p->addr = new;
316         } else if ((P_)new != q) {
317           removeHashTable(addrToStableHash, (W_)q, NULL);
318           if (!lookupHashTable(addrToStableHash, (W_)new)) {
319             insertHashTable(addrToStableHash, (W_)new, 
320                             (void *)(p - stable_ptr_table));
321           }
322           (StgClosure *)p->addr = new;
323         }
324         IF_DEBUG(stable, fprintf(stderr,"Stable ptr %d still alive at %p, weight %u\n", p - stable_ptr_table, new, p->weight));
325       }
326     }
327   }
328 }
329
330 /* -----------------------------------------------------------------------------
331  * Garbage collect any dead entries in the stable pointer table.
332  *
333  * A dead entry has:
334  *
335  *          - a weight of zero (i.e. 2^32)
336  *          - a dead sn_obj
337  *
338  * Both of these conditions must be true in order to re-use the stable
339  * name table entry.  We can re-use stable name table entries for live
340  * heap objects, as long as the program has no StableName objects that
341  * refer to the entry.
342  *
343  * The boolean argument 'full' indicates that a major collection is
344  * being done, so we might as well throw away the hash table and build
345  * a new one.  For a minor collection, we just re-hash the elements
346  * that changed.
347  * -------------------------------------------------------------------------- */
348
349 void
350 gcStablePtrTable(rtsBool full)
351 {
352   snEntry *p, *end_stable_ptr_table;
353   StgPtr q, new;
354
355   if (SPT_size == 0) {
356     return;
357   }
358
359   end_stable_ptr_table = &stable_ptr_table[SPT_size];
360
361   /* NOTE: _starting_ at index 1; index 0 is unused. */
362   for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
363
364     /* Update the pointer to the StableName object, if there is one */
365     if (p->sn_obj != NULL) {
366       p->sn_obj = isAlive(p->sn_obj);
367     }
368
369     q = p->addr;
370     if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
371
372       /* We're only interested in Stable Names here.  The weight != 0
373        * case is handled in markStablePtrTable above.
374        */
375       if (p->weight == 0) {
376         
377         if (p->sn_obj == NULL) {
378           /* StableName object is dead */
379           freeStableName(p);
380           IF_DEBUG(stable, fprintf(stderr,"GC'd Stable name %d\n", p - stable_ptr_table));
381         } 
382         else {
383           (StgClosure *)new = isAlive((StgClosure *)q);
384           IF_DEBUG(stable, fprintf(stderr,"Stable name %d still alive at %p, weight %d\n", p - stable_ptr_table, new, p->weight));
385
386           if (new == NULL) {
387             /* The target has been garbage collected.  Remove its
388              * entry from the hash table.
389              */
390             removeHashTable(addrToStableHash, (W_)q, NULL);
391
392           } else {
393             /* Target still alive, Re-hash this stable name 
394              */
395             if (full) {
396               insertHashTable(addrToStableHash, (W_)new, (void *)(p - stable_ptr_table));
397             } else if (new != q) {
398               removeHashTable(addrToStableHash, (W_)q, NULL);
399               insertHashTable(addrToStableHash, (W_)new, (void *)(p - stable_ptr_table));
400             }
401           }
402
403           /* finally update the address of the target to point to its
404            * new location.
405            */
406           p->addr = new;
407         }
408       }
409     }
410   }
411 }