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