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." };
94 /* Version macros are now defined in gc_version.h, which is included by */
95 /* gc.h, which is included by gc_priv.h". */
97 #ifndef GC_NO_VERSION_VAR
99 unsigned GC_version = ((GC_VERSION_MAJOR << 16) | (GC_VERSION_MINOR << 8) | GC_TMP_ALPHA_VERSION);
101 #endif /* GC_NO_VERSION_VAR */
103 /* some more variables */
105 extern signed_word GC_bytes_found; /* Number of reclaimed bytes */
106 /* after garbage collection */
108 GC_bool GC_dont_expand = 0;
110 word GC_free_space_divisor = 3;
112 extern GC_bool GC_collection_in_progress();
113 /* Collection is in progress, or was abandoned. */
115 int GC_never_stop_func (void) { return(0); }
117 unsigned long GC_time_limit = TIME_LIMIT;
119 CLOCK_TYPE GC_start_time; /* Time at which we stopped world. */
120 /* used only in GC_timeout_stop_func. */
122 int GC_n_attempts = 0; /* Number of attempts at finishing */
123 /* collection within GC_time_limit. */
125 #if defined(SMALL_CONFIG) || defined(NO_CLOCK)
126 # define GC_timeout_stop_func GC_never_stop_func
128 int GC_timeout_stop_func (void)
130 CLOCK_TYPE current_time;
131 static unsigned count = 0;
132 unsigned long time_diff;
134 if ((count++ & 3) != 0) return(0);
135 GET_TIME(current_time);
136 time_diff = MS_TIME_DIFF(current_time,GC_start_time);
137 if (time_diff >= GC_time_limit) {
138 if (GC_print_stats) {
139 GC_log_printf("Abandoning stopped marking after ");
140 GC_log_printf("%lu msecs", time_diff);
141 GC_log_printf("(attempt %d)\n", GC_n_attempts);
147 #endif /* !SMALL_CONFIG */
149 /* Return the minimum number of words that must be allocated between */
150 /* collections to amortize the collection cost. */
151 static word min_bytes_allocd()
154 /* We punt, for now. */
155 signed_word stack_size = 10000;
158 signed_word stack_size = (ptr_t)(&dummy) - GC_stackbottom;
160 word total_root_size; /* includes double stack size, */
161 /* since the stack is expensive */
163 word scan_size; /* Estimate of memory to be scanned */
164 /* during normal GC. */
166 if (stack_size < 0) stack_size = -stack_size;
167 total_root_size = 2 * stack_size + GC_root_size;
168 scan_size = 2 * GC_composite_in_use + GC_atomic_in_use/4
170 if (TRUE_INCREMENTAL) {
171 return scan_size / (2 * GC_free_space_divisor);
173 return scan_size / GC_free_space_divisor;
177 /* Return the number of bytes allocated, adjusted for explicit storage */
178 /* management, etc.. This number is used in deciding when to trigger */
180 word GC_adj_bytes_allocd(void)
183 signed_word expl_managed =
184 (signed_word)GC_non_gc_bytes
185 - (signed_word)GC_non_gc_bytes_at_gc;
187 /* Don't count what was explicitly freed, or newly allocated for */
188 /* explicit management. Note that deallocating an explicitly */
189 /* managed object should not alter result, assuming the client */
190 /* is playing by the rules. */
191 result = (signed_word)GC_bytes_allocd
192 + (signed_word)GC_bytes_dropped
193 - (signed_word)GC_bytes_freed
194 + (signed_word)GC_finalizer_bytes_freed
196 if (result > (signed_word)GC_bytes_allocd) {
197 result = GC_bytes_allocd;
198 /* probably client bug or unfortunate scheduling */
200 result += GC_bytes_finalized;
201 /* We count objects enqueued for finalization as though they */
202 /* had been reallocated this round. Finalization is user */
203 /* visible progress. And if we don't count this, we have */
204 /* stability problems for programs that finalize all objects. */
205 if (result < (signed_word)(GC_bytes_allocd >> 3)) {
206 /* Always count at least 1/8 of the allocations. We don't want */
207 /* to collect too infrequently, since that would inhibit */
208 /* coalescing of free storage blocks. */
209 /* This also makes us partially robust against client bugs. */
210 return(GC_bytes_allocd >> 3);
217 /* Clear up a few frames worth of garbage left at the top of the stack. */
218 /* This is used to prevent us from accidentally treating garbade left */
219 /* on the stack by other parts of the collector as roots. This */
220 /* differs from the code in misc.c, which actually tries to keep the */
221 /* stack clear of long-lived, client-generated garbage. */
222 void GC_clear_a_few_frames()
228 for (i = 0; i < NWORDS; i++) frames[i] = 0;
231 /* Heap size at which we need a collection to avoid expanding past */
232 /* limits used by blacklisting. */
233 static word GC_collect_at_heapsize = (word)(-1);
235 /* Have we allocated enough to amortize a collection? */
236 GC_bool GC_should_collect(void)
238 static word last_min_bytes_allocd;
239 static word last_gc_no;
240 if (last_gc_no != GC_gc_no) {
241 last_gc_no = GC_gc_no;
242 last_min_bytes_allocd = min_bytes_allocd();
244 return(GC_adj_bytes_allocd() >= last_min_bytes_allocd
245 || GC_heapsize >= GC_collect_at_heapsize);
249 void GC_notify_full_gc(void)
251 if (GC_start_call_back != (void (*) (void))0) {
252 (*GC_start_call_back)();
256 GC_bool GC_is_full_gc = FALSE;
259 * Initiate a garbage collection if appropriate.
261 * between partial, full, and stop-world collections.
263 void GC_maybe_gc(void)
265 static int n_partial_gcs = 0;
267 GC_ASSERT(I_HOLD_LOCK());
268 if (GC_should_collect()) {
269 if (!GC_incremental) {
274 # ifdef PARALLEL_MARK
275 GC_wait_for_reclaim();
277 if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) {
278 if (GC_print_stats) {
280 "***>Full mark for collection %lu after %ld allocd bytes\n",
281 (unsigned long)GC_gc_no+1,
282 (long)GC_bytes_allocd);
284 GC_promote_black_lists();
285 (void)GC_reclaim_all((GC_stop_func)0, TRUE);
289 GC_is_full_gc = TRUE;
294 /* We try to mark with the world stopped. */
295 /* If we run out of time, this turns into */
296 /* incremental marking. */
298 if (GC_time_limit != GC_TIME_UNLIMITED) { GET_TIME(GC_start_time); }
300 if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED?
301 GC_never_stop_func : GC_timeout_stop_func)) {
302 # ifdef SAVE_CALL_CHAIN
303 GC_save_callers(GC_last_stack);
305 GC_finish_collection();
307 if (!GC_is_full_gc) {
308 /* Count this as the first attempt */
317 * Stop the world garbage collection. Assumes lock held, signals disabled.
318 * If stop_func is not GC_never_stop_func, then abort if stop_func returns TRUE.
319 * Return TRUE if we successfully completed the collection.
321 GC_bool GC_try_to_collect_inner(GC_stop_func stop_func)
323 CLOCK_TYPE start_time, current_time;
324 if (GC_dont_gc) return FALSE;
325 if (GC_incremental && GC_collection_in_progress()) {
326 if (GC_print_stats) {
328 "GC_try_to_collect_inner: finishing collection in progress\n");
330 /* Just finish collection already in progress. */
331 while(GC_collection_in_progress()) {
332 if (stop_func()) return(FALSE);
333 GC_collect_a_little_inner(1);
336 if (stop_func == GC_never_stop_func) GC_notify_full_gc();
337 if (GC_print_stats) {
338 GET_TIME(start_time);
340 "Initiating full world-stop collection %lu after %ld allocd bytes\n",
341 (unsigned long)GC_gc_no+1, (long)GC_bytes_allocd);
343 GC_promote_black_lists();
344 /* Make sure all blocks have been reclaimed, so sweep routines */
345 /* don't see cleared mark bits. */
346 /* If we're guaranteed to finish, then this is unnecessary. */
347 /* In the find_leak case, we have to finish to guarantee that */
348 /* previously unmarked objects are not reported as leaks. */
349 # ifdef PARALLEL_MARK
350 GC_wait_for_reclaim();
352 if ((GC_find_leak || stop_func != GC_never_stop_func)
353 && !GC_reclaim_all(stop_func, FALSE)) {
354 /* Aborted. So far everything is still consistent. */
357 GC_invalidate_mark_state(); /* Flush mark stack. */
359 # ifdef SAVE_CALL_CHAIN
360 GC_save_callers(GC_last_stack);
362 GC_is_full_gc = TRUE;
363 if (!GC_stopped_mark(stop_func)) {
364 if (!GC_incremental) {
365 /* We're partially done and have no way to complete or use */
366 /* current work. Reestablish invariants as cheaply as */
368 GC_invalidate_mark_state();
369 GC_unpromote_black_lists();
370 } /* else we claim the world is already still consistent. We'll */
371 /* finish incrementally. */
374 GC_finish_collection();
375 if (GC_print_stats) {
376 GET_TIME(current_time);
377 GC_log_printf("Complete collection took %lu msecs\n",
378 MS_TIME_DIFF(current_time,start_time));
386 * Perform n units of garbage collection work. A unit is intended to touch
387 * roughly GC_RATE pages. Every once in a while, we do more than that.
388 * This needs to be a fairly large number with our current incremental
389 * GC strategy, since otherwise we allocate too much during GC, and the
390 * cleanup gets expensive.
393 # define MAX_PRIOR_ATTEMPTS 1
394 /* Maximum number of prior attempts at world stop marking */
395 /* A value of 1 means that we finish the second time, no matter */
396 /* how long it takes. Doesn't count the initial root scan */
399 int GC_deficit = 0; /* The number of extra calls to GC_mark_some */
400 /* that we have made. */
402 void GC_collect_a_little_inner(int n)
406 if (GC_dont_gc) return;
407 if (GC_incremental && GC_collection_in_progress()) {
408 for (i = GC_deficit; i < GC_RATE*n; i++) {
409 if (GC_mark_some((ptr_t)0)) {
410 /* Need to finish a collection */
411 # ifdef SAVE_CALL_CHAIN
412 GC_save_callers(GC_last_stack);
414 # ifdef PARALLEL_MARK
415 GC_wait_for_reclaim();
417 if (GC_n_attempts < MAX_PRIOR_ATTEMPTS
418 && GC_time_limit != GC_TIME_UNLIMITED) {
419 GET_TIME(GC_start_time);
420 if (!GC_stopped_mark(GC_timeout_stop_func)) {
425 (void)GC_stopped_mark(GC_never_stop_func);
427 GC_finish_collection();
431 if (GC_deficit > 0) GC_deficit -= GC_RATE*n;
432 if (GC_deficit < 0) GC_deficit = 0;
438 int GC_collect_a_little(void)
444 GC_collect_a_little_inner(1);
445 result = (int)GC_collection_in_progress();
447 if (!result && GC_debugging_started) GC_print_all_smashed();
451 # if !defined(REDIRECT_MALLOC) && (defined(MSWIN32) || defined(MSWINCE))
452 void GC_add_current_malloc_heap();
455 * Assumes lock is held, signals are disabled.
457 * If stop_func() ever returns TRUE, we may fail and return FALSE.
458 * Increment GC_gc_no if we succeed.
460 GC_bool GC_stopped_mark(GC_stop_func stop_func)
464 CLOCK_TYPE start_time, current_time;
467 GET_TIME(start_time);
469 # if !defined(REDIRECT_MALLOC) && (defined(MSWIN32) || defined(MSWINCE))
470 GC_add_current_malloc_heap();
472 # if defined(REGISTER_LIBRARIES_EARLY)
473 GC_cond_register_dynamic_libraries();
476 IF_THREADS(GC_world_stopped = TRUE);
477 if (GC_print_stats) {
478 GC_log_printf("--> Marking for collection %lu ",
479 (unsigned long)GC_gc_no + 1);
480 GC_log_printf("after %lu allocd bytes\n",
481 (unsigned long) GC_bytes_allocd);
483 # ifdef MAKE_BACK_GRAPH
484 if (GC_print_back_height) {
485 GC_build_back_graph();
489 /* Mark from all roots. */
490 /* Minimize junk left in my registers and on the stack */
491 GC_clear_a_few_frames();
492 GC_noop(0,0,0,0,0,0);
495 if ((*stop_func)()) {
496 if (GC_print_stats) {
497 GC_log_printf("Abandoned stopped marking after ");
498 GC_log_printf("%u iterations\n", i);
500 GC_deficit = i; /* Give the mutator a chance. */
501 IF_THREADS(GC_world_stopped = FALSE);
505 if (GC_mark_some((ptr_t)(&dummy))) break;
509 if (GC_print_stats) {
510 GC_log_printf("Collection %lu reclaimed %ld bytes",
511 (unsigned long)GC_gc_no - 1,
512 (long)GC_bytes_found);
513 GC_log_printf(" ---> heapsize = %lu bytes\n",
514 (unsigned long) GC_heapsize);
515 /* Printf arguments may be pushed in funny places. Clear the */
520 /* Check all debugged objects for consistency */
521 if (GC_debugging_started) {
525 IF_THREADS(GC_world_stopped = FALSE);
527 if (GC_print_stats) {
528 GET_TIME(current_time);
529 GC_log_printf("World-stopped marking took %lu msecs\n",
530 MS_TIME_DIFF(current_time,start_time));
535 /* Set all mark bits for the free list whose first entry is q */
536 void GC_set_fl_marks(ptr_t q)
539 struct hblk * h, * last_h = 0;
540 hdr *hhdr; /* gcc "might be uninitialized" warning is bogus. */
541 IF_PER_OBJ(size_t sz;)
544 for (p = q; p != 0; p = obj_link(p)){
549 IF_PER_OBJ(sz = hhdr->hb_sz;)
551 bit_no = MARK_BIT_NO((ptr_t)p - (ptr_t)h, sz);
552 if (!mark_bit_from_hdr(hhdr, bit_no)) {
553 set_mark_bit_from_hdr(hhdr, bit_no);
554 ++hhdr -> hb_n_marks;
560 /* Check that all mark bits for the free list whose first entry is q */
562 void GC_check_fl_marks(ptr_t q)
566 for (p = q; p != 0; p = obj_link(p)){
567 if (!GC_is_marked(p)) {
568 GC_err_printf("Unmarked object %p on list %p\n", p, q);
569 ABORT("Unmarked local free list entry.");
575 /* Clear all mark bits for the free list whose first entry is q */
576 /* Decrement GC_bytes_found by number of bytes on free list. */
577 void GC_clear_fl_marks(ptr_t q)
580 struct hblk * h, * last_h = 0;
585 for (p = q; p != 0; p = obj_link(p)){
590 sz = hhdr->hb_sz; /* Normally set only once. */
592 bit_no = MARK_BIT_NO((ptr_t)p - (ptr_t)h, sz);
593 if (mark_bit_from_hdr(hhdr, bit_no)) {
594 size_t n_marks = hhdr -> hb_n_marks - 1;
595 clear_mark_bit_from_hdr(hhdr, bit_no);
596 # ifdef PARALLEL_MARK
597 /* Appr. count, don't decrement to zero! */
599 hhdr -> hb_n_marks = n_marks;
602 hhdr -> hb_n_marks = n_marks;
605 GC_bytes_found -= sz;
609 #if defined(GC_ASSERTIONS) && defined(THREADS) && defined(THREAD_LOCAL_ALLOC)
610 extern void GC_check_tls(void);
613 /* Finish up a collection. Assumes lock is held, signals are disabled, */
614 /* but the world is otherwise running. */
615 void GC_finish_collection()
617 CLOCK_TYPE start_time;
618 CLOCK_TYPE finalize_time;
619 CLOCK_TYPE done_time;
621 # if defined(GC_ASSERTIONS) && defined(THREADS) \
622 && defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
623 /* Check that we marked some of our own data. */
624 /* FIXME: Add more checks. */
629 GET_TIME(start_time);
632 # if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
633 if (getenv("GC_PRINT_ADDRESS_MAP") != 0) {
634 GC_print_address_map();
639 /* Mark all objects on the free list. All objects should be */
640 /* marked when we're done. */
642 word size; /* current object size */
646 for (kind = 0; kind < GC_n_kinds; kind++) {
647 for (size = 1; size <= MAXOBJGRANULES; size++) {
648 q = GC_obj_kinds[kind].ok_freelist[size];
649 if (q != 0) GC_set_fl_marks(q);
653 GC_start_reclaim(TRUE);
654 /* The above just checks; it doesn't really reclaim anything. */
658 # ifdef STUBBORN_ALLOC
659 GC_clean_changing_list();
663 GET_TIME(finalize_time);
665 if (GC_print_back_height) {
666 # ifdef MAKE_BACK_GRAPH
667 GC_traverse_back_graph();
669 # ifndef SMALL_CONFIG
670 GC_err_printf("Back height not available: "
671 "Rebuild collector with -DMAKE_BACK_GRAPH\n");
676 /* Clear free list mark bits, in case they got accidentally marked */
677 /* (or GC_find_leak is set and they were intentionally marked). */
678 /* Also subtract memory remaining from GC_bytes_found count. */
679 /* Note that composite objects on free list are cleared. */
680 /* Thus accidentally marking a free list is not a problem; only */
681 /* objects on the list itself will be marked, and that's fixed here. */
683 word size; /* current object size */
684 ptr_t q; /* pointer to current object */
687 for (kind = 0; kind < GC_n_kinds; kind++) {
688 for (size = 1; size <= MAXOBJGRANULES; size++) {
689 q = GC_obj_kinds[kind].ok_freelist[size];
690 if (q != 0) GC_clear_fl_marks(q);
696 if (GC_print_stats == VERBOSE)
697 GC_log_printf("Bytes recovered before sweep - f.l. count = %ld\n",
698 (long)GC_bytes_found);
700 /* Reconstruct free lists to contain everything not marked */
701 GC_start_reclaim(FALSE);
702 if (GC_print_stats) {
703 GC_log_printf("Heap contains %lu pointer-containing "
704 "+ %lu pointer-free reachable bytes\n",
705 (unsigned long)GC_composite_in_use,
706 (unsigned long)GC_atomic_in_use);
709 GC_used_heap_size_after_full = USED_HEAP_SIZE;
710 GC_need_full_gc = FALSE;
713 USED_HEAP_SIZE - GC_used_heap_size_after_full
714 > min_bytes_allocd();
717 if (GC_print_stats == VERBOSE) {
719 "Immediately reclaimed %ld bytes in heap of size %lu bytes",
720 (long)GC_bytes_found,
721 (unsigned long)GC_heapsize);
723 GC_log_printf("(%lu unmapped)", (unsigned long)GC_unmapped_bytes);
728 /* Reset or increment counters for next cycle */
730 GC_is_full_gc = FALSE;
731 GC_bytes_allocd_before_gc += GC_bytes_allocd;
732 GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
734 GC_bytes_dropped = 0;
736 GC_finalizer_bytes_freed = 0;
741 if (GC_print_stats) {
743 GC_log_printf("Finalize + initiate sweep took %lu + %lu msecs\n",
744 MS_TIME_DIFF(finalize_time,start_time),
745 MS_TIME_DIFF(done_time,finalize_time));
749 /* Externally callable routine to invoke full, stop-world collection */
750 int GC_try_to_collect(GC_stop_func stop_func)
755 if (!GC_is_initialized) GC_init();
756 if (GC_debugging_started) GC_print_all_smashed();
757 GC_INVOKE_FINALIZERS();
760 if (!GC_is_initialized) GC_init_inner();
761 /* Minimize junk left in my registers */
762 GC_noop(0,0,0,0,0,0);
763 result = (int)GC_try_to_collect_inner(stop_func);
767 if (GC_debugging_started) GC_print_all_smashed();
768 GC_INVOKE_FINALIZERS();
773 void GC_gcollect(void)
775 (void)GC_try_to_collect(GC_never_stop_func);
776 if (GC_have_errors) GC_print_all_errors();
779 word GC_n_heap_sects = 0; /* Number of sections currently in heap. */
781 #ifdef USE_PROC_FOR_LIBRARIES
782 word GC_n_memory = 0; /* Number of GET_MEM allocated memory */
786 #ifdef USE_PROC_FOR_LIBRARIES
787 /* Add HBLKSIZE aligned, GET_MEM-generated block to GC_our_memory. */
788 /* Defined to do nothing if USE_PROC_FOR_LIBRARIES not set. */
789 void GC_add_to_our_memory(ptr_t p, size_t bytes)
792 GC_our_memory[GC_n_memory].hs_start = p;
793 GC_our_memory[GC_n_memory].hs_bytes = bytes;
798 * Use the chunk of memory starting at p of size bytes as part of the heap.
799 * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
801 void GC_add_to_heap(struct hblk *p, size_t bytes)
806 if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
807 ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
809 while ((word)p <= HBLKSIZE) {
810 /* Can't handle memory near address zero. */
813 if (0 == bytes) return;
815 endp = (word)p + bytes;
816 if (endp <= (word)p) {
817 /* Address wrapped. */
819 if (0 == bytes) return;
822 phdr = GC_install_header(p);
824 /* This is extremely unlikely. Can't add it. This will */
825 /* almost certainly result in a 0 return from the allocator, */
826 /* which is entirely appropriate. */
829 GC_ASSERT(endp > (word)p && endp == (word)p + bytes);
830 GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
831 GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
833 phdr -> hb_sz = bytes;
834 phdr -> hb_flags = 0;
836 GC_heapsize += bytes;
837 if ((ptr_t)p <= (ptr_t)GC_least_plausible_heap_addr
838 || GC_least_plausible_heap_addr == 0) {
839 GC_least_plausible_heap_addr = (void *)((ptr_t)p - sizeof(word));
840 /* Making it a little smaller than necessary prevents */
841 /* us from getting a false hit from the variable */
842 /* itself. There's some unintentional reflection */
845 if ((ptr_t)p + bytes >= (ptr_t)GC_greatest_plausible_heap_addr) {
846 GC_greatest_plausible_heap_addr = (void *)endp;
850 # if !defined(NO_DEBUGGING)
851 void GC_print_heap_sects(void)
855 GC_printf("Total heap size: %lu\n", (unsigned long) GC_heapsize);
856 for (i = 0; i < GC_n_heap_sects; i++) {
857 ptr_t start = GC_heap_sects[i].hs_start;
858 size_t len = GC_heap_sects[i].hs_bytes;
862 GC_printf("Section %d from %p to %p ", i,
864 for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) {
865 if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
867 GC_printf("%lu/%lu blacklisted\n", (unsigned long)nbl,
868 (unsigned long)(len/HBLKSIZE));
873 void * GC_least_plausible_heap_addr = (void *)ONES;
874 void * GC_greatest_plausible_heap_addr = 0;
876 static INLINE word GC_max(word x, word y)
878 return(x > y? x : y);
881 static INLINE word GC_min(word x, word y)
883 return(x < y? x : y);
886 void GC_set_max_heap_size(GC_word n)
891 word GC_get_max_heap_size()
893 return GC_max_heapsize;
896 GC_word GC_max_retries = 0;
899 * this explicitly increases the size of the heap. It is used
900 * internally, but may also be invoked from GC_expand_hp by the user.
901 * The argument is in units of HBLKSIZE.
902 * Tiny values of n are rounded up.
903 * Returns FALSE on failure.
905 GC_bool GC_expand_hp_inner(word n)
909 word expansion_slop; /* Number of bytes by which we expect the */
910 /* heap to expand soon. */
912 if (n < MINHINCR) n = MINHINCR;
913 bytes = n * HBLKSIZE;
914 /* Make sure bytes is a multiple of GC_page_size */
916 word mask = GC_page_size - 1;
921 if (GC_max_heapsize != 0 && GC_heapsize + bytes > GC_max_heapsize) {
922 /* Exceeded self-imposed limit */
925 space = GET_MEM(bytes);
926 GC_add_to_our_memory((ptr_t)space, bytes);
928 if (GC_print_stats) {
929 GC_log_printf("Failed to expand heap by %ld bytes\n",
930 (unsigned long)bytes);
934 if (GC_print_stats) {
935 GC_log_printf("Increasing heap size by %lu after %lu allocated bytes\n",
936 (unsigned long)bytes,
937 (unsigned long)GC_bytes_allocd);
939 /* Adjust heap limits generously for blacklisting to work better. */
940 /* GC_add_to_heap performs minimal adjustment need for correctness. */
941 expansion_slop = min_bytes_allocd() + 4*MAXHINCR*HBLKSIZE;
942 if ((GC_last_heap_addr == 0 && !((word)space & SIGNB))
943 || (GC_last_heap_addr != 0 && GC_last_heap_addr < (ptr_t)space)) {
944 /* Assume the heap is growing up */
945 word new_limit = (word)space + bytes + expansion_slop;
946 if (new_limit > (word)space) {
947 GC_greatest_plausible_heap_addr =
948 (void *)GC_max((word)GC_greatest_plausible_heap_addr,
952 /* Heap is growing down */
953 word new_limit = (word)space - expansion_slop;
954 if (new_limit < (word)space) {
955 GC_least_plausible_heap_addr =
956 (void *)GC_min((word)GC_least_plausible_heap_addr,
957 (word)space - expansion_slop);
960 GC_prev_heap_addr = GC_last_heap_addr;
961 GC_last_heap_addr = (ptr_t)space;
962 GC_add_to_heap(space, bytes);
963 /* Force GC before we are likely to allocate past expansion_slop */
964 GC_collect_at_heapsize =
965 GC_heapsize + expansion_slop - 2*MAXHINCR*HBLKSIZE;
966 # if defined(LARGE_CONFIG)
967 if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
968 GC_collect_at_heapsize = (word)(-1);
973 /* Really returns a bool, but it's externally visible, so that's clumsy. */
974 /* Arguments is in bytes. */
975 int GC_expand_hp(size_t bytes)
981 if (!GC_is_initialized) GC_init_inner();
982 result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
983 if (result) GC_requested_heapsize += bytes;
988 unsigned GC_fail_count = 0;
989 /* How many consecutive GC/expansion failures? */
990 /* Reset by GC_allochblk. */
992 GC_bool GC_collect_or_expand(word needed_blocks, GC_bool ignore_off_page)
994 if (!GC_incremental && !GC_dont_gc &&
995 ((GC_dont_expand && GC_bytes_allocd > 0) || GC_should_collect())) {
998 word blocks_to_get = GC_heapsize/(HBLKSIZE*GC_free_space_divisor)
1001 if (blocks_to_get > MAXHINCR) {
1004 /* Get the minimum required to make it likely that we */
1005 /* can satisfy the current request in the presence of black- */
1006 /* listing. This will probably be more than MAXHINCR. */
1007 if (ignore_off_page) {
1010 slop = 2*divHBLKSZ(BL_LIMIT);
1011 if (slop > needed_blocks) slop = needed_blocks;
1013 if (needed_blocks + slop > MAXHINCR) {
1014 blocks_to_get = needed_blocks + slop;
1016 blocks_to_get = MAXHINCR;
1019 if (!GC_expand_hp_inner(blocks_to_get)
1020 && !GC_expand_hp_inner(needed_blocks)) {
1021 if (GC_fail_count++ < GC_max_retries) {
1022 WARN("Out of Memory! Trying to continue ...\n", 0);
1023 GC_gcollect_inner();
1025 # if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
1026 WARN("Out of Memory! Returning NIL!\n", 0);
1031 if (GC_fail_count && GC_print_stats) {
1032 GC_printf("Memory available again ...\n");
1040 * Make sure the object free list for size gran (in granules) is not empty.
1041 * Return a pointer to the first object on the free list.
1042 * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
1043 * Assumes we hold the allocator lock and signals are disabled.
1046 ptr_t GC_allocobj(size_t gran, int kind)
1048 void ** flh = &(GC_obj_kinds[kind].ok_freelist[gran]);
1049 GC_bool tried_minor = FALSE;
1051 if (gran == 0) return(0);
1055 /* Do our share of marking work */
1056 if(TRUE_INCREMENTAL) GC_collect_a_little_inner(1);
1057 /* Sweep blocks for objects of this size */
1058 GC_continue_reclaim(gran, kind);
1061 GC_new_hblk(gran, kind);
1065 if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED
1066 && ! tried_minor ) {
1067 GC_collect_a_little_inner(1);
1070 if (!GC_collect_or_expand((word)1,FALSE)) {
1078 /* Successful allocation; reset failure count. */