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