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