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