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