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