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