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