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