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