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