killing lutexes, adding timeouts
[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 unsigned long bytes_allocated = 0;
153 unsigned long 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     unsigned long bytes_allocated;
289
290     /* the number of bytes at which to trigger a GC */
291     unsigned long gc_trigger;
292
293     /* to calculate a new level for gc_trigger */
294     unsigned long 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     unsigned long 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", 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 /* Helper for valid_lisp_pointer_p and
2111  * possibly_valid_dynamic_space_pointer.
2112  *
2113  * pointer is the pointer to validate, and start_addr is the address
2114  * of the enclosing object.
2115  */
2116 static int
2117 looks_like_valid_lisp_pointer_p(lispobj *pointer, lispobj *start_addr)
2118 {
2119     if (!is_lisp_pointer((lispobj)pointer)) {
2120         return 0;
2121     }
2122
2123     /* Check that the object pointed to is consistent with the pointer
2124      * low tag. */
2125     switch (lowtag_of((lispobj)pointer)) {
2126     case FUN_POINTER_LOWTAG:
2127         /* Start_addr should be the enclosing code object, or a closure
2128          * header. */
2129         switch (widetag_of(*start_addr)) {
2130         case CODE_HEADER_WIDETAG:
2131           /* Make sure we actually point to a function in the code object,
2132            * as opposed to a random point there. */
2133           if (SIMPLE_FUN_HEADER_WIDETAG==widetag_of(*(pointer-FUN_POINTER_LOWTAG)))
2134             return 1;
2135           else
2136             return 0;
2137         case CLOSURE_HEADER_WIDETAG:
2138         case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
2139             if ((unsigned long)pointer !=
2140                 ((unsigned long)start_addr+FUN_POINTER_LOWTAG)) {
2141                 if (gencgc_verbose) {
2142                     FSHOW((stderr,
2143                            "/Wf2: %x %x %x\n",
2144                            pointer, start_addr, *start_addr));
2145                 }
2146                 return 0;
2147             }
2148             break;
2149         default:
2150             if (gencgc_verbose) {
2151                 FSHOW((stderr,
2152                        "/Wf3: %x %x %x\n",
2153                        pointer, start_addr, *start_addr));
2154             }
2155             return 0;
2156         }
2157         break;
2158     case LIST_POINTER_LOWTAG:
2159         if ((unsigned long)pointer !=
2160             ((unsigned long)start_addr+LIST_POINTER_LOWTAG)) {
2161             if (gencgc_verbose) {
2162                 FSHOW((stderr,
2163                        "/Wl1: %x %x %x\n",
2164                        pointer, start_addr, *start_addr));
2165             }
2166             return 0;
2167         }
2168         /* Is it plausible cons? */
2169         if ((is_lisp_pointer(start_addr[0]) ||
2170              is_lisp_immediate(start_addr[0])) &&
2171             (is_lisp_pointer(start_addr[1]) ||
2172              is_lisp_immediate(start_addr[1])))
2173             break;
2174         else {
2175             if (gencgc_verbose) {
2176                 FSHOW((stderr,
2177                        "/Wl2: %x %x %x\n",
2178                        pointer, start_addr, *start_addr));
2179             }
2180             return 0;
2181         }
2182     case INSTANCE_POINTER_LOWTAG:
2183         if ((unsigned long)pointer !=
2184             ((unsigned long)start_addr+INSTANCE_POINTER_LOWTAG)) {
2185             if (gencgc_verbose) {
2186                 FSHOW((stderr,
2187                        "/Wi1: %x %x %x\n",
2188                        pointer, start_addr, *start_addr));
2189             }
2190             return 0;
2191         }
2192         if (widetag_of(start_addr[0]) != INSTANCE_HEADER_WIDETAG) {
2193             if (gencgc_verbose) {
2194                 FSHOW((stderr,
2195                        "/Wi2: %x %x %x\n",
2196                        pointer, start_addr, *start_addr));
2197             }
2198             return 0;
2199         }
2200         break;
2201     case OTHER_POINTER_LOWTAG:
2202
2203 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
2204         /* The all-architecture test below is good as far as it goes,
2205          * but an LRA object is similar to a FUN-POINTER: It is
2206          * embedded within a CODE-OBJECT pointed to by start_addr, and
2207          * cannot be found by simply walking the heap, therefore we
2208          * need to check for it. -- AB, 2010-Jun-04 */
2209         if ((widetag_of(start_addr[0]) == CODE_HEADER_WIDETAG)) {
2210             lispobj *potential_lra =
2211                 (lispobj *)(((unsigned long)pointer) - OTHER_POINTER_LOWTAG);
2212             if ((widetag_of(potential_lra[0]) == RETURN_PC_HEADER_WIDETAG) &&
2213                 ((potential_lra - HeaderValue(potential_lra[0])) == start_addr)) {
2214                 return 1; /* It's as good as we can verify. */
2215             }
2216         }
2217 #endif
2218
2219         if ((unsigned long)pointer !=
2220             ((unsigned long)start_addr+OTHER_POINTER_LOWTAG)) {
2221             if (gencgc_verbose) {
2222                 FSHOW((stderr,
2223                        "/Wo1: %x %x %x\n",
2224                        pointer, start_addr, *start_addr));
2225             }
2226             return 0;
2227         }
2228         /* Is it plausible?  Not a cons. XXX should check the headers. */
2229         if (is_lisp_pointer(start_addr[0]) || ((start_addr[0] & 3) == 0)) {
2230             if (gencgc_verbose) {
2231                 FSHOW((stderr,
2232                        "/Wo2: %x %x %x\n",
2233                        pointer, start_addr, *start_addr));
2234             }
2235             return 0;
2236         }
2237         switch (widetag_of(start_addr[0])) {
2238         case UNBOUND_MARKER_WIDETAG:
2239         case NO_TLS_VALUE_MARKER_WIDETAG:
2240         case CHARACTER_WIDETAG:
2241 #if N_WORD_BITS == 64
2242         case SINGLE_FLOAT_WIDETAG:
2243 #endif
2244             if (gencgc_verbose) {
2245                 FSHOW((stderr,
2246                        "*Wo3: %x %x %x\n",
2247                        pointer, start_addr, *start_addr));
2248             }
2249             return 0;
2250
2251             /* only pointed to by function pointers? */
2252         case CLOSURE_HEADER_WIDETAG:
2253         case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
2254             if (gencgc_verbose) {
2255                 FSHOW((stderr,
2256                        "*Wo4: %x %x %x\n",
2257                        pointer, start_addr, *start_addr));
2258             }
2259             return 0;
2260
2261         case INSTANCE_HEADER_WIDETAG:
2262             if (gencgc_verbose) {
2263                 FSHOW((stderr,
2264                        "*Wo5: %x %x %x\n",
2265                        pointer, start_addr, *start_addr));
2266             }
2267             return 0;
2268
2269             /* the valid other immediate pointer objects */
2270         case SIMPLE_VECTOR_WIDETAG:
2271         case RATIO_WIDETAG:
2272         case COMPLEX_WIDETAG:
2273 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
2274         case COMPLEX_SINGLE_FLOAT_WIDETAG:
2275 #endif
2276 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
2277         case COMPLEX_DOUBLE_FLOAT_WIDETAG:
2278 #endif
2279 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
2280         case COMPLEX_LONG_FLOAT_WIDETAG:
2281 #endif
2282         case SIMPLE_ARRAY_WIDETAG:
2283         case COMPLEX_BASE_STRING_WIDETAG:
2284 #ifdef COMPLEX_CHARACTER_STRING_WIDETAG
2285         case COMPLEX_CHARACTER_STRING_WIDETAG:
2286 #endif
2287         case COMPLEX_VECTOR_NIL_WIDETAG:
2288         case COMPLEX_BIT_VECTOR_WIDETAG:
2289         case COMPLEX_VECTOR_WIDETAG:
2290         case COMPLEX_ARRAY_WIDETAG:
2291         case VALUE_CELL_HEADER_WIDETAG:
2292         case SYMBOL_HEADER_WIDETAG:
2293         case FDEFN_WIDETAG:
2294         case CODE_HEADER_WIDETAG:
2295         case BIGNUM_WIDETAG:
2296 #if N_WORD_BITS != 64
2297         case SINGLE_FLOAT_WIDETAG:
2298 #endif
2299         case DOUBLE_FLOAT_WIDETAG:
2300 #ifdef LONG_FLOAT_WIDETAG
2301         case LONG_FLOAT_WIDETAG:
2302 #endif
2303         case SIMPLE_BASE_STRING_WIDETAG:
2304 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
2305         case SIMPLE_CHARACTER_STRING_WIDETAG:
2306 #endif
2307         case SIMPLE_BIT_VECTOR_WIDETAG:
2308         case SIMPLE_ARRAY_NIL_WIDETAG:
2309         case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2310         case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2311         case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
2312         case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2313         case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
2314         case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2315
2316         case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
2317
2318         case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
2319         case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2320 #ifdef  SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
2321         case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
2322 #endif
2323 #ifdef  SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
2324         case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
2325 #endif
2326 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2327         case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2328 #endif
2329 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2330         case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2331 #endif
2332
2333         case SIMPLE_ARRAY_FIXNUM_WIDETAG:
2334
2335 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2336         case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2337 #endif
2338 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
2339         case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
2340 #endif
2341         case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2342         case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2343 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2344         case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2345 #endif
2346 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2347         case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2348 #endif
2349 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2350         case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2351 #endif
2352 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2353         case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2354 #endif
2355         case SAP_WIDETAG:
2356         case WEAK_POINTER_WIDETAG:
2357             break;
2358
2359         default:
2360             if (gencgc_verbose) {
2361                 FSHOW((stderr,
2362                        "/Wo6: %x %x %x\n",
2363                        pointer, start_addr, *start_addr));
2364             }
2365             return 0;
2366         }
2367         break;
2368     default:
2369         if (gencgc_verbose) {
2370             FSHOW((stderr,
2371                    "*W?: %x %x %x\n",
2372                    pointer, start_addr, *start_addr));
2373         }
2374         return 0;
2375     }
2376
2377     /* looks good */
2378     return 1;
2379 }
2380
2381 /* Used by the debugger to validate possibly bogus pointers before
2382  * calling MAKE-LISP-OBJ on them.
2383  *
2384  * FIXME: We would like to make this perfect, because if the debugger
2385  * constructs a reference to a bugs lisp object, and it ends up in a
2386  * location scavenged by the GC all hell breaks loose.
2387  *
2388  * Whereas possibly_valid_dynamic_space_pointer has to be conservative
2389  * and return true for all valid pointers, this could actually be eager
2390  * and lie about a few pointers without bad results... but that should
2391  * be reflected in the name.
2392  */
2393 int
2394 valid_lisp_pointer_p(lispobj *pointer)
2395 {
2396     lispobj *start;
2397     if (((start=search_dynamic_space(pointer))!=NULL) ||
2398         ((start=search_static_space(pointer))!=NULL) ||
2399         ((start=search_read_only_space(pointer))!=NULL))
2400         return looks_like_valid_lisp_pointer_p(pointer, start);
2401     else
2402         return 0;
2403 }
2404
2405 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2406
2407 /* Is there any possibility that pointer is a valid Lisp object
2408  * reference, and/or something else (e.g. subroutine call return
2409  * address) which should prevent us from moving the referred-to thing?
2410  * This is called from preserve_pointers() */
2411 static int
2412 possibly_valid_dynamic_space_pointer(lispobj *pointer)
2413 {
2414     lispobj *start_addr;
2415
2416     /* Find the object start address. */
2417     if ((start_addr = search_dynamic_space(pointer)) == NULL) {
2418         return 0;
2419     }
2420
2421     return looks_like_valid_lisp_pointer_p(pointer, start_addr);
2422 }
2423
2424 #endif  // defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2425
2426 /* Adjust large bignum and vector objects. This will adjust the
2427  * allocated region if the size has shrunk, and move unboxed objects
2428  * into unboxed pages. The pages are not promoted here, and the
2429  * promoted region is not added to the new_regions; this is really
2430  * only designed to be called from preserve_pointer(). Shouldn't fail
2431  * if this is missed, just may delay the moving of objects to unboxed
2432  * pages, and the freeing of pages. */
2433 static void
2434 maybe_adjust_large_object(lispobj *where)
2435 {
2436     page_index_t first_page;
2437     page_index_t next_page;
2438     long nwords;
2439
2440     unsigned long remaining_bytes;
2441     unsigned long bytes_freed;
2442     unsigned long old_bytes_used;
2443
2444     int boxed;
2445
2446     /* Check whether it's a vector or bignum object. */
2447     switch (widetag_of(where[0])) {
2448     case SIMPLE_VECTOR_WIDETAG:
2449         boxed = BOXED_PAGE_FLAG;
2450         break;
2451     case BIGNUM_WIDETAG:
2452     case SIMPLE_BASE_STRING_WIDETAG:
2453 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
2454     case SIMPLE_CHARACTER_STRING_WIDETAG:
2455 #endif
2456     case SIMPLE_BIT_VECTOR_WIDETAG:
2457     case SIMPLE_ARRAY_NIL_WIDETAG:
2458     case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
2459     case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
2460     case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
2461     case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
2462     case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
2463     case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
2464
2465     case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
2466
2467     case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
2468     case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
2469 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
2470     case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
2471 #endif
2472 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
2473     case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
2474 #endif
2475 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
2476     case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
2477 #endif
2478 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
2479     case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
2480 #endif
2481
2482     case SIMPLE_ARRAY_FIXNUM_WIDETAG:
2483
2484 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
2485     case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
2486 #endif
2487 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
2488     case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
2489 #endif
2490     case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
2491     case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
2492 #ifdef SIMPLE_ARRAY_LONG_FLOAT_WIDETAG
2493     case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
2494 #endif
2495 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
2496     case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
2497 #endif
2498 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
2499     case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
2500 #endif
2501 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
2502     case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
2503 #endif
2504         boxed = UNBOXED_PAGE_FLAG;
2505         break;
2506     default:
2507         return;
2508     }
2509
2510     /* Find its current size. */
2511     nwords = (sizetab[widetag_of(where[0])])(where);
2512
2513     first_page = find_page_index((void *)where);
2514     gc_assert(first_page >= 0);
2515
2516     /* Note: Any page write-protection must be removed, else a later
2517      * scavenge_newspace may incorrectly not scavenge these pages.
2518      * This would not be necessary if they are added to the new areas,
2519      * but lets do it for them all (they'll probably be written
2520      * anyway?). */
2521
2522     gc_assert(page_table[first_page].region_start_offset == 0);
2523
2524     next_page = first_page;
2525     remaining_bytes = nwords*N_WORD_BYTES;
2526     while (remaining_bytes > GENCGC_CARD_BYTES) {
2527         gc_assert(page_table[next_page].gen == from_space);
2528         gc_assert(page_allocated_no_region_p(next_page));
2529         gc_assert(page_table[next_page].large_object);
2530         gc_assert(page_table[next_page].region_start_offset ==
2531                   npage_bytes(next_page-first_page));
2532         gc_assert(page_table[next_page].bytes_used == GENCGC_CARD_BYTES);
2533
2534         page_table[next_page].allocated = boxed;
2535
2536         /* Shouldn't be write-protected at this stage. Essential that the
2537          * pages aren't. */
2538         gc_assert(!page_table[next_page].write_protected);
2539         remaining_bytes -= GENCGC_CARD_BYTES;
2540         next_page++;
2541     }
2542
2543     /* Now only one page remains, but the object may have shrunk so
2544      * there may be more unused pages which will be freed. */
2545
2546     /* Object may have shrunk but shouldn't have grown - check. */
2547     gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
2548
2549     page_table[next_page].allocated = boxed;
2550     gc_assert(page_table[next_page].allocated ==
2551               page_table[first_page].allocated);
2552
2553     /* Adjust the bytes_used. */
2554     old_bytes_used = page_table[next_page].bytes_used;
2555     page_table[next_page].bytes_used = remaining_bytes;
2556
2557     bytes_freed = old_bytes_used - remaining_bytes;
2558
2559     /* Free any remaining pages; needs care. */
2560     next_page++;
2561     while ((old_bytes_used == GENCGC_CARD_BYTES) &&
2562            (page_table[next_page].gen == from_space) &&
2563            page_allocated_no_region_p(next_page) &&
2564            page_table[next_page].large_object &&
2565            (page_table[next_page].region_start_offset ==
2566             npage_bytes(next_page - first_page))) {
2567         /* It checks out OK, free the page. We don't need to both zeroing
2568          * pages as this should have been done before shrinking the
2569          * object. These pages shouldn't be write protected as they
2570          * should be zero filled. */
2571         gc_assert(page_table[next_page].write_protected == 0);
2572
2573         old_bytes_used = page_table[next_page].bytes_used;
2574         page_table[next_page].allocated = FREE_PAGE_FLAG;
2575         page_table[next_page].bytes_used = 0;
2576         bytes_freed += old_bytes_used;
2577         next_page++;
2578     }
2579
2580     if ((bytes_freed > 0) && gencgc_verbose) {
2581         FSHOW((stderr,
2582                "/maybe_adjust_large_object() freed %d\n",
2583                bytes_freed));
2584     }
2585
2586     generations[from_space].bytes_allocated -= bytes_freed;
2587     bytes_allocated -= bytes_freed;
2588
2589     return;
2590 }
2591
2592 /* Take a possible pointer to a Lisp object and mark its page in the
2593  * page_table so that it will not be relocated during a GC.
2594  *
2595  * This involves locating the page it points to, then backing up to
2596  * the start of its region, then marking all pages dont_move from there
2597  * up to the first page that's not full or has a different generation
2598  *
2599  * It is assumed that all the page static flags have been cleared at
2600  * the start of a GC.
2601  *
2602  * It is also assumed that the current gc_alloc() region has been
2603  * flushed and the tables updated. */
2604
2605 static void
2606 preserve_pointer(void *addr)
2607 {
2608     page_index_t addr_page_index = find_page_index(addr);
2609     page_index_t first_page;
2610     page_index_t i;
2611     unsigned int region_allocation;
2612
2613     /* quick check 1: Address is quite likely to have been invalid. */
2614     if ((addr_page_index == -1)
2615         || page_free_p(addr_page_index)
2616         || (page_table[addr_page_index].bytes_used == 0)
2617         || (page_table[addr_page_index].gen != from_space)
2618         /* Skip if already marked dont_move. */
2619         || (page_table[addr_page_index].dont_move != 0))
2620         return;
2621     gc_assert(!(page_table[addr_page_index].allocated&OPEN_REGION_PAGE_FLAG));
2622     /* (Now that we know that addr_page_index is in range, it's
2623      * safe to index into page_table[] with it.) */
2624     region_allocation = page_table[addr_page_index].allocated;
2625
2626     /* quick check 2: Check the offset within the page.
2627      *
2628      */
2629     if (((unsigned long)addr & (GENCGC_CARD_BYTES - 1)) >
2630         page_table[addr_page_index].bytes_used)
2631         return;
2632
2633     /* Filter out anything which can't be a pointer to a Lisp object
2634      * (or, as a special case which also requires dont_move, a return
2635      * address referring to something in a CodeObject). This is
2636      * expensive but important, since it vastly reduces the
2637      * probability that random garbage will be bogusly interpreted as
2638      * a pointer which prevents a page from moving.
2639      *
2640      * This only needs to happen on x86oids, where this is used for
2641      * conservative roots.  Non-x86oid systems only ever call this
2642      * function on known-valid lisp objects. */
2643 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
2644     if (!(code_page_p(addr_page_index)
2645           || (is_lisp_pointer((lispobj)addr) &&
2646               possibly_valid_dynamic_space_pointer(addr))))
2647         return;
2648 #endif
2649
2650     /* Find the beginning of the region.  Note that there may be
2651      * objects in the region preceding the one that we were passed a
2652      * pointer to: if this is the case, we will write-protect all the
2653      * previous objects' pages too.     */
2654
2655 #if 0
2656     /* I think this'd work just as well, but without the assertions.
2657      * -dan 2004.01.01 */
2658     first_page = find_page_index(page_region_start(addr_page_index))
2659 #else
2660     first_page = addr_page_index;
2661     while (page_table[first_page].region_start_offset != 0) {
2662         --first_page;
2663         /* Do some checks. */
2664         gc_assert(page_table[first_page].bytes_used == GENCGC_CARD_BYTES);
2665         gc_assert(page_table[first_page].gen == from_space);
2666         gc_assert(page_table[first_page].allocated == region_allocation);
2667     }
2668 #endif
2669
2670     /* Adjust any large objects before promotion as they won't be
2671      * copied after promotion. */
2672     if (page_table[first_page].large_object) {
2673         maybe_adjust_large_object(page_address(first_page));
2674         /* If a large object has shrunk then addr may now point to a
2675          * free area in which case it's ignored here. Note it gets
2676          * through the valid pointer test above because the tail looks
2677          * like conses. */
2678         if (page_free_p(addr_page_index)
2679             || (page_table[addr_page_index].bytes_used == 0)
2680             /* Check the offset within the page. */
2681             || (((unsigned long)addr & (GENCGC_CARD_BYTES - 1))
2682                 > page_table[addr_page_index].bytes_used)) {
2683             FSHOW((stderr,
2684                    "weird? ignore ptr 0x%x to freed area of large object\n",
2685                    addr));
2686             return;
2687         }
2688         /* It may have moved to unboxed pages. */
2689         region_allocation = page_table[first_page].allocated;
2690     }
2691
2692     /* Now work forward until the end of this contiguous area is found,
2693      * marking all pages as dont_move. */
2694     for (i = first_page; ;i++) {
2695         gc_assert(page_table[i].allocated == region_allocation);
2696
2697         /* Mark the page static. */
2698         page_table[i].dont_move = 1;
2699
2700         /* Move the page to the new_space. XX I'd rather not do this
2701          * but the GC logic is not quite able to copy with the static
2702          * pages remaining in the from space. This also requires the
2703          * generation bytes_allocated counters be updated. */
2704         page_table[i].gen = new_space;
2705         generations[new_space].bytes_allocated += page_table[i].bytes_used;
2706         generations[from_space].bytes_allocated -= page_table[i].bytes_used;
2707
2708         /* It is essential that the pages are not write protected as
2709          * they may have pointers into the old-space which need
2710          * scavenging. They shouldn't be write protected at this
2711          * stage. */
2712         gc_assert(!page_table[i].write_protected);
2713
2714         /* Check whether this is the last page in this contiguous block.. */
2715         if ((page_table[i].bytes_used < GENCGC_CARD_BYTES)
2716             /* ..or it is CARD_BYTES and is the last in the block */
2717             || page_free_p(i+1)
2718             || (page_table[i+1].bytes_used == 0) /* next page free */
2719             || (page_table[i+1].gen != from_space) /* diff. gen */
2720             || (page_table[i+1].region_start_offset == 0))
2721             break;
2722     }
2723
2724     /* Check that the page is now static. */
2725     gc_assert(page_table[addr_page_index].dont_move != 0);
2726 }
2727 \f
2728 /* If the given page is not write-protected, then scan it for pointers
2729  * to younger generations or the top temp. generation, if no
2730  * suspicious pointers are found then the page is write-protected.
2731  *
2732  * Care is taken to check for pointers to the current gc_alloc()
2733  * region if it is a younger generation or the temp. generation. This
2734  * frees the caller from doing a gc_alloc_update_page_tables(). Actually
2735  * the gc_alloc_generation does not need to be checked as this is only
2736  * called from scavenge_generation() when the gc_alloc generation is
2737  * younger, so it just checks if there is a pointer to the current
2738  * region.
2739  *
2740  * We return 1 if the page was write-protected, else 0. */
2741 static int
2742 update_page_write_prot(page_index_t page)
2743 {
2744     generation_index_t gen = page_table[page].gen;
2745     long j;
2746     int wp_it = 1;
2747     void **page_addr = (void **)page_address(page);
2748     long num_words = page_table[page].bytes_used / N_WORD_BYTES;
2749
2750     /* Shouldn't be a free page. */
2751     gc_assert(page_allocated_p(page));
2752     gc_assert(page_table[page].bytes_used != 0);
2753
2754     /* Skip if it's already write-protected, pinned, or unboxed */
2755     if (page_table[page].write_protected
2756         /* FIXME: What's the reason for not write-protecting pinned pages? */
2757         || page_table[page].dont_move
2758         || page_unboxed_p(page))
2759         return (0);
2760
2761     /* Scan the page for pointers to younger generations or the
2762      * top temp. generation. */
2763
2764     for (j = 0; j < num_words; j++) {
2765         void *ptr = *(page_addr+j);
2766         page_index_t index = find_page_index(ptr);
2767
2768         /* Check that it's in the dynamic space */
2769         if (index != -1)
2770             if (/* Does it point to a younger or the temp. generation? */
2771                 (page_allocated_p(index)
2772                  && (page_table[index].bytes_used != 0)
2773                  && ((page_table[index].gen < gen)
2774                      || (page_table[index].gen == SCRATCH_GENERATION)))
2775
2776                 /* Or does it point within a current gc_alloc() region? */
2777                 || ((boxed_region.start_addr <= ptr)
2778                     && (ptr <= boxed_region.free_pointer))
2779                 || ((unboxed_region.start_addr <= ptr)
2780                     && (ptr <= unboxed_region.free_pointer))) {
2781                 wp_it = 0;
2782                 break;
2783             }
2784     }
2785
2786     if (wp_it == 1) {
2787         /* Write-protect the page. */
2788         /*FSHOW((stderr, "/write-protecting page %d gen %d\n", page, gen));*/
2789
2790         os_protect((void *)page_addr,
2791                    GENCGC_CARD_BYTES,
2792                    OS_VM_PROT_READ|OS_VM_PROT_EXECUTE);
2793
2794         /* Note the page as protected in the page tables. */
2795         page_table[page].write_protected = 1;
2796     }
2797
2798     return (wp_it);
2799 }
2800
2801 /* Scavenge all generations from FROM to TO, inclusive, except for
2802  * new_space which needs special handling, as new objects may be
2803  * added which are not checked here - use scavenge_newspace generation.
2804  *
2805  * Write-protected pages should not have any pointers to the
2806  * from_space so do need scavenging; thus write-protected pages are
2807  * not always scavenged. There is some code to check that these pages
2808  * are not written; but to check fully the write-protected pages need
2809  * to be scavenged by disabling the code to skip them.
2810  *
2811  * Under the current scheme when a generation is GCed the younger
2812  * generations will be empty. So, when a generation is being GCed it
2813  * is only necessary to scavenge the older generations for pointers
2814  * not the younger. So a page that does not have pointers to younger
2815  * generations does not need to be scavenged.
2816  *
2817  * The write-protection can be used to note pages that don't have
2818  * pointers to younger pages. But pages can be written without having
2819  * pointers to younger generations. After the pages are scavenged here
2820  * they can be scanned for pointers to younger generations and if
2821  * there are none the page can be write-protected.
2822  *
2823  * One complication is when the newspace is the top temp. generation.
2824  *
2825  * Enabling SC_GEN_CK scavenges the write-protected pages and checks
2826  * that none were written, which they shouldn't be as they should have
2827  * no pointers to younger generations. This breaks down for weak
2828  * pointers as the objects contain a link to the next and are written
2829  * if a weak pointer is scavenged. Still it's a useful check. */
2830 static void
2831 scavenge_generations(generation_index_t from, generation_index_t to)
2832 {
2833     page_index_t i;
2834     int num_wp = 0;
2835
2836 #define SC_GEN_CK 0
2837 #if SC_GEN_CK
2838     /* Clear the write_protected_cleared flags on all pages. */
2839     for (i = 0; i < page_table_pages; i++)
2840         page_table[i].write_protected_cleared = 0;
2841 #endif
2842
2843     for (i = 0; i < last_free_page; i++) {
2844         generation_index_t generation = page_table[i].gen;
2845         if (page_boxed_p(i)
2846             && (page_table[i].bytes_used != 0)
2847             && (generation != new_space)
2848             && (generation >= from)
2849             && (generation <= to)) {
2850             page_index_t last_page,j;
2851             int write_protected=1;
2852
2853             /* This should be the start of a region */
2854             gc_assert(page_table[i].region_start_offset == 0);
2855
2856             /* Now work forward until the end of the region */
2857             for (last_page = i; ; last_page++) {
2858                 write_protected =
2859                     write_protected && page_table[last_page].write_protected;
2860                 if ((page_table[last_page].bytes_used < GENCGC_CARD_BYTES)
2861                     /* Or it is CARD_BYTES and is the last in the block */
2862                     || (!page_boxed_p(last_page+1))
2863                     || (page_table[last_page+1].bytes_used == 0)
2864                     || (page_table[last_page+1].gen != generation)
2865                     || (page_table[last_page+1].region_start_offset == 0))
2866                     break;
2867             }
2868             if (!write_protected) {
2869                 scavenge(page_address(i),
2870                          ((unsigned long)(page_table[last_page].bytes_used
2871                                           + npage_bytes(last_page-i)))
2872                          /N_WORD_BYTES);
2873
2874                 /* Now scan the pages and write protect those that
2875                  * don't have pointers to younger generations. */
2876                 if (enable_page_protection) {
2877                     for (j = i; j <= last_page; j++) {
2878                         num_wp += update_page_write_prot(j);
2879                     }
2880                 }
2881                 if ((gencgc_verbose > 1) && (num_wp != 0)) {
2882                     FSHOW((stderr,
2883                            "/write protected %d pages within generation %d\n",
2884                            num_wp, generation));
2885                 }
2886             }
2887             i = last_page;
2888         }
2889     }
2890
2891 #if SC_GEN_CK
2892     /* Check that none of the write_protected pages in this generation
2893      * have been written to. */
2894     for (i = 0; i < page_table_pages; i++) {
2895         if (page_allocated_p(i)
2896             && (page_table[i].bytes_used != 0)
2897             && (page_table[i].gen == generation)
2898             && (page_table[i].write_protected_cleared != 0)) {
2899             FSHOW((stderr, "/scavenge_generation() %d\n", generation));
2900             FSHOW((stderr,
2901                    "/page bytes_used=%d region_start_offset=%lu dont_move=%d\n",
2902                     page_table[i].bytes_used,
2903                     page_table[i].region_start_offset,
2904                     page_table[i].dont_move));
2905             lose("write to protected page %d in scavenge_generation()\n", i);
2906         }
2907     }
2908 #endif
2909 }
2910
2911 \f
2912 /* Scavenge a newspace generation. As it is scavenged new objects may
2913  * be allocated to it; these will also need to be scavenged. This
2914  * repeats until there are no more objects unscavenged in the
2915  * newspace generation.
2916  *
2917  * To help improve the efficiency, areas written are recorded by
2918  * gc_alloc() and only these scavenged. Sometimes a little more will be
2919  * scavenged, but this causes no harm. An easy check is done that the
2920  * scavenged bytes equals the number allocated in the previous
2921  * scavenge.
2922  *
2923  * Write-protected pages are not scanned except if they are marked
2924  * dont_move in which case they may have been promoted and still have
2925  * pointers to the from space.
2926  *
2927  * Write-protected pages could potentially be written by alloc however
2928  * to avoid having to handle re-scavenging of write-protected pages
2929  * gc_alloc() does not write to write-protected pages.
2930  *
2931  * New areas of objects allocated are recorded alternatively in the two
2932  * new_areas arrays below. */
2933 static struct new_area new_areas_1[NUM_NEW_AREAS];
2934 static struct new_area new_areas_2[NUM_NEW_AREAS];
2935
2936 /* Do one full scan of the new space generation. This is not enough to
2937  * complete the job as new objects may be added to the generation in
2938  * the process which are not scavenged. */
2939 static void
2940 scavenge_newspace_generation_one_scan(generation_index_t generation)
2941 {
2942     page_index_t i;
2943
2944     FSHOW((stderr,
2945            "/starting one full scan of newspace generation %d\n",
2946            generation));
2947     for (i = 0; i < last_free_page; i++) {
2948         /* Note that this skips over open regions when it encounters them. */
2949         if (page_boxed_p(i)
2950             && (page_table[i].bytes_used != 0)
2951             && (page_table[i].gen == generation)
2952             && ((page_table[i].write_protected == 0)
2953                 /* (This may be redundant as write_protected is now
2954                  * cleared before promotion.) */
2955                 || (page_table[i].dont_move == 1))) {
2956             page_index_t last_page;
2957             int all_wp=1;
2958
2959             /* The scavenge will start at the region_start_offset of
2960              * page i.
2961              *
2962              * We need to find the full extent of this contiguous
2963              * block in case objects span pages.
2964              *
2965              * Now work forward until the end of this contiguous area
2966              * is found. A small area is preferred as there is a
2967              * better chance of its pages being write-protected. */
2968             for (last_page = i; ;last_page++) {
2969                 /* If all pages are write-protected and movable,
2970                  * then no need to scavenge */
2971                 all_wp=all_wp && page_table[last_page].write_protected &&
2972                     !page_table[last_page].dont_move;
2973
2974                 /* Check whether this is the last page in this
2975                  * contiguous block */
2976                 if ((page_table[last_page].bytes_used < GENCGC_CARD_BYTES)
2977                     /* Or it is CARD_BYTES and is the last in the block */
2978                     || (!page_boxed_p(last_page+1))
2979                     || (page_table[last_page+1].bytes_used == 0)
2980                     || (page_table[last_page+1].gen != generation)
2981                     || (page_table[last_page+1].region_start_offset == 0))
2982                     break;
2983             }
2984
2985             /* Do a limited check for write-protected pages.  */
2986             if (!all_wp) {
2987                 long nwords = (((unsigned long)
2988                                (page_table[last_page].bytes_used
2989                                 + npage_bytes(last_page-i)
2990                                 + page_table[i].region_start_offset))
2991                                / N_WORD_BYTES);
2992                 new_areas_ignore_page = last_page;
2993
2994                 scavenge(page_region_start(i), nwords);
2995
2996             }
2997             i = last_page;
2998         }
2999     }
3000     FSHOW((stderr,
3001            "/done with one full scan of newspace generation %d\n",
3002            generation));
3003 }
3004
3005 /* Do a complete scavenge of the newspace generation. */
3006 static void
3007 scavenge_newspace_generation(generation_index_t generation)
3008 {
3009     long i;
3010
3011     /* the new_areas array currently being written to by gc_alloc() */
3012     struct new_area (*current_new_areas)[] = &new_areas_1;
3013     long current_new_areas_index;
3014
3015     /* the new_areas created by the previous scavenge cycle */
3016     struct new_area (*previous_new_areas)[] = NULL;
3017     long previous_new_areas_index;
3018
3019     /* Flush the current regions updating the tables. */
3020     gc_alloc_update_all_page_tables();
3021
3022     /* Turn on the recording of new areas by gc_alloc(). */
3023     new_areas = current_new_areas;
3024     new_areas_index = 0;
3025
3026     /* Don't need to record new areas that get scavenged anyway during
3027      * scavenge_newspace_generation_one_scan. */
3028     record_new_objects = 1;
3029
3030     /* Start with a full scavenge. */
3031     scavenge_newspace_generation_one_scan(generation);
3032
3033     /* Record all new areas now. */
3034     record_new_objects = 2;
3035
3036     /* Give a chance to weak hash tables to make other objects live.
3037      * FIXME: The algorithm implemented here for weak hash table gcing
3038      * is O(W^2+N) as Bruno Haible warns in
3039      * http://www.haible.de/bruno/papers/cs/weak/WeakDatastructures-writeup.html
3040      * see "Implementation 2". */
3041     scav_weak_hash_tables();
3042
3043     /* Flush the current regions updating the tables. */
3044     gc_alloc_update_all_page_tables();
3045
3046     /* Grab new_areas_index. */
3047     current_new_areas_index = new_areas_index;
3048
3049     /*FSHOW((stderr,
3050              "The first scan is finished; current_new_areas_index=%d.\n",
3051              current_new_areas_index));*/
3052
3053     while (current_new_areas_index > 0) {
3054         /* Move the current to the previous new areas */
3055         previous_new_areas = current_new_areas;
3056         previous_new_areas_index = current_new_areas_index;
3057
3058         /* Scavenge all the areas in previous new areas. Any new areas
3059          * allocated are saved in current_new_areas. */
3060
3061         /* Allocate an array for current_new_areas; alternating between
3062          * new_areas_1 and 2 */
3063         if (previous_new_areas == &new_areas_1)
3064             current_new_areas = &new_areas_2;
3065         else
3066             current_new_areas = &new_areas_1;
3067
3068         /* Set up for gc_alloc(). */
3069         new_areas = current_new_areas;
3070         new_areas_index = 0;
3071
3072         /* Check whether previous_new_areas had overflowed. */
3073         if (previous_new_areas_index >= NUM_NEW_AREAS) {
3074
3075             /* New areas of objects allocated have been lost so need to do a
3076              * full scan to be sure! If this becomes a problem try
3077              * increasing NUM_NEW_AREAS. */
3078             if (gencgc_verbose) {
3079                 SHOW("new_areas overflow, doing full scavenge");
3080             }
3081
3082             /* Don't need to record new areas that get scavenged
3083              * anyway during scavenge_newspace_generation_one_scan. */
3084             record_new_objects = 1;
3085
3086             scavenge_newspace_generation_one_scan(generation);
3087
3088             /* Record all new areas now. */
3089             record_new_objects = 2;
3090
3091             scav_weak_hash_tables();
3092
3093             /* Flush the current regions updating the tables. */
3094             gc_alloc_update_all_page_tables();
3095
3096         } else {
3097
3098             /* Work through previous_new_areas. */
3099             for (i = 0; i < previous_new_areas_index; i++) {
3100                 page_index_t page = (*previous_new_areas)[i].page;
3101                 size_t offset = (*previous_new_areas)[i].offset;
3102                 size_t size = (*previous_new_areas)[i].size / N_WORD_BYTES;
3103                 gc_assert((*previous_new_areas)[i].size % N_WORD_BYTES == 0);
3104                 scavenge(page_address(page)+offset, size);
3105             }
3106
3107             scav_weak_hash_tables();
3108
3109             /* Flush the current regions updating the tables. */
3110             gc_alloc_update_all_page_tables();
3111         }
3112
3113         current_new_areas_index = new_areas_index;
3114
3115         /*FSHOW((stderr,
3116                  "The re-scan has finished; current_new_areas_index=%d.\n",
3117                  current_new_areas_index));*/
3118     }
3119
3120     /* Turn off recording of areas allocated by gc_alloc(). */
3121     record_new_objects = 0;
3122
3123 #if SC_NS_GEN_CK
3124     /* Check that none of the write_protected pages in this generation
3125      * have been written to. */
3126     for (i = 0; i < page_table_pages; i++) {
3127         if (page_allocated_p(i)
3128             && (page_table[i].bytes_used != 0)
3129             && (page_table[i].gen == generation)
3130             && (page_table[i].write_protected_cleared != 0)
3131             && (page_table[i].dont_move == 0)) {
3132             lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d\n",
3133                  i, generation, page_table[i].dont_move);
3134         }
3135     }
3136 #endif
3137 }
3138 \f
3139 /* Un-write-protect all the pages in from_space. This is done at the
3140  * start of a GC else there may be many page faults while scavenging
3141  * the newspace (I've seen drive the system time to 99%). These pages
3142  * would need to be unprotected anyway before unmapping in
3143  * free_oldspace; not sure what effect this has on paging.. */
3144 static void
3145 unprotect_oldspace(void)
3146 {
3147     page_index_t i;
3148     void *region_addr = 0;
3149     void *page_addr = 0;
3150     unsigned long region_bytes = 0;
3151
3152     for (i = 0; i < last_free_page; i++) {
3153         if (page_allocated_p(i)
3154             && (page_table[i].bytes_used != 0)
3155             && (page_table[i].gen == from_space)) {
3156
3157             /* Remove any write-protection. We should be able to rely
3158              * on the write-protect flag to avoid redundant calls. */
3159             if (page_table[i].write_protected) {
3160                 page_table[i].write_protected = 0;
3161                 page_addr = page_address(i);
3162                 if (!region_addr) {
3163                     /* First region. */
3164                     region_addr = page_addr;
3165                     region_bytes = GENCGC_CARD_BYTES;
3166                 } else if (region_addr + region_bytes == page_addr) {
3167                     /* Region continue. */
3168                     region_bytes += GENCGC_CARD_BYTES;
3169                 } else {
3170                     /* Unprotect previous region. */
3171                     os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
3172                     /* First page in new region. */
3173                     region_addr = page_addr;
3174                     region_bytes = GENCGC_CARD_BYTES;
3175                 }
3176             }
3177         }
3178     }
3179     if (region_addr) {
3180         /* Unprotect last region. */
3181         os_protect(region_addr, region_bytes, OS_VM_PROT_ALL);
3182     }
3183 }
3184
3185 /* Work through all the pages and free any in from_space. This
3186  * assumes that all objects have been copied or promoted to an older
3187  * generation. Bytes_allocated and the generation bytes_allocated
3188  * counter are updated. The number of bytes freed is returned. */
3189 static unsigned long
3190 free_oldspace(void)
3191 {
3192     unsigned long bytes_freed = 0;
3193     page_index_t first_page, last_page;
3194
3195     first_page = 0;
3196
3197     do {
3198         /* Find a first page for the next region of pages. */
3199         while ((first_page < last_free_page)
3200                && (page_free_p(first_page)
3201                    || (page_table[first_page].bytes_used == 0)
3202                    || (page_table[first_page].gen != from_space)))
3203             first_page++;
3204
3205         if (first_page >= last_free_page)
3206             break;
3207
3208         /* Find the last page of this region. */
3209         last_page = first_page;
3210
3211         do {
3212             /* Free the page. */
3213             bytes_freed += page_table[last_page].bytes_used;
3214             generations[page_table[last_page].gen].bytes_allocated -=
3215                 page_table[last_page].bytes_used;
3216             page_table[last_page].allocated = FREE_PAGE_FLAG;
3217             page_table[last_page].bytes_used = 0;
3218             /* Should already be unprotected by unprotect_oldspace(). */
3219             gc_assert(!page_table[last_page].write_protected);
3220             last_page++;
3221         }
3222         while ((last_page < last_free_page)
3223                && page_allocated_p(last_page)
3224                && (page_table[last_page].bytes_used != 0)
3225                && (page_table[last_page].gen == from_space));
3226
3227 #ifdef READ_PROTECT_FREE_PAGES
3228         os_protect(page_address(first_page),
3229                    npage_bytes(last_page-first_page),
3230                    OS_VM_PROT_NONE);
3231 #endif
3232         first_page = last_page;
3233     } while (first_page < last_free_page);
3234
3235     bytes_allocated -= bytes_freed;
3236     return bytes_freed;
3237 }
3238 \f
3239 #if 0
3240 /* Print some information about a pointer at the given address. */
3241 static void
3242 print_ptr(lispobj *addr)
3243 {
3244     /* If addr is in the dynamic space then out the page information. */
3245     page_index_t pi1 = find_page_index((void*)addr);
3246
3247     if (pi1 != -1)
3248         fprintf(stderr,"  %x: page %d  alloc %d  gen %d  bytes_used %d  offset %lu  dont_move %d\n",
3249                 (unsigned long) addr,
3250                 pi1,
3251                 page_table[pi1].allocated,
3252                 page_table[pi1].gen,
3253                 page_table[pi1].bytes_used,
3254                 page_table[pi1].region_start_offset,
3255                 page_table[pi1].dont_move);
3256     fprintf(stderr,"  %x %x %x %x (%x) %x %x %x %x\n",
3257             *(addr-4),
3258             *(addr-3),
3259             *(addr-2),
3260             *(addr-1),
3261             *(addr-0),
3262             *(addr+1),
3263             *(addr+2),
3264             *(addr+3),
3265             *(addr+4));
3266 }
3267 #endif
3268
3269 static int
3270 is_in_stack_space(lispobj ptr)
3271 {
3272     /* For space verification: Pointers can be valid if they point
3273      * to a thread stack space.  This would be faster if the thread
3274      * structures had page-table entries as if they were part of
3275      * the heap space. */
3276     struct thread *th;
3277     for_each_thread(th) {
3278         if ((th->control_stack_start <= (lispobj *)ptr) &&
3279             (th->control_stack_end >= (lispobj *)ptr)) {
3280             return 1;
3281         }
3282     }
3283     return 0;
3284 }
3285
3286 static void
3287 verify_space(lispobj *start, size_t words)
3288 {
3289     int is_in_dynamic_space = (find_page_index((void*)start) != -1);
3290     int is_in_readonly_space =
3291         (READ_ONLY_SPACE_START <= (unsigned long)start &&
3292          (unsigned long)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3293
3294     while (words > 0) {
3295         size_t count = 1;
3296         lispobj thing = *(lispobj*)start;
3297
3298         if (is_lisp_pointer(thing)) {
3299             page_index_t page_index = find_page_index((void*)thing);
3300             long to_readonly_space =
3301                 (READ_ONLY_SPACE_START <= thing &&
3302                  thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0));
3303             long to_static_space =
3304                 (STATIC_SPACE_START <= thing &&
3305                  thing < SymbolValue(STATIC_SPACE_FREE_POINTER,0));
3306
3307             /* Does it point to the dynamic space? */
3308             if (page_index != -1) {
3309                 /* If it's within the dynamic space it should point to a used
3310                  * page. XX Could check the offset too. */
3311                 if (page_allocated_p(page_index)
3312                     && (page_table[page_index].bytes_used == 0))
3313                     lose ("Ptr %p @ %p sees free page.\n", thing, start);
3314                 /* Check that it doesn't point to a forwarding pointer! */
3315                 if (*((lispobj *)native_pointer(thing)) == 0x01) {
3316                     lose("Ptr %p @ %p sees forwarding ptr.\n", thing, start);
3317                 }
3318                 /* Check that its not in the RO space as it would then be a
3319                  * pointer from the RO to the dynamic space. */
3320                 if (is_in_readonly_space) {
3321                     lose("ptr to dynamic space %p from RO space %x\n",
3322                          thing, start);
3323                 }
3324                 /* Does it point to a plausible object? This check slows
3325                  * it down a lot (so it's commented out).
3326                  *
3327                  * "a lot" is serious: it ate 50 minutes cpu time on
3328                  * my duron 950 before I came back from lunch and
3329                  * killed it.
3330                  *
3331                  *   FIXME: Add a variable to enable this
3332                  * dynamically. */
3333                 /*
3334                 if (!possibly_valid_dynamic_space_pointer((lispobj *)thing)) {
3335                     lose("ptr %p to invalid object %p\n", thing, start);
3336                 }
3337                 */
3338             } else {
3339                 extern void funcallable_instance_tramp;
3340                 /* Verify that it points to another valid space. */
3341                 if (!to_readonly_space && !to_static_space
3342                     && (thing != (lispobj)&funcallable_instance_tramp)
3343                     && !is_in_stack_space(thing)) {
3344                     lose("Ptr %p @ %p sees junk.\n", thing, start);
3345                 }
3346             }
3347         } else {
3348             if (!(fixnump(thing))) {
3349                 /* skip fixnums */
3350                 switch(widetag_of(*start)) {
3351
3352                     /* boxed objects */
3353                 case SIMPLE_VECTOR_WIDETAG:
3354                 case RATIO_WIDETAG:
3355                 case COMPLEX_WIDETAG:
3356                 case SIMPLE_ARRAY_WIDETAG:
3357                 case COMPLEX_BASE_STRING_WIDETAG:
3358 #ifdef COMPLEX_CHARACTER_STRING_WIDETAG
3359                 case COMPLEX_CHARACTER_STRING_WIDETAG:
3360 #endif
3361                 case COMPLEX_VECTOR_NIL_WIDETAG:
3362                 case COMPLEX_BIT_VECTOR_WIDETAG:
3363                 case COMPLEX_VECTOR_WIDETAG:
3364                 case COMPLEX_ARRAY_WIDETAG:
3365                 case CLOSURE_HEADER_WIDETAG:
3366                 case FUNCALLABLE_INSTANCE_HEADER_WIDETAG:
3367                 case VALUE_CELL_HEADER_WIDETAG:
3368                 case SYMBOL_HEADER_WIDETAG:
3369                 case CHARACTER_WIDETAG:
3370 #if N_WORD_BITS == 64
3371                 case SINGLE_FLOAT_WIDETAG:
3372 #endif
3373                 case UNBOUND_MARKER_WIDETAG:
3374                 case FDEFN_WIDETAG:
3375                     count = 1;
3376                     break;
3377
3378                 case INSTANCE_HEADER_WIDETAG:
3379                     {
3380                         lispobj nuntagged;
3381                         long ntotal = HeaderValue(thing);
3382                         lispobj layout = ((struct instance *)start)->slots[0];
3383                         if (!layout) {
3384                             count = 1;
3385                             break;
3386                         }
3387                         nuntagged = ((struct layout *)
3388                                      native_pointer(layout))->n_untagged_slots;
3389                         verify_space(start + 1,
3390                                      ntotal - fixnum_value(nuntagged));
3391                         count = ntotal + 1;
3392                         break;
3393                     }
3394                 case CODE_HEADER_WIDETAG:
3395                     {
3396                         lispobj object = *start;
3397                         struct code *code;
3398                         long nheader_words, ncode_words, nwords;
3399                         lispobj fheaderl;
3400                         struct simple_fun *fheaderp;
3401
3402                         code = (struct code *) start;
3403
3404                         /* Check that it's not in the dynamic space.
3405                          * FIXME: Isn't is supposed to be OK for code
3406                          * objects to be in the dynamic space these days? */
3407                         if (is_in_dynamic_space
3408                             /* It's ok if it's byte compiled code. The trace
3409                              * table offset will be a fixnum if it's x86
3410                              * compiled code - check.
3411                              *
3412                              * FIXME: #^#@@! lack of abstraction here..
3413                              * This line can probably go away now that
3414                              * there's no byte compiler, but I've got
3415                              * too much to worry about right now to try
3416                              * to make sure. -- WHN 2001-10-06 */
3417                             && fixnump(code->trace_table_offset)
3418                             /* Only when enabled */
3419                             && verify_dynamic_code_check) {
3420                             FSHOW((stderr,
3421                                    "/code object at %p in the dynamic space\n",
3422                                    start));
3423                         }
3424
3425                         ncode_words = fixnum_value(code->code_size);
3426                         nheader_words = HeaderValue(object);
3427                         nwords = ncode_words + nheader_words;
3428                         nwords = CEILING(nwords, 2);
3429                         /* Scavenge the boxed section of the code data block */
3430                         verify_space(start + 1, nheader_words - 1);
3431
3432                         /* Scavenge the boxed section of each function
3433                          * object in the code data block. */
3434                         fheaderl = code->entry_points;
3435                         while (fheaderl != NIL) {
3436                             fheaderp =
3437                                 (struct simple_fun *) native_pointer(fheaderl);
3438                             gc_assert(widetag_of(fheaderp->header) ==
3439                                       SIMPLE_FUN_HEADER_WIDETAG);
3440                             verify_space(&fheaderp->name, 1);
3441                             verify_space(&fheaderp->arglist, 1);
3442                             verify_space(&fheaderp->type, 1);
3443                             fheaderl = fheaderp->next;
3444                         }
3445                         count = nwords;
3446                         break;
3447                     }
3448
3449                     /* unboxed objects */
3450                 case BIGNUM_WIDETAG:
3451 #if N_WORD_BITS != 64
3452                 case SINGLE_FLOAT_WIDETAG:
3453 #endif
3454                 case DOUBLE_FLOAT_WIDETAG:
3455 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3456                 case LONG_FLOAT_WIDETAG:
3457 #endif
3458 #ifdef COMPLEX_SINGLE_FLOAT_WIDETAG
3459                 case COMPLEX_SINGLE_FLOAT_WIDETAG:
3460 #endif
3461 #ifdef COMPLEX_DOUBLE_FLOAT_WIDETAG
3462                 case COMPLEX_DOUBLE_FLOAT_WIDETAG:
3463 #endif
3464 #ifdef COMPLEX_LONG_FLOAT_WIDETAG
3465                 case COMPLEX_LONG_FLOAT_WIDETAG:
3466 #endif
3467                 case SIMPLE_BASE_STRING_WIDETAG:
3468 #ifdef SIMPLE_CHARACTER_STRING_WIDETAG
3469                 case SIMPLE_CHARACTER_STRING_WIDETAG:
3470 #endif
3471                 case SIMPLE_BIT_VECTOR_WIDETAG:
3472                 case SIMPLE_ARRAY_NIL_WIDETAG:
3473                 case SIMPLE_ARRAY_UNSIGNED_BYTE_2_WIDETAG:
3474                 case SIMPLE_ARRAY_UNSIGNED_BYTE_4_WIDETAG:
3475                 case SIMPLE_ARRAY_UNSIGNED_BYTE_7_WIDETAG:
3476                 case SIMPLE_ARRAY_UNSIGNED_BYTE_8_WIDETAG:
3477                 case SIMPLE_ARRAY_UNSIGNED_BYTE_15_WIDETAG:
3478                 case SIMPLE_ARRAY_UNSIGNED_BYTE_16_WIDETAG:
3479
3480                 case SIMPLE_ARRAY_UNSIGNED_FIXNUM_WIDETAG:
3481
3482                 case SIMPLE_ARRAY_UNSIGNED_BYTE_31_WIDETAG:
3483                 case SIMPLE_ARRAY_UNSIGNED_BYTE_32_WIDETAG:
3484 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG
3485                 case SIMPLE_ARRAY_UNSIGNED_BYTE_63_WIDETAG:
3486 #endif
3487 #ifdef SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG
3488                 case SIMPLE_ARRAY_UNSIGNED_BYTE_64_WIDETAG:
3489 #endif
3490 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG
3491                 case SIMPLE_ARRAY_SIGNED_BYTE_8_WIDETAG:
3492 #endif
3493 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG
3494                 case SIMPLE_ARRAY_SIGNED_BYTE_16_WIDETAG:
3495 #endif
3496
3497                 case SIMPLE_ARRAY_FIXNUM_WIDETAG:
3498
3499 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG
3500                 case SIMPLE_ARRAY_SIGNED_BYTE_32_WIDETAG:
3501 #endif
3502 #ifdef SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG
3503                 case SIMPLE_ARRAY_SIGNED_BYTE_64_WIDETAG:
3504 #endif
3505                 case SIMPLE_ARRAY_SINGLE_FLOAT_WIDETAG:
3506                 case SIMPLE_ARRAY_DOUBLE_FLOAT_WIDETAG:
3507 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3508                 case SIMPLE_ARRAY_LONG_FLOAT_WIDETAG:
3509 #endif
3510 #ifdef SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG
3511                 case SIMPLE_ARRAY_COMPLEX_SINGLE_FLOAT_WIDETAG:
3512 #endif
3513 #ifdef SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG
3514                 case SIMPLE_ARRAY_COMPLEX_DOUBLE_FLOAT_WIDETAG:
3515 #endif
3516 #ifdef SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG
3517                 case SIMPLE_ARRAY_COMPLEX_LONG_FLOAT_WIDETAG:
3518 #endif
3519                 case SAP_WIDETAG:
3520                 case WEAK_POINTER_WIDETAG:
3521 #ifdef NO_TLS_VALUE_MARKER_WIDETAG
3522                 case NO_TLS_VALUE_MARKER_WIDETAG:
3523 #endif
3524                     count = (sizetab[widetag_of(*start)])(start);
3525                     break;
3526
3527                 default:
3528                     lose("Unhandled widetag %p at %p\n",
3529                          widetag_of(*start), start);
3530                 }
3531             }
3532         }
3533         start += count;
3534         words -= count;
3535     }
3536 }
3537
3538 static void
3539 verify_gc(void)
3540 {
3541     /* FIXME: It would be nice to make names consistent so that
3542      * foo_size meant size *in* *bytes* instead of size in some
3543      * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
3544      * Some counts of lispobjs are called foo_count; it might be good
3545      * to grep for all foo_size and rename the appropriate ones to
3546      * foo_count. */
3547     long read_only_space_size =
3548         (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0)
3549         - (lispobj*)READ_ONLY_SPACE_START;
3550     long static_space_size =
3551         (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0)
3552         - (lispobj*)STATIC_SPACE_START;
3553     struct thread *th;
3554     for_each_thread(th) {
3555     long binding_stack_size =
3556         (lispobj*)get_binding_stack_pointer(th)
3557             - (lispobj*)th->binding_stack_start;
3558         verify_space(th->binding_stack_start, binding_stack_size);
3559     }
3560     verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
3561     verify_space((lispobj*)STATIC_SPACE_START   , static_space_size);
3562 }
3563
3564 static void
3565 verify_generation(generation_index_t generation)
3566 {
3567     page_index_t i;
3568
3569     for (i = 0; i < last_free_page; i++) {
3570         if (page_allocated_p(i)
3571             && (page_table[i].bytes_used != 0)
3572             && (page_table[i].gen == generation)) {
3573             page_index_t last_page;
3574             int region_allocation = page_table[i].allocated;
3575
3576             /* This should be the start of a contiguous block */
3577             gc_assert(page_table[i].region_start_offset == 0);
3578
3579             /* Need to find the full extent of this contiguous block in case
3580                objects span pages. */
3581
3582             /* Now work forward until the end of this contiguous area is
3583                found. */
3584             for (last_page = i; ;last_page++)
3585                 /* Check whether this is the last page in this contiguous
3586                  * block. */
3587                 if ((page_table[last_page].bytes_used < GENCGC_CARD_BYTES)
3588                     /* Or it is CARD_BYTES and is the last in the block */
3589                     || (page_table[last_page+1].allocated != region_allocation)
3590                     || (page_table[last_page+1].bytes_used == 0)
3591                     || (page_table[last_page+1].gen != generation)
3592                     || (page_table[last_page+1].region_start_offset == 0))
3593                     break;
3594
3595             verify_space(page_address(i),
3596                          ((unsigned long)
3597                           (page_table[last_page].bytes_used
3598                            + npage_bytes(last_page-i)))
3599                          / N_WORD_BYTES);
3600             i = last_page;
3601         }
3602     }
3603 }
3604
3605 /* Check that all the free space is zero filled. */
3606 static void
3607 verify_zero_fill(void)
3608 {
3609     page_index_t page;
3610
3611     for (page = 0; page < last_free_page; page++) {
3612         if (page_free_p(page)) {
3613             /* The whole page should be zero filled. */
3614             long *start_addr = (long *)page_address(page);
3615             long size = 1024;
3616             long i;
3617             for (i = 0; i < size; i++) {
3618                 if (start_addr[i] != 0) {
3619                     lose("free page not zero at %x\n", start_addr + i);
3620                 }
3621             }
3622         } else {
3623             long free_bytes = GENCGC_CARD_BYTES - page_table[page].bytes_used;
3624             if (free_bytes > 0) {
3625                 long *start_addr = (long *)((unsigned long)page_address(page)
3626                                           + page_table[page].bytes_used);
3627                 long size = free_bytes / N_WORD_BYTES;
3628                 long i;
3629                 for (i = 0; i < size; i++) {
3630                     if (start_addr[i] != 0) {
3631                         lose("free region not zero at %x\n", start_addr + i);
3632                     }
3633                 }
3634             }
3635         }
3636     }
3637 }
3638
3639 /* External entry point for verify_zero_fill */
3640 void
3641 gencgc_verify_zero_fill(void)
3642 {
3643     /* Flush the alloc regions updating the tables. */
3644     gc_alloc_update_all_page_tables();
3645     SHOW("verifying zero fill");
3646     verify_zero_fill();
3647 }
3648
3649 static void
3650 verify_dynamic_space(void)
3651 {
3652     generation_index_t i;
3653
3654     for (i = 0; i <= HIGHEST_NORMAL_GENERATION; i++)
3655         verify_generation(i);
3656
3657     if (gencgc_enable_verify_zero_fill)
3658         verify_zero_fill();
3659 }
3660 \f
3661 /* Write-protect all the dynamic boxed pages in the given generation. */
3662 static void
3663 write_protect_generation_pages(generation_index_t generation)
3664 {
3665     page_index_t start;
3666
3667     gc_assert(generation < SCRATCH_GENERATION);
3668
3669     for (start = 0; start < last_free_page; start++) {
3670         if (protect_page_p(start, generation)) {
3671             void *page_start;
3672             page_index_t last;
3673
3674             /* Note the page as protected in the page tables. */
3675             page_table[start].write_protected = 1;
3676
3677             for (last = start + 1; last < last_free_page; last++) {
3678                 if (!protect_page_p(last, generation))
3679                   break;
3680                 page_table[last].write_protected = 1;
3681             }
3682
3683             page_start = (void *)page_address(start);
3684
3685             os_protect(page_start,
3686                        npage_bytes(last - start),
3687                        OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
3688
3689             start = last;
3690         }
3691     }
3692
3693     if (gencgc_verbose > 1) {
3694         FSHOW((stderr,
3695                "/write protected %d of %d pages in generation %d\n",
3696                count_write_protect_generation_pages(generation),
3697                count_generation_pages(generation),
3698                generation));
3699     }
3700 }
3701
3702 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
3703 static void
3704 scavenge_control_stack(struct thread *th)
3705 {
3706     lispobj *control_stack =
3707         (lispobj *)(th->control_stack_start);
3708     unsigned long control_stack_size =
3709         access_control_stack_pointer(th) - control_stack;
3710
3711     scavenge(control_stack, control_stack_size);
3712 }
3713 #endif
3714
3715 #if defined(LISP_FEATURE_SB_THREAD) && (defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
3716 static void
3717 preserve_context_registers (os_context_t *c)
3718 {
3719     void **ptr;
3720     /* On Darwin the signal context isn't a contiguous block of memory,
3721      * so just preserve_pointering its contents won't be sufficient.
3722      */
3723 #if defined(LISP_FEATURE_DARWIN)
3724 #if defined LISP_FEATURE_X86
3725     preserve_pointer((void*)*os_context_register_addr(c,reg_EAX));
3726     preserve_pointer((void*)*os_context_register_addr(c,reg_ECX));
3727     preserve_pointer((void*)*os_context_register_addr(c,reg_EDX));
3728     preserve_pointer((void*)*os_context_register_addr(c,reg_EBX));
3729     preserve_pointer((void*)*os_context_register_addr(c,reg_ESI));
3730     preserve_pointer((void*)*os_context_register_addr(c,reg_EDI));
3731     preserve_pointer((void*)*os_context_pc_addr(c));
3732 #elif defined LISP_FEATURE_X86_64
3733     preserve_pointer((void*)*os_context_register_addr(c,reg_RAX));
3734     preserve_pointer((void*)*os_context_register_addr(c,reg_RCX));
3735     preserve_pointer((void*)*os_context_register_addr(c,reg_RDX));
3736     preserve_pointer((void*)*os_context_register_addr(c,reg_RBX));
3737     preserve_pointer((void*)*os_context_register_addr(c,reg_RSI));
3738     preserve_pointer((void*)*os_context_register_addr(c,reg_RDI));
3739     preserve_pointer((void*)*os_context_register_addr(c,reg_R8));
3740     preserve_pointer((void*)*os_context_register_addr(c,reg_R9));
3741     preserve_pointer((void*)*os_context_register_addr(c,reg_R10));
3742     preserve_pointer((void*)*os_context_register_addr(c,reg_R11));
3743     preserve_pointer((void*)*os_context_register_addr(c,reg_R12));
3744     preserve_pointer((void*)*os_context_register_addr(c,reg_R13));
3745     preserve_pointer((void*)*os_context_register_addr(c,reg_R14));
3746     preserve_pointer((void*)*os_context_register_addr(c,reg_R15));
3747     preserve_pointer((void*)*os_context_pc_addr(c));
3748 #else
3749     #error "preserve_context_registers needs to be tweaked for non-x86 Darwin"
3750 #endif
3751 #endif
3752     for(ptr = ((void **)(c+1))-1; ptr>=(void **)c; ptr--) {
3753         preserve_pointer(*ptr);
3754     }
3755 }
3756 #endif
3757
3758 /* Garbage collect a generation. If raise is 0 then the remains of the
3759  * generation are not raised to the next generation. */
3760 static void
3761 garbage_collect_generation(generation_index_t generation, int raise)
3762 {
3763     unsigned long bytes_freed;
3764     page_index_t i;
3765     unsigned long static_space_size;
3766     struct thread *th;
3767
3768     gc_assert(generation <= HIGHEST_NORMAL_GENERATION);
3769
3770     /* The oldest generation can't be raised. */
3771     gc_assert((generation != HIGHEST_NORMAL_GENERATION) || (raise == 0));
3772
3773     /* Check if weak hash tables were processed in the previous GC. */
3774     gc_assert(weak_hash_tables == NULL);
3775
3776     /* Initialize the weak pointer list. */
3777     weak_pointers = NULL;
3778
3779     /* When a generation is not being raised it is transported to a
3780      * temporary generation (NUM_GENERATIONS), and lowered when
3781      * done. Set up this new generation. There should be no pages
3782      * allocated to it yet. */
3783     if (!raise) {
3784          gc_assert(generations[SCRATCH_GENERATION].bytes_allocated == 0);
3785     }
3786
3787     /* Set the global src and dest. generations */
3788     from_space = generation;
3789     if (raise)
3790         new_space = generation+1;
3791     else
3792         new_space = SCRATCH_GENERATION;
3793
3794     /* Change to a new space for allocation, resetting the alloc_start_page */
3795     gc_alloc_generation = new_space;
3796     generations[new_space].alloc_start_page = 0;
3797     generations[new_space].alloc_unboxed_start_page = 0;
3798     generations[new_space].alloc_large_start_page = 0;
3799     generations[new_space].alloc_large_unboxed_start_page = 0;
3800
3801     /* Before any pointers are preserved, the dont_move flags on the
3802      * pages need to be cleared. */
3803     for (i = 0; i < last_free_page; i++)
3804         if(page_table[i].gen==from_space)
3805             page_table[i].dont_move = 0;
3806
3807     /* Un-write-protect the old-space pages. This is essential for the
3808      * promoted pages as they may contain pointers into the old-space
3809      * which need to be scavenged. It also helps avoid unnecessary page
3810      * faults as forwarding pointers are written into them. They need to
3811      * be un-protected anyway before unmapping later. */
3812     unprotect_oldspace();
3813
3814     /* Scavenge the stacks' conservative roots. */
3815
3816     /* there are potentially two stacks for each thread: the main
3817      * stack, which may contain Lisp pointers, and the alternate stack.
3818      * We don't ever run Lisp code on the altstack, but it may
3819      * host a sigcontext with lisp objects in it */
3820
3821     /* what we need to do: (1) find the stack pointer for the main
3822      * stack; scavenge it (2) find the interrupt context on the
3823      * alternate stack that might contain lisp values, and scavenge
3824      * that */
3825
3826     /* we assume that none of the preceding applies to the thread that
3827      * initiates GC.  If you ever call GC from inside an altstack
3828      * handler, you will lose. */
3829
3830 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
3831     /* And if we're saving a core, there's no point in being conservative. */
3832     if (conservative_stack) {
3833         for_each_thread(th) {
3834             void **ptr;
3835             void **esp=(void **)-1;
3836 #ifdef LISP_FEATURE_SB_THREAD
3837             long i,free;
3838             if(th==arch_os_get_current_thread()) {
3839                 /* Somebody is going to burn in hell for this, but casting
3840                  * it in two steps shuts gcc up about strict aliasing. */
3841                 esp = (void **)((void *)&raise);
3842             } else {
3843                 void **esp1;
3844                 free=fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,th));
3845                 for(i=free-1;i>=0;i--) {
3846                     os_context_t *c=th->interrupt_contexts[i];
3847                     esp1 = (void **) *os_context_register_addr(c,reg_SP);
3848                     if (esp1>=(void **)th->control_stack_start &&
3849                         esp1<(void **)th->control_stack_end) {
3850                         if(esp1<esp) esp=esp1;
3851                         preserve_context_registers(c);
3852                     }
3853                 }
3854             }
3855 #else
3856             esp = (void **)((void *)&raise);
3857 #endif
3858             for (ptr = ((void **)th->control_stack_end)-1; ptr >= esp;  ptr--) {
3859                 preserve_pointer(*ptr);
3860             }
3861         }
3862     }
3863 #else
3864     /* Non-x86oid systems don't have "conservative roots" as such, but
3865      * the same mechanism is used for objects pinned for use by alien
3866      * code. */
3867     for_each_thread(th) {
3868         lispobj pin_list = SymbolTlValue(PINNED_OBJECTS,th);
3869         while (pin_list != NIL) {
3870             struct cons *list_entry =
3871                 (struct cons *)native_pointer(pin_list);
3872             preserve_pointer(list_entry->car);
3873             pin_list = list_entry->cdr;
3874         }
3875     }
3876 #endif
3877
3878 #if QSHOW
3879     if (gencgc_verbose > 1) {
3880         long num_dont_move_pages = count_dont_move_pages();
3881         fprintf(stderr,
3882                 "/non-movable pages due to conservative pointers = %d (%d bytes)\n",
3883                 num_dont_move_pages,
3884                 npage_bytes(num_dont_move_pages));
3885     }
3886 #endif
3887
3888     /* Scavenge all the rest of the roots. */
3889
3890 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
3891     /*
3892      * If not x86, we need to scavenge the interrupt context(s) and the
3893      * control stack.
3894      */
3895     {
3896         struct thread *th;
3897         for_each_thread(th) {
3898             scavenge_interrupt_contexts(th);
3899             scavenge_control_stack(th);
3900         }
3901
3902         /* Scrub the unscavenged control stack space, so that we can't run
3903          * into any stale pointers in a later GC (this is done by the
3904          * stop-for-gc handler in the other threads). */
3905         scrub_control_stack();
3906     }
3907 #endif
3908
3909     /* Scavenge the Lisp functions of the interrupt handlers, taking
3910      * care to avoid SIG_DFL and SIG_IGN. */
3911     for (i = 0; i < NSIG; i++) {
3912         union interrupt_handler handler = interrupt_handlers[i];
3913         if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
3914             !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
3915             scavenge((lispobj *)(interrupt_handlers + i), 1);
3916         }
3917     }
3918     /* Scavenge the binding stacks. */
3919     {
3920         struct thread *th;
3921         for_each_thread(th) {
3922             long len= (lispobj *)get_binding_stack_pointer(th) -
3923                 th->binding_stack_start;
3924             scavenge((lispobj *) th->binding_stack_start,len);
3925 #ifdef LISP_FEATURE_SB_THREAD
3926             /* do the tls as well */
3927             len=(SymbolValue(FREE_TLS_INDEX,0) >> WORD_SHIFT) -
3928                 (sizeof (struct thread))/(sizeof (lispobj));
3929             scavenge((lispobj *) (th+1),len);
3930 #endif
3931         }
3932     }
3933
3934     /* The original CMU CL code had scavenge-read-only-space code
3935      * controlled by the Lisp-level variable
3936      * *SCAVENGE-READ-ONLY-SPACE*. It was disabled by default, and it
3937      * wasn't documented under what circumstances it was useful or
3938      * safe to turn it on, so it's been turned off in SBCL. If you
3939      * want/need this functionality, and can test and document it,
3940      * please submit a patch. */
3941 #if 0
3942     if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
3943         unsigned long read_only_space_size =
3944             (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
3945             (lispobj*)READ_ONLY_SPACE_START;
3946         FSHOW((stderr,
3947                "/scavenge read only space: %d bytes\n",
3948                read_only_space_size * sizeof(lispobj)));
3949         scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
3950     }
3951 #endif
3952
3953     /* Scavenge static space. */
3954     static_space_size =
3955         (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0) -
3956         (lispobj *)STATIC_SPACE_START;
3957     if (gencgc_verbose > 1) {
3958         FSHOW((stderr,
3959                "/scavenge static space: %d bytes\n",
3960                static_space_size * sizeof(lispobj)));
3961     }
3962     scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
3963
3964     /* All generations but the generation being GCed need to be
3965      * scavenged. The new_space generation needs special handling as
3966      * objects may be moved in - it is handled separately below. */
3967     scavenge_generations(generation+1, PSEUDO_STATIC_GENERATION);
3968
3969     /* Finally scavenge the new_space generation. Keep going until no
3970      * more objects are moved into the new generation */
3971     scavenge_newspace_generation(new_space);
3972
3973     /* FIXME: I tried reenabling this check when debugging unrelated
3974      * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
3975      * Since the current GC code seems to work well, I'm guessing that
3976      * this debugging code is just stale, but I haven't tried to
3977      * figure it out. It should be figured out and then either made to
3978      * work or just deleted. */
3979 #define RESCAN_CHECK 0
3980 #if RESCAN_CHECK
3981     /* As a check re-scavenge the newspace once; no new objects should
3982      * be found. */
3983     {
3984         long old_bytes_allocated = bytes_allocated;
3985         long bytes_allocated;
3986
3987         /* Start with a full scavenge. */
3988         scavenge_newspace_generation_one_scan(new_space);
3989
3990         /* Flush the current regions, updating the tables. */
3991         gc_alloc_update_all_page_tables();
3992
3993         bytes_allocated = bytes_allocated - old_bytes_allocated;
3994
3995         if (bytes_allocated != 0) {
3996             lose("Rescan of new_space allocated %d more bytes.\n",
3997                  bytes_allocated);
3998         }
3999     }
4000 #endif
4001
4002     scan_weak_hash_tables();
4003     scan_weak_pointers();
4004
4005     /* Flush the current regions, updating the tables. */
4006     gc_alloc_update_all_page_tables();
4007
4008     /* Free the pages in oldspace, but not those marked dont_move. */
4009     bytes_freed = free_oldspace();
4010
4011     /* If the GC is not raising the age then lower the generation back
4012      * to its normal generation number */
4013     if (!raise) {
4014         for (i = 0; i < last_free_page; i++)
4015             if ((page_table[i].bytes_used != 0)
4016                 && (page_table[i].gen == SCRATCH_GENERATION))
4017                 page_table[i].gen = generation;
4018         gc_assert(generations[generation].bytes_allocated == 0);
4019         generations[generation].bytes_allocated =
4020             generations[SCRATCH_GENERATION].bytes_allocated;
4021         generations[SCRATCH_GENERATION].bytes_allocated = 0;
4022     }
4023
4024     /* Reset the alloc_start_page for generation. */
4025     generations[generation].alloc_start_page = 0;
4026     generations[generation].alloc_unboxed_start_page = 0;
4027     generations[generation].alloc_large_start_page = 0;
4028     generations[generation].alloc_large_unboxed_start_page = 0;
4029
4030     if (generation >= verify_gens) {
4031         if (gencgc_verbose) {
4032             SHOW("verifying");
4033         }
4034         verify_gc();
4035         verify_dynamic_space();
4036     }
4037
4038     /* Set the new gc trigger for the GCed generation. */
4039     generations[generation].gc_trigger =
4040         generations[generation].bytes_allocated
4041         + generations[generation].bytes_consed_between_gc;
4042
4043     if (raise)
4044         generations[generation].num_gc = 0;
4045     else
4046         ++generations[generation].num_gc;
4047
4048 }
4049
4050 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
4051 long
4052 update_dynamic_space_free_pointer(void)
4053 {
4054     page_index_t last_page = -1, i;
4055
4056     for (i = 0; i < last_free_page; i++)
4057         if (page_allocated_p(i) && (page_table[i].bytes_used != 0))
4058             last_page = i;
4059
4060     last_free_page = last_page+1;
4061
4062     set_alloc_pointer((lispobj)(page_address(last_free_page)));
4063     return 0; /* dummy value: return something ... */
4064 }
4065
4066 static void
4067 remap_page_range (page_index_t from, page_index_t to)
4068 {
4069     /* There's a mysterious Solaris/x86 problem with using mmap
4070      * tricks for memory zeroing. See sbcl-devel thread
4071      * "Re: patch: standalone executable redux".
4072      */
4073 #if defined(LISP_FEATURE_SUNOS)
4074     zero_and_mark_pages(from, to);
4075 #else
4076     const page_index_t
4077             release_granularity = gencgc_release_granularity/GENCGC_CARD_BYTES,
4078                    release_mask = release_granularity-1,
4079                             end = to+1,
4080                    aligned_from = (from+release_mask)&~release_mask,
4081                     aligned_end = (end&~release_mask);
4082
4083     if (aligned_from < aligned_end) {
4084         zero_pages_with_mmap(aligned_from, aligned_end-1);
4085         if (aligned_from != from)
4086             zero_and_mark_pages(from, aligned_from-1);
4087         if (aligned_end != end)
4088             zero_and_mark_pages(aligned_end, end-1);
4089     } else {
4090         zero_and_mark_pages(from, to);
4091     }
4092 #endif
4093 }
4094
4095 static void
4096 remap_free_pages (page_index_t from, page_index_t to, int forcibly)
4097 {
4098     page_index_t first_page, last_page;
4099
4100     if (forcibly)
4101         return remap_page_range(from, to);
4102
4103     for (first_page = from; first_page <= to; first_page++) {
4104         if (page_allocated_p(first_page) ||
4105             (page_table[first_page].need_to_zero == 0))
4106             continue;
4107
4108         last_page = first_page + 1;
4109         while (page_free_p(last_page) &&
4110                (last_page <= to) &&
4111                (page_table[last_page].need_to_zero == 1))
4112             last_page++;
4113
4114         remap_page_range(first_page, last_page-1);
4115
4116         first_page = last_page;
4117     }
4118 }
4119
4120 generation_index_t small_generation_limit = 1;
4121
4122 /* GC all generations newer than last_gen, raising the objects in each
4123  * to the next older generation - we finish when all generations below
4124  * last_gen are empty.  Then if last_gen is due for a GC, or if
4125  * last_gen==NUM_GENERATIONS (the scratch generation?  eh?) we GC that
4126  * too.  The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
4127  *
4128  * We stop collecting at gencgc_oldest_gen_to_gc, even if this is less than
4129  * last_gen (oh, and note that by default it is NUM_GENERATIONS-1) */
4130 void
4131 collect_garbage(generation_index_t last_gen)
4132 {
4133     generation_index_t gen = 0, i;
4134     int raise;
4135     int gen_to_wp;
4136     /* The largest value of last_free_page seen since the time
4137      * remap_free_pages was called. */
4138     static page_index_t high_water_mark = 0;
4139
4140     FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
4141     log_generation_stats(gc_logfile, "=== GC Start ===");
4142
4143     gc_active_p = 1;
4144
4145     if (last_gen > HIGHEST_NORMAL_GENERATION+1) {
4146         FSHOW((stderr,
4147                "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
4148                last_gen));
4149         last_gen = 0;
4150     }
4151
4152     /* Flush the alloc regions updating the tables. */
4153     gc_alloc_update_all_page_tables();
4154
4155     /* Verify the new objects created by Lisp code. */
4156     if (pre_verify_gen_0) {
4157         FSHOW((stderr, "pre-checking generation 0\n"));
4158         verify_generation(0);
4159     }
4160
4161     if (gencgc_verbose > 1)
4162         print_generation_stats();
4163
4164     do {
4165         /* Collect the generation. */
4166
4167         if (gen >= gencgc_oldest_gen_to_gc) {
4168             /* Never raise the oldest generation. */
4169             raise = 0;
4170         } else {
4171             raise =
4172                 (gen < last_gen)
4173                 || (generations[gen].num_gc >= generations[gen].number_of_gcs_before_promotion);
4174         }
4175
4176         if (gencgc_verbose > 1) {
4177             FSHOW((stderr,
4178                    "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
4179                    gen,
4180                    raise,
4181                    generations[gen].bytes_allocated,
4182                    generations[gen].gc_trigger,
4183                    generations[gen].num_gc));
4184         }
4185
4186         /* If an older generation is being filled, then update its
4187          * memory age. */
4188         if (raise == 1) {
4189             generations[gen+1].cum_sum_bytes_allocated +=
4190                 generations[gen+1].bytes_allocated;
4191         }
4192
4193         garbage_collect_generation(gen, raise);
4194
4195         /* Reset the memory age cum_sum. */
4196         generations[gen].cum_sum_bytes_allocated = 0;
4197
4198         if (gencgc_verbose > 1) {
4199             FSHOW((stderr, "GC of generation %d finished:\n", gen));
4200             print_generation_stats();
4201         }
4202
4203         gen++;
4204     } while ((gen <= gencgc_oldest_gen_to_gc)
4205              && ((gen < last_gen)
4206                  || ((gen <= gencgc_oldest_gen_to_gc)
4207                      && raise
4208                      && (generations[gen].bytes_allocated
4209                          > generations[gen].gc_trigger)
4210                      && (generation_average_age(gen)
4211                          > generations[gen].minimum_age_before_gc))));
4212
4213     /* Now if gen-1 was raised all generations before gen are empty.
4214      * If it wasn't raised then all generations before gen-1 are empty.
4215      *
4216      * Now objects within this gen's pages cannot point to younger
4217      * generations unless they are written to. This can be exploited
4218      * by write-protecting the pages of gen; then when younger
4219      * generations are GCed only the pages which have been written
4220      * need scanning. */
4221     if (raise)
4222         gen_to_wp = gen;
4223     else
4224         gen_to_wp = gen - 1;
4225
4226     /* There's not much point in WPing pages in generation 0 as it is
4227      * never scavenged (except promoted pages). */
4228     if ((gen_to_wp > 0) && enable_page_protection) {
4229         /* Check that they are all empty. */
4230         for (i = 0; i < gen_to_wp; i++) {
4231             if (generations[i].bytes_allocated)
4232                 lose("trying to write-protect gen. %d when gen. %d nonempty\n",
4233                      gen_to_wp, i);
4234         }
4235         write_protect_generation_pages(gen_to_wp);
4236     }
4237
4238     /* Set gc_alloc() back to generation 0. The current regions should
4239      * be flushed after the above GCs. */
4240     gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
4241     gc_alloc_generation = 0;
4242
4243     /* Save the high-water mark before updating last_free_page */
4244     if (last_free_page > high_water_mark)
4245         high_water_mark = last_free_page;
4246
4247     update_dynamic_space_free_pointer();
4248
4249     auto_gc_trigger = bytes_allocated + bytes_consed_between_gcs;
4250     if(gencgc_verbose)
4251         fprintf(stderr,"Next gc when %ld bytes have been consed\n",
4252                 auto_gc_trigger);
4253
4254     /* If we did a big GC (arbitrarily defined as gen > 1), release memory
4255      * back to the OS.
4256      */
4257     if (gen > small_generation_limit) {
4258         if (last_free_page > high_water_mark)
4259             high_water_mark = last_free_page;
4260         remap_free_pages(0, high_water_mark, 0);
4261         high_water_mark = 0;
4262     }
4263
4264     gc_active_p = 0;
4265
4266     log_generation_stats(gc_logfile, "=== GC End ===");
4267     SHOW("returning from collect_garbage");
4268 }
4269
4270 /* This is called by Lisp PURIFY when it is finished. All live objects
4271  * will have been moved to the RO and Static heaps. The dynamic space
4272  * will need a full re-initialization. We don't bother having Lisp
4273  * PURIFY flush the current gc_alloc() region, as the page_tables are
4274  * re-initialized, and every page is zeroed to be sure. */
4275 void
4276 gc_free_heap(void)
4277 {
4278     page_index_t page, last_page;
4279
4280     if (gencgc_verbose > 1) {
4281         SHOW("entering gc_free_heap");
4282     }
4283
4284     for (page = 0; page < page_table_pages; page++) {
4285         /* Skip free pages which should already be zero filled. */
4286         if (page_allocated_p(page)) {
4287             void *page_start, *addr;
4288             for (last_page = page;
4289                  (last_page < page_table_pages) && page_allocated_p(last_page);
4290                  last_page++) {
4291                 /* Mark the page free. The other slots are assumed invalid
4292                  * when it is a FREE_PAGE_FLAG and bytes_used is 0 and it
4293                  * should not be write-protected -- except that the
4294                  * generation is used for the current region but it sets
4295                  * that up. */
4296                 page_table[page].allocated = FREE_PAGE_FLAG;
4297                 page_table[page].bytes_used = 0;
4298                 page_table[page].write_protected = 0;
4299             }
4300
4301 #ifndef LISP_FEATURE_WIN32 /* Pages already zeroed on win32? Not sure
4302                             * about this change. */
4303             page_start = (void *)page_address(page);
4304             os_protect(page_start, npage_bytes(last_page-page), OS_VM_PROT_ALL);
4305             remap_free_pages(page, last_page-1, 1);
4306             page = last_page-1;
4307 #endif
4308         } else if (gencgc_zero_check_during_free_heap) {
4309             /* Double-check that the page is zero filled. */
4310             long *page_start;
4311             page_index_t i;
4312             gc_assert(page_free_p(page));
4313             gc_assert(page_table[page].bytes_used == 0);
4314             page_start = (long *)page_address(page);
4315             for (i=0; i<GENCGC_CARD_BYTES/sizeof(long); i++) {
4316                 if (page_start[i] != 0) {
4317                     lose("free region not zero at %x\n", page_start + i);
4318                 }
4319             }
4320         }
4321     }
4322
4323     bytes_allocated = 0;
4324
4325     /* Initialize the generations. */
4326     for (page = 0; page < NUM_GENERATIONS; page++) {
4327         generations[page].alloc_start_page = 0;
4328         generations[page].alloc_unboxed_start_page = 0;
4329         generations[page].alloc_large_start_page = 0;
4330         generations[page].alloc_large_unboxed_start_page = 0;
4331         generations[page].bytes_allocated = 0;
4332         generations[page].gc_trigger = 2000000;
4333         generations[page].num_gc = 0;
4334         generations[page].cum_sum_bytes_allocated = 0;
4335     }
4336
4337     if (gencgc_verbose > 1)
4338         print_generation_stats();
4339
4340     /* Initialize gc_alloc(). */
4341     gc_alloc_generation = 0;
4342
4343     gc_set_region_empty(&boxed_region);
4344     gc_set_region_empty(&unboxed_region);
4345
4346     last_free_page = 0;
4347     set_alloc_pointer((lispobj)((char *)heap_base));
4348
4349     if (verify_after_free_heap) {
4350         /* Check whether purify has left any bad pointers. */
4351         FSHOW((stderr, "checking after free_heap\n"));
4352         verify_gc();
4353     }
4354 }
4355 \f
4356 void
4357 gc_init(void)
4358 {
4359     page_index_t i;
4360
4361     /* Compute the number of pages needed for the dynamic space.
4362      * Dynamic space size should be aligned on page size. */
4363     page_table_pages = dynamic_space_size/GENCGC_CARD_BYTES;
4364     gc_assert(dynamic_space_size == npage_bytes(page_table_pages));
4365
4366     /* The page_table must be allocated using "calloc" to initialize
4367      * the page structures correctly. There used to be a separate
4368      * initialization loop (now commented out; see below) but that was
4369      * unnecessary and did hurt startup time. */
4370     page_table = calloc(page_table_pages, sizeof(struct page));
4371     gc_assert(page_table);
4372
4373     gc_init_tables();
4374     scavtab[WEAK_POINTER_WIDETAG] = scav_weak_pointer;
4375     transother[SIMPLE_ARRAY_WIDETAG] = trans_boxed_large;
4376
4377     heap_base = (void*)DYNAMIC_SPACE_START;
4378
4379     /* The page structures are initialized implicitly when page_table
4380      * is allocated with "calloc" above. Formerly we had the following
4381      * explicit initialization here (comments converted to C99 style
4382      * for readability as C's block comments don't nest):
4383      *
4384      * // Initialize each page structure.
4385      * for (i = 0; i < page_table_pages; i++) {
4386      *     // Initialize all pages as free.
4387      *     page_table[i].allocated = FREE_PAGE_FLAG;
4388      *     page_table[i].bytes_used = 0;
4389      *
4390      *     // Pages are not write-protected at startup.
4391      *     page_table[i].write_protected = 0;
4392      * }
4393      *
4394      * Without this loop the image starts up much faster when dynamic
4395      * space is large -- which it is on 64-bit platforms already by
4396      * default -- and when "calloc" for large arrays is implemented
4397      * using copy-on-write of a page of zeroes -- which it is at least
4398      * on Linux. In this case the pages that page_table_pages is stored
4399      * in are mapped and cleared not before the corresponding part of
4400      * dynamic space is used. For example, this saves clearing 16 MB of
4401      * memory at startup if the page size is 4 KB and the size of
4402      * dynamic space is 4 GB.
4403      * FREE_PAGE_FLAG must be 0 for this to work correctly which is
4404      * asserted below: */
4405     {
4406       /* Compile time assertion: If triggered, declares an array
4407        * of dimension -1 forcing a syntax error. The intent of the
4408        * assignment is to avoid an "unused variable" warning. */
4409       char assert_free_page_flag_0[(FREE_PAGE_FLAG) ? -1 : 1];
4410       assert_free_page_flag_0[0] = assert_free_page_flag_0[0];
4411     }
4412
4413     bytes_allocated = 0;
4414
4415     /* Initialize the generations.
4416      *
4417      * FIXME: very similar to code in gc_free_heap(), should be shared */
4418     for (i = 0; i < NUM_GENERATIONS; i++) {
4419         generations[i].alloc_start_page = 0;
4420         generations[i].alloc_unboxed_start_page = 0;
4421         generations[i].alloc_large_start_page = 0;
4422         generations[i].alloc_large_unboxed_start_page = 0;
4423         generations[i].bytes_allocated = 0;
4424         generations[i].gc_trigger = 2000000;
4425         generations[i].num_gc = 0;
4426         generations[i].cum_sum_bytes_allocated = 0;
4427         /* the tune-able parameters */
4428         generations[i].bytes_consed_between_gc = 2000000;
4429         generations[i].number_of_gcs_before_promotion = 1;
4430         generations[i].minimum_age_before_gc = 0.75;
4431     }
4432
4433     /* Initialize gc_alloc. */
4434     gc_alloc_generation = 0;
4435     gc_set_region_empty(&boxed_region);
4436     gc_set_region_empty(&unboxed_region);
4437
4438     last_free_page = 0;
4439 }
4440
4441 /*  Pick up the dynamic space from after a core load.
4442  *
4443  *  The ALLOCATION_POINTER points to the end of the dynamic space.
4444  */
4445
4446 static void
4447 gencgc_pickup_dynamic(void)
4448 {
4449     page_index_t page = 0;
4450     void *alloc_ptr = (void *)get_alloc_pointer();
4451     lispobj *prev=(lispobj *)page_address(page);
4452     generation_index_t gen = PSEUDO_STATIC_GENERATION;
4453     do {
4454         lispobj *first,*ptr= (lispobj *)page_address(page);
4455
4456         if (!gencgc_partial_pickup || page_allocated_p(page)) {
4457           /* It is possible, though rare, for the saved page table
4458            * to contain free pages below alloc_ptr. */
4459           page_table[page].gen = gen;
4460           page_table[page].bytes_used = GENCGC_CARD_BYTES;
4461           page_table[page].large_object = 0;
4462           page_table[page].write_protected = 0;
4463           page_table[page].write_protected_cleared = 0;
4464           page_table[page].dont_move = 0;
4465           page_table[page].need_to_zero = 1;
4466         }
4467
4468         if (!gencgc_partial_pickup) {
4469             page_table[page].allocated = BOXED_PAGE_FLAG;
4470             first=gc_search_space(prev,(ptr+2)-prev,ptr);
4471             if(ptr == first)
4472                 prev=ptr;
4473             page_table[page].region_start_offset =
4474                 page_address(page) - (void *)prev;
4475         }
4476         page++;
4477     } while (page_address(page) < alloc_ptr);
4478
4479     last_free_page = page;
4480
4481     generations[gen].bytes_allocated = npage_bytes(page);
4482     bytes_allocated = npage_bytes(page);
4483
4484     gc_alloc_update_all_page_tables();
4485     write_protect_generation_pages(gen);
4486 }
4487
4488 void
4489 gc_initialize_pointers(void)
4490 {
4491     gencgc_pickup_dynamic();
4492 }
4493 \f
4494
4495 /* alloc(..) is the external interface for memory allocation. It
4496  * allocates to generation 0. It is not called from within the garbage
4497  * collector as it is only external uses that need the check for heap
4498  * size (GC trigger) and to disable the interrupts (interrupts are
4499  * always disabled during a GC).
4500  *
4501  * The vops that call alloc(..) assume that the returned space is zero-filled.
4502  * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
4503  *
4504  * The check for a GC trigger is only performed when the current
4505  * region is full, so in most cases it's not needed. */
4506
4507 static inline lispobj *
4508 general_alloc_internal(long nbytes, int page_type_flag, struct alloc_region *region,
4509                        struct thread *thread)
4510 {
4511 #ifndef LISP_FEATURE_WIN32
4512     lispobj alloc_signal;
4513 #endif
4514     void *new_obj;
4515     void *new_free_pointer;
4516
4517     gc_assert(nbytes>0);
4518
4519     /* Check for alignment allocation problems. */
4520     gc_assert((((unsigned long)region->free_pointer & LOWTAG_MASK) == 0)
4521               && ((nbytes & LOWTAG_MASK) == 0));
4522
4523     /* Must be inside a PA section. */
4524     gc_assert(get_pseudo_atomic_atomic(thread));
4525
4526     /* maybe we can do this quickly ... */
4527     new_free_pointer = region->free_pointer + nbytes;
4528     if (new_free_pointer <= region->end_addr) {
4529         new_obj = (void*)(region->free_pointer);
4530         region->free_pointer = new_free_pointer;
4531         return(new_obj);        /* yup */
4532     }
4533
4534     /* we have to go the long way around, it seems. Check whether we
4535      * should GC in the near future
4536      */
4537     if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
4538         /* Don't flood the system with interrupts if the need to gc is
4539          * already noted. This can happen for example when SUB-GC
4540          * allocates or after a gc triggered in a WITHOUT-GCING. */
4541         if (SymbolValue(GC_PENDING,thread) == NIL) {
4542             /* set things up so that GC happens when we finish the PA
4543              * section */
4544             SetSymbolValue(GC_PENDING,T,thread);
4545             if (SymbolValue(GC_INHIBIT,thread) == NIL) {
4546                 set_pseudo_atomic_interrupted(thread);
4547 #ifdef LISP_FEATURE_PPC
4548                 /* PPC calls alloc() from a trap or from pa_alloc(),
4549                  * look up the most context if it's from a trap. */
4550                 {
4551                     os_context_t *context =
4552                         thread->interrupt_data->allocation_trap_context;
4553                     maybe_save_gc_mask_and_block_deferrables
4554                         (context ? os_context_sigmask_addr(context) : NULL);
4555                 }
4556 #else
4557                 maybe_save_gc_mask_and_block_deferrables(NULL);
4558 #endif
4559             }
4560         }
4561     }
4562     new_obj = gc_alloc_with_region(nbytes, page_type_flag, region, 0);
4563
4564 #ifndef LISP_FEATURE_WIN32
4565     alloc_signal = SymbolValue(ALLOC_SIGNAL,thread);
4566     if ((alloc_signal & FIXNUM_TAG_MASK) == 0) {
4567         if ((signed long) alloc_signal <= 0) {
4568             SetSymbolValue(ALLOC_SIGNAL, T, thread);
4569             raise(SIGPROF);
4570         } else {
4571             SetSymbolValue(ALLOC_SIGNAL,
4572                            alloc_signal - (1 << N_FIXNUM_TAG_BITS),
4573                            thread);
4574         }
4575     }
4576 #endif
4577
4578     return (new_obj);
4579 }
4580
4581 lispobj *
4582 general_alloc(long nbytes, int page_type_flag)
4583 {
4584     struct thread *thread = arch_os_get_current_thread();
4585     /* Select correct region, and call general_alloc_internal with it.
4586      * For other then boxed allocation we must lock first, since the
4587      * region is shared. */
4588     if (BOXED_PAGE_FLAG & page_type_flag) {
4589 #ifdef LISP_FEATURE_SB_THREAD
4590         struct alloc_region *region = (thread ? &(thread->alloc_region) : &boxed_region);
4591 #else
4592         struct alloc_region *region = &boxed_region;
4593 #endif
4594         return general_alloc_internal(nbytes, page_type_flag, region, thread);
4595     } else if (UNBOXED_PAGE_FLAG == page_type_flag) {
4596         lispobj * obj;
4597         gc_assert(0 == thread_mutex_lock(&allocation_lock));
4598         obj = general_alloc_internal(nbytes, page_type_flag, &unboxed_region, thread);
4599         gc_assert(0 == thread_mutex_unlock(&allocation_lock));
4600         return obj;
4601     } else {
4602         lose("bad page type flag: %d", page_type_flag);
4603     }
4604 }
4605
4606 lispobj *
4607 alloc(long nbytes)
4608 {
4609     gc_assert(get_pseudo_atomic_atomic(arch_os_get_current_thread()));
4610     return general_alloc(nbytes, BOXED_PAGE_FLAG);
4611 }
4612 \f
4613 /*
4614  * shared support for the OS-dependent signal handlers which
4615  * catch GENCGC-related write-protect violations
4616  */
4617 void unhandled_sigmemoryfault(void* addr);
4618
4619 /* Depending on which OS we're running under, different signals might
4620  * be raised for a violation of write protection in the heap. This
4621  * function factors out the common generational GC magic which needs
4622  * to invoked in this case, and should be called from whatever signal
4623  * handler is appropriate for the OS we're running under.
4624  *
4625  * Return true if this signal is a normal generational GC thing that
4626  * we were able to handle, or false if it was abnormal and control
4627  * should fall through to the general SIGSEGV/SIGBUS/whatever logic. */
4628
4629 int
4630 gencgc_handle_wp_violation(void* fault_addr)
4631 {
4632     page_index_t page_index = find_page_index(fault_addr);
4633
4634 #if QSHOW_SIGNALS
4635     FSHOW((stderr, "heap WP violation? fault_addr=%x, page_index=%d\n",
4636            fault_addr, page_index));
4637 #endif
4638
4639     /* Check whether the fault is within the dynamic space. */
4640     if (page_index == (-1)) {
4641
4642         /* It can be helpful to be able to put a breakpoint on this
4643          * case to help diagnose low-level problems. */
4644         unhandled_sigmemoryfault(fault_addr);
4645
4646         /* not within the dynamic space -- not our responsibility */
4647         return 0;
4648
4649     } else {
4650         int ret;
4651         ret = thread_mutex_lock(&free_pages_lock);
4652         gc_assert(ret == 0);
4653         if (page_table[page_index].write_protected) {
4654             /* Unprotect the page. */
4655             os_protect(page_address(page_index), GENCGC_CARD_BYTES, OS_VM_PROT_ALL);
4656             page_table[page_index].write_protected_cleared = 1;
4657             page_table[page_index].write_protected = 0;
4658         } else {
4659             /* The only acceptable reason for this signal on a heap
4660              * access is that GENCGC write-protected the page.
4661              * However, if two CPUs hit a wp page near-simultaneously,
4662              * we had better not have the second one lose here if it
4663              * does this test after the first one has already set wp=0
4664              */
4665             if(page_table[page_index].write_protected_cleared != 1)
4666                 lose("fault in heap page %d not marked as write-protected\nboxed_region.first_page: %d, boxed_region.last_page %d\n",
4667                      page_index, boxed_region.first_page,
4668                      boxed_region.last_page);
4669         }
4670         ret = thread_mutex_unlock(&free_pages_lock);
4671         gc_assert(ret == 0);
4672         /* Don't worry, we can handle it. */
4673         return 1;
4674     }
4675 }
4676 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
4677  * it's not just a case of the program hitting the write barrier, and
4678  * are about to let Lisp deal with it. It's basically just a
4679  * convenient place to set a gdb breakpoint. */
4680 void
4681 unhandled_sigmemoryfault(void *addr)
4682 {}
4683
4684 void gc_alloc_update_all_page_tables(void)
4685 {
4686     /* Flush the alloc regions updating the tables. */
4687     struct thread *th;
4688     for_each_thread(th)
4689         gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
4690     gc_alloc_update_page_tables(UNBOXED_PAGE_FLAG, &unboxed_region);
4691     gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &boxed_region);
4692 }
4693
4694 void
4695 gc_set_region_empty(struct alloc_region *region)
4696 {
4697     region->first_page = 0;
4698     region->last_page = -1;
4699     region->start_addr = page_address(0);
4700     region->free_pointer = page_address(0);
4701     region->end_addr = page_address(0);
4702 }
4703
4704 static void
4705 zero_all_free_pages()
4706 {
4707     page_index_t i;
4708
4709     for (i = 0; i < last_free_page; i++) {
4710         if (page_free_p(i)) {
4711 #ifdef READ_PROTECT_FREE_PAGES
4712             os_protect(page_address(i),
4713                        GENCGC_CARD_BYTES,
4714                        OS_VM_PROT_ALL);
4715 #endif
4716             zero_pages(i, i);
4717         }
4718     }
4719 }
4720
4721 /* Things to do before doing a final GC before saving a core (without
4722  * purify).
4723  *
4724  * + Pages in large_object pages aren't moved by the GC, so we need to
4725  *   unset that flag from all pages.
4726  * + The pseudo-static generation isn't normally collected, but it seems
4727  *   reasonable to collect it at least when saving a core. So move the
4728  *   pages to a normal generation.
4729  */
4730 static void
4731 prepare_for_final_gc ()
4732 {
4733     page_index_t i;
4734     for (i = 0; i < last_free_page; i++) {
4735         page_table[i].large_object = 0;
4736         if (page_table[i].gen == PSEUDO_STATIC_GENERATION) {
4737             int used = page_table[i].bytes_used;
4738             page_table[i].gen = HIGHEST_NORMAL_GENERATION;
4739             generations[PSEUDO_STATIC_GENERATION].bytes_allocated -= used;
4740             generations[HIGHEST_NORMAL_GENERATION].bytes_allocated += used;
4741         }
4742     }
4743 }
4744
4745
4746 /* Do a non-conservative GC, and then save a core with the initial
4747  * function being set to the value of the static symbol
4748  * SB!VM:RESTART-LISP-FUNCTION */
4749 void
4750 gc_and_save(char *filename, boolean prepend_runtime,
4751             boolean save_runtime_options,
4752             boolean compressed, int compression_level)
4753 {
4754     FILE *file;
4755     void *runtime_bytes = NULL;
4756     size_t runtime_size;
4757
4758     file = prepare_to_save(filename, prepend_runtime, &runtime_bytes,
4759                            &runtime_size);
4760     if (file == NULL)
4761        return;
4762
4763     conservative_stack = 0;
4764
4765     /* The filename might come from Lisp, and be moved by the now
4766      * non-conservative GC. */
4767     filename = strdup(filename);
4768
4769     /* Collect twice: once into relatively high memory, and then back
4770      * into low memory. This compacts the retained data into the lower
4771      * pages, minimizing the size of the core file.
4772      */
4773     prepare_for_final_gc();
4774     gencgc_alloc_start_page = last_free_page;
4775     collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4776
4777     prepare_for_final_gc();
4778     gencgc_alloc_start_page = -1;
4779     collect_garbage(HIGHEST_NORMAL_GENERATION+1);
4780
4781     if (prepend_runtime)
4782         save_runtime_to_filehandle(file, runtime_bytes, runtime_size);
4783
4784     /* The dumper doesn't know that pages need to be zeroed before use. */
4785     zero_all_free_pages();
4786     save_to_filehandle(file, filename, SymbolValue(RESTART_LISP_FUNCTION,0),
4787                        prepend_runtime, save_runtime_options,
4788                        compressed ? compression_level : COMPRESSION_LEVEL_NONE);
4789     /* Oops. Save still managed to fail. Since we've mangled the stack
4790      * beyond hope, there's not much we can do.
4791      * (beyond FUNCALLing RESTART_LISP_FUNCTION, but I suspect that's
4792      * going to be rather unsatisfactory too... */
4793     lose("Attempt to save core after non-conservative GC failed.\n");
4794 }