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