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