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