default nursery to 5% of total dynamic space size on GENCGC
[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(long *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 size_t
249 npage_bytes(long npages)
250 {
251     gc_assert(npages>=0);
252     return ((unsigned long)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
258 size_t 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 unsigned long gencgc_release_granularity;
354 unsigned long gencgc_release_granularity = GENCGC_RELEASE_GRANULARITY;
355
356 extern unsigned long gencgc_alloc_granularity;
357 unsigned long 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 long
367 count_write_protect_generation_pages(generation_index_t generation)
368 {
369     page_index_t i;
370     unsigned long count = 0;
371
372     for (i = 0; i < last_free_page; i++)
373         if (page_allocated_p(i)
374             && (page_table[i].gen == generation)
375             && (page_table[i].write_protected == 1))
376             count++;
377     return count;
378 }
379
380 /* Count the number of pages within the given generation. */
381 static long
382 count_generation_pages(generation_index_t generation)
383 {
384     page_index_t i;
385     long count = 0;
386
387     for (i = 0; i < last_free_page; i++)
388         if (page_allocated_p(i)
389             && (page_table[i].gen == generation))
390             count++;
391     return count;
392 }
393
394 #if QSHOW
395 static long
396 count_dont_move_pages(void)
397 {
398     page_index_t i;
399     long count = 0;
400     for (i = 0; i < last_free_page; i++) {
401         if (page_allocated_p(i)
402             && (page_table[i].dont_move != 0)) {
403             ++count;
404         }
405     }
406     return count;
407 }
408 #endif /* QSHOW */
409
410 /* Work through the pages and add up the number of bytes used for the
411  * given generation. */
412 static unsigned long
413 count_generation_bytes_allocated (generation_index_t gen)
414 {
415     page_index_t i;
416     unsigned long result = 0;
417     for (i = 0; i < last_free_page; i++) {
418         if (page_allocated_p(i)
419             && (page_table[i].gen == gen))
420             result += page_table[i].bytes_used;
421     }
422     return result;
423 }
424
425 /* Return the average age of the memory in a generation. */
426 extern double
427 generation_average_age(generation_index_t gen)
428 {
429     if (generations[gen].bytes_allocated == 0)
430         return 0.0;
431
432     return
433         ((double)generations[gen].cum_sum_bytes_allocated)
434         / ((double)generations[gen].bytes_allocated);
435 }
436
437 extern void
438 write_generation_stats(FILE *file)
439 {
440     generation_index_t i;
441
442 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
443 #define FPU_STATE_SIZE 27
444     int fpu_state[FPU_STATE_SIZE];
445 #elif defined(LISP_FEATURE_PPC)
446 #define FPU_STATE_SIZE 32
447     long long fpu_state[FPU_STATE_SIZE];
448 #endif
449
450     /* This code uses the FP instructions which may be set up for Lisp
451      * so they need to be saved and reset for C. */
452     fpu_save(fpu_state);
453
454     /* Print the heap stats. */
455     fprintf(file,
456             " Gen StaPg UbSta LaSta LUbSt Boxed Unboxed LB   LUB  !move  Alloc  Waste   Trig    WP  GCs Mem-age\n");
457
458     for (i = 0; i < SCRATCH_GENERATION; i++) {
459         page_index_t j;
460         long boxed_cnt = 0;
461         long unboxed_cnt = 0;
462         long large_boxed_cnt = 0;
463         long large_unboxed_cnt = 0;
464         long pinned_cnt=0;
465
466         for (j = 0; j < last_free_page; j++)
467             if (page_table[j].gen == i) {
468
469                 /* Count the number of boxed pages within the given
470                  * generation. */
471                 if (page_boxed_p(j)) {
472                     if (page_table[j].large_object)
473                         large_boxed_cnt++;
474                     else
475                         boxed_cnt++;
476                 }
477                 if(page_table[j].dont_move) pinned_cnt++;
478                 /* Count the number of unboxed pages within the given
479                  * generation. */
480                 if (page_unboxed_p(j)) {
481                     if (page_table[j].large_object)
482                         large_unboxed_cnt++;
483                     else
484                         unboxed_cnt++;
485                 }
486             }
487
488         gc_assert(generations[i].bytes_allocated
489                   == count_generation_bytes_allocated(i));
490         fprintf(file,
491                 "   %1d: %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %8ld %5ld %8ld %4ld %3d %7.4f\n",
492                 i,
493                 generations[i].alloc_start_page,
494                 generations[i].alloc_unboxed_start_page,
495                 generations[i].alloc_large_start_page,
496                 generations[i].alloc_large_unboxed_start_page,
497                 boxed_cnt,
498                 unboxed_cnt,
499                 large_boxed_cnt,
500                 large_unboxed_cnt,
501                 pinned_cnt,
502                 generations[i].bytes_allocated,
503                 (npage_bytes(count_generation_pages(i))
504                  - generations[i].bytes_allocated),
505                 generations[i].gc_trigger,
506                 count_write_protect_generation_pages(i),
507                 generations[i].num_gc,
508                 generation_average_age(i));
509     }
510     fprintf(file,"   Total bytes allocated    = %lu\n", (unsigned long)bytes_allocated);
511     fprintf(file,"   Dynamic-space-size bytes = %lu\n", (unsigned long)dynamic_space_size);
512
513     fpu_restore(fpu_state);
514 }
515
516 extern void
517 write_heap_exhaustion_report(FILE *file, long available, long requested,
518                              struct thread *thread)
519 {
520     fprintf(file,
521             "Heap exhausted during %s: %ld bytes available, %ld requested.\n",
522             gc_active_p ? "garbage collection" : "allocation",
523             available,
524             requested);
525     write_generation_stats(file);
526     fprintf(file, "GC control variables:\n");
527     fprintf(file, "   *GC-INHIBIT* = %s\n   *GC-PENDING* = %s\n",
528             SymbolValue(GC_INHIBIT,thread)==NIL ? "false" : "true",
529             (SymbolValue(GC_PENDING, thread) == T) ?
530             "true" : ((SymbolValue(GC_PENDING, thread) == NIL) ?
531                       "false" : "in progress"));
532 #ifdef LISP_FEATURE_SB_THREAD
533     fprintf(file, "   *STOP-FOR-GC-PENDING* = %s\n",
534             SymbolValue(STOP_FOR_GC_PENDING,thread)==NIL ? "false" : "true");
535 #endif
536 }
537
538 extern void
539 print_generation_stats(void)
540 {
541     write_generation_stats(stderr);
542 }
543
544 extern char* gc_logfile;
545 char * gc_logfile = NULL;
546
547 extern void
548 log_generation_stats(char *logfile, char *header)
549 {
550     if (logfile) {
551         FILE * log = fopen(logfile, "a");
552         if (log) {
553             fprintf(log, "%s\n", header);
554             write_generation_stats(log);
555             fclose(log);
556         } else {
557             fprintf(stderr, "Could not open gc logfile: %s\n", logfile);
558             fflush(stderr);
559         }
560     }
561 }
562
563 extern void
564 report_heap_exhaustion(long available, long requested, struct thread *th)
565 {
566     if (gc_logfile) {
567         FILE * log = fopen(gc_logfile, "a");
568         if (log) {
569             write_heap_exhaustion_report(log, available, requested, th);
570             fclose(log);
571         } else {
572             fprintf(stderr, "Could not open gc logfile: %s\n", gc_logfile);
573             fflush(stderr);
574         }
575     }
576     /* Always to stderr as well. */
577     write_heap_exhaustion_report(stderr, available, requested, th);
578 }
579 \f
580
581 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
582 void fast_bzero(void*, size_t); /* in <arch>-assem.S */
583 #endif
584
585 /* Zero the pages from START to END (inclusive), but use mmap/munmap instead
586  * if zeroing it ourselves, i.e. in practice give the memory back to the
587  * OS. Generally done after a large GC.
588  */
589 void zero_pages_with_mmap(page_index_t start, page_index_t end) {
590     int i;
591     void *addr = page_address(start), *new_addr;
592     size_t length = npage_bytes(1+end-start);
593
594     if (start > end)
595       return;
596
597     gc_assert(length >= gencgc_release_granularity);
598     gc_assert((length % gencgc_release_granularity) == 0);
599
600     os_invalidate(addr, length);
601     new_addr = os_validate(addr, length);
602     if (new_addr == NULL || new_addr != addr) {
603         lose("remap_free_pages: page moved, 0x%08x ==> 0x%08x",
604              start, new_addr);
605     }
606
607     for (i = start; i <= end; i++) {
608         page_table[i].need_to_zero = 0;
609     }
610 }
611
612 /* Zero the pages from START to END (inclusive). Generally done just after
613  * a new region has been allocated.
614  */
615 static void
616 zero_pages(page_index_t start, page_index_t end) {
617     if (start > end)
618       return;
619
620 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
621     fast_bzero(page_address(start), npage_bytes(1+end-start));
622 #else
623     bzero(page_address(start), npage_bytes(1+end-start));
624 #endif
625
626 }
627
628 static void
629 zero_and_mark_pages(page_index_t start, page_index_t end) {
630     page_index_t i;
631
632     zero_pages(start, end);
633     for (i = start; i <= end; i++)
634         page_table[i].need_to_zero = 0;
635 }
636
637 /* Zero the pages from START to END (inclusive), except for those
638  * pages that are known to already zeroed. Mark all pages in the
639  * ranges as non-zeroed.
640  */
641 static void
642 zero_dirty_pages(page_index_t start, page_index_t end) {
643     page_index_t i, j;
644
645     for (i = start; i <= end; i++) {
646         if (!page_table[i].need_to_zero) continue;
647         for (j = i+1; (j <= end) && (page_table[j].need_to_zero); j++);
648         zero_pages(i, j-1);
649         i = j;
650     }
651
652     for (i = start; i <= end; i++) {
653         page_table[i].need_to_zero = 1;
654     }
655 }
656
657
658 /*
659  * To support quick and inline allocation, regions of memory can be
660  * allocated and then allocated from with just a free pointer and a
661  * check against an end address.
662  *
663  * Since objects can be allocated to spaces with different properties
664  * e.g. boxed/unboxed, generation, ages; there may need to be many
665  * allocation regions.
666  *
667  * Each allocation region may start within a partly used page. Many
668  * features of memory use are noted on a page wise basis, e.g. the
669  * generation; so if a region starts within an existing allocated page
670  * it must be consistent with this page.
671  *
672  * During the scavenging of the newspace, objects will be transported
673  * into an allocation region, and pointers updated to point to this
674  * allocation region. It is possible that these pointers will be
675  * scavenged again before the allocation region is closed, e.g. due to
676  * trans_list which jumps all over the place to cleanup the list. It
677  * is important to be able to determine properties of all objects
678  * pointed to when scavenging, e.g to detect pointers to the oldspace.
679  * Thus it's important that the allocation regions have the correct
680  * properties set when allocated, and not just set when closed. The
681  * region allocation routines return regions with the specified
682  * properties, and grab all the pages, setting their properties
683  * appropriately, except that the amount used is not known.
684  *
685  * These regions are used to support quicker allocation using just a
686  * free pointer. The actual space used by the region is not reflected
687  * in the pages tables until it is closed. It can't be scavenged until
688  * closed.
689  *
690  * When finished with the region it should be closed, which will
691  * update the page tables for the actual space used returning unused
692  * space. Further it may be noted in the new regions which is
693  * necessary when scavenging the newspace.
694  *
695  * Large objects may be allocated directly without an allocation
696  * region, the page tables are updated immediately.
697  *
698  * Unboxed objects don't contain pointers to other objects and so
699  * don't need scavenging. Further they can't contain pointers to
700  * younger generations so WP is not needed. By allocating pages to
701  * unboxed objects the whole page never needs scavenging or
702  * write-protecting. */
703
704 /* We are only using two regions at present. Both are for the current
705  * newspace generation. */
706 struct alloc_region boxed_region;
707 struct alloc_region unboxed_region;
708
709 /* The generation currently being allocated to. */
710 static generation_index_t gc_alloc_generation;
711
712 static inline page_index_t
713 generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large)
714 {
715     if (large) {
716         if (UNBOXED_PAGE_FLAG == page_type_flag) {
717             return generations[generation].alloc_large_unboxed_start_page;
718         } else if (BOXED_PAGE_FLAG & page_type_flag) {
719             /* Both code and data. */
720             return generations[generation].alloc_large_start_page;
721         } else {
722             lose("bad page type flag: %d", page_type_flag);
723         }
724     } else {
725         if (UNBOXED_PAGE_FLAG == page_type_flag) {
726             return generations[generation].alloc_unboxed_start_page;
727         } else if (BOXED_PAGE_FLAG & page_type_flag) {
728             /* Both code and data. */
729             return generations[generation].alloc_start_page;
730         } else {
731             lose("bad page_type_flag: %d", page_type_flag);
732         }
733     }
734 }
735
736 static inline void
737 set_generation_alloc_start_page(generation_index_t generation, int page_type_flag, int large,
738                                 page_index_t page)
739 {
740     if (large) {
741         if (UNBOXED_PAGE_FLAG == page_type_flag) {
742             generations[generation].alloc_large_unboxed_start_page = page;
743         } else if (BOXED_PAGE_FLAG & page_type_flag) {
744             /* Both code and data. */
745             generations[generation].alloc_large_start_page = page;
746         } else {
747             lose("bad page type flag: %d", page_type_flag);
748         }
749     } else {
750         if (UNBOXED_PAGE_FLAG == page_type_flag) {
751             generations[generation].alloc_unboxed_start_page = page;
752         } else if (BOXED_PAGE_FLAG & page_type_flag) {
753             /* Both code and data. */
754             generations[generation].alloc_start_page = page;
755         } else {
756             lose("bad page type flag: %d", page_type_flag);
757         }
758     }
759 }
760
761 /* Find a new region with room for at least the given number of bytes.
762  *
763  * It starts looking at the current generation's alloc_start_page. So
764  * may pick up from the previous region if there is enough space. This
765  * keeps the allocation contiguous when scavenging the newspace.
766  *
767  * The alloc_region should have been closed by a call to
768  * gc_alloc_update_page_tables(), and will thus be in an empty state.
769  *
770  * To assist the scavenging functions write-protected pages are not
771  * used. Free pages should not be write-protected.
772  *
773  * It is critical to the conservative GC that the start of regions be
774  * known. To help achieve this only small regions are allocated at a
775  * time.
776  *
777  * During scavenging, pointers may be found to within the current
778  * region and the page generation must be set so that pointers to the
779  * from space can be recognized. Therefore the generation of pages in
780  * the region are set to gc_alloc_generation. To prevent another
781  * allocation call using the same pages, all the pages in the region
782  * are allocated, although they will initially be empty.
783  */
784 static void
785 gc_alloc_new_region(long nbytes, int page_type_flag, struct alloc_region *alloc_region)
786 {
787     page_index_t first_page;
788     page_index_t last_page;
789     unsigned long bytes_found;
790     page_index_t i;
791     int ret;
792
793     /*
794     FSHOW((stderr,
795            "/alloc_new_region for %d bytes from gen %d\n",
796            nbytes, gc_alloc_generation));
797     */
798
799     /* Check that the region is in a reset state. */
800     gc_assert((alloc_region->first_page == 0)
801               && (alloc_region->last_page == -1)
802               && (alloc_region->free_pointer == alloc_region->end_addr));
803     ret = thread_mutex_lock(&free_pages_lock);
804     gc_assert(ret == 0);
805     first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0);
806     last_page=gc_find_freeish_pages(&first_page, nbytes, page_type_flag);
807     bytes_found=(GENCGC_CARD_BYTES - page_table[first_page].bytes_used)
808             + npage_bytes(last_page-first_page);
809
810     /* Set up the alloc_region. */
811     alloc_region->first_page = first_page;
812     alloc_region->last_page = last_page;
813     alloc_region->start_addr = page_table[first_page].bytes_used
814         + page_address(first_page);
815     alloc_region->free_pointer = alloc_region->start_addr;
816     alloc_region->end_addr = alloc_region->start_addr + bytes_found;
817
818     /* Set up the pages. */
819
820     /* The first page may have already been in use. */
821     if (page_table[first_page].bytes_used == 0) {
822         page_table[first_page].allocated = page_type_flag;
823         page_table[first_page].gen = gc_alloc_generation;
824         page_table[first_page].large_object = 0;
825         page_table[first_page].region_start_offset = 0;
826     }
827
828     gc_assert(page_table[first_page].allocated == page_type_flag);
829     page_table[first_page].allocated |= OPEN_REGION_PAGE_FLAG;
830
831     gc_assert(page_table[first_page].gen == gc_alloc_generation);
832     gc_assert(page_table[first_page].large_object == 0);
833
834     for (i = first_page+1; i <= last_page; i++) {
835         page_table[i].allocated = page_type_flag;
836         page_table[i].gen = gc_alloc_generation;
837         page_table[i].large_object = 0;
838         /* This may not be necessary for unboxed regions (think it was
839          * broken before!) */
840         page_table[i].region_start_offset =
841             void_diff(page_address(i),alloc_region->start_addr);
842         page_table[i].allocated |= OPEN_REGION_PAGE_FLAG ;
843     }
844     /* Bump up last_free_page. */
845     if (last_page+1 > last_free_page) {
846         last_free_page = last_page+1;
847         /* do we only want to call this on special occasions? like for
848          * boxed_region? */
849         set_alloc_pointer((lispobj)page_address(last_free_page));
850     }
851     ret = thread_mutex_unlock(&free_pages_lock);
852     gc_assert(ret == 0);
853
854 #ifdef READ_PROTECT_FREE_PAGES
855     os_protect(page_address(first_page),
856                npage_bytes(1+last_page-first_page),
857                OS_VM_PROT_ALL);
858 #endif
859
860     /* If the first page was only partial, don't check whether it's
861      * zeroed (it won't be) and don't zero it (since the parts that
862      * we're interested in are guaranteed to be zeroed).
863      */
864     if (page_table[first_page].bytes_used) {
865         first_page++;
866     }
867
868     zero_dirty_pages(first_page, last_page);
869
870     /* we can do this after releasing free_pages_lock */
871     if (gencgc_zero_check) {
872         long *p;
873         for (p = (long *)alloc_region->start_addr;
874              p < (long *)alloc_region->end_addr; p++) {
875             if (*p != 0) {
876                 /* KLUDGE: It would be nice to use %lx and explicit casts
877                  * (long) in code like this, so that it is less likely to
878                  * break randomly when running on a machine with different
879                  * word sizes. -- WHN 19991129 */
880                 lose("The new region at %x is not zero (start=%p, end=%p).\n",
881                      p, alloc_region->start_addr, alloc_region->end_addr);
882             }
883         }
884     }
885 }
886
887 /* If the record_new_objects flag is 2 then all new regions created
888  * are recorded.
889  *
890  * If it's 1 then then it is only recorded if the first page of the
891  * current region is <= new_areas_ignore_page. This helps avoid
892  * unnecessary recording when doing full scavenge pass.
893  *
894  * The new_object structure holds the page, byte offset, and size of
895  * new regions of objects. Each new area is placed in the array of
896  * these structures pointer to by new_areas. new_areas_index holds the
897  * offset into new_areas.
898  *
899  * If new_area overflows NUM_NEW_AREAS then it stops adding them. The
900  * later code must detect this and handle it, probably by doing a full
901  * scavenge of a generation. */
902 #define NUM_NEW_AREAS 512
903 static int record_new_objects = 0;
904 static page_index_t new_areas_ignore_page;
905 struct new_area {
906     page_index_t page;
907     size_t offset;
908     size_t size;
909 };
910 static struct new_area (*new_areas)[];
911 static long new_areas_index;
912 long max_new_areas;
913
914 /* Add a new area to new_areas. */
915 static void
916 add_new_area(page_index_t first_page, size_t offset, size_t size)
917 {
918     unsigned long new_area_start,c;
919     long i;
920
921     /* Ignore if full. */
922     if (new_areas_index >= NUM_NEW_AREAS)
923         return;
924
925     switch (record_new_objects) {
926     case 0:
927         return;
928     case 1:
929         if (first_page > new_areas_ignore_page)
930             return;
931         break;
932     case 2:
933         break;
934     default:
935         gc_abort();
936     }
937
938     new_area_start = npage_bytes(first_page) + offset;
939
940     /* Search backwards for a prior area that this follows from. If
941        found this will save adding a new area. */
942     for (i = new_areas_index-1, c = 0; (i >= 0) && (c < 8); i--, c++) {
943         unsigned long area_end =
944             npage_bytes((*new_areas)[i].page)
945             + (*new_areas)[i].offset
946             + (*new_areas)[i].size;
947         /*FSHOW((stderr,
948                "/add_new_area S1 %d %d %d %d\n",
949                i, c, new_area_start, area_end));*/
950         if (new_area_start == area_end) {
951             /*FSHOW((stderr,
952                    "/adding to [%d] %d %d %d with %d %d %d:\n",
953                    i,
954                    (*new_areas)[i].page,
955                    (*new_areas)[i].offset,
956                    (*new_areas)[i].size,
957                    first_page,
958                    offset,
959                     size);*/
960             (*new_areas)[i].size += size;
961             return;
962         }
963     }
964
965     (*new_areas)[new_areas_index].page = first_page;
966     (*new_areas)[new_areas_index].offset = offset;
967     (*new_areas)[new_areas_index].size = size;
968     /*FSHOW((stderr,
969            "/new_area %d page %d offset %d size %d\n",
970            new_areas_index, first_page, offset, size));*/
971     new_areas_index++;
972
973     /* Note the max new_areas used. */
974     if (new_areas_index > max_new_areas)
975         max_new_areas = new_areas_index;
976 }
977
978 /* Update the tables for the alloc_region. The region may be added to
979  * the new_areas.
980  *
981  * When done the alloc_region is set up so that the next quick alloc
982  * will fail safely and thus a new region will be allocated. Further
983  * it is safe to try to re-update the page table of this reset
984  * alloc_region. */
985 void
986 gc_alloc_update_page_tables(int page_type_flag, struct alloc_region *alloc_region)
987 {
988     int more;
989     page_index_t first_page;
990     page_index_t next_page;
991     unsigned long bytes_used;
992     unsigned long orig_first_page_bytes_used;
993     unsigned long region_size;
994     unsigned long byte_cnt;
995     int ret;
996
997
998     first_page = alloc_region->first_page;
999
1000     /* Catch an unused alloc_region. */
1001     if ((first_page == 0) && (alloc_region->last_page == -1))
1002         return;
1003
1004     next_page = first_page+1;
1005
1006     ret = thread_mutex_lock(&free_pages_lock);
1007     gc_assert(ret == 0);
1008     if (alloc_region->free_pointer != alloc_region->start_addr) {
1009         /* some bytes were allocated in the region */
1010         orig_first_page_bytes_used = page_table[first_page].bytes_used;
1011
1012         gc_assert(alloc_region->start_addr ==
1013                   (page_address(first_page)
1014                    + page_table[first_page].bytes_used));
1015
1016         /* All the pages used need to be updated */
1017
1018         /* Update the first page. */
1019
1020         /* If the page was free then set up the gen, and
1021          * region_start_offset. */
1022         if (page_table[first_page].bytes_used == 0)
1023             gc_assert(page_table[first_page].region_start_offset == 0);
1024         page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1025
1026         gc_assert(page_table[first_page].allocated & page_type_flag);
1027         gc_assert(page_table[first_page].gen == gc_alloc_generation);
1028         gc_assert(page_table[first_page].large_object == 0);
1029
1030         byte_cnt = 0;
1031
1032         /* Calculate the number of bytes used in this page. This is not
1033          * always the number of new bytes, unless it was free. */
1034         more = 0;
1035         if ((bytes_used = void_diff(alloc_region->free_pointer,
1036                                     page_address(first_page)))
1037             >GENCGC_CARD_BYTES) {
1038             bytes_used = GENCGC_CARD_BYTES;
1039             more = 1;
1040         }
1041         page_table[first_page].bytes_used = bytes_used;
1042         byte_cnt += bytes_used;
1043
1044
1045         /* All the rest of the pages should be free. We need to set
1046          * their region_start_offset pointer to the start of the
1047          * region, and set the bytes_used. */
1048         while (more) {
1049             page_table[next_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1050             gc_assert(page_table[next_page].allocated & page_type_flag);
1051             gc_assert(page_table[next_page].bytes_used == 0);
1052             gc_assert(page_table[next_page].gen == gc_alloc_generation);
1053             gc_assert(page_table[next_page].large_object == 0);
1054
1055             gc_assert(page_table[next_page].region_start_offset ==
1056                       void_diff(page_address(next_page),
1057                                 alloc_region->start_addr));
1058
1059             /* Calculate the number of bytes used in this page. */
1060             more = 0;
1061             if ((bytes_used = void_diff(alloc_region->free_pointer,
1062                                         page_address(next_page)))>GENCGC_CARD_BYTES) {
1063                 bytes_used = GENCGC_CARD_BYTES;
1064                 more = 1;
1065             }
1066             page_table[next_page].bytes_used = bytes_used;
1067             byte_cnt += bytes_used;
1068
1069             next_page++;
1070         }
1071
1072         region_size = void_diff(alloc_region->free_pointer,
1073                                 alloc_region->start_addr);
1074         bytes_allocated += region_size;
1075         generations[gc_alloc_generation].bytes_allocated += region_size;
1076
1077         gc_assert((byte_cnt- orig_first_page_bytes_used) == region_size);
1078
1079         /* Set the generations alloc restart page to the last page of
1080          * the region. */
1081         set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 0, next_page-1);
1082
1083         /* Add the region to the new_areas if requested. */
1084         if (BOXED_PAGE_FLAG & page_type_flag)
1085             add_new_area(first_page,orig_first_page_bytes_used, region_size);
1086
1087         /*
1088         FSHOW((stderr,
1089                "/gc_alloc_update_page_tables update %d bytes to gen %d\n",
1090                region_size,
1091                gc_alloc_generation));
1092         */
1093     } else {
1094         /* There are no bytes allocated. Unallocate the first_page if
1095          * there are 0 bytes_used. */
1096         page_table[first_page].allocated &= ~(OPEN_REGION_PAGE_FLAG);
1097         if (page_table[first_page].bytes_used == 0)
1098             page_table[first_page].allocated = FREE_PAGE_FLAG;
1099     }
1100
1101     /* Unallocate any unused pages. */
1102     while (next_page <= alloc_region->last_page) {
1103         gc_assert(page_table[next_page].bytes_used == 0);
1104         page_table[next_page].allocated = FREE_PAGE_FLAG;
1105         next_page++;
1106     }
1107     ret = thread_mutex_unlock(&free_pages_lock);
1108     gc_assert(ret == 0);
1109
1110     /* alloc_region is per-thread, we're ok to do this unlocked */
1111     gc_set_region_empty(alloc_region);
1112 }
1113
1114 static inline void *gc_quick_alloc(long nbytes);
1115
1116 /* Allocate a possibly large object. */
1117 void *
1118 gc_alloc_large(long nbytes, int page_type_flag, struct alloc_region *alloc_region)
1119 {
1120     page_index_t first_page;
1121     page_index_t last_page;
1122     int orig_first_page_bytes_used;
1123     long byte_cnt;
1124     int more;
1125     unsigned long bytes_used;
1126     page_index_t next_page;
1127     int ret;
1128
1129     ret = thread_mutex_lock(&free_pages_lock);
1130     gc_assert(ret == 0);
1131
1132     first_page = generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1);
1133     if (first_page <= alloc_region->last_page) {
1134         first_page = alloc_region->last_page+1;
1135     }
1136
1137     last_page=gc_find_freeish_pages(&first_page,nbytes, page_type_flag);
1138
1139     gc_assert(first_page > alloc_region->last_page);
1140
1141     set_generation_alloc_start_page(gc_alloc_generation, page_type_flag, 1, last_page);
1142
1143     /* Set up the pages. */
1144     orig_first_page_bytes_used = page_table[first_page].bytes_used;
1145
1146     /* If the first page was free then set up the gen, and
1147      * region_start_offset. */
1148     if (page_table[first_page].bytes_used == 0) {
1149         page_table[first_page].allocated = page_type_flag;
1150         page_table[first_page].gen = gc_alloc_generation;
1151         page_table[first_page].region_start_offset = 0;
1152         page_table[first_page].large_object = 1;
1153     }
1154
1155     gc_assert(page_table[first_page].allocated == page_type_flag);
1156     gc_assert(page_table[first_page].gen == gc_alloc_generation);
1157     gc_assert(page_table[first_page].large_object == 1);
1158
1159     byte_cnt = 0;
1160
1161     /* Calc. the number of bytes used in this page. This is not
1162      * always the number of new bytes, unless it was free. */
1163     more = 0;
1164     if ((bytes_used = nbytes+orig_first_page_bytes_used) > GENCGC_CARD_BYTES) {
1165         bytes_used = GENCGC_CARD_BYTES;
1166         more = 1;
1167     }
1168     page_table[first_page].bytes_used = bytes_used;
1169     byte_cnt += bytes_used;
1170
1171     next_page = first_page+1;
1172
1173     /* All the rest of the pages should be free. We need to set their
1174      * region_start_offset pointer to the start of the region, and set
1175      * the bytes_used. */
1176     while (more) {
1177         gc_assert(page_free_p(next_page));
1178         gc_assert(page_table[next_page].bytes_used == 0);
1179         page_table[next_page].allocated = page_type_flag;
1180         page_table[next_page].gen = gc_alloc_generation;
1181         page_table[next_page].large_object = 1;
1182
1183         page_table[next_page].region_start_offset =
1184             npage_bytes(next_page-first_page) - orig_first_page_bytes_used;
1185
1186         /* Calculate the number of bytes used in this page. */
1187         more = 0;
1188         bytes_used=(nbytes+orig_first_page_bytes_used)-byte_cnt;
1189         if (bytes_used > GENCGC_CARD_BYTES) {
1190             bytes_used = GENCGC_CARD_BYTES;
1191             more = 1;
1192         }
1193         page_table[next_page].bytes_used = bytes_used;
1194         page_table[next_page].write_protected=0;
1195         page_table[next_page].dont_move=0;
1196         byte_cnt += bytes_used;
1197         next_page++;
1198     }
1199
1200     gc_assert((byte_cnt-orig_first_page_bytes_used) == nbytes);
1201
1202     bytes_allocated += nbytes;
1203     generations[gc_alloc_generation].bytes_allocated += nbytes;
1204
1205     /* Add the region to the new_areas if requested. */
1206     if (BOXED_PAGE_FLAG & page_type_flag)
1207         add_new_area(first_page,orig_first_page_bytes_used,nbytes);
1208
1209     /* Bump up last_free_page */
1210     if (last_page+1 > last_free_page) {
1211         last_free_page = last_page+1;
1212         set_alloc_pointer((lispobj)(page_address(last_free_page)));
1213     }
1214     ret = thread_mutex_unlock(&free_pages_lock);
1215     gc_assert(ret == 0);
1216
1217 #ifdef READ_PROTECT_FREE_PAGES
1218     os_protect(page_address(first_page),
1219                npage_bytes(1+last_page-first_page),
1220                OS_VM_PROT_ALL);
1221 #endif
1222
1223     zero_dirty_pages(first_page, last_page);
1224
1225     return page_address(first_page);
1226 }
1227
1228 static page_index_t gencgc_alloc_start_page = -1;
1229
1230 void
1231 gc_heap_exhausted_error_or_lose (long available, long requested)
1232 {
1233     struct thread *thread = arch_os_get_current_thread();
1234     /* Write basic information before doing anything else: if we don't
1235      * call to lisp this is a must, and even if we do there is always
1236      * the danger that we bounce back here before the error has been
1237      * handled, or indeed even printed.
1238      */
1239     report_heap_exhaustion(available, requested, thread);
1240     if (gc_active_p || (available == 0)) {
1241         /* If we are in GC, or totally out of memory there is no way
1242          * to sanely transfer control to the lisp-side of things.
1243          */
1244         lose("Heap exhausted, game over.");
1245     }
1246     else {
1247         /* FIXME: assert free_pages_lock held */
1248         (void)thread_mutex_unlock(&free_pages_lock);
1249         gc_assert(get_pseudo_atomic_atomic(thread));
1250         clear_pseudo_atomic_atomic(thread);
1251         if (get_pseudo_atomic_interrupted(thread))
1252             do_pending_interrupt();
1253         /* Another issue is that signalling HEAP-EXHAUSTED error leads
1254          * to running user code at arbitrary places, even in a
1255          * WITHOUT-INTERRUPTS which may lead to a deadlock without
1256          * running out of the heap. So at this point all bets are
1257          * off. */
1258         if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL)
1259             corruption_warning_and_maybe_lose
1260                 ("Signalling HEAP-EXHAUSTED in a WITHOUT-INTERRUPTS.");
1261         funcall2(StaticSymbolFunction(HEAP_EXHAUSTED_ERROR),
1262                  alloc_number(available), alloc_number(requested));
1263         lose("HEAP-EXHAUSTED-ERROR fell through");
1264     }
1265 }
1266
1267 page_index_t
1268 gc_find_freeish_pages(page_index_t *restart_page_ptr, long nbytes,
1269                       int page_type_flag)
1270 {
1271     page_index_t first_page, last_page;
1272     page_index_t restart_page = *restart_page_ptr;
1273     long nbytes_goal = nbytes;
1274     long bytes_found = 0;
1275     long most_bytes_found = 0;
1276     page_index_t most_bytes_found_from, most_bytes_found_to;
1277     int small_object = nbytes < GENCGC_CARD_BYTES;
1278     /* FIXME: assert(free_pages_lock is held); */
1279
1280     if (nbytes_goal < gencgc_alloc_granularity)
1281             nbytes_goal = gencgc_alloc_granularity;
1282
1283     /* Toggled by gc_and_save for heap compaction, normally -1. */
1284     if (gencgc_alloc_start_page != -1) {
1285         restart_page = gencgc_alloc_start_page;
1286     }
1287
1288     gc_assert(nbytes>=0);
1289     /* Search for a page with at least nbytes of space. We prefer
1290      * not to split small objects on multiple pages, to reduce the
1291      * number of contiguous allocation regions spaning multiple
1292      * pages: this helps avoid excessive conservativism.
1293      *
1294      * For other objects, we guarantee that they start on their own
1295      * page boundary.
1296      */
1297     first_page = restart_page;
1298     while (first_page < page_table_pages) {
1299         bytes_found = 0;
1300         if (page_free_p(first_page)) {
1301                 gc_assert(0 == page_table[first_page].bytes_used);
1302                 bytes_found = GENCGC_CARD_BYTES;
1303         } else if (small_object &&
1304                    (page_table[first_page].allocated == page_type_flag) &&
1305                    (page_table[first_page].large_object == 0) &&
1306                    (page_table[first_page].gen == gc_alloc_generation) &&
1307                    (page_table[first_page].write_protected == 0) &&
1308                    (page_table[first_page].dont_move == 0)) {
1309             bytes_found = GENCGC_CARD_BYTES - page_table[first_page].bytes_used;
1310             if (bytes_found < nbytes) {
1311                 if (bytes_found > most_bytes_found)
1312                     most_bytes_found = bytes_found;
1313                 first_page++;
1314                 continue;
1315             }
1316         } else {
1317             first_page++;
1318             continue;
1319         }
1320
1321         gc_assert(page_table[first_page].write_protected == 0);
1322         for (last_page = first_page+1;
1323              ((last_page < page_table_pages) &&
1324               page_free_p(last_page) &&
1325               (bytes_found < nbytes_goal));
1326              last_page++) {
1327             bytes_found += GENCGC_CARD_BYTES;
1328             gc_assert(0 == page_table[last_page].bytes_used);
1329             gc_assert(0 == page_table[last_page].write_protected);
1330         }
1331
1332         if (bytes_found > most_bytes_found) {
1333             most_bytes_found = bytes_found;
1334             most_bytes_found_from = first_page;
1335             most_bytes_found_to = last_page;
1336         }
1337         if (bytes_found >= nbytes_goal)
1338             break;
1339
1340         first_page = last_page;
1341     }
1342
1343     bytes_found = most_bytes_found;
1344     restart_page = first_page + 1;
1345
1346     /* Check for a failure */
1347     if (bytes_found < nbytes) {
1348         gc_assert(restart_page >= page_table_pages);
1349         gc_heap_exhausted_error_or_lose(most_bytes_found, nbytes);
1350     }
1351
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     int 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     /* Check that none of the write_protected pages in this generation
2830      * have been written to. */
2831     for (i = 0; i < page_table_pages; i++) {
2832         if (page_allocated_p(i)
2833             && (page_table[i].bytes_used != 0)
2834             && (page_table[i].gen == generation)
2835             && (page_table[i].write_protected_cleared != 0)
2836             && (page_table[i].dont_move == 0)) {
2837             lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d\n",
2838                  i, generation, page_table[i].dont_move);
2839         }
2840     }
2841 #endif
2842 }
2843 \f
2844 /* Un-write-protect all the pages in from_space. This is done at the
2845  * start of a GC else there may be many page faults while scavenging
2846  * the newspace (I've seen drive the system time to 99%). These pages
2847  * would need to be unprotected anyway before unmapping in
2848  * free_oldspace; not sure what effect this has on paging.. */
2849 static void
2850 unprotect_oldspace(void)
2851 {
2852     page_index_t i;
2853     void *region_addr = 0;
2854     void *page_addr = 0;
2855     unsigned long region_bytes = 0;
2856
2857     for (i = 0; i < last_free_page; i++) {
2858         if (page_allocated_p(i)
2859             && (page_table[i].bytes_used != 0)
2860             && (page_table[i].gen == from_space)) {
2861
2862             /* Remove any write-protection. We should be able to rely
2863              * on the write-protect flag to avoid redundant calls. */
2864             if (page_table[i].write_protected) {
2865                 page_table[i].write_protected = 0;
2866                 page_addr = page_address(i);
2867                 if (!region_addr) {
2868                     /* First region. */
2869                     region_addr = page_addr;
2870                     region_bytes = GENCGC_CARD_BYTES;
2871                 } else if (region_addr + region_bytes == page_addr) {
2872                     /* Region continue. */
2873                     region_bytes += GENCGC_CARD_BYTES;
2874                 } else {
2875                     /* Unprotect previous region. */
2876                     os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
2877                     /* First page in new region. */
2878                     region_addr = page_addr;
2879                     region_bytes = GENCGC_CARD_BYTES;
2880                 }
2881             }
2882         }
2883     }
2884     if (region_addr) {
2885         /* Unprotect last region. */
2886         os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
2887     }
2888 }
2889
2890 /* Work through all the pages and free any in from_space. This
2891  * assumes that all objects have been copied or promoted to an older
2892  * generation. Bytes_allocated and the generation bytes_allocated
2893  * counter are updated. The number of bytes freed is returned. */
2894 static unsigned long
2895 free_oldspace(void)
2896 {
2897     unsigned long bytes_freed = 0;
2898     page_index_t first_page, last_page;
2899
2900     first_page = 0;
2901
2902     do {
2903         /* Find a first page for the next region of pages. */
2904         while ((first_page < last_free_page)
2905                && (page_free_p(first_page)
2906                    || (page_table[first_page].bytes_used == 0)
2907                    || (page_table[first_page].gen != from_space)))
2908             first_page++;
2909
2910         if (first_page >= last_free_page)
2911             break;
2912
2913         /* Find the last page of this region. */
2914         last_page = first_page;
2915
2916         do {
2917             /* Free the page. */
2918             bytes_freed += page_table[last_page].bytes_used;
2919             generations[page_table[last_page].gen].bytes_allocated -=
2920                 page_table[last_page].bytes_used;
2921             page_table[last_page].allocated = FREE_PAGE_FLAG;
2922             page_table[last_page].bytes_used = 0;
2923             /* Should already be unprotected by unprotect_oldspace(). */
2924             gc_assert(!page_table[last_page].write_protected);
2925             last_page++;
2926         }
2927         while ((last_page < last_free_page)
2928                && page_allocated_p(last_page)
2929                && (page_table[last_page].bytes_used != 0)
2930                && (page_table[last_page].gen == from_space));
2931
2932 #ifdef READ_PROTECT_FREE_PAGES
2933         os_protect(page_address(first_page),
2934                    npage_bytes(last_page-first_page),
2935                    OS_VM_PROT_NONE);
2936 #endif
2937         first_page = last_page;
2938     } while (first_page < last_free_page);
2939
2940     bytes_allocated -= bytes_freed;
2941     return bytes_freed;
2942 }
2943 \f
2944 #if 0
2945 /* Print some information about a pointer at the given address. */
2946 static void
2947 print_ptr(lispobj *addr)
2948 {
2949     /* If addr is in the dynamic space then out the page information. */
2950     page_index_t pi1 = find_page_index((void*)addr);
2951
2952     if (pi1 != -1)
2953         fprintf(stderr,"  %x: page %d  alloc %d  gen %d  bytes_used %d  offset %lu  dont_move %d\n",
2954                 (unsigned long) addr,
2955                 pi1,
2956                 page_table[pi1].allocated,
2957                 page_table[pi1].gen,
2958                 page_table[pi1].bytes_used,
2959                 page_table[pi1].region_start_offset,
2960                 page_table[pi1].dont_move);
2961     fprintf(stderr,"  %x %x %x %x (%x) %x %x %x %x\n",
2962             *(addr-4),
2963             *(addr-3),
2964             *(addr-2),
2965             *(addr-1),
2966             *(addr-0),
2967             *(addr+1),
2968             *(addr+2),
2969             *(addr+3),
2970             *(addr+4));
2971 }
2972 #endif
2973
2974 static int
2975 is_in_stack_space(lispobj ptr)
2976 {
2977     /* For space verification: Pointers can be valid if they point
2978      * to a thread stack space.  This would be faster if the thread
2979      * structures had page-table entries as if they were part of
2980      * the heap space. */
2981     struct thread *th;
2982     for_each_thread(th) {
2983         if ((th->control_stack_start <= (lispobj *)ptr) &&
2984             (th->control_stack_end >= (lispobj *)ptr)) {
2985             return 1;
2986         }
2987     }
2988     return 0;
2989 }
2990
2991 static void
2992 verify_space(lispobj *start, size_t words)
2993 {
2994     int is_in_dynamic_space = (find_page_index((void*)start) != -1);
2995     int is_in_readonly_space =
2996         (READ_ONLY_SPACE_START <= (unsigned long)start &&
2997          (unsigned long)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
2998
2999     while (words > 0) {
3000         size_t count = 1;
3001         lispobj thing = *(lispobj*)start;
3002
3003         if (is_lisp_pointer(thing)) {
3004             page_index_t page_index = find_page_index((void*)thing);
3005             long to_readonly_space =
3006                 (READ_ONLY_SPACE_START <= thing &&
3007                  thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3008             long to_static_space =
3009                 (STATIC_SPACE_START <= thing &&
3010                  thing < SymbolValue(STATIC_SPACE_FREE_POINTER,0));
3011
3012             /* Does it point to the dynamic space? */
3013             if (page_index != -1) {
3014                 /* If it's within the dynamic space it should point to a used
3015                  * page. XX Could check the offset too. */
3016                 if (page_allocated_p(page_index)
3017                     && (page_table[page_index].bytes_used == 0))
3018                     lose ("Ptr %p @ %p sees free page.\n", thing, start);
3019                 /* Check that it doesn't point to a forwarding pointer! */
3020                 if (*((lispobj *)native_pointer(thing)) == 0x01) {
3021                     lose("Ptr %p @ %p sees forwarding ptr.\n", thing, start);
3022                 }
3023                 /* Check that its not in the RO space as it would then be a
3024                  * pointer from the RO to the dynamic space. */
3025                 if (is_in_readonly_space) {
3026                     lose("ptr to dynamic space %p from RO space %x\n",
3027                          thing, start);
3028                 }
3029                 /* Does it point to a plausible object? This check slows
3030                  * it down a lot (so it's commented out).
3031                  *
3032                  * "a lot" is serious: it ate 50 minutes cpu time on
3033                  * my duron 950 before I came back from lunch and
3034                  * killed it.
3035                  *
3036                  *   FIXME: Add a variable to enable this
3037                  * dynamically. */
3038                 /*
3039                 if (!possibly_valid_dynamic_space_pointer((lispobj *)thing)) {
3040                     lose("ptr %p to invalid object %p\n", thing, start);
3041                 }
3042                 */
3043             } else {
3044                 extern void funcallable_instance_tramp;
3045                 /* Verify that it points to another valid space. */
3046                 if (!to_readonly_space && !to_static_space
3047                     && (thing != (lispobj)&funcallable_instance_tramp)
3048                     && !is_in_stack_space(thing)) {
3049                     lose("Ptr %p @ %p sees junk.\n", thing, start);
3050                 }
3051             }
3052         } else {
3053             if (!(fixnump(thing))) {
3054                 /* skip fixnums */
3055                 switch(widetag_of(*start)) {
3056
3057                     /* boxed objects */
3058                 case SIMPLE_VECTOR_WIDETAG:
3059                 case RATIO_WIDETAG:
3060                 case COMPLEX_WIDETAG:
3061                 case SIMPLE_ARRAY_WIDETAG:
3062                 case COMPLEX_BASE_STRING_WIDETAG:
3063 #ifdef COMPLEX_CHARACTER_STRING_WIDETAG
3064                 case COMPLEX_CHARACTER_STRING_WIDETAG:
3065 #endif
3066                 case COMPLEX_VECTOR_NIL_WIDETAG:
3067                 case COMPLEX_BIT_VECTOR_WIDETAG:
3068                 case COMPLEX_VECTOR_WIDETAG:
3069                 case COMPLEX_ARRAY_WIDETAG:
3070                 case CLOSURE_HEADER_WIDETAG:
3071                 case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
3072                 case VALUE_CELL_HEADER_WIDETAG:
3073                 case SYMBOL_HEADER_WIDETAG:
3074                 case CHARACTER_WIDETAG:
3075 #if N_WORD_BITS == 64
3076                 case SINGLE_FLOAT_WIDETAG:
3077 #endif
3078                 case UNBOUND_MARKER_WIDETAG:
3079                 case FDEFN_WIDETAG:
3080                     count = 1;
3081                     break;
3082
3083                 case INSTANCE_HEADER_WIDETAG:
3084                     {
3085                         lispobj nuntagged;
3086                         long ntotal = HeaderValue(thing);
3087                         lispobj layout = ((struct instance *)start)->slots[0];
3088                         if (!layout) {
3089                             count = 1;
3090                             break;
3091                         }
3092                         nuntagged = ((struct layout *)
3093                                      native_pointer(layout))->n_untagged_slots;
3094                         verify_space(start + 1,
3095                                      ntotal - fixnum_value(nuntagged));
3096                         count = ntotal + 1;
3097                         break;
3098                     }
3099                 case CODE_HEADER_WIDETAG:
3100                     {
3101                         lispobj object = *start;
3102                         struct code *code;
3103                         long nheader_words, ncode_words, nwords;
3104                         lispobj fheaderl;
3105                         struct simple_fun *fheaderp;
3106
3107                         code = (struct code *) start;
3108
3109                         /* Check that it's not in the dynamic space.
3110                          * FIXME: Isn't is supposed to be OK for code
3111                          * objects to be in the dynamic space these days? */
3112                         if (is_in_dynamic_space
3113                             /* It's ok if it's byte compiled code. The trace
3114                              * table offset will be a fixnum if it's x86
3115                              * compiled code - check.
3116                              *
3117                              * FIXME: #^#@@! lack of abstraction here..
3118                              * This line can probably go away now that
3119                              * there's no byte compiler, but I've got
3120                              * too much to worry about right now to try
3121                              * to make sure. -- WHN 2001-10-06 */
3122                             && fixnump(code->trace_table_offset)
3123                             /* Only when enabled */
3124                             && verify_dynamic_code_check) {
3125                             FSHOW((stderr,
3126                                    "/code object at %p in the dynamic space\n",
3127                                    start));
3128                         }
3129
3130                         ncode_words = fixnum_value(code->code_size);
3131                         nheader_words = HeaderValue(object);
3132                         nwords = ncode_words + nheader_words;
3133                         nwords = CEILING(nwords, 2);
3134                         /* Scavenge the boxed section of the code data block */
3135                         verify_space(start + 1, nheader_words - 1);
3136
3137                         /* Scavenge the boxed section of each function
3138                          * object in the code data block. */
3139                         fheaderl = code->entry_points;
3140                         while (fheaderl != NIL) {
3141                             fheaderp =
3142                                 (struct simple_fun *) native_pointer(fheaderl);
3143                             gc_assert(widetag_of(fheaderp->header) ==
3144                                       SIMPLE_FUN_HEADER_WIDETAG);
3145                             verify_space(&fheaderp->name, 1);
3146                             verify_space(&fheaderp->arglist, 1);
3147                             verify_space(&fheaderp->type, 1);
3148                             fheaderl = fheaderp->next;
3149                         }
3150                         count = nwords;
3151                         break;
3152                     }
3153
3154                     /* unboxed objects */
3155                 case BIGNUM_WIDETAG:
3156 #if N_WORD_BITS != 64
3157                 case SINGLE_FLOAT_WIDETAG:
3158 #endif
3159                 case DOUBLE_FLOAT_WIDETAG:
3160 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3161                 case LONG_FLOAT_WIDETAG:
3162 #endif
3163 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
3164                 case COMPLEX_SINGLE_FLOAT_WIDETAG:
3165 #endif
3166 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
3167                 case COMPLEX_DOUBLE_FLOAT_WIDETAG:
3168 #endif
3169 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3170                 case COMPLEX_LONG_FLOAT_WIDETAG:
3171 #endif
3172                 case SIMPLE_BASE_STRING_WIDETAG:
3173 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
3174                 case SIMPLE_CHARACTER_STRING_WIDETAG:
3175 #endif
3176                 case SIMPLE_BIT_VECTOR_WIDETAG:
3177                 case SIMPLE_ARRAY_NIL_WIDETAG:
3178                 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
3179                 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
3180                 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
3181                 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
3182                 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
3183                 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
3184
3185                 case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
3186
3187                 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
3188                 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
3189 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
3190                 case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
3191 #endif
3192 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
3193                 case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
3194 #endif
3195 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
3196                 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
3197 #endif
3198 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
3199                 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
3200 #endif
3201
3202                 case SIMPLE_ARRAY_FIXNUM_WIDETAG:
3203
3204 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
3205                 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
3206 #endif
3207 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
3208                 case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
3209 #endif
3210                 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
3211                 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
3212 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3213                 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
3214 #endif
3215 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
3216                 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
3217 #endif
3218 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
3219                 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
3220 #endif
3221 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3222                 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
3223 #endif
3224                 case SAP_WIDETAG:
3225                 case WEAK_POINTER_WIDETAG:
3226 #ifdef NO_TLS_VALUE_MARKER_WIDETAG
3227                 case NO_TLS_VALUE_MARKER_WIDETAG:
3228 #endif
3229                     count = (sizetab[widetag_of(*start)])(start);
3230                     break;
3231
3232                 default:
3233                     lose("Unhandled widetag %p at %p\n",
3234                          widetag_of(*start), start);
3235                 }
3236             }
3237         }
3238         start += count;
3239         words -= count;
3240     }
3241 }
3242
3243 static void
3244 verify_gc(void)
3245 {
3246     /* FIXME: It would be nice to make names consistent so that
3247      * foo_size meant size *in* *bytes* instead of size in some
3248      * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
3249      * Some counts of lispobjs are called foo_count; it might be good
3250      * to grep for all foo_size and rename the appropriate ones to
3251      * foo_count. */
3252     long read_only_space_size =
3253         (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0)
3254         - (lispobj*)READ_ONLY_SPACE_START;
3255     long static_space_size =
3256         (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0)
3257         - (lispobj*)STATIC_SPACE_START;
3258     struct thread *th;
3259     for_each_thread(th) {
3260     long binding_stack_size =
3261         (lispobj*)get_binding_stack_pointer(th)
3262             - (lispobj*)th->binding_stack_start;
3263         verify_space(th->binding_stack_start, binding_stack_size);
3264     }
3265     verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
3266     verify_space((lispobj*)STATIC_SPACE_START   , static_space_size);
3267 }
3268
3269 static void
3270 verify_generation(generation_index_t generation)
3271 {
3272     page_index_t i;
3273
3274     for (i = 0; i < last_free_page; i++) {
3275         if (page_allocated_p(i)
3276             && (page_table[i].bytes_used != 0)
3277             && (page_table[i].gen == generation)) {
3278             page_index_t last_page;
3279             int region_allocation = page_table[i].allocated;
3280
3281             /* This should be the start of a contiguous block */
3282             gc_assert(page_table[i].region_start_offset == 0);
3283
3284             /* Need to find the full extent of this contiguous block in case
3285                objects span pages. */
3286
3287             /* Now work forward until the end of this contiguous area is
3288                found. */
3289             for (last_page = i; ;last_page++)
3290                 /* Check whether this is the last page in this contiguous
3291                  * block. */
3292                 if ((page_table[last_page].bytes_used < GENCGC_CARD_BYTES)
3293                     /* Or it is CARD_BYTES and is the last in the block */
3294                     || (page_table[last_page+1].allocated != region_allocation)
3295                     || (page_table[last_page+1].bytes_used == 0)
3296                     || (page_table[last_page+1].gen != generation)
3297                     || (page_table[last_page+1].region_start_offset == 0))
3298                     break;
3299
3300             verify_space(page_address(i),
3301                          ((unsigned long)
3302                           (page_table[last_page].bytes_used
3303                            + npage_bytes(last_page-i)))
3304                          / N_WORD_BYTES);
3305             i = last_page;
3306         }
3307     }
3308 }
3309
3310 /* Check that all the free space is zero filled. */
3311 static void
3312 verify_zero_fill(void)
3313 {
3314     page_index_t page;
3315
3316     for (page = 0; page < last_free_page; page++) {
3317         if (page_free_p(page)) {
3318             /* The whole page should be zero filled. */
3319             long *start_addr = (long *)page_address(page);
3320             long size = 1024;
3321             long i;
3322             for (i = 0; i < size; i++) {
3323                 if (start_addr[i] != 0) {
3324                     lose("free page not zero at %x\n", start_addr + i);
3325                 }
3326             }
3327         } else {
3328             long free_bytes = GENCGC_CARD_BYTES - page_table[page].bytes_used;
3329             if (free_bytes > 0) {
3330                 long *start_addr = (long *)((unsigned long)page_address(page)
3331                                           + page_table[page].bytes_used);
3332                 long size = free_bytes / N_WORD_BYTES;
3333                 long i;
3334                 for (i = 0; i < size; i++) {
3335                     if (start_addr[i] != 0) {
3336                         lose("free region not zero at %x\n", start_addr + i);
3337                     }
3338                 }
3339             }
3340         }
3341     }
3342 }
3343
3344 /* External entry point for verify_zero_fill */
3345 void
3346 gencgc_verify_zero_fill(void)
3347 {
3348     /* Flush the alloc regions updating the tables. */
3349     gc_alloc_update_all_page_tables();
3350     SHOW("verifying zero fill");
3351     verify_zero_fill();
3352 }
3353
3354 static void
3355 verify_dynamic_space(void)
3356 {
3357     generation_index_t i;
3358
3359     for (i = 0; i <= HIGHEST_NORMAL_GENERATION; i++)
3360         verify_generation(i);
3361
3362     if (gencgc_enable_verify_zero_fill)
3363         verify_zero_fill();
3364 }
3365 \f
3366 /* Write-protect all the dynamic boxed pages in the given generation. */
3367 static void
3368 write_protect_generation_pages(generation_index_t generation)
3369 {
3370     page_index_t start;
3371
3372     gc_assert(generation < SCRATCH_GENERATION);
3373
3374     for (start = 0; start < last_free_page; start++) {
3375         if (protect_page_p(start, generation)) {
3376             void *page_start;
3377             page_index_t last;
3378
3379             /* Note the page as protected in the page tables. */
3380             page_table[start].write_protected = 1;
3381
3382             for (last = start + 1; last < last_free_page; last++) {
3383                 if (!protect_page_p(last, generation))
3384                   break;
3385                 page_table[last].write_protected = 1;
3386             }
3387
3388             page_start = (void *)page_address(start);
3389
3390             os_protect(page_start,
3391                        npage_bytes(last - start),
3392                        OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
3393
3394             start = last;
3395         }
3396     }
3397
3398     if (gencgc_verbose > 1) {
3399         FSHOW((stderr,
3400                "/write protected %d of %d pages in generation %d\n",
3401                count_write_protect_generation_pages(generation),
3402                count_generation_pages(generation),
3403                generation));
3404     }
3405 }
3406
3407 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
3408 static void
3409 scavenge_control_stack(struct thread *th)
3410 {
3411     lispobj *control_stack =
3412         (lispobj *)(th->control_stack_start);
3413     unsigned long control_stack_size =
3414         access_control_stack_pointer(th) - control_stack;
3415
3416     scavenge(control_stack, control_stack_size);
3417 }
3418 #endif
3419
3420 #if defined(LISP_FEATURE_SB_THREAD) && (defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
3421 static void
3422 preserve_context_registers (os_context_t *c)
3423 {
3424     void **ptr;
3425     /* On Darwin the signal context isn't a contiguous block of memory,
3426      * so just preserve_pointering its contents won't be sufficient.
3427      */
3428 #if defined(LISP_FEATURE_DARWIN)
3429 #if defined LISP_FEATURE_X86
3430     preserve_pointer((void*)*os_context_register_addr(c,reg_EAX));
3431     preserve_pointer((void*)*os_context_register_addr(c,reg_ECX));
3432     preserve_pointer((void*)*os_context_register_addr(c,reg_EDX));
3433     preserve_pointer((void*)*os_context_register_addr(c,reg_EBX));
3434     preserve_pointer((void*)*os_context_register_addr(c,reg_ESI));
3435     preserve_pointer((void*)*os_context_register_addr(c,reg_EDI));
3436     preserve_pointer((void*)*os_context_pc_addr(c));
3437 #elif defined LISP_FEATURE_X86_64
3438     preserve_pointer((void*)*os_context_register_addr(c,reg_RAX));
3439     preserve_pointer((void*)*os_context_register_addr(c,reg_RCX));
3440     preserve_pointer((void*)*os_context_register_addr(c,reg_RDX));
3441     preserve_pointer((void*)*os_context_register_addr(c,reg_RBX));
3442     preserve_pointer((void*)*os_context_register_addr(c,reg_RSI));
3443     preserve_pointer((void*)*os_context_register_addr(c,reg_RDI));
3444     preserve_pointer((void*)*os_context_register_addr(c,reg_R8));
3445     preserve_pointer((void*)*os_context_register_addr(c,reg_R9));
3446     preserve_pointer((void*)*os_context_register_addr(c,reg_R10));
3447     preserve_pointer((void*)*os_context_register_addr(c,reg_R11));
3448     preserve_pointer((void*)*os_context_register_addr(c,reg_R12));
3449     preserve_pointer((void*)*os_context_register_addr(c,reg_R13));
3450     preserve_pointer((void*)*os_context_register_addr(c,reg_R14));
3451     preserve_pointer((void*)*os_context_register_addr(c,reg_R15));
3452     preserve_pointer((void*)*os_context_pc_addr(c));
3453 #else
3454     #error "preserve_context_registers needs to be tweaked for non-x86 Darwin"
3455 #endif
3456 #endif
3457     for(ptr = ((void **)(c+1))-1; ptr>=(void **)c; ptr--) {
3458         preserve_pointer(*ptr);
3459     }
3460 }
3461 #endif
3462
3463 /* Garbage collect a generation. If raise is 0 then the remains of the
3464  * generation are not raised to the next generation. */
3465 static void
3466 garbage_collect_generation(generation_index_t generation, int raise)
3467 {
3468     unsigned long bytes_freed;
3469     page_index_t i;
3470     unsigned long static_space_size;
3471     struct thread *th;
3472
3473     gc_assert(generation <= HIGHEST_NORMAL_GENERATION);
3474
3475     /* The oldest generation can't be raised. */
3476     gc_assert((generation != HIGHEST_NORMAL_GENERATION) || (raise == 0));
3477
3478     /* Check if weak hash tables were processed in the previous GC. */
3479     gc_assert(weak_hash_tables == NULL);
3480
3481     /* Initialize the weak pointer list. */
3482     weak_pointers = NULL;
3483
3484     /* When a generation is not being raised it is transported to a
3485      * temporary generation (NUM_GENERATIONS), and lowered when
3486      * done. Set up this new generation. There should be no pages
3487      * allocated to it yet. */
3488     if (!raise) {
3489          gc_assert(generations[SCRATCH_GENERATION].bytes_allocated == 0);
3490     }
3491
3492     /* Set the global src and dest. generations */
3493     from_space = generation;
3494     if (raise)
3495         new_space = generation+1;
3496     else
3497         new_space = SCRATCH_GENERATION;
3498
3499     /* Change to a new space for allocation, resetting the alloc_start_page */
3500     gc_alloc_generation = new_space;
3501     generations[new_space].alloc_start_page = 0;
3502     generations[new_space].alloc_unboxed_start_page = 0;
3503     generations[new_space].alloc_large_start_page = 0;
3504     generations[new_space].alloc_large_unboxed_start_page = 0;
3505
3506     /* Before any pointers are preserved, the dont_move flags on the
3507      * pages need to be cleared. */
3508     for (i = 0; i < last_free_page; i++)
3509         if(page_table[i].gen==from_space)
3510             page_table[i].dont_move = 0;
3511
3512     /* Un-write-protect the old-space pages. This is essential for the
3513      * promoted pages as they may contain pointers into the old-space
3514      * which need to be scavenged. It also helps avoid unnecessary page
3515      * faults as forwarding pointers are written into them. They need to
3516      * be un-protected anyway before unmapping later. */
3517     unprotect_oldspace();
3518
3519     /* Scavenge the stacks' conservative roots. */
3520
3521     /* there are potentially two stacks for each thread: the main
3522      * stack, which may contain Lisp pointers, and the alternate stack.
3523      * We don't ever run Lisp code on the altstack, but it may
3524      * host a sigcontext with lisp objects in it */
3525
3526     /* what we need to do: (1) find the stack pointer for the main
3527      * stack; scavenge it (2) find the interrupt context on the
3528      * alternate stack that might contain lisp values, and scavenge
3529      * that */
3530
3531     /* we assume that none of the preceding applies to the thread that
3532      * initiates GC.  If you ever call GC from inside an altstack
3533      * handler, you will lose. */
3534
3535 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
3536     /* And if we're saving a core, there's no point in being conservative. */
3537     if (conservative_stack) {
3538         for_each_thread(th) {
3539             void **ptr;
3540             void **esp=(void **)-1;
3541 #ifdef LISP_FEATURE_SB_THREAD
3542             long i,free;
3543             if(th==arch_os_get_current_thread()) {
3544                 /* Somebody is going to burn in hell for this, but casting
3545                  * it in two steps shuts gcc up about strict aliasing. */
3546                 esp = (void **)((void *)&raise);
3547             } else {
3548                 void **esp1;
3549                 free=fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
3550                 for(i=free-1;i>=0;i--) {
3551                     os_context_t *c=th->interrupt_contexts[i];
3552                     esp1 = (void **) *os_context_register_addr(c,reg_SP);
3553                     if (esp1>=(void **)th->control_stack_start &&
3554                         esp1<(void **)th->control_stack_end) {
3555                         if(esp1<esp) esp=esp1;
3556                         preserve_context_registers(c);
3557                     }
3558                 }
3559             }
3560 #else
3561             esp = (void **)((void *)&raise);
3562 #endif
3563             for (ptr = ((void **)th->control_stack_end)-1; ptr >= esp;  ptr--) {
3564                 preserve_pointer(*ptr);
3565             }
3566         }
3567     }
3568 #else
3569     /* Non-x86oid systems don't have "conservative roots" as such, but
3570      * the same mechanism is used for objects pinned for use by alien
3571      * code. */
3572     for_each_thread(th) {
3573         lispobj pin_list = SymbolTlValue(PINNED_OBJECTS,th);
3574         while (pin_list != NIL) {
3575             struct cons *list_entry =
3576                 (struct cons *)native_pointer(pin_list);
3577             preserve_pointer(list_entry->car);
3578             pin_list = list_entry->cdr;
3579         }
3580     }
3581 #endif
3582
3583 #if QSHOW
3584     if (gencgc_verbose > 1) {
3585         long num_dont_move_pages = count_dont_move_pages();
3586         fprintf(stderr,
3587                 "/non-movable pages due to conservative pointers = %d (%d bytes)\n",
3588                 num_dont_move_pages,
3589                 npage_bytes(num_dont_move_pages));
3590     }
3591 #endif
3592
3593     /* Scavenge all the rest of the roots. */
3594
3595 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
3596     /*
3597      * If not x86, we need to scavenge the interrupt context(s) and the
3598      * control stack.
3599      */
3600     {
3601         struct thread *th;
3602         for_each_thread(th) {
3603             scavenge_interrupt_contexts(th);
3604             scavenge_control_stack(th);
3605         }
3606
3607         /* Scrub the unscavenged control stack space, so that we can't run
3608          * into any stale pointers in a later GC (this is done by the
3609          * stop-for-gc handler in the other threads). */
3610         scrub_control_stack();
3611     }
3612 #endif
3613
3614     /* Scavenge the Lisp functions of the interrupt handlers, taking
3615      * care to avoid SIG_DFL and SIG_IGN. */
3616     for (i = 0; i < NSIG; i++) {
3617         union interrupt_handler handler = interrupt_handlers[i];
3618         if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
3619             !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
3620             scavenge((lispobj *)(interrupt_handlers + i), 1);
3621         }
3622     }
3623     /* Scavenge the binding stacks. */
3624     {
3625         struct thread *th;
3626         for_each_thread(th) {
3627             long len= (lispobj *)get_binding_stack_pointer(th) -
3628                 th->binding_stack_start;
3629             scavenge((lispobj *) th->binding_stack_start,len);
3630 #ifdef LISP_FEATURE_SB_THREAD
3631             /* do the tls as well */
3632             len=(SymbolValue(FREE_TLS_INDEX,0) >> WORD_SHIFT) -
3633                 (sizeof (struct thread))/(sizeof (lispobj));
3634             scavenge((lispobj *) (th+1),len);
3635 #endif
3636         }
3637     }
3638
3639     /* The original CMU CL code had scavenge-read-only-space code
3640      * controlled by the Lisp-level variable
3641      * *SCAVENGE-READ-ONLY-SPACE*. It was disabled by default, and it
3642      * wasn't documented under what circumstances it was useful or
3643      * safe to turn it on, so it's been turned off in SBCL. If you
3644      * want/need this functionality, and can test and document it,
3645      * please submit a patch. */
3646 #if 0
3647     if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
3648         unsigned long read_only_space_size =
3649             (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
3650             (lispobj*)READ_ONLY_SPACE_START;
3651         FSHOW((stderr,
3652                "/scavenge read only space: %d bytes\n",
3653                read_only_space_size * sizeof(lispobj)));
3654         scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
3655     }
3656 #endif
3657
3658     /* Scavenge static space. */
3659     static_space_size =
3660         (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0) -
3661         (lispobj *)STATIC_SPACE_START;
3662     if (gencgc_verbose > 1) {
3663         FSHOW((stderr,
3664                "/scavenge static space: %d bytes\n",
3665                static_space_size * sizeof(lispobj)));
3666     }
3667     scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
3668
3669     /* All generations but the generation being GCed need to be
3670      * scavenged. The new_space generation needs special handling as
3671      * objects may be moved in - it is handled separately below. */
3672     scavenge_generations(generation+1, PSEUDO_STATIC_GENERATION);
3673
3674     /* Finally scavenge the new_space generation. Keep going until no
3675      * more objects are moved into the new generation */
3676     scavenge_newspace_generation(new_space);
3677
3678     /* FIXME: I tried reenabling this check when debugging unrelated
3679      * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
3680      * Since the current GC code seems to work well, I'm guessing that
3681      * this debugging code is just stale, but I haven't tried to
3682      * figure it out. It should be figured out and then either made to
3683      * work or just deleted. */
3684 #define RESCAN_CHECK 0
3685 #if RESCAN_CHECK
3686     /* As a check re-scavenge the newspace once; no new objects should
3687      * be found. */
3688     {
3689         os_vm_size_t old_bytes_allocated = bytes_allocated;
3690         os_vm_size_t bytes_allocated;
3691
3692         /* Start with a full scavenge. */
3693         scavenge_newspace_generation_one_scan(new_space);
3694
3695         /* Flush the current regions, updating the tables. */
3696         gc_alloc_update_all_page_tables();
3697
3698         bytes_allocated = bytes_allocated - old_bytes_allocated;
3699
3700         if (bytes_allocated != 0) {
3701             lose("Rescan of new_space allocated %d more bytes.\n",
3702                  bytes_allocated);
3703         }
3704     }
3705 #endif
3706
3707     scan_weak_hash_tables();
3708     scan_weak_pointers();
3709
3710     /* Flush the current regions, updating the tables. */
3711     gc_alloc_update_all_page_tables();
3712
3713     /* Free the pages in oldspace, but not those marked dont_move. */
3714     bytes_freed = free_oldspace();
3715
3716     /* If the GC is not raising the age then lower the generation back
3717      * to its normal generation number */
3718     if (!raise) {
3719         for (i = 0; i < last_free_page; i++)
3720             if ((page_table[i].bytes_used != 0)
3721                 && (page_table[i].gen == SCRATCH_GENERATION))
3722                 page_table[i].gen = generation;
3723         gc_assert(generations[generation].bytes_allocated == 0);
3724         generations[generation].bytes_allocated =
3725             generations[SCRATCH_GENERATION].bytes_allocated;
3726         generations[SCRATCH_GENERATION].bytes_allocated = 0;
3727     }
3728
3729     /* Reset the alloc_start_page for generation. */
3730     generations[generation].alloc_start_page = 0;
3731     generations[generation].alloc_unboxed_start_page = 0;
3732     generations[generation].alloc_large_start_page = 0;
3733     generations[generation].alloc_large_unboxed_start_page = 0;
3734
3735     if (generation >= verify_gens) {
3736         if (gencgc_verbose) {
3737             SHOW("verifying");
3738         }
3739         verify_gc();
3740         verify_dynamic_space();
3741     }
3742
3743     /* Set the new gc trigger for the GCed generation. */
3744     generations[generation].gc_trigger =
3745         generations[generation].bytes_allocated
3746         + generations[generation].bytes_consed_between_gc;
3747
3748     if (raise)
3749         generations[generation].num_gc = 0;
3750     else
3751         ++generations[generation].num_gc;
3752
3753 }
3754
3755 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
3756 long
3757 update_dynamic_space_free_pointer(void)
3758 {
3759     page_index_t last_page = -1, i;
3760
3761     for (i = 0; i < last_free_page; i++)
3762         if (page_allocated_p(i) && (page_table[i].bytes_used != 0))
3763             last_page = i;
3764
3765     last_free_page = last_page+1;
3766
3767     set_alloc_pointer((lispobj)(page_address(last_free_page)));
3768     return 0; /* dummy value: return something ... */
3769 }
3770
3771 static void
3772 remap_page_range (page_index_t from, page_index_t to)
3773 {
3774     /* There's a mysterious Solaris/x86 problem with using mmap
3775      * tricks for memory zeroing. See sbcl-devel thread
3776      * "Re: patch: standalone executable redux".
3777      */
3778 #if defined(LISP_FEATURE_SUNOS)
3779     zero_and_mark_pages(from, to);
3780 #else
3781     const page_index_t
3782             release_granularity = gencgc_release_granularity/GENCGC_CARD_BYTES,
3783                    release_mask = release_granularity-1,
3784                             end = to+1,
3785                    aligned_from = (from+release_mask)&~release_mask,
3786                     aligned_end = (end&~release_mask);
3787
3788     if (aligned_from < aligned_end) {
3789         zero_pages_with_mmap(aligned_from, aligned_end-1);
3790         if (aligned_from != from)
3791             zero_and_mark_pages(from, aligned_from-1);
3792         if (aligned_end != end)
3793             zero_and_mark_pages(aligned_end, end-1);
3794     } else {
3795         zero_and_mark_pages(from, to);
3796     }
3797 #endif
3798 }
3799
3800 static void
3801 remap_free_pages (page_index_t from, page_index_t to, int forcibly)
3802 {
3803     page_index_t first_page, last_page;
3804
3805     if (forcibly)
3806         return remap_page_range(from, to);
3807
3808     for (first_page = from; first_page <= to; first_page++) {
3809         if (page_allocated_p(first_page) ||
3810             (page_table[first_page].need_to_zero == 0))
3811             continue;
3812
3813         last_page = first_page + 1;
3814         while (page_free_p(last_page) &&
3815                (last_page <= to) &&
3816                (page_table[last_page].need_to_zero == 1))
3817             last_page++;
3818
3819         remap_page_range(first_page, last_page-1);
3820
3821         first_page = last_page;
3822     }
3823 }
3824
3825 generation_index_t small_generation_limit = 1;
3826
3827 /* GC all generations newer than last_gen, raising the objects in each
3828  * to the next older generation - we finish when all generations below
3829  * last_gen are empty.  Then if last_gen is due for a GC, or if
3830  * last_gen==NUM_GENERATIONS (the scratch generation?  eh?) we GC that
3831  * too.  The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
3832  *
3833  * We stop collecting at gencgc_oldest_gen_to_gc, even if this is less than
3834  * last_gen (oh, and note that by default it is NUM_GENERATIONS-1) */
3835 void
3836 collect_garbage(generation_index_t last_gen)
3837 {
3838     generation_index_t gen = 0, i;
3839     int raise;
3840     int gen_to_wp;
3841     /* The largest value of last_free_page seen since the time
3842      * remap_free_pages was called. */
3843     static page_index_t high_water_mark = 0;
3844
3845     FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
3846     log_generation_stats(gc_logfile, "=== GC Start ===");
3847
3848     gc_active_p = 1;
3849
3850     if (last_gen > HIGHEST_NORMAL_GENERATION+1) {
3851         FSHOW((stderr,
3852                "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
3853                last_gen));
3854         last_gen = 0;
3855     }
3856
3857     /* Flush the alloc regions updating the tables. */
3858     gc_alloc_update_all_page_tables();
3859
3860     /* Verify the new objects created by Lisp code. */
3861     if (pre_verify_gen_0) {
3862         FSHOW((stderr, "pre-checking generation 0\n"));
3863         verify_generation(0);
3864     }
3865
3866     if (gencgc_verbose > 1)
3867         print_generation_stats();
3868
3869     do {
3870         /* Collect the generation. */
3871
3872         if (gen >= gencgc_oldest_gen_to_gc) {
3873             /* Never raise the oldest generation. */
3874             raise = 0;
3875         } else {
3876             raise =
3877                 (gen < last_gen)
3878                 || (generations[gen].num_gc >= generations[gen].number_of_gcs_before_promotion);
3879         }
3880
3881         if (gencgc_verbose > 1) {
3882             FSHOW((stderr,
3883                    "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
3884                    gen,
3885                    raise,
3886                    generations[gen].bytes_allocated,
3887                    generations[gen].gc_trigger,
3888                    generations[gen].num_gc));
3889         }
3890
3891         /* If an older generation is being filled, then update its
3892          * memory age. */
3893         if (raise == 1) {
3894             generations[gen+1].cum_sum_bytes_allocated +=
3895                 generations[gen+1].bytes_allocated;
3896         }
3897
3898         garbage_collect_generation(gen, raise);
3899
3900         /* Reset the memory age cum_sum. */
3901         generations[gen].cum_sum_bytes_allocated = 0;
3902
3903         if (gencgc_verbose > 1) {
3904             FSHOW((stderr, "GC of generation %d finished:\n", gen));
3905             print_generation_stats();
3906         }
3907
3908         gen++;
3909     } while ((gen <= gencgc_oldest_gen_to_gc)
3910              && ((gen < last_gen)
3911                  || ((gen <= gencgc_oldest_gen_to_gc)
3912                      && raise
3913                      && (generations[gen].bytes_allocated
3914                          > generations[gen].gc_trigger)
3915                      && (generation_average_age(gen)
3916                          > generations[gen].minimum_age_before_gc))));
3917
3918     /* Now if gen-1 was raised all generations before gen are empty.
3919      * If it wasn't raised then all generations before gen-1 are empty.
3920      *
3921      * Now objects within this gen's pages cannot point to younger
3922      * generations unless they are written to. This can be exploited
3923      * by write-protecting the pages of gen; then when younger
3924      * generations are GCed only the pages which have been written
3925      * need scanning. */
3926     if (raise)
3927         gen_to_wp = gen;
3928     else
3929         gen_to_wp = gen - 1;
3930
3931     /* There's not much point in WPing pages in generation 0 as it is
3932      * never scavenged (except promoted pages). */
3933     if ((gen_to_wp > 0) && enable_page_protection) {
3934         /* Check that they are all empty. */
3935         for (i = 0; i < gen_to_wp; i++) {
3936             if (generations[i].bytes_allocated)
3937                 lose("trying to write-protect gen. %d when gen. %d nonempty\n",
3938                      gen_to_wp, i);
3939         }
3940         write_protect_generation_pages(gen_to_wp);
3941     }
3942
3943     /* Set gc_alloc() back to generation 0. The current regions should
3944      * be flushed after the above GCs. */
3945     gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
3946     gc_alloc_generation = 0;
3947
3948     /* Save the high-water mark before updating last_free_page */
3949     if (last_free_page > high_water_mark)
3950         high_water_mark = last_free_page;
3951
3952     update_dynamic_space_free_pointer();
3953
3954     auto_gc_trigger = bytes_allocated + bytes_consed_between_gcs;
3955     if(gencgc_verbose)
3956         fprintf(stderr,"Next gc when %ld bytes have been consed\n",
3957                 auto_gc_trigger);
3958
3959     /* If we did a big GC (arbitrarily defined as gen > 1), release memory
3960      * back to the OS.
3961      */
3962     if (gen > small_generation_limit) {
3963         if (last_free_page > high_water_mark)
3964             high_water_mark = last_free_page;
3965         remap_free_pages(0, high_water_mark, 0);
3966         high_water_mark = 0;
3967     }
3968
3969     gc_active_p = 0;
3970
3971     log_generation_stats(gc_logfile, "=== GC End ===");
3972     SHOW("returning from collect_garbage");
3973 }
3974
3975 /* This is called by Lisp PURIFY when it is finished. All live objects
3976  * will have been moved to the RO and Static heaps. The dynamic space
3977  * will need a full re-initialization. We don't bother having Lisp
3978  * PURIFY flush the current gc_alloc() region, as the page_tables are
3979  * re-initialized, and every page is zeroed to be sure. */
3980 void
3981 gc_free_heap(void)
3982 {
3983     page_index_t page, last_page;
3984
3985     if (gencgc_verbose > 1) {
3986         SHOW("entering gc_free_heap");
3987     }
3988
3989     for (page = 0; page < page_table_pages; page++) {
3990         /* Skip free pages which should already be zero filled. */
3991         if (page_allocated_p(page)) {
3992             void *page_start, *addr;
3993             for (last_page = page;
3994                  (last_page < page_table_pages) && page_allocated_p(last_page);
3995                  last_page++) {
3996                 /* Mark the page free. The other slots are assumed invalid
3997                  * when it is a FREE_PAGE_FLAG and bytes_used is 0 and it
3998                  * should not be write-protected -- except that the
3999                  * generation is used for the current region but it sets
4000                  * that up. */
4001                 page_table[page].allocated = FREE_PAGE_FLAG;
4002                 page_table[page].bytes_used = 0;
4003                 page_table[page].write_protected = 0;
4004             }
4005
4006 #ifndef LISP_FEATURE_WIN32 /* Pages already zeroed on win32? Not sure
4007                             * about this change. */
4008             page_start = (void *)page_address(page);
4009             os_protect(page_start, npage_bytes(last_page-page), OS_VM_PROT_ALL);
4010             remap_free_pages(page, last_page-1, 1);
4011             page = last_page-1;
4012 #endif
4013         } else if (gencgc_zero_check_during_free_heap) {
4014             /* Double-check that the page is zero filled. */
4015             long *page_start;
4016             page_index_t i;
4017             gc_assert(page_free_p(page));
4018             gc_assert(page_table[page].bytes_used == 0);
4019             page_start = (long *)page_address(page);
4020             for (i=0; i<GENCGC_CARD_BYTES/sizeof(long); i++) {
4021                 if (page_start[i] != 0) {
4022                     lose("free region not zero at %x\n", page_start + i);
4023                 }
4024             }
4025         }
4026     }
4027
4028     bytes_allocated = 0;
4029
4030     /* Initialize the generations. */
4031     for (page = 0; page < NUM_GENERATIONS; page++) {
4032         generations[page].alloc_start_page = 0;
4033         generations[page].alloc_unboxed_start_page = 0;
4034         generations[page].alloc_large_start_page = 0;
4035         generations[page].alloc_large_unboxed_start_page = 0;
4036         generations[page].bytes_allocated = 0;
4037         generations[page].gc_trigger = 2000000;
4038         generations[page].num_gc = 0;
4039         generations[page].cum_sum_bytes_allocated = 0;
4040     }
4041
4042     if (gencgc_verbose > 1)
4043         print_generation_stats();
4044
4045     /* Initialize gc_alloc(). */
4046     gc_alloc_generation = 0;
4047
4048     gc_set_region_empty(&boxed_region);
4049     gc_set_region_empty(&unboxed_region);
4050
4051     last_free_page = 0;
4052     set_alloc_pointer((lispobj)((char *)heap_base));
4053
4054     if (verify_after_free_heap) {
4055         /* Check whether purify has left any bad pointers. */
4056         FSHOW((stderr, "checking after free_heap\n"));
4057         verify_gc();
4058     }
4059 }
4060 \f
4061 void
4062 gc_init(void)
4063 {
4064     page_index_t i;
4065
4066     /* Compute the number of pages needed for the dynamic space.
4067      * Dynamic space size should be aligned on page size. */
4068     page_table_pages = dynamic_space_size/GENCGC_CARD_BYTES;
4069     gc_assert(dynamic_space_size == npage_bytes(page_table_pages));
4070
4071     /* Default nursery size to 5% of the total dynamic space size,
4072      * min 1Mb. */
4073     bytes_consed_between_gcs = dynamic_space_size/(os_vm_size_t)20;
4074     if (bytes_consed_between_gcs < (1024*1024))
4075         bytes_consed_between_gcs = 1024*1024;
4076
4077     /* The page_table must be allocated using "calloc" to initialize
4078      * the page structures correctly. There used to be a separate
4079      * initialization loop (now commented out; see below) but that was
4080      * unnecessary and did hurt startup time. */
4081     page_table = calloc(page_table_pages, sizeof(struct page));
4082     gc_assert(page_table);
4083
4084     gc_init_tables();
4085     scavtab[WEAK_POINTER_WIDETAG] = scav_weak_pointer;
4086     transother[SIMPLE_ARRAY_WIDETAG] = trans_boxed_large;
4087
4088     heap_base = (void*)DYNAMIC_SPACE_START;
4089
4090     /* The page structures are initialized implicitly when page_table
4091      * is allocated with "calloc" above. Formerly we had the following
4092      * explicit initialization here (comments converted to C99 style
4093      * for readability as C's block comments don't nest):
4094      *
4095      * // Initialize each page structure.
4096      * for (i = 0; i < page_table_pages; i++) {
4097      *     // Initialize all pages as free.
4098      *     page_table[i].allocated = FREE_PAGE_FLAG;
4099      *     page_table[i].bytes_used = 0;
4100      *
4101      *     // Pages are not write-protected at startup.
4102      *     page_table[i].write_protected = 0;
4103      * }
4104      *
4105      * Without this loop the image starts up much faster when dynamic
4106      * space is large -- which it is on 64-bit platforms already by
4107      * default -- and when "calloc" for large arrays is implemented
4108      * using copy-on-write of a page of zeroes -- which it is at least
4109      * on Linux. In this case the pages that page_table_pages is stored
4110      * in are mapped and cleared not before the corresponding part of
4111      * dynamic space is used. For example, this saves clearing 16 MB of
4112      * memory at startup if the page size is 4 KB and the size of
4113      * dynamic space is 4 GB.
4114      * FREE_PAGE_FLAG must be 0 for this to work correctly which is
4115      * asserted below: */
4116     {
4117       /* Compile time assertion: If triggered, declares an array
4118        * of dimension -1 forcing a syntax error. The intent of the
4119        * assignment is to avoid an "unused variable" warning. */
4120       char assert_free_page_flag_0[(FREE_PAGE_FLAG) ? -1 : 1];
4121       assert_free_page_flag_0[0] = assert_free_page_flag_0[0];
4122     }
4123
4124     bytes_allocated = 0;
4125
4126     /* Initialize the generations.
4127      *
4128      * FIXME: very similar to code in gc_free_heap(), should be shared */
4129     for (i = 0; i < NUM_GENERATIONS; i++) {
4130         generations[i].alloc_start_page = 0;
4131         generations[i].alloc_unboxed_start_page = 0;
4132         generations[i].alloc_large_start_page = 0;
4133         generations[i].alloc_large_unboxed_start_page = 0;
4134         generations[i].bytes_allocated = 0;
4135         generations[i].gc_trigger = 2000000;
4136         generations[i].num_gc = 0;
4137         generations[i].cum_sum_bytes_allocated = 0;
4138         /* the tune-able parameters */
4139         generations[i].bytes_consed_between_gc = 2000000;
4140         generations[i].number_of_gcs_before_promotion = 1;
4141         generations[i].minimum_age_before_gc = 0.75;
4142     }
4143
4144     /* Initialize gc_alloc. */
4145     gc_alloc_generation = 0;
4146     gc_set_region_empty(&boxed_region);
4147     gc_set_region_empty(&unboxed_region);
4148
4149     last_free_page = 0;
4150 }
4151
4152 /*  Pick up the dynamic space from after a core load.
4153  *
4154  *  The ALLOCATION_POINTER points to the end of the dynamic space.
4155  */
4156
4157 static void
4158 gencgc_pickup_dynamic(void)
4159 {
4160     page_index_t page = 0;
4161     void *alloc_ptr = (void *)get_alloc_pointer();
4162     lispobj *prev=(lispobj *)page_address(page);
4163     generation_index_t gen = PSEUDO_STATIC_GENERATION;
4164     do {
4165         lispobj *first,*ptr= (lispobj *)page_address(page);
4166
4167         if (!gencgc_partial_pickup || page_allocated_p(page)) {
4168           /* It is possible, though rare, for the saved page table
4169            * to contain free pages below alloc_ptr. */
4170           page_table[page].gen = gen;
4171           page_table[page].bytes_used = GENCGC_CARD_BYTES;
4172           page_table[page].large_object = 0;
4173           page_table[page].write_protected = 0;
4174           page_table[page].write_protected_cleared = 0;
4175           page_table[page].dont_move = 0;
4176           page_table[page].need_to_zero = 1;
4177         }
4178
4179         if (!gencgc_partial_pickup) {
4180             page_table[page].allocated = BOXED_PAGE_FLAG;
4181             first=gc_search_space(prev,(ptr+2)-prev,ptr);
4182             if(ptr == first)
4183                 prev=ptr;
4184             page_table[page].region_start_offset =
4185                 page_address(page) - (void *)prev;
4186         }
4187         page++;
4188     } while (page_address(page) < alloc_ptr);
4189
4190     last_free_page = page;
4191
4192     generations[gen].bytes_allocated = npage_bytes(page);
4193     bytes_allocated = npage_bytes(page);
4194
4195     gc_alloc_update_all_page_tables();
4196     write_protect_generation_pages(gen);
4197 }
4198
4199 void
4200 gc_initialize_pointers(void)
4201 {
4202     gencgc_pickup_dynamic();
4203 }
4204 \f
4205
4206 /* alloc(..) is the external interface for memory allocation. It
4207  * allocates to generation 0. It is not called from within the garbage
4208  * collector as it is only external uses that need the check for heap
4209  * size (GC trigger) and to disable the interrupts (interrupts are
4210  * always disabled during a GC).
4211  *
4212  * The vops that call alloc(..) assume that the returned space is zero-filled.
4213  * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
4214  *
4215  * The check for a GC trigger is only performed when the current
4216  * region is full, so in most cases it's not needed. */
4217
4218 static inline lispobj *
4219 general_alloc_internal(long nbytes, int page_type_flag, struct alloc_region *region,
4220                        struct thread *thread)
4221 {
4222 #ifndef LISP_FEATURE_WIN32
4223     lispobj alloc_signal;
4224 #endif
4225     void *new_obj;
4226     void *new_free_pointer;
4227
4228     gc_assert(nbytes>0);
4229
4230     /* Check for alignment allocation problems. */
4231     gc_assert((((unsigned long)region->free_pointer & LOWTAG_MASK) == 0)
4232               && ((nbytes & LOWTAG_MASK) == 0));
4233
4234     /* Must be inside a PA section. */
4235     gc_assert(get_pseudo_atomic_atomic(thread));
4236
4237     /* maybe we can do this quickly ... */
4238     new_free_pointer = region->free_pointer + nbytes;
4239     if (new_free_pointer <= region->end_addr) {
4240         new_obj = (void*)(region->free_pointer);
4241         region->free_pointer = new_free_pointer;
4242         return(new_obj);        /* yup */
4243     }
4244
4245     /* we have to go the long way around, it seems. Check whether we
4246      * should GC in the near future
4247      */
4248     if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
4249         /* Don't flood the system with interrupts if the need to gc is
4250          * already noted. This can happen for example when SUB-GC
4251          * allocates or after a gc triggered in a WITHOUT-GCING. */
4252         if (SymbolValue(GC_PENDING,thread) == NIL) {
4253             /* set things up so that GC happens when we finish the PA
4254              * section */
4255             SetSymbolValue(GC_PENDING,T,thread);
4256             if (SymbolValue(GC_INHIBIT,thread) == NIL) {
4257                 set_pseudo_atomic_interrupted(thread);
4258 #ifdef LISP_FEATURE_PPC
4259                 /* PPC calls alloc() from a trap or from pa_alloc(),
4260                  * look up the most context if it's from a trap. */
4261                 {
4262                     os_context_t *context =
4263                         thread->interrupt_data->allocation_trap_context;
4264                     maybe_save_gc_mask_and_block_deferrables
4265                         (context ? os_context_sigmask_addr(context) : NULL);
4266                 }
4267 #else
4268                 maybe_save_gc_mask_and_block_deferrables(NULL);
4269 #endif
4270             }
4271         }
4272     }
4273     new_obj = gc_alloc_with_region(nbytes, page_type_flag, region, 0);
4274
4275 #ifndef LISP_FEATURE_WIN32
4276     alloc_signal = SymbolValue(ALLOC_SIGNAL,thread);
4277     if ((alloc_signal & FIXNUM_TAG_MASK) == 0) {
4278         if ((signed long) alloc_signal <= 0) {
4279             SetSymbolValue(ALLOC_SIGNAL, T, thread);
4280             raise(SIGPROF);
4281         } else {
4282             SetSymbolValue(ALLOC_SIGNAL,
4283                            alloc_signal - (1 << N_FIXNUM_TAG_BITS),
4284                            thread);
4285         }
4286     }
4287 #endif
4288
4289     return (new_obj);
4290 }
4291
4292 lispobj *
4293 general_alloc(long nbytes, int page_type_flag)
4294 {
4295     struct thread *thread = arch_os_get_current_thread();
4296     /* Select correct region, and call general_alloc_internal with it.
4297      * For other then boxed allocation we must lock first, since the
4298      * region is shared. */
4299     if (BOXED_PAGE_FLAG & page_type_flag) {
4300 #ifdef LISP_FEATURE_SB_THREAD
4301         struct alloc_region *region = (thread ? &(thread->alloc_region) : &boxed_region);
4302 #else
4303         struct alloc_region *region = &boxed_region;
4304 #endif
4305         return general_alloc_internal(nbytes, page_type_flag, region, thread);
4306     } else if (UNBOXED_PAGE_FLAG == page_type_flag) {
4307         lispobj * obj;
4308         gc_assert(0 == thread_mutex_lock(&allocation_lock));
4309         obj = general_alloc_internal(nbytes, page_type_flag, &unboxed_region, thread);
4310         gc_assert(0 == thread_mutex_unlock(&allocation_lock));
4311         return obj;
4312     } else {
4313         lose("bad page type flag: %d", page_type_flag);
4314     }
4315 }
4316
4317 lispobj *
4318 alloc(long nbytes)
4319 {
4320     gc_assert(get_pseudo_atomic_atomic(arch_os_get_current_thread()));
4321     return general_alloc(nbytes, BOXED_PAGE_FLAG);
4322 }
4323 \f
4324 /*
4325  * shared support for the OS-dependent signal handlers which
4326  * catch GENCGC-related write-protect violations
4327  */
4328 void unhandled_sigmemoryfault(void* addr);
4329
4330 /* Depending on which OS we're running under, different signals might
4331  * be raised for a violation of write protection in the heap. This
4332  * function factors out the common generational GC magic which needs
4333  * to invoked in this case, and should be called from whatever signal
4334  * handler is appropriate for the OS we're running under.
4335  *
4336  * Return true if this signal is a normal generational GC thing that
4337  * we were able to handle, or false if it was abnormal and control
4338  * should fall through to the general SIGSEGV/SIGBUS/whatever logic. */
4339
4340 int
4341 gencgc_handle_wp_violation(void* fault_addr)
4342 {
4343     page_index_t page_index = find_page_index(fault_addr);
4344
4345 #if QSHOW_SIGNALS
4346     FSHOW((stderr, "heap WP violation? fault_addr=%x, page_index=%d\n",
4347            fault_addr, page_index));
4348 #endif
4349
4350     /* Check whether the fault is within the dynamic space. */
4351     if (page_index == (-1)) {
4352
4353         /* It can be helpful to be able to put a breakpoint on this
4354          * case to help diagnose low-level problems. */
4355         unhandled_sigmemoryfault(fault_addr);
4356
4357         /* not within the dynamic space -- not our responsibility */
4358         return 0;
4359
4360     } else {
4361         int ret;
4362         ret = thread_mutex_lock(&free_pages_lock);
4363         gc_assert(ret == 0);
4364         if (page_table[page_index].write_protected) {
4365             /* Unprotect the page. */
4366             os_protect(page_address(page_index), GENCGC_CARD_BYTES, OS_VM_PROT_ALL);
4367             page_table[page_index].write_protected_cleared = 1;
4368             page_table[page_index].write_protected = 0;
4369         } else {
4370             /* The only acceptable reason for this signal on a heap
4371              * access is that GENCGC write-protected the page.
4372              * However, if two CPUs hit a wp page near-simultaneously,
4373              * we had better not have the second one lose here if it
4374              * does this test after the first one has already set wp=0
4375              */
4376             if(page_table[page_index].write_protected_cleared != 1)
4377                 lose("fault in heap page %d not marked as write-protected\nboxed_region.first_page: %d, boxed_region.last_page %d\n",
4378                      page_index, boxed_region.first_page,
4379                      boxed_region.last_page);
4380         }
4381         ret = thread_mutex_unlock(&free_pages_lock);
4382         gc_assert(ret == 0);
4383         /* Don't worry, we can handle it. */
4384         return 1;
4385     }
4386 }
4387 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
4388  * it's not just a case of the program hitting the write barrier, and
4389  * are about to let Lisp deal with it. It's basically just a
4390  * convenient place to set a gdb breakpoint. */
4391 void
4392 unhandled_sigmemoryfault(void *addr)
4393 {}
4394
4395 void gc_alloc_update_all_page_tables(void)
4396 {
4397     /* Flush the alloc regions updating the tables. */
4398     struct thread *th;
4399     for_each_thread(th)
4400         gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
4401     gc_alloc_update_page_tables(UNBOXED_PAGE_FLAG, &unboxed_region);
4402     gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &boxed_region);
4403 }
4404
4405 void
4406 gc_set_region_empty(struct alloc_region *region)
4407 {
4408     region->first_page = 0;
4409     region->last_page = -1;
4410     region->start_addr = page_address(0);
4411     region->free_pointer = page_address(0);
4412     region->end_addr = page_address(0);
4413 }
4414
4415 static void
4416 zero_all_free_pages()
4417 {
4418     page_index_t i;
4419
4420     for (i = 0; i < last_free_page; i++) {
4421         if (page_free_p(i)) {
4422 #ifdef READ_PROTECT_FREE_PAGES
4423             os_protect(page_address(i),
4424                        GENCGC_CARD_BYTES,
4425                        OS_VM_PROT_ALL);
4426 #endif
4427             zero_pages(i, i);
4428         }
4429     }
4430 }
4431
4432 /* Things to do before doing a final GC before saving a core (without
4433  * purify).
4434  *
4435  * + Pages in large_object pages aren't moved by the GC, so we need to
4436  *   unset that flag from all pages.
4437  * + The pseudo-static generation isn't normally collected, but it seems
4438  *   reasonable to collect it at least when saving a core. So move the
4439  *   pages to a normal generation.
4440  */
4441 static void
4442 prepare_for_final_gc ()
4443 {
4444     page_index_t i;
4445     for (i = 0; i < last_free_page; i++) {
4446         page_table[i].large_object = 0;
4447         if (page_table[i].gen == PSEUDO_STATIC_GENERATION) {
4448             int used = page_table[i].bytes_used;
4449             page_table[i].gen = HIGHEST_NORMAL_GENERATION;
4450             generations[PSEUDO_STATIC_GENERATION].bytes_allocated -= used;
4451             generations[HIGHEST_NORMAL_GENERATION].bytes_allocated += used;
4452         }
4453     }
4454 }
4455
4456
4457 /* Do a non-conservative GC, and then save a core with the initial
4458  * function being set to the value of the static symbol
4459  * SB!VM:RESTART-LISP-FUNCTION */
4460 void
4461 gc_and_save(char *filename, boolean prepend_runtime,
4462             boolean save_runtime_options,
4463             boolean compressed, int compression_level)
4464 {
4465     FILE *file;
4466     void *runtime_bytes = NULL;
4467     size_t runtime_size;
4468
4469     file = prepare_to_save(filename, prepend_runtime, &runtime_bytes,
4470                            &runtime_size);
4471     if (file == NULL)
4472        return;
4473
4474     conservative_stack = 0;
4475
4476     /* The filename might come from Lisp, and be moved by the now
4477      * non-conservative GC. */
4478     filename = strdup(filename);
4479
4480     /* Collect twice: once into relatively high memory, and then back
4481      * into low memory. This compacts the retained data into the lower
4482      * pages, minimizing the size of the core file.
4483      */
4484     prepare_for_final_gc();
4485     gencgc_alloc_start_page = last_free_page;
4486     collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4487
4488     prepare_for_final_gc();
4489     gencgc_alloc_start_page = -1;
4490     collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4491
4492     if (prepend_runtime)
4493         save_runtime_to_filehandle(file, runtime_bytes, runtime_size);
4494
4495     /* The dumper doesn't know that pages need to be zeroed before use. */
4496     zero_all_free_pages();
4497     save_to_filehandle(file, filename, SymbolValue(RESTART_LISP_FUNCTION,0),
4498                        prepend_runtime, save_runtime_options,
4499                        compressed ? compression_level : COMPRESSION_LEVEL_NONE);
4500     /* Oops. Save still managed to fail. Since we've mangled the stack
4501      * beyond hope, there's not much we can do.
4502      * (beyond FUNCALLing RESTART_LISP_FUNCTION, but I suspect that's
4503      * going to be rather unsatisfactory too... */
4504     lose("Attempt to save core after non-conservative GC failed.\n");
4505 }