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