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