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