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