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