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