2009-08-01 Mark Probst <mark.probst@gmail.com>
[mono-project/dkf.git] / libgc / alloc.c
blob9ec6992352ad893b381dff712b37791359a183e8
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 #ifdef THREADS
76 GC_bool GC_world_stopped = FALSE;
77 # define IF_THREADS(x) x
78 #else
79 # define IF_THREADS(x)
80 #endif
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 # include "version.h"
95 #if defined(SAVE_CALL_CHAIN) && \
96 !(defined(REDIRECT_MALLOC) && defined(GC_HAVE_BUILTIN_BACKTRACE))
97 # define SAVE_CALL_CHAIN_IN_GC
98 /* This is only safe if the call chain save mechanism won't end up */
99 /* calling GC_malloc. The GNU C library documentation suggests */
100 /* that backtrace doesn't use malloc, but at least the initial */
101 /* call in some versions does seem to invoke the dynamic linker, */
102 /* which uses malloc. */
103 #endif
105 /* some more variables */
107 extern signed_word GC_mem_found; /* Number of reclaimed longwords */
108 /* after garbage collection */
110 GC_bool GC_dont_expand = 0;
112 word GC_free_space_divisor = 3;
114 extern GC_bool GC_collection_in_progress();
115 /* Collection is in progress, or was abandoned. */
117 int GC_never_stop_func GC_PROTO((void)) { return(0); }
119 unsigned long GC_time_limit = TIME_LIMIT;
121 CLOCK_TYPE GC_start_time; /* Time at which we stopped world. */
122 /* used only in GC_timeout_stop_func. */
124 int GC_n_attempts = 0; /* Number of attempts at finishing */
125 /* collection within GC_time_limit. */
127 #if defined(SMALL_CONFIG) || defined(NO_CLOCK)
128 # define GC_timeout_stop_func GC_never_stop_func
129 #else
130 int GC_timeout_stop_func GC_PROTO((void))
132 CLOCK_TYPE current_time;
133 static unsigned count = 0;
134 unsigned long time_diff;
136 if ((count++ & 3) != 0) return(0);
137 GET_TIME(current_time);
138 time_diff = MS_TIME_DIFF(current_time,GC_start_time);
139 if (time_diff >= GC_time_limit) {
140 # ifdef CONDPRINT
141 if (GC_print_stats) {
142 GC_printf0("Abandoning stopped marking after ");
143 GC_printf1("%lu msecs", (unsigned long)time_diff);
144 GC_printf1("(attempt %ld)\n", (unsigned long) GC_n_attempts);
146 # endif
147 return(1);
149 return(0);
151 #endif /* !SMALL_CONFIG */
153 /* Return the minimum number of words that must be allocated between */
154 /* collections to amortize the collection cost. */
155 static word min_words_allocd()
157 # ifdef THREADS
158 /* We punt, for now. */
159 register signed_word stack_size = 10000;
160 # else
161 int dummy;
162 register signed_word stack_size = (ptr_t)(&dummy) - GC_stackbottom;
163 # endif
164 word total_root_size; /* includes double stack size, */
165 /* since the stack is expensive */
166 /* to scan. */
167 word scan_size; /* Estimate of memory to be scanned */
168 /* during normal GC. */
170 if (stack_size < 0) stack_size = -stack_size;
171 total_root_size = 2 * stack_size + GC_root_size;
172 scan_size = BYTES_TO_WORDS(GC_heapsize - GC_large_free_bytes
173 + (GC_large_free_bytes >> 2)
174 /* use a bit more of large empty heap */
175 + total_root_size);
176 if (TRUE_INCREMENTAL) {
177 return scan_size / (2 * GC_free_space_divisor);
178 } else {
179 return scan_size / GC_free_space_divisor;
183 /* Return the number of words allocated, adjusted for explicit storage */
184 /* management, etc.. This number is used in deciding when to trigger */
185 /* collections. */
186 word GC_adj_words_allocd()
188 register signed_word result;
189 register signed_word expl_managed =
190 BYTES_TO_WORDS((long)GC_non_gc_bytes
191 - (long)GC_non_gc_bytes_at_gc);
193 /* Don't count what was explicitly freed, or newly allocated for */
194 /* explicit management. Note that deallocating an explicitly */
195 /* managed object should not alter result, assuming the client */
196 /* is playing by the rules. */
197 result = (signed_word)GC_words_allocd
198 - (signed_word)GC_mem_freed
199 + (signed_word)GC_finalizer_mem_freed - expl_managed;
200 if (result > (signed_word)GC_words_allocd) {
201 result = GC_words_allocd;
202 /* probably client bug or unfortunate scheduling */
204 result += GC_words_finalized;
205 /* We count objects enqueued for finalization as though they */
206 /* had been reallocated this round. Finalization is user */
207 /* visible progress. And if we don't count this, we have */
208 /* stability problems for programs that finalize all objects. */
209 if ((GC_words_wasted >> 3) < result)
210 result += GC_words_wasted;
211 /* This doesn't reflect useful work. But if there is lots of */
212 /* new fragmentation, the same is probably true of the heap, */
213 /* and the collection will be correspondingly cheaper. */
214 if (result < (signed_word)(GC_words_allocd >> 3)) {
215 /* Always count at least 1/8 of the allocations. We don't want */
216 /* to collect too infrequently, since that would inhibit */
217 /* coalescing of free storage blocks. */
218 /* This also makes us partially robust against client bugs. */
219 return(GC_words_allocd >> 3);
220 } else {
221 return(result);
226 /* Clear up a few frames worth of garbage left at the top of the stack. */
227 /* This is used to prevent us from accidentally treating garbade left */
228 /* on the stack by other parts of the collector as roots. This */
229 /* differs from the code in misc.c, which actually tries to keep the */
230 /* stack clear of long-lived, client-generated garbage. */
231 void GC_clear_a_few_frames()
233 # define NWORDS 64
234 word frames[NWORDS];
235 /* Some compilers will warn that frames was set but never used. */
236 /* That's the whole idea ... */
237 register int i;
239 for (i = 0; i < NWORDS; i++) frames[i] = 0;
242 /* Heap size at which we need a collection to avoid expanding past */
243 /* limits used by blacklisting. */
244 static word GC_collect_at_heapsize = (word)(-1);
246 /* Have we allocated enough to amortize a collection? */
247 GC_bool GC_should_collect()
249 return(GC_adj_words_allocd() >= min_words_allocd()
250 || GC_heapsize >= GC_collect_at_heapsize);
254 void GC_notify_full_gc()
256 if (GC_start_call_back != (void (*) GC_PROTO((void)))0) {
257 (*GC_start_call_back)();
261 GC_bool GC_is_full_gc = FALSE;
264 * Initiate a garbage collection if appropriate.
265 * Choose judiciously
266 * between partial, full, and stop-world collections.
267 * Assumes lock held, signals disabled.
269 void GC_maybe_gc()
271 static int n_partial_gcs = 0;
273 if (GC_should_collect()) {
274 if (!GC_incremental) {
275 GC_gcollect_inner();
276 n_partial_gcs = 0;
277 return;
278 } else {
279 # ifdef PARALLEL_MARK
280 GC_wait_for_reclaim();
281 # endif
282 if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) {
283 # ifdef CONDPRINT
284 if (GC_print_stats) {
285 GC_printf2(
286 "***>Full mark for collection %lu after %ld allocd bytes\n",
287 (unsigned long) GC_gc_no+1,
288 (long)WORDS_TO_BYTES(GC_words_allocd));
290 # endif
291 GC_promote_black_lists();
292 (void)GC_reclaim_all((GC_stop_func)0, TRUE);
293 GC_clear_marks();
294 n_partial_gcs = 0;
295 GC_notify_full_gc();
296 GC_is_full_gc = TRUE;
297 } else {
298 n_partial_gcs++;
301 /* We try to mark with the world stopped. */
302 /* If we run out of time, this turns into */
303 /* incremental marking. */
304 # ifndef NO_CLOCK
305 if (GC_time_limit != GC_TIME_UNLIMITED) { GET_TIME(GC_start_time); }
306 # endif
307 if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED?
308 GC_never_stop_func : GC_timeout_stop_func)) {
309 # ifdef SAVE_CALL_CHAIN_IN_GC
310 GC_save_callers(GC_last_stack);
311 # endif
312 GC_finish_collection();
313 } else {
314 if (!GC_is_full_gc) {
315 /* Count this as the first attempt */
316 GC_n_attempts++;
324 * Stop the world garbage collection. Assumes lock held, signals disabled.
325 * If stop_func is not GC_never_stop_func, then abort if stop_func returns TRUE.
326 * Return TRUE if we successfully completed the collection.
328 GC_bool GC_try_to_collect_inner(stop_func)
329 GC_stop_func stop_func;
331 # ifdef CONDPRINT
332 CLOCK_TYPE start_time, current_time;
333 # endif
334 if (GC_dont_gc) return FALSE;
336 if (GC_notify_event)
337 GC_notify_event (GC_EVENT_START);
339 if (GC_incremental && GC_collection_in_progress()) {
340 # ifdef CONDPRINT
341 if (GC_print_stats) {
342 GC_printf0(
343 "GC_try_to_collect_inner: finishing collection in progress\n");
345 # endif /* CONDPRINT */
346 /* Just finish collection already in progress. */
347 while(GC_collection_in_progress()) {
348 if (stop_func()) return(FALSE);
349 GC_collect_a_little_inner(1);
352 if (stop_func == GC_never_stop_func) GC_notify_full_gc();
353 # ifdef CONDPRINT
354 if (GC_print_stats) {
355 if (GC_print_stats) GET_TIME(start_time);
356 GC_printf2(
357 "Initiating full world-stop collection %lu after %ld allocd bytes\n",
358 (unsigned long) GC_gc_no+1,
359 (long)WORDS_TO_BYTES(GC_words_allocd));
361 # endif
362 GC_promote_black_lists();
363 /* Make sure all blocks have been reclaimed, so sweep routines */
364 /* don't see cleared mark bits. */
365 /* If we're guaranteed to finish, then this is unnecessary. */
366 /* In the find_leak case, we have to finish to guarantee that */
367 /* previously unmarked objects are not reported as leaks. */
368 # ifdef PARALLEL_MARK
369 GC_wait_for_reclaim();
370 # endif
371 if ((GC_find_leak || stop_func != GC_never_stop_func)
372 && !GC_reclaim_all(stop_func, FALSE)) {
373 /* Aborted. So far everything is still consistent. */
374 return(FALSE);
376 GC_invalidate_mark_state(); /* Flush mark stack. */
377 GC_clear_marks();
378 # ifdef SAVE_CALL_CHAIN_IN_GC
379 GC_save_callers(GC_last_stack);
380 # endif
381 GC_is_full_gc = TRUE;
382 if (!GC_stopped_mark(stop_func)) {
383 if (!GC_incremental) {
384 /* We're partially done and have no way to complete or use */
385 /* current work. Reestablish invariants as cheaply as */
386 /* possible. */
387 GC_invalidate_mark_state();
388 GC_unpromote_black_lists();
389 } /* else we claim the world is already still consistent. We'll */
390 /* finish incrementally. */
391 return(FALSE);
393 GC_finish_collection();
394 # if defined(CONDPRINT)
395 if (GC_print_stats) {
396 GET_TIME(current_time);
397 GC_printf1("Complete collection took %lu msecs\n",
398 MS_TIME_DIFF(current_time,start_time));
400 # endif
401 if (GC_notify_event)
402 GC_notify_event (GC_EVENT_END);
404 return(TRUE);
410 * Perform n units of garbage collection work. A unit is intended to touch
411 * roughly GC_RATE pages. Every once in a while, we do more than that.
412 * This needa to be a fairly large number with our current incremental
413 * GC strategy, since otherwise we allocate too much during GC, and the
414 * cleanup gets expensive.
416 # define GC_RATE 10
417 # define MAX_PRIOR_ATTEMPTS 1
418 /* Maximum number of prior attempts at world stop marking */
419 /* A value of 1 means that we finish the second time, no matter */
420 /* how long it takes. Doesn't count the initial root scan */
421 /* for a full GC. */
423 int GC_deficit = 0; /* The number of extra calls to GC_mark_some */
424 /* that we have made. */
426 void GC_collect_a_little_inner(n)
427 int n;
429 register int i;
431 if (GC_dont_gc) return;
432 if (GC_incremental && GC_collection_in_progress()) {
433 for (i = GC_deficit; i < GC_RATE*n; i++) {
434 if (GC_mark_some((ptr_t)0)) {
435 /* Need to finish a collection */
436 # ifdef SAVE_CALL_CHAIN_IN_GC
437 GC_save_callers(GC_last_stack);
438 # endif
439 # ifdef PARALLEL_MARK
440 GC_wait_for_reclaim();
441 # endif
442 if (GC_n_attempts < MAX_PRIOR_ATTEMPTS
443 && GC_time_limit != GC_TIME_UNLIMITED) {
444 GET_TIME(GC_start_time);
445 if (!GC_stopped_mark(GC_timeout_stop_func)) {
446 GC_n_attempts++;
447 break;
449 } else {
450 (void)GC_stopped_mark(GC_never_stop_func);
452 GC_finish_collection();
453 break;
456 if (GC_deficit > 0) GC_deficit -= GC_RATE*n;
457 if (GC_deficit < 0) GC_deficit = 0;
458 } else {
459 GC_maybe_gc();
463 int GC_collect_a_little GC_PROTO(())
465 int result;
466 DCL_LOCK_STATE;
468 DISABLE_SIGNALS();
469 LOCK();
470 GC_collect_a_little_inner(1);
471 result = (int)GC_collection_in_progress();
472 UNLOCK();
473 ENABLE_SIGNALS();
474 if (!result && GC_debugging_started) GC_print_all_smashed();
475 return(result);
479 * Assumes lock is held, signals are disabled.
480 * We stop the world.
481 * If stop_func() ever returns TRUE, we may fail and return FALSE.
482 * Increment GC_gc_no if we succeed.
484 GC_bool GC_stopped_mark(stop_func)
485 GC_stop_func stop_func;
487 register int i;
488 int dummy;
489 # if defined(PRINTTIMES) || defined(CONDPRINT)
490 CLOCK_TYPE start_time, current_time;
491 # endif
493 # ifdef PRINTTIMES
494 GET_TIME(start_time);
495 # endif
496 # if defined(CONDPRINT) && !defined(PRINTTIMES)
497 if (GC_print_stats) GET_TIME(start_time);
498 # endif
500 # if defined(REGISTER_LIBRARIES_EARLY)
501 GC_cond_register_dynamic_libraries();
502 # endif
503 STOP_WORLD();
504 IF_THREADS(GC_world_stopped = TRUE);
506 if (GC_notify_event)
507 GC_notify_event (GC_EVENT_MARK_START);
509 # ifdef CONDPRINT
510 if (GC_print_stats) {
511 GC_printf1("--> Marking for collection %lu ",
512 (unsigned long) GC_gc_no + 1);
513 GC_printf2("after %lu allocd bytes + %lu wasted bytes\n",
514 (unsigned long) WORDS_TO_BYTES(GC_words_allocd),
515 (unsigned long) WORDS_TO_BYTES(GC_words_wasted));
517 # endif
518 # ifdef MAKE_BACK_GRAPH
519 if (GC_print_back_height) {
520 GC_build_back_graph();
522 # endif
524 /* Mark from all roots. */
525 /* Minimize junk left in my registers and on the stack */
526 GC_clear_a_few_frames();
527 GC_noop(0,0,0,0,0,0);
528 GC_initiate_gc();
529 for(i = 0;;i++) {
530 if ((*stop_func)()) {
531 # ifdef CONDPRINT
532 if (GC_print_stats) {
533 GC_printf0("Abandoned stopped marking after ");
534 GC_printf1("%lu iterations\n",
535 (unsigned long)i);
537 # endif
538 GC_deficit = i; /* Give the mutator a chance. */
539 IF_THREADS(GC_world_stopped = FALSE);
540 START_WORLD();
541 return(FALSE);
543 if (GC_mark_some((ptr_t)(&dummy))) break;
546 GC_gc_no++;
547 # ifdef PRINTSTATS
548 GC_printf2("Collection %lu reclaimed %ld bytes",
549 (unsigned long) GC_gc_no - 1,
550 (long)WORDS_TO_BYTES(GC_mem_found));
551 # else
552 # ifdef CONDPRINT
553 if (GC_print_stats) {
554 GC_printf1("Collection %lu finished", (unsigned long) GC_gc_no - 1);
556 # endif
557 # endif /* !PRINTSTATS */
558 # ifdef CONDPRINT
559 if (GC_print_stats) {
560 GC_printf1(" ---> heapsize = %lu bytes\n",
561 (unsigned long) GC_heapsize);
562 /* Printf arguments may be pushed in funny places. Clear the */
563 /* space. */
564 GC_printf0("");
566 # endif /* CONDPRINT */
568 /* Check all debugged objects for consistency */
569 if (GC_debugging_started) {
570 (*GC_check_heap)();
574 if (GC_notify_event)
575 GC_notify_event (GC_EVENT_MARK_END);
577 IF_THREADS(GC_world_stopped = FALSE);
578 START_WORLD();
579 # ifdef PRINTTIMES
580 GET_TIME(current_time);
581 GC_printf1("World-stopped marking took %lu msecs\n",
582 MS_TIME_DIFF(current_time,start_time));
583 # else
584 # ifdef CONDPRINT
585 if (GC_print_stats) {
586 GET_TIME(current_time);
587 GC_printf1("World-stopped marking took %lu msecs\n",
588 MS_TIME_DIFF(current_time,start_time));
590 # endif
591 # endif
592 return(TRUE);
595 /* Set all mark bits for the free list whose first entry is q */
596 #ifdef __STDC__
597 void GC_set_fl_marks(ptr_t q)
598 #else
599 void GC_set_fl_marks(q)
600 ptr_t q;
601 #endif
603 ptr_t p;
604 struct hblk * h, * last_h = 0;
605 hdr *hhdr;
606 int word_no;
608 for (p = q; p != 0; p = obj_link(p)){
609 h = HBLKPTR(p);
610 if (h != last_h) {
611 last_h = h;
612 hhdr = HDR(h);
614 word_no = (((word *)p) - ((word *)h));
615 set_mark_bit_from_hdr(hhdr, word_no);
619 /* Clear all mark bits for the free list whose first entry is q */
620 /* Decrement GC_mem_found by number of words on free list. */
621 #ifdef __STDC__
622 void GC_clear_fl_marks(ptr_t q)
623 #else
624 void GC_clear_fl_marks(q)
625 ptr_t q;
626 #endif
628 ptr_t p;
629 struct hblk * h, * last_h = 0;
630 hdr *hhdr;
631 int word_no;
633 for (p = q; p != 0; p = obj_link(p)){
634 h = HBLKPTR(p);
635 if (h != last_h) {
636 last_h = h;
637 hhdr = HDR(h);
639 word_no = (((word *)p) - ((word *)h));
640 clear_mark_bit_from_hdr(hhdr, word_no);
641 # ifdef GATHERSTATS
642 GC_mem_found -= hhdr -> hb_sz;
643 # endif
647 void (*GC_notify_event) GC_PROTO((GCEventType e));
648 void (*GC_on_heap_resize) GC_PROTO((size_t new_size));
650 /* Finish up a collection. Assumes lock is held, signals are disabled, */
651 /* but the world is otherwise running. */
652 void GC_finish_collection()
654 # ifdef PRINTTIMES
655 CLOCK_TYPE start_time;
656 CLOCK_TYPE finalize_time;
657 CLOCK_TYPE done_time;
659 GET_TIME(start_time);
660 finalize_time = start_time;
661 # endif
664 if (GC_notify_event)
665 GC_notify_event (GC_EVENT_RECLAIM_START);
667 # ifdef GATHERSTATS
668 GC_mem_found = 0;
669 # endif
670 # if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
671 if (getenv("GC_PRINT_ADDRESS_MAP") != 0) {
672 GC_print_address_map();
674 # endif
676 COND_DUMP;
677 if (GC_find_leak) {
678 /* Mark all objects on the free list. All objects should be */
679 /* marked when we're done. */
681 register word size; /* current object size */
682 int kind;
683 ptr_t q;
685 for (kind = 0; kind < GC_n_kinds; kind++) {
686 for (size = 1; size <= MAXOBJSZ; size++) {
687 q = GC_obj_kinds[kind].ok_freelist[size];
688 if (q != 0) GC_set_fl_marks(q);
692 GC_start_reclaim(TRUE);
693 /* The above just checks; it doesn't really reclaim anything. */
696 GC_finalize();
697 # ifdef STUBBORN_ALLOC
698 GC_clean_changing_list();
699 # endif
701 # ifdef PRINTTIMES
702 GET_TIME(finalize_time);
703 # endif
705 if (GC_print_back_height) {
706 # ifdef MAKE_BACK_GRAPH
707 GC_traverse_back_graph();
708 # else
709 # ifndef SMALL_CONFIG
710 GC_err_printf0("Back height not available: "
711 "Rebuild collector with -DMAKE_BACK_GRAPH\n");
712 # endif
713 # endif
716 /* Clear free list mark bits, in case they got accidentally marked */
717 /* (or GC_find_leak is set and they were intentionally marked). */
718 /* Also subtract memory remaining from GC_mem_found count. */
719 /* Note that composite objects on free list are cleared. */
720 /* Thus accidentally marking a free list is not a problem; only */
721 /* objects on the list itself will be marked, and that's fixed here. */
723 register word size; /* current object size */
724 register ptr_t q; /* pointer to current object */
725 int kind;
727 for (kind = 0; kind < GC_n_kinds; kind++) {
728 for (size = 1; size <= MAXOBJSZ; size++) {
729 q = GC_obj_kinds[kind].ok_freelist[size];
730 if (q != 0) GC_clear_fl_marks(q);
736 # ifdef PRINTSTATS
737 GC_printf1("Bytes recovered before sweep - f.l. count = %ld\n",
738 (long)WORDS_TO_BYTES(GC_mem_found));
739 # endif
740 /* Reconstruct free lists to contain everything not marked */
741 GC_start_reclaim(FALSE);
742 if (GC_is_full_gc) {
743 GC_used_heap_size_after_full = USED_HEAP_SIZE;
744 GC_need_full_gc = FALSE;
745 } else {
746 GC_need_full_gc =
747 BYTES_TO_WORDS(USED_HEAP_SIZE - GC_used_heap_size_after_full)
748 > min_words_allocd();
751 # ifdef PRINTSTATS
752 GC_printf2(
753 "Immediately reclaimed %ld bytes in heap of size %lu bytes",
754 (long)WORDS_TO_BYTES(GC_mem_found),
755 (unsigned long)GC_heapsize);
756 # ifdef USE_MUNMAP
757 GC_printf1("(%lu unmapped)", GC_unmapped_bytes);
758 # endif
759 GC_printf2(
760 "\n%lu (atomic) + %lu (composite) collectable bytes in use\n",
761 (unsigned long)WORDS_TO_BYTES(GC_atomic_in_use),
762 (unsigned long)WORDS_TO_BYTES(GC_composite_in_use));
763 # endif
765 GC_n_attempts = 0;
766 GC_is_full_gc = FALSE;
767 /* Reset or increment counters for next cycle */
768 GC_words_allocd_before_gc += GC_words_allocd;
769 GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
770 GC_words_allocd = 0;
771 GC_words_wasted = 0;
772 GC_mem_freed = 0;
773 GC_finalizer_mem_freed = 0;
775 # ifdef USE_MUNMAP
776 GC_unmap_old();
777 # endif
779 if (GC_notify_event)
780 GC_notify_event (GC_EVENT_RECLAIM_END);
782 # ifdef PRINTTIMES
783 GET_TIME(done_time);
784 GC_printf2("Finalize + initiate sweep took %lu + %lu msecs\n",
785 MS_TIME_DIFF(finalize_time,start_time),
786 MS_TIME_DIFF(done_time,finalize_time));
787 # endif
790 /* Externally callable routine to invoke full, stop-world collection */
791 # if defined(__STDC__) || defined(__cplusplus)
792 int GC_try_to_collect(GC_stop_func stop_func)
793 # else
794 int GC_try_to_collect(stop_func)
795 GC_stop_func stop_func;
796 # endif
798 int result;
799 DCL_LOCK_STATE;
801 if (GC_debugging_started) GC_print_all_smashed();
802 GC_INVOKE_FINALIZERS();
803 DISABLE_SIGNALS();
804 LOCK();
805 ENTER_GC();
806 if (!GC_is_initialized) GC_init_inner();
807 /* Minimize junk left in my registers */
808 GC_noop(0,0,0,0,0,0);
809 result = (int)GC_try_to_collect_inner(stop_func);
810 EXIT_GC();
811 UNLOCK();
812 ENABLE_SIGNALS();
813 if(result) {
814 if (GC_debugging_started) GC_print_all_smashed();
815 GC_INVOKE_FINALIZERS();
817 return(result);
820 void GC_gcollect GC_PROTO(())
822 (void)GC_try_to_collect(GC_never_stop_func);
823 if (GC_have_errors) GC_print_all_errors();
826 word GC_n_heap_sects = 0; /* Number of sections currently in heap. */
829 * Use the chunk of memory starting at p of size bytes as part of the heap.
830 * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
832 void GC_add_to_heap(p, bytes)
833 struct hblk *p;
834 word bytes;
836 word words;
837 hdr * phdr;
839 if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
840 ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
842 phdr = GC_install_header(p);
843 if (0 == phdr) {
844 /* This is extremely unlikely. Can't add it. This will */
845 /* almost certainly result in a 0 return from the allocator, */
846 /* which is entirely appropriate. */
847 return;
849 GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
850 GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
851 GC_n_heap_sects++;
852 words = BYTES_TO_WORDS(bytes);
853 phdr -> hb_sz = words;
854 phdr -> hb_map = (unsigned char *)1; /* A value != GC_invalid_map */
855 phdr -> hb_flags = 0;
856 GC_freehblk(p);
857 GC_heapsize += bytes;
858 if ((ptr_t)p <= (ptr_t)GC_least_plausible_heap_addr
859 || GC_least_plausible_heap_addr == 0) {
860 GC_least_plausible_heap_addr = (GC_PTR)((ptr_t)p - sizeof(word));
861 /* Making it a little smaller than necessary prevents */
862 /* us from getting a false hit from the variable */
863 /* itself. There's some unintentional reflection */
864 /* here. */
866 if ((ptr_t)p + bytes >= (ptr_t)GC_greatest_plausible_heap_addr) {
867 GC_greatest_plausible_heap_addr = (GC_PTR)((ptr_t)p + bytes);
871 # if !defined(NO_DEBUGGING)
872 void GC_print_heap_sects()
874 register unsigned i;
876 GC_printf1("Total heap size: %lu\n", (unsigned long) GC_heapsize);
877 for (i = 0; i < GC_n_heap_sects; i++) {
878 unsigned long start = (unsigned long) GC_heap_sects[i].hs_start;
879 unsigned long len = (unsigned long) GC_heap_sects[i].hs_bytes;
880 struct hblk *h;
881 unsigned nbl = 0;
883 GC_printf3("Section %ld from 0x%lx to 0x%lx ", (unsigned long)i,
884 start, (unsigned long)(start + len));
885 for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) {
886 if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
888 GC_printf2("%lu/%lu blacklisted\n", (unsigned long)nbl,
889 (unsigned long)(len/HBLKSIZE));
892 # endif
894 GC_PTR GC_least_plausible_heap_addr = (GC_PTR)ONES;
895 GC_PTR GC_greatest_plausible_heap_addr = 0;
897 ptr_t GC_max(x,y)
898 ptr_t x, y;
900 return(x > y? x : y);
903 ptr_t GC_min(x,y)
904 ptr_t x, y;
906 return(x < y? x : y);
909 # if defined(__STDC__) || defined(__cplusplus)
910 void GC_set_max_heap_size(GC_word n)
911 # else
912 void GC_set_max_heap_size(n)
913 GC_word n;
914 # endif
916 GC_max_heapsize = n;
919 GC_word GC_max_retries = 0;
922 * this explicitly increases the size of the heap. It is used
923 * internally, but may also be invoked from GC_expand_hp by the user.
924 * The argument is in units of HBLKSIZE.
925 * Tiny values of n are rounded up.
926 * Returns FALSE on failure.
928 GC_bool GC_expand_hp_inner(n)
929 word n;
931 word bytes;
932 struct hblk * space;
933 word expansion_slop; /* Number of bytes by which we expect the */
934 /* heap to expand soon. */
936 if (n < MINHINCR) n = MINHINCR;
937 bytes = n * HBLKSIZE;
938 /* Make sure bytes is a multiple of GC_page_size */
940 word mask = GC_page_size - 1;
941 bytes += mask;
942 bytes &= ~mask;
945 if (GC_max_heapsize != 0 && GC_heapsize + bytes > GC_max_heapsize) {
946 /* Exceeded self-imposed limit */
947 return(FALSE);
949 space = GET_MEM(bytes);
950 if( space == 0 ) {
951 # ifdef CONDPRINT
952 if (GC_print_stats) {
953 GC_printf1("Failed to expand heap by %ld bytes\n",
954 (unsigned long)bytes);
956 # endif
957 return(FALSE);
959 # ifdef CONDPRINT
960 if (GC_print_stats) {
961 GC_printf2("Increasing heap size by %lu after %lu allocated bytes\n",
962 (unsigned long)bytes,
963 (unsigned long)WORDS_TO_BYTES(GC_words_allocd));
964 # ifdef UNDEFINED
965 GC_printf1("Root size = %lu\n", GC_root_size);
966 GC_print_block_list(); GC_print_hblkfreelist();
967 GC_printf0("\n");
968 # endif
970 # endif
971 expansion_slop = WORDS_TO_BYTES(min_words_allocd()) + 4*MAXHINCR*HBLKSIZE;
972 if (GC_last_heap_addr == 0 && !((word)space & SIGNB)
973 || (GC_last_heap_addr != 0 && GC_last_heap_addr < (ptr_t)space)) {
974 /* Assume the heap is growing up */
975 GC_greatest_plausible_heap_addr =
976 (GC_PTR)GC_max((ptr_t)GC_greatest_plausible_heap_addr,
977 (ptr_t)space + bytes + expansion_slop);
978 } else {
979 /* Heap is growing down */
980 GC_least_plausible_heap_addr =
981 (GC_PTR)GC_min((ptr_t)GC_least_plausible_heap_addr,
982 (ptr_t)space - expansion_slop);
984 # if defined(LARGE_CONFIG)
985 if (((ptr_t)GC_greatest_plausible_heap_addr <= (ptr_t)space + bytes
986 || (ptr_t)GC_least_plausible_heap_addr >= (ptr_t)space)
987 && GC_heapsize > 0) {
988 /* GC_add_to_heap will fix this, but ... */
989 WARN("Too close to address space limit: blacklisting ineffective\n", 0);
991 # endif
992 GC_prev_heap_addr = GC_last_heap_addr;
993 GC_last_heap_addr = (ptr_t)space;
994 GC_add_to_heap(space, bytes);
995 /* Force GC before we are likely to allocate past expansion_slop */
996 GC_collect_at_heapsize =
997 GC_heapsize + expansion_slop - 2*MAXHINCR*HBLKSIZE;
998 # if defined(LARGE_CONFIG)
999 if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
1000 GC_collect_at_heapsize = (word)(-1);
1001 # endif
1002 if (GC_on_heap_resize)
1003 GC_on_heap_resize (GC_heapsize);
1005 return(TRUE);
1008 /* Really returns a bool, but it's externally visible, so that's clumsy. */
1009 /* Arguments is in bytes. */
1010 # if defined(__STDC__) || defined(__cplusplus)
1011 int GC_expand_hp(size_t bytes)
1012 # else
1013 int GC_expand_hp(bytes)
1014 size_t bytes;
1015 # endif
1017 int result;
1018 DCL_LOCK_STATE;
1020 DISABLE_SIGNALS();
1021 LOCK();
1022 if (!GC_is_initialized) GC_init_inner();
1023 result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
1024 if (result) GC_requested_heapsize += bytes;
1025 UNLOCK();
1026 ENABLE_SIGNALS();
1027 return(result);
1030 unsigned GC_fail_count = 0;
1031 /* How many consecutive GC/expansion failures? */
1032 /* Reset by GC_allochblk. */
1034 static word last_fo_entries = 0;
1035 static word last_words_finalized = 0;
1037 GC_bool GC_collect_or_expand(needed_blocks, ignore_off_page)
1038 word needed_blocks;
1039 GC_bool ignore_off_page;
1041 if (!GC_incremental && !GC_dont_gc &&
1042 ((GC_dont_expand && GC_words_allocd > 0)
1043 || (GC_fo_entries > (last_fo_entries + 500) && (last_words_finalized || GC_words_finalized))
1044 || GC_should_collect())) {
1045 GC_gcollect_inner();
1046 last_fo_entries = GC_fo_entries;
1047 last_words_finalized = GC_words_finalized;
1048 } else {
1049 word blocks_to_get = GC_heapsize/(HBLKSIZE*GC_free_space_divisor)
1050 + needed_blocks;
1052 if (blocks_to_get > MAXHINCR) {
1053 word slop;
1055 /* Get the minimum required to make it likely that we */
1056 /* can satisfy the current request in the presence of black- */
1057 /* listing. This will probably be more than MAXHINCR. */
1058 if (ignore_off_page) {
1059 slop = 4;
1060 } else {
1061 slop = 2*divHBLKSZ(BL_LIMIT);
1062 if (slop > needed_blocks) slop = needed_blocks;
1064 if (needed_blocks + slop > MAXHINCR) {
1065 blocks_to_get = needed_blocks + slop;
1066 } else {
1067 blocks_to_get = MAXHINCR;
1070 if (!GC_expand_hp_inner(blocks_to_get)
1071 && !GC_expand_hp_inner(needed_blocks)) {
1072 if (GC_fail_count++ < GC_max_retries) {
1073 WARN("Out of Memory! Trying to continue ...\n", 0);
1074 GC_gcollect_inner();
1075 } else {
1076 # if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
1077 WARN("Out of Memory! Returning NIL!\n", 0);
1078 # endif
1079 return(FALSE);
1081 } else {
1082 # ifdef CONDPRINT
1083 if (GC_fail_count && GC_print_stats) {
1084 GC_printf0("Memory available again ...\n");
1086 # endif
1089 return(TRUE);
1093 * Make sure the object free list for sz is not empty.
1094 * Return a pointer to the first object on the free list.
1095 * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
1096 * Assumes we hold the allocator lock and signals are disabled.
1099 ptr_t GC_allocobj(sz, kind)
1100 word sz;
1101 int kind;
1103 ptr_t * flh = &(GC_obj_kinds[kind].ok_freelist[sz]);
1104 GC_bool tried_minor = FALSE;
1106 if (sz == 0) return(0);
1108 while (*flh == 0) {
1109 ENTER_GC();
1110 /* Do our share of marking work */
1111 if(TRUE_INCREMENTAL) GC_collect_a_little_inner(1);
1112 /* Sweep blocks for objects of this size */
1113 GC_continue_reclaim(sz, kind);
1114 EXIT_GC();
1115 if (*flh == 0) {
1116 GC_new_hblk(sz, kind);
1118 if (*flh == 0) {
1119 ENTER_GC();
1120 if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED
1121 && ! tried_minor ) {
1122 GC_collect_a_little_inner(1);
1123 tried_minor = TRUE;
1124 } else {
1125 if (!GC_collect_or_expand((word)1,FALSE)) {
1126 EXIT_GC();
1127 return(0);
1130 EXIT_GC();
1133 /* Successful allocation; reset failure count. */
1134 GC_fail_count = 0;
1136 return(*flh);