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