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