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