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