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