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