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