2 * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3 * Copyright (c) 1991-1996 by Xerox Corporation. All rights reserved.
4 * Copyright (c) 1998 by Silicon Graphics. All rights reserved.
5 * Copyright (c) 1999-2004 Hewlett-Packard Development Company, L.P.
7 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
8 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
10 * Permission is hereby granted to use or copy this program
11 * for any purpose, provided the above notices are retained on all copies.
12 * Permission to modify the code and to distribute modified code is granted,
13 * provided the above notices are retained, and a notice that the code was
14 * modified is included with the above copyright notice.
20 # include "private/gc_priv.h"
23 # if !defined(MACOS) && !defined(MSWINCE)
25 # include <sys/types.h>
29 * Separate free lists are maintained for different sized objects
31 * The call GC_allocobj(i,k) ensures that the freelist for
32 * kind k objects of size i points to a non-empty
33 * free list. It returns a pointer to the first entry on the free list.
34 * In a single-threaded world, GC_allocobj may be called to allocate
35 * an object of (small) size i as follows:
37 * opp = &(GC_objfreelist[i]);
38 * if (*opp == 0) GC_allocobj(i, NORMAL);
40 * *opp = obj_link(ptr);
42 * Note that this is very fast if the free list is non-empty; it should
43 * only involve the execution of 4 or 5 simple instructions.
44 * All composite objects on freelists are cleared, except for
49 * The allocator uses GC_allochblk to allocate large chunks of objects.
50 * These chunks all start on addresses which are multiples of
51 * HBLKSZ. Each allocated chunk has an associated header,
52 * which can be located quickly based on the address of the chunk.
53 * (See headers.c for details.)
54 * This makes it possible to check quickly whether an
55 * arbitrary address corresponds to an object administered by the
59 word GC_non_gc_bytes = 0; /* Number of bytes not intended to be collected */
64 int GC_incremental = 0; /* By default, stop the world. */
67 int GC_parallel = FALSE; /* By default, parallel GC is off. */
69 int GC_full_freq = 19; /* Every 20th collection is a full */
70 /* collection, whether we need it */
73 GC_bool GC_need_full_gc = FALSE;
74 /* Need full GC do to heap growth. */
77 GC_bool GC_world_stopped = FALSE;
78 # define IF_THREADS(x) x
80 # define IF_THREADS(x)
83 word GC_used_heap_size_after_full = 0;
85 char * GC_copyright[] =
86 {"Copyright 1988,1989 Hans-J. Boehm and Alan J. Demers ",
87 "Copyright (c) 1991-1995 by Xerox Corporation. All rights reserved. ",
88 "Copyright (c) 1996-1998 by Silicon Graphics. All rights reserved. ",
89 "Copyright (c) 1999-2001 by Hewlett-Packard Company. All rights reserved. ",
90 "THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY",
91 " EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.",
92 "See source code for details." };
96 /* some more variables */
98 extern signed_word GC_bytes_found; /* Number of reclaimed bytes */
99 /* after garbage collection */
101 GC_bool GC_dont_expand = 0;
103 word GC_free_space_divisor = 3;
105 extern GC_bool GC_collection_in_progress();
106 /* Collection is in progress, or was abandoned. */
108 int GC_never_stop_func (void) { return(0); }
110 unsigned long GC_time_limit = TIME_LIMIT;
112 CLOCK_TYPE GC_start_time; /* Time at which we stopped world. */
113 /* used only in GC_timeout_stop_func. */
115 int GC_n_attempts = 0; /* Number of attempts at finishing */
116 /* collection within GC_time_limit. */
118 #if defined(SMALL_CONFIG) || defined(NO_CLOCK)
119 # define GC_timeout_stop_func GC_never_stop_func
121 int GC_timeout_stop_func (void)
123 CLOCK_TYPE current_time;
124 static unsigned count = 0;
125 unsigned long time_diff;
127 if ((count++ & 3) != 0) return(0);
128 GET_TIME(current_time);
129 time_diff = MS_TIME_DIFF(current_time,GC_start_time);
130 if (time_diff >= GC_time_limit) {
131 if (GC_print_stats) {
132 GC_log_printf("Abandoning stopped marking after ");
133 GC_log_printf("%lu msecs", time_diff);
134 GC_log_printf("(attempt %d)\n", GC_n_attempts);
140 #endif /* !SMALL_CONFIG */
142 /* Return the minimum number of words that must be allocated between */
143 /* collections to amortize the collection cost. */
144 static word min_bytes_allocd()
147 /* We punt, for now. */
148 signed_word stack_size = 10000;
151 signed_word stack_size = (ptr_t)(&dummy) - GC_stackbottom;
153 word total_root_size; /* includes double stack size, */
154 /* since the stack is expensive */
156 word scan_size; /* Estimate of memory to be scanned */
157 /* during normal GC. */
159 if (stack_size < 0) stack_size = -stack_size;
160 total_root_size = 2 * stack_size + GC_root_size;
161 scan_size = 2 * GC_composite_in_use + GC_atomic_in_use
163 if (TRUE_INCREMENTAL) {
164 return scan_size / (2 * GC_free_space_divisor);
166 return scan_size / GC_free_space_divisor;
170 /* Return the number of bytes allocated, adjusted for explicit storage */
171 /* management, etc.. This number is used in deciding when to trigger */
173 word GC_adj_bytes_allocd(void)
176 signed_word expl_managed =
177 (signed_word)GC_non_gc_bytes
178 - (signed_word)GC_non_gc_bytes_at_gc;
180 /* Don't count what was explicitly freed, or newly allocated for */
181 /* explicit management. Note that deallocating an explicitly */
182 /* managed object should not alter result, assuming the client */
183 /* is playing by the rules. */
184 result = (signed_word)GC_bytes_allocd
185 - (signed_word)GC_bytes_freed
186 + (signed_word)GC_finalizer_bytes_freed
188 if (result > (signed_word)GC_bytes_allocd) {
189 result = GC_bytes_allocd;
190 /* probably client bug or unfortunate scheduling */
192 result += GC_bytes_finalized;
193 /* We count objects enqueued for finalization as though they */
194 /* had been reallocated this round. Finalization is user */
195 /* visible progress. And if we don't count this, we have */
196 /* stability problems for programs that finalize all objects. */
197 if (result < (signed_word)(GC_bytes_allocd >> 3)) {
198 /* Always count at least 1/8 of the allocations. We don't want */
199 /* to collect too infrequently, since that would inhibit */
200 /* coalescing of free storage blocks. */
201 /* This also makes us partially robust against client bugs. */
202 return(GC_bytes_allocd >> 3);
209 /* Clear up a few frames worth of garbage left at the top of the stack. */
210 /* This is used to prevent us from accidentally treating garbade left */
211 /* on the stack by other parts of the collector as roots. This */
212 /* differs from the code in misc.c, which actually tries to keep the */
213 /* stack clear of long-lived, client-generated garbage. */
214 void GC_clear_a_few_frames()
220 for (i = 0; i < NWORDS; i++) frames[i] = 0;
223 /* Heap size at which we need a collection to avoid expanding past */
224 /* limits used by blacklisting. */
225 static word GC_collect_at_heapsize = (word)(-1);
227 /* Have we allocated enough to amortize a collection? */
228 GC_bool GC_should_collect(void)
230 return(GC_adj_bytes_allocd() >= min_bytes_allocd()
231 || GC_heapsize >= GC_collect_at_heapsize);
235 void GC_notify_full_gc(void)
237 if (GC_start_call_back != (void (*) (void))0) {
238 (*GC_start_call_back)();
242 GC_bool GC_is_full_gc = FALSE;
245 * Initiate a garbage collection if appropriate.
247 * between partial, full, and stop-world collections.
248 * Assumes lock held, signals disabled.
250 void GC_maybe_gc(void)
252 static int n_partial_gcs = 0;
254 if (GC_should_collect()) {
255 if (!GC_incremental) {
260 # ifdef PARALLEL_MARK
261 GC_wait_for_reclaim();
263 if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) {
264 if (GC_print_stats) {
266 "***>Full mark for collection %lu after %ld allocd bytes\n",
267 (unsigned long)GC_gc_no+1,
268 (long)GC_bytes_allocd);
270 GC_promote_black_lists();
271 (void)GC_reclaim_all((GC_stop_func)0, TRUE);
275 GC_is_full_gc = TRUE;
280 /* We try to mark with the world stopped. */
281 /* If we run out of time, this turns into */
282 /* incremental marking. */
284 if (GC_time_limit != GC_TIME_UNLIMITED) { GET_TIME(GC_start_time); }
286 if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED?
287 GC_never_stop_func : GC_timeout_stop_func)) {
288 # ifdef SAVE_CALL_CHAIN
289 GC_save_callers(GC_last_stack);
291 GC_finish_collection();
293 if (!GC_is_full_gc) {
294 /* Count this as the first attempt */
303 * Stop the world garbage collection. Assumes lock held, signals disabled.
304 * If stop_func is not GC_never_stop_func, then abort if stop_func returns TRUE.
305 * Return TRUE if we successfully completed the collection.
307 GC_bool GC_try_to_collect_inner(GC_stop_func stop_func)
309 CLOCK_TYPE start_time, current_time;
310 if (GC_dont_gc) return FALSE;
311 if (GC_incremental && GC_collection_in_progress()) {
312 if (GC_print_stats) {
314 "GC_try_to_collect_inner: finishing collection in progress\n");
316 /* Just finish collection already in progress. */
317 while(GC_collection_in_progress()) {
318 if (stop_func()) return(FALSE);
319 GC_collect_a_little_inner(1);
322 if (stop_func == GC_never_stop_func) GC_notify_full_gc();
323 if (GC_print_stats) {
324 GET_TIME(start_time);
326 "Initiating full world-stop collection %lu after %ld allocd bytes\n",
327 (unsigned long)GC_gc_no+1, (long)GC_bytes_allocd);
329 GC_promote_black_lists();
330 /* Make sure all blocks have been reclaimed, so sweep routines */
331 /* don't see cleared mark bits. */
332 /* If we're guaranteed to finish, then this is unnecessary. */
333 /* In the find_leak case, we have to finish to guarantee that */
334 /* previously unmarked objects are not reported as leaks. */
335 # ifdef PARALLEL_MARK
336 GC_wait_for_reclaim();
338 if ((GC_find_leak || stop_func != GC_never_stop_func)
339 && !GC_reclaim_all(stop_func, FALSE)) {
340 /* Aborted. So far everything is still consistent. */
343 GC_invalidate_mark_state(); /* Flush mark stack. */
345 # ifdef SAVE_CALL_CHAIN
346 GC_save_callers(GC_last_stack);
348 GC_is_full_gc = TRUE;
349 if (!GC_stopped_mark(stop_func)) {
350 if (!GC_incremental) {
351 /* We're partially done and have no way to complete or use */
352 /* current work. Reestablish invariants as cheaply as */
354 GC_invalidate_mark_state();
355 GC_unpromote_black_lists();
356 } /* else we claim the world is already still consistent. We'll */
357 /* finish incrementally. */
360 GC_finish_collection();
361 if (GC_print_stats) {
362 GET_TIME(current_time);
363 GC_log_printf("Complete collection took %lu msecs\n",
364 MS_TIME_DIFF(current_time,start_time));
372 * Perform n units of garbage collection work. A unit is intended to touch
373 * roughly GC_RATE pages. Every once in a while, we do more than that.
374 * This needs to be a fairly large number with our current incremental
375 * GC strategy, since otherwise we allocate too much during GC, and the
376 * cleanup gets expensive.
379 # define MAX_PRIOR_ATTEMPTS 1
380 /* Maximum number of prior attempts at world stop marking */
381 /* A value of 1 means that we finish the second time, no matter */
382 /* how long it takes. Doesn't count the initial root scan */
385 int GC_deficit = 0; /* The number of extra calls to GC_mark_some */
386 /* that we have made. */
388 void GC_collect_a_little_inner(int n)
392 if (GC_dont_gc) return;
393 if (GC_incremental && GC_collection_in_progress()) {
394 for (i = GC_deficit; i < GC_RATE*n; i++) {
395 if (GC_mark_some((ptr_t)0)) {
396 /* Need to finish a collection */
397 # ifdef SAVE_CALL_CHAIN
398 GC_save_callers(GC_last_stack);
400 # ifdef PARALLEL_MARK
401 GC_wait_for_reclaim();
403 if (GC_n_attempts < MAX_PRIOR_ATTEMPTS
404 && GC_time_limit != GC_TIME_UNLIMITED) {
405 GET_TIME(GC_start_time);
406 if (!GC_stopped_mark(GC_timeout_stop_func)) {
411 (void)GC_stopped_mark(GC_never_stop_func);
413 GC_finish_collection();
417 if (GC_deficit > 0) GC_deficit -= GC_RATE*n;
418 if (GC_deficit < 0) GC_deficit = 0;
424 int GC_collect_a_little(void)
430 GC_collect_a_little_inner(1);
431 result = (int)GC_collection_in_progress();
433 if (!result && GC_debugging_started) GC_print_all_smashed();
438 * Assumes lock is held, signals are disabled.
440 * If stop_func() ever returns TRUE, we may fail and return FALSE.
441 * Increment GC_gc_no if we succeed.
443 GC_bool GC_stopped_mark(GC_stop_func stop_func)
447 CLOCK_TYPE start_time, current_time;
450 GET_TIME(start_time);
452 # if defined(REGISTER_LIBRARIES_EARLY)
453 GC_cond_register_dynamic_libraries();
456 IF_THREADS(GC_world_stopped = TRUE);
457 if (GC_print_stats) {
458 GC_log_printf("--> Marking for collection %lu ",
459 (unsigned long)GC_gc_no + 1);
460 GC_log_printf("after %lu allocd bytes\n",
461 (unsigned long) GC_bytes_allocd);
463 # ifdef MAKE_BACK_GRAPH
464 if (GC_print_back_height) {
465 GC_build_back_graph();
469 /* Mark from all roots. */
470 /* Minimize junk left in my registers and on the stack */
471 GC_clear_a_few_frames();
472 GC_noop(0,0,0,0,0,0);
475 if ((*stop_func)()) {
476 if (GC_print_stats) {
477 GC_log_printf("Abandoned stopped marking after ");
478 GC_log_printf("%u iterations\n", i);
480 GC_deficit = i; /* Give the mutator a chance. */
481 IF_THREADS(GC_world_stopped = FALSE);
485 if (GC_mark_some((ptr_t)(&dummy))) break;
489 if (GC_print_stats) {
490 GC_log_printf("Collection %lu reclaimed %ld bytes",
491 (unsigned long)GC_gc_no - 1,
492 (long)GC_bytes_found);
493 GC_log_printf(" ---> heapsize = %lu bytes\n",
494 (unsigned long) GC_heapsize);
495 /* Printf arguments may be pushed in funny places. Clear the */
500 /* Check all debugged objects for consistency */
501 if (GC_debugging_started) {
505 IF_THREADS(GC_world_stopped = FALSE);
507 if (GC_print_stats) {
508 GET_TIME(current_time);
509 GC_log_printf("World-stopped marking took %lu msecs\n",
510 MS_TIME_DIFF(current_time,start_time));
515 /* Set all mark bits for the free list whose first entry is q */
516 void GC_set_fl_marks(ptr_t q)
519 struct hblk * h, * last_h = 0;
520 hdr *hhdr; /* gcc "might be uninitialized" warning is bogus. */
521 IF_PER_OBJ(size_t sz;)
524 for (p = q; p != 0; p = obj_link(p)){
529 IF_PER_OBJ(sz = hhdr->hb_sz;)
531 bit_no = MARK_BIT_NO((ptr_t)p - (ptr_t)h, sz);
532 if (!mark_bit_from_hdr(hhdr, bit_no)) {
533 set_mark_bit_from_hdr(hhdr, bit_no);
534 ++hhdr -> hb_n_marks;
540 /* Check that all mark bits for the free list whose first entry is q */
542 void GC_check_fl_marks(ptr_t q)
546 for (p = q; p != 0; p = obj_link(p)){
547 if (!GC_is_marked(p)) {
548 GC_err_printf("Unmarked object %p on list %p\n", p, q);
549 ABORT("Unmarked local free list entry.");
555 /* Clear all mark bits for the free list whose first entry is q */
556 /* Decrement GC_bytes_found by number of bytes on free list. */
557 void GC_clear_fl_marks(ptr_t q)
560 struct hblk * h, * last_h = 0;
565 for (p = q; p != 0; p = obj_link(p)){
570 sz = hhdr->hb_sz; /* Normally set only once. */
572 bit_no = MARK_BIT_NO((ptr_t)p - (ptr_t)h, sz);
573 if (mark_bit_from_hdr(hhdr, bit_no)) {
574 size_t n_marks = hhdr -> hb_n_marks - 1;
575 clear_mark_bit_from_hdr(hhdr, bit_no);
576 # ifdef PARALLEL_MARK
577 /* Appr. count, don't decrement to zero! */
579 hhdr -> hb_n_marks = n_marks;
582 hhdr -> hb_n_marks = n_marks;
585 GC_bytes_found -= sz;
589 #if defined(GC_ASSERTIONS) && defined(THREADS) && defined(THREAD_LOCAL_ALLOC)
590 extern void GC_check_tls(void);
593 /* Finish up a collection. Assumes lock is held, signals are disabled, */
594 /* but the world is otherwise running. */
595 void GC_finish_collection()
597 CLOCK_TYPE start_time;
598 CLOCK_TYPE finalize_time;
599 CLOCK_TYPE done_time;
601 # if defined(GC_ASSERTIONS) && defined(THREADS) \
602 && defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
603 /* Check that we marked some of our own data. */
604 /* FIXME: Add more checks. */
609 GET_TIME(start_time);
612 # if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
613 if (getenv("GC_PRINT_ADDRESS_MAP") != 0) {
614 GC_print_address_map();
619 /* Mark all objects on the free list. All objects should be */
620 /* marked when we're done. */
622 word size; /* current object size */
626 for (kind = 0; kind < GC_n_kinds; kind++) {
627 for (size = 1; size <= MAXOBJGRANULES; size++) {
628 q = GC_obj_kinds[kind].ok_freelist[size];
629 if (q != 0) GC_set_fl_marks(q);
633 GC_start_reclaim(TRUE);
634 /* The above just checks; it doesn't really reclaim anything. */
638 # ifdef STUBBORN_ALLOC
639 GC_clean_changing_list();
643 GET_TIME(finalize_time);
645 if (GC_print_back_height) {
646 # ifdef MAKE_BACK_GRAPH
647 GC_traverse_back_graph();
649 # ifndef SMALL_CONFIG
650 GC_err_printf("Back height not available: "
651 "Rebuild collector with -DMAKE_BACK_GRAPH\n");
656 /* Clear free list mark bits, in case they got accidentally marked */
657 /* (or GC_find_leak is set and they were intentionally marked). */
658 /* Also subtract memory remaining from GC_bytes_found count. */
659 /* Note that composite objects on free list are cleared. */
660 /* Thus accidentally marking a free list is not a problem; only */
661 /* objects on the list itself will be marked, and that's fixed here. */
663 word size; /* current object size */
664 ptr_t q; /* pointer to current object */
667 for (kind = 0; kind < GC_n_kinds; kind++) {
668 for (size = 1; size <= MAXOBJGRANULES; size++) {
669 q = GC_obj_kinds[kind].ok_freelist[size];
670 if (q != 0) GC_clear_fl_marks(q);
676 if (GC_print_stats == VERBOSE)
677 GC_log_printf("Bytes recovered before sweep - f.l. count = %ld\n",
678 (long)GC_bytes_found);
680 /* Reconstruct free lists to contain everything not marked */
681 GC_start_reclaim(FALSE);
682 if (GC_print_stats) {
683 GC_log_printf("Heap contains %lu pointer-containing "
684 "+ %lu pointer-free reachable bytes\n",
685 (unsigned long)GC_composite_in_use,
686 (unsigned long)GC_atomic_in_use);
689 GC_used_heap_size_after_full = USED_HEAP_SIZE;
690 GC_need_full_gc = FALSE;
693 USED_HEAP_SIZE - GC_used_heap_size_after_full
694 > min_bytes_allocd();
697 if (GC_print_stats == VERBOSE) {
699 "Immediately reclaimed %ld bytes in heap of size %lu bytes",
700 (long)GC_bytes_found,
701 (unsigned long)GC_heapsize);
703 GC_log_printf("(%lu unmapped)", (unsigned long)GC_unmapped_bytes);
708 /* Reset or increment counters for next cycle */
710 GC_is_full_gc = FALSE;
711 GC_bytes_allocd_before_gc += GC_bytes_allocd;
712 GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
715 GC_finalizer_bytes_freed = 0;
720 if (GC_print_stats) {
722 GC_log_printf("Finalize + initiate sweep took %lu + %lu msecs\n",
723 MS_TIME_DIFF(finalize_time,start_time),
724 MS_TIME_DIFF(done_time,finalize_time));
728 /* Externally callable routine to invoke full, stop-world collection */
729 int GC_try_to_collect(GC_stop_func stop_func)
734 if (!GC_is_initialized) GC_init();
735 if (GC_debugging_started) GC_print_all_smashed();
736 GC_INVOKE_FINALIZERS();
739 if (!GC_is_initialized) GC_init_inner();
740 /* Minimize junk left in my registers */
741 GC_noop(0,0,0,0,0,0);
742 result = (int)GC_try_to_collect_inner(stop_func);
746 if (GC_debugging_started) GC_print_all_smashed();
747 GC_INVOKE_FINALIZERS();
752 void GC_gcollect(void)
754 (void)GC_try_to_collect(GC_never_stop_func);
755 if (GC_have_errors) GC_print_all_errors();
758 word GC_n_heap_sects = 0; /* Number of sections currently in heap. */
761 * Use the chunk of memory starting at p of size bytes as part of the heap.
762 * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
764 void GC_add_to_heap(struct hblk *p, size_t bytes)
768 if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
769 ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
771 phdr = GC_install_header(p);
773 /* This is extremely unlikely. Can't add it. This will */
774 /* almost certainly result in a 0 return from the allocator, */
775 /* which is entirely appropriate. */
778 GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
779 GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
781 phdr -> hb_sz = bytes;
782 phdr -> hb_flags = 0;
784 GC_heapsize += bytes;
785 if ((ptr_t)p <= (ptr_t)GC_least_plausible_heap_addr
786 || GC_least_plausible_heap_addr == 0) {
787 GC_least_plausible_heap_addr = (void *)((ptr_t)p - sizeof(word));
788 /* Making it a little smaller than necessary prevents */
789 /* us from getting a false hit from the variable */
790 /* itself. There's some unintentional reflection */
793 if ((ptr_t)p + bytes >= (ptr_t)GC_greatest_plausible_heap_addr) {
794 GC_greatest_plausible_heap_addr = (void *)((ptr_t)p + bytes);
798 # if !defined(NO_DEBUGGING)
799 void GC_print_heap_sects(void)
803 GC_printf("Total heap size: %lu\n", (unsigned long) GC_heapsize);
804 for (i = 0; i < GC_n_heap_sects; i++) {
805 ptr_t start = GC_heap_sects[i].hs_start;
806 size_t len = GC_heap_sects[i].hs_bytes;
810 GC_printf("Section %d from %p to %p ", i,
812 for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) {
813 if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
815 GC_printf("%lu/%lu blacklisted\n", (unsigned long)nbl,
816 (unsigned long)(len/HBLKSIZE));
821 void * GC_least_plausible_heap_addr = (void *)ONES;
822 void * GC_greatest_plausible_heap_addr = 0;
824 static INLINE ptr_t GC_max(ptr_t x, ptr_t y)
826 return(x > y? x : y);
829 static INLINE ptr_t GC_min(ptr_t x, ptr_t y)
831 return(x < y? x : y);
834 void GC_set_max_heap_size(GC_word n)
839 word GC_get_max_heap_size()
841 return GC_max_heapsize;
844 GC_word GC_max_retries = 0;
847 * this explicitly increases the size of the heap. It is used
848 * internally, but may also be invoked from GC_expand_hp by the user.
849 * The argument is in units of HBLKSIZE.
850 * Tiny values of n are rounded up.
851 * Returns FALSE on failure.
853 GC_bool GC_expand_hp_inner(word n)
857 word expansion_slop; /* Number of bytes by which we expect the */
858 /* heap to expand soon. */
860 if (n < MINHINCR) n = MINHINCR;
861 bytes = n * HBLKSIZE;
862 /* Make sure bytes is a multiple of GC_page_size */
864 word mask = GC_page_size - 1;
869 if (GC_max_heapsize != 0 && GC_heapsize + bytes > GC_max_heapsize) {
870 /* Exceeded self-imposed limit */
873 space = GET_MEM(bytes);
875 if (GC_print_stats) {
876 GC_log_printf("Failed to expand heap by %ld bytes\n",
877 (unsigned long)bytes);
881 if (GC_print_stats) {
882 GC_log_printf("Increasing heap size by %lu after %lu allocated bytes\n",
883 (unsigned long)bytes,
884 (unsigned long)GC_bytes_allocd);
886 expansion_slop = min_bytes_allocd() + 4*MAXHINCR*HBLKSIZE;
887 if ((GC_last_heap_addr == 0 && !((word)space & SIGNB))
888 || (GC_last_heap_addr != 0 && GC_last_heap_addr < (ptr_t)space)) {
889 /* Assume the heap is growing up */
890 GC_greatest_plausible_heap_addr =
891 (void *)GC_max((ptr_t)GC_greatest_plausible_heap_addr,
892 (ptr_t)space + bytes + expansion_slop);
894 /* Heap is growing down */
895 GC_least_plausible_heap_addr =
896 (void *)GC_min((ptr_t)GC_least_plausible_heap_addr,
897 (ptr_t)space - expansion_slop);
899 # if defined(LARGE_CONFIG)
900 if (((ptr_t)GC_greatest_plausible_heap_addr <= (ptr_t)space + bytes
901 || (ptr_t)GC_least_plausible_heap_addr >= (ptr_t)space)
902 && GC_heapsize > 0) {
903 /* GC_add_to_heap will fix this, but ... */
904 WARN("Too close to address space limit: blacklisting ineffective\n", 0);
907 GC_prev_heap_addr = GC_last_heap_addr;
908 GC_last_heap_addr = (ptr_t)space;
909 GC_add_to_heap(space, bytes);
910 /* Force GC before we are likely to allocate past expansion_slop */
911 GC_collect_at_heapsize =
912 GC_heapsize + expansion_slop - 2*MAXHINCR*HBLKSIZE;
913 # if defined(LARGE_CONFIG)
914 if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
915 GC_collect_at_heapsize = (word)(-1);
920 /* Really returns a bool, but it's externally visible, so that's clumsy. */
921 /* Arguments is in bytes. */
922 int GC_expand_hp(size_t bytes)
928 if (!GC_is_initialized) GC_init_inner();
929 result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
930 if (result) GC_requested_heapsize += bytes;
935 unsigned GC_fail_count = 0;
936 /* How many consecutive GC/expansion failures? */
937 /* Reset by GC_allochblk. */
939 GC_bool GC_collect_or_expand(word needed_blocks, GC_bool ignore_off_page)
941 if (!GC_incremental && !GC_dont_gc &&
942 ((GC_dont_expand && GC_bytes_allocd > 0) || GC_should_collect())) {
945 word blocks_to_get = GC_heapsize/(HBLKSIZE*GC_free_space_divisor)
948 if (blocks_to_get > MAXHINCR) {
951 /* Get the minimum required to make it likely that we */
952 /* can satisfy the current request in the presence of black- */
953 /* listing. This will probably be more than MAXHINCR. */
954 if (ignore_off_page) {
957 slop = 2*divHBLKSZ(BL_LIMIT);
958 if (slop > needed_blocks) slop = needed_blocks;
960 if (needed_blocks + slop > MAXHINCR) {
961 blocks_to_get = needed_blocks + slop;
963 blocks_to_get = MAXHINCR;
966 if (!GC_expand_hp_inner(blocks_to_get)
967 && !GC_expand_hp_inner(needed_blocks)) {
968 if (GC_fail_count++ < GC_max_retries) {
969 WARN("Out of Memory! Trying to continue ...\n", 0);
972 # if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
973 WARN("Out of Memory! Returning NIL!\n", 0);
978 if (GC_fail_count && GC_print_stats) {
979 GC_printf("Memory available again ...\n");
987 * Make sure the object free list for size gran (in granules) is not empty.
988 * Return a pointer to the first object on the free list.
989 * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
990 * Assumes we hold the allocator lock and signals are disabled.
993 ptr_t GC_allocobj(size_t gran, int kind)
995 void ** flh = &(GC_obj_kinds[kind].ok_freelist[gran]);
996 GC_bool tried_minor = FALSE;
998 if (gran == 0) return(0);
1002 /* Do our share of marking work */
1003 if(TRUE_INCREMENTAL) GC_collect_a_little_inner(1);
1004 /* Sweep blocks for objects of this size */
1005 GC_continue_reclaim(gran, kind);
1008 GC_new_hblk(gran, kind);
1012 if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED
1013 && ! tried_minor ) {
1014 GC_collect_a_little_inner(1);
1017 if (!GC_collect_or_expand((word)1,FALSE)) {
1025 /* Successful allocation; reset failure count. */