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