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