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