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