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