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