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