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