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