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