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