2 * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3 * Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
5 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
6 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
8 * Permission is hereby granted to use or copy this program
9 * for any purpose, provided the above notices are retained on all copies.
10 * Permission to modify the code and to distribute modified code is granted,
11 * provided the above notices are retained, and a notice that the code was
12 * modified is included with the above copyright notice.
15 /* Boehm, February 16, 1996 2:26 pm PST */
23 # include <sys/types.h>
27 * Separate free lists are maintained for different sized objects
29 * The call GC_allocobj(i,k) ensures that the freelist for
30 * kind k objects of size i points to a non-empty
31 * free list. It returns a pointer to the first entry on the free list.
32 * In a single-threaded world, GC_allocobj may be called to allocate
33 * an object of (small) size i as follows:
35 * opp = &(GC_objfreelist[i]);
36 * if (*opp == 0) GC_allocobj(i, NORMAL);
38 * *opp = obj_link(ptr);
40 * Note that this is very fast if the free list is non-empty; it should
41 * only involve the execution of 4 or 5 simple instructions.
42 * All composite objects on freelists are cleared, except for
47 * The allocator uses GC_allochblk to allocate large chunks of objects.
48 * These chunks all start on addresses which are multiples of
49 * HBLKSZ. Each allocated chunk has an associated header,
50 * which can be located quickly based on the address of the chunk.
51 * (See headers.c for details.)
52 * This makes it possible to check quickly whether an
53 * arbitrary address corresponds to an object administered by the
57 word GC_non_gc_bytes
= 0; /* Number of bytes not intended to be collected */
61 int GC_incremental
= 0; /* By default, stop the world. */
63 int GC_full_freq
= 4; /* Every 5th collection is a full */
66 char * GC_copyright
[] =
67 {"Copyright 1988,1989 Hans-J. Boehm and Alan J. Demers ",
68 "Copyright (c) 1991-1995 by Xerox Corporation. All rights reserved. ",
69 "Copyright (c) 1996-1997 by Silicon Graphics. All rights reserved. ",
70 "THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY",
71 " EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.",
72 "See source code for details." };
76 /* some more variables */
78 extern signed_word GC_mem_found
; /* Number of reclaimed longwords */
79 /* after garbage collection */
81 GC_bool GC_dont_expand
= 0;
83 word GC_free_space_divisor
= 4;
85 extern GC_bool
GC_collection_in_progress();
87 int GC_never_stop_func
GC_PROTO((void)) { return(0); }
89 CLOCK_TYPE GC_start_time
;
91 int GC_timeout_stop_func
GC_PROTO((void))
93 CLOCK_TYPE current_time
;
94 static unsigned count
= 0;
95 unsigned long time_diff
;
97 if ((count
++ & 3) != 0) return(0);
99 GET_TIME(current_time
);
100 time_diff
= MS_TIME_DIFF(current_time
,GC_start_time
);
101 if (time_diff
>= TIME_LIMIT
) {
103 GC_printf0("Abandoning stopped marking after ");
104 GC_printf1("%lu msecs\n", (unsigned long)time_diff
);
112 /* Return the minimum number of words that must be allocated between */
113 /* collections to amortize the collection cost. */
114 static word
min_words_allocd()
117 /* We punt, for now. */
118 register signed_word stack_size
= 10000;
121 register signed_word stack_size
= (ptr_t
)(&dummy
) - GC_stackbottom
;
123 register word total_root_size
; /* includes double stack size, */
124 /* since the stack is expensive */
127 if (stack_size
< 0) stack_size
= -stack_size
;
128 total_root_size
= 2 * stack_size
+ GC_root_size
;
129 if (GC_incremental
) {
130 return(BYTES_TO_WORDS(GC_heapsize
+ total_root_size
)
131 / (2 * GC_free_space_divisor
));
133 return(BYTES_TO_WORDS(GC_heapsize
+ total_root_size
)
134 / GC_free_space_divisor
);
138 /* Return the number of words allocated, adjusted for explicit storage */
139 /* management, etc.. This number is used in deciding when to trigger */
141 word
GC_adj_words_allocd()
143 register signed_word result
;
144 register signed_word expl_managed
=
145 BYTES_TO_WORDS((long)GC_non_gc_bytes
146 - (long)GC_non_gc_bytes_at_gc
);
148 /* Don't count what was explicitly freed, or newly allocated for */
149 /* explicit management. Note that deallocating an explicitly */
150 /* managed object should not alter result, assuming the client */
151 /* is playing by the rules. */
152 result
= (signed_word
)GC_words_allocd
153 - (signed_word
)GC_mem_freed
- expl_managed
;
154 if (result
> (signed_word
)GC_words_allocd
) {
155 result
= GC_words_allocd
;
156 /* probably client bug or unfortunate scheduling */
158 result
+= GC_words_finalized
;
159 /* We count objects enqueued for finalization as though they */
160 /* had been reallocated this round. Finalization is user */
161 /* visible progress. And if we don't count this, we have */
162 /* stability problems for programs that finalize all objects. */
163 result
+= GC_words_wasted
;
164 /* This doesn't reflect useful work. But if there is lots of */
165 /* new fragmentation, the same is probably true of the heap, */
166 /* and the collection will be correspondingly cheaper. */
167 if (result
< (signed_word
)(GC_words_allocd
>> 3)) {
168 /* Always count at least 1/8 of the allocations. We don't want */
169 /* to collect too infrequently, since that would inhibit */
170 /* coalescing of free storage blocks. */
171 /* This also makes us partially robust against client bugs. */
172 return(GC_words_allocd
>> 3);
179 /* Clear up a few frames worth of garbage left at the top of the stack. */
180 /* This is used to prevent us from accidentally treating garbade left */
181 /* on the stack by other parts of the collector as roots. This */
182 /* differs from the code in misc.c, which actually tries to keep the */
183 /* stack clear of long-lived, client-generated garbage. */
184 void GC_clear_a_few_frames()
190 for (i
= 0; i
< NWORDS
; i
++) frames
[i
] = 0;
193 /* Have we allocated enough to amortize a collection? */
194 GC_bool
GC_should_collect()
196 return(GC_adj_words_allocd() >= min_words_allocd());
199 void GC_notify_full_gc()
201 if (GC_start_call_back
!= (void (*)())0) {
202 (*GC_start_call_back
)();
207 * Initiate a garbage collection if appropriate.
209 * between partial, full, and stop-world collections.
210 * Assumes lock held, signals disabled.
214 static int n_partial_gcs
= 0;
215 if (GC_should_collect()) {
216 if (!GC_incremental
) {
221 } else if (n_partial_gcs
>= GC_full_freq
) {
224 "***>Full mark for collection %lu after %ld allocd bytes\n",
225 (unsigned long) GC_gc_no
+1,
226 (long)WORDS_TO_BYTES(GC_words_allocd
));
228 GC_promote_black_lists();
229 (void)GC_reclaim_all((GC_stop_func
)0, TRUE
);
236 /* We try to mark with the world stopped. */
237 /* If we run out of time, this turns into */
238 /* incremental marking. */
240 GET_TIME(GC_start_time
);
242 if (GC_stopped_mark(GC_timeout_stop_func
)) {
243 # ifdef SAVE_CALL_CHAIN
244 GC_save_callers(GC_last_stack
);
246 GC_finish_collection();
253 * Stop the world garbage collection. Assumes lock held, signals disabled.
254 * If stop_func is not GC_never_stop_func, then abort if stop_func returns TRUE.
256 GC_bool
GC_try_to_collect_inner(stop_func
)
257 GC_stop_func stop_func
;
259 if (GC_collection_in_progress()) {
262 "GC_try_to_collect_inner: finishing collection in progress\n");
263 # endif /* PRINTSTATS */
264 /* Just finish collection already in progress. */
265 while(GC_collection_in_progress()) {
266 if (stop_func()) return(FALSE
);
267 GC_collect_a_little_inner(1);
272 "Initiating full world-stop collection %lu after %ld allocd bytes\n",
273 (unsigned long) GC_gc_no
+1,
274 (long)WORDS_TO_BYTES(GC_words_allocd
));
276 GC_promote_black_lists();
277 /* Make sure all blocks have been reclaimed, so sweep routines */
278 /* don't see cleared mark bits. */
279 /* If we're guaranteed to finish, then this is unnecessary. */
280 if (stop_func
!= GC_never_stop_func
281 && !GC_reclaim_all(stop_func
, FALSE
)) {
282 /* Aborted. So far everything is still consistent. */
285 GC_invalidate_mark_state(); /* Flush mark stack. */
287 # ifdef SAVE_CALL_CHAIN
288 GC_save_callers(GC_last_stack
);
290 if (!GC_stopped_mark(stop_func
)) {
291 if (!GC_incremental
) {
292 /* We're partially done and have no way to complete or use */
293 /* current work. Reestablish invariants as cheaply as */
295 GC_invalidate_mark_state();
296 GC_unpromote_black_lists();
297 } /* else we claim the world is already still consistent. We'll */
298 /* finish incrementally. */
301 GC_finish_collection();
308 * Perform n units of garbage collection work. A unit is intended to touch
309 * roughly a GC_RATE pages. Every once in a while, we do more than that.
313 int GC_deficit
= 0; /* The number of extra calls to GC_mark_some */
314 /* that we have made. */
315 /* Negative values are equivalent to 0. */
317 void GC_collect_a_little_inner(n
)
322 if (GC_collection_in_progress()) {
323 for (i
= GC_deficit
; i
< GC_RATE
*n
; i
++) {
324 if (GC_mark_some()) {
325 /* Need to finish a collection */
326 # ifdef SAVE_CALL_CHAIN
327 GC_save_callers(GC_last_stack
);
329 (void) GC_stopped_mark(GC_never_stop_func
);
330 GC_finish_collection();
334 if (GC_deficit
> 0) GC_deficit
-= GC_RATE
*n
;
340 int GC_collect_a_little
GC_PROTO(())
347 GC_collect_a_little_inner(1);
348 result
= (int)GC_collection_in_progress();
355 * Assumes lock is held, signals are disabled.
357 * If final is TRUE, then we finish the collection, no matter how long
359 * Otherwise we may fail and return FALSE if this takes too long.
360 * Increment GC_gc_no if we succeed.
362 GC_bool
GC_stopped_mark(stop_func
)
363 GC_stop_func stop_func
;
367 CLOCK_TYPE start_time
, current_time
;
372 GET_TIME(start_time
);
373 GC_printf1("--> Marking for collection %lu ",
374 (unsigned long) GC_gc_no
+ 1);
375 GC_printf2("after %lu allocd bytes + %lu wasted bytes\n",
376 (unsigned long) WORDS_TO_BYTES(GC_words_allocd
),
377 (unsigned long) WORDS_TO_BYTES(GC_words_wasted
));
380 /* Mark from all roots. */
381 /* Minimize junk left in my registers and on the stack */
382 GC_clear_a_few_frames();
383 GC_noop(0,0,0,0,0,0);
386 if ((*stop_func
)()) {
388 GC_printf0("Abandoned stopped marking after ");
389 GC_printf1("%lu iterations\n",
392 GC_deficit
= i
; /* Give the mutator a chance. */
396 if (GC_mark_some()) break;
401 GC_printf2("Collection %lu reclaimed %ld bytes",
402 (unsigned long) GC_gc_no
- 1,
403 (long)WORDS_TO_BYTES(GC_mem_found
));
404 GC_printf1(" ---> heapsize = %lu bytes\n",
405 (unsigned long) GC_heapsize
);
406 /* Printf arguments may be pushed in funny places. Clear the */
411 /* Check all debugged objects for consistency */
412 if (GC_debugging_started
) {
417 GET_TIME(current_time
);
418 GC_printf1("World-stopped marking took %lu msecs\n",
419 MS_TIME_DIFF(current_time
,start_time
));
426 /* Finish up a collection. Assumes lock is held, signals are disabled, */
427 /* but the world is otherwise running. */
428 void GC_finish_collection()
431 CLOCK_TYPE start_time
;
432 CLOCK_TYPE finalize_time
;
433 CLOCK_TYPE done_time
;
435 GET_TIME(start_time
);
436 finalize_time
= start_time
;
443 /* Mark all objects on the free list. All objects should be */
444 /* marked when we're done. */
446 register word size
; /* current object size */
447 register ptr_t p
; /* pointer to current object */
448 register struct hblk
* h
; /* pointer to block containing *p */
450 register int word_no
; /* "index" of *p in *q */
453 for (kind
= 0; kind
< GC_n_kinds
; kind
++) {
454 for (size
= 1; size
<= MAXOBJSZ
; size
++) {
455 for (p
= GC_obj_kinds
[kind
].ok_freelist
[size
];
456 p
!= 0; p
=obj_link(p
)){
459 word_no
= (((word
*)p
) - ((word
*)h
));
460 set_mark_bit_from_hdr(hhdr
, word_no
);
465 /* Check that everything is marked */
466 GC_start_reclaim(TRUE
);
470 # ifdef STUBBORN_ALLOC
471 GC_clean_changing_list();
475 GET_TIME(finalize_time
);
478 /* Clear free list mark bits, in case they got accidentally marked */
479 /* Note: HBLKPTR(p) == pointer to head of block containing *p */
480 /* Also subtract memory remaining from GC_mem_found count. */
481 /* Note that composite objects on free list are cleared. */
482 /* Thus accidentally marking a free list is not a problem; only */
483 /* objects on the list itself will be marked, and that's fixed here. */
485 register word size
; /* current object size */
486 register ptr_t p
; /* pointer to current object */
487 register struct hblk
* h
; /* pointer to block containing *p */
489 register int word_no
; /* "index" of *p in *q */
492 for (kind
= 0; kind
< GC_n_kinds
; kind
++) {
493 for (size
= 1; size
<= MAXOBJSZ
; size
++) {
494 for (p
= GC_obj_kinds
[kind
].ok_freelist
[size
];
495 p
!= 0; p
=obj_link(p
)){
498 word_no
= (((word
*)p
) - ((word
*)h
));
499 clear_mark_bit_from_hdr(hhdr
, word_no
);
501 GC_mem_found
-= size
;
510 GC_printf1("Bytes recovered before sweep - f.l. count = %ld\n",
511 (long)WORDS_TO_BYTES(GC_mem_found
));
514 /* Reconstruct free lists to contain everything not marked */
515 GC_start_reclaim(FALSE
);
517 # endif /* !FIND_LEAK */
521 "Immediately reclaimed %ld bytes in heap of size %lu bytes\n",
522 (long)WORDS_TO_BYTES(GC_mem_found
),
523 (unsigned long)GC_heapsize
);
524 GC_printf2("%lu (atomic) + %lu (composite) collectable bytes in use\n",
525 (unsigned long)WORDS_TO_BYTES(GC_atomic_in_use
),
526 (unsigned long)WORDS_TO_BYTES(GC_composite_in_use
));
529 /* Reset or increment counters for next cycle */
530 GC_words_allocd_before_gc
+= GC_words_allocd
;
531 GC_non_gc_bytes_at_gc
= GC_non_gc_bytes
;
538 GC_printf2("Finalize + initiate sweep took %lu + %lu msecs\n",
539 MS_TIME_DIFF(finalize_time
,start_time
),
540 MS_TIME_DIFF(done_time
,finalize_time
));
544 /* Externally callable routine to invoke full, stop-world collection */
545 # if defined(__STDC__) || defined(__cplusplus)
546 int GC_try_to_collect(GC_stop_func stop_func
)
548 int GC_try_to_collect(stop_func
)
549 GC_stop_func stop_func
;
555 GC_INVOKE_FINALIZERS();
559 if (!GC_is_initialized
) GC_init_inner();
560 /* Minimize junk left in my registers */
561 GC_noop(0,0,0,0,0,0);
562 result
= (int)GC_try_to_collect_inner(stop_func
);
566 if(result
) GC_INVOKE_FINALIZERS();
570 void GC_gcollect
GC_PROTO(())
573 (void)GC_try_to_collect(GC_never_stop_func
);
576 word GC_n_heap_sects
= 0; /* Number of sections currently in heap. */
579 * Use the chunk of memory starting at p of syze bytes as part of the heap.
580 * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
582 void GC_add_to_heap(p
, bytes
)
588 if (GC_n_heap_sects
>= MAX_HEAP_SECTS
) {
589 ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
591 if (!GC_install_header(p
)) {
592 /* This is extremely unlikely. Can't add it. This will */
593 /* almost certainly result in a 0 return from the allocator, */
594 /* which is entirely appropriate. */
597 GC_heap_sects
[GC_n_heap_sects
].hs_start
= (ptr_t
)p
;
598 GC_heap_sects
[GC_n_heap_sects
].hs_bytes
= bytes
;
600 words
= BYTES_TO_WORDS(bytes
- HDR_BYTES
);
601 HDR(p
) -> hb_sz
= words
;
603 GC_heapsize
+= bytes
;
604 if ((ptr_t
)p
<= GC_least_plausible_heap_addr
605 || GC_least_plausible_heap_addr
== 0) {
606 GC_least_plausible_heap_addr
= (ptr_t
)p
- sizeof(word
);
607 /* Making it a little smaller than necessary prevents */
608 /* us from getting a false hit from the variable */
609 /* itself. There's some unintentional reflection */
612 if ((ptr_t
)p
+ bytes
>= GC_greatest_plausible_heap_addr
) {
613 GC_greatest_plausible_heap_addr
= (ptr_t
)p
+ bytes
;
618 GC_bool
GC_in_last_heap_sect(p
)
621 struct HeapSect
* last_heap_sect
= &(GC_heap_sects
[GC_n_heap_sects
-1]);
622 ptr_t start
= last_heap_sect
-> hs_start
;
625 if (p
< start
) return FALSE
;
626 end
= start
+ last_heap_sect
-> hs_bytes
;
627 if (p
>= end
) return FALSE
;
632 # if !defined(NO_DEBUGGING)
633 void GC_print_heap_sects()
637 GC_printf1("Total heap size: %lu\n", (unsigned long) GC_heapsize
);
638 for (i
= 0; i
< GC_n_heap_sects
; i
++) {
639 unsigned long start
= (unsigned long) GC_heap_sects
[i
].hs_start
;
640 unsigned long len
= (unsigned long) GC_heap_sects
[i
].hs_bytes
;
644 GC_printf3("Section %ld from 0x%lx to 0x%lx ", (unsigned long)i
,
645 start
, (unsigned long)(start
+ len
));
646 for (h
= (struct hblk
*)start
; h
< (struct hblk
*)(start
+ len
); h
++) {
647 if (GC_is_black_listed(h
, HBLKSIZE
)) nbl
++;
649 GC_printf2("%lu/%lu blacklisted\n", (unsigned long)nbl
,
650 (unsigned long)(len
/HBLKSIZE
));
655 ptr_t GC_least_plausible_heap_addr
= (ptr_t
)ONES
;
656 ptr_t GC_greatest_plausible_heap_addr
= 0;
661 return(x
> y
? x
: y
);
667 return(x
< y
? x
: y
);
670 # if defined(__STDC__) || defined(__cplusplus)
671 void GC_set_max_heap_size(GC_word n
)
673 void GC_set_max_heap_size(n
)
680 GC_word GC_max_retries
= 0;
683 * this explicitly increases the size of the heap. It is used
684 * internally, but may also be invoked from GC_expand_hp by the user.
685 * The argument is in units of HBLKSIZE.
686 * Tiny values of n are rounded up.
687 * Returns FALSE on failure.
689 GC_bool
GC_expand_hp_inner(n
)
694 word expansion_slop
; /* Number of bytes by which we expect the */
695 /* heap to expand soon. */
697 if (n
< MINHINCR
) n
= MINHINCR
;
698 bytes
= n
* HBLKSIZE
;
699 /* Make sure bytes is a multiple of GC_page_size */
701 word mask
= GC_page_size
- 1;
706 if (GC_max_heapsize
!= 0 && GC_heapsize
+ bytes
> GC_max_heapsize
) {
707 /* Exceeded self-imposed limit */
710 space
= GET_MEM(bytes
);
715 GC_printf2("Increasing heap size by %lu after %lu allocated bytes\n",
716 (unsigned long)bytes
,
717 (unsigned long)WORDS_TO_BYTES(GC_words_allocd
));
719 GC_printf1("Root size = %lu\n", GC_root_size
);
720 GC_print_block_list(); GC_print_hblkfreelist();
724 expansion_slop
= 8 * WORDS_TO_BYTES(min_words_allocd());
725 if (5 * HBLKSIZE
* MAXHINCR
> expansion_slop
) {
726 expansion_slop
= 5 * HBLKSIZE
* MAXHINCR
;
728 if (GC_last_heap_addr
== 0 && !((word
)space
& SIGNB
)
729 || GC_last_heap_addr
!= 0 && GC_last_heap_addr
< (ptr_t
)space
) {
730 /* Assume the heap is growing up */
731 GC_greatest_plausible_heap_addr
=
732 GC_max(GC_greatest_plausible_heap_addr
,
733 (ptr_t
)space
+ bytes
+ expansion_slop
);
735 /* Heap is growing down */
736 GC_least_plausible_heap_addr
=
737 GC_min(GC_least_plausible_heap_addr
,
738 (ptr_t
)space
- expansion_slop
);
740 GC_prev_heap_addr
= GC_last_heap_addr
;
741 GC_last_heap_addr
= (ptr_t
)space
;
742 GC_add_to_heap(space
, bytes
);
746 /* Really returns a bool, but it's externally visible, so that's clumsy. */
747 /* Arguments is in bytes. */
748 # if defined(__STDC__) || defined(__cplusplus)
749 int GC_expand_hp(size_t bytes
)
751 int GC_expand_hp(bytes
)
760 if (!GC_is_initialized
) GC_init_inner();
761 result
= (int)GC_expand_hp_inner(divHBLKSZ((word
)bytes
));
767 unsigned GC_fail_count
= 0;
768 /* How many consecutive GC/expansion failures? */
769 /* Reset by GC_allochblk. */
771 GC_bool
GC_collect_or_expand(needed_blocks
, ignore_off_page
)
773 GC_bool ignore_off_page
;
776 if (!GC_incremental
&& !GC_dont_gc
&& GC_should_collect()) {
780 word blocks_to_get
= GC_heapsize
/(HBLKSIZE
*GC_free_space_divisor
)
783 if (blocks_to_get
> MAXHINCR
) {
786 if (ignore_off_page
) {
789 slop
= 2*divHBLKSZ(BL_LIMIT
);
790 if (slop
> needed_blocks
) slop
= needed_blocks
;
792 if (needed_blocks
+ slop
> MAXHINCR
) {
793 blocks_to_get
= needed_blocks
+ slop
;
795 blocks_to_get
= MAXHINCR
;
798 if (!GC_expand_hp_inner(blocks_to_get
)
799 && !GC_expand_hp_inner(needed_blocks
)) {
800 if (GC_fail_count
++ < GC_max_retries
) {
801 WARN("Out of Memory! Trying to continue ...\n", 0);
805 WARN("Out of Memory! Returning NIL!\n", 0);
808 } else if (GC_fail_count
) {
810 GC_printf0("Memory available again ...\n");
818 * Make sure the object free list for sz is not empty.
819 * Return a pointer to the first object on the free list.
820 * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
821 * Assumes we hold the allocator lock and signals are disabled.
824 ptr_t
GC_allocobj(sz
, kind
)
828 register ptr_t
* flh
= &(GC_obj_kinds
[kind
].ok_freelist
[sz
]);
830 if (sz
== 0) return(0);
834 /* Do our share of marking work */
835 if(GC_incremental
&& !GC_dont_gc
) GC_collect_a_little_inner(1);
836 /* Sweep blocks for objects of this size */
837 GC_continue_reclaim(sz
, kind
);
840 GC_new_hblk(sz
, kind
);
844 if (!GC_collect_or_expand((word
)1,FALSE
)) {