OSDN Git Service

2004-08-16 Michael Koch <konqueror@gmx.de>
[pf3gnuchains/gcc-fork.git] / boehm-gc / alloc.c
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.
6  *
7  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
8  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
9  *
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.
15  *
16  */
17
18
19 # include "private/gc_priv.h"
20
21 # include <stdio.h>
22 # if !defined(MACOS) && !defined(MSWINCE)
23 #   include <signal.h>
24 #   include <sys/types.h>
25 # endif
26
27 /*
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:
35  *
36  *            opp = &(GC_objfreelist[i]);
37  *            if (*opp == 0) GC_allocobj(i, NORMAL);
38  *            ptr = *opp;
39  *            *opp = obj_link(ptr);
40  *
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.
45  */
46
47 /*
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.
56  */
57
58 word GC_non_gc_bytes = 0;  /* Number of bytes not intended to be collected */
59
60 word GC_gc_no = 0;
61
62 #ifndef SMALL_CONFIG
63   int GC_incremental = 0;  /* By default, stop the world.       */
64 #endif
65
66 int GC_parallel = FALSE;   /* By default, parallel GC is off.   */
67
68 int GC_full_freq = 19;     /* Every 20th collection is a full   */
69                            /* collection, whether we need it    */
70                            /* or not.                           */
71
72 GC_bool GC_need_full_gc = FALSE;
73                            /* Need full GC do to heap growth.   */
74
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
81
82 word GC_used_heap_size_after_full = 0;
83
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." };
92
93 # include "version.h"
94
95 /* some more variables */
96
97 extern signed_word GC_mem_found;  /* Number of reclaimed longwords      */
98                                   /* after garbage collection           */
99
100 GC_bool GC_dont_expand = 0;
101
102 word GC_free_space_divisor = 3;
103
104 extern GC_bool GC_collection_in_progress();
105                 /* Collection is in progress, or was abandoned. */
106
107 extern GC_bool GC_print_back_height;
108
109 int GC_never_stop_func GC_PROTO((void)) { return(0); }
110
111 unsigned long GC_time_limit = TIME_LIMIT;
112
113 CLOCK_TYPE GC_start_time;       /* Time at which we stopped world.      */
114                                 /* used only in GC_timeout_stop_func.   */
115
116 int GC_n_attempts = 0;          /* Number of attempts at finishing      */
117                                 /* collection within GC_time_limit.     */
118
119 #if defined(SMALL_CONFIG) || defined(NO_CLOCK)
120 #   define GC_timeout_stop_func GC_never_stop_func
121 #else
122   int GC_timeout_stop_func GC_PROTO((void))
123   {
124     CLOCK_TYPE current_time;
125     static unsigned count = 0;
126     unsigned long time_diff;
127     
128     if ((count++ & 3) != 0) return(0);
129     GET_TIME(current_time);
130     time_diff = MS_TIME_DIFF(current_time,GC_start_time);
131     if (time_diff >= GC_time_limit) {
132 #       ifdef CONDPRINT
133           if (GC_print_stats) {
134             GC_printf0("Abandoning stopped marking after ");
135             GC_printf1("%lu msecs", (unsigned long)time_diff);
136             GC_printf1("(attempt %ld)\n", (unsigned long) GC_n_attempts);
137           }
138 #       endif
139         return(1);
140     }
141     return(0);
142   }
143 #endif /* !SMALL_CONFIG */
144
145 /* Return the minimum number of words that must be allocated between    */
146 /* collections to amortize the collection cost.                         */
147 static word min_words_allocd()
148 {
149 #   ifdef THREADS
150         /* We punt, for now. */
151         register signed_word stack_size = 10000;
152 #   else
153         int dummy;
154         register signed_word stack_size = (ptr_t)(&dummy) - GC_stackbottom;
155 #   endif
156     word total_root_size;           /* includes double stack size,      */
157                                     /* since the stack is expensive     */
158                                     /* to scan.                         */
159     word scan_size;             /* Estimate of memory to be scanned     */
160                                 /* during normal GC.                    */
161     
162     if (stack_size < 0) stack_size = -stack_size;
163     total_root_size = 2 * stack_size + GC_root_size;
164     scan_size = BYTES_TO_WORDS(GC_heapsize - GC_large_free_bytes
165                                + (GC_large_free_bytes >> 2)
166                                    /* use a bit more of large empty heap */
167                                + total_root_size);
168     if (TRUE_INCREMENTAL) {
169         return scan_size / (2 * GC_free_space_divisor);
170     } else {
171         return scan_size / GC_free_space_divisor;
172     }
173 }
174
175 /* Return the number of words allocated, adjusted for explicit storage  */
176 /* management, etc..  This number is used in deciding when to trigger   */
177 /* collections.                                                         */
178 word GC_adj_words_allocd()
179 {
180     register signed_word result;
181     register signed_word expl_managed =
182                 BYTES_TO_WORDS((long)GC_non_gc_bytes
183                                 - (long)GC_non_gc_bytes_at_gc);
184     
185     /* Don't count what was explicitly freed, or newly allocated for    */
186     /* explicit management.  Note that deallocating an explicitly       */
187     /* managed object should not alter result, assuming the client      */
188     /* is playing by the rules.                                         */
189     result = (signed_word)GC_words_allocd
190              - (signed_word)GC_mem_freed 
191              + (signed_word)GC_finalizer_mem_freed - expl_managed;
192     if (result > (signed_word)GC_words_allocd) {
193         result = GC_words_allocd;
194         /* probably client bug or unfortunate scheduling */
195     }
196     result += GC_words_finalized;
197         /* We count objects enqueued for finalization as though they    */
198         /* had been reallocated this round. Finalization is user        */
199         /* visible progress.  And if we don't count this, we have       */
200         /* stability problems for programs that finalize all objects.   */
201     result += GC_words_wasted;
202         /* This doesn't reflect useful work.  But if there is lots of   */
203         /* new fragmentation, the same is probably true of the heap,    */
204         /* and the collection will be correspondingly cheaper.          */
205     if (result < (signed_word)(GC_words_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_words_allocd >> 3);
211     } else {
212         return(result);
213     }
214 }
215
216
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()
223 {
224 #   define NWORDS 64
225     word frames[NWORDS];
226     register int i;
227     
228     for (i = 0; i < NWORDS; i++) frames[i] = 0;
229 }
230
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);
234
235 /* Have we allocated enough to amortize a collection? */
236 GC_bool GC_should_collect()
237 {
238     return(GC_adj_words_allocd() >= min_words_allocd()
239            || GC_heapsize >= GC_collect_at_heapsize);
240 }
241
242
243 void GC_notify_full_gc()
244 {
245     if (GC_start_call_back != (void (*) GC_PROTO((void)))0) {
246         (*GC_start_call_back)();
247     }
248 }
249
250 GC_bool GC_is_full_gc = FALSE;
251
252 /* 
253  * Initiate a garbage collection if appropriate.
254  * Choose judiciously
255  * between partial, full, and stop-world collections.
256  * Assumes lock held, signals disabled.
257  */
258 void GC_maybe_gc()
259 {
260     static int n_partial_gcs = 0;
261
262     if (GC_should_collect()) {
263         if (!GC_incremental) {
264             GC_gcollect_inner();
265             n_partial_gcs = 0;
266             return;
267         } else {
268 #         ifdef PARALLEL_MARK
269             GC_wait_for_reclaim();
270 #         endif
271           if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) {
272 #           ifdef CONDPRINT
273               if (GC_print_stats) {
274                 GC_printf2(
275                   "***>Full mark for collection %lu after %ld allocd bytes\n",
276                   (unsigned long) GC_gc_no+1,
277                   (long)WORDS_TO_BYTES(GC_words_allocd));
278               }
279 #           endif
280             GC_promote_black_lists();
281             (void)GC_reclaim_all((GC_stop_func)0, TRUE);
282             GC_clear_marks();
283             n_partial_gcs = 0;
284             GC_notify_full_gc();
285             GC_is_full_gc = TRUE;
286           } else {
287             n_partial_gcs++;
288           }
289         }
290         /* We try to mark with the world stopped.       */
291         /* If we run out of time, this turns into       */
292         /* incremental marking.                 */
293 #       ifndef NO_CLOCK
294           if (GC_time_limit != GC_TIME_UNLIMITED) { GET_TIME(GC_start_time); }
295 #       endif
296         if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED? 
297                             GC_never_stop_func : GC_timeout_stop_func)) {
298 #           ifdef SAVE_CALL_CHAIN
299                 GC_save_callers(GC_last_stack);
300 #           endif
301             GC_finish_collection();
302         } else {
303             if (!GC_is_full_gc) {
304                 /* Count this as the first attempt */
305                 GC_n_attempts++;
306             }
307         }
308     }
309 }
310
311
312 /*
313  * Stop the world garbage collection.  Assumes lock held, signals disabled.
314  * If stop_func is not GC_never_stop_func, then abort if stop_func returns TRUE.
315  * Return TRUE if we successfully completed the collection.
316  */
317 GC_bool GC_try_to_collect_inner(stop_func)
318 GC_stop_func stop_func;
319 {
320 #   ifdef CONDPRINT
321         CLOCK_TYPE start_time, current_time;
322 #   endif
323     if (GC_dont_gc) return FALSE;
324     if (GC_incremental && GC_collection_in_progress()) {
325 #   ifdef CONDPRINT
326       if (GC_print_stats) {
327         GC_printf0(
328             "GC_try_to_collect_inner: finishing collection in progress\n");
329       }
330 #   endif /* CONDPRINT */
331       /* Just finish collection already in progress.    */
332         while(GC_collection_in_progress()) {
333             if (stop_func()) return(FALSE);
334             GC_collect_a_little_inner(1);
335         }
336     }
337     if (stop_func == GC_never_stop_func) GC_notify_full_gc();
338 #   ifdef CONDPRINT
339       if (GC_print_stats) {
340         if (GC_print_stats) GET_TIME(start_time);
341         GC_printf2(
342            "Initiating full world-stop collection %lu after %ld allocd bytes\n",
343            (unsigned long) GC_gc_no+1,
344            (long)WORDS_TO_BYTES(GC_words_allocd));
345       }
346 #   endif
347     GC_promote_black_lists();
348     /* Make sure all blocks have been reclaimed, so sweep routines      */
349     /* don't see cleared mark bits.                                     */
350     /* If we're guaranteed to finish, then this is unnecessary.         */
351     /* In the find_leak case, we have to finish to guarantee that       */
352     /* previously unmarked objects are not reported as leaks.           */
353 #       ifdef PARALLEL_MARK
354             GC_wait_for_reclaim();
355 #       endif
356         if ((GC_find_leak || stop_func != GC_never_stop_func)
357             && !GC_reclaim_all(stop_func, FALSE)) {
358             /* Aborted.  So far everything is still consistent. */
359             return(FALSE);
360         }
361     GC_invalidate_mark_state();  /* Flush mark stack.   */
362     GC_clear_marks();
363 #   ifdef SAVE_CALL_CHAIN
364         GC_save_callers(GC_last_stack);
365 #   endif
366     GC_is_full_gc = TRUE;
367     if (!GC_stopped_mark(stop_func)) {
368       if (!GC_incremental) {
369         /* We're partially done and have no way to complete or use      */
370         /* current work.  Reestablish invariants as cheaply as          */
371         /* possible.                                                    */
372         GC_invalidate_mark_state();
373         GC_unpromote_black_lists();
374       } /* else we claim the world is already still consistent.  We'll  */
375         /* finish incrementally.                                        */
376       return(FALSE);
377     }
378     GC_finish_collection();
379 #   if defined(CONDPRINT)
380       if (GC_print_stats) {
381         GET_TIME(current_time);
382         GC_printf1("Complete collection took %lu msecs\n",
383                    MS_TIME_DIFF(current_time,start_time));
384       }
385 #   endif
386     return(TRUE);
387 }
388
389
390
391 /*
392  * Perform n units of garbage collection work.  A unit is intended to touch
393  * roughly GC_RATE pages.  Every once in a while, we do more than that.
394  * This needa to be a fairly large number with our current incremental
395  * GC strategy, since otherwise we allocate too much during GC, and the
396  * cleanup gets expensive.
397  */
398 # define GC_RATE 10 
399 # define MAX_PRIOR_ATTEMPTS 1
400         /* Maximum number of prior attempts at world stop marking       */
401         /* A value of 1 means that we finish the second time, no matter */
402         /* how long it takes.  Doesn't count the initial root scan      */
403         /* for a full GC.                                               */
404
405 int GC_deficit = 0;     /* The number of extra calls to GC_mark_some    */
406                         /* that we have made.                           */
407
408 void GC_collect_a_little_inner(n)
409 int n;
410 {
411     register int i;
412     
413     if (GC_dont_gc) return;
414     if (GC_incremental && GC_collection_in_progress()) {
415         for (i = GC_deficit; i < GC_RATE*n; i++) {
416             if (GC_mark_some((ptr_t)0)) {
417                 /* Need to finish a collection */
418 #               ifdef SAVE_CALL_CHAIN
419                     GC_save_callers(GC_last_stack);
420 #               endif
421 #               ifdef PARALLEL_MARK
422                     GC_wait_for_reclaim();
423 #               endif
424                 if (GC_n_attempts < MAX_PRIOR_ATTEMPTS
425                     && GC_time_limit != GC_TIME_UNLIMITED) {
426                   GET_TIME(GC_start_time);
427                   if (!GC_stopped_mark(GC_timeout_stop_func)) {
428                     GC_n_attempts++;
429                     break;
430                   }
431                 } else {
432                   (void)GC_stopped_mark(GC_never_stop_func);
433                 }
434                 GC_finish_collection();
435                 break;
436             }
437         }
438         if (GC_deficit > 0) GC_deficit -= GC_RATE*n;
439         if (GC_deficit < 0) GC_deficit = 0;
440     } else {
441         GC_maybe_gc();
442     }
443 }
444
445 int GC_collect_a_little GC_PROTO(())
446 {
447     int result;
448     DCL_LOCK_STATE;
449
450     DISABLE_SIGNALS();
451     LOCK();
452     GC_collect_a_little_inner(1);
453     result = (int)GC_collection_in_progress();
454     UNLOCK();
455     ENABLE_SIGNALS();
456     if (!result && GC_debugging_started) GC_print_all_smashed();
457     return(result);
458 }
459
460 /*
461  * Assumes lock is held, signals are disabled.
462  * We stop the world.
463  * If stop_func() ever returns TRUE, we may fail and return FALSE.
464  * Increment GC_gc_no if we succeed.
465  */
466 GC_bool GC_stopped_mark(stop_func)
467 GC_stop_func stop_func;
468 {
469     register int i;
470     int dummy;
471 #   if defined(PRINTTIMES) || defined(CONDPRINT)
472         CLOCK_TYPE start_time, current_time;
473 #   endif
474         
475 #   ifdef PRINTTIMES
476         GET_TIME(start_time);
477 #   endif
478 #   if defined(CONDPRINT) && !defined(PRINTTIMES)
479         if (GC_print_stats) GET_TIME(start_time);
480 #   endif
481 #   if defined(REGISTER_LIBRARIES_EARLY)
482         GC_cond_register_dynamic_libraries();
483 #   endif
484     STOP_WORLD();
485     IF_THREADS(GC_world_stopped = TRUE);
486 #   ifdef CONDPRINT
487       if (GC_print_stats) {
488         GC_printf1("--> Marking for collection %lu ",
489                    (unsigned long) GC_gc_no + 1);
490         GC_printf2("after %lu allocd bytes + %lu wasted bytes\n",
491                    (unsigned long) WORDS_TO_BYTES(GC_words_allocd),
492                    (unsigned long) WORDS_TO_BYTES(GC_words_wasted));
493       }
494 #   endif
495 #   ifdef MAKE_BACK_GRAPH
496       if (GC_print_back_height) {
497         GC_build_back_graph();
498       }
499 #   endif
500
501     /* Mark from all roots.  */
502         /* Minimize junk left in my registers and on the stack */
503             GC_clear_a_few_frames();
504             GC_noop(0,0,0,0,0,0);
505         GC_initiate_gc();
506         for(i = 0;;i++) {
507             if ((*stop_func)()) {
508 #                   ifdef CONDPRINT
509                       if (GC_print_stats) {
510                         GC_printf0("Abandoned stopped marking after ");
511                         GC_printf1("%lu iterations\n",
512                                    (unsigned long)i);
513                       }
514 #                   endif
515                     GC_deficit = i; /* Give the mutator a chance. */
516                     IF_THREADS(GC_world_stopped = FALSE);
517                     START_WORLD();
518                     return(FALSE);
519             }
520             if (GC_mark_some((ptr_t)(&dummy))) break;
521         }
522         
523     GC_gc_no++;
524 #   ifdef PRINTSTATS
525       GC_printf2("Collection %lu reclaimed %ld bytes",
526                   (unsigned long) GC_gc_no - 1,
527                   (long)WORDS_TO_BYTES(GC_mem_found));
528 #   else
529 #     ifdef CONDPRINT
530         if (GC_print_stats) {
531           GC_printf1("Collection %lu finished", (unsigned long) GC_gc_no - 1);
532         }
533 #     endif
534 #   endif /* !PRINTSTATS */
535 #   ifdef CONDPRINT
536       if (GC_print_stats) {
537         GC_printf1(" ---> heapsize = %lu bytes\n",
538                    (unsigned long) GC_heapsize);
539         /* Printf arguments may be pushed in funny places.  Clear the   */
540         /* space.                                                       */
541         GC_printf0("");
542       }
543 #   endif  /* CONDPRINT  */
544
545     /* Check all debugged objects for consistency */
546         if (GC_debugging_started) {
547             (*GC_check_heap)();
548         }
549     
550     IF_THREADS(GC_world_stopped = FALSE);
551     START_WORLD();
552 #   ifdef PRINTTIMES
553         GET_TIME(current_time);
554         GC_printf1("World-stopped marking took %lu msecs\n",
555                    MS_TIME_DIFF(current_time,start_time));
556 #   else
557 #     ifdef CONDPRINT
558         if (GC_print_stats) {
559           GET_TIME(current_time);
560           GC_printf1("World-stopped marking took %lu msecs\n",
561                      MS_TIME_DIFF(current_time,start_time));
562         }
563 #     endif
564 #   endif
565     return(TRUE);
566 }
567
568 /* Set all mark bits for the free list whose first entry is q   */
569 #ifdef __STDC__
570   void GC_set_fl_marks(ptr_t q)
571 #else
572   void GC_set_fl_marks(q)
573   ptr_t q;
574 #endif
575 {
576    ptr_t p;
577    struct hblk * h, * last_h = 0;
578    hdr *hhdr;
579    int word_no;
580
581    for (p = q; p != 0; p = obj_link(p)){
582         h = HBLKPTR(p);
583         if (h != last_h) {
584           last_h = h; 
585           hhdr = HDR(h);
586         }
587         word_no = (((word *)p) - ((word *)h));
588         set_mark_bit_from_hdr(hhdr, word_no);
589    }
590 }
591
592 /* Clear all mark bits for the free list whose first entry is q */
593 /* Decrement GC_mem_found by number of words on free list.      */
594 #ifdef __STDC__
595   void GC_clear_fl_marks(ptr_t q)
596 #else
597   void GC_clear_fl_marks(q)
598   ptr_t q;
599 #endif
600 {
601    ptr_t p;
602    struct hblk * h, * last_h = 0;
603    hdr *hhdr;
604    int word_no;
605
606    for (p = q; p != 0; p = obj_link(p)){
607         h = HBLKPTR(p);
608         if (h != last_h) {
609           last_h = h; 
610           hhdr = HDR(h);
611         }
612         word_no = (((word *)p) - ((word *)h));
613         clear_mark_bit_from_hdr(hhdr, word_no);
614 #       ifdef GATHERSTATS
615             GC_mem_found -= hhdr -> hb_sz;
616 #       endif
617    }
618 }
619
620 /* Finish up a collection.  Assumes lock is held, signals are disabled, */
621 /* but the world is otherwise running.                                  */
622 void GC_finish_collection()
623 {
624 #   ifdef PRINTTIMES
625         CLOCK_TYPE start_time;
626         CLOCK_TYPE finalize_time;
627         CLOCK_TYPE done_time;
628         
629         GET_TIME(start_time);
630         finalize_time = start_time;
631 #   endif
632
633 #   ifdef GATHERSTATS
634         GC_mem_found = 0;
635 #   endif
636 #   if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
637         if (getenv("GC_PRINT_ADDRESS_MAP") != 0) {
638           GC_print_address_map();
639         }
640 #   endif
641     COND_DUMP;
642     if (GC_find_leak) {
643       /* Mark all objects on the free list.  All objects should be */
644       /* marked when we're done.                                   */
645         {
646           register word size;           /* current object size          */
647           int kind;
648           ptr_t q;
649
650           for (kind = 0; kind < GC_n_kinds; kind++) {
651             for (size = 1; size <= MAXOBJSZ; size++) {
652               q = GC_obj_kinds[kind].ok_freelist[size];
653               if (q != 0) GC_set_fl_marks(q);
654             }
655           }
656         }
657         GC_start_reclaim(TRUE);
658           /* The above just checks; it doesn't really reclaim anything. */
659     }
660
661     GC_finalize();
662 #   ifdef STUBBORN_ALLOC
663       GC_clean_changing_list();
664 #   endif
665
666 #   ifdef PRINTTIMES
667       GET_TIME(finalize_time);
668 #   endif
669
670     if (GC_print_back_height) {
671 #     ifdef MAKE_BACK_GRAPH
672         GC_traverse_back_graph();
673 #     else
674 #       ifndef SMALL_CONFIG
675           GC_err_printf0("Back height not available: "
676                          "Rebuild collector with -DMAKE_BACK_GRAPH\n");
677 #       endif
678 #     endif
679     }
680
681     /* Clear free list mark bits, in case they got accidentally marked   */
682     /* (or GC_find_leak is set and they were intentionally marked).      */
683     /* Also subtract memory remaining from GC_mem_found count.           */
684     /* Note that composite objects on free list are cleared.             */
685     /* Thus accidentally marking a free list is not a problem;  only     */
686     /* objects on the list itself will be marked, and that's fixed here. */
687       {
688         register word size;             /* current object size          */
689         register ptr_t q;       /* pointer to current object    */
690         int kind;
691
692         for (kind = 0; kind < GC_n_kinds; kind++) {
693           for (size = 1; size <= MAXOBJSZ; size++) {
694             q = GC_obj_kinds[kind].ok_freelist[size];
695             if (q != 0) GC_clear_fl_marks(q);
696           }
697         }
698       }
699
700
701 #   ifdef PRINTSTATS
702         GC_printf1("Bytes recovered before sweep - f.l. count = %ld\n",
703                   (long)WORDS_TO_BYTES(GC_mem_found));
704 #   endif
705     /* Reconstruct free lists to contain everything not marked */
706         GC_start_reclaim(FALSE);
707         if (GC_is_full_gc)  {
708             GC_used_heap_size_after_full = USED_HEAP_SIZE;
709             GC_need_full_gc = FALSE;
710         } else {
711             GC_need_full_gc =
712                  BYTES_TO_WORDS(USED_HEAP_SIZE - GC_used_heap_size_after_full)
713                  > min_words_allocd();
714         }
715
716 #   ifdef PRINTSTATS
717         GC_printf2(
718                   "Immediately reclaimed %ld bytes in heap of size %lu bytes",
719                   (long)WORDS_TO_BYTES(GC_mem_found),
720                   (unsigned long)GC_heapsize);
721 #       ifdef USE_MUNMAP
722           GC_printf1("(%lu unmapped)", GC_unmapped_bytes);
723 #       endif
724         GC_printf2(
725                 "\n%lu (atomic) + %lu (composite) collectable bytes in use\n",
726                 (unsigned long)WORDS_TO_BYTES(GC_atomic_in_use),
727                 (unsigned long)WORDS_TO_BYTES(GC_composite_in_use));
728 #   endif
729
730       GC_n_attempts = 0;
731       GC_is_full_gc = FALSE;
732     /* Reset or increment counters for next cycle */
733       GC_words_allocd_before_gc += GC_words_allocd;
734       GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
735       GC_words_allocd = 0;
736       GC_words_wasted = 0;
737       GC_mem_freed = 0;
738       GC_finalizer_mem_freed = 0;
739       
740 #   ifdef USE_MUNMAP
741       GC_unmap_old();
742 #   endif
743 #   ifdef PRINTTIMES
744         GET_TIME(done_time);
745         GC_printf2("Finalize + initiate sweep took %lu + %lu msecs\n",
746                    MS_TIME_DIFF(finalize_time,start_time),
747                    MS_TIME_DIFF(done_time,finalize_time));
748 #   endif
749 }
750
751 /* Externally callable routine to invoke full, stop-world collection */
752 # if defined(__STDC__) || defined(__cplusplus)
753     int GC_try_to_collect(GC_stop_func stop_func)
754 # else
755     int GC_try_to_collect(stop_func)
756     GC_stop_func stop_func;
757 # endif
758 {
759     int result;
760     DCL_LOCK_STATE;
761     
762     if (GC_debugging_started) GC_print_all_smashed();
763     GC_INVOKE_FINALIZERS();
764     DISABLE_SIGNALS();
765     LOCK();
766     ENTER_GC();
767     if (!GC_is_initialized) GC_init_inner();
768     /* Minimize junk left in my registers */
769       GC_noop(0,0,0,0,0,0);
770     result = (int)GC_try_to_collect_inner(stop_func);
771     EXIT_GC();
772     UNLOCK();
773     ENABLE_SIGNALS();
774     if(result) {
775         if (GC_debugging_started) GC_print_all_smashed();
776         GC_INVOKE_FINALIZERS();
777     }
778     return(result);
779 }
780
781 void GC_gcollect GC_PROTO(())
782 {
783     (void)GC_try_to_collect(GC_never_stop_func);
784     if (GC_have_errors) GC_print_all_errors();
785 }
786
787 word GC_n_heap_sects = 0;       /* Number of sections currently in heap. */
788
789 /*
790  * Use the chunk of memory starting at p of size bytes as part of the heap.
791  * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
792  */
793 void GC_add_to_heap(p, bytes)
794 struct hblk *p;
795 word bytes;
796 {
797     word words;
798     hdr * phdr;
799     
800     if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
801         ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
802     }
803     phdr = GC_install_header(p);
804     if (0 == phdr) {
805         /* This is extremely unlikely. Can't add it.  This will         */
806         /* almost certainly result in a 0 return from the allocator,    */
807         /* which is entirely appropriate.                               */
808         return;
809     }
810     GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
811     GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
812     GC_n_heap_sects++;
813     words = BYTES_TO_WORDS(bytes);
814     phdr -> hb_sz = words;
815     phdr -> hb_map = (unsigned char *)1;   /* A value != GC_invalid_map */
816     phdr -> hb_flags = 0;
817     GC_freehblk(p);
818     GC_heapsize += bytes;
819     if ((ptr_t)p <= (ptr_t)GC_least_plausible_heap_addr
820         || GC_least_plausible_heap_addr == 0) {
821         GC_least_plausible_heap_addr = (GC_PTR)((ptr_t)p - sizeof(word));
822                 /* Making it a little smaller than necessary prevents   */
823                 /* us from getting a false hit from the variable        */
824                 /* itself.  There's some unintentional reflection       */
825                 /* here.                                                */
826     }
827     if ((ptr_t)p + bytes >= (ptr_t)GC_greatest_plausible_heap_addr) {
828         GC_greatest_plausible_heap_addr = (GC_PTR)((ptr_t)p + bytes);
829     }
830 }
831
832 # if !defined(NO_DEBUGGING)
833 void GC_print_heap_sects()
834 {
835     register unsigned i;
836     
837     GC_printf1("Total heap size: %lu\n", (unsigned long) GC_heapsize);
838     for (i = 0; i < GC_n_heap_sects; i++) {
839         unsigned long start = (unsigned long) GC_heap_sects[i].hs_start;
840         unsigned long len = (unsigned long) GC_heap_sects[i].hs_bytes;
841         struct hblk *h;
842         unsigned nbl = 0;
843         
844         GC_printf3("Section %ld from 0x%lx to 0x%lx ", (unsigned long)i,
845                    start, (unsigned long)(start + len));
846         for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) {
847             if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
848         }
849         GC_printf2("%lu/%lu blacklisted\n", (unsigned long)nbl,
850                    (unsigned long)(len/HBLKSIZE));
851     }
852 }
853 # endif
854
855 GC_PTR GC_least_plausible_heap_addr = (GC_PTR)ONES;
856 GC_PTR GC_greatest_plausible_heap_addr = 0;
857
858 ptr_t GC_max(x,y)
859 ptr_t x, y;
860 {
861     return(x > y? x : y);
862 }
863
864 ptr_t GC_min(x,y)
865 ptr_t x, y;
866 {
867     return(x < y? x : y);
868 }
869
870 # if defined(__STDC__) || defined(__cplusplus)
871     void GC_set_max_heap_size(GC_word n)
872 # else
873     void GC_set_max_heap_size(n)
874     GC_word n;
875 # endif
876 {
877     GC_max_heapsize = n;
878 }
879
880 GC_word GC_max_retries = 0;
881
882 /*
883  * this explicitly increases the size of the heap.  It is used
884  * internally, but may also be invoked from GC_expand_hp by the user.
885  * The argument is in units of HBLKSIZE.
886  * Tiny values of n are rounded up.
887  * Returns FALSE on failure.
888  */
889 GC_bool GC_expand_hp_inner(n)
890 word n;
891 {
892     word bytes;
893     struct hblk * space;
894     word expansion_slop;        /* Number of bytes by which we expect the */
895                                 /* heap to expand soon.                   */
896
897     if (n < MINHINCR) n = MINHINCR;
898     bytes = n * HBLKSIZE;
899     /* Make sure bytes is a multiple of GC_page_size */
900       {
901         word mask = GC_page_size - 1;
902         bytes += mask;
903         bytes &= ~mask;
904       }
905     
906     if (GC_max_heapsize != 0 && GC_heapsize + bytes > GC_max_heapsize) {
907         /* Exceeded self-imposed limit */
908         return(FALSE);
909     }
910     space = GET_MEM(bytes);
911     if( space == 0 ) {
912 #       ifdef CONDPRINT
913           if (GC_print_stats) {
914             GC_printf1("Failed to expand heap by %ld bytes\n",
915                        (unsigned long)bytes);
916           }
917 #       endif
918         return(FALSE);
919     }
920 #   ifdef CONDPRINT
921       if (GC_print_stats) {
922         GC_printf2("Increasing heap size by %lu after %lu allocated bytes\n",
923                    (unsigned long)bytes,
924                    (unsigned long)WORDS_TO_BYTES(GC_words_allocd));
925 #       ifdef UNDEFINED
926           GC_printf1("Root size = %lu\n", GC_root_size);
927           GC_print_block_list(); GC_print_hblkfreelist();
928           GC_printf0("\n");
929 #       endif
930       }
931 #   endif
932     expansion_slop = WORDS_TO_BYTES(min_words_allocd()) + 4*MAXHINCR*HBLKSIZE;
933     if (GC_last_heap_addr == 0 && !((word)space & SIGNB)
934         || GC_last_heap_addr != 0 && GC_last_heap_addr < (ptr_t)space) {
935         /* Assume the heap is growing up */
936         GC_greatest_plausible_heap_addr =
937             (GC_PTR)GC_max((ptr_t)GC_greatest_plausible_heap_addr,
938                            (ptr_t)space + bytes + expansion_slop);
939     } else {
940         /* Heap is growing down */
941         GC_least_plausible_heap_addr =
942             (GC_PTR)GC_min((ptr_t)GC_least_plausible_heap_addr,
943                            (ptr_t)space - expansion_slop);
944     }
945 #   if defined(LARGE_CONFIG)
946       if (((ptr_t)GC_greatest_plausible_heap_addr <= (ptr_t)space + bytes
947            || (ptr_t)GC_least_plausible_heap_addr >= (ptr_t)space)
948           && GC_heapsize > 0) {
949         /* GC_add_to_heap will fix this, but ... */
950         WARN("Too close to address space limit: blacklisting ineffective\n", 0);
951       }
952 #   endif
953     GC_prev_heap_addr = GC_last_heap_addr;
954     GC_last_heap_addr = (ptr_t)space;
955     GC_add_to_heap(space, bytes);
956     /* Force GC before we are likely to allocate past expansion_slop */
957       GC_collect_at_heapsize =
958           GC_heapsize + expansion_slop - 2*MAXHINCR*HBLKSIZE;
959 #     if defined(LARGE_CONFIG)
960         if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
961           GC_collect_at_heapsize = (word)(-1);
962 #     endif
963     return(TRUE);
964 }
965
966 /* Really returns a bool, but it's externally visible, so that's clumsy. */
967 /* Arguments is in bytes.                                               */
968 # if defined(__STDC__) || defined(__cplusplus)
969   int GC_expand_hp(size_t bytes)
970 # else
971   int GC_expand_hp(bytes)
972   size_t bytes;
973 # endif
974 {
975     int result;
976     DCL_LOCK_STATE;
977     
978     DISABLE_SIGNALS();
979     LOCK();
980     if (!GC_is_initialized) GC_init_inner();
981     result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
982     if (result) GC_requested_heapsize += bytes;
983     UNLOCK();
984     ENABLE_SIGNALS();
985     return(result);
986 }
987
988 unsigned GC_fail_count = 0;  
989                         /* How many consecutive GC/expansion failures?  */
990                         /* Reset by GC_allochblk.                       */
991
992 GC_bool GC_collect_or_expand(needed_blocks, ignore_off_page)
993 word needed_blocks;
994 GC_bool ignore_off_page;
995 {
996     if (!GC_incremental && !GC_dont_gc &&
997         (GC_dont_expand && GC_words_allocd > 0 || GC_should_collect())) {
998       GC_gcollect_inner();
999     } else {
1000       word blocks_to_get = GC_heapsize/(HBLKSIZE*GC_free_space_divisor)
1001                            + needed_blocks;
1002       
1003       if (blocks_to_get > MAXHINCR) {
1004           word slop;
1005           
1006           if (ignore_off_page) {
1007               slop = 4;
1008           } else {
1009               slop = 2*divHBLKSZ(BL_LIMIT);
1010               if (slop > needed_blocks) slop = needed_blocks;
1011           }
1012           if (needed_blocks + slop > MAXHINCR) {
1013               blocks_to_get = needed_blocks + slop;
1014           } else {
1015               blocks_to_get = MAXHINCR;
1016           }
1017       }
1018       if (!GC_expand_hp_inner(blocks_to_get)
1019         && !GC_expand_hp_inner(needed_blocks)) {
1020         if (GC_fail_count++ < GC_max_retries) {
1021             WARN("Out of Memory!  Trying to continue ...\n", 0);
1022             GC_gcollect_inner();
1023         } else {
1024 #           if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
1025               WARN("Out of Memory!  Returning NIL!\n", 0);
1026 #           endif
1027             return(FALSE);
1028         }
1029       } else {
1030 #         ifdef CONDPRINT
1031             if (GC_fail_count && GC_print_stats) {
1032               GC_printf0("Memory available again ...\n");
1033             }
1034 #         endif
1035       }
1036     }
1037     return(TRUE);
1038 }
1039
1040 /*
1041  * Make sure the object free list for sz is not empty.
1042  * Return a pointer to the first object on the free list.
1043  * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
1044  * Assumes we hold the allocator lock and signals are disabled.
1045  *
1046  */
1047 ptr_t GC_allocobj(sz, kind)
1048 word sz;
1049 int kind;
1050 {
1051     ptr_t * flh = &(GC_obj_kinds[kind].ok_freelist[sz]);
1052     GC_bool tried_minor = FALSE;
1053     
1054     if (sz == 0) return(0);
1055
1056     while (*flh == 0) {
1057       ENTER_GC();
1058       /* Do our share of marking work */
1059         if(TRUE_INCREMENTAL) GC_collect_a_little_inner(1);
1060       /* Sweep blocks for objects of this size */
1061         GC_continue_reclaim(sz, kind);
1062       EXIT_GC();
1063       if (*flh == 0) {
1064         GC_new_hblk(sz, kind);
1065       }
1066       if (*flh == 0) {
1067         ENTER_GC();
1068         if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED
1069             && ! tried_minor ) {
1070             GC_collect_a_little_inner(1);
1071             tried_minor = TRUE;
1072         } else {
1073           if (!GC_collect_or_expand((word)1,FALSE)) {
1074             EXIT_GC();
1075             return(0);
1076           }
1077         }
1078         EXIT_GC();
1079       }
1080     }
1081     /* Successful allocation; reset failure count.      */
1082     GC_fail_count = 0;
1083     
1084     return(*flh);
1085 }