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