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