1 /* -----------------------------------------------------------------------------
2 * $Id: Stable.c,v 1.15 2001/07/23 17:23:19 simonmar Exp $
4 * (c) The GHC Team, 1998-1999
6 * Stable names and stable pointers.
8 * ---------------------------------------------------------------------------*/
12 #include "StablePriv.h"
18 /* Comment from ADR's implementation in old RTS:
20 This files (together with @ghc/runtime/storage/PerformIO.lhc@ and a
21 small change in @HpOverflow.lc@) consists of the changes in the
22 runtime system required to implement "Stable Pointers". But we're
23 getting a bit ahead of ourselves --- what is a stable pointer and what
26 When Haskell calls C, it normally just passes over primitive integers,
27 floats, bools, strings, etc. This doesn't cause any problems at all
28 for garbage collection because the act of passing them makes a copy
29 from the heap, stack or wherever they are onto the C-world stack.
30 However, if we were to pass a heap object such as a (Haskell) @String@
31 and a garbage collection occured before we finished using it, we'd run
32 into problems since the heap object might have been moved or even
35 So, if a C call is able to cause a garbage collection or we want to
36 store a pointer to a heap object between C calls, we must be careful
37 when passing heap objects. Our solution is to keep a table of all
38 objects we've given to the C-world and to make sure that the garbage
39 collector collects these objects --- updating the table as required to
40 make sure we can still find the object.
43 Of course, all this rather begs the question: why would we want to
46 One very good reason is to preserve laziness across the language
47 interface. Rather than evaluating an integer or a string because it
48 {\em might\/} be required by the C function, we can wait until the C
49 function actually wants the value and then force an evaluation.
51 Another very good reason (the motivating reason!) is that the C code
52 might want to execute an object of sort $IO ()$ for the side-effects
53 it will produce. For example, this is used when interfacing to an X
54 widgets library to allow a direct implementation of callbacks.
57 The @makeStablePointer :: a -> IO (StablePtr a)@ function
58 converts a value into a stable pointer. It is part of the @PrimIO@
59 monad, because we want to be sure we don't allocate one twice by
60 accident, and then only free one of the copies.
63 makeStablePtr# :: a -> State# RealWorld -> (# RealWorld, a #)
64 freeStablePtr# :: StablePtr# a -> State# RealWorld -> State# RealWorld
65 deRefStablePtr# :: StablePtr# a -> State# RealWorld ->
66 (# State# RealWorld, a #)
69 There may be additional functions on the C side to allow evaluation,
70 application, etc of a stable pointer.
72 When Haskell calls C, it normally just passes over primitive integers,
73 floats, bools, strings, etc. This doesn't cause any problems at all
74 for garbage collection because the act of passing them makes a copy
75 from the heap, stack or wherever they are onto the C-world stack.
76 However, if we were to pass a heap object such as a (Haskell) @String@
77 and a garbage collection occured before we finished using it, we'd run
78 into problems since the heap object might have been moved or even
81 So, if a C call is able to cause a garbage collection or we want to
82 store a pointer to a heap object between C calls, we must be careful
83 when passing heap objects. Our solution is to keep a table of all
84 objects we've given to the C-world and to make sure that the garbage
85 collector collects these objects --- updating the table as required to
86 make sure we can still find the object.
89 snEntry *stable_ptr_table;
90 snEntry *stable_ptr_free;
92 unsigned int SPT_size;
94 /* This hash table maps Haskell objects to stable names, so that every
95 * call to lookupStableName on a given object will return the same
100 * A plain stable name entry has a zero reference count, which means
101 * the entry will dissappear when the object it points to is
102 * unreachable. For stable pointers, we need an entry that sticks
103 * around and keeps the object it points to alive, so each stable name
104 * entry has an associated reference count.
106 * A stable pointer has a weighted reference count N attached to it
107 * (actually in its upper 5 bits), which represents the weight
108 * 2^(N-1). The stable name entry keeps a 32-bit reference count, which
109 * represents any weight between 1 and 2^32 (represented as zero).
110 * When the weight is 2^32, the stable name table owns "all" of the
111 * stable pointers to this object, and the entry can be garbage
112 * collected if the object isn't reachable.
114 * A new stable pointer is given the weight log2(W/2), where W is the
115 * weight stored in the table entry. The new weight in the table is W
118 * A stable pointer can be "split" into two stable pointers, by
119 * dividing the weight by 2 and giving each pointer half.
120 * When freeing a stable pointer, the weight of the pointer is added
121 * to the weight stored in the table entry.
124 HashTable *addrToStableHash;
126 #define INIT_SPT_SIZE 64
129 initFreeList(snEntry *table, nat n, snEntry *free)
133 for (p = table + n - 1; p >= table; p--) {
140 stable_ptr_free = table;
144 initStablePtrTable(void)
146 /* the table will be allocated the first time makeStablePtr is
148 stable_ptr_table = NULL;
149 stable_ptr_free = NULL;
150 addrToStableHash = NULL;
155 * get at the real stuff...remove indirections.
157 * ToDo: move to a better home.
161 removeIndirections(StgClosure* p)
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;
176 lookupStableName(StgPtr p)
180 if (stable_ptr_free == NULL) {
181 enlargeStablePtrTable();
184 /* removing indirections increases the likelihood
185 * of finding a match in the stable name hash table.
187 p = (StgPtr)removeIndirections((StgClosure*)p);
189 (void *)sn = lookupHashTable(addrToStableHash,(W_)p);
192 ASSERT(stable_ptr_table[sn].addr == p);
193 IF_DEBUG(stable,fprintf(stderr,"cached stable name %d at %p\n",sn,p));
196 sn = stable_ptr_free - stable_ptr_table;
197 (P_)stable_ptr_free = stable_ptr_free->addr;
198 stable_ptr_table[sn].weight = 0;
199 stable_ptr_table[sn].addr = p;
200 stable_ptr_table[sn].sn_obj = NULL;
201 /* IF_DEBUG(stable,fprintf(stderr,"new stable name %d at
204 /* add the new stable name to the hash table */
205 insertHashTable(addrToStableHash, (W_)p, (void *)sn);
212 freeStableName(snEntry *sn)
214 ASSERT(sn->sn_obj == NULL);
215 if (sn->addr != NULL) {
216 removeHashTable(addrToStableHash, (W_)sn->addr, NULL);
218 sn->addr = (P_)stable_ptr_free;
219 stable_ptr_free = sn;
223 getStablePtr(StgPtr p)
225 StgWord sn = lookupStableName(p);
227 weight = stable_ptr_table[sn].weight;
229 weight = (StgWord)1 << (BITS_IN(StgWord)-1);
230 stable_ptr_table[sn].weight = weight;
231 return (StgStablePtr)(sn + (BITS_IN(StgWord) << STABLEPTR_WEIGHT_SHIFT));
233 else if (weight == 1) {
234 barf("getStablePtr: too light");
238 /* find log2(weight) */
239 for (n = 0; weight != 1; n++) {
242 stable_ptr_table[sn].weight -= 1 << n;
243 return (StgStablePtr)(sn + ((n+1) << STABLEPTR_WEIGHT_SHIFT));
248 enlargeStablePtrTable(void)
250 nat old_SPT_size = SPT_size;
254 SPT_size = INIT_SPT_SIZE;
255 stable_ptr_table = stgMallocWords(SPT_size * sizeof(snEntry),
256 "initStablePtrTable");
258 /* we don't use index 0 in the stable name table, because that
259 * would conflict with the hash table lookup operations which
260 * return NULL if an entry isn't found in the hash table.
262 initFreeList(stable_ptr_table+1,INIT_SPT_SIZE-1,NULL);
263 addrToStableHash = allocHashTable();
266 // 2nd and subsequent times
269 stgReallocWords(stable_ptr_table, SPT_size * sizeof(snEntry),
270 "enlargeStablePtrTable");
272 initFreeList(stable_ptr_table + old_SPT_size, old_SPT_size, NULL);
276 /* -----------------------------------------------------------------------------
277 * Treat stable pointers as roots for the garbage collector.
279 * A stable pointer is any stable name entry with a weight > 0. We'll
280 * take the opportunity to zero the "keep" flags at the same time.
281 * -------------------------------------------------------------------------- */
284 markStablePtrTable(evac_fn evac)
286 snEntry *p, *end_stable_ptr_table;
289 end_stable_ptr_table = &stable_ptr_table[SPT_size];
291 // Mark all the stable *pointers* (not stable names).
292 // _starting_ at index 1; index 0 is unused.
293 for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
296 // internal pointers or NULL are free slots
297 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
299 // save the current addr away: we need to be able to tell
300 // whether the objects moved in order to be able to update
301 // the hash table later.
304 // if the weight is non-zero, treat addr as a root
305 if (p->weight != 0) {
306 evac((StgClosure **)&p->addr);
312 /* -----------------------------------------------------------------------------
313 * Thread the stable pointer table for compacting GC.
315 * Here we must call the supplied evac function for each pointer into
316 * the heap from the stable pointer table, because the compacting
317 * collector may move the object it points to.
318 * -------------------------------------------------------------------------- */
321 threadStablePtrTable( evac_fn evac )
323 snEntry *p, *end_stable_ptr_table;
326 end_stable_ptr_table = &stable_ptr_table[SPT_size];
328 for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
331 // internal pointers or NULL are free slots
332 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
333 if (p->weight != 0) {
334 evac((StgClosure **)&p->addr);
336 if (p->sn_obj != NULL) {
337 evac((StgClosure **)&p->sn_obj);
343 /* -----------------------------------------------------------------------------
344 * Garbage collect any dead entries in the stable pointer table.
348 * - a weight of zero (i.e. 2^32)
351 * Both of these conditions must be true in order to re-use the stable
352 * name table entry. We can re-use stable name table entries for live
353 * heap objects, as long as the program has no StableName objects that
354 * refer to the entry.
355 * -------------------------------------------------------------------------- */
358 gcStablePtrTable( void )
360 snEntry *p, *end_stable_ptr_table;
363 end_stable_ptr_table = &stable_ptr_table[SPT_size];
365 // NOTE: _starting_ at index 1; index 0 is unused.
366 for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
368 // Update the pointer to the StableName object, if there is one
369 if (p->sn_obj != NULL) {
370 p->sn_obj = isAlive(p->sn_obj);
374 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
377 if (p->weight == 0) {
378 if (p->sn_obj == NULL) {
379 // StableName object is dead
381 IF_DEBUG(stable, fprintf(stderr,"GC'd Stable name %d\n",
382 p - stable_ptr_table));
386 (StgClosure *)p->addr = isAlive((StgClosure *)p->addr);
387 IF_DEBUG(stable, fprintf(stderr,"Stable name %d still alive at %p, weight %d\n", p - stable_ptr_table, p->addr, p->weight));
394 /* -----------------------------------------------------------------------------
395 * Update the StablePtr/StableName hash table
397 * The boolean argument 'full' indicates that a major collection is
398 * being done, so we might as well throw away the hash table and build
399 * a new one. For a minor collection, we just re-hash the elements
401 * -------------------------------------------------------------------------- */
404 updateStablePtrTable(rtsBool full)
406 snEntry *p, *end_stable_ptr_table;
408 if (full && addrToStableHash != NULL) {
409 freeHashTable(addrToStableHash,NULL);
410 addrToStableHash = allocHashTable();
413 end_stable_ptr_table = &stable_ptr_table[SPT_size];
415 // NOTE: _starting_ at index 1; index 0 is unused.
416 for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
418 if (p->addr == NULL) {
419 if (p->old != NULL) {
420 // The target has been garbage collected. Remove its
421 // entry from the hash table.
422 removeHashTable(addrToStableHash, (W_)p->old, NULL);
426 else if (p->addr < (P_)stable_ptr_table
427 || p->addr >= (P_)end_stable_ptr_table) {
428 // Target still alive, Re-hash this stable name
430 insertHashTable(addrToStableHash, (W_)p->addr,
431 (void *)(p - stable_ptr_table));
432 } else if (p->addr != p->old) {
433 removeHashTable(addrToStableHash, (W_)p->old, NULL);
434 insertHashTable(addrToStableHash, (W_)p->addr,
435 (void *)(p - stable_ptr_table));