1.0.25.33: protect against recursive gcs
[sbcl.git] / src / runtime / gencgc.c
1 /*
2  * GENerational Conservative Garbage Collector for SBCL
3  */
4
5 /*
6  * This software is part of the SBCL system. See the README file for
7  * more information.
8  *
9  * This software is derived from the CMU CL system, which was
10  * written at Carnegie Mellon University and released into the
11  * public domain. The software is in the public domain and is
12  * provided with absolutely no warranty. See the COPYING and CREDITS
13  * files for more information.
14  */
15
16 /*
17  * For a review of garbage collection techniques (e.g. generational
18  * GC) and terminology (e.g. "scavenging") see Paul R. Wilson,
19  * "Uniprocessor Garbage Collection Techniques". As of 20000618, this
20  * had been accepted for _ACM Computing Surveys_ and was available
21  * as a PostScript preprint through
22  *   <http://www.cs.utexas.edu/users/oops/papers.html>
23  * as
24  *   <ftp://ftp.cs.utexas.edu/pub/garbage/bigsurv.ps>.
25  */
26
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <signal.h>
30 #include <errno.h>
31 #include <string.h>
32 #include "sbcl.h"
33 #include "runtime.h"
34 #include "os.h"
35 #include "interr.h"
36 #include "globals.h"
37 #include "interrupt.h"
38 #include "validate.h"
39 #include "lispregs.h"
40 #include "arch.h"
41 #include "gc.h"
42 #include "gc-internal.h"
43 #include "thread.h"
44 #include "pseudo-atomic.h"
45 #include "alloc.h"
46 #include "genesis/vector.h"
47 #include "genesis/weak-pointer.h"
48 #include "genesis/fdefn.h"
49 #include "genesis/simple-fun.h"
50 #include "save.h"
51 #include "genesis/hash-table.h"
52 #include "genesis/instance.h"
53 #include "genesis/layout.h"
54 #include "gencgc.h"
55 #if defined(LUTEX_WIDETAG)
56 #include "pthread-lutex.h"
57 #endif
58
59 /* forward declarations */
60 page_index_t  gc_find_freeish_pages(long *restart_page_ptr, long nbytes,
61                                     int page_type_flag);
62
63 \f
64 /*
65  * GC parameters
66  */
67
68 /* Generations 0-5 are normal collected generations, 6 is only used as
69  * scratch space by the collector, and should never get collected.
70  */
71 enum {
72     HIGHEST_NORMAL_GENERATION = 5,
73     PSEUDO_STATIC_GENERATION,
74     SCRATCH_GENERATION,
75     NUM_GENERATIONS
76 };
77
78 /* Should we use page protection to help avoid the scavenging of pages
79  * that don't have pointers to younger generations? */
80 boolean enable_page_protection = 1;
81
82 /* the minimum size (in bytes) for a large object*/
83 long large_object_size = 4 * PAGE_BYTES;
84
85 \f
86 /*
87  * debugging
88  */
89
90 /* the verbosity level. All non-error messages are disabled at level 0;
91  * and only a few rare messages are printed at level 1. */
92 #ifdef QSHOW
93 boolean gencgc_verbose = 1;
94 #else
95 boolean gencgc_verbose = 0;
96 #endif
97
98 /* FIXME: At some point enable the various error-checking things below
99  * and see what they say. */
100
101 /* We hunt for pointers to old-space, when GCing generations >= verify_gen.
102  * Set verify_gens to HIGHEST_NORMAL_GENERATION + 1 to disable this kind of
103  * check. */
104 generation_index_t verify_gens = HIGHEST_NORMAL_GENERATION + 1;
105
106 /* Should we do a pre-scan verify of generation 0 before it's GCed? */
107 boolean pre_verify_gen_0 = 0;
108
109 /* Should we check for bad pointers after gc_free_heap is called
110  * from Lisp PURIFY? */
111 boolean verify_after_free_heap = 0;
112
113 /* Should we print a note when code objects are found in the dynamic space
114  * during a heap verify? */
115 boolean verify_dynamic_code_check = 0;
116
117 /* Should we check code objects for fixup errors after they are transported? */
118 boolean check_code_fixups = 0;
119
120 /* Should we check that newly allocated regions are zero filled? */
121 boolean gencgc_zero_check = 0;
122
123 /* Should we check that the free space is zero filled? */
124 boolean gencgc_enable_verify_zero_fill = 0;
125
126 /* Should we check that free pages are zero filled during gc_free_heap
127  * called after Lisp PURIFY? */
128 boolean gencgc_zero_check_during_free_heap = 0;
129
130 /* When loading a core, don't do a full scan of the memory for the
131  * memory region boundaries. (Set to true by coreparse.c if the core
132  * contained a pagetable entry).
133  */
134 boolean gencgc_partial_pickup = 0;
135
136 /* If defined, free pages are read-protected to ensure that nothing
137  * accesses them.
138  */
139
140 /* #define READ_PROTECT_FREE_PAGES */
141
142 \f
143 /*
144  * GC structures and variables
145  */
146
147 /* the total bytes allocated. These are seen by Lisp DYNAMIC-USAGE. */
148 unsigned long bytes_allocated = 0;
149 unsigned long auto_gc_trigger = 0;
150
151 /* the source and destination generations. These are set before a GC starts
152  * scavenging. */
153 generation_index_t from_space;
154 generation_index_t new_space;
155
156 /* Set to 1 when in GC */
157 boolean gc_active_p = 0;
158
159 /* should the GC be conservative on stack. If false (only right before
160  * saving a core), don't scan the stack / mark pages dont_move. */
161 static boolean conservative_stack = 1;
162
163 /* An array of page structures is allocated on gc initialization.
164  * This helps quickly map between an address its page structure.
165  * page_table_pages is set from the size of the dynamic space. */
166 page_index_t page_table_pages;
167 struct page *page_table;
168
169 static inline boolean page_allocated_p(page_index_t page) {
170     return (page_table[page].allocated != FREE_PAGE_FLAG);
171 }
172
173 static inline boolean page_no_region_p(page_index_t page) {
174     return !(page_table[page].allocated & OPEN_REGION_PAGE_FLAG);
175 }
176
177 static inline boolean page_allocated_no_region_p(page_index_t page) {
178     return ((page_table[page].allocated & (UNBOXED_PAGE_FLAG | BOXED_PAGE_FLAG))
179             && page_no_region_p(page));
180 }
181
182 static inline boolean page_free_p(page_index_t page) {
183     return (page_table[page].allocated == FREE_PAGE_FLAG);
184 }
185
186 static inline boolean page_boxed_p(page_index_t page) {
187     return (page_table[page].allocated & BOXED_PAGE_FLAG);
188 }
189
190 static inline boolean code_page_p(page_index_t page) {
191     return (page_table[page].allocated & CODE_PAGE_FLAG);
192 }
193
194 static inline boolean page_boxed_no_region_p(page_index_t page) {
195     return page_boxed_p(page) && page_no_region_p(page);
196 }
197
198 static inline boolean page_unboxed_p(page_index_t page) {
199     /* Both flags set == boxed code page */
200     return ((page_table[page].allocated & UNBOXED_PAGE_FLAG)
201             && !page_boxed_p(page));
202 }
203
204 static inline boolean protect_page_p(page_index_t page, generation_index_t generation) {
205     return (page_boxed_no_region_p(page)
206             && (page_table[page].bytes_used != 0)
207             && !page_table[page].dont_move
208             && (page_table[page].gen == generation));
209 }
210
211 /* To map addresses to page structures the address of the first page
212  * is needed. */
213 static void *heap_base = NULL;
214
215 /* Calculate the start address for the given page number. */
216 inline void *
217 page_address(page_index_t page_num)
218 {
219     return (heap_base + (page_num * PAGE_BYTES));
220 }
221
222 /* Calculate the address where the allocation region associated with
223  * the page starts. */
224 static inline void *
225 page_region_start(page_index_t page_index)
226 {
227     return page_address(page_index)-page_table[page_index].region_start_offset;
228 }
229
230 /* Find the page index within the page_table for the given
231  * address. Return -1 on failure. */
232 inline page_index_t
233 find_page_index(void *addr)
234 {
235     if (addr >= heap_base) {
236         page_index_t index = ((pointer_sized_uint_t)addr -
237                               (pointer_sized_uint_t)heap_base) / PAGE_BYTES;
238         if (index < page_table_pages)
239             return (index);
240     }
241     return (-1);
242 }
243
244 static size_t
245 npage_bytes(long npages)
246 {
247     gc_assert(npages>=0);
248     return ((unsigned long)npages)*PAGE_BYTES;
249 }
250
251 /* Check that X is a higher address than Y and return offset from Y to
252  * X in bytes. */
253 static inline
254 size_t void_diff(void *x, void *y)
255 {
256     gc_assert(x >= y);
257     return (pointer_sized_uint_t)x - (pointer_sized_uint_t)y;
258 }
259
260 /* a structure to hold the state of a generation */
261 struct generation {
262
263     /* the first page that gc_alloc() checks on its next call */
264     page_index_t alloc_start_page;
265
266     /* the first page that gc_alloc_unboxed() checks on its next call */
267     page_index_t alloc_unboxed_start_page;
268
269     /* the first page that gc_alloc_large (boxed) considers on its next
270      * call. (Although it always allocates after the boxed_region.) */
271     page_index_t alloc_large_start_page;
272
273     /* the first page that gc_alloc_large (unboxed) considers on its
274      * next call. (Although it always allocates after the
275      * current_unboxed_region.) */
276     page_index_t alloc_large_unboxed_start_page;
277
278     /* the bytes allocated to this generation */
279     unsigned long bytes_allocated;
280
281     /* the number of bytes at which to trigger a GC */
282     unsigned long gc_trigger;
283
284     /* to calculate a new level for gc_trigger */
285     unsigned long bytes_consed_between_gc;
286
287     /* the number of GCs since the last raise */
288     int num_gc;
289
290     /* the average age after which a GC will raise objects to the
291      * next generation */
292     int trigger_age;
293
294     /* the cumulative sum of the bytes allocated to this generation. It is
295      * cleared after a GC on this generations, and update before new
296      * objects are added from a GC of a younger generation. Dividing by
297      * the bytes_allocated will give the average age of the memory in
298      * this generation since its last GC. */
299     unsigned long cum_sum_bytes_allocated;
300
301     /* a minimum average memory age before a GC will occur helps
302      * prevent a GC when a large number of new live objects have been
303      * added, in which case a GC could be a waste of time */
304     double min_av_mem_age;
305
306     /* A linked list of lutex structures in this generation, used for
307      * implementing lutex finalization. */
308 #ifdef LUTEX_WIDETAG
309     struct lutex *lutexes;
310 #else
311     void *lutexes;
312 #endif
313 };
314
315 /* an array of generation structures. There needs to be one more
316  * generation structure than actual generations as the oldest
317  * generation is temporarily raised then lowered. */
318 struct generation generations[NUM_GENERATIONS];
319
320 /* the oldest generation that is will currently be GCed by default.
321  * Valid values are: 0, 1, ... HIGHEST_NORMAL_GENERATION
322  *
323  * The default of HIGHEST_NORMAL_GENERATION enables GC on all generations.
324  *
325  * Setting this to 0 effectively disables the generational nature of
326  * the GC. In some applications generational GC may not be useful
327  * because there are no long-lived objects.
328  *
329  * An intermediate value could be handy after moving long-lived data
330  * into an older generation so an unnecessary GC of this long-lived
331  * data can be avoided. */
332 generation_index_t gencgc_oldest_gen_to_gc = HIGHEST_NORMAL_GENERATION;
333
334 /* The maximum free page in the heap is maintained and used to update
335  * ALLOCATION_POINTER which is used by the room function to limit its
336  * search of the heap. XX Gencgc obviously needs to be better
337  * integrated with the Lisp code. */
338 page_index_t last_free_page;
339 \f
340 #ifdef LISP_FEATURE_SB_THREAD
341 /* This lock is to prevent multiple threads from simultaneously
342  * allocating new regions which overlap each other.  Note that the
343  * majority of GC is single-threaded, but alloc() may be called from
344  * >1 thread at a time and must be thread-safe.  This lock must be
345  * seized before all accesses to generations[] or to parts of
346  * page_table[] that other threads may want to see */
347 static pthread_mutex_t free_pages_lock = PTHREAD_MUTEX_INITIALIZER;
348 /* This lock is used to protect non-thread-local allocation. */
349 static pthread_mutex_t allocation_lock = PTHREAD_MUTEX_INITIALIZER;
350 #endif
351
352 \f
353 /*
354  * miscellaneous heap functions
355  */
356
357 /* Count the number of pages which are write-protected within the
358  * given generation. */
359 static long
360 count_write_protect_generation_pages(generation_index_t generation)
361 {
362     page_index_t i;
363     unsigned long count = 0;
364
365     for (i = 0; i < last_free_page; i++)
366         if (page_allocated_p(i)
367             && (page_table[i].gen == generation)
368             && (page_table[i].write_protected == 1))
369             count++;
370     return count;
371 }
372
373 /* Count the number of pages within the given generation. */
374 static long
375 count_generation_pages(generation_index_t generation)
376 {
377     page_index_t i;
378     long count = 0;
379
380     for (i = 0; i < last_free_page; i++)
381         if (page_allocated_p(i)
382             && (page_table[i].gen == generation))
383             count++;
384     return count;
385 }
386
387 #ifdef QSHOW
388 static long
389 count_dont_move_pages(void)
390 {
391     page_index_t i;
392     long count = 0;
393     for (i = 0; i < last_free_page; i++) {
394         if (page_allocated_p(i)
395             && (page_table[i].dont_move != 0)) {
396             ++count;
397         }
398     }
399     return count;
400 }
401 #endif /* QSHOW */
402
403 /* Work through the pages and add up the number of bytes used for the
404  * given generation. */
405 static unsigned long
406 count_generation_bytes_allocated (generation_index_t gen)
407 {
408     page_index_t i;
409     unsigned long result = 0;
410     for (i = 0; i < last_free_page; i++) {
411         if (page_allocated_p(i)
412             && (page_table[i].gen == gen))
413             result += page_table[i].bytes_used;
414     }
415     return result;
416 }
417
418 /* Return the average age of the memory in a generation. */
419 static double
420 gen_av_mem_age(generation_index_t gen)
421 {
422     if (generations[gen].bytes_allocated == 0)
423         return 0.0;
424
425     return
426         ((double)generations[gen].cum_sum_bytes_allocated)
427         / ((double)generations[gen].bytes_allocated);
428 }
429
430 /* The verbose argument controls how much to print: 0 for normal
431  * level of detail; 1 for debugging. */
432 static void
433 print_generation_stats(int verbose) /* FIXME: should take FILE argument */
434 {
435     generation_index_t i, gens;
436
437 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
438 #define FPU_STATE_SIZE 27
439     int fpu_state[FPU_STATE_SIZE];
440 #elif defined(LISP_FEATURE_PPC)
441 #define FPU_STATE_SIZE 32
442     long long fpu_state[FPU_STATE_SIZE];
443 #endif
444
445     /* This code uses the FP instructions which may be set up for Lisp
446      * so they need to be saved and reset for C. */
447     fpu_save(fpu_state);
448
449     /* highest generation to print */
450     if (verbose)
451         gens = SCRATCH_GENERATION;
452     else
453         gens = PSEUDO_STATIC_GENERATION;
454
455     /* Print the heap stats. */
456     fprintf(stderr,
457             " Gen StaPg UbSta LaSta LUbSt Boxed Unboxed LB   LUB  !move  Alloc  Waste   Trig    WP  GCs Mem-age\n");
458
459     for (i = 0; i < gens; i++) {
460         page_index_t j;
461         long boxed_cnt = 0;
462         long unboxed_cnt = 0;
463         long large_boxed_cnt = 0;
464         long large_unboxed_cnt = 0;
465         long pinned_cnt=0;
466
467         for (j = 0; j < last_free_page; j++)
468             if (page_table[j].gen == i) {
469
470                 /* Count the number of boxed pages within the given
471                  * generation. */
472                 if (page_boxed_p(j)) {
473                     if (page_table[j].large_object)
474                         large_boxed_cnt++;
475                     else
476                         boxed_cnt++;
477                 }
478                 if(page_table[j].dont_move) pinned_cnt++;
479                 /* Count the number of unboxed pages within the given
480                  * generation. */
481                 if (page_unboxed_p(j)) {
482                     if (page_table[j].large_object)
483                         large_unboxed_cnt++;
484                     else
485                         unboxed_cnt++;
486                 }
487             }
488
489         gc_assert(generations[i].bytes_allocated
490                   == count_generation_bytes_allocated(i));
491         fprintf(stderr,
492                 "   %1d: %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %8ld %5ld %8ld %4ld %3d %7.4f\n",
493                 i,
494                 generations[i].alloc_start_page,
495                 generations[i].alloc_unboxed_start_page,
496                 generations[i].alloc_large_start_page,
497                 generations[i].alloc_large_unboxed_start_page,
498                 boxed_cnt,
499                 unboxed_cnt,
500                 large_boxed_cnt,
501                 large_unboxed_cnt,
502                 pinned_cnt,
503                 generations[i].bytes_allocated,
504                 (npage_bytes(count_generation_pages(i))
505                  - generations[i].bytes_allocated),
506                 generations[i].gc_trigger,
507                 count_write_protect_generation_pages(i),
508                 generations[i].num_gc,
509                 gen_av_mem_age(i));
510     }
511     fprintf(stderr,"   Total bytes allocated    = %lu\n", bytes_allocated);
512     fprintf(stderr,"   Dynamic-space-size bytes = %u\n", dynamic_space_size);
513
514     fpu_restore(fpu_state);
515 }
516 \f
517
518 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
519 void fast_bzero(void*, size_t); /* in <arch>-assem.S */
520 #endif
521
522 /* Zero the pages from START to END (inclusive), but use mmap/munmap instead
523  * if zeroing it ourselves, i.e. in practice give the memory back to the
524  * OS. Generally done after a large GC.
525  */
526 void zero_pages_with_mmap(page_index_t start, page_index_t end) {
527     int i;
528     void *addr = page_address(start), *new_addr;
529     size_t length = npage_bytes(1+end-start);
530
531     if (start > end)
532       return;
533
534     os_invalidate(addr, length);
535     new_addr = os_validate(addr, length);
536     if (new_addr == NULL || new_addr != addr) {
537         lose("remap_free_pages: page moved, 0x%08x ==> 0x%08x",
538              start, new_addr);
539     }
540
541     for (i = start; i <= end; i++) {
542         page_table[i].need_to_zero = 0;
543     }
544 }
545
546 /* Zero the pages from START to END (inclusive). Generally done just after
547  * a new region has been allocated.
548  */
549 static void
550 zero_pages(page_index_t start, page_index_t end) {
551     if (start > end)
552       return;
553
554 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
555     fast_bzero(page_address(start), npage_bytes(1+end-start));
556 #else
557     bzero(page_address(start), npage_bytes(1+end-start));
558 #endif
559
560 }
561
562 /* Zero the pages from START to END (inclusive), except for those
563  * pages that are known to already zeroed. Mark all pages in the
564  * ranges as non-zeroed.
565  */
566 static void
567 zero_dirty_pages(page_index_t start, page_index_t end) {
568     page_index_t i;
569
570     for (i = start; i <= end; i++) {
571         if (page_table[i].need_to_zero == 1) {
572             zero_pages(start, end);
573             break;
574         }
575     }
576
577     for (i = start; i <= end; i++) {
578         page_table[i].need_to_zero = 1;
579     }
580 }
581
582
583 /*
584  * To support quick and inline allocation, regions of memory can be
585  * allocated and then allocated from with just a free pointer and a
586  * check against an end address.
587  *
588  * Since objects can be allocated to spaces with different properties
589  * e.g. boxed/unboxed, generation, ages; there may need to be many
590  * allocation regions.
591  *
592  * Each allocation region may start within a partly used page. Many
593  * features of memory use are noted on a page wise basis, e.g. the
594  * generation; so if a region starts within an existing allocated page
595  * it must be consistent with this page.
596  *
597  * During the scavenging of the newspace, objects will be transported
598  * into an allocation region, and pointers updated to point to this
599  * allocation region. It is possible that these pointers will be
600  * scavenged again before the allocation region is closed, e.g. due to
601  * trans_list which jumps all over the place to cleanup the list. It
602  * is important to be able to determine properties of all objects
603  * pointed to when scavenging, e.g to detect pointers to the oldspace.
604  * Thus it's important that the allocation regions have the correct
605  * properties set when allocated, and not just set when closed. The
606  * region allocation routines return regions with the specified
607  * properties, and grab all the pages, setting their properties
608  * appropriately, except that the amount used is not known.
609  *
610  * These regions are used to support quicker allocation using just a
611  * free pointer. The actual space used by the region is not reflected
612  * in the pages tables until it is closed. It can't be scavenged until
613  * closed.
614  *
615  * When finished with the region it should be closed, which will
616  * update the page tables for the actual space used returning unused
617  * space. Further it may be noted in the new regions which is
618  * necessary when scavenging the newspace.
619  *
620  * Large objects may be allocated directly without an allocation
621  * region, the page tables are updated immediately.
622  *
623  * Unboxed objects don't contain pointers to other objects and so
624  * don't need scavenging. Further they can't contain pointers to
625  * younger generations so WP is not needed. By allocating pages to
626  * unboxed objects the whole page never needs scavenging or
627  * write-protecting. */
628
629 /* We are only using two regions at present. Both are for the current
630  * newspace generation. */
631 struct alloc_region boxed_region;
632 struct alloc_region unboxed_region;
633
634 /* The generation currently being allocated to. */
635 static generation_index_t gc_alloc_generation;
636
637 static inline page_index_t
638 generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large)
639 {
640     if (large) {
641         if (UNBOXED_PAGE_FLAG == page_type_flag) {
642             return generations[generation].alloc_large_unboxed_start_page;
643         } else if (BOXED_PAGE_FLAG & page_type_flag) {
644             /* Both code and data. */
645             return generations[generation].alloc_large_start_page;
646         } else {
647             lose("bad page type flag: %d", page_type_flag);
648         }
649     } else {
650         if (UNBOXED_PAGE_FLAG == page_type_flag) {
651             return generations[generation].alloc_unboxed_start_page;
652         } else if (BOXED_PAGE_FLAG & page_type_flag) {
653             /* Both code and data. */
654             return generations[generation].alloc_start_page;
655         } else {
656             lose("bad page_type_flag: %d", page_type_flag);
657         }
658     }
659 }
660
661 static inline void
662 set_generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large,
663                                 page_index_t page)
664 {
665     if (large) {
666         if (UNBOXED_PAGE_FLAG == page_type_flag) {
667             generations[generation].alloc_large_unboxed_start_page = page;
668         } else if (BOXED_PAGE_FLAG & page_type_flag) {
669             /* Both code and data. */
670             generations[generation].alloc_large_start_page = page;
671         } else {
672             lose("bad page type flag: %d", page_type_flag);
673         }
674     } else {
675         if (UNBOXED_PAGE_FLAG == page_type_flag) {
676             generations[generation].alloc_unboxed_start_page = page;
677         } else if (BOXED_PAGE_FLAG & page_type_flag) {
678             /* Both code and data. */
679             generations[generation].alloc_start_page = page;
680         } else {
681             lose("bad page type flag: %d", page_type_flag);
682         }
683     }
684 }
685
686 /* Find a new region with room for at least the given number of bytes.
687  *
688  * It starts looking at the current generation's alloc_start_page. So
689  * may pick up from the previous region if there is enough space. This
690  * keeps the allocation contiguous when scavenging the newspace.
691  *
692  * The alloc_region should have been closed by a call to
693  * gc_alloc_update_page_tables(), and will thus be in an empty state.
694  *
695  * To assist the scavenging functions write-protected pages are not
696  * used. Free pages should not be write-protected.
697  *
698  * It is critical to the conservative GC that the start of regions be
699  * known. To help achieve this only small regions are allocated at a
700  * time.
701  *
702  * During scavenging, pointers may be found to within the current
703  * region and the page generation must be set so that pointers to the
704  * from space can be recognized. Therefore the generation of pages in
705  * the region are set to gc_alloc_generation. To prevent another
706  * allocation call using the same pages, all the pages in the region
707  * are allocated, although they will initially be empty.
708  */
709 static void
710 gc_alloc_new_region(long nbytes, int page_type_flag, struct alloc_region *alloc_region)
711 {
712     page_index_t first_page;
713     page_index_t last_page;
714     unsigned long bytes_found;
715     page_index_t i;
716     int ret;
717
718     /*
719     FSHOW((stderr,
720            "/alloc_new_region for %d bytes from gen %d\n",
721            nbytes, gc_alloc_generation));
722     */
723
724     /* Check that the region is in a reset state. */
725     gc_assert((alloc_region->first_page == 0)
726               && (alloc_region->last_page == -1)
727               && (alloc_region->free_pointer == alloc_region->end_addr));
728     ret = thread_mutex_lock(&free_pages_lock);
729     gc_assert(ret == 0);
730     first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0);
731     last_page=gc_find_freeish_pages(&first_page, nbytes, page_type_flag);
732     bytes_found=(PAGE_BYTES - page_table[first_page].bytes_used)
733             + npage_bytes(last_page-first_page);
734
735     /* Set up the alloc_region. */
736     alloc_region->first_page = first_page;
737     alloc_region->last_page = last_page;
738     alloc_region->start_addr = page_table[first_page].bytes_used
739         + page_address(first_page);
740     alloc_region->free_pointer = alloc_region->start_addr;
741     alloc_region->end_addr = alloc_region->start_addr + bytes_found;
742
743     /* Set up the pages. */
744
745     /* The first page may have already been in use. */
746     if (page_table[first_page].bytes_used == 0) {
747         page_table[first_page].allocated = page_type_flag;
748         page_table[first_page].gen = gc_alloc_generation;
749         page_table[first_page].large_object = 0;
750         page_table[first_page].region_start_offset = 0;
751     }
752
753     gc_assert(page_table[first_page].allocated == page_type_flag);
754     page_table[first_page].allocated |= OPEN_REGION_PAGE_FLAG;
755
756     gc_assert(page_table[first_page].gen == gc_alloc_generation);
757     gc_assert(page_table[first_page].large_object == 0);
758
759     for (i = first_page+1; i <= last_page; i++) {
760         page_table[i].allocated = page_type_flag;
761         page_table[i].gen = gc_alloc_generation;
762         page_table[i].large_object = 0;
763         /* This may not be necessary for unboxed regions (think it was
764          * broken before!) */
765         page_table[i].region_start_offset =
766             void_diff(page_address(i),alloc_region->start_addr);
767         page_table[i].allocated |= OPEN_REGION_PAGE_FLAG ;
768     }
769     /* Bump up last_free_page. */
770     if (last_page+1 > last_free_page) {
771         last_free_page = last_page+1;
772         /* do we only want to call this on special occasions? like for
773          * boxed_region? */
774         set_alloc_pointer((lispobj)page_address(last_free_page));
775     }
776     ret = thread_mutex_unlock(&free_pages_lock);
777     gc_assert(ret == 0);
778
779 #ifdef READ_PROTECT_FREE_PAGES
780     os_protect(page_address(first_page),
781                npage_bytes(1+last_page-first_page),
782                OS_VM_PROT_ALL);
783 #endif
784
785     /* If the first page was only partial, don't check whether it's
786      * zeroed (it won't be) and don't zero it (since the parts that
787      * we're interested in are guaranteed to be zeroed).
788      */
789     if (page_table[first_page].bytes_used) {
790         first_page++;
791     }
792
793     zero_dirty_pages(first_page, last_page);
794
795     /* we can do this after releasing free_pages_lock */
796     if (gencgc_zero_check) {
797         long *p;
798         for (p = (long *)alloc_region->start_addr;
799              p < (long *)alloc_region->end_addr; p++) {
800             if (*p != 0) {
801                 /* KLUDGE: It would be nice to use %lx and explicit casts
802                  * (long) in code like this, so that it is less likely to
803                  * break randomly when running on a machine with different
804                  * word sizes. -- WHN 19991129 */
805                 lose("The new region at %x is not zero (start=%p, end=%p).\n",
806                      p, alloc_region->start_addr, alloc_region->end_addr);
807             }
808         }
809     }
810 }
811
812 /* If the record_new_objects flag is 2 then all new regions created
813  * are recorded.
814  *
815  * If it's 1 then then it is only recorded if the first page of the
816  * current region is <= new_areas_ignore_page. This helps avoid
817  * unnecessary recording when doing full scavenge pass.
818  *
819  * The new_object structure holds the page, byte offset, and size of
820  * new regions of objects. Each new area is placed in the array of
821  * these structures pointer to by new_areas. new_areas_index holds the
822  * offset into new_areas.
823  *
824  * If new_area overflows NUM_NEW_AREAS then it stops adding them. The
825  * later code must detect this and handle it, probably by doing a full
826  * scavenge of a generation. */
827 #define NUM_NEW_AREAS 512
828 static int record_new_objects = 0;
829 static page_index_t new_areas_ignore_page;
830 struct new_area {
831     page_index_t page;
832     size_t offset;
833     size_t size;
834 };
835 static struct new_area (*new_areas)[];
836 static long new_areas_index;
837 long max_new_areas;
838
839 /* Add a new area to new_areas. */
840 static void
841 add_new_area(page_index_t first_page, size_t offset, size_t size)
842 {
843     unsigned long new_area_start,c;
844     long i;
845
846     /* Ignore if full. */
847     if (new_areas_index >= NUM_NEW_AREAS)
848         return;
849
850     switch (record_new_objects) {
851     case 0:
852         return;
853     case 1:
854         if (first_page > new_areas_ignore_page)
855             return;
856         break;
857     case 2:
858         break;
859     default:
860         gc_abort();
861     }
862
863     new_area_start = npage_bytes(first_page) + offset;
864
865     /* Search backwards for a prior area that this follows from. If
866        found this will save adding a new area. */
867     for (i = new_areas_index-1, c = 0; (i >= 0) && (c < 8); i--, c++) {
868         unsigned long area_end =
869             npage_bytes((*new_areas)[i].page)
870             + (*new_areas)[i].offset
871             + (*new_areas)[i].size;
872         /*FSHOW((stderr,
873                "/add_new_area S1 %d %d %d %d\n",
874                i, c, new_area_start, area_end));*/
875         if (new_area_start == area_end) {
876             /*FSHOW((stderr,
877                    "/adding to [%d] %d %d %d with %d %d %d:\n",
878                    i,
879                    (*new_areas)[i].page,
880                    (*new_areas)[i].offset,
881                    (*new_areas)[i].size,
882                    first_page,
883                    offset,
884                     size);*/
885             (*new_areas)[i].size += size;
886             return;
887         }
888     }
889
890     (*new_areas)[new_areas_index].page = first_page;
891     (*new_areas)[new_areas_index].offset = offset;
892     (*new_areas)[new_areas_index].size = size;
893     /*FSHOW((stderr,
894            "/new_area %d page %d offset %d size %d\n",
895            new_areas_index, first_page, offset, size));*/
896     new_areas_index++;
897
898     /* Note the max new_areas used. */
899     if (new_areas_index > max_new_areas)
900         max_new_areas = new_areas_index;
901 }
902
903 /* Update the tables for the alloc_region. The region may be added to
904  * the new_areas.
905  *
906  * When done the alloc_region is set up so that the next quick alloc
907  * will fail safely and thus a new region will be allocated. Further
908  * it is safe to try to re-update the page table of this reset
909  * alloc_region. */
910 void
911 gc_alloc_update_page_tables(int page_type_flag, struct alloc_region *alloc_region)
912 {
913     int more;
914     page_index_t first_page;
915     page_index_t next_page;
916     unsigned long bytes_used;
917     unsigned long orig_first_page_bytes_used;
918     unsigned long region_size;
919     unsigned long byte_cnt;
920     int ret;
921
922
923     first_page = alloc_region->first_page;
924
925     /* Catch an unused alloc_region. */
926     if ((first_page == 0) && (alloc_region->last_page == -1))
927         return;
928
929     next_page = first_page+1;
930
931     ret = thread_mutex_lock(&free_pages_lock);
932     gc_assert(ret == 0);
933     if (alloc_region->free_pointer != alloc_region->start_addr) {
934         /* some bytes were allocated in the region */
935         orig_first_page_bytes_used = page_table[first_page].bytes_used;
936
937         gc_assert(alloc_region->start_addr ==
938                   (page_address(first_page)
939                    + page_table[first_page].bytes_used));
940
941         /* All the pages used need to be updated */
942
943         /* Update the first page. */
944
945         /* If the page was free then set up the gen, and
946          * region_start_offset. */
947         if (page_table[first_page].bytes_used == 0)
948             gc_assert(page_table[first_page].region_start_offset == 0);
949         page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
950
951         gc_assert(page_table[first_page].allocated & page_type_flag);
952         gc_assert(page_table[first_page].gen == gc_alloc_generation);
953         gc_assert(page_table[first_page].large_object == 0);
954
955         byte_cnt = 0;
956
957         /* Calculate the number of bytes used in this page. This is not
958          * always the number of new bytes, unless it was free. */
959         more = 0;
960         if ((bytes_used = void_diff(alloc_region->free_pointer,
961                                     page_address(first_page)))
962             >PAGE_BYTES) {
963             bytes_used = PAGE_BYTES;
964             more = 1;
965         }
966         page_table[first_page].bytes_used = bytes_used;
967         byte_cnt += bytes_used;
968
969
970         /* All the rest of the pages should be free. We need to set
971          * their region_start_offset pointer to the start of the
972          * region, and set the bytes_used. */
973         while (more) {
974             page_table[next_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
975             gc_assert(page_table[next_page].allocated & page_type_flag);
976             gc_assert(page_table[next_page].bytes_used == 0);
977             gc_assert(page_table[next_page].gen == gc_alloc_generation);
978             gc_assert(page_table[next_page].large_object == 0);
979
980             gc_assert(page_table[next_page].region_start_offset ==
981                       void_diff(page_address(next_page),
982                                 alloc_region->start_addr));
983
984             /* Calculate the number of bytes used in this page. */
985             more = 0;
986             if ((bytes_used = void_diff(alloc_region->free_pointer,
987                                         page_address(next_page)))>PAGE_BYTES) {
988                 bytes_used = PAGE_BYTES;
989                 more = 1;
990             }
991             page_table[next_page].bytes_used = bytes_used;
992             byte_cnt += bytes_used;
993
994             next_page++;
995         }
996
997         region_size = void_diff(alloc_region->free_pointer,
998                                 alloc_region->start_addr);
999         bytes_allocated += region_size;
1000         generations[gc_alloc_generation].bytes_allocated += region_size;
1001
1002         gc_assert((byte_cnt- orig_first_page_bytes_used) == region_size);
1003
1004         /* Set the generations alloc restart page to the last page of
1005          * the region. */
1006         set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0, next_page-1);
1007
1008         /* Add the region to the new_areas if requested. */
1009         if (BOXED_PAGE_FLAG & page_type_flag)
1010             add_new_area(first_page,orig_first_page_bytes_used, region_size);
1011
1012         /*
1013         FSHOW((stderr,
1014                "/gc_alloc_update_page_tables update %d bytes to gen %d\n",
1015                region_size,
1016                gc_alloc_generation));
1017         */
1018     } else {
1019         /* There are no bytes allocated. Unallocate the first_page if
1020          * there are 0 bytes_used. */
1021         page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1022         if (page_table[first_page].bytes_used == 0)
1023             page_table[first_page].allocated = FREE_PAGE_FLAG;
1024     }
1025
1026     /* Unallocate any unused pages. */
1027     while (next_page <= alloc_region->last_page) {
1028         gc_assert(page_table[next_page].bytes_used == 0);
1029         page_table[next_page].allocated = FREE_PAGE_FLAG;
1030         next_page++;
1031     }
1032     ret = thread_mutex_unlock(&free_pages_lock);
1033     gc_assert(ret == 0);
1034
1035     /* alloc_region is per-thread, we're ok to do this unlocked */
1036     gc_set_region_empty(alloc_region);
1037 }
1038
1039 static inline void *gc_quick_alloc(long nbytes);
1040
1041 /* Allocate a possibly large object. */
1042 void *
1043 gc_alloc_large(long nbytes, int page_type_flag, struct alloc_region *alloc_region)
1044 {
1045     page_index_t first_page;
1046     page_index_t last_page;
1047     int orig_first_page_bytes_used;
1048     long byte_cnt;
1049     int more;
1050     unsigned long bytes_used;
1051     page_index_t next_page;
1052     int ret;
1053
1054     ret = thread_mutex_lock(&free_pages_lock);
1055     gc_assert(ret == 0);
1056
1057     first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1);
1058     if (first_page <= alloc_region->last_page) {
1059         first_page = alloc_region->last_page+1;
1060     }
1061
1062     last_page=gc_find_freeish_pages(&first_page,nbytes, page_type_flag);
1063
1064     gc_assert(first_page > alloc_region->last_page);
1065
1066     set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1, last_page);
1067
1068     /* Set up the pages. */
1069     orig_first_page_bytes_used = page_table[first_page].bytes_used;
1070
1071     /* If the first page was free then set up the gen, and
1072      * region_start_offset. */
1073     if (page_table[first_page].bytes_used == 0) {
1074         page_table[first_page].allocated = page_type_flag;
1075         page_table[first_page].gen = gc_alloc_generation;
1076         page_table[first_page].region_start_offset = 0;
1077         page_table[first_page].large_object = 1;
1078     }
1079
1080     gc_assert(page_table[first_page].allocated == page_type_flag);
1081     gc_assert(page_table[first_page].gen == gc_alloc_generation);
1082     gc_assert(page_table[first_page].large_object == 1);
1083
1084     byte_cnt = 0;
1085
1086     /* Calc. the number of bytes used in this page. This is not
1087      * always the number of new bytes, unless it was free. */
1088     more = 0;
1089     if ((bytes_used = nbytes+orig_first_page_bytes_used) > PAGE_BYTES) {
1090         bytes_used = PAGE_BYTES;
1091         more = 1;
1092     }
1093     page_table[first_page].bytes_used = bytes_used;
1094     byte_cnt += bytes_used;
1095
1096     next_page = first_page+1;
1097
1098     /* All the rest of the pages should be free. We need to set their
1099      * region_start_offset pointer to the start of the region, and set
1100      * the bytes_used. */
1101     while (more) {
1102         gc_assert(page_free_p(next_page));
1103         gc_assert(page_table[next_page].bytes_used == 0);
1104         page_table[next_page].allocated = page_type_flag;
1105         page_table[next_page].gen = gc_alloc_generation;
1106         page_table[next_page].large_object = 1;
1107
1108         page_table[next_page].region_start_offset =
1109             npage_bytes(next_page-first_page) - orig_first_page_bytes_used;
1110
1111         /* Calculate the number of bytes used in this page. */
1112         more = 0;
1113         bytes_used=(nbytes+orig_first_page_bytes_used)-byte_cnt;
1114         if (bytes_used > PAGE_BYTES) {
1115             bytes_used = PAGE_BYTES;
1116             more = 1;
1117         }
1118         page_table[next_page].bytes_used = bytes_used;
1119         page_table[next_page].write_protected=0;
1120         page_table[next_page].dont_move=0;
1121         byte_cnt += bytes_used;
1122         next_page++;
1123     }
1124
1125     gc_assert((byte_cnt-orig_first_page_bytes_used) == nbytes);
1126
1127     bytes_allocated += nbytes;
1128     generations[gc_alloc_generation].bytes_allocated += nbytes;
1129
1130     /* Add the region to the new_areas if requested. */
1131     if (BOXED_PAGE_FLAG & page_type_flag)
1132         add_new_area(first_page,orig_first_page_bytes_used,nbytes);
1133
1134     /* Bump up last_free_page */
1135     if (last_page+1 > last_free_page) {
1136         last_free_page = last_page+1;
1137         set_alloc_pointer((lispobj)(page_address(last_free_page)));
1138     }
1139     ret = thread_mutex_unlock(&free_pages_lock);
1140     gc_assert(ret == 0);
1141
1142 #ifdef READ_PROTECT_FREE_PAGES
1143     os_protect(page_address(first_page),
1144                npage_bytes(1+last_page-first_page),
1145                OS_VM_PROT_ALL);
1146 #endif
1147
1148     zero_dirty_pages(first_page, last_page);
1149
1150     return page_address(first_page);
1151 }
1152
1153 static page_index_t gencgc_alloc_start_page = -1;
1154
1155 void
1156 gc_heap_exhausted_error_or_lose (long available, long requested)
1157 {
1158     struct thread *thread = arch_os_get_current_thread();
1159     /* Write basic information before doing anything else: if we don't
1160      * call to lisp this is a must, and even if we do there is always
1161      * the danger that we bounce back here before the error has been
1162      * handled, or indeed even printed.
1163      */
1164     fprintf(stderr, "Heap exhausted during %s: %ld bytes available, %ld requested.\n",
1165             gc_active_p ? "garbage collection" : "allocation",
1166             available, requested);
1167     if (gc_active_p || (available == 0)) {
1168         /* If we are in GC, or totally out of memory there is no way
1169          * to sanely transfer control to the lisp-side of things.
1170          */
1171         print_generation_stats(1);
1172         fprintf(stderr, "GC control variables:\n");
1173         fprintf(stderr, "          *GC-INHIBIT* = %s\n          *GC-PENDING* = %s\n",
1174                 SymbolValue(GC_INHIBIT,thread)==NIL ? "false" : "true",
1175                 (SymbolValue(GC_PENDING, thread) == T) ?
1176                 "true" : ((SymbolValue(GC_PENDING, thread) == NIL) ?
1177                   "false" : "in progress"));
1178 #ifdef LISP_FEATURE_SB_THREAD
1179         fprintf(stderr, " *STOP-FOR-GC-PENDING* = %s\n",
1180                 SymbolValue(STOP_FOR_GC_PENDING,thread)==NIL ? "false" : "true");
1181 #endif
1182         lose("Heap exhausted, game over.");
1183     }
1184     else {
1185         /* FIXME: assert free_pages_lock held */
1186         (void)thread_mutex_unlock(&free_pages_lock);
1187         gc_assert(get_pseudo_atomic_atomic(thread));
1188         clear_pseudo_atomic_atomic(thread);
1189         if (get_pseudo_atomic_interrupted(thread))
1190             do_pending_interrupt();
1191         /* Another issue is that signalling HEAP-EXHAUSTED error leads
1192          * to running user code at arbitrary places, even in a
1193          * WITHOUT-INTERRUPTS which may lead to a deadlock without
1194          * running out of the heap. So at this point all bets are
1195          * off. */
1196         if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL)
1197             corruption_warning_and_maybe_lose
1198                 ("Signalling HEAP-EXHAUSTED in a WITHOUT-INTERRUPTS.");
1199         funcall2(StaticSymbolFunction(HEAP_EXHAUSTED_ERROR),
1200                  alloc_number(available), alloc_number(requested));
1201         lose("HEAP-EXHAUSTED-ERROR fell through");
1202     }
1203 }
1204
1205 page_index_t
1206 gc_find_freeish_pages(page_index_t *restart_page_ptr, long nbytes,
1207                       int page_type_flag)
1208 {
1209     page_index_t first_page, last_page;
1210     page_index_t restart_page = *restart_page_ptr;
1211     long bytes_found = 0;
1212     long most_bytes_found = 0;
1213     /* FIXME: assert(free_pages_lock is held); */
1214
1215     /* Toggled by gc_and_save for heap compaction, normally -1. */
1216     if (gencgc_alloc_start_page != -1) {
1217         restart_page = gencgc_alloc_start_page;
1218     }
1219
1220     gc_assert(nbytes>=0);
1221     if (((unsigned long)nbytes)>=PAGE_BYTES) {
1222         /* Search for a contiguous free space of at least nbytes,
1223          * aligned on a page boundary. The page-alignment is strictly
1224          * speaking needed only for objects at least large_object_size
1225          * bytes in size. */
1226         do {
1227             first_page = restart_page;
1228             while ((first_page < page_table_pages) &&
1229                    page_allocated_p(first_page))
1230                 first_page++;
1231
1232             last_page = first_page;
1233             bytes_found = PAGE_BYTES;
1234             while ((bytes_found < nbytes) &&
1235                    (last_page < (page_table_pages-1)) &&
1236                    page_free_p(last_page+1)) {
1237                 last_page++;
1238                 bytes_found += PAGE_BYTES;
1239                 gc_assert(0 == page_table[last_page].bytes_used);
1240                 gc_assert(0 == page_table[last_page].write_protected);
1241             }
1242             if (bytes_found > most_bytes_found)
1243                 most_bytes_found = bytes_found;
1244             restart_page = last_page + 1;
1245         } while ((restart_page < page_table_pages) && (bytes_found < nbytes));
1246
1247     } else {
1248         /* Search for a page with at least nbytes of space. We prefer
1249          * not to split small objects on multiple pages, to reduce the
1250          * number of contiguous allocation regions spaning multiple
1251          * pages: this helps avoid excessive conservativism. */
1252         first_page = restart_page;
1253         while (first_page < page_table_pages) {
1254             if (page_free_p(first_page))
1255                 {
1256                     gc_assert(0 == page_table[first_page].bytes_used);
1257                     bytes_found = PAGE_BYTES;
1258                     break;
1259                 }
1260             else if ((page_table[first_page].allocated == page_type_flag) &&
1261                      (page_table[first_page].large_object == 0) &&
1262                      (page_table[first_page].gen == gc_alloc_generation) &&
1263                      (page_table[first_page].write_protected == 0) &&
1264                      (page_table[first_page].dont_move == 0))
1265                 {
1266                     bytes_found = PAGE_BYTES
1267                         - page_table[first_page].bytes_used;
1268                     if (bytes_found > most_bytes_found)
1269                         most_bytes_found = bytes_found;
1270                     if (bytes_found >= nbytes)
1271                         break;
1272                 }
1273             first_page++;
1274         }
1275         last_page = first_page;
1276         restart_page = first_page + 1;
1277     }
1278
1279     /* Check for a failure */
1280     if (bytes_found < nbytes) {
1281         gc_assert(restart_page >= page_table_pages);
1282         gc_heap_exhausted_error_or_lose(most_bytes_found, nbytes);
1283     }
1284
1285     gc_assert(page_table[first_page].write_protected == 0);
1286
1287     *restart_page_ptr = first_page;
1288     return last_page;
1289 }
1290
1291 /* Allocate bytes.  All the rest of the special-purpose allocation
1292  * functions will eventually call this  */
1293
1294 void *
1295 gc_alloc_with_region(long nbytes,int page_type_flag, struct alloc_region *my_region,
1296                      int quick_p)
1297 {
1298     void *new_free_pointer;
1299
1300     if (nbytes>=large_object_size)
1301         return gc_alloc_large(nbytes, page_type_flag, my_region);
1302
1303     /* Check whether there is room in the current alloc region. */
1304     new_free_pointer = my_region->free_pointer + nbytes;
1305
1306     /* fprintf(stderr, "alloc %d bytes from %p to %p\n", nbytes,
1307        my_region->free_pointer, new_free_pointer); */
1308
1309     if (new_free_pointer <= my_region->end_addr) {
1310         /* If so then allocate from the current alloc region. */
1311         void *new_obj = my_region->free_pointer;
1312         my_region->free_pointer = new_free_pointer;
1313
1314         /* Unless a `quick' alloc was requested, check whether the
1315            alloc region is almost empty. */
1316         if (!quick_p &&
1317             void_diff(my_region->end_addr,my_region->free_pointer) <= 32) {
1318             /* If so, finished with the current region. */
1319             gc_alloc_update_page_tables(page_type_flag, my_region);
1320             /* Set up a new region. */
1321             gc_alloc_new_region(32 /*bytes*/, page_type_flag, my_region);
1322         }
1323
1324         return((void *)new_obj);
1325     }
1326
1327     /* Else not enough free space in the current region: retry with a
1328      * new region. */
1329
1330     gc_alloc_update_page_tables(page_type_flag, my_region);
1331     gc_alloc_new_region(nbytes, page_type_flag, my_region);
1332     return gc_alloc_with_region(nbytes, page_type_flag, my_region,0);
1333 }
1334
1335 /* these are only used during GC: all allocation from the mutator calls
1336  * alloc() -> gc_alloc_with_region() with the appropriate per-thread
1337  * region */
1338
1339 static inline void *
1340 gc_quick_alloc(long nbytes)
1341 {
1342     return gc_general_alloc(nbytes, BOXED_PAGE_FLAG, ALLOC_QUICK);
1343 }
1344
1345 static inline void *
1346 gc_quick_alloc_large(long nbytes)
1347 {
1348     return gc_general_alloc(nbytes, BOXED_PAGE_FLAG ,ALLOC_QUICK);
1349 }
1350
1351 static inline void *
1352 gc_alloc_unboxed(long nbytes)
1353 {
1354     return gc_general_alloc(nbytes, UNBOXED_PAGE_FLAG, 0);
1355 }
1356
1357 static inline void *
1358 gc_quick_alloc_unboxed(long nbytes)
1359 {
1360     return gc_general_alloc(nbytes, UNBOXED_PAGE_FLAG, ALLOC_QUICK);
1361 }
1362
1363 static inline void *
1364 gc_quick_alloc_large_unboxed(long nbytes)
1365 {
1366     return gc_general_alloc(nbytes, UNBOXED_PAGE_FLAG, ALLOC_QUICK);
1367 }
1368 \f
1369
1370 /* Copy a large boxed object. If the object is in a large object
1371  * region then it is simply promoted, else it is copied. If it's large
1372  * enough then it's copied to a large object region.
1373  *
1374  * Vectors may have shrunk. If the object is not copied the space
1375  * needs to be reclaimed, and the page_tables corrected. */
1376 lispobj
1377 copy_large_object(lispobj object, long nwords)
1378 {
1379     int tag;
1380     lispobj *new;
1381     page_index_t first_page;
1382
1383     gc_assert(is_lisp_pointer(object));
1384     gc_assert(from_space_p(object));
1385     gc_assert((nwords & 0x01) == 0);
1386
1387
1388     /* Check whether it's in a large object region. */
1389     first_page = find_page_index((void *)object);
1390     gc_assert(first_page >= 0);
1391
1392     if (page_table[first_page].large_object) {
1393
1394         /* Promote the object. */
1395
1396         unsigned long remaining_bytes;
1397         page_index_t next_page;
1398         unsigned long bytes_freed;
1399         unsigned long old_bytes_used;
1400
1401         /* Note: Any page write-protection must be removed, else a
1402          * later scavenge_newspace may incorrectly not scavenge these
1403          * pages. This would not be necessary if they are added to the
1404          * new areas, but let's do it for them all (they'll probably
1405          * be written anyway?). */
1406
1407         gc_assert(page_table[first_page].region_start_offset == 0);
1408
1409         next_page = first_page;
1410         remaining_bytes = nwords*N_WORD_BYTES;
1411         while (remaining_bytes > PAGE_BYTES) {
1412             gc_assert(page_table[next_page].gen == from_space);
1413             gc_assert(page_boxed_p(next_page));
1414             gc_assert(page_table[next_page].large_object);
1415             gc_assert(page_table[next_page].region_start_offset ==
1416                       npage_bytes(next_page-first_page));
1417             gc_assert(page_table[next_page].bytes_used == PAGE_BYTES);
1418
1419             page_table[next_page].gen = new_space;
1420
1421             /* Remove any write-protection. We should be able to rely
1422              * on the write-protect flag to avoid redundant calls. */
1423             if (page_table[next_page].write_protected) {
1424                 os_protect(page_address(next_page), PAGE_BYTES, OS_VM_PROT_ALL);
1425                 page_table[next_page].write_protected = 0;
1426             }
1427             remaining_bytes -= PAGE_BYTES;
1428             next_page++;
1429         }
1430
1431         /* Now only one page remains, but the object may have shrunk
1432          * so there may be more unused pages which will be freed. */
1433
1434         /* The object may have shrunk but shouldn't have grown. */
1435         gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1436
1437         page_table[next_page].gen = new_space;
1438         gc_assert(page_boxed_p(next_page));
1439
1440         /* Adjust the bytes_used. */
1441         old_bytes_used = page_table[next_page].bytes_used;
1442         page_table[next_page].bytes_used = remaining_bytes;
1443
1444         bytes_freed = old_bytes_used - remaining_bytes;
1445
1446         /* Free any remaining pages; needs care. */
1447         next_page++;
1448         while ((old_bytes_used == PAGE_BYTES) &&
1449                (page_table[next_page].gen == from_space) &&
1450                page_boxed_p(next_page) &&
1451                page_table[next_page].large_object &&
1452                (page_table[next_page].region_start_offset ==
1453                 npage_bytes(next_page - first_page))) {
1454             /* Checks out OK, free the page. Don't need to bother zeroing
1455              * pages as this should have been done before shrinking the
1456              * object. These pages shouldn't be write-protected as they
1457              * should be zero filled. */
1458             gc_assert(page_table[next_page].write_protected == 0);
1459
1460             old_bytes_used = page_table[next_page].bytes_used;
1461             page_table[next_page].allocated = FREE_PAGE_FLAG;
1462             page_table[next_page].bytes_used = 0;
1463             bytes_freed += old_bytes_used;
1464             next_page++;
1465         }
1466
1467         generations[from_space].bytes_allocated -= N_WORD_BYTES*nwords
1468             + bytes_freed;
1469         generations[new_space].bytes_allocated += N_WORD_BYTES*nwords;
1470         bytes_allocated -= bytes_freed;
1471
1472         /* Add the region to the new_areas if requested. */
1473         add_new_area(first_page,0,nwords*N_WORD_BYTES);
1474
1475         return(object);
1476     } else {
1477         /* Get tag of object. */
1478         tag = lowtag_of(object);
1479
1480         /* Allocate space. */
1481         new = gc_quick_alloc_large(nwords*N_WORD_BYTES);
1482
1483         memcpy(new,native_pointer(object),nwords*N_WORD_BYTES);
1484
1485         /* Return Lisp pointer of new object. */
1486         return ((lispobj) new) | tag;
1487     }
1488 }
1489
1490 /* to copy unboxed objects */
1491 lispobj
1492 copy_unboxed_object(lispobj object, long nwords)
1493 {
1494     long tag;
1495     lispobj *new;
1496
1497     gc_assert(is_lisp_pointer(object));
1498     gc_assert(from_space_p(object));
1499     gc_assert((nwords & 0x01) == 0);
1500
1501     /* Get tag of object. */
1502     tag = lowtag_of(object);
1503
1504     /* Allocate space. */
1505     new = gc_quick_alloc_unboxed(nwords*N_WORD_BYTES);
1506
1507     memcpy(new,native_pointer(object),nwords*N_WORD_BYTES);
1508
1509     /* Return Lisp pointer of new object. */
1510     return ((lispobj) new) | tag;
1511 }
1512
1513 /* to copy large unboxed objects
1514  *
1515  * If the object is in a large object region then it is simply
1516  * promoted, else it is copied. If it's large enough then it's copied
1517  * to a large object region.
1518  *
1519  * Bignums and vectors may have shrunk. If the object is not copied
1520  * the space needs to be reclaimed, and the page_tables corrected.
1521  *
1522  * KLUDGE: There's a lot of cut-and-paste duplication between this
1523  * function and copy_large_object(..). -- WHN 20000619 */
1524 lispobj
1525 copy_large_unboxed_object(lispobj object, long nwords)
1526 {
1527     int tag;
1528     lispobj *new;
1529     page_index_t first_page;
1530
1531     gc_assert(is_lisp_pointer(object));
1532     gc_assert(from_space_p(object));
1533     gc_assert((nwords & 0x01) == 0);
1534
1535     if ((nwords > 1024*1024) && gencgc_verbose) {
1536         FSHOW((stderr, "/copy_large_unboxed_object: %d bytes\n",
1537                nwords*N_WORD_BYTES));
1538     }
1539
1540     /* Check whether it's a large object. */
1541     first_page = find_page_index((void *)object);
1542     gc_assert(first_page >= 0);
1543
1544     if (page_table[first_page].large_object) {
1545         /* Promote the object. Note: Unboxed objects may have been
1546          * allocated to a BOXED region so it may be necessary to
1547          * change the region to UNBOXED. */
1548         unsigned long remaining_bytes;
1549         page_index_t next_page;
1550         unsigned long bytes_freed;
1551         unsigned long old_bytes_used;
1552
1553         gc_assert(page_table[first_page].region_start_offset == 0);
1554
1555         next_page = first_page;
1556         remaining_bytes = nwords*N_WORD_BYTES;
1557         while (remaining_bytes > PAGE_BYTES) {
1558             gc_assert(page_table[next_page].gen == from_space);
1559             gc_assert(page_allocated_no_region_p(next_page));
1560             gc_assert(page_table[next_page].large_object);
1561             gc_assert(page_table[next_page].region_start_offset ==
1562                       npage_bytes(next_page-first_page));
1563             gc_assert(page_table[next_page].bytes_used == PAGE_BYTES);
1564
1565             page_table[next_page].gen = new_space;
1566             page_table[next_page].allocated = UNBOXED_PAGE_FLAG;
1567             remaining_bytes -= PAGE_BYTES;
1568             next_page++;
1569         }
1570
1571         /* Now only one page remains, but the object may have shrunk so
1572          * there may be more unused pages which will be freed. */
1573
1574         /* Object may have shrunk but shouldn't have grown - check. */
1575         gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1576
1577         page_table[next_page].gen = new_space;
1578         page_table[next_page].allocated = UNBOXED_PAGE_FLAG;
1579
1580         /* Adjust the bytes_used. */
1581         old_bytes_used = page_table[next_page].bytes_used;
1582         page_table[next_page].bytes_used = remaining_bytes;
1583
1584         bytes_freed = old_bytes_used - remaining_bytes;
1585
1586         /* Free any remaining pages; needs care. */
1587         next_page++;
1588         while ((old_bytes_used == PAGE_BYTES) &&
1589                (page_table[next_page].gen == from_space) &&
1590                page_allocated_no_region_p(next_page) &&
1591                page_table[next_page].large_object &&
1592                (page_table[next_page].region_start_offset ==
1593                 npage_bytes(next_page - first_page))) {
1594             /* Checks out OK, free the page. Don't need to both zeroing
1595              * pages as this should have been done before shrinking the
1596              * object. These pages shouldn't be write-protected, even if
1597              * boxed they should be zero filled. */
1598             gc_assert(page_table[next_page].write_protected == 0);
1599
1600             old_bytes_used = page_table[next_page].bytes_used;
1601             page_table[next_page].allocated = FREE_PAGE_FLAG;
1602             page_table[next_page].bytes_used = 0;
1603             bytes_freed += old_bytes_used;
1604             next_page++;
1605         }
1606
1607         if ((bytes_freed > 0) && gencgc_verbose) {
1608             FSHOW((stderr,
1609                    "/copy_large_unboxed bytes_freed=%d\n",
1610                    bytes_freed));
1611         }
1612
1613         generations[from_space].bytes_allocated -=
1614             nwords*N_WORD_BYTES + bytes_freed;
1615         generations[new_space].bytes_allocated += nwords*N_WORD_BYTES;
1616         bytes_allocated -= bytes_freed;
1617
1618         return(object);
1619     }
1620     else {
1621         /* Get tag of object. */
1622         tag = lowtag_of(object);
1623
1624         /* Allocate space. */
1625         new = gc_quick_alloc_large_unboxed(nwords*N_WORD_BYTES);
1626
1627         /* Copy the object. */
1628         memcpy(new,native_pointer(object),nwords*N_WORD_BYTES);
1629
1630         /* Return Lisp pointer of new object. */
1631         return ((lispobj) new) | tag;
1632     }
1633 }
1634
1635
1636
1637 \f
1638
1639 /*
1640  * code and code-related objects
1641  */
1642 /*
1643 static lispobj trans_fun_header(lispobj object);
1644 static lispobj trans_boxed(lispobj object);
1645 */
1646
1647 /* Scan a x86 compiled code object, looking for possible fixups that
1648  * have been missed after a move.
1649  *
1650  * Two types of fixups are needed:
1651  * 1. Absolute fixups to within the code object.
1652  * 2. Relative fixups to outside the code object.
1653  *
1654  * Currently only absolute fixups to the constant vector, or to the
1655  * code area are checked. */
1656 void
1657 sniff_code_object(struct code *code, unsigned long displacement)
1658 {
1659 #ifdef LISP_FEATURE_X86
1660     long nheader_words, ncode_words, nwords;
1661     void *p;
1662     void *constants_start_addr = NULL, *constants_end_addr;
1663     void *code_start_addr, *code_end_addr;
1664     int fixup_found = 0;
1665
1666     if (!check_code_fixups)
1667         return;
1668
1669     FSHOW((stderr, "/sniffing code: %p, %lu\n", code, displacement));
1670
1671     ncode_words = fixnum_value(code->code_size);
1672     nheader_words = HeaderValue(*(lispobj *)code);
1673     nwords = ncode_words + nheader_words;
1674
1675     constants_start_addr = (void *)code + 5*N_WORD_BYTES;
1676     constants_end_addr = (void *)code + nheader_words*N_WORD_BYTES;
1677     code_start_addr = (void *)code + nheader_words*N_WORD_BYTES;
1678     code_end_addr = (void *)code + nwords*N_WORD_BYTES;
1679
1680     /* Work through the unboxed code. */
1681     for (p = code_start_addr; p < code_end_addr; p++) {
1682         void *data = *(void **)p;
1683         unsigned d1 = *((unsigned char *)p - 1);
1684         unsigned d2 = *((unsigned char *)p - 2);
1685         unsigned d3 = *((unsigned char *)p - 3);
1686         unsigned d4 = *((unsigned char *)p - 4);
1687 #ifdef QSHOW
1688         unsigned d5 = *((unsigned char *)p - 5);
1689         unsigned d6 = *((unsigned char *)p - 6);
1690 #endif
1691
1692         /* Check for code references. */
1693         /* Check for a 32 bit word that looks like an absolute
1694            reference to within the code adea of the code object. */
1695         if ((data >= (code_start_addr-displacement))
1696             && (data < (code_end_addr-displacement))) {
1697             /* function header */
1698             if ((d4 == 0x5e)
1699                 && (((unsigned)p - 4 - 4*HeaderValue(*((unsigned *)p-1))) ==
1700                     (unsigned)code)) {
1701                 /* Skip the function header */
1702                 p += 6*4 - 4 - 1;
1703                 continue;
1704             }
1705             /* the case of PUSH imm32 */
1706             if (d1 == 0x68) {
1707                 fixup_found = 1;
1708                 FSHOW((stderr,
1709                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1710                        p, d6, d5, d4, d3, d2, d1, data));
1711                 FSHOW((stderr, "/PUSH $0x%.8x\n", data));
1712             }
1713             /* the case of MOV [reg-8],imm32 */
1714             if ((d3 == 0xc7)
1715                 && (d2==0x40 || d2==0x41 || d2==0x42 || d2==0x43
1716                     || d2==0x45 || d2==0x46 || d2==0x47)
1717                 && (d1 == 0xf8)) {
1718                 fixup_found = 1;
1719                 FSHOW((stderr,
1720                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1721                        p, d6, d5, d4, d3, d2, d1, data));
1722                 FSHOW((stderr, "/MOV [reg-8],$0x%.8x\n", data));
1723             }
1724             /* the case of LEA reg,[disp32] */
1725             if ((d2 == 0x8d) && ((d1 & 0xc7) == 5)) {
1726                 fixup_found = 1;
1727                 FSHOW((stderr,
1728                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1729                        p, d6, d5, d4, d3, d2, d1, data));
1730                 FSHOW((stderr,"/LEA reg,[$0x%.8x]\n", data));
1731             }
1732         }
1733
1734         /* Check for constant references. */
1735         /* Check for a 32 bit word that looks like an absolute
1736            reference to within the constant vector. Constant references
1737            will be aligned. */
1738         if ((data >= (constants_start_addr-displacement))
1739             && (data < (constants_end_addr-displacement))
1740             && (((unsigned)data & 0x3) == 0)) {
1741             /*  Mov eax,m32 */
1742             if (d1 == 0xa1) {
1743                 fixup_found = 1;
1744                 FSHOW((stderr,
1745                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1746                        p, d6, d5, d4, d3, d2, d1, data));
1747                 FSHOW((stderr,"/MOV eax,0x%.8x\n", data));
1748             }
1749
1750             /*  the case of MOV m32,EAX */
1751             if (d1 == 0xa3) {
1752                 fixup_found = 1;
1753                 FSHOW((stderr,
1754                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1755                        p, d6, d5, d4, d3, d2, d1, data));
1756                 FSHOW((stderr, "/MOV 0x%.8x,eax\n", data));
1757             }
1758
1759             /* the case of CMP m32,imm32 */
1760             if ((d1 == 0x3d) && (d2 == 0x81)) {
1761                 fixup_found = 1;
1762                 FSHOW((stderr,
1763                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1764                        p, d6, d5, d4, d3, d2, d1, data));
1765                 /* XX Check this */
1766                 FSHOW((stderr, "/CMP 0x%.8x,immed32\n", data));
1767             }
1768
1769             /* Check for a mod=00, r/m=101 byte. */
1770             if ((d1 & 0xc7) == 5) {
1771                 /* Cmp m32,reg */
1772                 if (d2 == 0x39) {
1773                     fixup_found = 1;
1774                     FSHOW((stderr,
1775                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1776                            p, d6, d5, d4, d3, d2, d1, data));
1777                     FSHOW((stderr,"/CMP 0x%.8x,reg\n", data));
1778                 }
1779                 /* the case of CMP reg32,m32 */
1780                 if (d2 == 0x3b) {
1781                     fixup_found = 1;
1782                     FSHOW((stderr,
1783                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1784                            p, d6, d5, d4, d3, d2, d1, data));
1785                     FSHOW((stderr, "/CMP reg32,0x%.8x\n", data));
1786                 }
1787                 /* the case of MOV m32,reg32 */
1788                 if (d2 == 0x89) {
1789                     fixup_found = 1;
1790                     FSHOW((stderr,
1791                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1792                            p, d6, d5, d4, d3, d2, d1, data));
1793                     FSHOW((stderr, "/MOV 0x%.8x,reg32\n", data));
1794                 }
1795                 /* the case of MOV reg32,m32 */
1796                 if (d2 == 0x8b) {
1797                     fixup_found = 1;
1798                     FSHOW((stderr,
1799                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1800                            p, d6, d5, d4, d3, d2, d1, data));
1801                     FSHOW((stderr, "/MOV reg32,0x%.8x\n", data));
1802                 }
1803                 /* the case of LEA reg32,m32 */
1804                 if (d2 == 0x8d) {
1805                     fixup_found = 1;
1806                     FSHOW((stderr,
1807                            "abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1808                            p, d6, d5, d4, d3, d2, d1, data));
1809                     FSHOW((stderr, "/LEA reg32,0x%.8x\n", data));
1810                 }
1811             }
1812         }
1813     }
1814
1815     /* If anything was found, print some information on the code
1816      * object. */
1817     if (fixup_found) {
1818         FSHOW((stderr,
1819                "/compiled code object at %x: header words = %d, code words = %d\n",
1820                code, nheader_words, ncode_words));
1821         FSHOW((stderr,
1822                "/const start = %x, end = %x\n",
1823                constants_start_addr, constants_end_addr));
1824         FSHOW((stderr,
1825                "/code start = %x, end = %x\n",
1826                code_start_addr, code_end_addr));
1827     }
1828 #endif
1829 }
1830
1831 void
1832 gencgc_apply_code_fixups(struct code *old_code, struct code *new_code)
1833 {
1834 /* x86-64 uses pc-relative addressing instead of this kludge */
1835 #ifndef LISP_FEATURE_X86_64
1836     long nheader_words, ncode_words, nwords;
1837     void *constants_start_addr, *constants_end_addr;
1838     void *code_start_addr, *code_end_addr;
1839     lispobj fixups = NIL;
1840     unsigned long displacement =
1841         (unsigned long)new_code - (unsigned long)old_code;
1842     struct vector *fixups_vector;
1843
1844     ncode_words = fixnum_value(new_code->code_size);
1845     nheader_words = HeaderValue(*(lispobj *)new_code);
1846     nwords = ncode_words + nheader_words;
1847     /* FSHOW((stderr,
1848              "/compiled code object at %x: header words = %d, code words = %d\n",
1849              new_code, nheader_words, ncode_words)); */
1850     constants_start_addr = (void *)new_code + 5*N_WORD_BYTES;
1851     constants_end_addr = (void *)new_code + nheader_words*N_WORD_BYTES;
1852     code_start_addr = (void *)new_code + nheader_words*N_WORD_BYTES;
1853     code_end_addr = (void *)new_code + nwords*N_WORD_BYTES;
1854     /*
1855     FSHOW((stderr,
1856            "/const start = %x, end = %x\n",
1857            constants_start_addr,constants_end_addr));
1858     FSHOW((stderr,
1859            "/code start = %x; end = %x\n",
1860            code_start_addr,code_end_addr));
1861     */
1862
1863     /* The first constant should be a pointer to the fixups for this
1864        code objects. Check. */
1865     fixups = new_code->constants[0];
1866
1867     /* It will be 0 or the unbound-marker if there are no fixups (as
1868      * will be the case if the code object has been purified, for
1869      * example) and will be an other pointer if it is valid. */
1870     if ((fixups == 0) || (fixups == UNBOUND_MARKER_WIDETAG) ||
1871         !is_lisp_pointer(fixups)) {
1872         /* Check for possible errors. */
1873         if (check_code_fixups)
1874             sniff_code_object(new_code, displacement);
1875
1876         return;
1877     }
1878
1879     fixups_vector = (struct vector *)native_pointer(fixups);
1880
1881     /* Could be pointing to a forwarding pointer. */
1882     /* FIXME is this always in from_space?  if so, could replace this code with
1883      * forwarding_pointer_p/forwarding_pointer_value */
1884     if (is_lisp_pointer(fixups) &&
1885         (find_page_index((void*)fixups_vector) != -1) &&
1886         (fixups_vector->header == 0x01)) {
1887         /* If so, then follow it. */
1888         /*SHOW("following pointer to a forwarding pointer");*/
1889         fixups_vector =
1890             (struct vector *)native_pointer((lispobj)fixups_vector->length);
1891     }
1892
1893     /*SHOW("got fixups");*/
1894
1895     if (widetag_of(fixups_vector->header) == SIMPLE_ARRAY_WORD_WIDETAG) {
1896         /* Got the fixups for the code block. Now work through the vector,
1897            and apply a fixup at each address. */
1898         long length = fixnum_value(fixups_vector->length);
1899         long i;
1900         for (i = 0; i < length; i++) {
1901             unsigned long offset = fixups_vector->data[i];
1902             /* Now check the current value of offset. */
1903             unsigned long old_value =
1904                 *(unsigned long *)((unsigned long)code_start_addr + offset);
1905
1906             /* If it's within the old_code object then it must be an
1907              * absolute fixup (relative ones are not saved) */
1908             if ((old_value >= (unsigned long)old_code)
1909                 && (old_value < ((unsigned long)old_code
1910                                  + nwords*N_WORD_BYTES)))
1911                 /* So add the dispacement. */
1912                 *(unsigned long *)((unsigned long)code_start_addr + offset) =
1913                     old_value + displacement;
1914             else
1915                 /* It is outside the old code object so it must be a
1916                  * relative fixup (absolute fixups are not saved). So
1917                  * subtract the displacement. */
1918                 *(unsigned long *)((unsigned long)code_start_addr + offset) =
1919                     old_value - displacement;
1920         }
1921     } else {
1922         /* This used to just print a note to stderr, but a bogus fixup seems to
1923          * indicate real heap corruption, so a hard hailure is in order. */
1924         lose("fixup vector %p has a bad widetag: %d\n",
1925              fixups_vector, widetag_of(fixups_vector->header));
1926     }
1927
1928     /* Check for possible errors. */
1929     if (check_code_fixups) {
1930         sniff_code_object(new_code,displacement);
1931     }
1932 #endif
1933 }
1934
1935
1936 static lispobj
1937 trans_boxed_large(lispobj object)
1938 {
1939     lispobj header;
1940     unsigned long length;
1941
1942     gc_assert(is_lisp_pointer(object));
1943
1944     header = *((lispobj *) native_pointer(object));
1945     length = HeaderValue(header) + 1;
1946     length = CEILING(length, 2);
1947
1948     return copy_large_object(object, length);
1949 }
1950
1951 /* Doesn't seem to be used, delete it after the grace period. */
1952 #if 0
1953 static lispobj
1954 trans_unboxed_large(lispobj object)
1955 {
1956     lispobj header;
1957     unsigned long length;
1958
1959     gc_assert(is_lisp_pointer(object));
1960
1961     header = *((lispobj *) native_pointer(object));
1962     length = HeaderValue(header) + 1;
1963     length = CEILING(length, 2);
1964
1965     return copy_large_unboxed_object(object, length);
1966 }
1967 #endif
1968
1969 \f
1970 /*
1971  * Lutexes. Using the normal finalization machinery for finalizing
1972  * lutexes is tricky, since the finalization depends on working lutexes.
1973  * So we track the lutexes in the GC and finalize them manually.
1974  */
1975
1976 #if defined(LUTEX_WIDETAG)
1977
1978 /*
1979  * Start tracking LUTEX in the GC, by adding it to the linked list of
1980  * lutexes in the nursery generation. The caller is responsible for
1981  * locking, and GCs must be inhibited until the registration is
1982  * complete.
1983  */
1984 void
1985 gencgc_register_lutex (struct lutex *lutex) {
1986     int index = find_page_index(lutex);
1987     generation_index_t gen;
1988     struct lutex *head;
1989
1990     /* This lutex is in static space, so we don't need to worry about
1991      * finalizing it.
1992      */
1993     if (index == -1)
1994         return;
1995
1996     gen = page_table[index].gen;
1997
1998     gc_assert(gen >= 0);
1999     gc_assert(gen < NUM_GENERATIONS);
2000
2001     head = generations[gen].lutexes;
2002
2003     lutex->gen = gen;
2004     lutex->next = head;
2005     lutex->prev = NULL;
2006     if (head)
2007         head->prev = lutex;
2008     generations[gen].lutexes = lutex;
2009 }
2010
2011 /*
2012  * Stop tracking LUTEX in the GC by removing it from the appropriate
2013  * linked lists. This will only be called during GC, so no locking is
2014  * needed.
2015  */
2016 void
2017 gencgc_unregister_lutex (struct lutex *lutex) {
2018     if (lutex->prev) {
2019         lutex->prev->next = lutex->next;
2020     } else {
2021         generations[lutex->gen].lutexes = lutex->next;
2022     }
2023
2024     if (lutex->next) {
2025         lutex->next->prev = lutex->prev;
2026     }
2027
2028     lutex->next = NULL;
2029     lutex->prev = NULL;
2030     lutex->gen = -1;
2031 }
2032
2033 /*
2034  * Mark all lutexes in generation GEN as not live.
2035  */
2036 static void
2037 unmark_lutexes (generation_index_t gen) {
2038     struct lutex *lutex = generations[gen].lutexes;
2039
2040     while (lutex) {
2041         lutex->live = 0;
2042         lutex = lutex->next;
2043     }
2044 }
2045
2046 /*
2047  * Finalize all lutexes in generation GEN that have not been marked live.
2048  */
2049 static void
2050 reap_lutexes (generation_index_t gen) {
2051     struct lutex *lutex = generations[gen].lutexes;
2052
2053     while (lutex) {
2054         struct lutex *next = lutex->next;
2055         if (!lutex->live) {
2056             lutex_destroy((tagged_lutex_t) lutex);
2057             gencgc_unregister_lutex(lutex);
2058         }
2059         lutex = next;
2060     }
2061 }
2062
2063 /*
2064  * Mark LUTEX as live.
2065  */
2066 static void
2067 mark_lutex (lispobj tagged_lutex) {
2068     struct lutex *lutex = (struct lutex*) native_pointer(tagged_lutex);
2069
2070     lutex->live = 1;
2071 }
2072
2073 /*
2074  * Move all lutexes in generation FROM to generation TO.
2075  */
2076 static void
2077 move_lutexes (generation_index_t from, generation_index_t to) {
2078     struct lutex *tail = generations[from].lutexes;
2079
2080     /* Nothing to move */
2081     if (!tail)
2082         return;
2083
2084     /* Change the generation of the lutexes in FROM. */
2085     while (tail->next) {
2086         tail->gen = to;
2087         tail = tail->next;
2088     }
2089     tail->gen = to;
2090
2091     /* Link the last lutex in the FROM list to the start of the TO list */
2092     tail->next = generations[to].lutexes;
2093
2094     /* And vice versa */
2095     if (generations[to].lutexes) {
2096         generations[to].lutexes->prev = tail;
2097     }
2098
2099     /* And update the generations structures to match this */
2100     generations[to].lutexes = generations[from].lutexes;
2101     generations[from].lutexes = NULL;
2102 }
2103
2104 static long
2105 scav_lutex(lispobj *where, lispobj object)
2106 {
2107     mark_lutex((lispobj) where);
2108
2109     return CEILING(sizeof(struct lutex)/sizeof(lispobj), 2);
2110 }
2111
2112 static lispobj
2113 trans_lutex(lispobj object)
2114 {
2115     struct lutex *lutex = (struct lutex *) native_pointer(object);
2116     lispobj copied;
2117     size_t words = CEILING(sizeof(struct lutex)/sizeof(lispobj), 2);
2118     gc_assert(is_lisp_pointer(object));
2119     copied = copy_object(object, words);
2120
2121     /* Update the links, since the lutex moved in memory. */
2122     if (lutex->next) {
2123         lutex->next->prev = (struct lutex *) native_pointer(copied);
2124     }
2125
2126     if (lutex->prev) {
2127         lutex->prev->next = (struct lutex *) native_pointer(copied);
2128     } else {
2129         generations[lutex->gen].lutexes =
2130           (struct lutex *) native_pointer(copied);
2131     }
2132
2133     return copied;
2134 }
2135
2136 static long
2137 size_lutex(lispobj *where)
2138 {
2139     return CEILING(sizeof(struct lutex)/sizeof(lispobj), 2);
2140 }
2141 #endif /* LUTEX_WIDETAG */
2142
2143 \f
2144 /*
2145  * weak pointers
2146  */
2147
2148 /* XX This is a hack adapted from cgc.c. These don't work too
2149  * efficiently with the gencgc as a list of the weak pointers is
2150  * maintained within the objects which causes writes to the pages. A
2151  * limited attempt is made to avoid unnecessary writes, but this needs
2152  * a re-think. */
2153 #define WEAK_POINTER_NWORDS \
2154     CEILING((sizeof(struct weak_pointer) / sizeof(lispobj)), 2)
2155
2156 static long
2157 scav_weak_pointer(lispobj *where, lispobj object)
2158 {
2159     /* Since we overwrite the 'next' field, we have to make
2160      * sure not to do so for pointers already in the list.
2161      * Instead of searching the list of weak_pointers each
2162      * time, we ensure that next is always NULL when the weak
2163      * pointer isn't in the list, and not NULL otherwise.
2164      * Since we can't use NULL to denote end of list, we
2165      * use a pointer back to the same weak_pointer.
2166      */
2167     struct weak_pointer * wp = (struct weak_pointer*)where;
2168
2169     if (NULL == wp->next) {
2170         wp->next = weak_pointers;
2171         weak_pointers = wp;
2172         if (NULL == wp->next)
2173             wp->next = wp;
2174     }
2175
2176     /* Do not let GC scavenge the value slot of the weak pointer.
2177      * (That is why it is a weak pointer.) */
2178
2179     return WEAK_POINTER_NWORDS;
2180 }
2181
2182 \f
2183 lispobj *
2184 search_read_only_space(void *pointer)
2185 {
2186     lispobj *start = (lispobj *) READ_ONLY_SPACE_START;
2187     lispobj *end = (lispobj *) SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0);
2188     if ((pointer < (void *)start) || (pointer >= (void *)end))
2189         return NULL;
2190     return (gc_search_space(start,
2191                             (((lispobj *)pointer)+2)-start,
2192                             (lispobj *) pointer));
2193 }
2194
2195 lispobj *
2196 search_static_space(void *pointer)
2197 {
2198     lispobj *start = (lispobj *)STATIC_SPACE_START;
2199     lispobj *end = (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0);
2200     if ((pointer < (void *)start) || (pointer >= (void *)end))
2201         return NULL;
2202     return (gc_search_space(start,
2203                             (((lispobj *)pointer)+2)-start,
2204                             (lispobj *) pointer));
2205 }
2206
2207 /* a faster version for searching the dynamic space. This will work even
2208  * if the object is in a current allocation region. */
2209 lispobj *
2210 search_dynamic_space(void *pointer)
2211 {
2212     page_index_t page_index = find_page_index(pointer);
2213     lispobj *start;
2214
2215     /* The address may be invalid, so do some checks. */
2216     if ((page_index == -1) || page_free_p(page_index))
2217         return NULL;
2218     start = (lispobj *)page_region_start(page_index);
2219     return (gc_search_space(start,
2220                             (((lispobj *)pointer)+2)-start,
2221                             (lispobj *)pointer));
2222 }
2223
2224 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2225
2226 /* Helper for valid_lisp_pointer_p and
2227  * possibly_valid_dynamic_space_pointer.
2228  *
2229  * pointer is the pointer to validate, and start_addr is the address
2230  * of the enclosing object.
2231  */
2232 static int
2233 looks_like_valid_lisp_pointer_p(lispobj *pointer, lispobj *start_addr)
2234 {
2235     if (!is_lisp_pointer((lispobj)pointer)) {
2236         return 0;
2237     }
2238
2239     /* Check that the object pointed to is consistent with the pointer
2240      * low tag. */
2241     switch (lowtag_of((lispobj)pointer)) {
2242     case FUN_POINTER_LOWTAG:
2243         /* Start_addr should be the enclosing code object, or a closure
2244          * header. */
2245         switch (widetag_of(*start_addr)) {
2246         case CODE_HEADER_WIDETAG:
2247             /* This case is probably caught above. */
2248             break;
2249         case CLOSURE_HEADER_WIDETAG:
2250         case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
2251             if ((unsigned long)pointer !=
2252                 ((unsigned long)start_addr+FUN_POINTER_LOWTAG)) {
2253                 if (gencgc_verbose) {
2254                     FSHOW((stderr,
2255                            "/Wf2: %x %x %x\n",
2256                            pointer, start_addr, *start_addr));
2257                 }
2258                 return 0;
2259             }
2260             break;
2261         default:
2262             if (gencgc_verbose) {
2263                 FSHOW((stderr,
2264                        "/Wf3: %x %x %x\n",
2265                        pointer, start_addr, *start_addr));
2266             }
2267             return 0;
2268         }
2269         break;
2270     case LIST_POINTER_LOWTAG:
2271         if ((unsigned long)pointer !=
2272             ((unsigned long)start_addr+LIST_POINTER_LOWTAG)) {
2273             if (gencgc_verbose) {
2274                 FSHOW((stderr,
2275                        "/Wl1: %x %x %x\n",
2276                        pointer, start_addr, *start_addr));
2277             }
2278             return 0;
2279         }
2280         /* Is it plausible cons? */
2281         if ((is_lisp_pointer(start_addr[0]) ||
2282              is_lisp_immediate(start_addr[0])) &&
2283             (is_lisp_pointer(start_addr[1]) ||
2284              is_lisp_immediate(start_addr[1])))
2285             break;
2286         else {
2287             if (gencgc_verbose) {
2288                 FSHOW((stderr,
2289                        "/Wl2: %x %x %x\n",
2290                        pointer, start_addr, *start_addr));
2291             }
2292             return 0;
2293         }
2294     case INSTANCE_POINTER_LOWTAG:
2295         if ((unsigned long)pointer !=
2296             ((unsigned long)start_addr+INSTANCE_POINTER_LOWTAG)) {
2297             if (gencgc_verbose) {
2298                 FSHOW((stderr,
2299                        "/Wi1: %x %x %x\n",
2300                        pointer, start_addr, *start_addr));
2301             }
2302             return 0;
2303         }
2304         if (widetag_of(start_addr[0]) != INSTANCE_HEADER_WIDETAG) {
2305             if (gencgc_verbose) {
2306                 FSHOW((stderr,
2307                        "/Wi2: %x %x %x\n",
2308                        pointer, start_addr, *start_addr));
2309             }
2310             return 0;
2311         }
2312         break;
2313     case OTHER_POINTER_LOWTAG:
2314         if ((unsigned long)pointer !=
2315             ((unsigned long)start_addr+OTHER_POINTER_LOWTAG)) {
2316             if (gencgc_verbose) {
2317                 FSHOW((stderr,
2318                        "/Wo1: %x %x %x\n",
2319                        pointer, start_addr, *start_addr));
2320             }
2321             return 0;
2322         }
2323         /* Is it plausible?  Not a cons. XXX should check the headers. */
2324         if (is_lisp_pointer(start_addr[0]) || ((start_addr[0] & 3) == 0)) {
2325             if (gencgc_verbose) {
2326                 FSHOW((stderr,
2327                        "/Wo2: %x %x %x\n",
2328                        pointer, start_addr, *start_addr));
2329             }
2330             return 0;
2331         }
2332         switch (widetag_of(start_addr[0])) {
2333         case UNBOUND_MARKER_WIDETAG:
2334         case NO_TLS_VALUE_MARKER_WIDETAG:
2335         case CHARACTER_WIDETAG:
2336 #if N_WORD_BITS == 64
2337         case SINGLE_FLOAT_WIDETAG:
2338 #endif
2339             if (gencgc_verbose) {
2340                 FSHOW((stderr,
2341                        "*Wo3: %x %x %x\n",
2342                        pointer, start_addr, *start_addr));
2343             }
2344             return 0;
2345
2346             /* only pointed to by function pointers? */
2347         case CLOSURE_HEADER_WIDETAG:
2348         case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
2349             if (gencgc_verbose) {
2350                 FSHOW((stderr,
2351                        "*Wo4: %x %x %x\n",
2352                        pointer, start_addr, *start_addr));
2353             }
2354             return 0;
2355
2356         case INSTANCE_HEADER_WIDETAG:
2357             if (gencgc_verbose) {
2358                 FSHOW((stderr,
2359                        "*Wo5: %x %x %x\n",
2360                        pointer, start_addr, *start_addr));
2361             }
2362             return 0;
2363
2364             /* the valid other immediate pointer objects */
2365         case SIMPLE_VECTOR_WIDETAG:
2366         case RATIO_WIDETAG:
2367         case COMPLEX_WIDETAG:
2368 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
2369         case COMPLEX_SINGLE_FLOAT_WIDETAG:
2370 #endif
2371 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
2372         case COMPLEX_DOUBLE_FLOAT_WIDETAG:
2373 #endif
2374 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
2375         case COMPLEX_LONG_FLOAT_WIDETAG:
2376 #endif
2377         case SIMPLE_ARRAY_WIDETAG:
2378         case COMPLEX_BASE_STRING_WIDETAG:
2379 #ifdef COMPLEX_CHARACTER_STRING_WIDETAG
2380         case COMPLEX_CHARACTER_STRING_WIDETAG:
2381 #endif
2382         case COMPLEX_VECTOR_NIL_WIDETAG:
2383         case COMPLEX_BIT_VECTOR_WIDETAG:
2384         case COMPLEX_VECTOR_WIDETAG:
2385         case COMPLEX_ARRAY_WIDETAG:
2386         case VALUE_CELL_HEADER_WIDETAG:
2387         case SYMBOL_HEADER_WIDETAG:
2388         case FDEFN_WIDETAG:
2389         case CODE_HEADER_WIDETAG:
2390         case BIGNUM_WIDETAG:
2391 #if N_WORD_BITS != 64
2392         case SINGLE_FLOAT_WIDETAG:
2393 #endif
2394         case DOUBLE_FLOAT_WIDETAG:
2395 #ifdef LONG_FLOAT_WIDETAG
2396         case LONG_FLOAT_WIDETAG:
2397 #endif
2398         case SIMPLE_BASE_STRING_WIDETAG:
2399 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
2400         case SIMPLE_CHARACTER_STRING_WIDETAG:
2401 #endif
2402         case SIMPLE_BIT_VECTOR_WIDETAG:
2403         case SIMPLE_ARRAY_NIL_WIDETAG:
2404         case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2405         case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2406         case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
2407         case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2408         case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
2409         case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2410 #ifdef  SIMPLE_ARRAY_UNSIGNED_BYTE_29_WIDETAG
2411         case SIMPLE_ARRAY_UNSIGNED_BYTE_29_WIDETAG:
2412 #endif
2413         case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
2414         case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2415 #ifdef  SIMPLE_ARRAY_UNSIGNED_BYTE_60_WIDETAG
2416         case SIMPLE_ARRAY_UNSIGNED_BYTE_60_WIDETAG:
2417 #endif
2418 #ifdef  SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
2419         case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
2420 #endif
2421 #ifdef  SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
2422         case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
2423 #endif
2424 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2425         case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2426 #endif
2427 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2428         case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2429 #endif
2430 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG
2431         case SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG:
2432 #endif
2433 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2434         case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2435 #endif
2436 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_61_WIDETAG
2437         case SIMPLE_ARRAY_SIGNED_BYTE_61_WIDETAG:
2438 #endif
2439 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
2440         case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
2441 #endif
2442         case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2443         case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2444 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2445         case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2446 #endif
2447 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2448         case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2449 #endif
2450 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2451         case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2452 #endif
2453 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2454         case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2455 #endif
2456         case SAP_WIDETAG:
2457         case WEAK_POINTER_WIDETAG:
2458 #ifdef LUTEX_WIDETAG
2459         case LUTEX_WIDETAG:
2460 #endif
2461             break;
2462
2463         default:
2464             if (gencgc_verbose) {
2465                 FSHOW((stderr,
2466                        "/Wo6: %x %x %x\n",
2467                        pointer, start_addr, *start_addr));
2468             }
2469             return 0;
2470         }
2471         break;
2472     default:
2473         if (gencgc_verbose) {
2474             FSHOW((stderr,
2475                    "*W?: %x %x %x\n",
2476                    pointer, start_addr, *start_addr));
2477         }
2478         return 0;
2479     }
2480
2481     /* looks good */
2482     return 1;
2483 }
2484
2485 /* Used by the debugger to validate possibly bogus pointers before
2486  * calling MAKE-LISP-OBJ on them.
2487  *
2488  * FIXME: We would like to make this perfect, because if the debugger
2489  * constructs a reference to a bugs lisp object, and it ends up in a
2490  * location scavenged by the GC all hell breaks loose.
2491  *
2492  * Whereas possibly_valid_dynamic_space_pointer has to be conservative
2493  * and return true for all valid pointers, this could actually be eager
2494  * and lie about a few pointers without bad results... but that should
2495  * be reflected in the name.
2496  */
2497 int
2498 valid_lisp_pointer_p(lispobj *pointer)
2499 {
2500     lispobj *start;
2501     if (((start=search_dynamic_space(pointer))!=NULL) ||
2502         ((start=search_static_space(pointer))!=NULL) ||
2503         ((start=search_read_only_space(pointer))!=NULL))
2504         return looks_like_valid_lisp_pointer_p(pointer, start);
2505     else
2506         return 0;
2507 }
2508
2509 /* Is there any possibility that pointer is a valid Lisp object
2510  * reference, and/or something else (e.g. subroutine call return
2511  * address) which should prevent us from moving the referred-to thing?
2512  * This is called from preserve_pointers() */
2513 static int
2514 possibly_valid_dynamic_space_pointer(lispobj *pointer)
2515 {
2516     lispobj *start_addr;
2517
2518     /* Find the object start address. */
2519     if ((start_addr = search_dynamic_space(pointer)) == NULL) {
2520         return 0;
2521     }
2522
2523     return looks_like_valid_lisp_pointer_p(pointer, start_addr);
2524 }
2525
2526 /* Adjust large bignum and vector objects. This will adjust the
2527  * allocated region if the size has shrunk, and move unboxed objects
2528  * into unboxed pages. The pages are not promoted here, and the
2529  * promoted region is not added to the new_regions; this is really
2530  * only designed to be called from preserve_pointer(). Shouldn't fail
2531  * if this is missed, just may delay the moving of objects to unboxed
2532  * pages, and the freeing of pages. */
2533 static void
2534 maybe_adjust_large_object(lispobj *where)
2535 {
2536     page_index_t first_page;
2537     page_index_t next_page;
2538     long nwords;
2539
2540     unsigned long remaining_bytes;
2541     unsigned long bytes_freed;
2542     unsigned long old_bytes_used;
2543
2544     int boxed;
2545
2546     /* Check whether it's a vector or bignum object. */
2547     switch (widetag_of(where[0])) {
2548     case SIMPLE_VECTOR_WIDETAG:
2549         boxed = BOXED_PAGE_FLAG;
2550         break;
2551     case BIGNUM_WIDETAG:
2552     case SIMPLE_BASE_STRING_WIDETAG:
2553 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
2554     case SIMPLE_CHARACTER_STRING_WIDETAG:
2555 #endif
2556     case SIMPLE_BIT_VECTOR_WIDETAG:
2557     case SIMPLE_ARRAY_NIL_WIDETAG:
2558     case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2559     case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2560     case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
2561     case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2562     case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
2563     case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2564 #ifdef  SIMPLE_ARRAY_UNSIGNED_BYTE_29_WIDETAG
2565     case SIMPLE_ARRAY_UNSIGNED_BYTE_29_WIDETAG:
2566 #endif
2567     case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
2568     case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2569 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_60_WIDETAG
2570     case SIMPLE_ARRAY_UNSIGNED_BYTE_60_WIDETAG:
2571 #endif
2572 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
2573     case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
2574 #endif
2575 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
2576     case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
2577 #endif
2578 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2579     case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2580 #endif
2581 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2582     case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2583 #endif
2584 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG
2585     case SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG:
2586 #endif
2587 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2588     case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2589 #endif
2590 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_61_WIDETAG
2591     case SIMPLE_ARRAY_SIGNED_BYTE_61_WIDETAG:
2592 #endif
2593 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
2594     case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
2595 #endif
2596     case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2597     case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2598 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2599     case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2600 #endif
2601 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2602     case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2603 #endif
2604 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2605     case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2606 #endif
2607 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2608     case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2609 #endif
2610         boxed = UNBOXED_PAGE_FLAG;
2611         break;
2612     default:
2613         return;
2614     }
2615
2616     /* Find its current size. */
2617     nwords = (sizetab[widetag_of(where[0])])(where);
2618
2619     first_page = find_page_index((void *)where);
2620     gc_assert(first_page >= 0);
2621
2622     /* Note: Any page write-protection must be removed, else a later
2623      * scavenge_newspace may incorrectly not scavenge these pages.
2624      * This would not be necessary if they are added to the new areas,
2625      * but lets do it for them all (they'll probably be written
2626      * anyway?). */
2627
2628     gc_assert(page_table[first_page].region_start_offset == 0);
2629
2630     next_page = first_page;
2631     remaining_bytes = nwords*N_WORD_BYTES;
2632     while (remaining_bytes > PAGE_BYTES) {
2633         gc_assert(page_table[next_page].gen == from_space);
2634         gc_assert(page_allocated_no_region_p(next_page));
2635         gc_assert(page_table[next_page].large_object);
2636         gc_assert(page_table[next_page].region_start_offset ==
2637                   npage_bytes(next_page-first_page));
2638         gc_assert(page_table[next_page].bytes_used == PAGE_BYTES);
2639
2640         page_table[next_page].allocated = boxed;
2641
2642         /* Shouldn't be write-protected at this stage. Essential that the
2643          * pages aren't. */
2644         gc_assert(!page_table[next_page].write_protected);
2645         remaining_bytes -= PAGE_BYTES;
2646         next_page++;
2647     }
2648
2649     /* Now only one page remains, but the object may have shrunk so
2650      * there may be more unused pages which will be freed. */
2651
2652     /* Object may have shrunk but shouldn't have grown - check. */
2653     gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
2654
2655     page_table[next_page].allocated = boxed;
2656     gc_assert(page_table[next_page].allocated ==
2657               page_table[first_page].allocated);
2658
2659     /* Adjust the bytes_used. */
2660     old_bytes_used = page_table[next_page].bytes_used;
2661     page_table[next_page].bytes_used = remaining_bytes;
2662
2663     bytes_freed = old_bytes_used - remaining_bytes;
2664
2665     /* Free any remaining pages; needs care. */
2666     next_page++;
2667     while ((old_bytes_used == PAGE_BYTES) &&
2668            (page_table[next_page].gen == from_space) &&
2669            page_allocated_no_region_p(next_page) &&
2670            page_table[next_page].large_object &&
2671            (page_table[next_page].region_start_offset ==
2672             npage_bytes(next_page - first_page))) {
2673         /* It checks out OK, free the page. We don't need to both zeroing
2674          * pages as this should have been done before shrinking the
2675          * object. These pages shouldn't be write protected as they
2676          * should be zero filled. */
2677         gc_assert(page_table[next_page].write_protected == 0);
2678
2679         old_bytes_used = page_table[next_page].bytes_used;
2680         page_table[next_page].allocated = FREE_PAGE_FLAG;
2681         page_table[next_page].bytes_used = 0;
2682         bytes_freed += old_bytes_used;
2683         next_page++;
2684     }
2685
2686     if ((bytes_freed > 0) && gencgc_verbose) {
2687         FSHOW((stderr,
2688                "/maybe_adjust_large_object() freed %d\n",
2689                bytes_freed));
2690     }
2691
2692     generations[from_space].bytes_allocated -= bytes_freed;
2693     bytes_allocated -= bytes_freed;
2694
2695     return;
2696 }
2697
2698 /* Take a possible pointer to a Lisp object and mark its page in the
2699  * page_table so that it will not be relocated during a GC.
2700  *
2701  * This involves locating the page it points to, then backing up to
2702  * the start of its region, then marking all pages dont_move from there
2703  * up to the first page that's not full or has a different generation
2704  *
2705  * It is assumed that all the page static flags have been cleared at
2706  * the start of a GC.
2707  *
2708  * It is also assumed that the current gc_alloc() region has been
2709  * flushed and the tables updated. */
2710
2711 static void
2712 preserve_pointer(void *addr)
2713 {
2714     page_index_t addr_page_index = find_page_index(addr);
2715     page_index_t first_page;
2716     page_index_t i;
2717     unsigned int region_allocation;
2718
2719     /* quick check 1: Address is quite likely to have been invalid. */
2720     if ((addr_page_index == -1)
2721         || page_free_p(addr_page_index)
2722         || (page_table[addr_page_index].bytes_used == 0)
2723         || (page_table[addr_page_index].gen != from_space)
2724         /* Skip if already marked dont_move. */
2725         || (page_table[addr_page_index].dont_move != 0))
2726         return;
2727     gc_assert(!(page_table[addr_page_index].allocated&OPEN_REGION_PAGE_FLAG));
2728     /* (Now that we know that addr_page_index is in range, it's
2729      * safe to index into page_table[] with it.) */
2730     region_allocation = page_table[addr_page_index].allocated;
2731
2732     /* quick check 2: Check the offset within the page.
2733      *
2734      */
2735     if (((unsigned long)addr & (PAGE_BYTES - 1)) >
2736         page_table[addr_page_index].bytes_used)
2737         return;
2738
2739     /* Filter out anything which can't be a pointer to a Lisp object
2740      * (or, as a special case which also requires dont_move, a return
2741      * address referring to something in a CodeObject). This is
2742      * expensive but important, since it vastly reduces the
2743      * probability that random garbage will be bogusly interpreted as
2744      * a pointer which prevents a page from moving. */
2745     if (!(code_page_p(addr_page_index)
2746           || (is_lisp_pointer((lispobj)addr) &&
2747               possibly_valid_dynamic_space_pointer(addr))))
2748         return;
2749
2750     /* Find the beginning of the region.  Note that there may be
2751      * objects in the region preceding the one that we were passed a
2752      * pointer to: if this is the case, we will write-protect all the
2753      * previous objects' pages too.     */
2754
2755 #if 0
2756     /* I think this'd work just as well, but without the assertions.
2757      * -dan 2004.01.01 */
2758     first_page = find_page_index(page_region_start(addr_page_index))
2759 #else
2760     first_page = addr_page_index;
2761     while (page_table[first_page].region_start_offset != 0) {
2762         --first_page;
2763         /* Do some checks. */
2764         gc_assert(page_table[first_page].bytes_used == PAGE_BYTES);
2765         gc_assert(page_table[first_page].gen == from_space);
2766         gc_assert(page_table[first_page].allocated == region_allocation);
2767     }
2768 #endif
2769
2770     /* Adjust any large objects before promotion as they won't be
2771      * copied after promotion. */
2772     if (page_table[first_page].large_object) {
2773         maybe_adjust_large_object(page_address(first_page));
2774         /* If a large object has shrunk then addr may now point to a
2775          * free area in which case it's ignored here. Note it gets
2776          * through the valid pointer test above because the tail looks
2777          * like conses. */
2778         if (page_free_p(addr_page_index)
2779             || (page_table[addr_page_index].bytes_used == 0)
2780             /* Check the offset within the page. */
2781             || (((unsigned long)addr & (PAGE_BYTES - 1))
2782                 > page_table[addr_page_index].bytes_used)) {
2783             FSHOW((stderr,
2784                    "weird? ignore ptr 0x%x to freed area of large object\n",
2785                    addr));
2786             return;
2787         }
2788         /* It may have moved to unboxed pages. */
2789         region_allocation = page_table[first_page].allocated;
2790     }
2791
2792     /* Now work forward until the end of this contiguous area is found,
2793      * marking all pages as dont_move. */
2794     for (i = first_page; ;i++) {
2795         gc_assert(page_table[i].allocated == region_allocation);
2796
2797         /* Mark the page static. */
2798         page_table[i].dont_move = 1;
2799
2800         /* Move the page to the new_space. XX I'd rather not do this
2801          * but the GC logic is not quite able to copy with the static
2802          * pages remaining in the from space. This also requires the
2803          * generation bytes_allocated counters be updated. */
2804         page_table[i].gen = new_space;
2805         generations[new_space].bytes_allocated += page_table[i].bytes_used;
2806         generations[from_space].bytes_allocated -= page_table[i].bytes_used;
2807
2808         /* It is essential that the pages are not write protected as
2809          * they may have pointers into the old-space which need
2810          * scavenging. They shouldn't be write protected at this
2811          * stage. */
2812         gc_assert(!page_table[i].write_protected);
2813
2814         /* Check whether this is the last page in this contiguous block.. */
2815         if ((page_table[i].bytes_used < PAGE_BYTES)
2816             /* ..or it is PAGE_BYTES and is the last in the block */
2817             || page_free_p(i+1)
2818             || (page_table[i+1].bytes_used == 0) /* next page free */
2819             || (page_table[i+1].gen != from_space) /* diff. gen */
2820             || (page_table[i+1].region_start_offset == 0))
2821             break;
2822     }
2823
2824     /* Check that the page is now static. */
2825     gc_assert(page_table[addr_page_index].dont_move != 0);
2826 }
2827
2828 #endif  // defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2829
2830 \f
2831 /* If the given page is not write-protected, then scan it for pointers
2832  * to younger generations or the top temp. generation, if no
2833  * suspicious pointers are found then the page is write-protected.
2834  *
2835  * Care is taken to check for pointers to the current gc_alloc()
2836  * region if it is a younger generation or the temp. generation. This
2837  * frees the caller from doing a gc_alloc_update_page_tables(). Actually
2838  * the gc_alloc_generation does not need to be checked as this is only
2839  * called from scavenge_generation() when the gc_alloc generation is
2840  * younger, so it just checks if there is a pointer to the current
2841  * region.
2842  *
2843  * We return 1 if the page was write-protected, else 0. */
2844 static int
2845 update_page_write_prot(page_index_t page)
2846 {
2847     generation_index_t gen = page_table[page].gen;
2848     long j;
2849     int wp_it = 1;
2850     void **page_addr = (void **)page_address(page);
2851     long num_words = page_table[page].bytes_used / N_WORD_BYTES;
2852
2853     /* Shouldn't be a free page. */
2854     gc_assert(page_allocated_p(page));
2855     gc_assert(page_table[page].bytes_used != 0);
2856
2857     /* Skip if it's already write-protected, pinned, or unboxed */
2858     if (page_table[page].write_protected
2859         /* FIXME: What's the reason for not write-protecting pinned pages? */
2860         || page_table[page].dont_move
2861         || page_unboxed_p(page))
2862         return (0);
2863
2864     /* Scan the page for pointers to younger generations or the
2865      * top temp. generation. */
2866
2867     for (j = 0; j < num_words; j++) {
2868         void *ptr = *(page_addr+j);
2869         page_index_t index = find_page_index(ptr);
2870
2871         /* Check that it's in the dynamic space */
2872         if (index != -1)
2873             if (/* Does it point to a younger or the temp. generation? */
2874                 (page_allocated_p(index)
2875                  && (page_table[index].bytes_used != 0)
2876                  && ((page_table[index].gen < gen)
2877                      || (page_table[index].gen == SCRATCH_GENERATION)))
2878
2879                 /* Or does it point within a current gc_alloc() region? */
2880                 || ((boxed_region.start_addr <= ptr)
2881                     && (ptr <= boxed_region.free_pointer))
2882                 || ((unboxed_region.start_addr <= ptr)
2883                     && (ptr <= unboxed_region.free_pointer))) {
2884                 wp_it = 0;
2885                 break;
2886             }
2887     }
2888
2889     if (wp_it == 1) {
2890         /* Write-protect the page. */
2891         /*FSHOW((stderr, "/write-protecting page %d gen %d\n", page, gen));*/
2892
2893         os_protect((void *)page_addr,
2894                    PAGE_BYTES,
2895                    OS_VM_PROT_READ|OS_VM_PROT_EXECUTE);
2896
2897         /* Note the page as protected in the page tables. */
2898         page_table[page].write_protected = 1;
2899     }
2900
2901     return (wp_it);
2902 }
2903
2904 /* Scavenge all generations from FROM to TO, inclusive, except for
2905  * new_space which needs special handling, as new objects may be
2906  * added which are not checked here - use scavenge_newspace generation.
2907  *
2908  * Write-protected pages should not have any pointers to the
2909  * from_space so do need scavenging; thus write-protected pages are
2910  * not always scavenged. There is some code to check that these pages
2911  * are not written; but to check fully the write-protected pages need
2912  * to be scavenged by disabling the code to skip them.
2913  *
2914  * Under the current scheme when a generation is GCed the younger
2915  * generations will be empty. So, when a generation is being GCed it
2916  * is only necessary to scavenge the older generations for pointers
2917  * not the younger. So a page that does not have pointers to younger
2918  * generations does not need to be scavenged.
2919  *
2920  * The write-protection can be used to note pages that don't have
2921  * pointers to younger pages. But pages can be written without having
2922  * pointers to younger generations. After the pages are scavenged here
2923  * they can be scanned for pointers to younger generations and if
2924  * there are none the page can be write-protected.
2925  *
2926  * One complication is when the newspace is the top temp. generation.
2927  *
2928  * Enabling SC_GEN_CK scavenges the write-protected pages and checks
2929  * that none were written, which they shouldn't be as they should have
2930  * no pointers to younger generations. This breaks down for weak
2931  * pointers as the objects contain a link to the next and are written
2932  * if a weak pointer is scavenged. Still it's a useful check. */
2933 static void
2934 scavenge_generations(generation_index_t from, generation_index_t to)
2935 {
2936     page_index_t i;
2937     int num_wp = 0;
2938
2939 #define SC_GEN_CK 0
2940 #if SC_GEN_CK
2941     /* Clear the write_protected_cleared flags on all pages. */
2942     for (i = 0; i < page_table_pages; i++)
2943         page_table[i].write_protected_cleared = 0;
2944 #endif
2945
2946     for (i = 0; i < last_free_page; i++) {
2947         generation_index_t generation = page_table[i].gen;
2948         if (page_boxed_p(i)
2949             && (page_table[i].bytes_used != 0)
2950             && (generation != new_space)
2951             && (generation >= from)
2952             && (generation <= to)) {
2953             page_index_t last_page,j;
2954             int write_protected=1;
2955
2956             /* This should be the start of a region */
2957             gc_assert(page_table[i].region_start_offset == 0);
2958
2959             /* Now work forward until the end of the region */
2960             for (last_page = i; ; last_page++) {
2961                 write_protected =
2962                     write_protected && page_table[last_page].write_protected;
2963                 if ((page_table[last_page].bytes_used < PAGE_BYTES)
2964                     /* Or it is PAGE_BYTES and is the last in the block */
2965                     || (!page_boxed_p(last_page+1))
2966                     || (page_table[last_page+1].bytes_used == 0)
2967                     || (page_table[last_page+1].gen != generation)
2968                     || (page_table[last_page+1].region_start_offset == 0))
2969                     break;
2970             }
2971             if (!write_protected) {
2972                 scavenge(page_address(i),
2973                          ((unsigned long)(page_table[last_page].bytes_used
2974                                           + npage_bytes(last_page-i)))
2975                          /N_WORD_BYTES);
2976
2977                 /* Now scan the pages and write protect those that
2978                  * don't have pointers to younger generations. */
2979                 if (enable_page_protection) {
2980                     for (j = i; j <= last_page; j++) {
2981                         num_wp += update_page_write_prot(j);
2982                     }
2983                 }
2984                 if ((gencgc_verbose > 1) && (num_wp != 0)) {
2985                     FSHOW((stderr,
2986                            "/write protected %d pages within generation %d\n",
2987                            num_wp, generation));
2988                 }
2989             }
2990             i = last_page;
2991         }
2992     }
2993
2994 #if SC_GEN_CK
2995     /* Check that none of the write_protected pages in this generation
2996      * have been written to. */
2997     for (i = 0; i < page_table_pages; i++) {
2998         if (page_allocated_p(i)
2999             && (page_table[i].bytes_used != 0)
3000             && (page_table[i].gen == generation)
3001             && (page_table[i].write_protected_cleared != 0)) {
3002             FSHOW((stderr, "/scavenge_generation() %d\n", generation));
3003             FSHOW((stderr,
3004                    "/page bytes_used=%d region_start_offset=%lu dont_move=%d\n",
3005                     page_table[i].bytes_used,
3006                     page_table[i].region_start_offset,
3007                     page_table[i].dont_move));
3008             lose("write to protected page %d in scavenge_generation()\n", i);
3009         }
3010     }
3011 #endif
3012 }
3013
3014 \f
3015 /* Scavenge a newspace generation. As it is scavenged new objects may
3016  * be allocated to it; these will also need to be scavenged. This
3017  * repeats until there are no more objects unscavenged in the
3018  * newspace generation.
3019  *
3020  * To help improve the efficiency, areas written are recorded by
3021  * gc_alloc() and only these scavenged. Sometimes a little more will be
3022  * scavenged, but this causes no harm. An easy check is done that the
3023  * scavenged bytes equals the number allocated in the previous
3024  * scavenge.
3025  *
3026  * Write-protected pages are not scanned except if they are marked
3027  * dont_move in which case they may have been promoted and still have
3028  * pointers to the from space.
3029  *
3030  * Write-protected pages could potentially be written by alloc however
3031  * to avoid having to handle re-scavenging of write-protected pages
3032  * gc_alloc() does not write to write-protected pages.
3033  *
3034  * New areas of objects allocated are recorded alternatively in the two
3035  * new_areas arrays below. */
3036 static struct new_area new_areas_1[NUM_NEW_AREAS];
3037 static struct new_area new_areas_2[NUM_NEW_AREAS];
3038
3039 /* Do one full scan of the new space generation. This is not enough to
3040  * complete the job as new objects may be added to the generation in
3041  * the process which are not scavenged. */
3042 static void
3043 scavenge_newspace_generation_one_scan(generation_index_t generation)
3044 {
3045     page_index_t i;
3046
3047     FSHOW((stderr,
3048            "/starting one full scan of newspace generation %d\n",
3049            generation));
3050     for (i = 0; i < last_free_page; i++) {
3051         /* Note that this skips over open regions when it encounters them. */
3052         if (page_boxed_p(i)
3053             && (page_table[i].bytes_used != 0)
3054             && (page_table[i].gen == generation)
3055             && ((page_table[i].write_protected == 0)
3056                 /* (This may be redundant as write_protected is now
3057                  * cleared before promotion.) */
3058                 || (page_table[i].dont_move == 1))) {
3059             page_index_t last_page;
3060             int all_wp=1;
3061
3062             /* The scavenge will start at the region_start_offset of
3063              * page i.
3064              *
3065              * We need to find the full extent of this contiguous
3066              * block in case objects span pages.
3067              *
3068              * Now work forward until the end of this contiguous area
3069              * is found. A small area is preferred as there is a
3070              * better chance of its pages being write-protected. */
3071             for (last_page = i; ;last_page++) {
3072                 /* If all pages are write-protected and movable,
3073                  * then no need to scavenge */
3074                 all_wp=all_wp && page_table[last_page].write_protected &&
3075                     !page_table[last_page].dont_move;
3076
3077                 /* Check whether this is the last page in this
3078                  * contiguous block */
3079                 if ((page_table[last_page].bytes_used < PAGE_BYTES)
3080                     /* Or it is PAGE_BYTES and is the last in the block */
3081                     || (!page_boxed_p(last_page+1))
3082                     || (page_table[last_page+1].bytes_used == 0)
3083                     || (page_table[last_page+1].gen != generation)
3084                     || (page_table[last_page+1].region_start_offset == 0))
3085                     break;
3086             }
3087
3088             /* Do a limited check for write-protected pages.  */
3089             if (!all_wp) {
3090                 long nwords = (((unsigned long)
3091                                (page_table[last_page].bytes_used
3092                                 + npage_bytes(last_page-i)
3093                                 + page_table[i].region_start_offset))
3094                                / N_WORD_BYTES);
3095                 new_areas_ignore_page = last_page;
3096
3097                 scavenge(page_region_start(i), nwords);
3098
3099             }
3100             i = last_page;
3101         }
3102     }
3103     FSHOW((stderr,
3104            "/done with one full scan of newspace generation %d\n",
3105            generation));
3106 }
3107
3108 /* Do a complete scavenge of the newspace generation. */
3109 static void
3110 scavenge_newspace_generation(generation_index_t generation)
3111 {
3112     long i;
3113
3114     /* the new_areas array currently being written to by gc_alloc() */
3115     struct new_area (*current_new_areas)[] = &new_areas_1;
3116     long current_new_areas_index;
3117
3118     /* the new_areas created by the previous scavenge cycle */
3119     struct new_area (*previous_new_areas)[] = NULL;
3120     long previous_new_areas_index;
3121
3122     /* Flush the current regions updating the tables. */
3123     gc_alloc_update_all_page_tables();
3124
3125     /* Turn on the recording of new areas by gc_alloc(). */
3126     new_areas = current_new_areas;
3127     new_areas_index = 0;
3128
3129     /* Don't need to record new areas that get scavenged anyway during
3130      * scavenge_newspace_generation_one_scan. */
3131     record_new_objects = 1;
3132
3133     /* Start with a full scavenge. */
3134     scavenge_newspace_generation_one_scan(generation);
3135
3136     /* Record all new areas now. */
3137     record_new_objects = 2;
3138
3139     /* Give a chance to weak hash tables to make other objects live.
3140      * FIXME: The algorithm implemented here for weak hash table gcing
3141      * is O(W^2+N) as Bruno Haible warns in
3142      * http://www.haible.de/bruno/papers/cs/weak/WeakDatastructures-writeup.html
3143      * see "Implementation 2". */
3144     scav_weak_hash_tables();
3145
3146     /* Flush the current regions updating the tables. */
3147     gc_alloc_update_all_page_tables();
3148
3149     /* Grab new_areas_index. */
3150     current_new_areas_index = new_areas_index;
3151
3152     /*FSHOW((stderr,
3153              "The first scan is finished; current_new_areas_index=%d.\n",
3154              current_new_areas_index));*/
3155
3156     while (current_new_areas_index > 0) {
3157         /* Move the current to the previous new areas */
3158         previous_new_areas = current_new_areas;
3159         previous_new_areas_index = current_new_areas_index;
3160
3161         /* Scavenge all the areas in previous new areas. Any new areas
3162          * allocated are saved in current_new_areas. */
3163
3164         /* Allocate an array for current_new_areas; alternating between
3165          * new_areas_1 and 2 */
3166         if (previous_new_areas == &new_areas_1)
3167             current_new_areas = &new_areas_2;
3168         else
3169             current_new_areas = &new_areas_1;
3170
3171         /* Set up for gc_alloc(). */
3172         new_areas = current_new_areas;
3173         new_areas_index = 0;
3174
3175         /* Check whether previous_new_areas had overflowed. */
3176         if (previous_new_areas_index >= NUM_NEW_AREAS) {
3177
3178             /* New areas of objects allocated have been lost so need to do a
3179              * full scan to be sure! If this becomes a problem try
3180              * increasing NUM_NEW_AREAS. */
3181             if (gencgc_verbose) {
3182                 SHOW("new_areas overflow, doing full scavenge");
3183             }
3184
3185             /* Don't need to record new areas that get scavenged
3186              * anyway during scavenge_newspace_generation_one_scan. */
3187             record_new_objects = 1;
3188
3189             scavenge_newspace_generation_one_scan(generation);
3190
3191             /* Record all new areas now. */
3192             record_new_objects = 2;
3193
3194             scav_weak_hash_tables();
3195
3196             /* Flush the current regions updating the tables. */
3197             gc_alloc_update_all_page_tables();
3198
3199         } else {
3200
3201             /* Work through previous_new_areas. */
3202             for (i = 0; i < previous_new_areas_index; i++) {
3203                 page_index_t page = (*previous_new_areas)[i].page;
3204                 size_t offset = (*previous_new_areas)[i].offset;
3205                 size_t size = (*previous_new_areas)[i].size / N_WORD_BYTES;
3206                 gc_assert((*previous_new_areas)[i].size % N_WORD_BYTES == 0);
3207                 scavenge(page_address(page)+offset, size);
3208             }
3209
3210             scav_weak_hash_tables();
3211
3212             /* Flush the current regions updating the tables. */
3213             gc_alloc_update_all_page_tables();
3214         }
3215
3216         current_new_areas_index = new_areas_index;
3217
3218         /*FSHOW((stderr,
3219                  "The re-scan has finished; current_new_areas_index=%d.\n",
3220                  current_new_areas_index));*/
3221     }
3222
3223     /* Turn off recording of areas allocated by gc_alloc(). */
3224     record_new_objects = 0;
3225
3226 #if SC_NS_GEN_CK
3227     /* Check that none of the write_protected pages in this generation
3228      * have been written to. */
3229     for (i = 0; i < page_table_pages; i++) {
3230         if (page_allocated_p(i)
3231             && (page_table[i].bytes_used != 0)
3232             && (page_table[i].gen == generation)
3233             && (page_table[i].write_protected_cleared != 0)
3234             && (page_table[i].dont_move == 0)) {
3235             lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d\n",
3236                  i, generation, page_table[i].dont_move);
3237         }
3238     }
3239 #endif
3240 }
3241 \f
3242 /* Un-write-protect all the pages in from_space. This is done at the
3243  * start of a GC else there may be many page faults while scavenging
3244  * the newspace (I've seen drive the system time to 99%). These pages
3245  * would need to be unprotected anyway before unmapping in
3246  * free_oldspace; not sure what effect this has on paging.. */
3247 static void
3248 unprotect_oldspace(void)
3249 {
3250     page_index_t i;
3251
3252     for (i = 0; i < last_free_page; i++) {
3253         if (page_allocated_p(i)
3254             && (page_table[i].bytes_used != 0)
3255             && (page_table[i].gen == from_space)) {
3256             void *page_start;
3257
3258             page_start = (void *)page_address(i);
3259
3260             /* Remove any write-protection. We should be able to rely
3261              * on the write-protect flag to avoid redundant calls. */
3262             if (page_table[i].write_protected) {
3263                 os_protect(page_start, PAGE_BYTES, OS_VM_PROT_ALL);
3264                 page_table[i].write_protected = 0;
3265             }
3266         }
3267     }
3268 }
3269
3270 /* Work through all the pages and free any in from_space. This
3271  * assumes that all objects have been copied or promoted to an older
3272  * generation. Bytes_allocated and the generation bytes_allocated
3273  * counter are updated. The number of bytes freed is returned. */
3274 static unsigned long
3275 free_oldspace(void)
3276 {
3277     unsigned long bytes_freed = 0;
3278     page_index_t first_page, last_page;
3279
3280     first_page = 0;
3281
3282     do {
3283         /* Find a first page for the next region of pages. */
3284         while ((first_page < last_free_page)
3285                && (page_free_p(first_page)
3286                    || (page_table[first_page].bytes_used == 0)
3287                    || (page_table[first_page].gen != from_space)))
3288             first_page++;
3289
3290         if (first_page >= last_free_page)
3291             break;
3292
3293         /* Find the last page of this region. */
3294         last_page = first_page;
3295
3296         do {
3297             /* Free the page. */
3298             bytes_freed += page_table[last_page].bytes_used;
3299             generations[page_table[last_page].gen].bytes_allocated -=
3300                 page_table[last_page].bytes_used;
3301             page_table[last_page].allocated = FREE_PAGE_FLAG;
3302             page_table[last_page].bytes_used = 0;
3303
3304             /* Remove any write-protection. We should be able to rely
3305              * on the write-protect flag to avoid redundant calls. */
3306             {
3307                 void  *page_start = (void *)page_address(last_page);
3308
3309                 if (page_table[last_page].write_protected) {
3310                     os_protect(page_start, PAGE_BYTES, OS_VM_PROT_ALL);
3311                     page_table[last_page].write_protected = 0;
3312                 }
3313             }
3314             last_page++;
3315         }
3316         while ((last_page < last_free_page)
3317                && page_allocated_p(last_page)
3318                && (page_table[last_page].bytes_used != 0)
3319                && (page_table[last_page].gen == from_space));
3320
3321 #ifdef READ_PROTECT_FREE_PAGES
3322         os_protect(page_address(first_page),
3323                    npage_bytes(last_page-first_page),
3324                    OS_VM_PROT_NONE);
3325 #endif
3326         first_page = last_page;
3327     } while (first_page < last_free_page);
3328
3329     bytes_allocated -= bytes_freed;
3330     return bytes_freed;
3331 }
3332 \f
3333 #if 0
3334 /* Print some information about a pointer at the given address. */
3335 static void
3336 print_ptr(lispobj *addr)
3337 {
3338     /* If addr is in the dynamic space then out the page information. */
3339     page_index_t pi1 = find_page_index((void*)addr);
3340
3341     if (pi1 != -1)
3342         fprintf(stderr,"  %x: page %d  alloc %d  gen %d  bytes_used %d  offset %lu  dont_move %d\n",
3343                 (unsigned long) addr,
3344                 pi1,
3345                 page_table[pi1].allocated,
3346                 page_table[pi1].gen,
3347                 page_table[pi1].bytes_used,
3348                 page_table[pi1].region_start_offset,
3349                 page_table[pi1].dont_move);
3350     fprintf(stderr,"  %x %x %x %x (%x) %x %x %x %x\n",
3351             *(addr-4),
3352             *(addr-3),
3353             *(addr-2),
3354             *(addr-1),
3355             *(addr-0),
3356             *(addr+1),
3357             *(addr+2),
3358             *(addr+3),
3359             *(addr+4));
3360 }
3361 #endif
3362
3363 static void
3364 verify_space(lispobj *start, size_t words)
3365 {
3366     int is_in_dynamic_space = (find_page_index((void*)start) != -1);
3367     int is_in_readonly_space =
3368         (READ_ONLY_SPACE_START <= (unsigned long)start &&
3369          (unsigned long)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3370
3371     while (words > 0) {
3372         size_t count = 1;
3373         lispobj thing = *(lispobj*)start;
3374
3375         if (is_lisp_pointer(thing)) {
3376             page_index_t page_index = find_page_index((void*)thing);
3377             long to_readonly_space =
3378                 (READ_ONLY_SPACE_START <= thing &&
3379                  thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3380             long to_static_space =
3381                 (STATIC_SPACE_START <= thing &&
3382                  thing < SymbolValue(STATIC_SPACE_FREE_POINTER,0));
3383
3384             /* Does it point to the dynamic space? */
3385             if (page_index != -1) {
3386                 /* If it's within the dynamic space it should point to a used
3387                  * page. XX Could check the offset too. */
3388                 if (page_allocated_p(page_index)
3389                     && (page_table[page_index].bytes_used == 0))
3390                     lose ("Ptr %x @ %x sees free page.\n", thing, start);
3391                 /* Check that it doesn't point to a forwarding pointer! */
3392                 if (*((lispobj *)native_pointer(thing)) == 0x01) {
3393                     lose("Ptr %x @ %x sees forwarding ptr.\n", thing, start);
3394                 }
3395                 /* Check that its not in the RO space as it would then be a
3396                  * pointer from the RO to the dynamic space. */
3397                 if (is_in_readonly_space) {
3398                     lose("ptr to dynamic space %x from RO space %x\n",
3399                          thing, start);
3400                 }
3401                 /* Does it point to a plausible object? This check slows
3402                  * it down a lot (so it's commented out).
3403                  *
3404                  * "a lot" is serious: it ate 50 minutes cpu time on
3405                  * my duron 950 before I came back from lunch and
3406                  * killed it.
3407                  *
3408                  *   FIXME: Add a variable to enable this
3409                  * dynamically. */
3410                 /*
3411                 if (!possibly_valid_dynamic_space_pointer((lispobj *)thing)) {
3412                     lose("ptr %x to invalid object %x\n", thing, start);
3413                 }
3414                 */
3415             } else {
3416                 /* Verify that it points to another valid space. */
3417                 if (!to_readonly_space && !to_static_space) {
3418                     lose("Ptr %x @ %x sees junk.\n", thing, start);
3419                 }
3420             }
3421         } else {
3422             if (!(fixnump(thing))) {
3423                 /* skip fixnums */
3424                 switch(widetag_of(*start)) {
3425
3426                     /* boxed objects */
3427                 case SIMPLE_VECTOR_WIDETAG:
3428                 case RATIO_WIDETAG:
3429                 case COMPLEX_WIDETAG:
3430                 case SIMPLE_ARRAY_WIDETAG:
3431                 case COMPLEX_BASE_STRING_WIDETAG:
3432 #ifdef COMPLEX_CHARACTER_STRING_WIDETAG
3433                 case COMPLEX_CHARACTER_STRING_WIDETAG:
3434 #endif
3435                 case COMPLEX_VECTOR_NIL_WIDETAG:
3436                 case COMPLEX_BIT_VECTOR_WIDETAG:
3437                 case COMPLEX_VECTOR_WIDETAG:
3438                 case COMPLEX_ARRAY_WIDETAG:
3439                 case CLOSURE_HEADER_WIDETAG:
3440                 case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
3441                 case VALUE_CELL_HEADER_WIDETAG:
3442                 case SYMBOL_HEADER_WIDETAG:
3443                 case CHARACTER_WIDETAG:
3444 #if N_WORD_BITS == 64
3445                 case SINGLE_FLOAT_WIDETAG:
3446 #endif
3447                 case UNBOUND_MARKER_WIDETAG:
3448                 case FDEFN_WIDETAG:
3449                     count = 1;
3450                     break;
3451
3452                 case INSTANCE_HEADER_WIDETAG:
3453                     {
3454                         lispobj nuntagged;
3455                         long ntotal = HeaderValue(thing);
3456                         lispobj layout = ((struct instance *)start)->slots[0];
3457                         if (!layout) {
3458                             count = 1;
3459                             break;
3460                         }
3461                         nuntagged = ((struct layout *)
3462                                      native_pointer(layout))->n_untagged_slots;
3463                         verify_space(start + 1,
3464                                      ntotal - fixnum_value(nuntagged));
3465                         count = ntotal + 1;
3466                         break;
3467                     }
3468                 case CODE_HEADER_WIDETAG:
3469                     {
3470                         lispobj object = *start;
3471                         struct code *code;
3472                         long nheader_words, ncode_words, nwords;
3473                         lispobj fheaderl;
3474                         struct simple_fun *fheaderp;
3475
3476                         code = (struct code *) start;
3477
3478                         /* Check that it's not in the dynamic space.
3479                          * FIXME: Isn't is supposed to be OK for code
3480                          * objects to be in the dynamic space these days? */
3481                         if (is_in_dynamic_space
3482                             /* It's ok if it's byte compiled code. The trace
3483                              * table offset will be a fixnum if it's x86
3484                              * compiled code - check.
3485                              *
3486                              * FIXME: #^#@@! lack of abstraction here..
3487                              * This line can probably go away now that
3488                              * there's no byte compiler, but I've got
3489                              * too much to worry about right now to try
3490                              * to make sure. -- WHN 2001-10-06 */
3491                             && fixnump(code->trace_table_offset)
3492                             /* Only when enabled */
3493                             && verify_dynamic_code_check) {
3494                             FSHOW((stderr,
3495                                    "/code object at %x in the dynamic space\n",
3496                                    start));
3497                         }
3498
3499                         ncode_words = fixnum_value(code->code_size);
3500                         nheader_words = HeaderValue(object);
3501                         nwords = ncode_words + nheader_words;
3502                         nwords = CEILING(nwords, 2);
3503                         /* Scavenge the boxed section of the code data block */
3504                         verify_space(start + 1, nheader_words - 1);
3505
3506                         /* Scavenge the boxed section of each function
3507                          * object in the code data block. */
3508                         fheaderl = code->entry_points;
3509                         while (fheaderl != NIL) {
3510                             fheaderp =
3511                                 (struct simple_fun *) native_pointer(fheaderl);
3512                             gc_assert(widetag_of(fheaderp->header) ==
3513                                       SIMPLE_FUN_HEADER_WIDETAG);
3514                             verify_space(&fheaderp->name, 1);
3515                             verify_space(&fheaderp->arglist, 1);
3516                             verify_space(&fheaderp->type, 1);
3517                             fheaderl = fheaderp->next;
3518                         }
3519                         count = nwords;
3520                         break;
3521                     }
3522
3523                     /* unboxed objects */
3524                 case BIGNUM_WIDETAG:
3525 #if N_WORD_BITS != 64
3526                 case SINGLE_FLOAT_WIDETAG:
3527 #endif
3528                 case DOUBLE_FLOAT_WIDETAG:
3529 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3530                 case LONG_FLOAT_WIDETAG:
3531 #endif
3532 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
3533                 case COMPLEX_SINGLE_FLOAT_WIDETAG:
3534 #endif
3535 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
3536                 case COMPLEX_DOUBLE_FLOAT_WIDETAG:
3537 #endif
3538 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3539                 case COMPLEX_LONG_FLOAT_WIDETAG:
3540 #endif
3541                 case SIMPLE_BASE_STRING_WIDETAG:
3542 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
3543                 case SIMPLE_CHARACTER_STRING_WIDETAG:
3544 #endif
3545                 case SIMPLE_BIT_VECTOR_WIDETAG:
3546                 case SIMPLE_ARRAY_NIL_WIDETAG:
3547                 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
3548                 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
3549                 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
3550                 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
3551                 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
3552                 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
3553 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_29_WIDETAG
3554                 case SIMPLE_ARRAY_UNSIGNED_BYTE_29_WIDETAG:
3555 #endif
3556                 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
3557                 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
3558 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_60_WIDETAG
3559                 case SIMPLE_ARRAY_UNSIGNED_BYTE_60_WIDETAG:
3560 #endif
3561 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
3562                 case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
3563 #endif
3564 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
3565                 case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
3566 #endif
3567 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
3568                 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
3569 #endif
3570 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
3571                 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
3572 #endif
3573 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG
3574                 case SIMPLE_ARRAY_SIGNED_BYTE_30_WIDETAG:
3575 #endif
3576 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
3577                 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
3578 #endif
3579 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_61_WIDETAG
3580                 case SIMPLE_ARRAY_SIGNED_BYTE_61_WIDETAG:
3581 #endif
3582 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
3583                 case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
3584 #endif
3585                 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
3586                 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
3587 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3588                 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
3589 #endif
3590 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
3591                 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
3592 #endif
3593 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
3594                 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
3595 #endif
3596 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3597                 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
3598 #endif
3599                 case SAP_WIDETAG:
3600                 case WEAK_POINTER_WIDETAG:
3601 #ifdef LUTEX_WIDETAG
3602                 case LUTEX_WIDETAG:
3603 #endif
3604 #ifdef NO_TLS_VALUE_MARKER_WIDETAG
3605                 case NO_TLS_VALUE_MARKER_WIDETAG:
3606 #endif
3607                     count = (sizetab[widetag_of(*start)])(start);
3608                     break;
3609
3610                 default:
3611                     lose("Unhandled widetag 0x%x at 0x%x\n",
3612                          widetag_of(*start), start);
3613                 }
3614             }
3615         }
3616         start += count;
3617         words -= count;
3618     }
3619 }
3620
3621 static void
3622 verify_gc(void)
3623 {
3624     /* FIXME: It would be nice to make names consistent so that
3625      * foo_size meant size *in* *bytes* instead of size in some
3626      * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
3627      * Some counts of lispobjs are called foo_count; it might be good
3628      * to grep for all foo_size and rename the appropriate ones to
3629      * foo_count. */
3630     long read_only_space_size =
3631         (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0)
3632         - (lispobj*)READ_ONLY_SPACE_START;
3633     long static_space_size =
3634         (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0)
3635         - (lispobj*)STATIC_SPACE_START;
3636     struct thread *th;
3637     for_each_thread(th) {
3638     long binding_stack_size =
3639         (lispobj*)get_binding_stack_pointer(th)
3640             - (lispobj*)th->binding_stack_start;
3641         verify_space(th->binding_stack_start, binding_stack_size);
3642     }
3643     verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
3644     verify_space((lispobj*)STATIC_SPACE_START   , static_space_size);
3645 }
3646
3647 static void
3648 verify_generation(generation_index_t generation)
3649 {
3650     page_index_t i;
3651
3652     for (i = 0; i < last_free_page; i++) {
3653         if (page_allocated_p(i)
3654             && (page_table[i].bytes_used != 0)
3655             && (page_table[i].gen == generation)) {
3656             page_index_t last_page;
3657             int region_allocation = page_table[i].allocated;
3658
3659             /* This should be the start of a contiguous block */
3660             gc_assert(page_table[i].region_start_offset == 0);
3661
3662             /* Need to find the full extent of this contiguous block in case
3663                objects span pages. */
3664
3665             /* Now work forward until the end of this contiguous area is
3666                found. */
3667             for (last_page = i; ;last_page++)
3668                 /* Check whether this is the last page in this contiguous
3669                  * block. */
3670                 if ((page_table[last_page].bytes_used < PAGE_BYTES)
3671                     /* Or it is PAGE_BYTES and is the last in the block */
3672                     || (page_table[last_page+1].allocated != region_allocation)
3673                     || (page_table[last_page+1].bytes_used == 0)
3674                     || (page_table[last_page+1].gen != generation)
3675                     || (page_table[last_page+1].region_start_offset == 0))
3676                     break;
3677
3678             verify_space(page_address(i),
3679                          ((unsigned long)
3680                           (page_table[last_page].bytes_used
3681                            + npage_bytes(last_page-i)))
3682                          / N_WORD_BYTES);
3683             i = last_page;
3684         }
3685     }
3686 }
3687
3688 /* Check that all the free space is zero filled. */
3689 static void
3690 verify_zero_fill(void)
3691 {
3692     page_index_t page;
3693
3694     for (page = 0; page < last_free_page; page++) {
3695         if (page_free_p(page)) {
3696             /* The whole page should be zero filled. */
3697             long *start_addr = (long *)page_address(page);
3698             long size = 1024;
3699             long i;
3700             for (i = 0; i < size; i++) {
3701                 if (start_addr[i] != 0) {
3702                     lose("free page not zero at %x\n", start_addr + i);
3703                 }
3704             }
3705         } else {
3706             long free_bytes = PAGE_BYTES - page_table[page].bytes_used;
3707             if (free_bytes > 0) {
3708                 long *start_addr = (long *)((unsigned long)page_address(page)
3709                                           + page_table[page].bytes_used);
3710                 long size = free_bytes / N_WORD_BYTES;
3711                 long i;
3712                 for (i = 0; i < size; i++) {
3713                     if (start_addr[i] != 0) {
3714                         lose("free region not zero at %x\n", start_addr + i);
3715                     }
3716                 }
3717             }
3718         }
3719     }
3720 }
3721
3722 /* External entry point for verify_zero_fill */
3723 void
3724 gencgc_verify_zero_fill(void)
3725 {
3726     /* Flush the alloc regions updating the tables. */
3727     gc_alloc_update_all_page_tables();
3728     SHOW("verifying zero fill");
3729     verify_zero_fill();
3730 }
3731
3732 static void
3733 verify_dynamic_space(void)
3734 {
3735     generation_index_t i;
3736
3737     for (i = 0; i <= HIGHEST_NORMAL_GENERATION; i++)
3738         verify_generation(i);
3739
3740     if (gencgc_enable_verify_zero_fill)
3741         verify_zero_fill();
3742 }
3743 \f
3744 /* Write-protect all the dynamic boxed pages in the given generation. */
3745 static void
3746 write_protect_generation_pages(generation_index_t generation)
3747 {
3748     page_index_t start;
3749
3750     gc_assert(generation < SCRATCH_GENERATION);
3751
3752     for (start = 0; start < last_free_page; start++) {
3753         if (protect_page_p(start, generation)) {
3754             void *page_start;
3755             page_index_t last;
3756
3757             /* Note the page as protected in the page tables. */
3758             page_table[start].write_protected = 1;
3759
3760             for (last = start + 1; last < last_free_page; last++) {
3761                 if (!protect_page_p(last, generation))
3762                   break;
3763                 page_table[last].write_protected = 1;
3764             }
3765
3766             page_start = (void *)page_address(start);
3767
3768             os_protect(page_start,
3769                        npage_bytes(last - start),
3770                        OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
3771
3772             start = last;
3773         }
3774     }
3775
3776     if (gencgc_verbose > 1) {
3777         FSHOW((stderr,
3778                "/write protected %d of %d pages in generation %d\n",
3779                count_write_protect_generation_pages(generation),
3780                count_generation_pages(generation),
3781                generation));
3782     }
3783 }
3784
3785 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
3786
3787 static void
3788 scavenge_control_stack()
3789 {
3790     unsigned long control_stack_size;
3791
3792     /* This is going to be a big problem when we try to port threads
3793      * to PPC... CLH */
3794     struct thread *th = arch_os_get_current_thread();
3795     lispobj *control_stack =
3796         (lispobj *)(th->control_stack_start);
3797
3798     control_stack_size = current_control_stack_pointer - control_stack;
3799     scavenge(control_stack, control_stack_size);
3800 }
3801
3802 /* Scavenging Interrupt Contexts */
3803
3804 static int boxed_registers[] = BOXED_REGISTERS;
3805
3806 static void
3807 scavenge_interrupt_context(os_context_t * context)
3808 {
3809     int i;
3810
3811 #ifdef reg_LIP
3812     unsigned long lip;
3813     unsigned long lip_offset;
3814     int lip_register_pair;
3815 #endif
3816     unsigned long pc_code_offset;
3817
3818 #ifdef ARCH_HAS_LINK_REGISTER
3819     unsigned long lr_code_offset;
3820 #endif
3821 #ifdef ARCH_HAS_NPC_REGISTER
3822     unsigned long npc_code_offset;
3823 #endif
3824
3825 #ifdef reg_LIP
3826     /* Find the LIP's register pair and calculate it's offset */
3827     /* before we scavenge the context. */
3828
3829     /*
3830      * I (RLT) think this is trying to find the boxed register that is
3831      * closest to the LIP address, without going past it.  Usually, it's
3832      * reg_CODE or reg_LRA.  But sometimes, nothing can be found.
3833      */
3834     lip = *os_context_register_addr(context, reg_LIP);
3835     lip_offset = 0x7FFFFFFF;
3836     lip_register_pair = -1;
3837     for (i = 0; i < (sizeof(boxed_registers) / sizeof(int)); i++) {
3838         unsigned long reg;
3839         long offset;
3840         int index;
3841
3842         index = boxed_registers[i];
3843         reg = *os_context_register_addr(context, index);
3844         if ((reg & ~((1L<<N_LOWTAG_BITS)-1)) <= lip) {
3845             offset = lip - reg;
3846             if (offset < lip_offset) {
3847                 lip_offset = offset;
3848                 lip_register_pair = index;
3849             }
3850         }
3851     }
3852 #endif /* reg_LIP */
3853
3854     /* Compute the PC's offset from the start of the CODE */
3855     /* register. */
3856     pc_code_offset = *os_context_pc_addr(context)
3857         - *os_context_register_addr(context, reg_CODE);
3858 #ifdef ARCH_HAS_NPC_REGISTER
3859     npc_code_offset = *os_context_npc_addr(context)
3860         - *os_context_register_addr(context, reg_CODE);
3861 #endif /* ARCH_HAS_NPC_REGISTER */
3862
3863 #ifdef ARCH_HAS_LINK_REGISTER
3864     lr_code_offset =
3865         *os_context_lr_addr(context) -
3866         *os_context_register_addr(context, reg_CODE);
3867 #endif
3868
3869     /* Scanvenge all boxed registers in the context. */
3870     for (i = 0; i < (sizeof(boxed_registers) / sizeof(int)); i++) {
3871         int index;
3872         lispobj foo;
3873
3874         index = boxed_registers[i];
3875         foo = *os_context_register_addr(context, index);
3876         scavenge(&foo, 1);
3877         *os_context_register_addr(context, index) = foo;
3878
3879         scavenge((lispobj*) &(*os_context_register_addr(context, index)), 1);
3880     }
3881
3882 #ifdef reg_LIP
3883     /* Fix the LIP */
3884
3885     /*
3886      * But what happens if lip_register_pair is -1?
3887      * *os_context_register_addr on Solaris (see
3888      * solaris_register_address in solaris-os.c) will return
3889      * &context->uc_mcontext.gregs[2]. But gregs[2] is REG_nPC. Is
3890      * that what we really want? My guess is that that is not what we
3891      * want, so if lip_register_pair is -1, we don't touch reg_LIP at
3892      * all. But maybe it doesn't really matter if LIP is trashed?
3893      */
3894     if (lip_register_pair >= 0) {
3895         *os_context_register_addr(context, reg_LIP) =
3896             *os_context_register_addr(context, lip_register_pair)
3897             + lip_offset;
3898     }
3899 #endif /* reg_LIP */
3900
3901     /* Fix the PC if it was in from space */
3902     if (from_space_p(*os_context_pc_addr(context)))
3903         *os_context_pc_addr(context) =
3904             *os_context_register_addr(context, reg_CODE) + pc_code_offset;
3905
3906 #ifdef ARCH_HAS_LINK_REGISTER
3907     /* Fix the LR ditto; important if we're being called from
3908      * an assembly routine that expects to return using blr, otherwise
3909      * harmless */
3910     if (from_space_p(*os_context_lr_addr(context)))
3911         *os_context_lr_addr(context) =
3912             *os_context_register_addr(context, reg_CODE) + lr_code_offset;
3913 #endif
3914
3915 #ifdef ARCH_HAS_NPC_REGISTER
3916     if (from_space_p(*os_context_npc_addr(context)))
3917         *os_context_npc_addr(context) =
3918             *os_context_register_addr(context, reg_CODE) + npc_code_offset;
3919 #endif /* ARCH_HAS_NPC_REGISTER */
3920 }
3921
3922 void
3923 scavenge_interrupt_contexts(void)
3924 {
3925     int i, index;
3926     os_context_t *context;
3927
3928     struct thread *th=arch_os_get_current_thread();
3929
3930     index = fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,0));
3931
3932 #if defined(DEBUG_PRINT_CONTEXT_INDEX)
3933     printf("Number of active contexts: %d\n", index);
3934 #endif
3935
3936     for (i = 0; i < index; i++) {
3937         context = th->interrupt_contexts[i];
3938         scavenge_interrupt_context(context);
3939     }
3940 }
3941
3942 #endif
3943
3944 #if defined(LISP_FEATURE_SB_THREAD)
3945 static void
3946 preserve_context_registers (os_context_t *c)
3947 {
3948     void **ptr;
3949     /* On Darwin the signal context isn't a contiguous block of memory,
3950      * so just preserve_pointering its contents won't be sufficient.
3951      */
3952 #if defined(LISP_FEATURE_DARWIN)
3953 #if defined LISP_FEATURE_X86
3954     preserve_pointer((void*)*os_context_register_addr(c,reg_EAX));
3955     preserve_pointer((void*)*os_context_register_addr(c,reg_ECX));
3956     preserve_pointer((void*)*os_context_register_addr(c,reg_EDX));
3957     preserve_pointer((void*)*os_context_register_addr(c,reg_EBX));
3958     preserve_pointer((void*)*os_context_register_addr(c,reg_ESI));
3959     preserve_pointer((void*)*os_context_register_addr(c,reg_EDI));
3960     preserve_pointer((void*)*os_context_pc_addr(c));
3961 #elif defined LISP_FEATURE_X86_64
3962     preserve_pointer((void*)*os_context_register_addr(c,reg_RAX));
3963     preserve_pointer((void*)*os_context_register_addr(c,reg_RCX));
3964     preserve_pointer((void*)*os_context_register_addr(c,reg_RDX));
3965     preserve_pointer((void*)*os_context_register_addr(c,reg_RBX));
3966     preserve_pointer((void*)*os_context_register_addr(c,reg_RSI));
3967     preserve_pointer((void*)*os_context_register_addr(c,reg_RDI));
3968     preserve_pointer((void*)*os_context_register_addr(c,reg_R8));
3969     preserve_pointer((void*)*os_context_register_addr(c,reg_R9));
3970     preserve_pointer((void*)*os_context_register_addr(c,reg_R10));
3971     preserve_pointer((void*)*os_context_register_addr(c,reg_R11));
3972     preserve_pointer((void*)*os_context_register_addr(c,reg_R12));
3973     preserve_pointer((void*)*os_context_register_addr(c,reg_R13));
3974     preserve_pointer((void*)*os_context_register_addr(c,reg_R14));
3975     preserve_pointer((void*)*os_context_register_addr(c,reg_R15));
3976     preserve_pointer((void*)*os_context_pc_addr(c));
3977 #else
3978     #error "preserve_context_registers needs to be tweaked for non-x86 Darwin"
3979 #endif
3980 #endif
3981     for(ptr = ((void **)(c+1))-1; ptr>=(void **)c; ptr--) {
3982         preserve_pointer(*ptr);
3983     }
3984 }
3985 #endif
3986
3987 /* Garbage collect a generation. If raise is 0 then the remains of the
3988  * generation are not raised to the next generation. */
3989 static void
3990 garbage_collect_generation(generation_index_t generation, int raise)
3991 {
3992     unsigned long bytes_freed;
3993     page_index_t i;
3994     unsigned long static_space_size;
3995 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
3996     struct thread *th;
3997 #endif
3998     gc_assert(generation <= HIGHEST_NORMAL_GENERATION);
3999
4000     /* The oldest generation can't be raised. */
4001     gc_assert((generation != HIGHEST_NORMAL_GENERATION) || (raise == 0));
4002
4003     /* Check if weak hash tables were processed in the previous GC. */
4004     gc_assert(weak_hash_tables == NULL);
4005
4006     /* Initialize the weak pointer list. */
4007     weak_pointers = NULL;
4008
4009 #ifdef LUTEX_WIDETAG
4010     unmark_lutexes(generation);
4011 #endif
4012
4013     /* When a generation is not being raised it is transported to a
4014      * temporary generation (NUM_GENERATIONS), and lowered when
4015      * done. Set up this new generation. There should be no pages
4016      * allocated to it yet. */
4017     if (!raise) {
4018          gc_assert(generations[SCRATCH_GENERATION].bytes_allocated == 0);
4019     }
4020
4021     /* Set the global src and dest. generations */
4022     from_space = generation;
4023     if (raise)
4024         new_space = generation+1;
4025     else
4026         new_space = SCRATCH_GENERATION;
4027
4028     /* Change to a new space for allocation, resetting the alloc_start_page */
4029     gc_alloc_generation = new_space;
4030     generations[new_space].alloc_start_page = 0;
4031     generations[new_space].alloc_unboxed_start_page = 0;
4032     generations[new_space].alloc_large_start_page = 0;
4033     generations[new_space].alloc_large_unboxed_start_page = 0;
4034
4035     /* Before any pointers are preserved, the dont_move flags on the
4036      * pages need to be cleared. */
4037     for (i = 0; i < last_free_page; i++)
4038         if(page_table[i].gen==from_space)
4039             page_table[i].dont_move = 0;
4040
4041     /* Un-write-protect the old-space pages. This is essential for the
4042      * promoted pages as they may contain pointers into the old-space
4043      * which need to be scavenged. It also helps avoid unnecessary page
4044      * faults as forwarding pointers are written into them. They need to
4045      * be un-protected anyway before unmapping later. */
4046     unprotect_oldspace();
4047
4048     /* Scavenge the stacks' conservative roots. */
4049
4050     /* there are potentially two stacks for each thread: the main
4051      * stack, which may contain Lisp pointers, and the alternate stack.
4052      * We don't ever run Lisp code on the altstack, but it may
4053      * host a sigcontext with lisp objects in it */
4054
4055     /* what we need to do: (1) find the stack pointer for the main
4056      * stack; scavenge it (2) find the interrupt context on the
4057      * alternate stack that might contain lisp values, and scavenge
4058      * that */
4059
4060     /* we assume that none of the preceding applies to the thread that
4061      * initiates GC.  If you ever call GC from inside an altstack
4062      * handler, you will lose. */
4063
4064 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
4065     /* And if we're saving a core, there's no point in being conservative. */
4066     if (conservative_stack) {
4067         for_each_thread(th) {
4068             void **ptr;
4069             void **esp=(void **)-1;
4070 #ifdef LISP_FEATURE_SB_THREAD
4071             long i,free;
4072             if(th==arch_os_get_current_thread()) {
4073                 /* Somebody is going to burn in hell for this, but casting
4074                  * it in two steps shuts gcc up about strict aliasing. */
4075                 esp = (void **)((void *)&raise);
4076             } else {
4077                 void **esp1;
4078                 free=fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
4079                 for(i=free-1;i>=0;i--) {
4080                     os_context_t *c=th->interrupt_contexts[i];
4081                     esp1 = (void **) *os_context_register_addr(c,reg_SP);
4082                     if (esp1>=(void **)th->control_stack_start &&
4083                         esp1<(void **)th->control_stack_end) {
4084                         if(esp1<esp) esp=esp1;
4085                         preserve_context_registers(c);
4086                     }
4087                 }
4088             }
4089 #else
4090             esp = (void **)((void *)&raise);
4091 #endif
4092             for (ptr = ((void **)th->control_stack_end)-1; ptr >= esp;  ptr--) {
4093                 preserve_pointer(*ptr);
4094             }
4095         }
4096     }
4097 #endif
4098
4099 #ifdef QSHOW
4100     if (gencgc_verbose > 1) {
4101         long num_dont_move_pages = count_dont_move_pages();
4102         fprintf(stderr,
4103                 "/non-movable pages due to conservative pointers = %d (%d bytes)\n",
4104                 num_dont_move_pages,
4105                 npage_bytes(num_dont_move_pages));
4106     }
4107 #endif
4108
4109     /* Scavenge all the rest of the roots. */
4110
4111 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
4112     /*
4113      * If not x86, we need to scavenge the interrupt context(s) and the
4114      * control stack.
4115      */
4116     scavenge_interrupt_contexts();
4117     scavenge_control_stack();
4118 #endif
4119
4120     /* Scavenge the Lisp functions of the interrupt handlers, taking
4121      * care to avoid SIG_DFL and SIG_IGN. */
4122     for (i = 0; i < NSIG; i++) {
4123         union interrupt_handler handler = interrupt_handlers[i];
4124         if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
4125             !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
4126             scavenge((lispobj *)(interrupt_handlers + i), 1);
4127         }
4128     }
4129     /* Scavenge the binding stacks. */
4130     {
4131         struct thread *th;
4132         for_each_thread(th) {
4133             long len= (lispobj *)get_binding_stack_pointer(th) -
4134                 th->binding_stack_start;
4135             scavenge((lispobj *) th->binding_stack_start,len);
4136 #ifdef LISP_FEATURE_SB_THREAD
4137             /* do the tls as well */
4138             len=fixnum_value(SymbolValue(FREE_TLS_INDEX,0)) -
4139                 (sizeof (struct thread))/(sizeof (lispobj));
4140             scavenge((lispobj *) (th+1),len);
4141 #endif
4142         }
4143     }
4144
4145     /* The original CMU CL code had scavenge-read-only-space code
4146      * controlled by the Lisp-level variable
4147      * *SCAVENGE-READ-ONLY-SPACE*. It was disabled by default, and it
4148      * wasn't documented under what circumstances it was useful or
4149      * safe to turn it on, so it's been turned off in SBCL. If you
4150      * want/need this functionality, and can test and document it,
4151      * please submit a patch. */
4152 #if 0
4153     if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
4154         unsigned long read_only_space_size =
4155             (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
4156             (lispobj*)READ_ONLY_SPACE_START;
4157         FSHOW((stderr,
4158                "/scavenge read only space: %d bytes\n",
4159                read_only_space_size * sizeof(lispobj)));
4160         scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
4161     }
4162 #endif
4163
4164     /* Scavenge static space. */
4165     static_space_size =
4166         (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0) -
4167         (lispobj *)STATIC_SPACE_START;
4168     if (gencgc_verbose > 1) {
4169         FSHOW((stderr,
4170                "/scavenge static space: %d bytes\n",
4171                static_space_size * sizeof(lispobj)));
4172     }
4173     scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
4174
4175     /* All generations but the generation being GCed need to be
4176      * scavenged. The new_space generation needs special handling as
4177      * objects may be moved in - it is handled separately below. */
4178     scavenge_generations(generation+1, PSEUDO_STATIC_GENERATION);
4179
4180     /* Finally scavenge the new_space generation. Keep going until no
4181      * more objects are moved into the new generation */
4182     scavenge_newspace_generation(new_space);
4183
4184     /* FIXME: I tried reenabling this check when debugging unrelated
4185      * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
4186      * Since the current GC code seems to work well, I'm guessing that
4187      * this debugging code is just stale, but I haven't tried to
4188      * figure it out. It should be figured out and then either made to
4189      * work or just deleted. */
4190 #define RESCAN_CHECK 0
4191 #if RESCAN_CHECK
4192     /* As a check re-scavenge the newspace once; no new objects should
4193      * be found. */
4194     {
4195         long old_bytes_allocated = bytes_allocated;
4196         long bytes_allocated;
4197
4198         /* Start with a full scavenge. */
4199         scavenge_newspace_generation_one_scan(new_space);
4200
4201         /* Flush the current regions, updating the tables. */
4202         gc_alloc_update_all_page_tables();
4203
4204         bytes_allocated = bytes_allocated - old_bytes_allocated;
4205
4206         if (bytes_allocated != 0) {
4207             lose("Rescan of new_space allocated %d more bytes.\n",
4208                  bytes_allocated);
4209         }
4210     }
4211 #endif
4212
4213     scan_weak_hash_tables();
4214     scan_weak_pointers();
4215
4216     /* Flush the current regions, updating the tables. */
4217     gc_alloc_update_all_page_tables();
4218
4219     /* Free the pages in oldspace, but not those marked dont_move. */
4220     bytes_freed = free_oldspace();
4221
4222     /* If the GC is not raising the age then lower the generation back
4223      * to its normal generation number */
4224     if (!raise) {
4225         for (i = 0; i < last_free_page; i++)
4226             if ((page_table[i].bytes_used != 0)
4227                 && (page_table[i].gen == SCRATCH_GENERATION))
4228                 page_table[i].gen = generation;
4229         gc_assert(generations[generation].bytes_allocated == 0);
4230         generations[generation].bytes_allocated =
4231             generations[SCRATCH_GENERATION].bytes_allocated;
4232         generations[SCRATCH_GENERATION].bytes_allocated = 0;
4233     }
4234
4235     /* Reset the alloc_start_page for generation. */
4236     generations[generation].alloc_start_page = 0;
4237     generations[generation].alloc_unboxed_start_page = 0;
4238     generations[generation].alloc_large_start_page = 0;
4239     generations[generation].alloc_large_unboxed_start_page = 0;
4240
4241     if (generation >= verify_gens) {
4242         if (gencgc_verbose) {
4243             SHOW("verifying");
4244         }
4245         verify_gc();
4246         verify_dynamic_space();
4247     }
4248
4249     /* Set the new gc trigger for the GCed generation. */
4250     generations[generation].gc_trigger =
4251         generations[generation].bytes_allocated
4252         + generations[generation].bytes_consed_between_gc;
4253
4254     if (raise)
4255         generations[generation].num_gc = 0;
4256     else
4257         ++generations[generation].num_gc;
4258
4259 #ifdef LUTEX_WIDETAG
4260     reap_lutexes(generation);
4261     if (raise)
4262         move_lutexes(generation, generation+1);
4263 #endif
4264 }
4265
4266 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
4267 long
4268 update_dynamic_space_free_pointer(void)
4269 {
4270     page_index_t last_page = -1, i;
4271
4272     for (i = 0; i < last_free_page; i++)
4273         if (page_allocated_p(i) && (page_table[i].bytes_used != 0))
4274             last_page = i;
4275
4276     last_free_page = last_page+1;
4277
4278     set_alloc_pointer((lispobj)(page_address(last_free_page)));
4279     return 0; /* dummy value: return something ... */
4280 }
4281
4282 static void
4283 remap_free_pages (page_index_t from, page_index_t to)
4284 {
4285     page_index_t first_page, last_page;
4286
4287     for (first_page = from; first_page <= to; first_page++) {
4288         if (page_allocated_p(first_page) ||
4289             (page_table[first_page].need_to_zero == 0)) {
4290             continue;
4291         }
4292
4293         last_page = first_page + 1;
4294         while (page_free_p(last_page) &&
4295                (last_page < to) &&
4296                (page_table[last_page].need_to_zero == 1)) {
4297             last_page++;
4298         }
4299
4300         /* There's a mysterious Solaris/x86 problem with using mmap
4301          * tricks for memory zeroing. See sbcl-devel thread
4302          * "Re: patch: standalone executable redux".
4303          */
4304 #if defined(LISP_FEATURE_SUNOS)
4305         zero_pages(first_page, last_page-1);
4306 #else
4307         zero_pages_with_mmap(first_page, last_page-1);
4308 #endif
4309
4310         first_page = last_page;
4311     }
4312 }
4313
4314 generation_index_t small_generation_limit = 1;
4315
4316 /* GC all generations newer than last_gen, raising the objects in each
4317  * to the next older generation - we finish when all generations below
4318  * last_gen are empty.  Then if last_gen is due for a GC, or if
4319  * last_gen==NUM_GENERATIONS (the scratch generation?  eh?) we GC that
4320  * too.  The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
4321  *
4322  * We stop collecting at gencgc_oldest_gen_to_gc, even if this is less than
4323  * last_gen (oh, and note that by default it is NUM_GENERATIONS-1) */
4324 void
4325 collect_garbage(generation_index_t last_gen)
4326 {
4327     generation_index_t gen = 0, i;
4328     int raise;
4329     int gen_to_wp;
4330     /* The largest value of last_free_page seen since the time
4331      * remap_free_pages was called. */
4332     static page_index_t high_water_mark = 0;
4333
4334     FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
4335
4336     gc_active_p = 1;
4337
4338     if (last_gen > HIGHEST_NORMAL_GENERATION+1) {
4339         FSHOW((stderr,
4340                "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
4341                last_gen));
4342         last_gen = 0;
4343     }
4344
4345     /* Flush the alloc regions updating the tables. */
4346     gc_alloc_update_all_page_tables();
4347
4348     /* Verify the new objects created by Lisp code. */
4349     if (pre_verify_gen_0) {
4350         FSHOW((stderr, "pre-checking generation 0\n"));
4351         verify_generation(0);
4352     }
4353
4354     if (gencgc_verbose > 1)
4355         print_generation_stats(0);
4356
4357     do {
4358         /* Collect the generation. */
4359
4360         if (gen >= gencgc_oldest_gen_to_gc) {
4361             /* Never raise the oldest generation. */
4362             raise = 0;
4363         } else {
4364             raise =
4365                 (gen < last_gen)
4366                 || (generations[gen].num_gc >= generations[gen].trigger_age);
4367         }
4368
4369         if (gencgc_verbose > 1) {
4370             FSHOW((stderr,
4371                    "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
4372                    gen,
4373                    raise,
4374                    generations[gen].bytes_allocated,
4375                    generations[gen].gc_trigger,
4376                    generations[gen].num_gc));
4377         }
4378
4379         /* If an older generation is being filled, then update its
4380          * memory age. */
4381         if (raise == 1) {
4382             generations[gen+1].cum_sum_bytes_allocated +=
4383                 generations[gen+1].bytes_allocated;
4384         }
4385
4386         garbage_collect_generation(gen, raise);
4387
4388         /* Reset the memory age cum_sum. */
4389         generations[gen].cum_sum_bytes_allocated = 0;
4390
4391         if (gencgc_verbose > 1) {
4392             FSHOW((stderr, "GC of generation %d finished:\n", gen));
4393             print_generation_stats(0);
4394         }
4395
4396         gen++;
4397     } while ((gen <= gencgc_oldest_gen_to_gc)
4398              && ((gen < last_gen)
4399                  || ((gen <= gencgc_oldest_gen_to_gc)
4400                      && raise
4401                      && (generations[gen].bytes_allocated
4402                          > generations[gen].gc_trigger)
4403                      && (gen_av_mem_age(gen)
4404                          > generations[gen].min_av_mem_age))));
4405
4406     /* Now if gen-1 was raised all generations before gen are empty.
4407      * If it wasn't raised then all generations before gen-1 are empty.
4408      *
4409      * Now objects within this gen's pages cannot point to younger
4410      * generations unless they are written to. This can be exploited
4411      * by write-protecting the pages of gen; then when younger
4412      * generations are GCed only the pages which have been written
4413      * need scanning. */
4414     if (raise)
4415         gen_to_wp = gen;
4416     else
4417         gen_to_wp = gen - 1;
4418
4419     /* There's not much point in WPing pages in generation 0 as it is
4420      * never scavenged (except promoted pages). */
4421     if ((gen_to_wp > 0) && enable_page_protection) {
4422         /* Check that they are all empty. */
4423         for (i = 0; i < gen_to_wp; i++) {
4424             if (generations[i].bytes_allocated)
4425                 lose("trying to write-protect gen. %d when gen. %d nonempty\n",
4426                      gen_to_wp, i);
4427         }
4428         write_protect_generation_pages(gen_to_wp);
4429     }
4430
4431     /* Set gc_alloc() back to generation 0. The current regions should
4432      * be flushed after the above GCs. */
4433     gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
4434     gc_alloc_generation = 0;
4435
4436     /* Save the high-water mark before updating last_free_page */
4437     if (last_free_page > high_water_mark)
4438         high_water_mark = last_free_page;
4439
4440     update_dynamic_space_free_pointer();
4441
4442     auto_gc_trigger = bytes_allocated + bytes_consed_between_gcs;
4443     if(gencgc_verbose)
4444         fprintf(stderr,"Next gc when %ld bytes have been consed\n",
4445                 auto_gc_trigger);
4446
4447     /* If we did a big GC (arbitrarily defined as gen > 1), release memory
4448      * back to the OS.
4449      */
4450     if (gen > small_generation_limit) {
4451         if (last_free_page > high_water_mark)
4452             high_water_mark = last_free_page;
4453         remap_free_pages(0, high_water_mark);
4454         high_water_mark = 0;
4455     }
4456
4457     gc_active_p = 0;
4458
4459     SHOW("returning from collect_garbage");
4460 }
4461
4462 /* This is called by Lisp PURIFY when it is finished. All live objects
4463  * will have been moved to the RO and Static heaps. The dynamic space
4464  * will need a full re-initialization. We don't bother having Lisp
4465  * PURIFY flush the current gc_alloc() region, as the page_tables are
4466  * re-initialized, and every page is zeroed to be sure. */
4467 void
4468 gc_free_heap(void)
4469 {
4470     page_index_t page;
4471
4472     if (gencgc_verbose > 1) {
4473         SHOW("entering gc_free_heap");
4474     }
4475
4476     for (page = 0; page < page_table_pages; page++) {
4477         /* Skip free pages which should already be zero filled. */
4478         if (page_allocated_p(page)) {
4479             void *page_start, *addr;
4480
4481             /* Mark the page free. The other slots are assumed invalid
4482              * when it is a FREE_PAGE_FLAG and bytes_used is 0 and it
4483              * should not be write-protected -- except that the
4484              * generation is used for the current region but it sets
4485              * that up. */
4486             page_table[page].allocated = FREE_PAGE_FLAG;
4487             page_table[page].bytes_used = 0;
4488
4489 #ifndef LISP_FEATURE_WIN32 /* Pages already zeroed on win32? Not sure
4490                             * about this change. */
4491             /* Zero the page. */
4492             page_start = (void *)page_address(page);
4493
4494             /* First, remove any write-protection. */
4495             os_protect(page_start, PAGE_BYTES, OS_VM_PROT_ALL);
4496             page_table[page].write_protected = 0;
4497
4498             os_invalidate(page_start,PAGE_BYTES);
4499             addr = os_validate(page_start,PAGE_BYTES);
4500             if (addr == NULL || addr != page_start) {
4501                 lose("gc_free_heap: page moved, 0x%08x ==> 0x%08x\n",
4502                      page_start,
4503                      addr);
4504             }
4505 #else
4506             page_table[page].write_protected = 0;
4507 #endif
4508         } else if (gencgc_zero_check_during_free_heap) {
4509             /* Double-check that the page is zero filled. */
4510             long *page_start;
4511             page_index_t i;
4512             gc_assert(page_free_p(page));
4513             gc_assert(page_table[page].bytes_used == 0);
4514             page_start = (long *)page_address(page);
4515             for (i=0; i<1024; i++) {
4516                 if (page_start[i] != 0) {
4517                     lose("free region not zero at %x\n", page_start + i);
4518                 }
4519             }
4520         }
4521     }
4522
4523     bytes_allocated = 0;
4524
4525     /* Initialize the generations. */
4526     for (page = 0; page < NUM_GENERATIONS; page++) {
4527         generations[page].alloc_start_page = 0;
4528         generations[page].alloc_unboxed_start_page = 0;
4529         generations[page].alloc_large_start_page = 0;
4530         generations[page].alloc_large_unboxed_start_page = 0;
4531         generations[page].bytes_allocated = 0;
4532         generations[page].gc_trigger = 2000000;
4533         generations[page].num_gc = 0;
4534         generations[page].cum_sum_bytes_allocated = 0;
4535         generations[page].lutexes = NULL;
4536     }
4537
4538     if (gencgc_verbose > 1)
4539         print_generation_stats(0);
4540
4541     /* Initialize gc_alloc(). */
4542     gc_alloc_generation = 0;
4543
4544     gc_set_region_empty(&boxed_region);
4545     gc_set_region_empty(&unboxed_region);
4546
4547     last_free_page = 0;
4548     set_alloc_pointer((lispobj)((char *)heap_base));
4549
4550     if (verify_after_free_heap) {
4551         /* Check whether purify has left any bad pointers. */
4552         FSHOW((stderr, "checking after free_heap\n"));
4553         verify_gc();
4554     }
4555 }
4556 \f
4557 void
4558 gc_init(void)
4559 {
4560     page_index_t i;
4561
4562     /* Compute the number of pages needed for the dynamic space.
4563      * Dynamic space size should be aligned on page size. */
4564     page_table_pages = dynamic_space_size/PAGE_BYTES;
4565     gc_assert(dynamic_space_size == npage_bytes(page_table_pages));
4566
4567     page_table = calloc(page_table_pages, sizeof(struct page));
4568     gc_assert(page_table);
4569
4570     gc_init_tables();
4571     scavtab[WEAK_POINTER_WIDETAG] = scav_weak_pointer;
4572     transother[SIMPLE_ARRAY_WIDETAG] = trans_boxed_large;
4573
4574 #ifdef LUTEX_WIDETAG
4575     scavtab[LUTEX_WIDETAG] = scav_lutex;
4576     transother[LUTEX_WIDETAG] = trans_lutex;
4577     sizetab[LUTEX_WIDETAG] = size_lutex;
4578 #endif
4579
4580     heap_base = (void*)DYNAMIC_SPACE_START;
4581
4582     /* Initialize each page structure. */
4583     for (i = 0; i < page_table_pages; i++) {
4584         /* Initialize all pages as free. */
4585         page_table[i].allocated = FREE_PAGE_FLAG;
4586         page_table[i].bytes_used = 0;
4587
4588         /* Pages are not write-protected at startup. */
4589         page_table[i].write_protected = 0;
4590     }
4591
4592     bytes_allocated = 0;
4593
4594     /* Initialize the generations.
4595      *
4596      * FIXME: very similar to code in gc_free_heap(), should be shared */
4597     for (i = 0; i < NUM_GENERATIONS; i++) {
4598         generations[i].alloc_start_page = 0;
4599         generations[i].alloc_unboxed_start_page = 0;
4600         generations[i].alloc_large_start_page = 0;
4601         generations[i].alloc_large_unboxed_start_page = 0;
4602         generations[i].bytes_allocated = 0;
4603         generations[i].gc_trigger = 2000000;
4604         generations[i].num_gc = 0;
4605         generations[i].cum_sum_bytes_allocated = 0;
4606         /* the tune-able parameters */
4607         generations[i].bytes_consed_between_gc = 2000000;
4608         generations[i].trigger_age = 1;
4609         generations[i].min_av_mem_age = 0.75;
4610         generations[i].lutexes = NULL;
4611     }
4612
4613     /* Initialize gc_alloc. */
4614     gc_alloc_generation = 0;
4615     gc_set_region_empty(&boxed_region);
4616     gc_set_region_empty(&unboxed_region);
4617
4618     last_free_page = 0;
4619 }
4620
4621 /*  Pick up the dynamic space from after a core load.
4622  *
4623  *  The ALLOCATION_POINTER points to the end of the dynamic space.
4624  */
4625
4626 static void
4627 gencgc_pickup_dynamic(void)
4628 {
4629     page_index_t page = 0;
4630     void *alloc_ptr = (void *)get_alloc_pointer();
4631     lispobj *prev=(lispobj *)page_address(page);
4632     generation_index_t gen = PSEUDO_STATIC_GENERATION;
4633     do {
4634         lispobj *first,*ptr= (lispobj *)page_address(page);
4635         page_table[page].allocated = BOXED_PAGE_FLAG;
4636         page_table[page].gen = gen;
4637         page_table[page].bytes_used = PAGE_BYTES;
4638         page_table[page].large_object = 0;
4639         page_table[page].write_protected = 0;
4640         page_table[page].write_protected_cleared = 0;
4641         page_table[page].dont_move = 0;
4642         page_table[page].need_to_zero = 1;
4643
4644         if (!gencgc_partial_pickup) {
4645             first=gc_search_space(prev,(ptr+2)-prev,ptr);
4646             if(ptr == first)  prev=ptr;
4647             page_table[page].region_start_offset =
4648                 page_address(page) - (void *)prev;
4649         }
4650         page++;
4651     } while (page_address(page) < alloc_ptr);
4652
4653 #ifdef LUTEX_WIDETAG
4654     /* Lutexes have been registered in generation 0 by coreparse, and
4655      * need to be moved to the right one manually.
4656      */
4657     move_lutexes(0, PSEUDO_STATIC_GENERATION);
4658 #endif
4659
4660     last_free_page = page;
4661
4662     generations[gen].bytes_allocated = npage_bytes(page);
4663     bytes_allocated = npage_bytes(page);
4664
4665     gc_alloc_update_all_page_tables();
4666     write_protect_generation_pages(gen);
4667 }
4668
4669 void
4670 gc_initialize_pointers(void)
4671 {
4672     gencgc_pickup_dynamic();
4673 }
4674 \f
4675
4676 /* alloc(..) is the external interface for memory allocation. It
4677  * allocates to generation 0. It is not called from within the garbage
4678  * collector as it is only external uses that need the check for heap
4679  * size (GC trigger) and to disable the interrupts (interrupts are
4680  * always disabled during a GC).
4681  *
4682  * The vops that call alloc(..) assume that the returned space is zero-filled.
4683  * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
4684  *
4685  * The check for a GC trigger is only performed when the current
4686  * region is full, so in most cases it's not needed. */
4687
4688 static inline lispobj *
4689 general_alloc_internal(long nbytes, int page_type_flag, struct alloc_region *region,
4690                        struct thread *thread)
4691 {
4692 #ifndef LISP_FEATURE_WIN32
4693     lispobj alloc_signal;
4694 #endif
4695     void *new_obj;
4696     void *new_free_pointer;
4697
4698     gc_assert(nbytes>0);
4699
4700     /* Check for alignment allocation problems. */
4701     gc_assert((((unsigned long)region->free_pointer & LOWTAG_MASK) == 0)
4702               && ((nbytes & LOWTAG_MASK) == 0));
4703
4704     /* Must be inside a PA section. */
4705     gc_assert(get_pseudo_atomic_atomic(thread));
4706
4707     /* maybe we can do this quickly ... */
4708     new_free_pointer = region->free_pointer + nbytes;
4709     if (new_free_pointer <= region->end_addr) {
4710         new_obj = (void*)(region->free_pointer);
4711         region->free_pointer = new_free_pointer;
4712         return(new_obj);        /* yup */
4713     }
4714
4715     /* we have to go the long way around, it seems. Check whether we
4716      * should GC in the near future
4717      */
4718     if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
4719         /* Don't flood the system with interrupts if the need to gc is
4720          * already noted. This can happen for example when SUB-GC
4721          * allocates or after a gc triggered in a WITHOUT-GCING. */
4722         if (SymbolValue(GC_PENDING,thread) == NIL) {
4723             /* set things up so that GC happens when we finish the PA
4724              * section */
4725             SetSymbolValue(GC_PENDING,T,thread);
4726             if (SymbolValue(GC_INHIBIT,thread) == NIL)
4727               set_pseudo_atomic_interrupted(thread);
4728         }
4729     }
4730     new_obj = gc_alloc_with_region(nbytes, page_type_flag, region, 0);
4731
4732 #ifndef LISP_FEATURE_WIN32
4733     alloc_signal = SymbolValue(ALLOC_SIGNAL,thread);
4734     if ((alloc_signal & FIXNUM_TAG_MASK) == 0) {
4735         if ((signed long) alloc_signal <= 0) {
4736             SetSymbolValue(ALLOC_SIGNAL, T, thread);
4737             thread_kill(thread->os_thread, SIGPROF);
4738         } else {
4739             SetSymbolValue(ALLOC_SIGNAL,
4740                            alloc_signal - (1 << N_FIXNUM_TAG_BITS),
4741                            thread);
4742         }
4743     }
4744 #endif
4745
4746     return (new_obj);
4747 }
4748
4749 lispobj *
4750 general_alloc(long nbytes, int page_type_flag)
4751 {
4752     struct thread *thread = arch_os_get_current_thread();
4753     /* Select correct region, and call general_alloc_internal with it.
4754      * For other then boxed allocation we must lock first, since the
4755      * region is shared. */
4756     if (BOXED_PAGE_FLAG & page_type_flag) {
4757 #ifdef LISP_FEATURE_SB_THREAD
4758         struct alloc_region *region = (thread ? &(thread->alloc_region) : &boxed_region);
4759 #else
4760         struct alloc_region *region = &boxed_region;
4761 #endif
4762         return general_alloc_internal(nbytes, page_type_flag, region, thread);
4763     } else if (UNBOXED_PAGE_FLAG == page_type_flag) {
4764         lispobj * obj;
4765         gc_assert(0 == thread_mutex_lock(&allocation_lock));
4766         obj = general_alloc_internal(nbytes, page_type_flag, &unboxed_region, thread);
4767         gc_assert(0 == thread_mutex_unlock(&allocation_lock));
4768         return obj;
4769     } else {
4770         lose("bad page type flag: %d", page_type_flag);
4771     }
4772 }
4773
4774 lispobj *
4775 alloc(long nbytes)
4776 {
4777     gc_assert(get_pseudo_atomic_atomic(arch_os_get_current_thread()));
4778     return general_alloc(nbytes, BOXED_PAGE_FLAG);
4779 }
4780 \f
4781 /*
4782  * shared support for the OS-dependent signal handlers which
4783  * catch GENCGC-related write-protect violations
4784  */
4785 void unhandled_sigmemoryfault(void* addr);
4786
4787 /* Depending on which OS we're running under, different signals might
4788  * be raised for a violation of write protection in the heap. This
4789  * function factors out the common generational GC magic which needs
4790  * to invoked in this case, and should be called from whatever signal
4791  * handler is appropriate for the OS we're running under.
4792  *
4793  * Return true if this signal is a normal generational GC thing that
4794  * we were able to handle, or false if it was abnormal and control
4795  * should fall through to the general SIGSEGV/SIGBUS/whatever logic. */
4796
4797 int
4798 gencgc_handle_wp_violation(void* fault_addr)
4799 {
4800     page_index_t page_index = find_page_index(fault_addr);
4801
4802 #ifdef QSHOW_SIGNALS
4803     FSHOW((stderr, "heap WP violation? fault_addr=%x, page_index=%d\n",
4804            fault_addr, page_index));
4805 #endif
4806
4807     /* Check whether the fault is within the dynamic space. */
4808     if (page_index == (-1)) {
4809
4810         /* It can be helpful to be able to put a breakpoint on this
4811          * case to help diagnose low-level problems. */
4812         unhandled_sigmemoryfault(fault_addr);
4813
4814         /* not within the dynamic space -- not our responsibility */
4815         return 0;
4816
4817     } else {
4818         if (page_table[page_index].write_protected) {
4819             /* Unprotect the page. */
4820             os_protect(page_address(page_index), PAGE_BYTES, OS_VM_PROT_ALL);
4821             page_table[page_index].write_protected_cleared = 1;
4822             page_table[page_index].write_protected = 0;
4823         } else {
4824             /* The only acceptable reason for this signal on a heap
4825              * access is that GENCGC write-protected the page.
4826              * However, if two CPUs hit a wp page near-simultaneously,
4827              * we had better not have the second one lose here if it
4828              * does this test after the first one has already set wp=0
4829              */
4830             if(page_table[page_index].write_protected_cleared != 1)
4831                 lose("fault in heap page %d not marked as write-protected\nboxed_region.first_page: %d, boxed_region.last_page %d\n",
4832                      page_index, boxed_region.first_page,
4833                      boxed_region.last_page);
4834         }
4835         /* Don't worry, we can handle it. */
4836         return 1;
4837     }
4838 }
4839 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
4840  * it's not just a case of the program hitting the write barrier, and
4841  * are about to let Lisp deal with it. It's basically just a
4842  * convenient place to set a gdb breakpoint. */
4843 void
4844 unhandled_sigmemoryfault(void *addr)
4845 {}
4846
4847 void gc_alloc_update_all_page_tables(void)
4848 {
4849     /* Flush the alloc regions updating the tables. */
4850     struct thread *th;
4851     for_each_thread(th)
4852         gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
4853     gc_alloc_update_page_tables(UNBOXED_PAGE_FLAG, &unboxed_region);
4854     gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &boxed_region);
4855 }
4856
4857 void
4858 gc_set_region_empty(struct alloc_region *region)
4859 {
4860     region->first_page = 0;
4861     region->last_page = -1;
4862     region->start_addr = page_address(0);
4863     region->free_pointer = page_address(0);
4864     region->end_addr = page_address(0);
4865 }
4866
4867 static void
4868 zero_all_free_pages()
4869 {
4870     page_index_t i;
4871
4872     for (i = 0; i < last_free_page; i++) {
4873         if (page_free_p(i)) {
4874 #ifdef READ_PROTECT_FREE_PAGES
4875             os_protect(page_address(i),
4876                        PAGE_BYTES,
4877                        OS_VM_PROT_ALL);
4878 #endif
4879             zero_pages(i, i);
4880         }
4881     }
4882 }
4883
4884 /* Things to do before doing a final GC before saving a core (without
4885  * purify).
4886  *
4887  * + Pages in large_object pages aren't moved by the GC, so we need to
4888  *   unset that flag from all pages.
4889  * + The pseudo-static generation isn't normally collected, but it seems
4890  *   reasonable to collect it at least when saving a core. So move the
4891  *   pages to a normal generation.
4892  */
4893 static void
4894 prepare_for_final_gc ()
4895 {
4896     page_index_t i;
4897     for (i = 0; i < last_free_page; i++) {
4898         page_table[i].large_object = 0;
4899         if (page_table[i].gen == PSEUDO_STATIC_GENERATION) {
4900             int used = page_table[i].bytes_used;
4901             page_table[i].gen = HIGHEST_NORMAL_GENERATION;
4902             generations[PSEUDO_STATIC_GENERATION].bytes_allocated -= used;
4903             generations[HIGHEST_NORMAL_GENERATION].bytes_allocated += used;
4904         }
4905     }
4906 }
4907
4908
4909 /* Do a non-conservative GC, and then save a core with the initial
4910  * function being set to the value of the static symbol
4911  * SB!VM:RESTART-LISP-FUNCTION */
4912 void
4913 gc_and_save(char *filename, boolean prepend_runtime,
4914             boolean save_runtime_options)
4915 {
4916     FILE *file;
4917     void *runtime_bytes = NULL;
4918     size_t runtime_size;
4919
4920     file = prepare_to_save(filename, prepend_runtime, &runtime_bytes,
4921                            &runtime_size);
4922     if (file == NULL)
4923        return;
4924
4925     conservative_stack = 0;
4926
4927     /* The filename might come from Lisp, and be moved by the now
4928      * non-conservative GC. */
4929     filename = strdup(filename);
4930
4931     /* Collect twice: once into relatively high memory, and then back
4932      * into low memory. This compacts the retained data into the lower
4933      * pages, minimizing the size of the core file.
4934      */
4935     prepare_for_final_gc();
4936     gencgc_alloc_start_page = last_free_page;
4937     collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4938
4939     prepare_for_final_gc();
4940     gencgc_alloc_start_page = -1;
4941     collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4942
4943     if (prepend_runtime)
4944         save_runtime_to_filehandle(file, runtime_bytes, runtime_size);
4945
4946     /* The dumper doesn't know that pages need to be zeroed before use. */
4947     zero_all_free_pages();
4948     save_to_filehandle(file, filename, SymbolValue(RESTART_LISP_FUNCTION,0),
4949                        prepend_runtime, save_runtime_options);
4950     /* Oops. Save still managed to fail. Since we've mangled the stack
4951      * beyond hope, there's not much we can do.
4952      * (beyond FUNCALLing RESTART_LISP_FUNCTION, but I suspect that's
4953      * going to be rather unsatisfactory too... */
4954     lose("Attempt to save core after non-conservative GC failed.\n");
4955 }