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