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