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