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