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