OSDN Git Service

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