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