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