2 * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3 * Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
4 * Copyright (c) 1998 by Silicon Graphics. All rights reserved.
6 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
7 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
9 * Permission is hereby granted to use or copy this program
10 * for any purpose, provided the above notices are retained on all copies.
11 * Permission to modify the code and to distribute modified code is granted,
12 * provided the above notices are retained, and a notice that the code was
13 * modified is included with the above copyright notice.
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 */
62 int GC_incremental = 0; /* By default, stop the world. */
65 int GC_full_freq = 4; /* Every 5th collection is a full */
68 char * GC_copyright[] =
69 {"Copyright 1988,1989 Hans-J. Boehm and Alan J. Demers ",
70 "Copyright (c) 1991-1995 by Xerox Corporation. All rights reserved. ",
71 "Copyright (c) 1996-1998 by Silicon Graphics. All rights reserved. ",
72 "THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY",
73 " EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.",
74 "See source code for details." };
78 /* some more variables */
80 extern signed_word GC_mem_found; /* Number of reclaimed longwords */
81 /* after garbage collection */
83 GC_bool GC_dont_expand = 0;
85 word GC_free_space_divisor = 3;
87 extern GC_bool GC_collection_in_progress();
88 /* Collection is in progress, or was abandoned. */
90 int GC_never_stop_func GC_PROTO((void)) { return(0); }
92 CLOCK_TYPE GC_start_time; /* Time at which we stopped world. */
93 /* used only in GC_timeout_stop_func. */
95 int GC_n_attempts = 0; /* Number of attempts at finishing */
96 /* collection within TIME_LIMIT */
99 # define GC_timeout_stop_func GC_never_stop_func
101 int GC_timeout_stop_func GC_PROTO((void))
103 CLOCK_TYPE current_time;
104 static unsigned count = 0;
105 unsigned long time_diff;
107 if ((count++ & 3) != 0) return(0);
108 GET_TIME(current_time);
109 time_diff = MS_TIME_DIFF(current_time,GC_start_time);
110 if (time_diff >= TIME_LIMIT) {
112 GC_printf0("Abandoning stopped marking after ");
113 GC_printf1("%lu msecs", (unsigned long)time_diff);
114 GC_printf1("(attempt %d)\n", (unsigned long) GC_n_attempts);
120 #endif /* !SMALL_CONFIG */
122 /* Return the minimum number of words that must be allocated between */
123 /* collections to amortize the collection cost. */
124 static word min_words_allocd()
127 /* We punt, for now. */
128 register signed_word stack_size = 10000;
131 register signed_word stack_size = (ptr_t)(&dummy) - GC_stackbottom;
133 word total_root_size; /* includes double stack size, */
134 /* since the stack is expensive */
136 word scan_size; /* Estimate of memory to be scanned */
137 /* during normal GC. */
139 if (stack_size < 0) stack_size = -stack_size;
140 total_root_size = 2 * stack_size + GC_root_size;
141 scan_size = BYTES_TO_WORDS(GC_heapsize - GC_large_free_bytes
142 + (GC_large_free_bytes >> 2)
143 /* use a bit more of large empty heap */
145 if (GC_incremental) {
146 return scan_size / (2 * GC_free_space_divisor);
148 return scan_size / GC_free_space_divisor;
152 /* Return the number of words allocated, adjusted for explicit storage */
153 /* management, etc.. This number is used in deciding when to trigger */
155 word GC_adj_words_allocd()
157 register signed_word result;
158 register signed_word expl_managed =
159 BYTES_TO_WORDS((long)GC_non_gc_bytes
160 - (long)GC_non_gc_bytes_at_gc);
162 /* Don't count what was explicitly freed, or newly allocated for */
163 /* explicit management. Note that deallocating an explicitly */
164 /* managed object should not alter result, assuming the client */
165 /* is playing by the rules. */
166 result = (signed_word)GC_words_allocd
167 - (signed_word)GC_mem_freed - expl_managed;
168 if (result > (signed_word)GC_words_allocd) {
169 result = GC_words_allocd;
170 /* probably client bug or unfortunate scheduling */
172 result += GC_words_finalized;
173 /* We count objects enqueued for finalization as though they */
174 /* had been reallocated this round. Finalization is user */
175 /* visible progress. And if we don't count this, we have */
176 /* stability problems for programs that finalize all objects. */
177 result += GC_words_wasted;
178 /* This doesn't reflect useful work. But if there is lots of */
179 /* new fragmentation, the same is probably true of the heap, */
180 /* and the collection will be correspondingly cheaper. */
181 if (result < (signed_word)(GC_words_allocd >> 3)) {
182 /* Always count at least 1/8 of the allocations. We don't want */
183 /* to collect too infrequently, since that would inhibit */
184 /* coalescing of free storage blocks. */
185 /* This also makes us partially robust against client bugs. */
186 return(GC_words_allocd >> 3);
193 /* Clear up a few frames worth of garbage left at the top of the stack. */
194 /* This is used to prevent us from accidentally treating garbade left */
195 /* on the stack by other parts of the collector as roots. This */
196 /* differs from the code in misc.c, which actually tries to keep the */
197 /* stack clear of long-lived, client-generated garbage. */
198 void GC_clear_a_few_frames()
204 for (i = 0; i < NWORDS; i++) frames[i] = 0;
207 /* Have we allocated enough to amortize a collection? */
208 GC_bool GC_should_collect()
210 return(GC_adj_words_allocd() >= min_words_allocd());
213 void GC_notify_full_gc()
215 if (GC_start_call_back != (void (*)())0) {
216 (*GC_start_call_back)();
221 * Initiate a garbage collection if appropriate.
223 * between partial, full, and stop-world collections.
224 * Assumes lock held, signals disabled.
228 static int n_partial_gcs = 0;
229 GC_bool is_full_gc = FALSE;
231 if (GC_should_collect()) {
232 if (!GC_incremental) {
237 } else if (n_partial_gcs >= GC_full_freq) {
240 "***>Full mark for collection %lu after %ld allocd bytes\n",
241 (unsigned long) GC_gc_no+1,
242 (long)WORDS_TO_BYTES(GC_words_allocd));
244 GC_promote_black_lists();
245 (void)GC_reclaim_all((GC_stop_func)0, TRUE);
253 /* We try to mark with the world stopped. */
254 /* If we run out of time, this turns into */
255 /* incremental marking. */
256 GET_TIME(GC_start_time);
257 if (GC_stopped_mark(GC_timeout_stop_func)) {
258 # ifdef SAVE_CALL_CHAIN
259 GC_save_callers(GC_last_stack);
261 GC_finish_collection();
264 /* Count this as the first attempt */
273 * Stop the world garbage collection. Assumes lock held, signals disabled.
274 * If stop_func is not GC_never_stop_func, then abort if stop_func returns TRUE.
276 GC_bool GC_try_to_collect_inner(stop_func)
277 GC_stop_func stop_func;
279 if (GC_incremental && GC_collection_in_progress()) {
282 "GC_try_to_collect_inner: finishing collection in progress\n");
283 # endif /* PRINTSTATS */
284 /* Just finish collection already in progress. */
285 while(GC_collection_in_progress()) {
286 if (stop_func()) return(FALSE);
287 GC_collect_a_little_inner(1);
292 "Initiating full world-stop collection %lu after %ld allocd bytes\n",
293 (unsigned long) GC_gc_no+1,
294 (long)WORDS_TO_BYTES(GC_words_allocd));
296 GC_promote_black_lists();
297 /* Make sure all blocks have been reclaimed, so sweep routines */
298 /* don't see cleared mark bits. */
299 /* If we're guaranteed to finish, then this is unnecessary. */
300 if (stop_func != GC_never_stop_func
301 && !GC_reclaim_all(stop_func, FALSE)) {
302 /* Aborted. So far everything is still consistent. */
305 GC_invalidate_mark_state(); /* Flush mark stack. */
307 # ifdef SAVE_CALL_CHAIN
308 GC_save_callers(GC_last_stack);
310 if (!GC_stopped_mark(stop_func)) {
311 if (!GC_incremental) {
312 /* We're partially done and have no way to complete or use */
313 /* current work. Reestablish invariants as cheaply as */
315 GC_invalidate_mark_state();
316 GC_unpromote_black_lists();
317 } /* else we claim the world is already still consistent. We'll */
318 /* finish incrementally. */
321 GC_finish_collection();
328 * Perform n units of garbage collection work. A unit is intended to touch
329 * roughly GC_RATE pages. Every once in a while, we do more than that.
330 * This needa to be a fairly large number with our current incremental
331 * GC strategy, since otherwise we allocate too much during GC, and the
332 * cleanup gets expensive.
335 # define MAX_PRIOR_ATTEMPTS 1
336 /* Maximum number of prior attempts at world stop marking */
337 /* A value of 1 means that we finish the seconf time, no matter */
338 /* how long it takes. Doesn't count the initial root scan */
341 int GC_deficit = 0; /* The number of extra calls to GC_mark_some */
342 /* that we have made. */
344 void GC_collect_a_little_inner(n)
349 if (GC_incremental && GC_collection_in_progress()) {
350 for (i = GC_deficit; i < GC_RATE*n; i++) {
351 if (GC_mark_some((ptr_t)0)) {
352 /* Need to finish a collection */
353 # ifdef SAVE_CALL_CHAIN
354 GC_save_callers(GC_last_stack);
356 if (GC_n_attempts < MAX_PRIOR_ATTEMPTS) {
357 GET_TIME(GC_start_time);
358 if (!GC_stopped_mark(GC_timeout_stop_func)) {
363 (void)GC_stopped_mark(GC_never_stop_func);
365 GC_finish_collection();
369 if (GC_deficit > 0) GC_deficit -= GC_RATE*n;
370 if (GC_deficit < 0) GC_deficit = 0;
376 int GC_collect_a_little GC_PROTO(())
383 GC_collect_a_little_inner(1);
384 result = (int)GC_collection_in_progress();
391 * Assumes lock is held, signals are disabled.
393 * If stop_func() ever returns TRUE, we may fail and return FALSE.
394 * Increment GC_gc_no if we succeed.
396 GC_bool GC_stopped_mark(stop_func)
397 GC_stop_func stop_func;
402 CLOCK_TYPE start_time, current_time;
407 GET_TIME(start_time);
408 GC_printf1("--> Marking for collection %lu ",
409 (unsigned long) GC_gc_no + 1);
410 GC_printf2("after %lu allocd bytes + %lu wasted bytes\n",
411 (unsigned long) WORDS_TO_BYTES(GC_words_allocd),
412 (unsigned long) WORDS_TO_BYTES(GC_words_wasted));
415 /* Mark from all roots. */
416 /* Minimize junk left in my registers and on the stack */
417 GC_clear_a_few_frames();
418 GC_noop(0,0,0,0,0,0);
421 if ((*stop_func)()) {
423 GC_printf0("Abandoned stopped marking after ");
424 GC_printf1("%lu iterations\n",
427 GC_deficit = i; /* Give the mutator a chance. */
431 if (GC_mark_some((ptr_t)(&dummy))) break;
436 GC_printf2("Collection %lu reclaimed %ld bytes",
437 (unsigned long) GC_gc_no - 1,
438 (long)WORDS_TO_BYTES(GC_mem_found));
439 GC_printf1(" ---> heapsize = %lu bytes\n",
440 (unsigned long) GC_heapsize);
441 /* Printf arguments may be pushed in funny places. Clear the */
446 /* Check all debugged objects for consistency */
447 if (GC_debugging_started) {
452 GET_TIME(current_time);
453 GC_printf1("World-stopped marking took %lu msecs\n",
454 MS_TIME_DIFF(current_time,start_time));
461 /* Finish up a collection. Assumes lock is held, signals are disabled, */
462 /* but the world is otherwise running. */
463 void GC_finish_collection()
466 CLOCK_TYPE start_time;
467 CLOCK_TYPE finalize_time;
468 CLOCK_TYPE done_time;
470 GET_TIME(start_time);
471 finalize_time = start_time;
478 /* Mark all objects on the free list. All objects should be */
479 /* marked when we're done. */
481 register word size; /* current object size */
482 register ptr_t p; /* pointer to current object */
483 register struct hblk * h; /* pointer to block containing *p */
485 register int word_no; /* "index" of *p in *q */
488 for (kind = 0; kind < GC_n_kinds; kind++) {
489 for (size = 1; size <= MAXOBJSZ; size++) {
490 for (p= GC_obj_kinds[kind].ok_freelist[size];
491 p != 0; p=obj_link(p)){
494 word_no = (((word *)p) - ((word *)h));
495 set_mark_bit_from_hdr(hhdr, word_no);
500 GC_start_reclaim(TRUE);
501 /* The above just checks; it doesn't really reclaim anything. */
505 # ifdef STUBBORN_ALLOC
506 GC_clean_changing_list();
510 GET_TIME(finalize_time);
513 /* Clear free list mark bits, in case they got accidentally marked */
514 /* Note: HBLKPTR(p) == pointer to head of block containing *p */
515 /* (or GC_find_leak is set and they were intentionally marked.) */
516 /* Also subtract memory remaining from GC_mem_found count. */
517 /* Note that composite objects on free list are cleared. */
518 /* Thus accidentally marking a free list is not a problem; only */
519 /* objects on the list itself will be marked, and that's fixed here. */
521 register word size; /* current object size */
522 register ptr_t p; /* pointer to current object */
523 register struct hblk * h; /* pointer to block containing *p */
525 register int word_no; /* "index" of *p in *q */
528 for (kind = 0; kind < GC_n_kinds; kind++) {
529 for (size = 1; size <= MAXOBJSZ; size++) {
530 for (p= GC_obj_kinds[kind].ok_freelist[size];
531 p != 0; p=obj_link(p)){
534 word_no = (((word *)p) - ((word *)h));
535 clear_mark_bit_from_hdr(hhdr, word_no);
537 GC_mem_found -= size;
546 GC_printf1("Bytes recovered before sweep - f.l. count = %ld\n",
547 (long)WORDS_TO_BYTES(GC_mem_found));
549 /* Reconstruct free lists to contain everything not marked */
550 GC_start_reclaim(FALSE);
554 "Immediately reclaimed %ld bytes in heap of size %lu bytes",
555 (long)WORDS_TO_BYTES(GC_mem_found),
556 (unsigned long)GC_heapsize);
558 GC_printf1("(%lu unmapped)", GC_unmapped_bytes);
561 "\n%lu (atomic) + %lu (composite) collectable bytes in use\n",
562 (unsigned long)WORDS_TO_BYTES(GC_atomic_in_use),
563 (unsigned long)WORDS_TO_BYTES(GC_composite_in_use));
567 /* Reset or increment counters for next cycle */
568 GC_words_allocd_before_gc += GC_words_allocd;
569 GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
579 GC_printf2("Finalize + initiate sweep took %lu + %lu msecs\n",
580 MS_TIME_DIFF(finalize_time,start_time),
581 MS_TIME_DIFF(done_time,finalize_time));
585 /* Externally callable routine to invoke full, stop-world collection */
586 # if defined(__STDC__) || defined(__cplusplus)
587 int GC_try_to_collect(GC_stop_func stop_func)
589 int GC_try_to_collect(stop_func)
590 GC_stop_func stop_func;
596 GC_INVOKE_FINALIZERS();
600 if (!GC_is_initialized) GC_init_inner();
601 /* Minimize junk left in my registers */
602 GC_noop(0,0,0,0,0,0);
603 result = (int)GC_try_to_collect_inner(stop_func);
607 if(result) GC_INVOKE_FINALIZERS();
611 void GC_gcollect GC_PROTO(())
614 (void)GC_try_to_collect(GC_never_stop_func);
617 word GC_n_heap_sects = 0; /* Number of sections currently in heap. */
620 * Use the chunk of memory starting at p of size bytes as part of the heap.
621 * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
623 void GC_add_to_heap(p, bytes)
630 if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
631 ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
633 if (!GC_install_header(p)) {
634 /* This is extremely unlikely. Can't add it. This will */
635 /* almost certainly result in a 0 return from the allocator, */
636 /* which is entirely appropriate. */
639 GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
640 GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
642 words = BYTES_TO_WORDS(bytes - HDR_BYTES);
644 phdr -> hb_sz = words;
645 phdr -> hb_map = (char *)1; /* A value != GC_invalid_map */
646 phdr -> hb_flags = 0;
648 GC_heapsize += bytes;
649 if ((ptr_t)p <= GC_least_plausible_heap_addr
650 || GC_least_plausible_heap_addr == 0) {
651 GC_least_plausible_heap_addr = (ptr_t)p - sizeof(word);
652 /* Making it a little smaller than necessary prevents */
653 /* us from getting a false hit from the variable */
654 /* itself. There's some unintentional reflection */
657 if ((ptr_t)p + bytes >= GC_greatest_plausible_heap_addr) {
658 GC_greatest_plausible_heap_addr = (ptr_t)p + bytes;
662 # if !defined(NO_DEBUGGING)
663 void GC_print_heap_sects()
667 GC_printf1("Total heap size: %lu\n", (unsigned long) GC_heapsize);
668 for (i = 0; i < GC_n_heap_sects; i++) {
669 unsigned long start = (unsigned long) GC_heap_sects[i].hs_start;
670 unsigned long len = (unsigned long) GC_heap_sects[i].hs_bytes;
674 GC_printf3("Section %ld from 0x%lx to 0x%lx ", (unsigned long)i,
675 start, (unsigned long)(start + len));
676 for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) {
677 if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
679 GC_printf2("%lu/%lu blacklisted\n", (unsigned long)nbl,
680 (unsigned long)(len/HBLKSIZE));
685 ptr_t GC_least_plausible_heap_addr = (ptr_t)ONES;
686 ptr_t GC_greatest_plausible_heap_addr = 0;
691 return(x > y? x : y);
697 return(x < y? x : y);
700 # if defined(__STDC__) || defined(__cplusplus)
701 void GC_set_max_heap_size(GC_word n)
703 void GC_set_max_heap_size(n)
710 GC_word GC_max_retries = 0;
713 * this explicitly increases the size of the heap. It is used
714 * internally, but may also be invoked from GC_expand_hp by the user.
715 * The argument is in units of HBLKSIZE.
716 * Tiny values of n are rounded up.
717 * Returns FALSE on failure.
719 GC_bool GC_expand_hp_inner(n)
724 word expansion_slop; /* Number of bytes by which we expect the */
725 /* heap to expand soon. */
727 if (n < MINHINCR) n = MINHINCR;
728 bytes = n * HBLKSIZE;
729 /* Make sure bytes is a multiple of GC_page_size */
731 word mask = GC_page_size - 1;
736 if (GC_max_heapsize != 0 && GC_heapsize + bytes > GC_max_heapsize) {
737 /* Exceeded self-imposed limit */
740 space = GET_MEM(bytes);
745 GC_printf2("Increasing heap size by %lu after %lu allocated bytes\n",
746 (unsigned long)bytes,
747 (unsigned long)WORDS_TO_BYTES(GC_words_allocd));
749 GC_printf1("Root size = %lu\n", GC_root_size);
750 GC_print_block_list(); GC_print_hblkfreelist();
754 expansion_slop = 8 * WORDS_TO_BYTES(min_words_allocd());
755 if (5 * HBLKSIZE * MAXHINCR > expansion_slop) {
756 expansion_slop = 5 * HBLKSIZE * MAXHINCR;
758 if (GC_last_heap_addr == 0 && !((word)space & SIGNB)
759 || GC_last_heap_addr != 0 && GC_last_heap_addr < (ptr_t)space) {
760 /* Assume the heap is growing up */
761 GC_greatest_plausible_heap_addr =
762 GC_max(GC_greatest_plausible_heap_addr,
763 (ptr_t)space + bytes + expansion_slop);
765 /* Heap is growing down */
766 GC_least_plausible_heap_addr =
767 GC_min(GC_least_plausible_heap_addr,
768 (ptr_t)space - expansion_slop);
770 GC_prev_heap_addr = GC_last_heap_addr;
771 GC_last_heap_addr = (ptr_t)space;
772 GC_add_to_heap(space, bytes);
776 /* Really returns a bool, but it's externally visible, so that's clumsy. */
777 /* Arguments is in bytes. */
778 # if defined(__STDC__) || defined(__cplusplus)
779 int GC_expand_hp(size_t bytes)
781 int GC_expand_hp(bytes)
790 if (!GC_is_initialized) GC_init_inner();
791 result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
797 unsigned GC_fail_count = 0;
798 /* How many consecutive GC/expansion failures? */
799 /* Reset by GC_allochblk. */
801 GC_bool GC_collect_or_expand(needed_blocks, ignore_off_page)
803 GC_bool ignore_off_page;
805 if (!GC_incremental && !GC_dont_gc && GC_should_collect()) {
809 word blocks_to_get = GC_heapsize/(HBLKSIZE*GC_free_space_divisor)
812 if (blocks_to_get > MAXHINCR) {
815 if (ignore_off_page) {
818 slop = 2*divHBLKSZ(BL_LIMIT);
819 if (slop > needed_blocks) slop = needed_blocks;
821 if (needed_blocks + slop > MAXHINCR) {
822 blocks_to_get = needed_blocks + slop;
824 blocks_to_get = MAXHINCR;
827 if (!GC_expand_hp_inner(blocks_to_get)
828 && !GC_expand_hp_inner(needed_blocks)) {
829 if (GC_fail_count++ < GC_max_retries) {
830 WARN("Out of Memory! Trying to continue ...\n", 0);
834 WARN("Out of Memory! Returning NIL!\n", 0);
840 GC_printf0("Memory available again ...\n");
849 * Make sure the object free list for sz is not empty.
850 * Return a pointer to the first object on the free list.
851 * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
852 * Assumes we hold the allocator lock and signals are disabled.
855 ptr_t GC_allocobj(sz, kind)
859 register ptr_t * flh = &(GC_obj_kinds[kind].ok_freelist[sz]);
861 if (sz == 0) return(0);
865 /* Do our share of marking work */
866 if(GC_incremental && !GC_dont_gc) GC_collect_a_little_inner(1);
867 /* Sweep blocks for objects of this size */
868 GC_continue_reclaim(sz, kind);
871 GC_new_hblk(sz, kind);
875 if (!GC_collect_or_expand((word)1,FALSE)) {