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