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