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