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