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