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