*** empty log message ***
[emacs.git] / gc / alloc.c
blob4cb7a4c71077c734294eb2d36c1fdf714c0c808e
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-2001 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 extern GC_bool GC_print_back_height;
102 int GC_never_stop_func GC_PROTO((void)) { return(0); }
104 unsigned long GC_time_limit = TIME_LIMIT;
106 CLOCK_TYPE GC_start_time; /* Time at which we stopped world. */
107 /* used only in GC_timeout_stop_func. */
109 int GC_n_attempts = 0; /* Number of attempts at finishing */
110 /* collection within GC_time_limit. */
112 #if defined(SMALL_CONFIG) || defined(NO_CLOCK)
113 # define GC_timeout_stop_func GC_never_stop_func
114 #else
115 int GC_timeout_stop_func GC_PROTO((void))
117 CLOCK_TYPE current_time;
118 static unsigned count = 0;
119 unsigned long time_diff;
121 if ((count++ & 3) != 0) return(0);
122 GET_TIME(current_time);
123 time_diff = MS_TIME_DIFF(current_time,GC_start_time);
124 if (time_diff >= GC_time_limit) {
125 # ifdef CONDPRINT
126 if (GC_print_stats) {
127 GC_printf0("Abandoning stopped marking after ");
128 GC_printf1("%lu msecs", (unsigned long)time_diff);
129 GC_printf1("(attempt %d)\n", (unsigned long) GC_n_attempts);
131 # endif
132 return(1);
134 return(0);
136 #endif /* !SMALL_CONFIG */
138 /* Return the minimum number of words that must be allocated between */
139 /* collections to amortize the collection cost. */
140 static word min_words_allocd()
142 # ifdef THREADS
143 /* We punt, for now. */
144 register signed_word stack_size = 10000;
145 # else
146 int dummy;
147 register signed_word stack_size = (ptr_t)(&dummy) - GC_stackbottom;
148 # endif
149 word total_root_size; /* includes double stack size, */
150 /* since the stack is expensive */
151 /* to scan. */
152 word scan_size; /* Estimate of memory to be scanned */
153 /* during normal GC. */
155 if (stack_size < 0) stack_size = -stack_size;
156 total_root_size = 2 * stack_size + GC_root_size;
157 scan_size = BYTES_TO_WORDS(GC_heapsize - GC_large_free_bytes
158 + (GC_large_free_bytes >> 2)
159 /* use a bit more of large empty heap */
160 + total_root_size);
161 if (TRUE_INCREMENTAL) {
162 return scan_size / (2 * GC_free_space_divisor);
163 } else {
164 return scan_size / GC_free_space_divisor;
168 /* Return the number of words allocated, adjusted for explicit storage */
169 /* management, etc.. This number is used in deciding when to trigger */
170 /* collections. */
171 word GC_adj_words_allocd()
173 register signed_word result;
174 register signed_word expl_managed =
175 BYTES_TO_WORDS((long)GC_non_gc_bytes
176 - (long)GC_non_gc_bytes_at_gc);
178 /* Don't count what was explicitly freed, or newly allocated for */
179 /* explicit management. Note that deallocating an explicitly */
180 /* managed object should not alter result, assuming the client */
181 /* is playing by the rules. */
182 result = (signed_word)GC_words_allocd
183 - (signed_word)GC_mem_freed
184 + (signed_word)GC_finalizer_mem_freed - expl_managed;
185 if (result > (signed_word)GC_words_allocd) {
186 result = GC_words_allocd;
187 /* probably client bug or unfortunate scheduling */
189 result += GC_words_finalized;
190 /* We count objects enqueued for finalization as though they */
191 /* had been reallocated this round. Finalization is user */
192 /* visible progress. And if we don't count this, we have */
193 /* stability problems for programs that finalize all objects. */
194 result += GC_words_wasted;
195 /* This doesn't reflect useful work. But if there is lots of */
196 /* new fragmentation, the same is probably true of the heap, */
197 /* and the collection will be correspondingly cheaper. */
198 if (result < (signed_word)(GC_words_allocd >> 3)) {
199 /* Always count at least 1/8 of the allocations. We don't want */
200 /* to collect too infrequently, since that would inhibit */
201 /* coalescing of free storage blocks. */
202 /* This also makes us partially robust against client bugs. */
203 return(GC_words_allocd >> 3);
204 } else {
205 return(result);
210 /* Clear up a few frames worth of garbage left at the top of the stack. */
211 /* This is used to prevent us from accidentally treating garbade left */
212 /* on the stack by other parts of the collector as roots. This */
213 /* differs from the code in misc.c, which actually tries to keep the */
214 /* stack clear of long-lived, client-generated garbage. */
215 void GC_clear_a_few_frames()
217 # define NWORDS 64
218 word frames[NWORDS];
219 register int i;
221 for (i = 0; i < NWORDS; i++) frames[i] = 0;
224 /* Have we allocated enough to amortize a collection? */
225 GC_bool GC_should_collect()
227 return(GC_adj_words_allocd() >= min_words_allocd());
231 void GC_notify_full_gc()
233 if (GC_start_call_back != (void (*) GC_PROTO((void)))0) {
234 (*GC_start_call_back)();
238 GC_bool GC_is_full_gc = FALSE;
241 * Initiate a garbage collection if appropriate.
242 * Choose judiciously
243 * between partial, full, and stop-world collections.
244 * Assumes lock held, signals disabled.
246 void GC_maybe_gc()
248 static int n_partial_gcs = 0;
250 if (GC_should_collect()) {
251 if (!GC_incremental) {
252 GC_gcollect_inner();
253 n_partial_gcs = 0;
254 return;
255 } else {
256 # ifdef PARALLEL_MARK
257 GC_wait_for_reclaim();
258 # endif
259 if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) {
260 # ifdef CONDPRINT
261 if (GC_print_stats) {
262 GC_printf2(
263 "***>Full mark for collection %lu after %ld allocd bytes\n",
264 (unsigned long) GC_gc_no+1,
265 (long)WORDS_TO_BYTES(GC_words_allocd));
267 # endif
268 GC_promote_black_lists();
269 (void)GC_reclaim_all((GC_stop_func)0, TRUE);
270 GC_clear_marks();
271 n_partial_gcs = 0;
272 GC_notify_full_gc();
273 GC_is_full_gc = TRUE;
274 } else {
275 n_partial_gcs++;
278 /* We try to mark with the world stopped. */
279 /* If we run out of time, this turns into */
280 /* incremental marking. */
281 # ifndef NO_CLOCK
282 if (GC_time_limit != GC_TIME_UNLIMITED) { GET_TIME(GC_start_time); }
283 # endif
284 if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED?
285 GC_never_stop_func : GC_timeout_stop_func)) {
286 # ifdef SAVE_CALL_CHAIN
287 GC_save_callers(GC_last_stack);
288 # endif
289 GC_finish_collection();
290 } else {
291 if (!GC_is_full_gc) {
292 /* Count this as the first attempt */
293 GC_n_attempts++;
301 * Stop the world garbage collection. Assumes lock held, signals disabled.
302 * If stop_func is not GC_never_stop_func, then abort if stop_func returns TRUE.
303 * Return TRUE if we successfully completed the collection.
305 GC_bool GC_try_to_collect_inner(stop_func)
306 GC_stop_func stop_func;
308 # ifdef CONDPRINT
309 CLOCK_TYPE start_time, current_time;
310 # endif
311 if (GC_dont_gc) return FALSE;
312 if (GC_incremental && GC_collection_in_progress()) {
313 # ifdef CONDPRINT
314 if (GC_print_stats) {
315 GC_printf0(
316 "GC_try_to_collect_inner: finishing collection in progress\n");
318 # endif /* CONDPRINT */
319 /* Just finish collection already in progress. */
320 while(GC_collection_in_progress()) {
321 if (stop_func()) return(FALSE);
322 GC_collect_a_little_inner(1);
325 if (stop_func == GC_never_stop_func) GC_notify_full_gc();
326 # ifdef CONDPRINT
327 if (GC_print_stats) {
328 if (GC_print_stats) GET_TIME(start_time);
329 GC_printf2(
330 "Initiating full world-stop collection %lu after %ld allocd bytes\n",
331 (unsigned long) GC_gc_no+1,
332 (long)WORDS_TO_BYTES(GC_words_allocd));
334 # endif
335 GC_promote_black_lists();
336 /* Make sure all blocks have been reclaimed, so sweep routines */
337 /* don't see cleared mark bits. */
338 /* If we're guaranteed to finish, then this is unnecessary. */
339 /* In the find_leak case, we have to finish to guarantee that */
340 /* previously unmarked objects are not reported as leaks. */
341 # ifdef PARALLEL_MARK
342 GC_wait_for_reclaim();
343 # endif
344 if ((GC_find_leak || stop_func != GC_never_stop_func)
345 && !GC_reclaim_all(stop_func, FALSE)) {
346 /* Aborted. So far everything is still consistent. */
347 return(FALSE);
349 GC_invalidate_mark_state(); /* Flush mark stack. */
350 GC_clear_marks();
351 # ifdef SAVE_CALL_CHAIN
352 GC_save_callers(GC_last_stack);
353 # endif
354 GC_is_full_gc = TRUE;
355 if (!GC_stopped_mark(stop_func)) {
356 if (!GC_incremental) {
357 /* We're partially done and have no way to complete or use */
358 /* current work. Reestablish invariants as cheaply as */
359 /* possible. */
360 GC_invalidate_mark_state();
361 GC_unpromote_black_lists();
362 } /* else we claim the world is already still consistent. We'll */
363 /* finish incrementally. */
364 return(FALSE);
366 GC_finish_collection();
367 # if defined(CONDPRINT)
368 if (GC_print_stats) {
369 GET_TIME(current_time);
370 GC_printf1("Complete collection took %lu msecs\n",
371 MS_TIME_DIFF(current_time,start_time));
373 # endif
374 return(TRUE);
380 * Perform n units of garbage collection work. A unit is intended to touch
381 * roughly GC_RATE pages. Every once in a while, we do more than that.
382 * This needa to be a fairly large number with our current incremental
383 * GC strategy, since otherwise we allocate too much during GC, and the
384 * cleanup gets expensive.
386 # define GC_RATE 10
387 # define MAX_PRIOR_ATTEMPTS 1
388 /* Maximum number of prior attempts at world stop marking */
389 /* A value of 1 means that we finish the second time, no matter */
390 /* how long it takes. Doesn't count the initial root scan */
391 /* for a full GC. */
393 int GC_deficit = 0; /* The number of extra calls to GC_mark_some */
394 /* that we have made. */
396 void GC_collect_a_little_inner(n)
397 int n;
399 register int i;
401 if (GC_dont_gc) return;
402 if (GC_incremental && GC_collection_in_progress()) {
403 for (i = GC_deficit; i < GC_RATE*n; i++) {
404 if (GC_mark_some((ptr_t)0)) {
405 /* Need to finish a collection */
406 # ifdef SAVE_CALL_CHAIN
407 GC_save_callers(GC_last_stack);
408 # endif
409 # ifdef PARALLEL_MARK
410 GC_wait_for_reclaim();
411 # endif
412 if (GC_n_attempts < MAX_PRIOR_ATTEMPTS
413 && GC_time_limit != GC_TIME_UNLIMITED) {
414 GET_TIME(GC_start_time);
415 if (!GC_stopped_mark(GC_timeout_stop_func)) {
416 GC_n_attempts++;
417 break;
419 } else {
420 (void)GC_stopped_mark(GC_never_stop_func);
422 GC_finish_collection();
423 break;
426 if (GC_deficit > 0) GC_deficit -= GC_RATE*n;
427 if (GC_deficit < 0) GC_deficit = 0;
428 } else {
429 GC_maybe_gc();
433 int GC_collect_a_little GC_PROTO(())
435 int result;
436 DCL_LOCK_STATE;
438 DISABLE_SIGNALS();
439 LOCK();
440 GC_collect_a_little_inner(1);
441 result = (int)GC_collection_in_progress();
442 UNLOCK();
443 ENABLE_SIGNALS();
444 if (!result && GC_debugging_started) GC_print_all_smashed();
445 return(result);
449 * Assumes lock is held, signals are disabled.
450 * We stop the world.
451 * If stop_func() ever returns TRUE, we may fail and return FALSE.
452 * Increment GC_gc_no if we succeed.
454 GC_bool GC_stopped_mark(stop_func)
455 GC_stop_func stop_func;
457 register int i;
458 int dummy;
459 # if defined(PRINTTIMES) || defined(CONDPRINT)
460 CLOCK_TYPE start_time, current_time;
461 # endif
463 # ifdef PRINTTIMES
464 GET_TIME(start_time);
465 # endif
466 # if defined(CONDPRINT) && !defined(PRINTTIMES)
467 if (GC_print_stats) GET_TIME(start_time);
468 # endif
469 # if defined(REGISTER_LIBRARIES_EARLY)
470 GC_cond_register_dynamic_libraries();
471 # endif
472 STOP_WORLD();
473 # ifdef CONDPRINT
474 if (GC_print_stats) {
475 GC_printf1("--> Marking for collection %lu ",
476 (unsigned long) GC_gc_no + 1);
477 GC_printf2("after %lu allocd bytes + %lu wasted bytes\n",
478 (unsigned long) WORDS_TO_BYTES(GC_words_allocd),
479 (unsigned long) WORDS_TO_BYTES(GC_words_wasted));
481 # endif
482 # ifdef MAKE_BACK_GRAPH
483 if (GC_print_back_height) {
484 GC_build_back_graph();
486 # endif
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);
492 GC_initiate_gc();
493 for(i = 0;;i++) {
494 if ((*stop_func)()) {
495 # ifdef CONDPRINT
496 if (GC_print_stats) {
497 GC_printf0("Abandoned stopped marking after ");
498 GC_printf1("%lu iterations\n",
499 (unsigned long)i);
501 # endif
502 GC_deficit = i; /* Give the mutator a chance. */
503 START_WORLD();
504 return(FALSE);
506 if (GC_mark_some((ptr_t)(&dummy))) break;
509 GC_gc_no++;
510 # ifdef PRINTSTATS
511 GC_printf2("Collection %lu reclaimed %ld bytes",
512 (unsigned long) GC_gc_no - 1,
513 (long)WORDS_TO_BYTES(GC_mem_found));
514 # else
515 # ifdef CONDPRINT
516 if (GC_print_stats) {
517 GC_printf1("Collection %lu finished", (unsigned long) GC_gc_no - 1);
519 # endif
520 # endif /* !PRINTSTATS */
521 # ifdef CONDPRINT
522 if (GC_print_stats) {
523 GC_printf1(" ---> heapsize = %lu bytes\n",
524 (unsigned long) GC_heapsize);
525 /* Printf arguments may be pushed in funny places. Clear the */
526 /* space. */
527 GC_printf0("");
529 # endif /* CONDPRINT */
531 /* Check all debugged objects for consistency */
532 if (GC_debugging_started) {
533 (*GC_check_heap)();
536 START_WORLD();
537 # ifdef PRINTTIMES
538 GET_TIME(current_time);
539 GC_printf1("World-stopped marking took %lu msecs\n",
540 MS_TIME_DIFF(current_time,start_time));
541 # else
542 # ifdef CONDPRINT
543 if (GC_print_stats) {
544 GET_TIME(current_time);
545 GC_printf1("World-stopped marking took %lu msecs\n",
546 MS_TIME_DIFF(current_time,start_time));
548 # endif
549 # endif
550 return(TRUE);
553 /* Set all mark bits for the free list whose first entry is q */
554 #ifdef __STDC__
555 void GC_set_fl_marks(ptr_t q)
556 #else
557 void GC_set_fl_marks(q)
558 ptr_t q;
559 #endif
561 ptr_t p;
562 struct hblk * h, * last_h = 0;
563 hdr *hhdr;
564 int word_no;
566 for (p = q; p != 0; p = obj_link(p)){
567 h = HBLKPTR(p);
568 if (h != last_h) {
569 last_h = h;
570 hhdr = HDR(h);
572 word_no = (((word *)p) - ((word *)h));
573 set_mark_bit_from_hdr(hhdr, word_no);
577 /* Clear all mark bits for the free list whose first entry is q */
578 /* Decrement GC_mem_found by number of words on free list. */
579 #ifdef __STDC__
580 void GC_clear_fl_marks(ptr_t q)
581 #else
582 void GC_clear_fl_marks(q)
583 ptr_t q;
584 #endif
586 ptr_t p;
587 struct hblk * h, * last_h = 0;
588 hdr *hhdr;
589 int word_no;
591 for (p = q; p != 0; p = obj_link(p)){
592 h = HBLKPTR(p);
593 if (h != last_h) {
594 last_h = h;
595 hhdr = HDR(h);
597 word_no = (((word *)p) - ((word *)h));
598 clear_mark_bit_from_hdr(hhdr, word_no);
599 # ifdef GATHERSTATS
600 GC_mem_found -= hhdr -> hb_sz;
601 # endif
605 /* Finish up a collection. Assumes lock is held, signals are disabled, */
606 /* but the world is otherwise running. */
607 void GC_finish_collection()
609 # ifdef PRINTTIMES
610 CLOCK_TYPE start_time;
611 CLOCK_TYPE finalize_time;
612 CLOCK_TYPE done_time;
614 GET_TIME(start_time);
615 finalize_time = start_time;
616 # endif
618 # ifdef GATHERSTATS
619 GC_mem_found = 0;
620 # endif
621 # if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
622 if (getenv("GC_PRINT_ADDRESS_MAP") != 0) {
623 GC_print_address_map();
625 # endif
626 COND_DUMP;
627 if (GC_find_leak) {
628 /* Mark all objects on the free list. All objects should be */
629 /* marked when we're done. */
631 register word size; /* current object size */
632 int kind;
633 ptr_t q;
635 for (kind = 0; kind < GC_n_kinds; kind++) {
636 for (size = 1; size <= MAXOBJSZ; size++) {
637 q = GC_obj_kinds[kind].ok_freelist[size];
638 if (q != 0) GC_set_fl_marks(q);
642 GC_start_reclaim(TRUE);
643 /* The above just checks; it doesn't really reclaim anything. */
646 GC_finalize();
647 # ifdef STUBBORN_ALLOC
648 GC_clean_changing_list();
649 # endif
651 # ifdef PRINTTIMES
652 GET_TIME(finalize_time);
653 # endif
655 if (GC_print_back_height) {
656 # ifdef MAKE_BACK_GRAPH
657 GC_traverse_back_graph();
658 # else
659 # ifndef SMALL_CONFIG
660 GC_err_printf0("Back height not available: "
661 "Rebuild collector with -DMAKE_BACK_GRAPH\n");
662 # endif
663 # endif
666 /* Clear free list mark bits, in case they got accidentally marked */
667 /* (or GC_find_leak is set and they were intentionally marked). */
668 /* Also subtract memory remaining from GC_mem_found count. */
669 /* Note that composite objects on free list are cleared. */
670 /* Thus accidentally marking a free list is not a problem; only */
671 /* objects on the list itself will be marked, and that's fixed here. */
673 register word size; /* current object size */
674 register ptr_t q; /* pointer to current object */
675 int kind;
677 for (kind = 0; kind < GC_n_kinds; kind++) {
678 for (size = 1; size <= MAXOBJSZ; size++) {
679 q = GC_obj_kinds[kind].ok_freelist[size];
680 if (q != 0) GC_clear_fl_marks(q);
686 # ifdef PRINTSTATS
687 GC_printf1("Bytes recovered before sweep - f.l. count = %ld\n",
688 (long)WORDS_TO_BYTES(GC_mem_found));
689 # endif
690 /* Reconstruct free lists to contain everything not marked */
691 GC_start_reclaim(FALSE);
692 if (GC_is_full_gc) {
693 GC_used_heap_size_after_full = USED_HEAP_SIZE;
694 GC_need_full_gc = FALSE;
695 } else {
696 GC_need_full_gc =
697 BYTES_TO_WORDS(USED_HEAP_SIZE - GC_used_heap_size_after_full)
698 > min_words_allocd();
701 # ifdef PRINTSTATS
702 GC_printf2(
703 "Immediately reclaimed %ld bytes in heap of size %lu bytes",
704 (long)WORDS_TO_BYTES(GC_mem_found),
705 (unsigned long)GC_heapsize);
706 # ifdef USE_MUNMAP
707 GC_printf1("(%lu unmapped)", GC_unmapped_bytes);
708 # endif
709 GC_printf2(
710 "\n%lu (atomic) + %lu (composite) collectable bytes in use\n",
711 (unsigned long)WORDS_TO_BYTES(GC_atomic_in_use),
712 (unsigned long)WORDS_TO_BYTES(GC_composite_in_use));
713 # endif
715 GC_n_attempts = 0;
716 GC_is_full_gc = FALSE;
717 /* Reset or increment counters for next cycle */
718 GC_words_allocd_before_gc += GC_words_allocd;
719 GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
720 GC_words_allocd = 0;
721 GC_words_wasted = 0;
722 GC_mem_freed = 0;
723 GC_finalizer_mem_freed = 0;
725 # ifdef USE_MUNMAP
726 GC_unmap_old();
727 # endif
728 # ifdef PRINTTIMES
729 GET_TIME(done_time);
730 GC_printf2("Finalize + initiate sweep took %lu + %lu msecs\n",
731 MS_TIME_DIFF(finalize_time,start_time),
732 MS_TIME_DIFF(done_time,finalize_time));
733 # endif
736 /* Externally callable routine to invoke full, stop-world collection */
737 # if defined(__STDC__) || defined(__cplusplus)
738 int GC_try_to_collect(GC_stop_func stop_func)
739 # else
740 int GC_try_to_collect(stop_func)
741 GC_stop_func stop_func;
742 # endif
744 int result;
745 DCL_LOCK_STATE;
747 if (GC_debugging_started) GC_print_all_smashed();
748 GC_INVOKE_FINALIZERS();
749 DISABLE_SIGNALS();
750 LOCK();
751 ENTER_GC();
752 if (!GC_is_initialized) GC_init_inner();
753 /* Minimize junk left in my registers */
754 GC_noop(0,0,0,0,0,0);
755 result = (int)GC_try_to_collect_inner(stop_func);
756 EXIT_GC();
757 UNLOCK();
758 ENABLE_SIGNALS();
759 if(result) {
760 if (GC_debugging_started) GC_print_all_smashed();
761 GC_INVOKE_FINALIZERS();
763 return(result);
766 void GC_gcollect GC_PROTO(())
768 (void)GC_try_to_collect(GC_never_stop_func);
769 if (GC_have_errors) GC_print_all_errors();
772 word GC_n_heap_sects = 0; /* Number of sections currently in heap. */
775 * Use the chunk of memory starting at p of size bytes as part of the heap.
776 * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
778 void GC_add_to_heap(p, bytes)
779 struct hblk *p;
780 word bytes;
782 word words;
783 hdr * phdr;
785 if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
786 ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
788 phdr = GC_install_header(p);
789 if (0 == phdr) {
790 /* This is extremely unlikely. Can't add it. This will */
791 /* almost certainly result in a 0 return from the allocator, */
792 /* which is entirely appropriate. */
793 return;
795 GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
796 GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
797 GC_n_heap_sects++;
798 words = BYTES_TO_WORDS(bytes);
799 phdr -> hb_sz = words;
800 phdr -> hb_map = (unsigned char *)1; /* A value != GC_invalid_map */
801 phdr -> hb_flags = 0;
802 GC_freehblk(p);
803 GC_heapsize += bytes;
804 if ((ptr_t)p <= (ptr_t)GC_least_plausible_heap_addr
805 || GC_least_plausible_heap_addr == 0) {
806 GC_least_plausible_heap_addr = (GC_PTR)((ptr_t)p - sizeof(word));
807 /* Making it a little smaller than necessary prevents */
808 /* us from getting a false hit from the variable */
809 /* itself. There's some unintentional reflection */
810 /* here. */
812 if ((ptr_t)p + bytes >= (ptr_t)GC_greatest_plausible_heap_addr) {
813 GC_greatest_plausible_heap_addr = (GC_PTR)((ptr_t)p + bytes);
817 # if !defined(NO_DEBUGGING)
818 void GC_print_heap_sects()
820 register unsigned i;
822 GC_printf1("Total heap size: %lu\n", (unsigned long) GC_heapsize);
823 for (i = 0; i < GC_n_heap_sects; i++) {
824 unsigned long start = (unsigned long) GC_heap_sects[i].hs_start;
825 unsigned long len = (unsigned long) GC_heap_sects[i].hs_bytes;
826 struct hblk *h;
827 unsigned nbl = 0;
829 GC_printf3("Section %ld from 0x%lx to 0x%lx ", (unsigned long)i,
830 start, (unsigned long)(start + len));
831 for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) {
832 if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
834 GC_printf2("%lu/%lu blacklisted\n", (unsigned long)nbl,
835 (unsigned long)(len/HBLKSIZE));
838 # endif
840 GC_PTR GC_least_plausible_heap_addr = (GC_PTR)ONES;
841 GC_PTR GC_greatest_plausible_heap_addr = 0;
843 ptr_t GC_max(x,y)
844 ptr_t x, y;
846 return(x > y? x : y);
849 ptr_t GC_min(x,y)
850 ptr_t x, y;
852 return(x < y? x : y);
855 # if defined(__STDC__) || defined(__cplusplus)
856 void GC_set_max_heap_size(GC_word n)
857 # else
858 void GC_set_max_heap_size(n)
859 GC_word n;
860 # endif
862 GC_max_heapsize = n;
865 GC_word GC_max_retries = 0;
868 * this explicitly increases the size of the heap. It is used
869 * internally, but may also be invoked from GC_expand_hp by the user.
870 * The argument is in units of HBLKSIZE.
871 * Tiny values of n are rounded up.
872 * Returns FALSE on failure.
874 GC_bool GC_expand_hp_inner(n)
875 word n;
877 word bytes;
878 struct hblk * space;
879 word expansion_slop; /* Number of bytes by which we expect the */
880 /* heap to expand soon. */
882 if (n < MINHINCR) n = MINHINCR;
883 bytes = n * HBLKSIZE;
884 /* Make sure bytes is a multiple of GC_page_size */
886 word mask = GC_page_size - 1;
887 bytes += mask;
888 bytes &= ~mask;
891 if (GC_max_heapsize != 0 && GC_heapsize + bytes > GC_max_heapsize) {
892 /* Exceeded self-imposed limit */
893 return(FALSE);
895 space = GET_MEM(bytes);
896 if( space == 0 ) {
897 # ifdef CONDPRINT
898 if (GC_print_stats) {
899 GC_printf1("Failed to expand heap by %ld bytes\n",
900 (unsigned long)bytes);
902 # endif
903 return(FALSE);
905 # ifdef CONDPRINT
906 if (GC_print_stats) {
907 GC_printf2("Increasing heap size by %lu after %lu allocated bytes\n",
908 (unsigned long)bytes,
909 (unsigned long)WORDS_TO_BYTES(GC_words_allocd));
910 # ifdef UNDEFINED
911 GC_printf1("Root size = %lu\n", GC_root_size);
912 GC_print_block_list(); GC_print_hblkfreelist();
913 GC_printf0("\n");
914 # endif
916 # endif
917 expansion_slop = 8 * WORDS_TO_BYTES(min_words_allocd());
918 if (5 * HBLKSIZE * MAXHINCR > expansion_slop) {
919 expansion_slop = 5 * HBLKSIZE * MAXHINCR;
921 if (GC_last_heap_addr == 0 && !((word)space & SIGNB)
922 || GC_last_heap_addr != 0 && GC_last_heap_addr < (ptr_t)space) {
923 /* Assume the heap is growing up */
924 GC_greatest_plausible_heap_addr =
925 GC_max(GC_greatest_plausible_heap_addr,
926 (ptr_t)space + bytes + expansion_slop);
927 } else {
928 /* Heap is growing down */
929 GC_least_plausible_heap_addr =
930 GC_min(GC_least_plausible_heap_addr,
931 (ptr_t)space - expansion_slop);
933 GC_prev_heap_addr = GC_last_heap_addr;
934 GC_last_heap_addr = (ptr_t)space;
935 GC_add_to_heap(space, bytes);
936 return(TRUE);
939 /* Really returns a bool, but it's externally visible, so that's clumsy. */
940 /* Arguments is in bytes. */
941 # if defined(__STDC__) || defined(__cplusplus)
942 int GC_expand_hp(size_t bytes)
943 # else
944 int GC_expand_hp(bytes)
945 size_t bytes;
946 # endif
948 int result;
949 DCL_LOCK_STATE;
951 DISABLE_SIGNALS();
952 LOCK();
953 if (!GC_is_initialized) GC_init_inner();
954 result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
955 if (result) GC_requested_heapsize += bytes;
956 UNLOCK();
957 ENABLE_SIGNALS();
958 return(result);
961 unsigned GC_fail_count = 0;
962 /* How many consecutive GC/expansion failures? */
963 /* Reset by GC_allochblk. */
965 GC_bool GC_collect_or_expand(needed_blocks, ignore_off_page)
966 word needed_blocks;
967 GC_bool ignore_off_page;
969 if (!GC_incremental && !GC_dont_gc &&
970 (GC_dont_expand && GC_words_allocd > 0 || GC_should_collect())) {
971 GC_gcollect_inner();
972 } else {
973 word blocks_to_get = GC_heapsize/(HBLKSIZE*GC_free_space_divisor)
974 + needed_blocks;
976 if (blocks_to_get > MAXHINCR) {
977 word slop;
979 if (ignore_off_page) {
980 slop = 4;
981 } else {
982 slop = 2*divHBLKSZ(BL_LIMIT);
983 if (slop > needed_blocks) slop = needed_blocks;
985 if (needed_blocks + slop > MAXHINCR) {
986 blocks_to_get = needed_blocks + slop;
987 } else {
988 blocks_to_get = MAXHINCR;
991 if (!GC_expand_hp_inner(blocks_to_get)
992 && !GC_expand_hp_inner(needed_blocks)) {
993 if (GC_fail_count++ < GC_max_retries) {
994 WARN("Out of Memory! Trying to continue ...\n", 0);
995 GC_gcollect_inner();
996 } else {
997 # if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
998 WARN("Out of Memory! Returning NIL!\n", 0);
999 # endif
1000 return(FALSE);
1002 } else {
1003 # ifdef CONDPRINT
1004 if (GC_fail_count && GC_print_stats) {
1005 GC_printf0("Memory available again ...\n");
1007 # endif
1010 return(TRUE);
1014 * Make sure the object free list for sz is not empty.
1015 * Return a pointer to the first object on the free list.
1016 * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
1017 * Assumes we hold the allocator lock and signals are disabled.
1020 ptr_t GC_allocobj(sz, kind)
1021 word sz;
1022 int kind;
1024 ptr_t * flh = &(GC_obj_kinds[kind].ok_freelist[sz]);
1025 GC_bool tried_minor = FALSE;
1027 if (sz == 0) return(0);
1029 while (*flh == 0) {
1030 ENTER_GC();
1031 /* Do our share of marking work */
1032 if(TRUE_INCREMENTAL) GC_collect_a_little_inner(1);
1033 /* Sweep blocks for objects of this size */
1034 GC_continue_reclaim(sz, kind);
1035 EXIT_GC();
1036 if (*flh == 0) {
1037 GC_new_hblk(sz, kind);
1039 if (*flh == 0) {
1040 ENTER_GC();
1041 if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED
1042 && ! tried_minor ) {
1043 GC_collect_a_little_inner(1);
1044 tried_minor = TRUE;
1045 } else {
1046 if (!GC_collect_or_expand((word)1,FALSE)) {
1047 EXIT_GC();
1048 return(0);
1051 EXIT_GC();
1054 /* Successful allocation; reset failure count. */
1055 GC_fail_count = 0;
1057 return(*flh);