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