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