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