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