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