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