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