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