[project @ 2005-11-24 12:14:50 by simonmar]
[ghc-hetmet.git] / ghc / rts / Stable.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2002
4  *
5  * Stable names and stable pointers.
6  *
7  * ---------------------------------------------------------------------------*/
8
9 // Make static versions of inline functions in Stable.h:
10 #define RTS_STABLE_C
11
12 #include "PosixSource.h"
13 #include "Rts.h"
14 #include "Hash.h"
15 #include "RtsUtils.h"
16 #include "OSThreads.h"
17 #include "Storage.h"
18 #include "RtsAPI.h"
19 #include "RtsFlags.h"
20 #include "OSThreads.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 static Mutex stable_mutex;
84
85 /* This hash table maps Haskell objects to stable names, so that every
86  * call to lookupStableName on a given object will return the same
87  * stable name.
88  *
89  * OLD COMMENTS about reference counting follow.  The reference count
90  * in a stable name entry is now just a counter.
91  *
92  * Reference counting
93  * ------------------
94  * A plain stable name entry has a zero reference count, which means
95  * the entry will dissappear when the object it points to is
96  * unreachable.  For stable pointers, we need an entry that sticks
97  * around and keeps the object it points to alive, so each stable name
98  * entry has an associated reference count.
99  *
100  * A stable pointer has a weighted reference count N attached to it
101  * (actually in its upper 5 bits), which represents the weight
102  * 2^(N-1).  The stable name entry keeps a 32-bit reference count, which
103  * represents any weight between 1 and 2^32 (represented as zero).
104  * When the weight is 2^32, the stable name table owns "all" of the
105  * stable pointers to this object, and the entry can be garbage
106  * collected if the object isn't reachable.
107  *
108  * A new stable pointer is given the weight log2(W/2), where W is the
109  * weight stored in the table entry.  The new weight in the table is W
110  * - 2^log2(W/2).
111  *
112  * A stable pointer can be "split" into two stable pointers, by
113  * dividing the weight by 2 and giving each pointer half.
114  * When freeing a stable pointer, the weight of the pointer is added
115  * to the weight stored in the table entry.
116  * */
117
118 static HashTable *addrToStableHash = NULL;
119
120 #define INIT_SPT_SIZE 64
121
122 STATIC_INLINE void
123 initFreeList(snEntry *table, nat n, snEntry *free)
124 {
125   snEntry *p;
126
127   for (p = table + n - 1; p >= table; p--) {
128     p->addr   = (P_)free;
129     p->old    = NULL;
130     p->ref    = 0;
131     p->sn_obj = NULL;
132     free = p;
133   }
134   stable_ptr_free = table;
135 }
136
137 void
138 initStablePtrTable(void)
139 {
140     // Nothing to do:
141     // the table will be allocated the first time makeStablePtr is
142     // called, and we want the table to persist through multiple inits.
143     //
144     // Also, getStablePtr is now called from __attribute__((constructor))
145     // functions, so initialising things here wouldn't work anyway.
146     initMutex(&stable_mutex);
147 }
148
149 /*
150  * get at the real stuff...remove indirections.
151  *
152  * ToDo: move to a better home.
153  */
154 static
155 StgClosure*
156 removeIndirections(StgClosure* p)
157 {
158   StgClosure* q = p;
159
160   while (get_itbl(q)->type == IND ||
161          get_itbl(q)->type == IND_STATIC ||
162          get_itbl(q)->type == IND_OLDGEN ||
163          get_itbl(q)->type == IND_PERM ||
164          get_itbl(q)->type == IND_OLDGEN_PERM ) {
165       q = ((StgInd *)q)->indirectee;
166   }
167   return q;
168 }
169
170 static StgWord
171 lookupStableName_(StgPtr p)
172 {
173   StgWord sn;
174   void* sn_tmp;
175
176   if (stable_ptr_free == NULL) {
177     enlargeStablePtrTable();
178   }
179
180   /* removing indirections increases the likelihood
181    * of finding a match in the stable name hash table.
182    */
183   p = (StgPtr)removeIndirections((StgClosure*)p);
184
185   sn_tmp = lookupHashTable(addrToStableHash,(W_)p);
186   sn = (StgWord)sn_tmp;
187   
188   if (sn != 0) {
189     ASSERT(stable_ptr_table[sn].addr == p);
190     IF_DEBUG(stable,debugBelch("cached stable name %ld at %p\n",sn,p));
191     RELEASE_LOCK(&stable_mutex);
192     return sn;
193   } else {
194     sn = stable_ptr_free - stable_ptr_table;
195     stable_ptr_free  = (snEntry*)(stable_ptr_free->addr);
196     stable_ptr_table[sn].ref = 0;
197     stable_ptr_table[sn].addr = p;
198     stable_ptr_table[sn].sn_obj = NULL;
199     /* IF_DEBUG(stable,debugBelch("new stable name %d at %p\n",sn,p)); */
200     
201     /* add the new stable name to the hash table */
202     insertHashTable(addrToStableHash, (W_)p, (void *)sn);
203
204     return sn;
205   }
206 }
207
208 StgWord
209 lookupStableName(StgPtr p)
210 {
211     StgWord res;
212     ACQUIRE_LOCK(&stable_mutex);
213     res = lookupStableName_(p);
214     RELEASE_LOCK(&stable_mutex);
215     return res;
216 }
217
218 STATIC_INLINE void
219 freeStableName(snEntry *sn)
220 {
221   ASSERT(sn->sn_obj == NULL);
222   if (sn->addr != NULL) {
223       removeHashTable(addrToStableHash, (W_)sn->addr, NULL);
224   }
225   sn->addr = (P_)stable_ptr_free;
226   stable_ptr_free = sn;
227 }
228
229 StgStablePtr
230 getStablePtr(StgPtr p)
231 {
232   StgWord sn;
233
234   ACQUIRE_LOCK(&stable_mutex);
235   sn = lookupStableName_(p);
236   stable_ptr_table[sn].ref++;
237   RELEASE_LOCK(&stable_mutex);
238   return (StgStablePtr)(sn);
239 }
240
241 void
242 freeStablePtr(StgStablePtr sp)
243 {
244     snEntry *sn;
245
246     ACQUIRE_LOCK(&stable_mutex);
247
248     sn = &stable_ptr_table[(StgWord)sp];
249     
250     ASSERT((StgWord)sp < SPT_size  &&  sn->addr != NULL  &&  sn->ref > 0);
251
252     sn->ref--;
253
254     // If this entry has no StableName attached, then just free it
255     // immediately.  This is important; it might be a while before the
256     // next major GC which actually collects the entry.
257     if (sn->sn_obj == NULL && sn->ref == 0) {
258         freeStableName(sn);
259     }
260
261     RELEASE_LOCK(&stable_mutex);
262 }
263
264 void
265 enlargeStablePtrTable(void)
266 {
267   nat old_SPT_size = SPT_size;
268   
269   if (SPT_size == 0) {
270     // 1st time
271     SPT_size = INIT_SPT_SIZE;
272     stable_ptr_table = stgMallocBytes(SPT_size * sizeof(snEntry), 
273                                       "enlargeStablePtrTable");
274     
275     /* we don't use index 0 in the stable name table, because that
276      * would conflict with the hash table lookup operations which
277      * return NULL if an entry isn't found in the hash table.
278      */
279     initFreeList(stable_ptr_table+1,INIT_SPT_SIZE-1,NULL);
280     addrToStableHash = allocHashTable();
281   }
282   else {
283     // 2nd and subsequent times
284     SPT_size *= 2;
285     stable_ptr_table = 
286       stgReallocBytes(stable_ptr_table, 
287                       SPT_size * sizeof(snEntry),
288                       "enlargeStablePtrTable");
289
290     initFreeList(stable_ptr_table + old_SPT_size, old_SPT_size, NULL);
291   }
292 }
293
294 /* -----------------------------------------------------------------------------
295  * Treat stable pointers as roots for the garbage collector.
296  *
297  * A stable pointer is any stable name entry with a ref > 0.  We'll
298  * take the opportunity to zero the "keep" flags at the same time.
299  * -------------------------------------------------------------------------- */
300
301 void
302 markStablePtrTable(evac_fn evac)
303 {
304     snEntry *p, *end_stable_ptr_table;
305     StgPtr q;
306     
307     end_stable_ptr_table = &stable_ptr_table[SPT_size];
308     
309     // Mark all the stable *pointers* (not stable names).
310     // _starting_ at index 1; index 0 is unused.
311     for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
312         q = p->addr;
313
314         // Internal pointers are free slots.  If q == NULL, it's a
315         // stable name where the object has been GC'd, but the
316         // StableName object (sn_obj) is still alive.
317         if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
318
319             // save the current addr away: we need to be able to tell
320             // whether the objects moved in order to be able to update
321             // the hash table later.
322             p->old = p->addr;
323
324             // if the ref is non-zero, treat addr as a root
325             if (p->ref != 0) {
326                 evac((StgClosure **)&p->addr);
327             }
328         }
329     }
330 }
331
332 /* -----------------------------------------------------------------------------
333  * Thread the stable pointer table for compacting GC.
334  * 
335  * Here we must call the supplied evac function for each pointer into
336  * the heap from the stable pointer table, because the compacting
337  * collector may move the object it points to.
338  * -------------------------------------------------------------------------- */
339
340 void
341 threadStablePtrTable( evac_fn evac )
342 {
343     snEntry *p, *end_stable_ptr_table;
344     StgPtr q;
345     
346     end_stable_ptr_table = &stable_ptr_table[SPT_size];
347     
348     for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
349         
350         if (p->sn_obj != NULL) {
351             evac((StgClosure **)&p->sn_obj);
352         }
353
354         q = p->addr;
355         if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
356             evac((StgClosure **)&p->addr);
357         }
358     }
359 }
360
361 /* -----------------------------------------------------------------------------
362  * Garbage collect any dead entries in the stable pointer table.
363  *
364  * A dead entry has:
365  *
366  *          - a zero reference count
367  *          - a dead sn_obj
368  *
369  * Both of these conditions must be true in order to re-use the stable
370  * name table entry.  We can re-use stable name table entries for live
371  * heap objects, as long as the program has no StableName objects that
372  * refer to the entry.
373  * -------------------------------------------------------------------------- */
374
375 void
376 gcStablePtrTable( void )
377 {
378     snEntry *p, *end_stable_ptr_table;
379     StgPtr q;
380     
381     end_stable_ptr_table = &stable_ptr_table[SPT_size];
382     
383     // NOTE: _starting_ at index 1; index 0 is unused.
384     for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
385         
386         // Update the pointer to the StableName object, if there is one
387         if (p->sn_obj != NULL) {
388             p->sn_obj = isAlive(p->sn_obj);
389         }
390         
391         // Internal pointers are free slots.  If q == NULL, it's a
392         // stable name where the object has been GC'd, but the
393         // StableName object (sn_obj) is still alive.
394         q = p->addr;
395         if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
396
397             // StableNames only:
398             if (p->ref == 0) {
399                 if (p->sn_obj == NULL) {
400                     // StableName object is dead
401                     freeStableName(p);
402                     IF_DEBUG(stable, debugBelch("GC'd Stable name %ld\n", 
403                                                 p - stable_ptr_table));
404                     continue;
405                     
406                 } else {
407                   p->addr = (StgPtr)isAlive((StgClosure *)p->addr);
408                     IF_DEBUG(stable, debugBelch("Stable name %ld still alive at %p, ref %ld\n", p - stable_ptr_table, p->addr, p->ref));
409                 }
410             }
411         }
412     }
413 }
414
415 /* -----------------------------------------------------------------------------
416  * Update the StablePtr/StableName hash table
417  *
418  * The boolean argument 'full' indicates that a major collection is
419  * being done, so we might as well throw away the hash table and build
420  * a new one.  For a minor collection, we just re-hash the elements
421  * that changed.
422  * -------------------------------------------------------------------------- */
423
424 void
425 updateStablePtrTable(rtsBool full)
426 {
427     snEntry *p, *end_stable_ptr_table;
428     
429     if (full && addrToStableHash != NULL) {
430         freeHashTable(addrToStableHash,NULL);
431         addrToStableHash = allocHashTable();
432     }
433     
434     end_stable_ptr_table = &stable_ptr_table[SPT_size];
435     
436     // NOTE: _starting_ at index 1; index 0 is unused.
437     for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
438         
439         if (p->addr == NULL) {
440             if (p->old != NULL) {
441                 // The target has been garbage collected.  Remove its
442                 // entry from the hash table.
443                 removeHashTable(addrToStableHash, (W_)p->old, NULL);
444                 p->old = NULL;
445             }
446         }
447         else if (p->addr < (P_)stable_ptr_table 
448                  || p->addr >= (P_)end_stable_ptr_table) {
449             // Target still alive, Re-hash this stable name 
450             if (full) {
451                 insertHashTable(addrToStableHash, (W_)p->addr, 
452                                 (void *)(p - stable_ptr_table));
453             } else if (p->addr != p->old) {
454                 removeHashTable(addrToStableHash, (W_)p->old, NULL);
455                 insertHashTable(addrToStableHash, (W_)p->addr, 
456                                 (void *)(p - stable_ptr_table));
457             }
458         }
459     }
460 }