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.
19 # include "private/gc_priv.h"
22 # if !defined(MACOS) && !defined(MSWINCE)
24 # include <sys/types.h>
28 * Separate free lists are maintained for different sized objects
30 * The call GC_allocobj(i,k) ensures that the freelist for
31 * kind k objects of size i points to a non-empty
32 * free list. It returns a pointer to the first entry on the free list.
33 * In a single-threaded world, GC_allocobj may be called to allocate
34 * an object of (small) size i as follows:
36 * opp = &(GC_objfreelist[i]);
37 * if (*opp == 0) GC_allocobj(i, NORMAL);
39 * *opp = obj_link(ptr);
41 * Note that this is very fast if the free list is non-empty; it should
42 * only involve the execution of 4 or 5 simple instructions.
43 * All composite objects on freelists are cleared, except for
48 * The allocator uses GC_allochblk to allocate large chunks of objects.
49 * These chunks all start on addresses which are multiples of
50 * HBLKSZ. Each allocated chunk has an associated header,
51 * which can be located quickly based on the address of the chunk.
52 * (See headers.c for details.)
53 * This makes it possible to check quickly whether an
54 * arbitrary address corresponds to an object administered by the
58 word GC_non_gc_bytes = 0; /* Number of bytes not intended to be collected */
63 int GC_incremental = 0; /* By default, stop the world. */
66 int GC_parallel = FALSE; /* By default, parallel GC is off. */
68 int GC_full_freq = 19; /* Every 20th collection is a full */
69 /* collection, whether we need it */
72 GC_bool GC_need_full_gc = FALSE;
73 /* Need full GC do to heap growth. */
76 GC_bool GC_world_stopped = FALSE;
77 # define IF_THREADS(x) x
79 # define IF_THREADS(x)
82 word GC_used_heap_size_after_full = 0;
84 char * GC_copyright[] =
85 {"Copyright 1988,1989 Hans-J. Boehm and Alan J. Demers ",
86 "Copyright (c) 1991-1995 by Xerox Corporation. All rights reserved. ",
87 "Copyright (c) 1996-1998 by Silicon Graphics. All rights reserved. ",
88 "Copyright (c) 1999-2001 by Hewlett-Packard Company. All rights reserved. ",
89 "THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY",
90 " EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.",
91 "See source code for details." };
93 /* Version macros are now defined in gc_version.h, which is included by */
94 /* gc.h, which is included by gc_priv.h". */
96 #ifndef GC_NO_VERSION_VAR
98 unsigned GC_version = ((GC_VERSION_MAJOR << 16) | (GC_VERSION_MINOR << 8) | GC_TMP_ALPHA_VERSION);
100 #endif /* GC_NO_VERSION_VAR */
102 /* some more variables */
104 extern signed_word GC_bytes_found; /* Number of reclaimed bytes */
105 /* after garbage collection */
107 GC_bool GC_dont_expand = 0;
109 word GC_free_space_divisor = 3;
111 extern GC_bool GC_collection_in_progress();
112 /* Collection is in progress, or was abandoned. */
114 int GC_never_stop_func (void) { return(0); }
116 unsigned long GC_time_limit = TIME_LIMIT;
118 CLOCK_TYPE GC_start_time; /* Time at which we stopped world. */
119 /* used only in GC_timeout_stop_func. */
121 int GC_n_attempts = 0; /* Number of attempts at finishing */
122 /* collection within GC_time_limit. */
124 #if defined(SMALL_CONFIG) || defined(NO_CLOCK)
125 # define GC_timeout_stop_func GC_never_stop_func
127 int GC_timeout_stop_func (void)
129 CLOCK_TYPE current_time;
130 static unsigned count = 0;
131 unsigned long time_diff;
133 if ((count++ & 3) != 0) return(0);
134 GET_TIME(current_time);
135 time_diff = MS_TIME_DIFF(current_time,GC_start_time);
136 if (time_diff >= GC_time_limit) {
137 if (GC_print_stats) {
138 GC_log_printf("Abandoning stopped marking after ");
139 GC_log_printf("%lu msecs", time_diff);
140 GC_log_printf("(attempt %d)\n", GC_n_attempts);
146 #endif /* !SMALL_CONFIG */
148 /* Return the minimum number of words that must be allocated between */
149 /* collections to amortize the collection cost. */
150 static word min_bytes_allocd()
153 /* We punt, for now. */
154 signed_word stack_size = 10000;
157 signed_word stack_size = (ptr_t)(&dummy) - GC_stackbottom;
159 word total_root_size; /* includes double stack size, */
160 /* since the stack is expensive */
162 word scan_size; /* Estimate of memory to be scanned */
163 /* during normal GC. */
165 if (stack_size < 0) stack_size = -stack_size;
166 total_root_size = 2 * stack_size + GC_root_size;
167 scan_size = 2 * GC_composite_in_use + GC_atomic_in_use/4
169 if (TRUE_INCREMENTAL) {
170 return scan_size / (2 * GC_free_space_divisor);
172 return scan_size / GC_free_space_divisor;
176 /* Return the number of bytes allocated, adjusted for explicit storage */
177 /* management, etc.. This number is used in deciding when to trigger */
179 word GC_adj_bytes_allocd(void)
182 signed_word expl_managed =
183 (signed_word)GC_non_gc_bytes
184 - (signed_word)GC_non_gc_bytes_at_gc;
186 /* Don't count what was explicitly freed, or newly allocated for */
187 /* explicit management. Note that deallocating an explicitly */
188 /* managed object should not alter result, assuming the client */
189 /* is playing by the rules. */
190 result = (signed_word)GC_bytes_allocd
191 + (signed_word)GC_bytes_dropped
192 - (signed_word)GC_bytes_freed
193 + (signed_word)GC_finalizer_bytes_freed
195 if (result > (signed_word)GC_bytes_allocd) {
196 result = GC_bytes_allocd;
197 /* probably client bug or unfortunate scheduling */
199 result += GC_bytes_finalized;
200 /* We count objects enqueued for finalization as though they */
201 /* had been reallocated this round. Finalization is user */
202 /* visible progress. And if we don't count this, we have */
203 /* stability problems for programs that finalize all objects. */
204 if (result < (signed_word)(GC_bytes_allocd >> 3)) {
205 /* Always count at least 1/8 of the allocations. We don't want */
206 /* to collect too infrequently, since that would inhibit */
207 /* coalescing of free storage blocks. */
208 /* This also makes us partially robust against client bugs. */
209 return(GC_bytes_allocd >> 3);
216 /* Clear up a few frames worth of garbage left at the top of the stack. */
217 /* This is used to prevent us from accidentally treating garbade left */
218 /* on the stack by other parts of the collector as roots. This */
219 /* differs from the code in misc.c, which actually tries to keep the */
220 /* stack clear of long-lived, client-generated garbage. */
221 void GC_clear_a_few_frames()
227 for (i = 0; i < NWORDS; i++) frames[i] = 0;
230 /* Heap size at which we need a collection to avoid expanding past */
231 /* limits used by blacklisting. */
232 static word GC_collect_at_heapsize = (word)(-1);
234 /* Have we allocated enough to amortize a collection? */
235 GC_bool GC_should_collect(void)
237 static word last_min_bytes_allocd;
238 static word last_gc_no;
239 if (last_gc_no != GC_gc_no) {
240 last_gc_no = GC_gc_no;
241 last_min_bytes_allocd = min_bytes_allocd();
243 return(GC_adj_bytes_allocd() >= last_min_bytes_allocd
244 || GC_heapsize >= GC_collect_at_heapsize);
248 void GC_notify_full_gc(void)
250 if (GC_start_call_back != (void (*) (void))0) {
251 (*GC_start_call_back)();
255 GC_bool GC_is_full_gc = FALSE;
258 * Initiate a garbage collection if appropriate.
260 * between partial, full, and stop-world collections.
262 void GC_maybe_gc(void)
264 static int n_partial_gcs = 0;
266 GC_ASSERT(I_HOLD_LOCK());
267 if (GC_should_collect()) {
268 if (!GC_incremental) {
273 # ifdef PARALLEL_MARK
274 GC_wait_for_reclaim();
276 if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) {
277 if (GC_print_stats) {
279 "***>Full mark for collection %lu after %ld allocd bytes\n",
280 (unsigned long)GC_gc_no+1,
281 (long)GC_bytes_allocd);
283 GC_promote_black_lists();
284 (void)GC_reclaim_all((GC_stop_func)0, TRUE);
288 GC_is_full_gc = TRUE;
293 /* We try to mark with the world stopped. */
294 /* If we run out of time, this turns into */
295 /* incremental marking. */
297 if (GC_time_limit != GC_TIME_UNLIMITED) { GET_TIME(GC_start_time); }
299 if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED?
300 GC_never_stop_func : GC_timeout_stop_func)) {
301 # ifdef SAVE_CALL_CHAIN
302 GC_save_callers(GC_last_stack);
304 GC_finish_collection();
306 if (!GC_is_full_gc) {
307 /* Count this as the first attempt */
316 * Stop the world garbage collection. Assumes lock held, signals disabled.
317 * If stop_func is not GC_never_stop_func, then abort if stop_func returns TRUE.
318 * Return TRUE if we successfully completed the collection.
320 GC_bool GC_try_to_collect_inner(GC_stop_func stop_func)
322 CLOCK_TYPE start_time, current_time;
323 if (GC_dont_gc) return FALSE;
324 if (GC_incremental && GC_collection_in_progress()) {
325 if (GC_print_stats) {
327 "GC_try_to_collect_inner: finishing collection in progress\n");
329 /* Just finish collection already in progress. */
330 while(GC_collection_in_progress()) {
331 if (stop_func()) return(FALSE);
332 GC_collect_a_little_inner(1);
335 if (stop_func == GC_never_stop_func) GC_notify_full_gc();
336 if (GC_print_stats) {
337 GET_TIME(start_time);
339 "Initiating full world-stop collection %lu after %ld allocd bytes\n",
340 (unsigned long)GC_gc_no+1, (long)GC_bytes_allocd);
342 GC_promote_black_lists();
343 /* Make sure all blocks have been reclaimed, so sweep routines */
344 /* don't see cleared mark bits. */
345 /* If we're guaranteed to finish, then this is unnecessary. */
346 /* In the find_leak case, we have to finish to guarantee that */
347 /* previously unmarked objects are not reported as leaks. */
348 # ifdef PARALLEL_MARK
349 GC_wait_for_reclaim();
351 if ((GC_find_leak || stop_func != GC_never_stop_func)
352 && !GC_reclaim_all(stop_func, FALSE)) {
353 /* Aborted. So far everything is still consistent. */
356 GC_invalidate_mark_state(); /* Flush mark stack. */
358 # ifdef SAVE_CALL_CHAIN
359 GC_save_callers(GC_last_stack);
361 GC_is_full_gc = TRUE;
362 if (!GC_stopped_mark(stop_func)) {
363 if (!GC_incremental) {
364 /* We're partially done and have no way to complete or use */
365 /* current work. Reestablish invariants as cheaply as */
367 GC_invalidate_mark_state();
368 GC_unpromote_black_lists();
369 } /* else we claim the world is already still consistent. We'll */
370 /* finish incrementally. */
373 GC_finish_collection();
374 if (GC_print_stats) {
375 GET_TIME(current_time);
376 GC_log_printf("Complete collection took %lu msecs\n",
377 MS_TIME_DIFF(current_time,start_time));
385 * Perform n units of garbage collection work. A unit is intended to touch
386 * roughly GC_RATE pages. Every once in a while, we do more than that.
387 * This needs to be a fairly large number with our current incremental
388 * GC strategy, since otherwise we allocate too much during GC, and the
389 * cleanup gets expensive.
392 # define MAX_PRIOR_ATTEMPTS 1
393 /* Maximum number of prior attempts at world stop marking */
394 /* A value of 1 means that we finish the second time, no matter */
395 /* how long it takes. Doesn't count the initial root scan */
398 int GC_deficit = 0; /* The number of extra calls to GC_mark_some */
399 /* that we have made. */
401 void GC_collect_a_little_inner(int n)
405 if (GC_dont_gc) return;
406 if (GC_incremental && GC_collection_in_progress()) {
407 for (i = GC_deficit; i < GC_RATE*n; i++) {
408 if (GC_mark_some((ptr_t)0)) {
409 /* Need to finish a collection */
410 # ifdef SAVE_CALL_CHAIN
411 GC_save_callers(GC_last_stack);
413 # ifdef PARALLEL_MARK
414 GC_wait_for_reclaim();
416 if (GC_n_attempts < MAX_PRIOR_ATTEMPTS
417 && GC_time_limit != GC_TIME_UNLIMITED) {
418 GET_TIME(GC_start_time);
419 if (!GC_stopped_mark(GC_timeout_stop_func)) {
424 (void)GC_stopped_mark(GC_never_stop_func);
426 GC_finish_collection();
430 if (GC_deficit > 0) GC_deficit -= GC_RATE*n;
431 if (GC_deficit < 0) GC_deficit = 0;
437 int GC_collect_a_little(void)
443 GC_collect_a_little_inner(1);
444 result = (int)GC_collection_in_progress();
446 if (!result && GC_debugging_started) GC_print_all_smashed();
450 # if !defined(REDIRECT_MALLOC) && (defined(MSWIN32) || defined(MSWINCE))
451 void GC_add_current_malloc_heap();
454 * Assumes lock is held, signals are disabled.
456 * If stop_func() ever returns TRUE, we may fail and return FALSE.
457 * Increment GC_gc_no if we succeed.
459 GC_bool GC_stopped_mark(GC_stop_func stop_func)
463 CLOCK_TYPE start_time, current_time;
466 GET_TIME(start_time);
468 # if !defined(REDIRECT_MALLOC) && (defined(MSWIN32) || defined(MSWINCE))
469 GC_add_current_malloc_heap();
471 # if defined(REGISTER_LIBRARIES_EARLY)
472 GC_cond_register_dynamic_libraries();
475 IF_THREADS(GC_world_stopped = TRUE);
476 if (GC_print_stats) {
477 GC_log_printf("--> Marking for collection %lu ",
478 (unsigned long)GC_gc_no + 1);
479 GC_log_printf("after %lu allocd bytes\n",
480 (unsigned long) GC_bytes_allocd);
482 # ifdef MAKE_BACK_GRAPH
483 if (GC_print_back_height) {
484 GC_build_back_graph();
488 /* Mark from all roots. */
489 /* Minimize junk left in my registers and on the stack */
490 GC_clear_a_few_frames();
491 GC_noop(0,0,0,0,0,0);
494 if ((*stop_func)()) {
495 if (GC_print_stats) {
496 GC_log_printf("Abandoned stopped marking after ");
497 GC_log_printf("%u iterations\n", i);
499 GC_deficit = i; /* Give the mutator a chance. */
500 IF_THREADS(GC_world_stopped = FALSE);
504 if (GC_mark_some((ptr_t)(&dummy))) break;
508 if (GC_print_stats) {
509 GC_log_printf("Collection %lu reclaimed %ld bytes",
510 (unsigned long)GC_gc_no - 1,
511 (long)GC_bytes_found);
512 GC_log_printf(" ---> heapsize = %lu bytes\n",
513 (unsigned long) GC_heapsize);
514 /* Printf arguments may be pushed in funny places. Clear the */
519 /* Check all debugged objects for consistency */
520 if (GC_debugging_started) {
524 IF_THREADS(GC_world_stopped = FALSE);
526 if (GC_print_stats) {
527 GET_TIME(current_time);
528 GC_log_printf("World-stopped marking took %lu msecs\n",
529 MS_TIME_DIFF(current_time,start_time));
534 /* Set all mark bits for the free list whose first entry is q */
535 void GC_set_fl_marks(ptr_t q)
538 struct hblk * h, * last_h = 0;
539 hdr *hhdr; /* gcc "might be uninitialized" warning is bogus. */
540 IF_PER_OBJ(size_t sz;)
543 for (p = q; p != 0; p = obj_link(p)){
548 IF_PER_OBJ(sz = hhdr->hb_sz;)
550 bit_no = MARK_BIT_NO((ptr_t)p - (ptr_t)h, sz);
551 if (!mark_bit_from_hdr(hhdr, bit_no)) {
552 set_mark_bit_from_hdr(hhdr, bit_no);
553 ++hhdr -> hb_n_marks;
559 /* Check that all mark bits for the free list whose first entry is q */
561 void GC_check_fl_marks(ptr_t q)
565 for (p = q; p != 0; p = obj_link(p)){
566 if (!GC_is_marked(p)) {
567 GC_err_printf("Unmarked object %p on list %p\n", p, q);
568 ABORT("Unmarked local free list entry.");
574 /* Clear all mark bits for the free list whose first entry is q */
575 /* Decrement GC_bytes_found by number of bytes on free list. */
576 void GC_clear_fl_marks(ptr_t q)
579 struct hblk * h, * last_h = 0;
584 for (p = q; p != 0; p = obj_link(p)){
589 sz = hhdr->hb_sz; /* Normally set only once. */
591 bit_no = MARK_BIT_NO((ptr_t)p - (ptr_t)h, sz);
592 if (mark_bit_from_hdr(hhdr, bit_no)) {
593 size_t n_marks = hhdr -> hb_n_marks - 1;
594 clear_mark_bit_from_hdr(hhdr, bit_no);
595 # ifdef PARALLEL_MARK
596 /* Appr. count, don't decrement to zero! */
598 hhdr -> hb_n_marks = n_marks;
601 hhdr -> hb_n_marks = n_marks;
604 GC_bytes_found -= sz;
608 #if defined(GC_ASSERTIONS) && defined(THREADS) && defined(THREAD_LOCAL_ALLOC)
609 extern void GC_check_tls(void);
612 /* Finish up a collection. Assumes lock is held, signals are disabled, */
613 /* but the world is otherwise running. */
614 void GC_finish_collection()
616 CLOCK_TYPE start_time;
617 CLOCK_TYPE finalize_time;
618 CLOCK_TYPE done_time;
620 # if defined(GC_ASSERTIONS) && defined(THREADS) \
621 && defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
622 /* Check that we marked some of our own data. */
623 /* FIXME: Add more checks. */
628 GET_TIME(start_time);
631 # if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
632 if (getenv("GC_PRINT_ADDRESS_MAP") != 0) {
633 GC_print_address_map();
638 /* Mark all objects on the free list. All objects should be */
639 /* marked when we're done. */
641 word size; /* current object size */
645 for (kind = 0; kind < GC_n_kinds; kind++) {
646 for (size = 1; size <= MAXOBJGRANULES; size++) {
647 q = GC_obj_kinds[kind].ok_freelist[size];
648 if (q != 0) GC_set_fl_marks(q);
652 GC_start_reclaim(TRUE);
653 /* The above just checks; it doesn't really reclaim anything. */
657 # ifdef STUBBORN_ALLOC
658 GC_clean_changing_list();
662 GET_TIME(finalize_time);
664 if (GC_print_back_height) {
665 # ifdef MAKE_BACK_GRAPH
666 GC_traverse_back_graph();
668 # ifndef SMALL_CONFIG
669 GC_err_printf("Back height not available: "
670 "Rebuild collector with -DMAKE_BACK_GRAPH\n");
675 /* Clear free list mark bits, in case they got accidentally marked */
676 /* (or GC_find_leak is set and they were intentionally marked). */
677 /* Also subtract memory remaining from GC_bytes_found count. */
678 /* Note that composite objects on free list are cleared. */
679 /* Thus accidentally marking a free list is not a problem; only */
680 /* objects on the list itself will be marked, and that's fixed here. */
682 word size; /* current object size */
683 ptr_t q; /* pointer to current object */
686 for (kind = 0; kind < GC_n_kinds; kind++) {
687 for (size = 1; size <= MAXOBJGRANULES; size++) {
688 q = GC_obj_kinds[kind].ok_freelist[size];
689 if (q != 0) GC_clear_fl_marks(q);
695 if (GC_print_stats == VERBOSE)
696 GC_log_printf("Bytes recovered before sweep - f.l. count = %ld\n",
697 (long)GC_bytes_found);
699 /* Reconstruct free lists to contain everything not marked */
700 GC_start_reclaim(FALSE);
701 if (GC_print_stats) {
702 GC_log_printf("Heap contains %lu pointer-containing "
703 "+ %lu pointer-free reachable bytes\n",
704 (unsigned long)GC_composite_in_use,
705 (unsigned long)GC_atomic_in_use);
708 GC_used_heap_size_after_full = USED_HEAP_SIZE;
709 GC_need_full_gc = FALSE;
712 USED_HEAP_SIZE - GC_used_heap_size_after_full
713 > min_bytes_allocd();
716 if (GC_print_stats == VERBOSE) {
718 "Immediately reclaimed %ld bytes in heap of size %lu bytes",
719 (long)GC_bytes_found,
720 (unsigned long)GC_heapsize);
722 GC_log_printf("(%lu unmapped)", (unsigned long)GC_unmapped_bytes);
727 /* Reset or increment counters for next cycle */
729 GC_is_full_gc = FALSE;
730 GC_bytes_allocd_before_gc += GC_bytes_allocd;
731 GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
733 GC_bytes_dropped = 0;
735 GC_finalizer_bytes_freed = 0;
740 if (GC_print_stats) {
742 GC_log_printf("Finalize + initiate sweep took %lu + %lu msecs\n",
743 MS_TIME_DIFF(finalize_time,start_time),
744 MS_TIME_DIFF(done_time,finalize_time));
748 /* Externally callable routine to invoke full, stop-world collection */
749 int GC_try_to_collect(GC_stop_func stop_func)
754 if (!GC_is_initialized) GC_init();
755 if (GC_debugging_started) GC_print_all_smashed();
756 GC_INVOKE_FINALIZERS();
759 if (!GC_is_initialized) GC_init_inner();
760 /* Minimize junk left in my registers */
761 GC_noop(0,0,0,0,0,0);
762 result = (int)GC_try_to_collect_inner(stop_func);
766 if (GC_debugging_started) GC_print_all_smashed();
767 GC_INVOKE_FINALIZERS();
772 void GC_gcollect(void)
774 (void)GC_try_to_collect(GC_never_stop_func);
775 if (GC_have_errors) GC_print_all_errors();
778 word GC_n_heap_sects = 0; /* Number of sections currently in heap. */
780 #ifdef USE_PROC_FOR_LIBRARIES
781 word GC_n_memory = 0; /* Number of GET_MEM allocated memory */
785 #ifdef USE_PROC_FOR_LIBRARIES
786 /* Add HBLKSIZE aligned, GET_MEM-generated block to GC_our_memory. */
787 /* Defined to do nothing if USE_PROC_FOR_LIBRARIES not set. */
788 void GC_add_to_our_memory(ptr_t p, size_t bytes)
791 GC_our_memory[GC_n_memory].hs_start = p;
792 GC_our_memory[GC_n_memory].hs_bytes = bytes;
797 * Use the chunk of memory starting at p of size bytes as part of the heap.
798 * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
800 void GC_add_to_heap(struct hblk *p, size_t bytes)
805 if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
806 ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
808 while ((word)p <= HBLKSIZE) {
809 /* Can't handle memory near address zero. */
812 if (0 == bytes) return;
814 endp = (word)p + bytes;
815 if (endp <= (word)p) {
816 /* Address wrapped. */
818 if (0 == bytes) return;
821 phdr = GC_install_header(p);
823 /* This is extremely unlikely. Can't add it. This will */
824 /* almost certainly result in a 0 return from the allocator, */
825 /* which is entirely appropriate. */
828 GC_ASSERT(endp > (word)p && endp == (word)p + bytes);
829 GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
830 GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
832 phdr -> hb_sz = bytes;
833 phdr -> hb_flags = 0;
835 GC_heapsize += bytes;
836 if ((ptr_t)p <= (ptr_t)GC_least_plausible_heap_addr
837 || GC_least_plausible_heap_addr == 0) {
838 GC_least_plausible_heap_addr = (void *)((ptr_t)p - sizeof(word));
839 /* Making it a little smaller than necessary prevents */
840 /* us from getting a false hit from the variable */
841 /* itself. There's some unintentional reflection */
844 if ((ptr_t)p + bytes >= (ptr_t)GC_greatest_plausible_heap_addr) {
845 GC_greatest_plausible_heap_addr = (void *)endp;
849 # if !defined(NO_DEBUGGING)
850 void GC_print_heap_sects(void)
854 GC_printf("Total heap size: %lu\n", (unsigned long) GC_heapsize);
855 for (i = 0; i < GC_n_heap_sects; i++) {
856 ptr_t start = GC_heap_sects[i].hs_start;
857 size_t len = GC_heap_sects[i].hs_bytes;
861 GC_printf("Section %d from %p to %p ", i,
863 for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) {
864 if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
866 GC_printf("%lu/%lu blacklisted\n", (unsigned long)nbl,
867 (unsigned long)(len/HBLKSIZE));
872 void * GC_least_plausible_heap_addr = (void *)ONES;
873 void * GC_greatest_plausible_heap_addr = 0;
875 static INLINE word GC_max(word x, word y)
877 return(x > y? x : y);
880 static INLINE word GC_min(word x, word y)
882 return(x < y? x : y);
885 void GC_set_max_heap_size(GC_word n)
890 GC_word GC_max_retries = 0;
893 * this explicitly increases the size of the heap. It is used
894 * internally, but may also be invoked from GC_expand_hp by the user.
895 * The argument is in units of HBLKSIZE.
896 * Tiny values of n are rounded up.
897 * Returns FALSE on failure.
899 GC_bool GC_expand_hp_inner(word n)
903 word expansion_slop; /* Number of bytes by which we expect the */
904 /* heap to expand soon. */
906 if (n < MINHINCR) n = MINHINCR;
907 bytes = n * HBLKSIZE;
908 /* Make sure bytes is a multiple of GC_page_size */
910 word mask = GC_page_size - 1;
915 if (GC_max_heapsize != 0 && GC_heapsize + bytes > GC_max_heapsize) {
916 /* Exceeded self-imposed limit */
919 space = GET_MEM(bytes);
920 GC_add_to_our_memory((ptr_t)space, bytes);
922 if (GC_print_stats) {
923 GC_log_printf("Failed to expand heap by %ld bytes\n",
924 (unsigned long)bytes);
928 if (GC_print_stats) {
929 GC_log_printf("Increasing heap size by %lu after %lu allocated bytes\n",
930 (unsigned long)bytes,
931 (unsigned long)GC_bytes_allocd);
933 /* Adjust heap limits generously for blacklisting to work better. */
934 /* GC_add_to_heap performs minimal adjustment need for correctness. */
935 expansion_slop = min_bytes_allocd() + 4*MAXHINCR*HBLKSIZE;
936 if ((GC_last_heap_addr == 0 && !((word)space & SIGNB))
937 || (GC_last_heap_addr != 0 && GC_last_heap_addr < (ptr_t)space)) {
938 /* Assume the heap is growing up */
939 word new_limit = (word)space + bytes + expansion_slop;
940 if (new_limit > (word)space) {
941 GC_greatest_plausible_heap_addr =
942 (void *)GC_max((word)GC_greatest_plausible_heap_addr,
946 /* Heap is growing down */
947 word new_limit = (word)space - expansion_slop;
948 if (new_limit < (word)space) {
949 GC_least_plausible_heap_addr =
950 (void *)GC_min((word)GC_least_plausible_heap_addr,
951 (word)space - expansion_slop);
954 GC_prev_heap_addr = GC_last_heap_addr;
955 GC_last_heap_addr = (ptr_t)space;
956 GC_add_to_heap(space, bytes);
957 /* Force GC before we are likely to allocate past expansion_slop */
958 GC_collect_at_heapsize =
959 GC_heapsize + expansion_slop - 2*MAXHINCR*HBLKSIZE;
960 # if defined(LARGE_CONFIG)
961 if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
962 GC_collect_at_heapsize = (word)(-1);
967 /* Really returns a bool, but it's externally visible, so that's clumsy. */
968 /* Arguments is in bytes. */
969 int GC_expand_hp(size_t bytes)
975 if (!GC_is_initialized) GC_init_inner();
976 result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
977 if (result) GC_requested_heapsize += bytes;
982 unsigned GC_fail_count = 0;
983 /* How many consecutive GC/expansion failures? */
984 /* Reset by GC_allochblk. */
986 GC_bool GC_collect_or_expand(word needed_blocks, GC_bool ignore_off_page)
988 if (!GC_incremental && !GC_dont_gc &&
989 ((GC_dont_expand && GC_bytes_allocd > 0) || GC_should_collect())) {
992 word blocks_to_get = GC_heapsize/(HBLKSIZE*GC_free_space_divisor)
995 if (blocks_to_get > MAXHINCR) {
998 /* Get the minimum required to make it likely that we */
999 /* can satisfy the current request in the presence of black- */
1000 /* listing. This will probably be more than MAXHINCR. */
1001 if (ignore_off_page) {
1004 slop = 2*divHBLKSZ(BL_LIMIT);
1005 if (slop > needed_blocks) slop = needed_blocks;
1007 if (needed_blocks + slop > MAXHINCR) {
1008 blocks_to_get = needed_blocks + slop;
1010 blocks_to_get = MAXHINCR;
1013 if (!GC_expand_hp_inner(blocks_to_get)
1014 && !GC_expand_hp_inner(needed_blocks)) {
1015 if (GC_fail_count++ < GC_max_retries) {
1016 WARN("Out of Memory! Trying to continue ...\n", 0);
1017 GC_gcollect_inner();
1019 # if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
1020 WARN("Out of Memory! Returning NIL!\n", 0);
1025 if (GC_fail_count && GC_print_stats) {
1026 GC_printf("Memory available again ...\n");
1034 * Make sure the object free list for size gran (in granules) is not empty.
1035 * Return a pointer to the first object on the free list.
1036 * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
1037 * Assumes we hold the allocator lock and signals are disabled.
1040 ptr_t GC_allocobj(size_t gran, int kind)
1042 void ** flh = &(GC_obj_kinds[kind].ok_freelist[gran]);
1043 GC_bool tried_minor = FALSE;
1045 if (gran == 0) return(0);
1049 /* Do our share of marking work */
1050 if(TRUE_INCREMENTAL) GC_collect_a_little_inner(1);
1051 /* Sweep blocks for objects of this size */
1052 GC_continue_reclaim(gran, kind);
1055 GC_new_hblk(gran, kind);
1059 if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED
1060 && ! tried_minor ) {
1061 GC_collect_a_little_inner(1);
1064 if (!GC_collect_or_expand((word)1,FALSE)) {
1072 /* Successful allocation; reset failure count. */