Pass pointer to RTX when calling alter_subreg().
[official-gcc.git] / boehm-gc / alloc.c
blob1664e4a4df54dfbd0b3e60751b8420b82abe9b1b
1 /*
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 by Hewlett-Packard Company. All rights reserved.
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"
21 # include <stdio.h>
22 # if !defined(MACOS) && !defined(MSWINCE)
23 # include <signal.h>
24 # include <sys/types.h>
25 # endif
28 * Separate free lists are maintained for different sized objects
29 * up to MAXOBJSZ.
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);
38 * ptr = *opp;
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
44 * their first word.
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
55 * allocator.
58 word GC_non_gc_bytes = 0; /* Number of bytes not intended to be collected */
60 word GC_gc_no = 0;
62 #ifndef SMALL_CONFIG
63 int GC_incremental = 0; /* By default, stop the world. */
64 #endif
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 */
70 /* or not. */
72 GC_bool GC_need_full_gc = FALSE;
73 /* Need full GC do to heap growth. */
75 word GC_used_heap_size_after_full = 0;
77 char * GC_copyright[] =
78 {"Copyright 1988,1989 Hans-J. Boehm and Alan J. Demers ",
79 "Copyright (c) 1991-1995 by Xerox Corporation. All rights reserved. ",
80 "Copyright (c) 1996-1998 by Silicon Graphics. All rights reserved. ",
81 "Copyright (c) 1999-2000 by Hewlett-Packard Company. All rights reserved. ",
82 "THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY",
83 " EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.",
84 "See source code for details." };
86 # include "version.h"
88 /* some more variables */
90 extern signed_word GC_mem_found; /* Number of reclaimed longwords */
91 /* after garbage collection */
93 GC_bool GC_dont_expand = 0;
95 word GC_free_space_divisor = 3;
97 extern GC_bool GC_collection_in_progress();
98 /* Collection is in progress, or was abandoned. */
100 int GC_never_stop_func GC_PROTO((void)) { return(0); }
102 CLOCK_TYPE GC_start_time; /* Time at which we stopped world. */
103 /* used only in GC_timeout_stop_func. */
105 int GC_n_attempts = 0; /* Number of attempts at finishing */
106 /* collection within TIME_LIMIT */
108 #if defined(SMALL_CONFIG) || defined(NO_CLOCK)
109 # define GC_timeout_stop_func GC_never_stop_func
110 #else
111 int GC_timeout_stop_func GC_PROTO((void))
113 CLOCK_TYPE current_time;
114 static unsigned count = 0;
115 unsigned long time_diff;
117 if ((count++ & 3) != 0) return(0);
118 #ifndef NO_CLOCK
119 GET_TIME(current_time);
120 time_diff = MS_TIME_DIFF(current_time,GC_start_time);
121 if (time_diff >= TIME_LIMIT) {
122 # ifdef CONDPRINT
123 if (GC_print_stats) {
124 GC_printf0("Abandoning stopped marking after ");
125 GC_printf1("%lu msecs", (unsigned long)time_diff);
126 GC_printf1("(attempt %d)\n", (unsigned long) GC_n_attempts);
128 # endif
129 return(1);
131 #endif
132 return(0);
134 #endif /* !SMALL_CONFIG */
136 /* Return the minimum number of words that must be allocated between */
137 /* collections to amortize the collection cost. */
138 static word min_words_allocd()
140 # ifdef THREADS
141 /* We punt, for now. */
142 register signed_word stack_size = 10000;
143 # else
144 int dummy;
145 register signed_word stack_size = (ptr_t)(&dummy) - GC_stackbottom;
146 # endif
147 word total_root_size; /* includes double stack size, */
148 /* since the stack is expensive */
149 /* to scan. */
150 word scan_size; /* Estimate of memory to be scanned */
151 /* during normal GC. */
153 if (stack_size < 0) stack_size = -stack_size;
154 total_root_size = 2 * stack_size + GC_root_size;
155 scan_size = BYTES_TO_WORDS(GC_heapsize - GC_large_free_bytes
156 + (GC_large_free_bytes >> 2)
157 /* use a bit more of large empty heap */
158 + total_root_size);
159 if (GC_incremental) {
160 return scan_size / (2 * GC_free_space_divisor);
161 } else {
162 return scan_size / GC_free_space_divisor;
166 /* Return the number of words allocated, adjusted for explicit storage */
167 /* management, etc.. This number is used in deciding when to trigger */
168 /* collections. */
169 word GC_adj_words_allocd()
171 register signed_word result;
172 register signed_word expl_managed =
173 BYTES_TO_WORDS((long)GC_non_gc_bytes
174 - (long)GC_non_gc_bytes_at_gc);
176 /* Don't count what was explicitly freed, or newly allocated for */
177 /* explicit management. Note that deallocating an explicitly */
178 /* managed object should not alter result, assuming the client */
179 /* is playing by the rules. */
180 result = (signed_word)GC_words_allocd
181 - (signed_word)GC_mem_freed - expl_managed;
182 if (result > (signed_word)GC_words_allocd) {
183 result = GC_words_allocd;
184 /* probably client bug or unfortunate scheduling */
186 result += GC_words_finalized;
187 /* We count objects enqueued for finalization as though they */
188 /* had been reallocated this round. Finalization is user */
189 /* visible progress. And if we don't count this, we have */
190 /* stability problems for programs that finalize all objects. */
191 result += GC_words_wasted;
192 /* This doesn't reflect useful work. But if there is lots of */
193 /* new fragmentation, the same is probably true of the heap, */
194 /* and the collection will be correspondingly cheaper. */
195 if (result < (signed_word)(GC_words_allocd >> 3)) {
196 /* Always count at least 1/8 of the allocations. We don't want */
197 /* to collect too infrequently, since that would inhibit */
198 /* coalescing of free storage blocks. */
199 /* This also makes us partially robust against client bugs. */
200 return(GC_words_allocd >> 3);
201 } else {
202 return(result);
207 /* Clear up a few frames worth of garbage left at the top of the stack. */
208 /* This is used to prevent us from accidentally treating garbade left */
209 /* on the stack by other parts of the collector as roots. This */
210 /* differs from the code in misc.c, which actually tries to keep the */
211 /* stack clear of long-lived, client-generated garbage. */
212 void GC_clear_a_few_frames()
214 # define NWORDS 64
215 word frames[NWORDS];
216 register int i;
218 for (i = 0; i < NWORDS; i++) frames[i] = 0;
221 /* Have we allocated enough to amortize a collection? */
222 GC_bool GC_should_collect()
224 return(GC_adj_words_allocd() >= min_words_allocd());
228 void GC_notify_full_gc()
230 if (GC_start_call_back != (void (*) GC_PROTO((void)))0) {
231 (*GC_start_call_back)();
235 GC_bool GC_is_full_gc = FALSE;
238 * Initiate a garbage collection if appropriate.
239 * Choose judiciously
240 * between partial, full, and stop-world collections.
241 * Assumes lock held, signals disabled.
243 void GC_maybe_gc()
245 static int n_partial_gcs = 0;
247 if (GC_should_collect()) {
248 if (!GC_incremental) {
249 GC_notify_full_gc();
250 GC_gcollect_inner();
251 n_partial_gcs = 0;
252 return;
253 } else {
254 # ifdef PARALLEL_MARK
255 GC_wait_for_reclaim();
256 # endif
257 if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) {
258 # ifdef CONDPRINT
259 if (GC_print_stats) {
260 GC_printf2(
261 "***>Full mark for collection %lu after %ld allocd bytes\n",
262 (unsigned long) GC_gc_no+1,
263 (long)WORDS_TO_BYTES(GC_words_allocd));
265 # endif
266 GC_promote_black_lists();
267 (void)GC_reclaim_all((GC_stop_func)0, TRUE);
268 GC_clear_marks();
269 n_partial_gcs = 0;
270 GC_notify_full_gc();
271 GC_is_full_gc = TRUE;
272 } else {
273 n_partial_gcs++;
276 /* We try to mark with the world stopped. */
277 /* If we run out of time, this turns into */
278 /* incremental marking. */
279 # ifndef NO_CLOCK
280 GET_TIME(GC_start_time);
281 # endif
282 if (GC_stopped_mark(GC_timeout_stop_func)) {
283 # ifdef SAVE_CALL_CHAIN
284 GC_save_callers(GC_last_stack);
285 # endif
286 GC_finish_collection();
287 } else {
288 if (!GC_is_full_gc) {
289 /* Count this as the first attempt */
290 GC_n_attempts++;
298 * Stop the world garbage collection. Assumes lock held, signals disabled.
299 * If stop_func is not GC_never_stop_func, then abort if stop_func returns TRUE.
301 GC_bool GC_try_to_collect_inner(stop_func)
302 GC_stop_func stop_func;
304 if (GC_incremental && GC_collection_in_progress()) {
305 # ifdef CONDPRINT
306 if (GC_print_stats) {
307 GC_printf0(
308 "GC_try_to_collect_inner: finishing collection in progress\n");
310 # endif /* CONDPRINT */
311 /* Just finish collection already in progress. */
312 while(GC_collection_in_progress()) {
313 if (stop_func()) return(FALSE);
314 GC_collect_a_little_inner(1);
317 # ifdef CONDPRINT
318 if (GC_print_stats) {
319 GC_printf2(
320 "Initiating full world-stop collection %lu after %ld allocd bytes\n",
321 (unsigned long) GC_gc_no+1,
322 (long)WORDS_TO_BYTES(GC_words_allocd));
324 # endif
325 GC_promote_black_lists();
326 /* Make sure all blocks have been reclaimed, so sweep routines */
327 /* don't see cleared mark bits. */
328 /* If we're guaranteed to finish, then this is unnecessary. */
329 /* In the find_leak case, we have to finish to guarantee that */
330 /* previously unmarked objects are not reported as leaks. */
331 # ifdef PARALLEL_MARK
332 GC_wait_for_reclaim();
333 # endif
334 if ((GC_find_leak || stop_func != GC_never_stop_func)
335 && !GC_reclaim_all(stop_func, FALSE)) {
336 /* Aborted. So far everything is still consistent. */
337 return(FALSE);
339 GC_invalidate_mark_state(); /* Flush mark stack. */
340 GC_clear_marks();
341 # ifdef SAVE_CALL_CHAIN
342 GC_save_callers(GC_last_stack);
343 # endif
344 GC_is_full_gc = TRUE;
345 if (!GC_stopped_mark(stop_func)) {
346 if (!GC_incremental) {
347 /* We're partially done and have no way to complete or use */
348 /* current work. Reestablish invariants as cheaply as */
349 /* possible. */
350 GC_invalidate_mark_state();
351 GC_unpromote_black_lists();
352 } /* else we claim the world is already still consistent. We'll */
353 /* finish incrementally. */
354 return(FALSE);
356 GC_finish_collection();
357 return(TRUE);
363 * Perform n units of garbage collection work. A unit is intended to touch
364 * roughly GC_RATE pages. Every once in a while, we do more than that.
365 * This needa to be a fairly large number with our current incremental
366 * GC strategy, since otherwise we allocate too much during GC, and the
367 * cleanup gets expensive.
369 # define GC_RATE 10
370 # define MAX_PRIOR_ATTEMPTS 1
371 /* Maximum number of prior attempts at world stop marking */
372 /* A value of 1 means that we finish the second time, no matter */
373 /* how long it takes. Doesn't count the initial root scan */
374 /* for a full GC. */
376 int GC_deficit = 0; /* The number of extra calls to GC_mark_some */
377 /* that we have made. */
379 void GC_collect_a_little_inner(n)
380 int n;
382 register int i;
384 if (GC_incremental && GC_collection_in_progress()) {
385 for (i = GC_deficit; i < GC_RATE*n; i++) {
386 if (GC_mark_some((ptr_t)0)) {
387 /* Need to finish a collection */
388 # ifdef SAVE_CALL_CHAIN
389 GC_save_callers(GC_last_stack);
390 # endif
391 # ifdef PARALLEL_MARK
392 GC_wait_for_reclaim();
393 # endif
394 if (GC_n_attempts < MAX_PRIOR_ATTEMPTS) {
395 GET_TIME(GC_start_time);
396 if (!GC_stopped_mark(GC_timeout_stop_func)) {
397 GC_n_attempts++;
398 break;
400 } else {
401 (void)GC_stopped_mark(GC_never_stop_func);
403 GC_finish_collection();
404 break;
407 if (GC_deficit > 0) GC_deficit -= GC_RATE*n;
408 if (GC_deficit < 0) GC_deficit = 0;
409 } else {
410 GC_maybe_gc();
414 int GC_collect_a_little GC_PROTO(())
416 int result;
417 DCL_LOCK_STATE;
419 DISABLE_SIGNALS();
420 LOCK();
421 GC_collect_a_little_inner(1);
422 result = (int)GC_collection_in_progress();
423 UNLOCK();
424 ENABLE_SIGNALS();
425 return(result);
429 * Assumes lock is held, signals are disabled.
430 * We stop the world.
431 * If stop_func() ever returns TRUE, we may fail and return FALSE.
432 * Increment GC_gc_no if we succeed.
434 GC_bool GC_stopped_mark(stop_func)
435 GC_stop_func stop_func;
437 register int i;
438 int dummy;
439 # ifdef PRINTTIMES
440 CLOCK_TYPE start_time, current_time;
441 # endif
443 STOP_WORLD();
444 # ifdef PRINTTIMES
445 GET_TIME(start_time);
446 # endif
447 # ifdef CONDPRINT
448 if (GC_print_stats) {
449 GC_printf1("--> Marking for collection %lu ",
450 (unsigned long) GC_gc_no + 1);
451 GC_printf2("after %lu allocd bytes + %lu wasted bytes\n",
452 (unsigned long) WORDS_TO_BYTES(GC_words_allocd),
453 (unsigned long) WORDS_TO_BYTES(GC_words_wasted));
455 # endif
457 /* Mark from all roots. */
458 /* Minimize junk left in my registers and on the stack */
459 GC_clear_a_few_frames();
460 GC_noop(0,0,0,0,0,0);
461 GC_initiate_gc();
462 for(i = 0;;i++) {
463 if ((*stop_func)()) {
464 # ifdef CONDPRINT
465 if (GC_print_stats) {
466 GC_printf0("Abandoned stopped marking after ");
467 GC_printf1("%lu iterations\n",
468 (unsigned long)i);
470 # endif
471 GC_deficit = i; /* Give the mutator a chance. */
472 START_WORLD();
473 return(FALSE);
475 if (GC_mark_some((ptr_t)(&dummy))) break;
478 GC_gc_no++;
479 # ifdef PRINTSTATS
480 GC_printf2("Collection %lu reclaimed %ld bytes",
481 (unsigned long) GC_gc_no - 1,
482 (long)WORDS_TO_BYTES(GC_mem_found));
483 # else
484 # ifdef CONDPRINT
485 if (GC_print_stats) {
486 GC_printf1("Collection %lu finished", (unsigned long) GC_gc_no - 1);
488 # endif
489 # endif /* !PRINTSTATS */
490 # ifdef CONDPRINT
491 if (GC_print_stats) {
492 GC_printf1(" ---> heapsize = %lu bytes\n",
493 (unsigned long) GC_heapsize);
494 /* Printf arguments may be pushed in funny places. Clear the */
495 /* space. */
496 GC_printf0("");
498 # endif /* CONDPRINT */
500 /* Check all debugged objects for consistency */
501 if (GC_debugging_started) {
502 (*GC_check_heap)();
505 # ifdef PRINTTIMES
506 GET_TIME(current_time);
507 GC_printf1("World-stopped marking took %lu msecs\n",
508 MS_TIME_DIFF(current_time,start_time));
509 # endif
510 START_WORLD();
511 return(TRUE);
514 /* Set all mark bits for the free list whose first entry is q */
515 #ifdef __STDC__
516 void GC_set_fl_marks(ptr_t q)
517 #else
518 void GC_set_fl_marks(q)
519 ptr_t q;
520 #endif
522 ptr_t p;
523 struct hblk * h, * last_h = 0;
524 hdr *hhdr;
525 int word_no;
527 for (p = q; p != 0; p = obj_link(p)){
528 h = HBLKPTR(p);
529 if (h != last_h) {
530 last_h = h;
531 hhdr = HDR(h);
533 word_no = (((word *)p) - ((word *)h));
534 set_mark_bit_from_hdr(hhdr, word_no);
538 /* Clear all mark bits for the free list whose first entry is q */
539 /* Decrement GC_mem_found by number of words on free list. */
540 #ifdef __STDC__
541 void GC_clear_fl_marks(ptr_t q)
542 #else
543 void GC_clear_fl_marks(q)
544 ptr_t q;
545 #endif
547 ptr_t p;
548 struct hblk * h, * last_h = 0;
549 hdr *hhdr;
550 int word_no;
552 for (p = q; p != 0; p = obj_link(p)){
553 h = HBLKPTR(p);
554 if (h != last_h) {
555 last_h = h;
556 hhdr = HDR(h);
558 word_no = (((word *)p) - ((word *)h));
559 clear_mark_bit_from_hdr(hhdr, word_no);
560 # ifdef GATHERSTATS
561 GC_mem_found -= hhdr -> hb_sz;
562 # endif
566 /* Finish up a collection. Assumes lock is held, signals are disabled, */
567 /* but the world is otherwise running. */
568 void GC_finish_collection()
570 # ifdef PRINTTIMES
571 CLOCK_TYPE start_time;
572 CLOCK_TYPE finalize_time;
573 CLOCK_TYPE done_time;
575 GET_TIME(start_time);
576 finalize_time = start_time;
577 # endif
579 # ifdef GATHERSTATS
580 GC_mem_found = 0;
581 # endif
582 # if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
583 if (getenv("GC_PRINT_ADDRESS_MAP") != 0) {
584 GC_print_address_map();
586 # endif
587 if (GC_find_leak) {
588 /* Mark all objects on the free list. All objects should be */
589 /* marked when we're done. */
591 register word size; /* current object size */
592 int kind;
593 ptr_t q;
595 for (kind = 0; kind < GC_n_kinds; kind++) {
596 for (size = 1; size <= MAXOBJSZ; size++) {
597 q = GC_obj_kinds[kind].ok_freelist[size];
598 if (q != 0) GC_set_fl_marks(q);
602 GC_start_reclaim(TRUE);
603 /* The above just checks; it doesn't really reclaim anything. */
606 GC_finalize();
607 # ifdef STUBBORN_ALLOC
608 GC_clean_changing_list();
609 # endif
611 # ifdef PRINTTIMES
612 GET_TIME(finalize_time);
613 # endif
615 /* Clear free list mark bits, in case they got accidentally marked */
616 /* (or GC_find_leak is set and they were intentionally marked). */
617 /* Also subtract memory remaining from GC_mem_found count. */
618 /* Note that composite objects on free list are cleared. */
619 /* Thus accidentally marking a free list is not a problem; only */
620 /* objects on the list itself will be marked, and that's fixed here. */
622 register word size; /* current object size */
623 register ptr_t q; /* pointer to current object */
624 int kind;
626 for (kind = 0; kind < GC_n_kinds; kind++) {
627 for (size = 1; size <= MAXOBJSZ; size++) {
628 q = GC_obj_kinds[kind].ok_freelist[size];
629 if (q != 0) GC_clear_fl_marks(q);
635 # ifdef PRINTSTATS
636 GC_printf1("Bytes recovered before sweep - f.l. count = %ld\n",
637 (long)WORDS_TO_BYTES(GC_mem_found));
638 # endif
639 /* Reconstruct free lists to contain everything not marked */
640 GC_start_reclaim(FALSE);
641 if (GC_is_full_gc) {
642 GC_used_heap_size_after_full = USED_HEAP_SIZE;
643 GC_need_full_gc = FALSE;
644 } else {
645 GC_need_full_gc =
646 BYTES_TO_WORDS(USED_HEAP_SIZE - GC_used_heap_size_after_full)
647 > min_words_allocd();
650 # ifdef PRINTSTATS
651 GC_printf2(
652 "Immediately reclaimed %ld bytes in heap of size %lu bytes",
653 (long)WORDS_TO_BYTES(GC_mem_found),
654 (unsigned long)GC_heapsize);
655 # ifdef USE_MUNMAP
656 GC_printf1("(%lu unmapped)", GC_unmapped_bytes);
657 # endif
658 GC_printf2(
659 "\n%lu (atomic) + %lu (composite) collectable bytes in use\n",
660 (unsigned long)WORDS_TO_BYTES(GC_atomic_in_use),
661 (unsigned long)WORDS_TO_BYTES(GC_composite_in_use));
662 # endif
664 GC_n_attempts = 0;
665 GC_is_full_gc = FALSE;
666 /* Reset or increment counters for next cycle */
667 GC_words_allocd_before_gc += GC_words_allocd;
668 GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
669 GC_words_allocd = 0;
670 GC_words_wasted = 0;
671 GC_mem_freed = 0;
673 # ifdef USE_MUNMAP
674 GC_unmap_old();
675 # endif
676 # ifdef PRINTTIMES
677 GET_TIME(done_time);
678 GC_printf2("Finalize + initiate sweep took %lu + %lu msecs\n",
679 MS_TIME_DIFF(finalize_time,start_time),
680 MS_TIME_DIFF(done_time,finalize_time));
681 # endif
684 /* Externally callable routine to invoke full, stop-world collection */
685 # if defined(__STDC__) || defined(__cplusplus)
686 int GC_try_to_collect(GC_stop_func stop_func)
687 # else
688 int GC_try_to_collect(stop_func)
689 GC_stop_func stop_func;
690 # endif
692 int result;
693 DCL_LOCK_STATE;
695 GC_INVOKE_FINALIZERS();
696 DISABLE_SIGNALS();
697 LOCK();
698 ENTER_GC();
699 if (!GC_is_initialized) GC_init_inner();
700 /* Minimize junk left in my registers */
701 GC_noop(0,0,0,0,0,0);
702 result = (int)GC_try_to_collect_inner(stop_func);
703 EXIT_GC();
704 UNLOCK();
705 ENABLE_SIGNALS();
706 if(result) GC_INVOKE_FINALIZERS();
707 return(result);
710 void GC_gcollect GC_PROTO(())
712 GC_notify_full_gc();
713 (void)GC_try_to_collect(GC_never_stop_func);
716 word GC_n_heap_sects = 0; /* Number of sections currently in heap. */
719 * Use the chunk of memory starting at p of size bytes as part of the heap.
720 * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
722 void GC_add_to_heap(p, bytes)
723 struct hblk *p;
724 word bytes;
726 word words;
727 hdr * phdr;
729 if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
730 ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
732 phdr = GC_install_header(p);
733 if (0 == phdr) {
734 /* This is extremely unlikely. Can't add it. This will */
735 /* almost certainly result in a 0 return from the allocator, */
736 /* which is entirely appropriate. */
737 return;
739 GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
740 GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
741 GC_n_heap_sects++;
742 words = BYTES_TO_WORDS(bytes);
743 phdr -> hb_sz = words;
744 phdr -> hb_map = (unsigned char *)1; /* A value != GC_invalid_map */
745 phdr -> hb_flags = 0;
746 GC_freehblk(p);
747 GC_heapsize += bytes;
748 if ((ptr_t)p <= (ptr_t)GC_least_plausible_heap_addr
749 || GC_least_plausible_heap_addr == 0) {
750 GC_least_plausible_heap_addr = (GC_PTR)((ptr_t)p - sizeof(word));
751 /* Making it a little smaller than necessary prevents */
752 /* us from getting a false hit from the variable */
753 /* itself. There's some unintentional reflection */
754 /* here. */
756 if ((ptr_t)p + bytes >= (ptr_t)GC_greatest_plausible_heap_addr) {
757 GC_greatest_plausible_heap_addr = (GC_PTR)((ptr_t)p + bytes);
761 # if !defined(NO_DEBUGGING)
762 void GC_print_heap_sects()
764 register unsigned i;
766 GC_printf1("Total heap size: %lu\n", (unsigned long) GC_heapsize);
767 for (i = 0; i < GC_n_heap_sects; i++) {
768 unsigned long start = (unsigned long) GC_heap_sects[i].hs_start;
769 unsigned long len = (unsigned long) GC_heap_sects[i].hs_bytes;
770 struct hblk *h;
771 unsigned nbl = 0;
773 GC_printf3("Section %ld from 0x%lx to 0x%lx ", (unsigned long)i,
774 start, (unsigned long)(start + len));
775 for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) {
776 if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
778 GC_printf2("%lu/%lu blacklisted\n", (unsigned long)nbl,
779 (unsigned long)(len/HBLKSIZE));
782 # endif
784 GC_PTR GC_least_plausible_heap_addr = (GC_PTR)ONES;
785 GC_PTR GC_greatest_plausible_heap_addr = 0;
787 ptr_t GC_max(x,y)
788 ptr_t x, y;
790 return(x > y? x : y);
793 ptr_t GC_min(x,y)
794 ptr_t x, y;
796 return(x < y? x : y);
799 # if defined(__STDC__) || defined(__cplusplus)
800 void GC_set_max_heap_size(GC_word n)
801 # else
802 void GC_set_max_heap_size(n)
803 GC_word n;
804 # endif
806 GC_max_heapsize = n;
809 GC_word GC_max_retries = 0;
812 * this explicitly increases the size of the heap. It is used
813 * internally, but may also be invoked from GC_expand_hp by the user.
814 * The argument is in units of HBLKSIZE.
815 * Tiny values of n are rounded up.
816 * Returns FALSE on failure.
818 GC_bool GC_expand_hp_inner(n)
819 word n;
821 word bytes;
822 struct hblk * space;
823 word expansion_slop; /* Number of bytes by which we expect the */
824 /* heap to expand soon. */
826 if (n < MINHINCR) n = MINHINCR;
827 bytes = n * HBLKSIZE;
828 /* Make sure bytes is a multiple of GC_page_size */
830 word mask = GC_page_size - 1;
831 bytes += mask;
832 bytes &= ~mask;
835 if (GC_max_heapsize != 0 && GC_heapsize + bytes > GC_max_heapsize) {
836 /* Exceeded self-imposed limit */
837 return(FALSE);
839 space = GET_MEM(bytes);
840 if( space == 0 ) {
841 # ifdef CONDPRINT
842 if (GC_print_stats) {
843 GC_printf1("Failed to expand heap by %ld bytes\n",
844 (unsigned long)bytes);
846 # endif
847 return(FALSE);
849 # ifdef CONDPRINT
850 if (GC_print_stats) {
851 GC_printf2("Increasing heap size by %lu after %lu allocated bytes\n",
852 (unsigned long)bytes,
853 (unsigned long)WORDS_TO_BYTES(GC_words_allocd));
854 # ifdef UNDEFINED
855 GC_printf1("Root size = %lu\n", GC_root_size);
856 GC_print_block_list(); GC_print_hblkfreelist();
857 GC_printf0("\n");
858 # endif
860 # endif
861 expansion_slop = 8 * WORDS_TO_BYTES(min_words_allocd());
862 if (5 * HBLKSIZE * MAXHINCR > expansion_slop) {
863 expansion_slop = 5 * HBLKSIZE * MAXHINCR;
865 if (GC_last_heap_addr == 0 && !((word)space & SIGNB)
866 || GC_last_heap_addr != 0 && GC_last_heap_addr < (ptr_t)space) {
867 /* Assume the heap is growing up */
868 GC_greatest_plausible_heap_addr =
869 GC_max(GC_greatest_plausible_heap_addr,
870 (ptr_t)space + bytes + expansion_slop);
871 } else {
872 /* Heap is growing down */
873 GC_least_plausible_heap_addr =
874 GC_min(GC_least_plausible_heap_addr,
875 (ptr_t)space - expansion_slop);
877 GC_prev_heap_addr = GC_last_heap_addr;
878 GC_last_heap_addr = (ptr_t)space;
879 GC_add_to_heap(space, bytes);
880 return(TRUE);
883 /* Really returns a bool, but it's externally visible, so that's clumsy. */
884 /* Arguments is in bytes. */
885 # if defined(__STDC__) || defined(__cplusplus)
886 int GC_expand_hp(size_t bytes)
887 # else
888 int GC_expand_hp(bytes)
889 size_t bytes;
890 # endif
892 int result;
893 DCL_LOCK_STATE;
895 DISABLE_SIGNALS();
896 LOCK();
897 if (!GC_is_initialized) GC_init_inner();
898 result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
899 if (result) GC_requested_heapsize += bytes;
900 UNLOCK();
901 ENABLE_SIGNALS();
902 return(result);
905 unsigned GC_fail_count = 0;
906 /* How many consecutive GC/expansion failures? */
907 /* Reset by GC_allochblk. */
909 GC_bool GC_collect_or_expand(needed_blocks, ignore_off_page)
910 word needed_blocks;
911 GC_bool ignore_off_page;
913 if (!GC_incremental && !GC_dont_gc &&
914 (GC_dont_expand && GC_words_allocd > 0 || GC_should_collect())) {
915 GC_notify_full_gc();
916 GC_gcollect_inner();
917 } else {
918 word blocks_to_get = GC_heapsize/(HBLKSIZE*GC_free_space_divisor)
919 + needed_blocks;
921 if (blocks_to_get > MAXHINCR) {
922 word slop;
924 if (ignore_off_page) {
925 slop = 4;
926 } else {
927 slop = 2*divHBLKSZ(BL_LIMIT);
928 if (slop > needed_blocks) slop = needed_blocks;
930 if (needed_blocks + slop > MAXHINCR) {
931 blocks_to_get = needed_blocks + slop;
932 } else {
933 blocks_to_get = MAXHINCR;
936 if (!GC_expand_hp_inner(blocks_to_get)
937 && !GC_expand_hp_inner(needed_blocks)) {
938 if (GC_fail_count++ < GC_max_retries) {
939 WARN("Out of Memory! Trying to continue ...\n", 0);
940 GC_notify_full_gc();
941 GC_gcollect_inner();
942 } else {
943 # if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
944 WARN("Out of Memory! Returning NIL!\n", 0);
945 # endif
946 return(FALSE);
948 } else {
949 # ifdef CONDPRINT
950 if (GC_fail_count && GC_print_stats) {
951 GC_printf0("Memory available again ...\n");
953 # endif
956 return(TRUE);
960 * Make sure the object free list for sz is not empty.
961 * Return a pointer to the first object on the free list.
962 * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
963 * Assumes we hold the allocator lock and signals are disabled.
966 ptr_t GC_allocobj(sz, kind)
967 word sz;
968 int kind;
970 register ptr_t * flh = &(GC_obj_kinds[kind].ok_freelist[sz]);
972 if (sz == 0) return(0);
974 while (*flh == 0) {
975 ENTER_GC();
976 /* Do our share of marking work */
977 if(GC_incremental && !GC_dont_gc) GC_collect_a_little_inner(1);
978 /* Sweep blocks for objects of this size */
979 GC_continue_reclaim(sz, kind);
980 EXIT_GC();
981 if (*flh == 0) {
982 GC_new_hblk(sz, kind);
984 if (*flh == 0) {
985 ENTER_GC();
986 if (!GC_collect_or_expand((word)1,FALSE)) {
987 EXIT_GC();
988 return(0);
990 EXIT_GC();
994 return(*flh);