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