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