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