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