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