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