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