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