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