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