0.pre7.49:
[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 "runtime.h"
30 #include "sbcl.h"
31 #include "os.h"
32 #include "interr.h"
33 #include "globals.h"
34 #include "interrupt.h"
35 #include "validate.h"
36 #include "lispregs.h"
37 #include "arch.h"
38 #include "gc.h"
39 #include "gencgc.h"
40
41 /* a function defined externally in assembly language, called from
42  * this file */
43 void do_pending_interrupt(void);
44 \f
45 /*
46  * GC parameters
47  */
48
49 /* the number of actual generations. (The number of 'struct
50  * generation' objects is one more than this, because one object
51  * serves as scratch when GC'ing.) */
52 #define NUM_GENERATIONS 6
53
54 /* Should we use page protection to help avoid the scavenging of pages
55  * that don't have pointers to younger generations? */
56 boolean enable_page_protection = 1;
57
58 /* Should we unmap a page and re-mmap it to have it zero filled? */
59 #if defined(__FreeBSD__) || defined(__OpenBSD__)
60 /* comment from cmucl-2.4.8: This can waste a lot of swap on FreeBSD
61  * so don't unmap there.
62  *
63  * The CMU CL comment didn't specify a version, but was probably an
64  * old version of FreeBSD (pre-4.0), so this might no longer be true.
65  * OTOH, if it is true, this behavior might exist on OpenBSD too, so
66  * for now we don't unmap there either. -- WHN 2001-04-07 */
67 boolean gencgc_unmap_zero = 0;
68 #else
69 boolean gencgc_unmap_zero = 1;
70 #endif
71
72 /* the minimum size (in bytes) for a large object*/
73 unsigned large_object_size = 4 * 4096;
74 \f
75 /*
76  * debugging
77  */
78
79 #define gc_abort() lose("GC invariant lost, file \"%s\", line %d", \
80                         __FILE__, __LINE__)
81
82 /* FIXME: In CMU CL, this was "#if 0" with no explanation. Find out
83  * how much it costs to make it "#if 1". If it's not too expensive,
84  * keep it. */
85 #if 1
86 #define gc_assert(ex) do { \
87         if (!(ex)) gc_abort(); \
88 } while (0)
89 #else
90 #define gc_assert(ex)
91 #endif
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 unsigned gencgc_verbose = (QSHOW ? 1 : 0);
96
97 /* FIXME: At some point enable the various error-checking things below
98  * and see what they say. */
99
100 /* We hunt for pointers to old-space, when GCing generations >= verify_gen.
101  * Set verify_gens to NUM_GENERATIONS to disable this kind of check. */
102 int verify_gens = NUM_GENERATIONS;
103
104 /* Should we do a pre-scan verify of generation 0 before it's GCed? */
105 boolean pre_verify_gen_0 = 0;
106
107 /* Should we check for bad pointers after gc_free_heap is called
108  * from Lisp PURIFY? */
109 boolean verify_after_free_heap = 0;
110
111 /* Should we print a note when code objects are found in the dynamic space
112  * during a heap verify? */
113 boolean verify_dynamic_code_check = 0;
114
115 /* Should we check code objects for fixup errors after they are transported? */
116 boolean check_code_fixups = 0;
117
118 /* Should we check that newly allocated regions are zero filled? */
119 boolean gencgc_zero_check = 0;
120
121 /* Should we check that the free space is zero filled? */
122 boolean gencgc_enable_verify_zero_fill = 0;
123
124 /* Should we check that free pages are zero filled during gc_free_heap
125  * called after Lisp PURIFY? */
126 boolean gencgc_zero_check_during_free_heap = 0;
127 \f
128 /*
129  * GC structures and variables
130  */
131
132 /* the total bytes allocated. These are seen by Lisp DYNAMIC-USAGE. */
133 unsigned long bytes_allocated = 0;
134 static unsigned long auto_gc_trigger = 0;
135
136 /* the source and destination generations. These are set before a GC starts
137  * scavenging. */
138 static int from_space;
139 static int new_space;
140
141 /* FIXME: It would be nice to use this symbolic constant instead of
142  * bare 4096 almost everywhere. We could also use an assertion that
143  * it's equal to getpagesize(). */
144 #define PAGE_BYTES 4096
145
146 /* An array of page structures is statically allocated.
147  * This helps quickly map between an address its page structure.
148  * NUM_PAGES is set from the size of the dynamic space. */
149 struct page page_table[NUM_PAGES];
150
151 /* To map addresses to page structures the address of the first page
152  * is needed. */
153 static void *heap_base = NULL;
154
155 /* Calculate the start address for the given page number. */
156 inline void *
157 page_address(int page_num)
158 {
159     return (heap_base + (page_num * 4096));
160 }
161
162 /* Find the page index within the page_table for the given
163  * address. Return -1 on failure. */
164 inline int
165 find_page_index(void *addr)
166 {
167     int index = addr-heap_base;
168
169     if (index >= 0) {
170         index = ((unsigned int)index)/4096;
171         if (index < NUM_PAGES)
172             return (index);
173     }
174
175     return (-1);
176 }
177
178 /* a structure to hold the state of a generation */
179 struct generation {
180
181     /* the first page that gc_alloc() checks on its next call */
182     int alloc_start_page;
183
184     /* the first page that gc_alloc_unboxed() checks on its next call */
185     int alloc_unboxed_start_page;
186
187     /* the first page that gc_alloc_large (boxed) considers on its next
188      * call. (Although it always allocates after the boxed_region.) */
189     int alloc_large_start_page;
190
191     /* the first page that gc_alloc_large (unboxed) considers on its
192      * next call. (Although it always allocates after the
193      * current_unboxed_region.) */
194     int alloc_large_unboxed_start_page;
195
196     /* the bytes allocated to this generation */
197     int bytes_allocated;
198
199     /* the number of bytes at which to trigger a GC */
200     int gc_trigger;
201
202     /* to calculate a new level for gc_trigger */
203     int bytes_consed_between_gc;
204
205     /* the number of GCs since the last raise */
206     int num_gc;
207
208     /* the average age after which a GC will raise objects to the
209      * next generation */
210     int trigger_age;
211
212     /* the cumulative sum of the bytes allocated to this generation. It is
213      * cleared after a GC on this generations, and update before new
214      * objects are added from a GC of a younger generation. Dividing by
215      * the bytes_allocated will give the average age of the memory in
216      * this generation since its last GC. */
217     int cum_sum_bytes_allocated;
218
219     /* a minimum average memory age before a GC will occur helps
220      * prevent a GC when a large number of new live objects have been
221      * added, in which case a GC could be a waste of time */
222     double min_av_mem_age;
223 };
224
225 /* an array of generation structures. There needs to be one more
226  * generation structure than actual generations as the oldest
227  * generation is temporarily raised then lowered. */
228 static struct generation generations[NUM_GENERATIONS+1];
229
230 /* the oldest generation that is will currently be GCed by default.
231  * Valid values are: 0, 1, ... (NUM_GENERATIONS-1)
232  *
233  * The default of (NUM_GENERATIONS-1) enables GC on all generations.
234  *
235  * Setting this to 0 effectively disables the generational nature of
236  * the GC. In some applications generational GC may not be useful
237  * because there are no long-lived objects.
238  *
239  * An intermediate value could be handy after moving long-lived data
240  * into an older generation so an unnecessary GC of this long-lived
241  * data can be avoided. */
242 unsigned int  gencgc_oldest_gen_to_gc = NUM_GENERATIONS-1;
243
244 /* The maximum free page in the heap is maintained and used to update
245  * ALLOCATION_POINTER which is used by the room function to limit its
246  * search of the heap. XX Gencgc obviously needs to be better
247  * integrated with the Lisp code. */
248 static int  last_free_page;
249 static int  last_used_page = 0;
250 \f
251 /*
252  * miscellaneous heap functions
253  */
254
255 /* Count the number of pages which are write-protected within the
256  * given generation. */
257 static int
258 count_write_protect_generation_pages(int generation)
259 {
260     int i;
261     int count = 0;
262
263     for (i = 0; i < last_free_page; i++)
264         if ((page_table[i].allocated != FREE_PAGE)
265             && (page_table[i].gen == generation)
266             && (page_table[i].write_protected == 1))
267             count++;
268     return count;
269 }
270
271 /* Count the number of pages within the given generation. */
272 static int
273 count_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 != 0)
280             && (page_table[i].gen == generation))
281             count++;
282     return count;
283 }
284
285 /* Count the number of dont_move pages. */
286 static int
287 count_dont_move_pages(void)
288 {
289     int i;
290     int count = 0;
291     for (i = 0; i < last_free_page; i++) {
292         if ((page_table[i].allocated != 0) && (page_table[i].dont_move != 0)) {
293             ++count;
294         }
295     }
296     return count;
297 }
298
299 /* Work through the pages and add up the number of bytes used for the
300  * given generation. */
301 static int
302 count_generation_bytes_allocated (int gen)
303 {
304     int i;
305     int result = 0;
306     for (i = 0; i < last_free_page; i++) {
307         if ((page_table[i].allocated != 0) && (page_table[i].gen == gen))
308             result += page_table[i].bytes_used;
309     }
310     return result;
311 }
312
313 /* Return the average age of the memory in a generation. */
314 static double
315 gen_av_mem_age(int gen)
316 {
317     if (generations[gen].bytes_allocated == 0)
318         return 0.0;
319
320     return
321         ((double)generations[gen].cum_sum_bytes_allocated)
322         / ((double)generations[gen].bytes_allocated);
323 }
324
325 /* The verbose argument controls how much to print: 0 for normal
326  * level of detail; 1 for debugging. */
327 static void
328 print_generation_stats(int verbose) /* FIXME: should take FILE argument */
329 {
330     int i, gens;
331     int fpu_state[27];
332
333     /* This code uses the FP instructions which may be set up for Lisp
334      * so they need to be saved and reset for C. */
335     fpu_save(fpu_state);
336
337     /* number of generations to print */
338     if (verbose)
339         gens = NUM_GENERATIONS+1;
340     else
341         gens = NUM_GENERATIONS;
342
343     /* Print the heap stats. */
344     fprintf(stderr,
345             "   Generation Boxed Unboxed LB   LUB    Alloc  Waste   Trig    WP  GCs Mem-age\n");
346
347     for (i = 0; i < gens; i++) {
348         int j;
349         int boxed_cnt = 0;
350         int unboxed_cnt = 0;
351         int large_boxed_cnt = 0;
352         int large_unboxed_cnt = 0;
353
354         for (j = 0; j < last_free_page; j++)
355             if (page_table[j].gen == i) {
356
357                 /* Count the number of boxed pages within the given
358                  * generation. */
359                 if (page_table[j].allocated == BOXED_PAGE) {
360                     if (page_table[j].large_object)
361                         large_boxed_cnt++;
362                     else
363                         boxed_cnt++;
364                 }
365
366                 /* Count the number of unboxed pages within the given
367                  * generation. */
368                 if (page_table[j].allocated == UNBOXED_PAGE) {
369                     if (page_table[j].large_object)
370                         large_unboxed_cnt++;
371                     else
372                         unboxed_cnt++;
373                 }
374             }
375
376         gc_assert(generations[i].bytes_allocated
377                   == count_generation_bytes_allocated(i));
378         fprintf(stderr,
379                 "   %8d: %5d %5d %5d %5d %8d %5d %8d %4d %3d %7.4f\n",
380                 i,
381                 boxed_cnt, unboxed_cnt, large_boxed_cnt, large_unboxed_cnt,
382                 generations[i].bytes_allocated,
383                 (count_generation_pages(i)*4096
384                  - generations[i].bytes_allocated),
385                 generations[i].gc_trigger,
386                 count_write_protect_generation_pages(i),
387                 generations[i].num_gc,
388                 gen_av_mem_age(i));
389     }
390     fprintf(stderr,"   Total bytes allocated=%ld\n", bytes_allocated);
391
392     fpu_restore(fpu_state);
393 }
394 \f
395 /*
396  * allocation routines
397  */
398
399 /*
400  * To support quick and inline allocation, regions of memory can be
401  * allocated and then allocated from with just a free pointer and a
402  * check against an end address.
403  *
404  * Since objects can be allocated to spaces with different properties
405  * e.g. boxed/unboxed, generation, ages; there may need to be many
406  * allocation regions.
407  *
408  * Each allocation region may be start within a partly used page. Many
409  * features of memory use are noted on a page wise basis, e.g. the
410  * generation; so if a region starts within an existing allocated page
411  * it must be consistent with this page.
412  *
413  * During the scavenging of the newspace, objects will be transported
414  * into an allocation region, and pointers updated to point to this
415  * allocation region. It is possible that these pointers will be
416  * scavenged again before the allocation region is closed, e.g. due to
417  * trans_list which jumps all over the place to cleanup the list. It
418  * is important to be able to determine properties of all objects
419  * pointed to when scavenging, e.g to detect pointers to the oldspace.
420  * Thus it's important that the allocation regions have the correct
421  * properties set when allocated, and not just set when closed. The
422  * region allocation routines return regions with the specified
423  * properties, and grab all the pages, setting their properties
424  * appropriately, except that the amount used is not known.
425  *
426  * These regions are used to support quicker allocation using just a
427  * free pointer. The actual space used by the region is not reflected
428  * in the pages tables until it is closed. It can't be scavenged until
429  * closed.
430  *
431  * When finished with the region it should be closed, which will
432  * update the page tables for the actual space used returning unused
433  * space. Further it may be noted in the new regions which is
434  * necessary when scavenging the newspace.
435  *
436  * Large objects may be allocated directly without an allocation
437  * region, the page tables are updated immediately.
438  *
439  * Unboxed objects don't contain pointers to other objects and so
440  * don't need scavenging. Further they can't contain pointers to
441  * younger generations so WP is not needed. By allocating pages to
442  * unboxed objects the whole page never needs scavenging or
443  * write-protecting. */
444
445 /* We are only using two regions at present. Both are for the current
446  * newspace generation. */
447 struct alloc_region boxed_region;
448 struct alloc_region unboxed_region;
449
450 /* XX hack. Current Lisp code uses the following. Need copying in/out. */
451 void *current_region_free_pointer;
452 void *current_region_end_addr;
453
454 /* The generation currently being allocated to. */
455 static int gc_alloc_generation;
456
457 /* Find a new region with room for at least the given number of bytes.
458  *
459  * It starts looking at the current generation's alloc_start_page. So
460  * may pick up from the previous region if there is enough space. This
461  * keeps the allocation contiguous when scavenging the newspace.
462  *
463  * The alloc_region should have been closed by a call to
464  * gc_alloc_update_page_tables(), and will thus be in an empty state.
465  *
466  * To assist the scavenging functions write-protected pages are not
467  * used. Free pages should not be write-protected.
468  *
469  * It is critical to the conservative GC that the start of regions be
470  * known. To help achieve this only small regions are allocated at a
471  * time.
472  *
473  * During scavenging, pointers may be found to within the current
474  * region and the page generation must be set so that pointers to the
475  * from space can be recognized. Therefore the generation of pages in
476  * the region are set to gc_alloc_generation. To prevent another
477  * allocation call using the same pages, all the pages in the region
478  * are allocated, although they will initially be empty.
479  */
480 static void
481 gc_alloc_new_region(int nbytes, int unboxed, struct alloc_region *alloc_region)
482 {
483     int first_page;
484     int last_page;
485     int region_size;
486     int restart_page;
487     int bytes_found;
488     int num_pages;
489     int i;
490
491     /*
492     FSHOW((stderr,
493            "/alloc_new_region for %d bytes from gen %d\n",
494            nbytes, gc_alloc_generation));
495     */
496
497     /* Check that the region is in a reset state. */
498     gc_assert((alloc_region->first_page == 0)
499               && (alloc_region->last_page == -1)
500               && (alloc_region->free_pointer == alloc_region->end_addr));
501
502     if (unboxed) {
503         restart_page =
504             generations[gc_alloc_generation].alloc_unboxed_start_page;
505     } else {
506         restart_page =
507             generations[gc_alloc_generation].alloc_start_page;
508     }
509
510     /* Search for a contiguous free region of at least nbytes with the
511      * given properties: boxed/unboxed, generation. */
512     do {
513         first_page = restart_page;
514
515         /* First search for a page with at least 32 bytes free, which is
516          * not write-protected, and which is not marked dont_move.
517          *
518          * FIXME: This looks extremely similar, perhaps identical, to
519          * code in gc_alloc_large(). It should be shared somehow. */
520         while ((first_page < NUM_PAGES)
521                && (page_table[first_page].allocated != FREE_PAGE) /* not free page */
522                && ((unboxed &&
523                     (page_table[first_page].allocated != UNBOXED_PAGE))
524                    || (!unboxed &&
525                        (page_table[first_page].allocated != BOXED_PAGE))
526                    || (page_table[first_page].large_object != 0)
527                    || (page_table[first_page].gen != gc_alloc_generation)
528                    || (page_table[first_page].bytes_used >= (4096-32))
529                    || (page_table[first_page].write_protected != 0)
530                    || (page_table[first_page].dont_move != 0)))
531             first_page++;
532         /* Check for a failure. */
533         if (first_page >= NUM_PAGES) {
534             fprintf(stderr,
535                     "Argh! gc_alloc_new_region failed on first_page, nbytes=%d.\n",
536                     nbytes);
537             print_generation_stats(1);
538             lose(NULL);
539         }
540
541         gc_assert(page_table[first_page].write_protected == 0);
542
543         /*
544         FSHOW((stderr,
545                "/first_page=%d bytes_used=%d\n",
546                first_page, page_table[first_page].bytes_used));
547         */
548
549         /* Now search forward to calculate the available region size. It
550          * tries to keeps going until nbytes are found and the number of
551          * pages is greater than some level. This helps keep down the
552          * number of pages in a region. */
553         last_page = first_page;
554         bytes_found = 4096 - page_table[first_page].bytes_used;
555         num_pages = 1;
556         while (((bytes_found < nbytes) || (num_pages < 2))
557                && (last_page < (NUM_PAGES-1))
558                && (page_table[last_page+1].allocated == FREE_PAGE)) {
559             last_page++;
560             num_pages++;
561             bytes_found += 4096;
562             gc_assert(page_table[last_page].write_protected == 0);
563         }
564
565         region_size = (4096 - page_table[first_page].bytes_used)
566             + 4096*(last_page-first_page);
567
568         gc_assert(bytes_found == region_size);
569
570         /*
571         FSHOW((stderr,
572                "/last_page=%d bytes_found=%d num_pages=%d\n",
573                last_page, bytes_found, num_pages));
574         */
575
576         restart_page = last_page + 1;
577     } while ((restart_page < NUM_PAGES) && (bytes_found < nbytes));
578
579     /* Check for a failure. */
580     if ((restart_page >= NUM_PAGES) && (bytes_found < nbytes)) {
581         fprintf(stderr,
582                 "Argh! gc_alloc_new_region() failed on restart_page, nbytes=%d.\n",
583                 nbytes);
584         print_generation_stats(1);
585         lose(NULL);
586     }
587
588     /*
589     FSHOW((stderr,
590            "/gc_alloc_new_region() gen %d: %d bytes: pages %d to %d: addr=%x\n",
591            gc_alloc_generation,
592            bytes_found,
593            first_page,
594            last_page,
595            page_address(first_page)));
596     */
597
598     /* Set up the alloc_region. */
599     alloc_region->first_page = first_page;
600     alloc_region->last_page = last_page;
601     alloc_region->start_addr = page_table[first_page].bytes_used
602         + page_address(first_page);
603     alloc_region->free_pointer = alloc_region->start_addr;
604     alloc_region->end_addr = alloc_region->start_addr + bytes_found;
605
606     if (gencgc_zero_check) {
607         int *p;
608         for (p = (int *)alloc_region->start_addr;
609             p < (int *)alloc_region->end_addr; p++) {
610             if (*p != 0) {
611                 /* KLUDGE: It would be nice to use %lx and explicit casts
612                  * (long) in code like this, so that it is less likely to
613                  * break randomly when running on a machine with different
614                  * word sizes. -- WHN 19991129 */
615                 lose("The new region at %x is not zero.", p);
616             }
617         }
618     }
619
620     /* Set up the pages. */
621
622     /* The first page may have already been in use. */
623     if (page_table[first_page].bytes_used == 0) {
624         if (unboxed)
625             page_table[first_page].allocated = UNBOXED_PAGE;
626         else
627             page_table[first_page].allocated = BOXED_PAGE;
628         page_table[first_page].gen = gc_alloc_generation;
629         page_table[first_page].large_object = 0;
630         page_table[first_page].first_object_offset = 0;
631     }
632
633     if (unboxed)
634         gc_assert(page_table[first_page].allocated == UNBOXED_PAGE);
635     else
636         gc_assert(page_table[first_page].allocated == BOXED_PAGE);
637     gc_assert(page_table[first_page].gen == gc_alloc_generation);
638     gc_assert(page_table[first_page].large_object == 0);
639
640     for (i = first_page+1; i <= last_page; i++) {
641         if (unboxed)
642             page_table[i].allocated = UNBOXED_PAGE;
643         else
644             page_table[i].allocated = BOXED_PAGE;
645         page_table[i].gen = gc_alloc_generation;
646         page_table[i].large_object = 0;
647         /* This may not be necessary for unboxed regions (think it was
648          * broken before!) */
649         page_table[i].first_object_offset =
650             alloc_region->start_addr - page_address(i);
651     }
652
653     /* Bump up last_free_page. */
654     if (last_page+1 > last_free_page) {
655         last_free_page = last_page+1;
656         SetSymbolValue(ALLOCATION_POINTER,
657                        (lispobj)(((char *)heap_base) + last_free_page*4096));
658         if (last_page+1 > last_used_page)
659             last_used_page = last_page+1;
660     }
661 }
662
663 /* If the record_new_objects flag is 2 then all new regions created
664  * are recorded.
665  *
666  * If it's 1 then then it is only recorded if the first page of the
667  * current region is <= new_areas_ignore_page. This helps avoid
668  * unnecessary recording when doing full scavenge pass.
669  *
670  * The new_object structure holds the page, byte offset, and size of
671  * new regions of objects. Each new area is placed in the array of
672  * these structures pointer to by new_areas. new_areas_index holds the
673  * offset into new_areas.
674  *
675  * If new_area overflows NUM_NEW_AREAS then it stops adding them. The
676  * later code must detect this and handle it, probably by doing a full
677  * scavenge of a generation. */
678 #define NUM_NEW_AREAS 512
679 static int record_new_objects = 0;
680 static int new_areas_ignore_page;
681 struct new_area {
682     int  page;
683     int  offset;
684     int  size;
685 };
686 static struct new_area (*new_areas)[];
687 static int new_areas_index;
688 int max_new_areas;
689
690 /* Add a new area to new_areas. */
691 static void
692 add_new_area(int first_page, int offset, int size)
693 {
694     unsigned new_area_start,c;
695     int i;
696
697     /* Ignore if full. */
698     if (new_areas_index >= NUM_NEW_AREAS)
699         return;
700
701     switch (record_new_objects) {
702     case 0:
703         return;
704     case 1:
705         if (first_page > new_areas_ignore_page)
706             return;
707         break;
708     case 2:
709         break;
710     default:
711         gc_abort();
712     }
713
714     new_area_start = 4096*first_page + offset;
715
716     /* Search backwards for a prior area that this follows from. If
717        found this will save adding a new area. */
718     for (i = new_areas_index-1, c = 0; (i >= 0) && (c < 8); i--, c++) {
719         unsigned area_end =
720             4096*((*new_areas)[i].page)
721             + (*new_areas)[i].offset
722             + (*new_areas)[i].size;
723         /*FSHOW((stderr,
724                "/add_new_area S1 %d %d %d %d\n",
725                i, c, new_area_start, area_end));*/
726         if (new_area_start == area_end) {
727             /*FSHOW((stderr,
728                    "/adding to [%d] %d %d %d with %d %d %d:\n",
729                    i,
730                    (*new_areas)[i].page,
731                    (*new_areas)[i].offset,
732                    (*new_areas)[i].size,
733                    first_page,
734                    offset,
735                    size));*/
736             (*new_areas)[i].size += size;
737             return;
738         }
739     }
740     /*FSHOW((stderr, "/add_new_area S1 %d %d %d\n", i, c, new_area_start));*/
741
742     (*new_areas)[new_areas_index].page = first_page;
743     (*new_areas)[new_areas_index].offset = offset;
744     (*new_areas)[new_areas_index].size = size;
745     /*FSHOW((stderr,
746            "/new_area %d page %d offset %d size %d\n",
747            new_areas_index, first_page, offset, size));*/
748     new_areas_index++;
749
750     /* Note the max new_areas used. */
751     if (new_areas_index > max_new_areas)
752         max_new_areas = new_areas_index;
753 }
754
755 /* Update the tables for the alloc_region. The region maybe added to
756  * the new_areas.
757  *
758  * When done the alloc_region is set up so that the next quick alloc
759  * will fail safely and thus a new region will be allocated. Further
760  * it is safe to try to re-update the page table of this reset
761  * alloc_region. */
762 void
763 gc_alloc_update_page_tables(int unboxed, struct alloc_region *alloc_region)
764 {
765     int more;
766     int first_page;
767     int next_page;
768     int bytes_used;
769     int orig_first_page_bytes_used;
770     int region_size;
771     int byte_cnt;
772
773     /*
774     FSHOW((stderr,
775            "/gc_alloc_update_page_tables() to gen %d:\n",
776            gc_alloc_generation));
777     */
778
779     first_page = alloc_region->first_page;
780
781     /* Catch an unused alloc_region. */
782     if ((first_page == 0) && (alloc_region->last_page == -1))
783         return;
784
785     next_page = first_page+1;
786
787     /* Skip if no bytes were allocated. */
788     if (alloc_region->free_pointer != alloc_region->start_addr) {
789         orig_first_page_bytes_used = page_table[first_page].bytes_used;
790
791         gc_assert(alloc_region->start_addr == (page_address(first_page) + page_table[first_page].bytes_used));
792
793         /* All the pages used need to be updated */
794
795         /* Update the first page. */
796
797         /* If the page was free then set up the gen, and
798          * first_object_offset. */
799         if (page_table[first_page].bytes_used == 0)
800             gc_assert(page_table[first_page].first_object_offset == 0);
801
802         if (unboxed)
803             gc_assert(page_table[first_page].allocated == UNBOXED_PAGE);
804         else
805             gc_assert(page_table[first_page].allocated == BOXED_PAGE);
806         gc_assert(page_table[first_page].gen == gc_alloc_generation);
807         gc_assert(page_table[first_page].large_object == 0);
808
809         byte_cnt = 0;
810
811         /* Calculate the number of bytes used in this page. This is not
812          * always the number of new bytes, unless it was free. */
813         more = 0;
814         if ((bytes_used = (alloc_region->free_pointer - page_address(first_page)))>4096) {
815             bytes_used = 4096;
816             more = 1;
817         }
818         page_table[first_page].bytes_used = bytes_used;
819         byte_cnt += bytes_used;
820
821
822         /* All the rest of the pages should be free. We need to set their
823          * first_object_offset pointer to the start of the region, and set
824          * the bytes_used. */
825         while (more) {
826             if (unboxed)
827                 gc_assert(page_table[next_page].allocated == UNBOXED_PAGE);
828             else
829                 gc_assert(page_table[next_page].allocated == BOXED_PAGE);
830             gc_assert(page_table[next_page].bytes_used == 0);
831             gc_assert(page_table[next_page].gen == gc_alloc_generation);
832             gc_assert(page_table[next_page].large_object == 0);
833
834             gc_assert(page_table[next_page].first_object_offset ==
835                       alloc_region->start_addr - page_address(next_page));
836
837             /* Calculate the number of bytes used in this page. */
838             more = 0;
839             if ((bytes_used = (alloc_region->free_pointer
840                                - page_address(next_page)))>4096) {
841                 bytes_used = 4096;
842                 more = 1;
843             }
844             page_table[next_page].bytes_used = bytes_used;
845             byte_cnt += bytes_used;
846
847             next_page++;
848         }
849
850         region_size = alloc_region->free_pointer - alloc_region->start_addr;
851         bytes_allocated += region_size;
852         generations[gc_alloc_generation].bytes_allocated += region_size;
853
854         gc_assert((byte_cnt- orig_first_page_bytes_used) == region_size);
855
856         /* Set the generations alloc restart page to the last page of
857          * the region. */
858         if (unboxed)
859             generations[gc_alloc_generation].alloc_unboxed_start_page =
860                 next_page-1;
861         else
862             generations[gc_alloc_generation].alloc_start_page = next_page-1;
863
864         /* Add the region to the new_areas if requested. */
865         if (!unboxed)
866             add_new_area(first_page,orig_first_page_bytes_used, region_size);
867
868         /*
869         FSHOW((stderr,
870                "/gc_alloc_update_page_tables update %d bytes to gen %d\n",
871                region_size,
872                gc_alloc_generation));
873         */
874     } else {
875         /* There are no bytes allocated. Unallocate the first_page if
876          * there are 0 bytes_used. */
877         if (page_table[first_page].bytes_used == 0)
878             page_table[first_page].allocated = FREE_PAGE;
879     }
880
881     /* Unallocate any unused pages. */
882     while (next_page <= alloc_region->last_page) {
883         gc_assert(page_table[next_page].bytes_used == 0);
884         page_table[next_page].allocated = FREE_PAGE;
885         next_page++;
886     }
887
888     /* Reset the alloc_region. */
889     alloc_region->first_page = 0;
890     alloc_region->last_page = -1;
891     alloc_region->start_addr = page_address(0);
892     alloc_region->free_pointer = page_address(0);
893     alloc_region->end_addr = page_address(0);
894 }
895
896 static inline void *gc_quick_alloc(int nbytes);
897
898 /* Allocate a possibly large object. */
899 static void *
900 gc_alloc_large(int nbytes, int unboxed, struct alloc_region *alloc_region)
901 {
902     int first_page;
903     int last_page;
904     int region_size;
905     int restart_page;
906     int bytes_found;
907     int num_pages;
908     int orig_first_page_bytes_used;
909     int byte_cnt;
910     int more;
911     int bytes_used;
912     int next_page;
913     int large = (nbytes >= large_object_size);
914
915     /*
916     if (nbytes > 200000)
917         FSHOW((stderr, "/alloc_large %d\n", nbytes));
918     */
919
920     /*
921     FSHOW((stderr,
922            "/gc_alloc_large() for %d bytes from gen %d\n",
923            nbytes, gc_alloc_generation));
924     */
925
926     /* If the object is small, and there is room in the current region
927        then allocation it in the current region. */
928     if (!large
929         && ((alloc_region->end_addr-alloc_region->free_pointer) >= nbytes))
930         return gc_quick_alloc(nbytes);
931
932     /* Search for a contiguous free region of at least nbytes. If it's a
933        large object then align it on a page boundary by searching for a
934        free page. */
935
936     /* To allow the allocation of small objects without the danger of
937        using a page in the current boxed region, the search starts after
938        the current boxed free region. XX could probably keep a page
939        index ahead of the current region and bumped up here to save a
940        lot of re-scanning. */
941     if (unboxed) {
942         restart_page =
943             generations[gc_alloc_generation].alloc_large_unboxed_start_page;
944     } else {
945         restart_page = generations[gc_alloc_generation].alloc_large_start_page;
946     }
947     if (restart_page <= alloc_region->last_page) {
948         restart_page = alloc_region->last_page+1;
949     }
950
951     do {
952         first_page = restart_page;
953
954         if (large)
955             while ((first_page < NUM_PAGES)
956                    && (page_table[first_page].allocated != FREE_PAGE))
957                 first_page++;
958         else
959             /* FIXME: This looks extremely similar, perhaps identical,
960              * to code in gc_alloc_new_region(). It should be shared
961              * somehow. */
962             while ((first_page < NUM_PAGES)
963                    && (page_table[first_page].allocated != FREE_PAGE)
964                    && ((unboxed &&
965                         (page_table[first_page].allocated != UNBOXED_PAGE))
966                        || (!unboxed &&
967                            (page_table[first_page].allocated != BOXED_PAGE))
968                        || (page_table[first_page].large_object != 0)
969                        || (page_table[first_page].gen != gc_alloc_generation)
970                        || (page_table[first_page].bytes_used >= (4096-32))
971                        || (page_table[first_page].write_protected != 0)
972                        || (page_table[first_page].dont_move != 0)))
973                 first_page++;
974
975         if (first_page >= NUM_PAGES) {
976             fprintf(stderr,
977                     "Argh! gc_alloc_large failed (first_page), nbytes=%d.\n",
978                     nbytes);
979             print_generation_stats(1);
980             lose(NULL);
981         }
982
983         gc_assert(page_table[first_page].write_protected == 0);
984
985         /*
986         FSHOW((stderr,
987                "/first_page=%d bytes_used=%d\n",
988                first_page, page_table[first_page].bytes_used));
989         */
990
991         last_page = first_page;
992         bytes_found = 4096 - page_table[first_page].bytes_used;
993         num_pages = 1;
994         while ((bytes_found < nbytes)
995                && (last_page < (NUM_PAGES-1))
996                && (page_table[last_page+1].allocated == FREE_PAGE)) {
997             last_page++;
998             num_pages++;
999             bytes_found += 4096;
1000             gc_assert(page_table[last_page].write_protected == 0);
1001         }
1002
1003         region_size = (4096 - page_table[first_page].bytes_used)
1004             + 4096*(last_page-first_page);
1005
1006         gc_assert(bytes_found == region_size);
1007
1008         /*
1009         FSHOW((stderr,
1010                "/last_page=%d bytes_found=%d num_pages=%d\n",
1011                last_page, bytes_found, num_pages));
1012         */
1013
1014         restart_page = last_page + 1;
1015     } while ((restart_page < NUM_PAGES) && (bytes_found < nbytes));
1016
1017     /* Check for a failure */
1018     if ((restart_page >= NUM_PAGES) && (bytes_found < nbytes)) {
1019         fprintf(stderr,
1020                 "Argh! gc_alloc_large failed (restart_page), nbytes=%d.\n",
1021                 nbytes);
1022         print_generation_stats(1);
1023         lose(NULL);
1024     }
1025
1026     /*
1027     if (large)
1028         FSHOW((stderr,
1029                "/gc_alloc_large() gen %d: %d of %d bytes: from pages %d to %d: addr=%x\n",
1030                gc_alloc_generation,
1031                nbytes,
1032                bytes_found,
1033                first_page,
1034                last_page,
1035                page_address(first_page)));
1036     */
1037
1038     gc_assert(first_page > alloc_region->last_page);
1039     if (unboxed)
1040         generations[gc_alloc_generation].alloc_large_unboxed_start_page =
1041             last_page;
1042     else
1043         generations[gc_alloc_generation].alloc_large_start_page = last_page;
1044
1045     /* Set up the pages. */
1046     orig_first_page_bytes_used = page_table[first_page].bytes_used;
1047
1048     /* If the first page was free then set up the gen, and
1049      * first_object_offset. */
1050     if (page_table[first_page].bytes_used == 0) {
1051         if (unboxed)
1052             page_table[first_page].allocated = UNBOXED_PAGE;
1053         else
1054             page_table[first_page].allocated = BOXED_PAGE;
1055         page_table[first_page].gen = gc_alloc_generation;
1056         page_table[first_page].first_object_offset = 0;
1057         page_table[first_page].large_object = large;
1058     }
1059
1060     if (unboxed)
1061         gc_assert(page_table[first_page].allocated == UNBOXED_PAGE);
1062     else
1063         gc_assert(page_table[first_page].allocated == BOXED_PAGE);
1064     gc_assert(page_table[first_page].gen == gc_alloc_generation);
1065     gc_assert(page_table[first_page].large_object == large);
1066
1067     byte_cnt = 0;
1068
1069     /* Calc. the number of bytes used in this page. This is not
1070      * always the number of new bytes, unless it was free. */
1071     more = 0;
1072     if ((bytes_used = nbytes+orig_first_page_bytes_used) > 4096) {
1073         bytes_used = 4096;
1074         more = 1;
1075     }
1076     page_table[first_page].bytes_used = bytes_used;
1077     byte_cnt += bytes_used;
1078
1079     next_page = first_page+1;
1080
1081     /* All the rest of the pages should be free. We need to set their
1082      * first_object_offset pointer to the start of the region, and
1083      * set the bytes_used. */
1084     while (more) {
1085         gc_assert(page_table[next_page].allocated == FREE_PAGE);
1086         gc_assert(page_table[next_page].bytes_used == 0);
1087         if (unboxed)
1088             page_table[next_page].allocated = UNBOXED_PAGE;
1089         else
1090             page_table[next_page].allocated = BOXED_PAGE;
1091         page_table[next_page].gen = gc_alloc_generation;
1092         page_table[next_page].large_object = large;
1093
1094         page_table[next_page].first_object_offset =
1095             orig_first_page_bytes_used - 4096*(next_page-first_page);
1096
1097         /* Calculate the number of bytes used in this page. */
1098         more = 0;
1099         if ((bytes_used=(nbytes+orig_first_page_bytes_used)-byte_cnt) > 4096) {
1100             bytes_used = 4096;
1101             more = 1;
1102         }
1103         page_table[next_page].bytes_used = bytes_used;
1104         byte_cnt += bytes_used;
1105
1106         next_page++;
1107     }
1108
1109     gc_assert((byte_cnt-orig_first_page_bytes_used) == nbytes);
1110
1111     bytes_allocated += nbytes;
1112     generations[gc_alloc_generation].bytes_allocated += nbytes;
1113
1114     /* Add the region to the new_areas if requested. */
1115     if (!unboxed)
1116         add_new_area(first_page,orig_first_page_bytes_used,nbytes);
1117
1118     /* Bump up last_free_page */
1119     if (last_page+1 > last_free_page) {
1120         last_free_page = last_page+1;
1121         SetSymbolValue(ALLOCATION_POINTER,
1122                        (lispobj)(((char *)heap_base) + last_free_page*4096));
1123         if (last_page+1 > last_used_page)
1124             last_used_page = last_page+1;
1125     }
1126
1127     return((void *)(page_address(first_page)+orig_first_page_bytes_used));
1128 }
1129
1130 /* Allocate bytes from the boxed_region. First checks whether there is
1131  * room. If not then call gc_alloc_new_region() to find a new region
1132  * with enough space. Return a pointer to the start of the region. */
1133 static void *
1134 gc_alloc(int nbytes)
1135 {
1136     void *new_free_pointer;
1137
1138     /* FSHOW((stderr, "/gc_alloc %d\n", nbytes)); */
1139
1140     /* Check whether there is room in the current alloc region. */
1141     new_free_pointer = boxed_region.free_pointer + nbytes;
1142
1143     if (new_free_pointer <= boxed_region.end_addr) {
1144         /* If so then allocate from the current alloc region. */
1145         void *new_obj = boxed_region.free_pointer;
1146         boxed_region.free_pointer = new_free_pointer;
1147
1148         /* Check whether the alloc region is almost empty. */
1149         if ((boxed_region.end_addr - boxed_region.free_pointer) <= 32) {
1150             /* If so finished with the current region. */
1151             gc_alloc_update_page_tables(0, &boxed_region);
1152             /* Set up a new region. */
1153             gc_alloc_new_region(32, 0, &boxed_region);
1154         }
1155         return((void *)new_obj);
1156     }
1157
1158     /* Else not enough free space in the current region. */
1159
1160     /* If there some room left in the current region, enough to be worth
1161      * saving, then allocate a large object. */
1162     /* FIXME: "32" should be a named parameter. */
1163     if ((boxed_region.end_addr-boxed_region.free_pointer) > 32)
1164         return gc_alloc_large(nbytes, 0, &boxed_region);
1165
1166     /* Else find a new region. */
1167
1168     /* Finished with the current region. */
1169     gc_alloc_update_page_tables(0, &boxed_region);
1170
1171     /* Set up a new region. */
1172     gc_alloc_new_region(nbytes, 0, &boxed_region);
1173
1174     /* Should now be enough room. */
1175
1176     /* Check whether there is room in the current region. */
1177     new_free_pointer = boxed_region.free_pointer + nbytes;
1178
1179     if (new_free_pointer <= boxed_region.end_addr) {
1180         /* If so then allocate from the current region. */
1181         void *new_obj = boxed_region.free_pointer;
1182         boxed_region.free_pointer = new_free_pointer;
1183
1184         /* Check whether the current region is almost empty. */
1185         if ((boxed_region.end_addr - boxed_region.free_pointer) <= 32) {
1186             /* If so find, finished with the current region. */
1187             gc_alloc_update_page_tables(0, &boxed_region);
1188
1189             /* Set up a new region. */
1190             gc_alloc_new_region(32, 0, &boxed_region);
1191         }
1192
1193         return((void *)new_obj);
1194     }
1195
1196     /* shouldn't happen */
1197     gc_assert(0);
1198     return((void *) NIL); /* dummy value: return something ... */
1199 }
1200
1201 /* Allocate space from the boxed_region. If there is not enough free
1202  * space then call gc_alloc to do the job. A pointer to the start of
1203  * the region is returned. */
1204 static inline void *
1205 gc_quick_alloc(int nbytes)
1206 {
1207     void *new_free_pointer;
1208
1209     /* Check whether there is room in the current region. */
1210     new_free_pointer = boxed_region.free_pointer + nbytes;
1211
1212     if (new_free_pointer <= boxed_region.end_addr) {
1213         /* Allocate from the current region. */
1214         void  *new_obj = boxed_region.free_pointer;
1215         boxed_region.free_pointer = new_free_pointer;
1216         return((void *)new_obj);
1217     } else {
1218         /* Let full gc_alloc() handle it. */
1219         return gc_alloc(nbytes);
1220     }
1221 }
1222
1223 /* Allocate space for the boxed object. If it is a large object then
1224  * do a large alloc else allocate from the current region. If there is
1225  * not enough free space then call gc_alloc() to do the job. A pointer
1226  * to the start of the region is returned. */
1227 static inline void *
1228 gc_quick_alloc_large(int nbytes)
1229 {
1230     void *new_free_pointer;
1231
1232     if (nbytes >= large_object_size)
1233         return gc_alloc_large(nbytes, 0, &boxed_region);
1234
1235     /* Check whether there is room in the current region. */
1236     new_free_pointer = boxed_region.free_pointer + nbytes;
1237
1238     if (new_free_pointer <= boxed_region.end_addr) {
1239         /* If so then allocate from the current region. */
1240         void *new_obj = boxed_region.free_pointer;
1241         boxed_region.free_pointer = new_free_pointer;
1242         return((void *)new_obj);
1243     } else {
1244         /* Let full gc_alloc() handle it. */
1245         return gc_alloc(nbytes);
1246     }
1247 }
1248
1249 static void *
1250 gc_alloc_unboxed(int nbytes)
1251 {
1252     void *new_free_pointer;
1253
1254     /*
1255     FSHOW((stderr, "/gc_alloc_unboxed() %d\n", nbytes));
1256     */
1257
1258     /* Check whether there is room in the current region. */
1259     new_free_pointer = unboxed_region.free_pointer + nbytes;
1260
1261     if (new_free_pointer <= unboxed_region.end_addr) {
1262         /* If so then allocate from the current region. */
1263         void *new_obj = unboxed_region.free_pointer;
1264         unboxed_region.free_pointer = new_free_pointer;
1265
1266         /* Check whether the current region is almost empty. */
1267         if ((unboxed_region.end_addr - unboxed_region.free_pointer) <= 32) {
1268             /* If so finished with the current region. */
1269             gc_alloc_update_page_tables(1, &unboxed_region);
1270
1271             /* Set up a new region. */
1272             gc_alloc_new_region(32, 1, &unboxed_region);
1273         }
1274
1275         return((void *)new_obj);
1276     }
1277
1278     /* Else not enough free space in the current region. */
1279
1280     /* If there is a bit of room left in the current region then
1281        allocate a large object. */
1282     if ((unboxed_region.end_addr-unboxed_region.free_pointer) > 32)
1283         return gc_alloc_large(nbytes,1,&unboxed_region);
1284
1285     /* Else find a new region. */
1286
1287     /* Finished with the current region. */
1288     gc_alloc_update_page_tables(1, &unboxed_region);
1289
1290     /* Set up a new region. */
1291     gc_alloc_new_region(nbytes, 1, &unboxed_region);
1292
1293     /* (There should now be enough room.) */
1294
1295     /* Check whether there is room in the current region. */
1296     new_free_pointer = unboxed_region.free_pointer + nbytes;
1297
1298     if (new_free_pointer <= unboxed_region.end_addr) {
1299         /* If so then allocate from the current region. */
1300         void *new_obj = unboxed_region.free_pointer;
1301         unboxed_region.free_pointer = new_free_pointer;
1302
1303         /* Check whether the current region is almost empty. */
1304         if ((unboxed_region.end_addr - unboxed_region.free_pointer) <= 32) {
1305             /* If so find, finished with the current region. */
1306             gc_alloc_update_page_tables(1, &unboxed_region);
1307
1308             /* Set up a new region. */
1309             gc_alloc_new_region(32, 1, &unboxed_region);
1310         }
1311
1312         return((void *)new_obj);
1313     }
1314
1315     /* shouldn't happen? */
1316     gc_assert(0);
1317     return((void *) NIL); /* dummy value: return something ... */
1318 }
1319
1320 static inline void *
1321 gc_quick_alloc_unboxed(int nbytes)
1322 {
1323     void *new_free_pointer;
1324
1325     /* Check whether there is room in the current region. */
1326     new_free_pointer = unboxed_region.free_pointer + nbytes;
1327
1328     if (new_free_pointer <= unboxed_region.end_addr) {
1329         /* If so then allocate from the current region. */
1330         void *new_obj = unboxed_region.free_pointer;
1331         unboxed_region.free_pointer = new_free_pointer;
1332
1333         return((void *)new_obj);
1334     } else {
1335         /* Let general gc_alloc_unboxed() handle it. */
1336         return gc_alloc_unboxed(nbytes);
1337     }
1338 }
1339
1340 /* Allocate space for the object. If it is a large object then do a
1341  * large alloc else allocate from the current region. If there is not
1342  * enough free space then call general gc_alloc_unboxed() to do the job.
1343  *
1344  * A pointer to the start of the region is returned. */
1345 static inline void *
1346 gc_quick_alloc_large_unboxed(int nbytes)
1347 {
1348     void *new_free_pointer;
1349
1350     if (nbytes >= large_object_size)
1351         return gc_alloc_large(nbytes,1,&unboxed_region);
1352
1353     /* Check whether there is room in the current region. */
1354     new_free_pointer = unboxed_region.free_pointer + nbytes;
1355     if (new_free_pointer <= unboxed_region.end_addr) {
1356         /* Allocate from the current region. */
1357         void *new_obj = unboxed_region.free_pointer;
1358         unboxed_region.free_pointer = new_free_pointer;
1359         return((void *)new_obj);
1360     } else {
1361         /* Let full gc_alloc() handle it. */
1362         return gc_alloc_unboxed(nbytes);
1363     }
1364 }
1365 \f
1366 /*
1367  * scavenging/transporting routines derived from gc.c in CMU CL ca. 18b
1368  */
1369
1370 static int (*scavtab[256])(lispobj *where, lispobj object);
1371 static lispobj (*transother[256])(lispobj object);
1372 static int (*sizetab[256])(lispobj *where);
1373
1374 static struct weak_pointer *weak_pointers;
1375
1376 #define CEILING(x,y) (((x) + ((y) - 1)) & (~((y) - 1)))
1377 \f
1378 /*
1379  * predicates
1380  */
1381
1382 static inline boolean
1383 from_space_p(lispobj obj)
1384 {
1385     int page_index=(void*)obj - heap_base;
1386     return ((page_index >= 0)
1387             && ((page_index = ((unsigned int)page_index)/4096) < NUM_PAGES)
1388             && (page_table[page_index].gen == from_space));
1389 }
1390
1391 static inline boolean
1392 new_space_p(lispobj obj)
1393 {
1394     int page_index = (void*)obj - heap_base;
1395     return ((page_index >= 0)
1396             && ((page_index = ((unsigned int)page_index)/4096) < NUM_PAGES)
1397             && (page_table[page_index].gen == new_space));
1398 }
1399 \f
1400 /*
1401  * copying objects
1402  */
1403
1404 /* to copy a boxed object */
1405 static inline lispobj
1406 copy_object(lispobj object, int nwords)
1407 {
1408     int tag;
1409     lispobj *new;
1410     lispobj *source, *dest;
1411
1412     gc_assert(is_lisp_pointer(object));
1413     gc_assert(from_space_p(object));
1414     gc_assert((nwords & 0x01) == 0);
1415
1416     /* Get tag of object. */
1417     tag = LowtagOf(object);
1418
1419     /* Allocate space. */
1420     new = gc_quick_alloc(nwords*4);
1421
1422     dest = new;
1423     source = (lispobj *) native_pointer(object);
1424
1425     /* Copy the object. */
1426     while (nwords > 0) {
1427         dest[0] = source[0];
1428         dest[1] = source[1];
1429         dest += 2;
1430         source += 2;
1431         nwords -= 2;
1432     }
1433
1434     /* Return Lisp pointer of new object. */
1435     return ((lispobj) new) | tag;
1436 }
1437
1438 /* to copy a large boxed object. If the object is in a large object
1439  * region then it is simply promoted, else it is copied. If it's large
1440  * enough then it's copied to a large object region.
1441  *
1442  * Vectors may have shrunk. If the object is not copied the space
1443  * needs to be reclaimed, and the page_tables corrected. */
1444 static lispobj
1445 copy_large_object(lispobj object, int nwords)
1446 {
1447     int tag;
1448     lispobj *new;
1449     lispobj *source, *dest;
1450     int first_page;
1451
1452     gc_assert(is_lisp_pointer(object));
1453     gc_assert(from_space_p(object));
1454     gc_assert((nwords & 0x01) == 0);
1455
1456     if ((nwords > 1024*1024) && gencgc_verbose) {
1457         FSHOW((stderr, "/copy_large_object: %d bytes\n", nwords*4));
1458     }
1459
1460     /* Check whether it's a large object. */
1461     first_page = find_page_index((void *)object);
1462     gc_assert(first_page >= 0);
1463
1464     if (page_table[first_page].large_object) {
1465
1466         /* Promote the object. */
1467
1468         int remaining_bytes;
1469         int next_page;
1470         int bytes_freed;
1471         int old_bytes_used;
1472
1473         /* Note: Any page write-protection must be removed, else a
1474          * later scavenge_newspace may incorrectly not scavenge these
1475          * pages. This would not be necessary if they are added to the
1476          * new areas, but let's do it for them all (they'll probably
1477          * be written anyway?). */
1478
1479         gc_assert(page_table[first_page].first_object_offset == 0);
1480
1481         next_page = first_page;
1482         remaining_bytes = nwords*4;
1483         while (remaining_bytes > 4096) {
1484             gc_assert(page_table[next_page].gen == from_space);
1485             gc_assert(page_table[next_page].allocated == BOXED_PAGE);
1486             gc_assert(page_table[next_page].large_object);
1487             gc_assert(page_table[next_page].first_object_offset==
1488                       -4096*(next_page-first_page));
1489             gc_assert(page_table[next_page].bytes_used == 4096);
1490
1491             page_table[next_page].gen = new_space;
1492
1493             /* Remove any write-protection. We should be able to rely
1494              * on the write-protect flag to avoid redundant calls. */
1495             if (page_table[next_page].write_protected) {
1496                 os_protect(page_address(next_page), 4096, OS_VM_PROT_ALL);
1497                 page_table[next_page].write_protected = 0;
1498             }
1499             remaining_bytes -= 4096;
1500             next_page++;
1501         }
1502
1503         /* Now only one page remains, but the object may have shrunk
1504          * so there may be more unused pages which will be freed. */
1505
1506         /* The object may have shrunk but shouldn't have grown. */
1507         gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1508
1509         page_table[next_page].gen = new_space;
1510         gc_assert(page_table[next_page].allocated = BOXED_PAGE);
1511
1512         /* Adjust the bytes_used. */
1513         old_bytes_used = page_table[next_page].bytes_used;
1514         page_table[next_page].bytes_used = remaining_bytes;
1515
1516         bytes_freed = old_bytes_used - remaining_bytes;
1517
1518         /* Free any remaining pages; needs care. */
1519         next_page++;
1520         while ((old_bytes_used == 4096) &&
1521                (page_table[next_page].gen == from_space) &&
1522                (page_table[next_page].allocated == BOXED_PAGE) &&
1523                page_table[next_page].large_object &&
1524                (page_table[next_page].first_object_offset ==
1525                 -(next_page - first_page)*4096)) {
1526             /* Checks out OK, free the page. Don't need to both zeroing
1527              * pages as this should have been done before shrinking the
1528              * object. These pages shouldn't be write-protected as they
1529              * should be zero filled. */
1530             gc_assert(page_table[next_page].write_protected == 0);
1531
1532             old_bytes_used = page_table[next_page].bytes_used;
1533             page_table[next_page].allocated = FREE_PAGE;
1534             page_table[next_page].bytes_used = 0;
1535             bytes_freed += old_bytes_used;
1536             next_page++;
1537         }
1538
1539         if ((bytes_freed > 0) && gencgc_verbose)
1540             FSHOW((stderr, "/copy_large_boxed bytes_freed=%d\n", bytes_freed));
1541
1542         generations[from_space].bytes_allocated -= 4*nwords + bytes_freed;
1543         generations[new_space].bytes_allocated += 4*nwords;
1544         bytes_allocated -= bytes_freed;
1545
1546         /* Add the region to the new_areas if requested. */
1547         add_new_area(first_page,0,nwords*4);
1548
1549         return(object);
1550     } else {
1551         /* Get tag of object. */
1552         tag = LowtagOf(object);
1553
1554         /* Allocate space. */
1555         new = gc_quick_alloc_large(nwords*4);
1556
1557         dest = new;
1558         source = (lispobj *) native_pointer(object);
1559
1560         /* Copy the object. */
1561         while (nwords > 0) {
1562             dest[0] = source[0];
1563             dest[1] = source[1];
1564             dest += 2;
1565             source += 2;
1566             nwords -= 2;
1567         }
1568
1569         /* Return Lisp pointer of new object. */
1570         return ((lispobj) new) | tag;
1571     }
1572 }
1573
1574 /* to copy unboxed objects */
1575 static inline lispobj
1576 copy_unboxed_object(lispobj object, int nwords)
1577 {
1578     int tag;
1579     lispobj *new;
1580     lispobj *source, *dest;
1581
1582     gc_assert(is_lisp_pointer(object));
1583     gc_assert(from_space_p(object));
1584     gc_assert((nwords & 0x01) == 0);
1585
1586     /* Get tag of object. */
1587     tag = LowtagOf(object);
1588
1589     /* Allocate space. */
1590     new = gc_quick_alloc_unboxed(nwords*4);
1591
1592     dest = new;
1593     source = (lispobj *) native_pointer(object);
1594
1595     /* Copy the object. */
1596     while (nwords > 0) {
1597         dest[0] = source[0];
1598         dest[1] = source[1];
1599         dest += 2;
1600         source += 2;
1601         nwords -= 2;
1602     }
1603
1604     /* Return Lisp pointer of new object. */
1605     return ((lispobj) new) | tag;
1606 }
1607
1608 /* to copy large unboxed objects
1609  *
1610  * If the object is in a large object region then it is simply
1611  * promoted, else it is copied. If it's large enough then it's copied
1612  * to a large object region.
1613  *
1614  * Bignums and vectors may have shrunk. If the object is not copied
1615  * the space needs to be reclaimed, and the page_tables corrected.
1616  *
1617  * KLUDGE: There's a lot of cut-and-paste duplication between this
1618  * function and copy_large_object(..). -- WHN 20000619 */
1619 static lispobj
1620 copy_large_unboxed_object(lispobj object, int nwords)
1621 {
1622     int tag;
1623     lispobj *new;
1624     lispobj *source, *dest;
1625     int first_page;
1626
1627     gc_assert(is_lisp_pointer(object));
1628     gc_assert(from_space_p(object));
1629     gc_assert((nwords & 0x01) == 0);
1630
1631     if ((nwords > 1024*1024) && gencgc_verbose)
1632         FSHOW((stderr, "/copy_large_unboxed_object: %d bytes\n", nwords*4));
1633
1634     /* Check whether it's a large object. */
1635     first_page = find_page_index((void *)object);
1636     gc_assert(first_page >= 0);
1637
1638     if (page_table[first_page].large_object) {
1639         /* Promote the object. Note: Unboxed objects may have been
1640          * allocated to a BOXED region so it may be necessary to
1641          * change the region to UNBOXED. */
1642         int remaining_bytes;
1643         int next_page;
1644         int bytes_freed;
1645         int old_bytes_used;
1646
1647         gc_assert(page_table[first_page].first_object_offset == 0);
1648
1649         next_page = first_page;
1650         remaining_bytes = nwords*4;
1651         while (remaining_bytes > 4096) {
1652             gc_assert(page_table[next_page].gen == from_space);
1653             gc_assert((page_table[next_page].allocated == UNBOXED_PAGE)
1654                       || (page_table[next_page].allocated == BOXED_PAGE));
1655             gc_assert(page_table[next_page].large_object);
1656             gc_assert(page_table[next_page].first_object_offset==
1657                       -4096*(next_page-first_page));
1658             gc_assert(page_table[next_page].bytes_used == 4096);
1659
1660             page_table[next_page].gen = new_space;
1661             page_table[next_page].allocated = UNBOXED_PAGE;
1662             remaining_bytes -= 4096;
1663             next_page++;
1664         }
1665
1666         /* Now only one page remains, but the object may have shrunk so
1667          * there may be more unused pages which will be freed. */
1668
1669         /* Object may have shrunk but shouldn't have grown - check. */
1670         gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
1671
1672         page_table[next_page].gen = new_space;
1673         page_table[next_page].allocated = UNBOXED_PAGE;
1674
1675         /* Adjust the bytes_used. */
1676         old_bytes_used = page_table[next_page].bytes_used;
1677         page_table[next_page].bytes_used = remaining_bytes;
1678
1679         bytes_freed = old_bytes_used - remaining_bytes;
1680
1681         /* Free any remaining pages; needs care. */
1682         next_page++;
1683         while ((old_bytes_used == 4096) &&
1684                (page_table[next_page].gen == from_space) &&
1685                ((page_table[next_page].allocated == UNBOXED_PAGE)
1686                 || (page_table[next_page].allocated == BOXED_PAGE)) &&
1687                page_table[next_page].large_object &&
1688                (page_table[next_page].first_object_offset ==
1689                 -(next_page - first_page)*4096)) {
1690             /* Checks out OK, free the page. Don't need to both zeroing
1691              * pages as this should have been done before shrinking the
1692              * object. These pages shouldn't be write-protected, even if
1693              * boxed they should be zero filled. */
1694             gc_assert(page_table[next_page].write_protected == 0);
1695
1696             old_bytes_used = page_table[next_page].bytes_used;
1697             page_table[next_page].allocated = FREE_PAGE;
1698             page_table[next_page].bytes_used = 0;
1699             bytes_freed += old_bytes_used;
1700             next_page++;
1701         }
1702
1703         if ((bytes_freed > 0) && gencgc_verbose)
1704             FSHOW((stderr,
1705                    "/copy_large_unboxed bytes_freed=%d\n",
1706                    bytes_freed));
1707
1708         generations[from_space].bytes_allocated -= 4*nwords + bytes_freed;
1709         generations[new_space].bytes_allocated += 4*nwords;
1710         bytes_allocated -= bytes_freed;
1711
1712         return(object);
1713     }
1714     else {
1715         /* Get tag of object. */
1716         tag = LowtagOf(object);
1717
1718         /* Allocate space. */
1719         new = gc_quick_alloc_large_unboxed(nwords*4);
1720
1721         dest = new;
1722         source = (lispobj *) native_pointer(object);
1723
1724         /* Copy the object. */
1725         while (nwords > 0) {
1726             dest[0] = source[0];
1727             dest[1] = source[1];
1728             dest += 2;
1729             source += 2;
1730             nwords -= 2;
1731         }
1732
1733         /* Return Lisp pointer of new object. */
1734         return ((lispobj) new) | tag;
1735     }
1736 }
1737 \f
1738 /*
1739  * scavenging
1740  */
1741
1742 /* FIXME: Most calls end up going to some trouble to compute an
1743  * 'n_words' value for this function. The system might be a little
1744  * simpler if this function used an 'end' parameter instead. */
1745 static void
1746 scavenge(lispobj *start, long n_words)
1747 {
1748     lispobj *end = start + n_words;
1749     lispobj *object_ptr;
1750     int n_words_scavenged;
1751     
1752     for (object_ptr = start;
1753          object_ptr < end;
1754          object_ptr += n_words_scavenged) {
1755
1756         lispobj object = *object_ptr;
1757         
1758         gc_assert(object != 0x01); /* not a forwarding pointer */
1759
1760         if (is_lisp_pointer(object)) {
1761             if (from_space_p(object)) {
1762                 /* It currently points to old space. Check for a
1763                  * forwarding pointer. */
1764                 lispobj *ptr = (lispobj *)native_pointer(object);
1765                 lispobj first_word = *ptr;
1766                 if (first_word == 0x01) {
1767                     /* Yes, there's a forwarding pointer. */
1768                     *object_ptr = ptr[1];
1769                     n_words_scavenged = 1;
1770                 } else {
1771                     /* Scavenge that pointer. */
1772                     n_words_scavenged =
1773                         (scavtab[TypeOf(object)])(object_ptr, object);
1774                 }
1775             } else {
1776                 /* It points somewhere other than oldspace. Leave it
1777                  * alone. */
1778                 n_words_scavenged = 1;
1779             }
1780         } else if ((object & 3) == 0) {
1781             /* It's a fixnum: really easy.. */
1782             n_words_scavenged = 1;
1783         } else {
1784             /* It's some sort of header object or another. */
1785             n_words_scavenged =
1786                 (scavtab[TypeOf(object)])(object_ptr, object);
1787         }
1788     }
1789     gc_assert(object_ptr == end);
1790 }
1791 \f
1792 /*
1793  * code and code-related objects
1794  */
1795
1796 #define RAW_ADDR_OFFSET (6*sizeof(lispobj) - type_FunctionPointer)
1797
1798 static lispobj trans_function_header(lispobj object);
1799 static lispobj trans_boxed(lispobj object);
1800
1801 static int
1802 scav_function_pointer(lispobj *where, lispobj object)
1803 {
1804     lispobj *first_pointer;
1805     lispobj copy;
1806
1807     gc_assert(is_lisp_pointer(object));
1808
1809     /* Object is a pointer into from space - no a FP. */
1810     first_pointer = (lispobj *) native_pointer(object);
1811
1812     /* must transport object -- object may point to either a function
1813      * header, a closure function header, or to a closure header. */
1814
1815     switch (TypeOf(*first_pointer)) {
1816     case type_FunctionHeader:
1817     case type_ClosureFunctionHeader:
1818         copy = trans_function_header(object);
1819         break;
1820     default:
1821         copy = trans_boxed(object);
1822         break;
1823     }
1824
1825     if (copy != object) {
1826         /* Set forwarding pointer */
1827         first_pointer[0] = 0x01;
1828         first_pointer[1] = copy;
1829     }
1830
1831     gc_assert(is_lisp_pointer(copy));
1832     gc_assert(!from_space_p(copy));
1833
1834     *where = copy;
1835
1836     return 1;
1837 }
1838
1839 /* Scan a x86 compiled code object, looking for possible fixups that
1840  * have been missed after a move.
1841  *
1842  * Two types of fixups are needed:
1843  * 1. Absolute fixups to within the code object.
1844  * 2. Relative fixups to outside the code object.
1845  *
1846  * Currently only absolute fixups to the constant vector, or to the
1847  * code area are checked. */
1848 void
1849 sniff_code_object(struct code *code, unsigned displacement)
1850 {
1851     int nheader_words, ncode_words, nwords;
1852     void *p;
1853     void *constants_start_addr, *constants_end_addr;
1854     void *code_start_addr, *code_end_addr;
1855     int fixup_found = 0;
1856
1857     if (!check_code_fixups)
1858         return;
1859
1860     ncode_words = fixnum_value(code->code_size);
1861     nheader_words = HeaderValue(*(lispobj *)code);
1862     nwords = ncode_words + nheader_words;
1863
1864     constants_start_addr = (void *)code + 5*4;
1865     constants_end_addr = (void *)code + nheader_words*4;
1866     code_start_addr = (void *)code + nheader_words*4;
1867     code_end_addr = (void *)code + nwords*4;
1868
1869     /* Work through the unboxed code. */
1870     for (p = code_start_addr; p < code_end_addr; p++) {
1871         void *data = *(void **)p;
1872         unsigned d1 = *((unsigned char *)p - 1);
1873         unsigned d2 = *((unsigned char *)p - 2);
1874         unsigned d3 = *((unsigned char *)p - 3);
1875         unsigned d4 = *((unsigned char *)p - 4);
1876 #if QSHOW
1877         unsigned d5 = *((unsigned char *)p - 5);
1878         unsigned d6 = *((unsigned char *)p - 6);
1879 #endif
1880
1881         /* Check for code references. */
1882         /* Check for a 32 bit word that looks like an absolute
1883            reference to within the code adea of the code object. */
1884         if ((data >= (code_start_addr-displacement))
1885             && (data < (code_end_addr-displacement))) {
1886             /* function header */
1887             if ((d4 == 0x5e)
1888                 && (((unsigned)p - 4 - 4*HeaderValue(*((unsigned *)p-1))) == (unsigned)code)) {
1889                 /* Skip the function header */
1890                 p += 6*4 - 4 - 1;
1891                 continue;
1892             }
1893             /* the case of PUSH imm32 */
1894             if (d1 == 0x68) {
1895                 fixup_found = 1;
1896                 FSHOW((stderr,
1897                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1898                        p, d6, d5, d4, d3, d2, d1, data));
1899                 FSHOW((stderr, "/PUSH $0x%.8x\n", data));
1900             }
1901             /* the case of MOV [reg-8],imm32 */
1902             if ((d3 == 0xc7)
1903                 && (d2==0x40 || d2==0x41 || d2==0x42 || d2==0x43
1904                     || d2==0x45 || d2==0x46 || d2==0x47)
1905                 && (d1 == 0xf8)) {
1906                 fixup_found = 1;
1907                 FSHOW((stderr,
1908                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1909                        p, d6, d5, d4, d3, d2, d1, data));
1910                 FSHOW((stderr, "/MOV [reg-8],$0x%.8x\n", data));
1911             }
1912             /* the case of LEA reg,[disp32] */
1913             if ((d2 == 0x8d) && ((d1 & 0xc7) == 5)) {
1914                 fixup_found = 1;
1915                 FSHOW((stderr,
1916                        "/code ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1917                        p, d6, d5, d4, d3, d2, d1, data));
1918                 FSHOW((stderr,"/LEA reg,[$0x%.8x]\n", data));
1919             }
1920         }
1921
1922         /* Check for constant references. */
1923         /* Check for a 32 bit word that looks like an absolute
1924            reference to within the constant vector. Constant references
1925            will be aligned. */
1926         if ((data >= (constants_start_addr-displacement))
1927             && (data < (constants_end_addr-displacement))
1928             && (((unsigned)data & 0x3) == 0)) {
1929             /*  Mov eax,m32 */
1930             if (d1 == 0xa1) {
1931                 fixup_found = 1;
1932                 FSHOW((stderr,
1933                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1934                        p, d6, d5, d4, d3, d2, d1, data));
1935                 FSHOW((stderr,"/MOV eax,0x%.8x\n", data));
1936             }
1937
1938             /*  the case of MOV m32,EAX */
1939             if (d1 == 0xa3) {
1940                 fixup_found = 1;
1941                 FSHOW((stderr,
1942                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1943                        p, d6, d5, d4, d3, d2, d1, data));
1944                 FSHOW((stderr, "/MOV 0x%.8x,eax\n", data));
1945             }
1946
1947             /* the case of CMP m32,imm32 */             
1948             if ((d1 == 0x3d) && (d2 == 0x81)) {
1949                 fixup_found = 1;
1950                 FSHOW((stderr,
1951                        "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1952                        p, d6, d5, d4, d3, d2, d1, data));
1953                 /* XX Check this */
1954                 FSHOW((stderr, "/CMP 0x%.8x,immed32\n", data));
1955             }
1956
1957             /* Check for a mod=00, r/m=101 byte. */
1958             if ((d1 & 0xc7) == 5) {
1959                 /* Cmp m32,reg */
1960                 if (d2 == 0x39) {
1961                     fixup_found = 1;
1962                     FSHOW((stderr,
1963                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1964                            p, d6, d5, d4, d3, d2, d1, data));
1965                     FSHOW((stderr,"/CMP 0x%.8x,reg\n", data));
1966                 }
1967                 /* the case of CMP reg32,m32 */
1968                 if (d2 == 0x3b) {
1969                     fixup_found = 1;
1970                     FSHOW((stderr,
1971                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1972                            p, d6, d5, d4, d3, d2, d1, data));
1973                     FSHOW((stderr, "/CMP reg32,0x%.8x\n", data));
1974                 }
1975                 /* the case of MOV m32,reg32 */
1976                 if (d2 == 0x89) {
1977                     fixup_found = 1;
1978                     FSHOW((stderr,
1979                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1980                            p, d6, d5, d4, d3, d2, d1, data));
1981                     FSHOW((stderr, "/MOV 0x%.8x,reg32\n", data));
1982                 }
1983                 /* the case of MOV reg32,m32 */
1984                 if (d2 == 0x8b) {
1985                     fixup_found = 1;
1986                     FSHOW((stderr,
1987                            "/abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1988                            p, d6, d5, d4, d3, d2, d1, data));
1989                     FSHOW((stderr, "/MOV reg32,0x%.8x\n", data));
1990                 }
1991                 /* the case of LEA reg32,m32 */
1992                 if (d2 == 0x8d) {
1993                     fixup_found = 1;
1994                     FSHOW((stderr,
1995                            "abs const ref @%x: %.2x %.2x %.2x %.2x %.2x %.2x (%.8x)\n",
1996                            p, d6, d5, d4, d3, d2, d1, data));
1997                     FSHOW((stderr, "/LEA reg32,0x%.8x\n", data));
1998                 }
1999             }
2000         }
2001     }
2002
2003     /* If anything was found, print some information on the code
2004      * object. */
2005     if (fixup_found) {
2006         FSHOW((stderr,
2007                "/compiled code object at %x: header words = %d, code words = %d\n",
2008                code, nheader_words, ncode_words));
2009         FSHOW((stderr,
2010                "/const start = %x, end = %x\n",
2011                constants_start_addr, constants_end_addr));
2012         FSHOW((stderr,
2013                "/code start = %x, end = %x\n",
2014                code_start_addr, code_end_addr));
2015     }
2016 }
2017
2018 static void
2019 apply_code_fixups(struct code *old_code, struct code *new_code)
2020 {
2021     int nheader_words, ncode_words, nwords;
2022     void *constants_start_addr, *constants_end_addr;
2023     void *code_start_addr, *code_end_addr;
2024     lispobj fixups = NIL;
2025     unsigned displacement = (unsigned)new_code - (unsigned)old_code;
2026     struct vector *fixups_vector;
2027
2028     ncode_words = fixnum_value(new_code->code_size);
2029     nheader_words = HeaderValue(*(lispobj *)new_code);
2030     nwords = ncode_words + nheader_words;
2031     /* FSHOW((stderr,
2032              "/compiled code object at %x: header words = %d, code words = %d\n",
2033              new_code, nheader_words, ncode_words)); */
2034     constants_start_addr = (void *)new_code + 5*4;
2035     constants_end_addr = (void *)new_code + nheader_words*4;
2036     code_start_addr = (void *)new_code + nheader_words*4;
2037     code_end_addr = (void *)new_code + nwords*4;
2038     /*
2039     FSHOW((stderr,
2040            "/const start = %x, end = %x\n",
2041            constants_start_addr,constants_end_addr));
2042     FSHOW((stderr,
2043            "/code start = %x; end = %x\n",
2044            code_start_addr,code_end_addr));
2045     */
2046
2047     /* The first constant should be a pointer to the fixups for this
2048        code objects. Check. */
2049     fixups = new_code->constants[0];
2050
2051     /* It will be 0 or the unbound-marker if there are no fixups, and
2052      * will be an other pointer if it is valid. */
2053     if ((fixups == 0) || (fixups == type_UnboundMarker) ||
2054         !is_lisp_pointer(fixups)) {
2055         /* Check for possible errors. */
2056         if (check_code_fixups)
2057             sniff_code_object(new_code, displacement);
2058
2059         /*fprintf(stderr,"Fixups for code object not found!?\n");
2060           fprintf(stderr,"*** Compiled code object at %x: header_words=%d code_words=%d .\n",
2061           new_code, nheader_words, ncode_words);
2062           fprintf(stderr,"*** Const. start = %x; end= %x; Code start = %x; end = %x\n",
2063           constants_start_addr,constants_end_addr,
2064           code_start_addr,code_end_addr);*/
2065         return;
2066     }
2067
2068     fixups_vector = (struct vector *)native_pointer(fixups);
2069
2070     /* Could be pointing to a forwarding pointer. */
2071     if (is_lisp_pointer(fixups) &&
2072         (find_page_index((void*)fixups_vector) != -1) &&
2073         (fixups_vector->header == 0x01)) {
2074         /* If so, then follow it. */
2075         /*SHOW("following pointer to a forwarding pointer");*/
2076         fixups_vector = (struct vector *)native_pointer((lispobj)fixups_vector->length);
2077     }
2078
2079     /*SHOW("got fixups");*/
2080
2081     if (TypeOf(fixups_vector->header) == type_SimpleArrayUnsignedByte32) {
2082         /* Got the fixups for the code block. Now work through the vector,
2083            and apply a fixup at each address. */
2084         int length = fixnum_value(fixups_vector->length);
2085         int i;
2086         for (i = 0; i < length; i++) {
2087             unsigned offset = fixups_vector->data[i];
2088             /* Now check the current value of offset. */
2089             unsigned old_value =
2090                 *(unsigned *)((unsigned)code_start_addr + offset);
2091
2092             /* If it's within the old_code object then it must be an
2093              * absolute fixup (relative ones are not saved) */
2094             if ((old_value >= (unsigned)old_code)
2095                 && (old_value < ((unsigned)old_code + nwords*4)))
2096                 /* So add the dispacement. */
2097                 *(unsigned *)((unsigned)code_start_addr + offset) =
2098                     old_value + displacement;
2099             else
2100                 /* It is outside the old code object so it must be a
2101                  * relative fixup (absolute fixups are not saved). So
2102                  * subtract the displacement. */
2103                 *(unsigned *)((unsigned)code_start_addr + offset) =
2104                     old_value - displacement;
2105         }
2106     }
2107
2108     /* Check for possible errors. */
2109     if (check_code_fixups) {
2110         sniff_code_object(new_code,displacement);
2111     }
2112 }
2113
2114 static struct code *
2115 trans_code(struct code *code)
2116 {
2117     struct code *new_code;
2118     lispobj l_code, l_new_code;
2119     int nheader_words, ncode_words, nwords;
2120     unsigned long displacement;
2121     lispobj fheaderl, *prev_pointer;
2122
2123     /* FSHOW((stderr,
2124              "\n/transporting code object located at 0x%08x\n",
2125              (unsigned long) code)); */
2126
2127     /* If object has already been transported, just return pointer. */
2128     if (*((lispobj *)code) == 0x01)
2129         return (struct code*)(((lispobj *)code)[1]);
2130
2131     gc_assert(TypeOf(code->header) == type_CodeHeader);
2132
2133     /* Prepare to transport the code vector. */
2134     l_code = (lispobj) code | type_OtherPointer;
2135
2136     ncode_words = fixnum_value(code->code_size);
2137     nheader_words = HeaderValue(code->header);
2138     nwords = ncode_words + nheader_words;
2139     nwords = CEILING(nwords, 2);
2140
2141     l_new_code = copy_large_object(l_code, nwords);
2142     new_code = (struct code *) native_pointer(l_new_code);
2143
2144     /* may not have been moved.. */
2145     if (new_code == code)
2146         return new_code;
2147
2148     displacement = l_new_code - l_code;
2149
2150     /*
2151     FSHOW((stderr,
2152            "/old code object at 0x%08x, new code object at 0x%08x\n",
2153            (unsigned long) code,
2154            (unsigned long) new_code));
2155     FSHOW((stderr, "/Code object is %d words long.\n", nwords));
2156     */
2157
2158     /* Set forwarding pointer. */
2159     ((lispobj *)code)[0] = 0x01;
2160     ((lispobj *)code)[1] = l_new_code;
2161
2162     /* Set forwarding pointers for all the function headers in the
2163      * code object. Also fix all self pointers. */
2164
2165     fheaderl = code->entry_points;
2166     prev_pointer = &new_code->entry_points;
2167
2168     while (fheaderl != NIL) {
2169         struct function *fheaderp, *nfheaderp;
2170         lispobj nfheaderl;
2171
2172         fheaderp = (struct function *) native_pointer(fheaderl);
2173         gc_assert(TypeOf(fheaderp->header) == type_FunctionHeader);
2174
2175         /* Calculate the new function pointer and the new */
2176         /* function header. */
2177         nfheaderl = fheaderl + displacement;
2178         nfheaderp = (struct function *) native_pointer(nfheaderl);
2179
2180         /* Set forwarding pointer. */
2181         ((lispobj *)fheaderp)[0] = 0x01;
2182         ((lispobj *)fheaderp)[1] = nfheaderl;
2183
2184         /* Fix self pointer. */
2185         nfheaderp->self = nfheaderl + RAW_ADDR_OFFSET;
2186
2187         *prev_pointer = nfheaderl;
2188
2189         fheaderl = fheaderp->next;
2190         prev_pointer = &nfheaderp->next;
2191     }
2192
2193     /*  sniff_code_object(new_code,displacement);*/
2194     apply_code_fixups(code,new_code);
2195
2196     return new_code;
2197 }
2198
2199 static int
2200 scav_code_header(lispobj *where, lispobj object)
2201 {
2202     struct code *code;
2203     int n_header_words, n_code_words, n_words;
2204     lispobj entry_point;        /* tagged pointer to entry point */
2205     struct function *function_ptr; /* untagged pointer to entry point */
2206
2207     code = (struct code *) where;
2208     n_code_words = fixnum_value(code->code_size);
2209     n_header_words = HeaderValue(object);
2210     n_words = n_code_words + n_header_words;
2211     n_words = CEILING(n_words, 2);
2212
2213     /* Scavenge the boxed section of the code data block. */
2214     scavenge(where + 1, n_header_words - 1);
2215
2216     /* Scavenge the boxed section of each function object in the */
2217     /* code data block. */
2218     for (entry_point = code->entry_points;
2219          entry_point != NIL;
2220          entry_point = function_ptr->next) {
2221
2222         gc_assert(is_lisp_pointer(entry_point));
2223
2224         function_ptr = (struct function *) native_pointer(entry_point);
2225         gc_assert(TypeOf(function_ptr->header) == type_FunctionHeader);
2226
2227         scavenge(&function_ptr->name, 1);
2228         scavenge(&function_ptr->arglist, 1);
2229         scavenge(&function_ptr->type, 1);
2230     }
2231         
2232     return n_words;
2233 }
2234
2235 static lispobj
2236 trans_code_header(lispobj object)
2237 {
2238     struct code *ncode;
2239
2240     ncode = trans_code((struct code *) native_pointer(object));
2241     return (lispobj) ncode | type_OtherPointer;
2242 }
2243
2244 static int
2245 size_code_header(lispobj *where)
2246 {
2247     struct code *code;
2248     int nheader_words, ncode_words, nwords;
2249
2250     code = (struct code *) where;
2251         
2252     ncode_words = fixnum_value(code->code_size);
2253     nheader_words = HeaderValue(code->header);
2254     nwords = ncode_words + nheader_words;
2255     nwords = CEILING(nwords, 2);
2256
2257     return nwords;
2258 }
2259
2260 static int
2261 scav_return_pc_header(lispobj *where, lispobj object)
2262 {
2263     lose("attempted to scavenge a return PC header where=0x%08x object=0x%08x",
2264          (unsigned long) where,
2265          (unsigned long) object);
2266     return 0; /* bogus return value to satisfy static type checking */
2267 }
2268
2269 static lispobj
2270 trans_return_pc_header(lispobj object)
2271 {
2272     struct function *return_pc;
2273     unsigned long offset;
2274     struct code *code, *ncode;
2275
2276     SHOW("/trans_return_pc_header: Will this work?");
2277
2278     return_pc = (struct function *) native_pointer(object);
2279     offset = HeaderValue(return_pc->header) * 4;
2280
2281     /* Transport the whole code object. */
2282     code = (struct code *) ((unsigned long) return_pc - offset);
2283     ncode = trans_code(code);
2284
2285     return ((lispobj) ncode + offset) | type_OtherPointer;
2286 }
2287
2288 /* On the 386, closures hold a pointer to the raw address instead of the
2289  * function object. */
2290 #ifdef __i386__
2291 static int
2292 scav_closure_header(lispobj *where, lispobj object)
2293 {
2294     struct closure *closure;
2295     lispobj fun;
2296
2297     closure = (struct closure *)where;
2298     fun = closure->function - RAW_ADDR_OFFSET;
2299     scavenge(&fun, 1);
2300     /* The function may have moved so update the raw address. But
2301      * don't write unnecessarily. */
2302     if (closure->function != fun + RAW_ADDR_OFFSET)
2303         closure->function = fun + RAW_ADDR_OFFSET;
2304
2305     return 2;
2306 }
2307 #endif
2308
2309 static int
2310 scav_function_header(lispobj *where, lispobj object)
2311 {
2312     lose("attempted to scavenge a function header where=0x%08x object=0x%08x",
2313          (unsigned long) where,
2314          (unsigned long) object);
2315     return 0; /* bogus return value to satisfy static type checking */
2316 }
2317
2318 static lispobj
2319 trans_function_header(lispobj object)
2320 {
2321     struct function *fheader;
2322     unsigned long offset;
2323     struct code *code, *ncode;
2324
2325     fheader = (struct function *) native_pointer(object);
2326     offset = HeaderValue(fheader->header) * 4;
2327
2328     /* Transport the whole code object. */
2329     code = (struct code *) ((unsigned long) fheader - offset);
2330     ncode = trans_code(code);
2331
2332     return ((lispobj) ncode + offset) | type_FunctionPointer;
2333 }
2334 \f
2335 /*
2336  * instances
2337  */
2338
2339 static int
2340 scav_instance_pointer(lispobj *where, lispobj object)
2341 {
2342     lispobj copy, *first_pointer;
2343
2344     /* Object is a pointer into from space - not a FP. */
2345     copy = trans_boxed(object);
2346
2347     gc_assert(copy != object);
2348
2349     first_pointer = (lispobj *) native_pointer(object);
2350
2351     /* Set forwarding pointer. */
2352     first_pointer[0] = 0x01;
2353     first_pointer[1] = copy;
2354     *where = copy;
2355
2356     return 1;
2357 }
2358 \f
2359 /*
2360  * lists and conses
2361  */
2362
2363 static lispobj trans_list(lispobj object);
2364
2365 static int
2366 scav_list_pointer(lispobj *where, lispobj object)
2367 {
2368     lispobj first, *first_pointer;
2369
2370     gc_assert(is_lisp_pointer(object));
2371
2372     /* Object is a pointer into from space - not FP. */
2373
2374     first = trans_list(object);
2375     gc_assert(first != object);
2376
2377     first_pointer = (lispobj *) native_pointer(object);
2378
2379     /* Set forwarding pointer */
2380     first_pointer[0] = 0x01;
2381     first_pointer[1] = first;
2382
2383     gc_assert(is_lisp_pointer(first));
2384     gc_assert(!from_space_p(first));
2385     *where = first;
2386     return 1;
2387 }
2388
2389 static lispobj
2390 trans_list(lispobj object)
2391 {
2392     lispobj new_list_pointer;
2393     struct cons *cons, *new_cons;
2394     lispobj cdr;
2395
2396     gc_assert(from_space_p(object));
2397
2398     cons = (struct cons *) native_pointer(object);
2399
2400     /* Copy 'object'. */
2401     new_cons = (struct cons *) gc_quick_alloc(sizeof(struct cons));
2402     new_cons->car = cons->car;
2403     new_cons->cdr = cons->cdr; /* updated later */
2404     new_list_pointer = (lispobj)new_cons | LowtagOf(object);
2405
2406     /* Grab the cdr before it is clobbered. */
2407     cdr = cons->cdr;
2408
2409     /* Set forwarding pointer (clobbers start of list). */
2410     cons->car = 0x01;
2411     cons->cdr = new_list_pointer;
2412
2413     /* Try to linearize the list in the cdr direction to help reduce
2414      * paging. */
2415     while (1) {
2416         lispobj  new_cdr;
2417         struct cons *cdr_cons, *new_cdr_cons;
2418
2419         if (LowtagOf(cdr) != type_ListPointer || !from_space_p(cdr)
2420             || (*((lispobj *)native_pointer(cdr)) == 0x01))
2421             break;
2422
2423         cdr_cons = (struct cons *) native_pointer(cdr);
2424
2425         /* Copy 'cdr'. */
2426         new_cdr_cons = (struct cons*) gc_quick_alloc(sizeof(struct cons));
2427         new_cdr_cons->car = cdr_cons->car;
2428         new_cdr_cons->cdr = cdr_cons->cdr;
2429         new_cdr = (lispobj)new_cdr_cons | LowtagOf(cdr);
2430
2431         /* Grab the cdr before it is clobbered. */
2432         cdr = cdr_cons->cdr;
2433
2434         /* Set forwarding pointer. */
2435         cdr_cons->car = 0x01;
2436         cdr_cons->cdr = new_cdr;
2437
2438         /* Update the cdr of the last cons copied into new space to
2439          * keep the newspace scavenge from having to do it. */
2440         new_cons->cdr = new_cdr;
2441
2442         new_cons = new_cdr_cons;
2443     }
2444
2445     return new_list_pointer;
2446 }
2447
2448 \f
2449 /*
2450  * scavenging and transporting other pointers
2451  */
2452
2453 static int
2454 scav_other_pointer(lispobj *where, lispobj object)
2455 {
2456     lispobj first, *first_pointer;
2457
2458     gc_assert(is_lisp_pointer(object));
2459
2460     /* Object is a pointer into from space - not FP. */
2461     first_pointer = (lispobj *) native_pointer(object);
2462
2463     first = (transother[TypeOf(*first_pointer)])(object);
2464
2465     if (first != object) {
2466         /* Set forwarding pointer. */
2467         first_pointer[0] = 0x01;
2468         first_pointer[1] = first;
2469         *where = first;
2470     }
2471
2472     gc_assert(is_lisp_pointer(first));
2473     gc_assert(!from_space_p(first));
2474
2475     return 1;
2476 }
2477 \f
2478 /*
2479  * immediate, boxed, and unboxed objects
2480  */
2481
2482 static int
2483 size_pointer(lispobj *where)
2484 {
2485     return 1;
2486 }
2487
2488 static int
2489 scav_immediate(lispobj *where, lispobj object)
2490 {
2491     return 1;
2492 }
2493
2494 static lispobj
2495 trans_immediate(lispobj object)
2496 {
2497     lose("trying to transport an immediate");
2498     return NIL; /* bogus return value to satisfy static type checking */
2499 }
2500
2501 static int
2502 size_immediate(lispobj *where)
2503 {
2504     return 1;
2505 }
2506
2507
2508 static int
2509 scav_boxed(lispobj *where, lispobj object)
2510 {
2511     return 1;
2512 }
2513
2514 static lispobj
2515 trans_boxed(lispobj object)
2516 {
2517     lispobj header;
2518     unsigned long length;
2519
2520     gc_assert(is_lisp_pointer(object));
2521
2522     header = *((lispobj *) native_pointer(object));
2523     length = HeaderValue(header) + 1;
2524     length = CEILING(length, 2);
2525
2526     return copy_object(object, length);
2527 }
2528
2529 static lispobj
2530 trans_boxed_large(lispobj object)
2531 {
2532     lispobj header;
2533     unsigned long length;
2534
2535     gc_assert(is_lisp_pointer(object));
2536
2537     header = *((lispobj *) native_pointer(object));
2538     length = HeaderValue(header) + 1;
2539     length = CEILING(length, 2);
2540
2541     return copy_large_object(object, length);
2542 }
2543
2544 static int
2545 size_boxed(lispobj *where)
2546 {
2547     lispobj header;
2548     unsigned long length;
2549
2550     header = *where;
2551     length = HeaderValue(header) + 1;
2552     length = CEILING(length, 2);
2553
2554     return length;
2555 }
2556
2557 static int
2558 scav_fdefn(lispobj *where, lispobj object)
2559 {
2560     struct fdefn *fdefn;
2561
2562     fdefn = (struct fdefn *)where;
2563
2564     /* FSHOW((stderr, "scav_fdefn, function = %p, raw_addr = %p\n", 
2565        fdefn->function, fdefn->raw_addr)); */
2566
2567     if ((char *)(fdefn->function + RAW_ADDR_OFFSET) == fdefn->raw_addr) {
2568         scavenge(where + 1, sizeof(struct fdefn)/sizeof(lispobj) - 1);
2569
2570         /* Don't write unnecessarily. */
2571         if (fdefn->raw_addr != (char *)(fdefn->function + RAW_ADDR_OFFSET))
2572             fdefn->raw_addr = (char *)(fdefn->function + RAW_ADDR_OFFSET);
2573
2574         return sizeof(struct fdefn) / sizeof(lispobj);
2575     } else {
2576         return 1;
2577     }
2578 }
2579
2580 static int
2581 scav_unboxed(lispobj *where, lispobj object)
2582 {
2583     unsigned long length;
2584
2585     length = HeaderValue(object) + 1;
2586     length = CEILING(length, 2);
2587
2588     return length;
2589 }
2590
2591 static lispobj
2592 trans_unboxed(lispobj object)
2593 {
2594     lispobj header;
2595     unsigned long length;
2596
2597
2598     gc_assert(is_lisp_pointer(object));
2599
2600     header = *((lispobj *) native_pointer(object));
2601     length = HeaderValue(header) + 1;
2602     length = CEILING(length, 2);
2603
2604     return copy_unboxed_object(object, length);
2605 }
2606
2607 static lispobj
2608 trans_unboxed_large(lispobj object)
2609 {
2610     lispobj header;
2611     unsigned long length;
2612
2613
2614     gc_assert(is_lisp_pointer(object));
2615
2616     header = *((lispobj *) native_pointer(object));
2617     length = HeaderValue(header) + 1;
2618     length = CEILING(length, 2);
2619
2620     return copy_large_unboxed_object(object, length);
2621 }
2622
2623 static int
2624 size_unboxed(lispobj *where)
2625 {
2626     lispobj header;
2627     unsigned long length;
2628
2629     header = *where;
2630     length = HeaderValue(header) + 1;
2631     length = CEILING(length, 2);
2632
2633     return length;
2634 }
2635 \f
2636 /*
2637  * vector-like objects
2638  */
2639
2640 #define NWORDS(x,y) (CEILING((x),(y)) / (y))
2641
2642 static int
2643 scav_string(lispobj *where, lispobj object)
2644 {
2645     struct vector *vector;
2646     int length, nwords;
2647
2648     /* NOTE: Strings contain one more byte of data than the length */
2649     /* slot indicates. */
2650
2651     vector = (struct vector *) where;
2652     length = fixnum_value(vector->length) + 1;
2653     nwords = CEILING(NWORDS(length, 4) + 2, 2);
2654
2655     return nwords;
2656 }
2657
2658 static lispobj
2659 trans_string(lispobj object)
2660 {
2661     struct vector *vector;
2662     int length, nwords;
2663
2664     gc_assert(is_lisp_pointer(object));
2665
2666     /* NOTE: A string contains one more byte of data (a terminating
2667      * '\0' to help when interfacing with C functions) than indicated
2668      * by the length slot. */
2669
2670     vector = (struct vector *) native_pointer(object);
2671     length = fixnum_value(vector->length) + 1;
2672     nwords = CEILING(NWORDS(length, 4) + 2, 2);
2673
2674     return copy_large_unboxed_object(object, nwords);
2675 }
2676
2677 static int
2678 size_string(lispobj *where)
2679 {
2680     struct vector *vector;
2681     int length, nwords;
2682
2683     /* NOTE: A string contains one more byte of data (a terminating
2684      * '\0' to help when interfacing with C functions) than indicated
2685      * by the length slot. */
2686
2687     vector = (struct vector *) where;
2688     length = fixnum_value(vector->length) + 1;
2689     nwords = CEILING(NWORDS(length, 4) + 2, 2);
2690
2691     return nwords;
2692 }
2693
2694 /* FIXME: What does this mean? */
2695 int gencgc_hash = 1;
2696
2697 static int
2698 scav_vector(lispobj *where, lispobj object)
2699 {
2700     unsigned int kv_length;
2701     lispobj *kv_vector;
2702     unsigned int length = 0; /* (0 = dummy to stop GCC warning) */
2703     lispobj *hash_table;
2704     lispobj empty_symbol;
2705     unsigned int *index_vector = NULL; /* (NULL = dummy to stop GCC warning) */
2706     unsigned int *next_vector = NULL; /* (NULL = dummy to stop GCC warning) */
2707     unsigned int *hash_vector = NULL; /* (NULL = dummy to stop GCC warning) */
2708     lispobj weak_p_obj;
2709     unsigned next_vector_length = 0;
2710
2711     /* FIXME: A comment explaining this would be nice. It looks as
2712      * though SB-VM:VECTOR-VALID-HASHING-SUBTYPE is set for EQ-based
2713      * hash tables in the Lisp HASH-TABLE code, and nowhere else. */
2714     if (HeaderValue(object) != subtype_VectorValidHashing)
2715         return 1;
2716
2717     if (!gencgc_hash) {
2718         /* This is set for backward compatibility. FIXME: Do we need
2719          * this any more? */
2720         *where = (subtype_VectorMustRehash << type_Bits) | type_SimpleVector;
2721         return 1;
2722     }
2723
2724     kv_length = fixnum_value(where[1]);
2725     kv_vector = where + 2;  /* Skip the header and length. */
2726     /*FSHOW((stderr,"/kv_length = %d\n", kv_length));*/
2727
2728     /* Scavenge element 0, which may be a hash-table structure. */
2729     scavenge(where+2, 1);
2730     if (!is_lisp_pointer(where[2])) {
2731         lose("no pointer at %x in hash table", where[2]);
2732     }
2733     hash_table = (lispobj *)native_pointer(where[2]);
2734     /*FSHOW((stderr,"/hash_table = %x\n", hash_table));*/
2735     if (TypeOf(hash_table[0]) != type_InstanceHeader) {
2736         lose("hash table not instance (%x at %x)", hash_table[0], hash_table);
2737     }
2738
2739     /* Scavenge element 1, which should be some internal symbol that
2740      * the hash table code reserves for marking empty slots. */
2741     scavenge(where+3, 1);
2742     if (!is_lisp_pointer(where[3])) {
2743         lose("not empty-hash-table-slot symbol pointer: %x", where[3]);
2744     }
2745     empty_symbol = where[3];
2746     /* fprintf(stderr,"* empty_symbol = %x\n", empty_symbol);*/
2747     if (TypeOf(*(lispobj *)native_pointer(empty_symbol)) != type_SymbolHeader) {
2748         lose("not a symbol where empty-hash-table-slot symbol expected: %x",
2749              *(lispobj *)native_pointer(empty_symbol));
2750     }
2751
2752     /* Scavenge hash table, which will fix the positions of the other
2753      * needed objects. */
2754     scavenge(hash_table, 16);
2755
2756     /* Cross-check the kv_vector. */
2757     if (where != (lispobj *)native_pointer(hash_table[9])) {
2758         lose("hash_table table!=this table %x", hash_table[9]);
2759     }
2760
2761     /* WEAK-P */
2762     weak_p_obj = hash_table[10];
2763
2764     /* index vector */
2765     {
2766         lispobj index_vector_obj = hash_table[13];
2767
2768         if (is_lisp_pointer(index_vector_obj) &&
2769             (TypeOf(*(lispobj *)native_pointer(index_vector_obj)) == type_SimpleArrayUnsignedByte32)) {
2770             index_vector = ((unsigned int *)native_pointer(index_vector_obj)) + 2;
2771             /*FSHOW((stderr, "/index_vector = %x\n",index_vector));*/
2772             length = fixnum_value(((unsigned int *)native_pointer(index_vector_obj))[1]);
2773             /*FSHOW((stderr, "/length = %d\n", length));*/
2774         } else {
2775             lose("invalid index_vector %x", index_vector_obj);
2776         }
2777     }
2778
2779     /* next vector */
2780     {
2781         lispobj next_vector_obj = hash_table[14];
2782
2783         if (is_lisp_pointer(next_vector_obj) &&
2784             (TypeOf(*(lispobj *)native_pointer(next_vector_obj)) == type_SimpleArrayUnsignedByte32)) {
2785             next_vector = ((unsigned int *)native_pointer(next_vector_obj)) + 2;
2786             /*FSHOW((stderr, "/next_vector = %x\n", next_vector));*/
2787             next_vector_length = fixnum_value(((unsigned int *)native_pointer(next_vector_obj))[1]);
2788             /*FSHOW((stderr, "/next_vector_length = %d\n", next_vector_length));*/
2789         } else {
2790             lose("invalid next_vector %x", next_vector_obj);
2791         }
2792     }
2793
2794     /* maybe hash vector */
2795     {
2796         /* FIXME: This bare "15" offset should become a symbolic
2797          * expression of some sort. And all the other bare offsets
2798          * too. And the bare "16" in scavenge(hash_table, 16). And
2799          * probably other stuff too. Ugh.. */
2800         lispobj hash_vector_obj = hash_table[15];
2801
2802         if (is_lisp_pointer(hash_vector_obj) &&
2803             (TypeOf(*(lispobj *)native_pointer(hash_vector_obj))
2804              == type_SimpleArrayUnsignedByte32)) {
2805             hash_vector = ((unsigned int *)native_pointer(hash_vector_obj)) + 2;
2806             /*FSHOW((stderr, "/hash_vector = %x\n", hash_vector));*/
2807             gc_assert(fixnum_value(((unsigned int *)native_pointer(hash_vector_obj))[1])
2808                       == next_vector_length);
2809         } else {
2810             hash_vector = NULL;
2811             /*FSHOW((stderr, "/no hash_vector: %x\n", hash_vector_obj));*/
2812         }
2813     }
2814
2815     /* These lengths could be different as the index_vector can be a
2816      * different length from the others, a larger index_vector could help
2817      * reduce collisions. */
2818     gc_assert(next_vector_length*2 == kv_length);
2819
2820     /* now all set up.. */
2821
2822     /* Work through the KV vector. */
2823     {
2824         int i;
2825         for (i = 1; i < next_vector_length; i++) {
2826             lispobj old_key = kv_vector[2*i];
2827             unsigned int  old_index = (old_key & 0x1fffffff)%length;
2828
2829             /* Scavenge the key and value. */
2830             scavenge(&kv_vector[2*i],2);
2831
2832             /* Check whether the key has moved and is EQ based. */
2833             {
2834                 lispobj new_key = kv_vector[2*i];
2835                 unsigned int new_index = (new_key & 0x1fffffff)%length;
2836
2837                 if ((old_index != new_index) &&
2838                     ((!hash_vector) || (hash_vector[i] == 0x80000000)) &&
2839                     ((new_key != empty_symbol) ||
2840                      (kv_vector[2*i] != empty_symbol))) {
2841
2842                     /*FSHOW((stderr,
2843                            "* EQ key %d moved from %x to %x; index %d to %d\n",
2844                            i, old_key, new_key, old_index, new_index));*/
2845
2846                     if (index_vector[old_index] != 0) {
2847                         /*FSHOW((stderr, "/P1 %d\n", index_vector[old_index]));*/
2848
2849                         /* Unlink the key from the old_index chain. */
2850                         if (index_vector[old_index] == i) {
2851                             /*FSHOW((stderr, "/P2a %d\n", next_vector[i]));*/
2852                             index_vector[old_index] = next_vector[i];
2853                             /* Link it into the needing rehash chain. */
2854                             next_vector[i] = fixnum_value(hash_table[11]);
2855                             hash_table[11] = make_fixnum(i);
2856                             /*SHOW("P2");*/
2857                         } else {
2858                             unsigned prior = index_vector[old_index];
2859                             unsigned next = next_vector[prior];
2860
2861                             /*FSHOW((stderr, "/P3a %d %d\n", prior, next));*/
2862
2863                             while (next != 0) {
2864                                 /*FSHOW((stderr, "/P3b %d %d\n", prior, next));*/
2865                                 if (next == i) {
2866                                     /* Unlink it. */
2867                                     next_vector[prior] = next_vector[next];
2868                                     /* Link it into the needing rehash
2869                                      * chain. */
2870                                     next_vector[next] =
2871                                         fixnum_value(hash_table[11]);
2872                                     hash_table[11] = make_fixnum(next);
2873                                     /*SHOW("/P3");*/
2874                                     break;
2875                                 }
2876                                 prior = next;
2877                                 next = next_vector[next];
2878                             }
2879                         }
2880                     }
2881                 }
2882             }
2883         }
2884     }
2885     return (CEILING(kv_length + 2, 2));
2886 }
2887
2888 static lispobj
2889 trans_vector(lispobj object)
2890 {
2891     struct vector *vector;
2892     int length, nwords;
2893
2894     gc_assert(is_lisp_pointer(object));
2895
2896     vector = (struct vector *) native_pointer(object);
2897
2898     length = fixnum_value(vector->length);
2899     nwords = CEILING(length + 2, 2);
2900
2901     return copy_large_object(object, nwords);
2902 }
2903
2904 static int
2905 size_vector(lispobj *where)
2906 {
2907     struct vector *vector;
2908     int length, nwords;
2909
2910     vector = (struct vector *) where;
2911     length = fixnum_value(vector->length);
2912     nwords = CEILING(length + 2, 2);
2913
2914     return nwords;
2915 }
2916
2917
2918 static int
2919 scav_vector_bit(lispobj *where, lispobj object)
2920 {
2921     struct vector *vector;
2922     int length, nwords;
2923
2924     vector = (struct vector *) where;
2925     length = fixnum_value(vector->length);
2926     nwords = CEILING(NWORDS(length, 32) + 2, 2);
2927
2928     return nwords;
2929 }
2930
2931 static lispobj
2932 trans_vector_bit(lispobj object)
2933 {
2934     struct vector *vector;
2935     int length, nwords;
2936
2937     gc_assert(is_lisp_pointer(object));
2938
2939     vector = (struct vector *) native_pointer(object);
2940     length = fixnum_value(vector->length);
2941     nwords = CEILING(NWORDS(length, 32) + 2, 2);
2942
2943     return copy_large_unboxed_object(object, nwords);
2944 }
2945
2946 static int
2947 size_vector_bit(lispobj *where)
2948 {
2949     struct vector *vector;
2950     int length, nwords;
2951
2952     vector = (struct vector *) where;
2953     length = fixnum_value(vector->length);
2954     nwords = CEILING(NWORDS(length, 32) + 2, 2);
2955
2956     return nwords;
2957 }
2958
2959
2960 static int
2961 scav_vector_unsigned_byte_2(lispobj *where, lispobj object)
2962 {
2963     struct vector *vector;
2964     int length, nwords;
2965
2966     vector = (struct vector *) where;
2967     length = fixnum_value(vector->length);
2968     nwords = CEILING(NWORDS(length, 16) + 2, 2);
2969
2970     return nwords;
2971 }
2972
2973 static lispobj
2974 trans_vector_unsigned_byte_2(lispobj object)
2975 {
2976     struct vector *vector;
2977     int length, nwords;
2978
2979     gc_assert(is_lisp_pointer(object));
2980
2981     vector = (struct vector *) native_pointer(object);
2982     length = fixnum_value(vector->length);
2983     nwords = CEILING(NWORDS(length, 16) + 2, 2);
2984
2985     return copy_large_unboxed_object(object, nwords);
2986 }
2987
2988 static int
2989 size_vector_unsigned_byte_2(lispobj *where)
2990 {
2991     struct vector *vector;
2992     int length, nwords;
2993
2994     vector = (struct vector *) where;
2995     length = fixnum_value(vector->length);
2996     nwords = CEILING(NWORDS(length, 16) + 2, 2);
2997
2998     return nwords;
2999 }
3000
3001
3002 static int
3003 scav_vector_unsigned_byte_4(lispobj *where, lispobj object)
3004 {
3005     struct vector *vector;
3006     int length, nwords;
3007
3008     vector = (struct vector *) where;
3009     length = fixnum_value(vector->length);
3010     nwords = CEILING(NWORDS(length, 8) + 2, 2);
3011
3012     return nwords;
3013 }
3014
3015 static lispobj
3016 trans_vector_unsigned_byte_4(lispobj object)
3017 {
3018     struct vector *vector;
3019     int length, nwords;
3020
3021     gc_assert(is_lisp_pointer(object));
3022
3023     vector = (struct vector *) native_pointer(object);
3024     length = fixnum_value(vector->length);
3025     nwords = CEILING(NWORDS(length, 8) + 2, 2);
3026
3027     return copy_large_unboxed_object(object, nwords);
3028 }
3029
3030 static int
3031 size_vector_unsigned_byte_4(lispobj *where)
3032 {
3033     struct vector *vector;
3034     int length, nwords;
3035
3036     vector = (struct vector *) where;
3037     length = fixnum_value(vector->length);
3038     nwords = CEILING(NWORDS(length, 8) + 2, 2);
3039
3040     return nwords;
3041 }
3042
3043 static int
3044 scav_vector_unsigned_byte_8(lispobj *where, lispobj object)
3045 {
3046     struct vector *vector;
3047     int length, nwords;
3048
3049     vector = (struct vector *) where;
3050     length = fixnum_value(vector->length);
3051     nwords = CEILING(NWORDS(length, 4) + 2, 2);
3052
3053     return nwords;
3054 }
3055
3056 static lispobj
3057 trans_vector_unsigned_byte_8(lispobj object)
3058 {
3059     struct vector *vector;
3060     int length, nwords;
3061
3062     gc_assert(is_lisp_pointer(object));
3063
3064     vector = (struct vector *) native_pointer(object);
3065     length = fixnum_value(vector->length);
3066     nwords = CEILING(NWORDS(length, 4) + 2, 2);
3067
3068     return copy_large_unboxed_object(object, nwords);
3069 }
3070
3071 static int
3072 size_vector_unsigned_byte_8(lispobj *where)
3073 {
3074     struct vector *vector;
3075     int length, nwords;
3076
3077     vector = (struct vector *) where;
3078     length = fixnum_value(vector->length);
3079     nwords = CEILING(NWORDS(length, 4) + 2, 2);
3080
3081     return nwords;
3082 }
3083
3084
3085 static int
3086 scav_vector_unsigned_byte_16(lispobj *where, lispobj object)
3087 {
3088     struct vector *vector;
3089     int length, nwords;
3090
3091     vector = (struct vector *) where;
3092     length = fixnum_value(vector->length);
3093     nwords = CEILING(NWORDS(length, 2) + 2, 2);
3094
3095     return nwords;
3096 }
3097
3098 static lispobj
3099 trans_vector_unsigned_byte_16(lispobj object)
3100 {
3101     struct vector *vector;
3102     int length, nwords;
3103
3104     gc_assert(is_lisp_pointer(object));
3105
3106     vector = (struct vector *) native_pointer(object);
3107     length = fixnum_value(vector->length);
3108     nwords = CEILING(NWORDS(length, 2) + 2, 2);
3109
3110     return copy_large_unboxed_object(object, nwords);
3111 }
3112
3113 static int
3114 size_vector_unsigned_byte_16(lispobj *where)
3115 {
3116     struct vector *vector;
3117     int length, nwords;
3118
3119     vector = (struct vector *) where;
3120     length = fixnum_value(vector->length);
3121     nwords = CEILING(NWORDS(length, 2) + 2, 2);
3122
3123     return nwords;
3124 }
3125
3126 static int
3127 scav_vector_unsigned_byte_32(lispobj *where, lispobj object)
3128 {
3129     struct vector *vector;
3130     int length, nwords;
3131
3132     vector = (struct vector *) where;
3133     length = fixnum_value(vector->length);
3134     nwords = CEILING(length + 2, 2);
3135
3136     return nwords;
3137 }
3138
3139 static lispobj
3140 trans_vector_unsigned_byte_32(lispobj object)
3141 {
3142     struct vector *vector;
3143     int length, nwords;
3144
3145     gc_assert(is_lisp_pointer(object));
3146
3147     vector = (struct vector *) native_pointer(object);
3148     length = fixnum_value(vector->length);
3149     nwords = CEILING(length + 2, 2);
3150
3151     return copy_large_unboxed_object(object, nwords);
3152 }
3153
3154 static int
3155 size_vector_unsigned_byte_32(lispobj *where)
3156 {
3157     struct vector *vector;
3158     int length, nwords;
3159
3160     vector = (struct vector *) where;
3161     length = fixnum_value(vector->length);
3162     nwords = CEILING(length + 2, 2);
3163
3164     return nwords;
3165 }
3166
3167 static int
3168 scav_vector_single_float(lispobj *where, lispobj object)
3169 {
3170     struct vector *vector;
3171     int length, nwords;
3172
3173     vector = (struct vector *) where;
3174     length = fixnum_value(vector->length);
3175     nwords = CEILING(length + 2, 2);
3176
3177     return nwords;
3178 }
3179
3180 static lispobj
3181 trans_vector_single_float(lispobj object)
3182 {
3183     struct vector *vector;
3184     int length, nwords;
3185
3186     gc_assert(is_lisp_pointer(object));
3187
3188     vector = (struct vector *) native_pointer(object);
3189     length = fixnum_value(vector->length);
3190     nwords = CEILING(length + 2, 2);
3191
3192     return copy_large_unboxed_object(object, nwords);
3193 }
3194
3195 static int
3196 size_vector_single_float(lispobj *where)
3197 {
3198     struct vector *vector;
3199     int length, nwords;
3200
3201     vector = (struct vector *) where;
3202     length = fixnum_value(vector->length);
3203     nwords = CEILING(length + 2, 2);
3204
3205     return nwords;
3206 }
3207
3208 static int
3209 scav_vector_double_float(lispobj *where, lispobj object)
3210 {
3211     struct vector *vector;
3212     int length, nwords;
3213
3214     vector = (struct vector *) where;
3215     length = fixnum_value(vector->length);
3216     nwords = CEILING(length * 2 + 2, 2);
3217
3218     return nwords;
3219 }
3220
3221 static lispobj
3222 trans_vector_double_float(lispobj object)
3223 {
3224     struct vector *vector;
3225     int length, nwords;
3226
3227     gc_assert(is_lisp_pointer(object));
3228
3229     vector = (struct vector *) native_pointer(object);
3230     length = fixnum_value(vector->length);
3231     nwords = CEILING(length * 2 + 2, 2);
3232
3233     return copy_large_unboxed_object(object, nwords);
3234 }
3235
3236 static int
3237 size_vector_double_float(lispobj *where)
3238 {
3239     struct vector *vector;
3240     int length, nwords;
3241
3242     vector = (struct vector *) where;
3243     length = fixnum_value(vector->length);
3244     nwords = CEILING(length * 2 + 2, 2);
3245
3246     return nwords;
3247 }
3248
3249 #ifdef type_SimpleArrayLongFloat
3250 static int
3251 scav_vector_long_float(lispobj *where, lispobj object)
3252 {
3253     struct vector *vector;
3254     int length, nwords;
3255
3256     vector = (struct vector *) where;
3257     length = fixnum_value(vector->length);
3258     nwords = CEILING(length * 3 + 2, 2);
3259
3260     return nwords;
3261 }
3262
3263 static lispobj
3264 trans_vector_long_float(lispobj object)
3265 {
3266     struct vector *vector;
3267     int length, nwords;
3268
3269     gc_assert(is_lisp_pointer(object));
3270
3271     vector = (struct vector *) native_pointer(object);
3272     length = fixnum_value(vector->length);
3273     nwords = CEILING(length * 3 + 2, 2);
3274
3275     return copy_large_unboxed_object(object, nwords);
3276 }
3277
3278 static int
3279 size_vector_long_float(lispobj *where)
3280 {
3281     struct vector *vector;
3282     int length, nwords;
3283
3284     vector = (struct vector *) where;
3285     length = fixnum_value(vector->length);
3286     nwords = CEILING(length * 3 + 2, 2);
3287
3288     return nwords;
3289 }
3290 #endif
3291
3292
3293 #ifdef type_SimpleArrayComplexSingleFloat
3294 static int
3295 scav_vector_complex_single_float(lispobj *where, lispobj object)
3296 {
3297     struct vector *vector;
3298     int length, nwords;
3299
3300     vector = (struct vector *) where;
3301     length = fixnum_value(vector->length);
3302     nwords = CEILING(length * 2 + 2, 2);
3303
3304     return nwords;
3305 }
3306
3307 static lispobj
3308 trans_vector_complex_single_float(lispobj object)
3309 {
3310     struct vector *vector;
3311     int length, nwords;
3312
3313     gc_assert(is_lisp_pointer(object));
3314
3315     vector = (struct vector *) native_pointer(object);
3316     length = fixnum_value(vector->length);
3317     nwords = CEILING(length * 2 + 2, 2);
3318
3319     return copy_large_unboxed_object(object, nwords);
3320 }
3321
3322 static int
3323 size_vector_complex_single_float(lispobj *where)
3324 {
3325     struct vector *vector;
3326     int length, nwords;
3327
3328     vector = (struct vector *) where;
3329     length = fixnum_value(vector->length);
3330     nwords = CEILING(length * 2 + 2, 2);
3331
3332     return nwords;
3333 }
3334 #endif
3335
3336 #ifdef type_SimpleArrayComplexDoubleFloat
3337 static int
3338 scav_vector_complex_double_float(lispobj *where, lispobj object)
3339 {
3340     struct vector *vector;
3341     int length, nwords;
3342
3343     vector = (struct vector *) where;
3344     length = fixnum_value(vector->length);
3345     nwords = CEILING(length * 4 + 2, 2);
3346
3347     return nwords;
3348 }
3349
3350 static lispobj
3351 trans_vector_complex_double_float(lispobj object)
3352 {
3353     struct vector *vector;
3354     int length, nwords;
3355
3356     gc_assert(is_lisp_pointer(object));
3357
3358     vector = (struct vector *) native_pointer(object);
3359     length = fixnum_value(vector->length);
3360     nwords = CEILING(length * 4 + 2, 2);
3361
3362     return copy_large_unboxed_object(object, nwords);
3363 }
3364
3365 static int
3366 size_vector_complex_double_float(lispobj *where)
3367 {
3368     struct vector *vector;
3369     int length, nwords;
3370
3371     vector = (struct vector *) where;
3372     length = fixnum_value(vector->length);
3373     nwords = CEILING(length * 4 + 2, 2);
3374
3375     return nwords;
3376 }
3377 #endif
3378
3379
3380 #ifdef type_SimpleArrayComplexLongFloat
3381 static int
3382 scav_vector_complex_long_float(lispobj *where, lispobj object)
3383 {
3384     struct vector *vector;
3385     int length, nwords;
3386
3387     vector = (struct vector *) where;
3388     length = fixnum_value(vector->length);
3389     nwords = CEILING(length * 6 + 2, 2);
3390
3391     return nwords;
3392 }
3393
3394 static lispobj
3395 trans_vector_complex_long_float(lispobj object)
3396 {
3397     struct vector *vector;
3398     int length, nwords;
3399
3400     gc_assert(is_lisp_pointer(object));
3401
3402     vector = (struct vector *) native_pointer(object);
3403     length = fixnum_value(vector->length);
3404     nwords = CEILING(length * 6 + 2, 2);
3405
3406     return copy_large_unboxed_object(object, nwords);
3407 }
3408
3409 static int
3410 size_vector_complex_long_float(lispobj *where)
3411 {
3412     struct vector *vector;
3413     int length, nwords;
3414
3415     vector = (struct vector *) where;
3416     length = fixnum_value(vector->length);
3417     nwords = CEILING(length * 6 + 2, 2);
3418
3419     return nwords;
3420 }
3421 #endif
3422
3423 \f
3424 /*
3425  * weak pointers
3426  */
3427
3428 /* XX This is a hack adapted from cgc.c. These don't work too well with the
3429  * gencgc as a list of the weak pointers is maintained within the
3430  * objects which causes writes to the pages. A limited attempt is made
3431  * to avoid unnecessary writes, but this needs a re-think. */
3432
3433 #define WEAK_POINTER_NWORDS \
3434     CEILING((sizeof(struct weak_pointer) / sizeof(lispobj)), 2)
3435
3436 static int
3437 scav_weak_pointer(lispobj *where, lispobj object)
3438 {
3439     struct weak_pointer *wp = weak_pointers;
3440     /* Push the weak pointer onto the list of weak pointers.
3441      * Do I have to watch for duplicates? Originally this was
3442      * part of trans_weak_pointer but that didn't work in the
3443      * case where the WP was in a promoted region.
3444      */
3445
3446     /* Check whether it's already in the list. */
3447     while (wp != NULL) {
3448         if (wp == (struct weak_pointer*)where) {
3449             break;
3450         }
3451         wp = wp->next;
3452     }
3453     if (wp == NULL) {
3454         /* Add it to the start of the list. */
3455         wp = (struct weak_pointer*)where;
3456         if (wp->next != weak_pointers) {
3457             wp->next = weak_pointers;
3458         } else {
3459             /*SHOW("avoided write to weak pointer");*/
3460         }
3461         weak_pointers = wp;
3462     }
3463
3464     /* Do not let GC scavenge the value slot of the weak pointer.
3465      * (That is why it is a weak pointer.) */
3466
3467     return WEAK_POINTER_NWORDS;
3468 }
3469
3470 static lispobj
3471 trans_weak_pointer(lispobj object)
3472 {
3473     lispobj copy;
3474     /* struct weak_pointer *wp; */
3475
3476     gc_assert(is_lisp_pointer(object));
3477
3478 #if defined(DEBUG_WEAK)
3479     FSHOW((stderr, "Transporting weak pointer from 0x%08x\n", object));
3480 #endif
3481
3482     /* Need to remember where all the weak pointers are that have */
3483     /* been transported so they can be fixed up in a post-GC pass. */
3484
3485     copy = copy_object(object, WEAK_POINTER_NWORDS);
3486     /*  wp = (struct weak_pointer *) native_pointer(copy);*/
3487         
3488
3489     /* Push the weak pointer onto the list of weak pointers. */
3490     /*  wp->next = weak_pointers;
3491      *  weak_pointers = wp;*/
3492
3493     return copy;
3494 }
3495
3496 static int
3497 size_weak_pointer(lispobj *where)
3498 {
3499     return WEAK_POINTER_NWORDS;
3500 }
3501
3502 void scan_weak_pointers(void)
3503 {
3504     struct weak_pointer *wp;
3505     for (wp = weak_pointers; wp != NULL; wp = wp->next) {
3506         lispobj value = wp->value;
3507         lispobj *first_pointer;
3508
3509         first_pointer = (lispobj *)native_pointer(value);
3510
3511         /*
3512         FSHOW((stderr, "/weak pointer at 0x%08x\n", (unsigned long) wp));
3513         FSHOW((stderr, "/value: 0x%08x\n", (unsigned long) value));
3514         */
3515
3516         if (is_lisp_pointer(value) && from_space_p(value)) {
3517             /* Now, we need to check whether the object has been forwarded. If
3518              * it has been, the weak pointer is still good and needs to be
3519              * updated. Otherwise, the weak pointer needs to be nil'ed
3520              * out. */
3521             if (first_pointer[0] == 0x01) {
3522                 wp->value = first_pointer[1];
3523             } else {
3524                 /* Break it. */
3525                 SHOW("broken");
3526                 wp->value = NIL;
3527                 wp->broken = T;
3528             }
3529         }
3530     }
3531 }
3532 \f
3533 /*
3534  * initialization
3535  */
3536
3537 static int
3538 scav_lose(lispobj *where, lispobj object)
3539 {
3540     lose("no scavenge function for object 0x%08x", (unsigned long) object);
3541     return 0; /* bogus return value to satisfy static type checking */
3542 }
3543
3544 static lispobj
3545 trans_lose(lispobj object)
3546 {
3547     lose("no transport function for object 0x%08x", (unsigned long) object);
3548     return NIL; /* bogus return value to satisfy static type checking */
3549 }
3550
3551 static int
3552 size_lose(lispobj *where)
3553 {
3554     lose("no size function for object at 0x%08x", (unsigned long) where);
3555     return 1; /* bogus return value to satisfy static type checking */
3556 }
3557
3558 static void
3559 gc_init_tables(void)
3560 {
3561     int i;
3562
3563     /* Set default value in all slots of scavenge table. */
3564     for (i = 0; i < 256; i++) { /* FIXME: bare constant length, ick! */
3565         scavtab[i] = scav_lose;
3566     }
3567
3568     /* For each type which can be selected by the low 3 bits of the tag
3569      * alone, set multiple entries in our 8-bit scavenge table (one for each
3570      * possible value of the high 5 bits). */
3571     for (i = 0; i < 32; i++) { /* FIXME: bare constant length, ick! */
3572         scavtab[type_EvenFixnum|(i<<3)] = scav_immediate;
3573         scavtab[type_FunctionPointer|(i<<3)] = scav_function_pointer;
3574         /* OtherImmediate0 */
3575         scavtab[type_ListPointer|(i<<3)] = scav_list_pointer;
3576         scavtab[type_OddFixnum|(i<<3)] = scav_immediate;
3577         scavtab[type_InstancePointer|(i<<3)] = scav_instance_pointer;
3578         /* OtherImmediate1 */
3579         scavtab[type_OtherPointer|(i<<3)] = scav_other_pointer;
3580     }
3581
3582     /* Other-pointer types (those selected by all eight bits of the tag) get
3583      * one entry each in the scavenge table. */
3584     scavtab[type_Bignum] = scav_unboxed;
3585     scavtab[type_Ratio] = scav_boxed;
3586     scavtab[type_SingleFloat] = scav_unboxed;
3587     scavtab[type_DoubleFloat] = scav_unboxed;
3588 #ifdef type_LongFloat
3589     scavtab[type_LongFloat] = scav_unboxed;
3590 #endif
3591     scavtab[type_Complex] = scav_boxed;
3592 #ifdef type_ComplexSingleFloat
3593     scavtab[type_ComplexSingleFloat] = scav_unboxed;
3594 #endif
3595 #ifdef type_ComplexDoubleFloat
3596     scavtab[type_ComplexDoubleFloat] = scav_unboxed;
3597 #endif
3598 #ifdef type_ComplexLongFloat
3599     scavtab[type_ComplexLongFloat] = scav_unboxed;
3600 #endif
3601     scavtab[type_SimpleArray] = scav_boxed;
3602     scavtab[type_SimpleString] = scav_string;
3603     scavtab[type_SimpleBitVector] = scav_vector_bit;
3604     scavtab[type_SimpleVector] = scav_vector;
3605     scavtab[type_SimpleArrayUnsignedByte2] = scav_vector_unsigned_byte_2;
3606     scavtab[type_SimpleArrayUnsignedByte4] = scav_vector_unsigned_byte_4;
3607     scavtab[type_SimpleArrayUnsignedByte8] = scav_vector_unsigned_byte_8;
3608     scavtab[type_SimpleArrayUnsignedByte16] = scav_vector_unsigned_byte_16;
3609     scavtab[type_SimpleArrayUnsignedByte32] = scav_vector_unsigned_byte_32;
3610 #ifdef type_SimpleArraySignedByte8
3611     scavtab[type_SimpleArraySignedByte8] = scav_vector_unsigned_byte_8;
3612 #endif
3613 #ifdef type_SimpleArraySignedByte16
3614     scavtab[type_SimpleArraySignedByte16] = scav_vector_unsigned_byte_16;
3615 #endif
3616 #ifdef type_SimpleArraySignedByte30
3617     scavtab[type_SimpleArraySignedByte30] = scav_vector_unsigned_byte_32;
3618 #endif
3619 #ifdef type_SimpleArraySignedByte32
3620     scavtab[type_SimpleArraySignedByte32] = scav_vector_unsigned_byte_32;
3621 #endif
3622     scavtab[type_SimpleArraySingleFloat] = scav_vector_single_float;
3623     scavtab[type_SimpleArrayDoubleFloat] = scav_vector_double_float;
3624 #ifdef type_SimpleArrayLongFloat
3625     scavtab[type_SimpleArrayLongFloat] = scav_vector_long_float;
3626 #endif
3627 #ifdef type_SimpleArrayComplexSingleFloat
3628     scavtab[type_SimpleArrayComplexSingleFloat] = scav_vector_complex_single_float;
3629 #endif
3630 #ifdef type_SimpleArrayComplexDoubleFloat
3631     scavtab[type_SimpleArrayComplexDoubleFloat] = scav_vector_complex_double_float;
3632 #endif
3633 #ifdef type_SimpleArrayComplexLongFloat
3634     scavtab[type_SimpleArrayComplexLongFloat] = scav_vector_complex_long_float;
3635 #endif
3636     scavtab[type_ComplexString] = scav_boxed;
3637     scavtab[type_ComplexBitVector] = scav_boxed;
3638     scavtab[type_ComplexVector] = scav_boxed;
3639     scavtab[type_ComplexArray] = scav_boxed;
3640     scavtab[type_CodeHeader] = scav_code_header;
3641     /*scavtab[type_FunctionHeader] = scav_function_header;*/
3642     /*scavtab[type_ClosureFunctionHeader] = scav_function_header;*/
3643     /*scavtab[type_ReturnPcHeader] = scav_return_pc_header;*/
3644 #ifdef __i386__
3645     scavtab[type_ClosureHeader] = scav_closure_header;
3646     scavtab[type_FuncallableInstanceHeader] = scav_closure_header;
3647     scavtab[type_ByteCodeFunction] = scav_closure_header;
3648     scavtab[type_ByteCodeClosure] = scav_closure_header;
3649 #else
3650     scavtab[type_ClosureHeader] = scav_boxed;
3651     scavtab[type_FuncallableInstanceHeader] = scav_boxed;
3652     scavtab[type_ByteCodeFunction] = scav_boxed;
3653     scavtab[type_ByteCodeClosure] = scav_boxed;
3654 #endif
3655     scavtab[type_ValueCellHeader] = scav_boxed;
3656     scavtab[type_SymbolHeader] = scav_boxed;
3657     scavtab[type_BaseChar] = scav_immediate;
3658     scavtab[type_Sap] = scav_unboxed;
3659     scavtab[type_UnboundMarker] = scav_immediate;
3660     scavtab[type_WeakPointer] = scav_weak_pointer;
3661     scavtab[type_InstanceHeader] = scav_boxed;
3662     scavtab[type_Fdefn] = scav_fdefn;
3663
3664     /* transport other table, initialized same way as scavtab */
3665     for (i = 0; i < 256; i++)
3666         transother[i] = trans_lose;
3667     transother[type_Bignum] = trans_unboxed;
3668     transother[type_Ratio] = trans_boxed;
3669     transother[type_SingleFloat] = trans_unboxed;
3670     transother[type_DoubleFloat] = trans_unboxed;
3671 #ifdef type_LongFloat
3672     transother[type_LongFloat] = trans_unboxed;
3673 #endif
3674     transother[type_Complex] = trans_boxed;
3675 #ifdef type_ComplexSingleFloat
3676     transother[type_ComplexSingleFloat] = trans_unboxed;
3677 #endif
3678 #ifdef type_ComplexDoubleFloat
3679     transother[type_ComplexDoubleFloat] = trans_unboxed;
3680 #endif
3681 #ifdef type_ComplexLongFloat
3682     transother[type_ComplexLongFloat] = trans_unboxed;
3683 #endif
3684     transother[type_SimpleArray] = trans_boxed_large;
3685     transother[type_SimpleString] = trans_string;
3686     transother[type_SimpleBitVector] = trans_vector_bit;
3687     transother[type_SimpleVector] = trans_vector;
3688     transother[type_SimpleArrayUnsignedByte2] = trans_vector_unsigned_byte_2;
3689     transother[type_SimpleArrayUnsignedByte4] = trans_vector_unsigned_byte_4;
3690     transother[type_SimpleArrayUnsignedByte8] = trans_vector_unsigned_byte_8;
3691     transother[type_SimpleArrayUnsignedByte16] = trans_vector_unsigned_byte_16;
3692     transother[type_SimpleArrayUnsignedByte32] = trans_vector_unsigned_byte_32;
3693 #ifdef type_SimpleArraySignedByte8
3694     transother[type_SimpleArraySignedByte8] = trans_vector_unsigned_byte_8;
3695 #endif
3696 #ifdef type_SimpleArraySignedByte16
3697     transother[type_SimpleArraySignedByte16] = trans_vector_unsigned_byte_16;
3698 #endif
3699 #ifdef type_SimpleArraySignedByte30
3700     transother[type_SimpleArraySignedByte30] = trans_vector_unsigned_byte_32;
3701 #endif
3702 #ifdef type_SimpleArraySignedByte32
3703     transother[type_SimpleArraySignedByte32] = trans_vector_unsigned_byte_32;
3704 #endif
3705     transother[type_SimpleArraySingleFloat] = trans_vector_single_float;
3706     transother[type_SimpleArrayDoubleFloat] = trans_vector_double_float;
3707 #ifdef type_SimpleArrayLongFloat
3708     transother[type_SimpleArrayLongFloat] = trans_vector_long_float;
3709 #endif
3710 #ifdef type_SimpleArrayComplexSingleFloat
3711     transother[type_SimpleArrayComplexSingleFloat] = trans_vector_complex_single_float;
3712 #endif
3713 #ifdef type_SimpleArrayComplexDoubleFloat
3714     transother[type_SimpleArrayComplexDoubleFloat] = trans_vector_complex_double_float;
3715 #endif
3716 #ifdef type_SimpleArrayComplexLongFloat
3717     transother[type_SimpleArrayComplexLongFloat] = trans_vector_complex_long_float;
3718 #endif
3719     transother[type_ComplexString] = trans_boxed;
3720     transother[type_ComplexBitVector] = trans_boxed;
3721     transother[type_ComplexVector] = trans_boxed;
3722     transother[type_ComplexArray] = trans_boxed;
3723     transother[type_CodeHeader] = trans_code_header;
3724     transother[type_FunctionHeader] = trans_function_header;
3725     transother[type_ClosureFunctionHeader] = trans_function_header;
3726     transother[type_ReturnPcHeader] = trans_return_pc_header;
3727     transother[type_ClosureHeader] = trans_boxed;
3728     transother[type_FuncallableInstanceHeader] = trans_boxed;
3729     transother[type_ByteCodeFunction] = trans_boxed;
3730     transother[type_ByteCodeClosure] = trans_boxed;
3731     transother[type_ValueCellHeader] = trans_boxed;
3732     transother[type_SymbolHeader] = trans_boxed;
3733     transother[type_BaseChar] = trans_immediate;
3734     transother[type_Sap] = trans_unboxed;
3735     transother[type_UnboundMarker] = trans_immediate;
3736     transother[type_WeakPointer] = trans_weak_pointer;
3737     transother[type_InstanceHeader] = trans_boxed;
3738     transother[type_Fdefn] = trans_boxed;
3739
3740     /* size table, initialized the same way as scavtab */
3741     for (i = 0; i < 256; i++)
3742         sizetab[i] = size_lose;
3743     for (i = 0; i < 32; i++) {
3744         sizetab[type_EvenFixnum|(i<<3)] = size_immediate;
3745         sizetab[type_FunctionPointer|(i<<3)] = size_pointer;
3746         /* OtherImmediate0 */
3747         sizetab[type_ListPointer|(i<<3)] = size_pointer;
3748         sizetab[type_OddFixnum|(i<<3)] = size_immediate;
3749         sizetab[type_InstancePointer|(i<<3)] = size_pointer;
3750         /* OtherImmediate1 */
3751         sizetab[type_OtherPointer|(i<<3)] = size_pointer;
3752     }
3753     sizetab[type_Bignum] = size_unboxed;
3754     sizetab[type_Ratio] = size_boxed;
3755     sizetab[type_SingleFloat] = size_unboxed;
3756     sizetab[type_DoubleFloat] = size_unboxed;
3757 #ifdef type_LongFloat
3758     sizetab[type_LongFloat] = size_unboxed;
3759 #endif
3760     sizetab[type_Complex] = size_boxed;
3761 #ifdef type_ComplexSingleFloat
3762     sizetab[type_ComplexSingleFloat] = size_unboxed;
3763 #endif
3764 #ifdef type_ComplexDoubleFloat
3765     sizetab[type_ComplexDoubleFloat] = size_unboxed;
3766 #endif
3767 #ifdef type_ComplexLongFloat
3768     sizetab[type_ComplexLongFloat] = size_unboxed;
3769 #endif
3770     sizetab[type_SimpleArray] = size_boxed;
3771     sizetab[type_SimpleString] = size_string;
3772     sizetab[type_SimpleBitVector] = size_vector_bit;
3773     sizetab[type_SimpleVector] = size_vector;
3774     sizetab[type_SimpleArrayUnsignedByte2] = size_vector_unsigned_byte_2;
3775     sizetab[type_SimpleArrayUnsignedByte4] = size_vector_unsigned_byte_4;
3776     sizetab[type_SimpleArrayUnsignedByte8] = size_vector_unsigned_byte_8;
3777     sizetab[type_SimpleArrayUnsignedByte16] = size_vector_unsigned_byte_16;
3778     sizetab[type_SimpleArrayUnsignedByte32] = size_vector_unsigned_byte_32;
3779 #ifdef type_SimpleArraySignedByte8
3780     sizetab[type_SimpleArraySignedByte8] = size_vector_unsigned_byte_8;
3781 #endif
3782 #ifdef type_SimpleArraySignedByte16
3783     sizetab[type_SimpleArraySignedByte16] = size_vector_unsigned_byte_16;
3784 #endif
3785 #ifdef type_SimpleArraySignedByte30
3786     sizetab[type_SimpleArraySignedByte30] = size_vector_unsigned_byte_32;
3787 #endif
3788 #ifdef type_SimpleArraySignedByte32
3789     sizetab[type_SimpleArraySignedByte32] = size_vector_unsigned_byte_32;
3790 #endif
3791     sizetab[type_SimpleArraySingleFloat] = size_vector_single_float;
3792     sizetab[type_SimpleArrayDoubleFloat] = size_vector_double_float;
3793 #ifdef type_SimpleArrayLongFloat
3794     sizetab[type_SimpleArrayLongFloat] = size_vector_long_float;
3795 #endif
3796 #ifdef type_SimpleArrayComplexSingleFloat
3797     sizetab[type_SimpleArrayComplexSingleFloat] = size_vector_complex_single_float;
3798 #endif
3799 #ifdef type_SimpleArrayComplexDoubleFloat
3800     sizetab[type_SimpleArrayComplexDoubleFloat] = size_vector_complex_double_float;
3801 #endif
3802 #ifdef type_SimpleArrayComplexLongFloat
3803     sizetab[type_SimpleArrayComplexLongFloat] = size_vector_complex_long_float;
3804 #endif
3805     sizetab[type_ComplexString] = size_boxed;
3806     sizetab[type_ComplexBitVector] = size_boxed;
3807     sizetab[type_ComplexVector] = size_boxed;
3808     sizetab[type_ComplexArray] = size_boxed;
3809     sizetab[type_CodeHeader] = size_code_header;
3810 #if 0
3811     /* We shouldn't see these, so just lose if it happens. */
3812     sizetab[type_FunctionHeader] = size_function_header;
3813     sizetab[type_ClosureFunctionHeader] = size_function_header;
3814     sizetab[type_ReturnPcHeader] = size_return_pc_header;
3815 #endif
3816     sizetab[type_ClosureHeader] = size_boxed;
3817     sizetab[type_FuncallableInstanceHeader] = size_boxed;
3818     sizetab[type_ValueCellHeader] = size_boxed;
3819     sizetab[type_SymbolHeader] = size_boxed;
3820     sizetab[type_BaseChar] = size_immediate;
3821     sizetab[type_Sap] = size_unboxed;
3822     sizetab[type_UnboundMarker] = size_immediate;
3823     sizetab[type_WeakPointer] = size_weak_pointer;
3824     sizetab[type_InstanceHeader] = size_boxed;
3825     sizetab[type_Fdefn] = size_boxed;
3826 }
3827 \f
3828 /* Scan an area looking for an object which encloses the given pointer.
3829  * Return the object start on success or NULL on failure. */
3830 static lispobj *
3831 search_space(lispobj *start, size_t words, lispobj *pointer)
3832 {
3833     while (words > 0) {
3834         size_t count = 1;
3835         lispobj thing = *start;
3836
3837         /* If thing is an immediate then this is a cons. */
3838         if (is_lisp_pointer(thing)
3839             || ((thing & 3) == 0) /* fixnum */
3840             || (TypeOf(thing) == type_BaseChar)
3841             || (TypeOf(thing) == type_UnboundMarker))
3842             count = 2;
3843         else
3844             count = (sizetab[TypeOf(thing)])(start);
3845
3846         /* Check whether the pointer is within this object. */
3847         if ((pointer >= start) && (pointer < (start+count))) {
3848             /* found it! */
3849             /*FSHOW((stderr,"/found %x in %x %x\n", pointer, start, thing));*/
3850             return(start);
3851         }
3852
3853         /* Round up the count. */
3854         count = CEILING(count,2);
3855
3856         start += count;
3857         words -= count;
3858     }
3859     return (NULL);
3860 }
3861
3862 static lispobj*
3863 search_read_only_space(lispobj *pointer)
3864 {
3865     lispobj* start = (lispobj*)READ_ONLY_SPACE_START;
3866     lispobj* end = (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER);
3867     if ((pointer < start) || (pointer >= end))
3868         return NULL;
3869     return (search_space(start, (pointer+2)-start, pointer));
3870 }
3871
3872 static lispobj *
3873 search_static_space(lispobj *pointer)
3874 {
3875     lispobj* start = (lispobj*)STATIC_SPACE_START;
3876     lispobj* end = (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER);
3877     if ((pointer < start) || (pointer >= end))
3878         return NULL;
3879     return (search_space(start, (pointer+2)-start, pointer));
3880 }
3881
3882 /* a faster version for searching the dynamic space. This will work even
3883  * if the object is in a current allocation region. */
3884 lispobj *
3885 search_dynamic_space(lispobj *pointer)
3886 {
3887     int  page_index = find_page_index(pointer);
3888     lispobj *start;
3889
3890     /* The address may be invalid, so do some checks. */
3891     if ((page_index == -1) || (page_table[page_index].allocated == FREE_PAGE))
3892         return NULL;
3893     start = (lispobj *)((void *)page_address(page_index)
3894                         + page_table[page_index].first_object_offset);
3895     return (search_space(start, (pointer+2)-start, pointer));
3896 }
3897
3898 /* Is there any possibility that pointer is a valid Lisp object
3899  * reference, and/or something else (e.g. subroutine call return
3900  * address) which should prevent us from moving the referred-to thing? */
3901 static int
3902 possibly_valid_dynamic_space_pointer(lispobj *pointer)
3903 {
3904     lispobj *start_addr;
3905
3906     /* Find the object start address. */
3907     if ((start_addr = search_dynamic_space(pointer)) == NULL) {
3908         return 0;
3909     }
3910
3911     /* We need to allow raw pointers into Code objects for return
3912      * addresses. This will also pick up pointers to functions in code
3913      * objects. */
3914     if (TypeOf(*start_addr) == type_CodeHeader) {
3915         /* XXX could do some further checks here */
3916         return 1;
3917     }
3918
3919     /* If it's not a return address then it needs to be a valid Lisp
3920      * pointer. */
3921     if (!is_lisp_pointer((lispobj)pointer)) {
3922         return 0;
3923     }
3924
3925     /* Check that the object pointed to is consistent with the pointer
3926      * low tag.
3927      *
3928      * FIXME: It's not safe to rely on the result from this check
3929      * before an object is initialized. Thus, if we were interrupted
3930      * just as an object had been allocated but not initialized, the
3931      * GC relying on this result could bogusly reclaim the memory.
3932      * However, we can't really afford to do without this check. So
3933      * we should make it safe somehow. 
3934      *   (1) Perhaps just review the code to make sure
3935      *       that WITHOUT-GCING or WITHOUT-INTERRUPTS or some such
3936      *       thing is wrapped around critical sections where allocated
3937      *       memory type bits haven't been set.
3938      *   (2) Perhaps find some other hack to protect against this, e.g.
3939      *       recording the result of the last call to allocate-lisp-memory,
3940      *       and returning true from this function when *pointer is
3941      *       a reference to that result. */
3942     switch (LowtagOf((lispobj)pointer)) {
3943     case type_FunctionPointer:
3944         /* Start_addr should be the enclosing code object, or a closure
3945          * header. */
3946         switch (TypeOf(*start_addr)) {
3947         case type_CodeHeader:
3948             /* This case is probably caught above. */
3949             break;
3950         case type_ClosureHeader:
3951         case type_FuncallableInstanceHeader:
3952         case type_ByteCodeFunction:
3953         case type_ByteCodeClosure:
3954             if ((unsigned)pointer !=
3955                 ((unsigned)start_addr+type_FunctionPointer)) {
3956                 if (gencgc_verbose)
3957                     FSHOW((stderr,
3958                            "/Wf2: %x %x %x\n",
3959                            pointer, start_addr, *start_addr));
3960                 return 0;
3961             }
3962             break;
3963         default:
3964             if (gencgc_verbose)
3965                 FSHOW((stderr,
3966                        "/Wf3: %x %x %x\n",
3967                        pointer, start_addr, *start_addr));
3968             return 0;
3969         }
3970         break;
3971     case type_ListPointer:
3972         if ((unsigned)pointer !=
3973             ((unsigned)start_addr+type_ListPointer)) {
3974             if (gencgc_verbose)
3975                 FSHOW((stderr,
3976                        "/Wl1: %x %x %x\n",
3977                        pointer, start_addr, *start_addr));
3978             return 0;
3979         }
3980         /* Is it plausible cons? */
3981         if ((is_lisp_pointer(start_addr[0])
3982             || ((start_addr[0] & 3) == 0) /* fixnum */
3983             || (TypeOf(start_addr[0]) == type_BaseChar)
3984             || (TypeOf(start_addr[0]) == type_UnboundMarker))
3985            && (is_lisp_pointer(start_addr[1])
3986                || ((start_addr[1] & 3) == 0) /* fixnum */
3987                || (TypeOf(start_addr[1]) == type_BaseChar)
3988                || (TypeOf(start_addr[1]) == type_UnboundMarker)))
3989             break;
3990         else {
3991             if (gencgc_verbose)
3992                 FSHOW((stderr,
3993                        "/Wl2: %x %x %x\n",
3994                        pointer, start_addr, *start_addr));
3995             return 0;
3996         }
3997     case type_InstancePointer:
3998         if ((unsigned)pointer !=
3999             ((unsigned)start_addr+type_InstancePointer)) {
4000             if (gencgc_verbose)
4001                 FSHOW((stderr,
4002                        "/Wi1: %x %x %x\n",
4003                        pointer, start_addr, *start_addr));
4004             return 0;
4005         }
4006         if (TypeOf(start_addr[0]) != type_InstanceHeader) {
4007             if (gencgc_verbose)
4008                 FSHOW((stderr,
4009                        "/Wi2: %x %x %x\n",
4010                        pointer, start_addr, *start_addr));
4011             return 0;
4012         }
4013         break;
4014     case type_OtherPointer:
4015         if ((unsigned)pointer !=
4016             ((int)start_addr+type_OtherPointer)) {
4017             if (gencgc_verbose)
4018                 FSHOW((stderr,
4019                        "/Wo1: %x %x %x\n",
4020                        pointer, start_addr, *start_addr));
4021             return 0;
4022         }
4023         /* Is it plausible?  Not a cons. XXX should check the headers. */
4024         if (is_lisp_pointer(start_addr[0]) || ((start_addr[0] & 3) == 0)) {
4025             if (gencgc_verbose)
4026                 FSHOW((stderr,
4027                        "/Wo2: %x %x %x\n",
4028                        pointer, start_addr, *start_addr));
4029             return 0;
4030         }
4031         switch (TypeOf(start_addr[0])) {
4032         case type_UnboundMarker:
4033         case type_BaseChar:
4034             if (gencgc_verbose)
4035                 FSHOW((stderr,
4036                        "*Wo3: %x %x %x\n",
4037                        pointer, start_addr, *start_addr));
4038             return 0;
4039
4040             /* only pointed to by function pointers? */
4041         case type_ClosureHeader:
4042         case type_FuncallableInstanceHeader:
4043         case type_ByteCodeFunction:
4044         case type_ByteCodeClosure:
4045             if (gencgc_verbose)
4046                 FSHOW((stderr,
4047                        "*Wo4: %x %x %x\n",
4048                        pointer, start_addr, *start_addr));
4049             return 0;
4050
4051         case type_InstanceHeader:
4052             if (gencgc_verbose)
4053                 FSHOW((stderr,
4054                        "*Wo5: %x %x %x\n",
4055                        pointer, start_addr, *start_addr));
4056             return 0;
4057
4058             /* the valid other immediate pointer objects */
4059         case type_SimpleVector:
4060         case type_Ratio:
4061         case type_Complex:
4062 #ifdef type_ComplexSingleFloat
4063         case type_ComplexSingleFloat:
4064 #endif
4065 #ifdef type_ComplexDoubleFloat
4066         case type_ComplexDoubleFloat:
4067 #endif
4068 #ifdef type_ComplexLongFloat
4069         case type_ComplexLongFloat:
4070 #endif
4071         case type_SimpleArray:
4072         case type_ComplexString:
4073         case type_ComplexBitVector:
4074         case type_ComplexVector:
4075         case type_ComplexArray:
4076         case type_ValueCellHeader:
4077         case type_SymbolHeader:
4078         case type_Fdefn:
4079         case type_CodeHeader:
4080         case type_Bignum:
4081         case type_SingleFloat:
4082         case type_DoubleFloat:
4083 #ifdef type_LongFloat
4084         case type_LongFloat:
4085 #endif
4086         case type_SimpleString:
4087         case type_SimpleBitVector:
4088         case type_SimpleArrayUnsignedByte2:
4089         case type_SimpleArrayUnsignedByte4:
4090         case type_SimpleArrayUnsignedByte8:
4091         case type_SimpleArrayUnsignedByte16:
4092         case type_SimpleArrayUnsignedByte32:
4093 #ifdef type_SimpleArraySignedByte8
4094         case type_SimpleArraySignedByte8:
4095 #endif
4096 #ifdef type_SimpleArraySignedByte16
4097         case type_SimpleArraySignedByte16:
4098 #endif
4099 #ifdef type_SimpleArraySignedByte30
4100         case type_SimpleArraySignedByte30:
4101 #endif
4102 #ifdef type_SimpleArraySignedByte32
4103         case type_SimpleArraySignedByte32:
4104 #endif
4105         case type_SimpleArraySingleFloat:
4106         case type_SimpleArrayDoubleFloat:
4107 #ifdef type_SimpleArrayLongFloat
4108         case type_SimpleArrayLongFloat:
4109 #endif
4110 #ifdef type_SimpleArrayComplexSingleFloat
4111         case type_SimpleArrayComplexSingleFloat:
4112 #endif
4113 #ifdef type_SimpleArrayComplexDoubleFloat
4114         case type_SimpleArrayComplexDoubleFloat:
4115 #endif
4116 #ifdef type_SimpleArrayComplexLongFloat
4117         case type_SimpleArrayComplexLongFloat:
4118 #endif
4119         case type_Sap:
4120         case type_WeakPointer:
4121             break;
4122
4123         default:
4124             if (gencgc_verbose)
4125                 FSHOW((stderr,
4126                        "/Wo6: %x %x %x\n",
4127                        pointer, start_addr, *start_addr));
4128             return 0;
4129         }
4130         break;
4131     default:
4132         if (gencgc_verbose)
4133             FSHOW((stderr,
4134                    "*W?: %x %x %x\n",
4135                    pointer, start_addr, *start_addr));
4136         return 0;
4137     }
4138
4139     /* looks good */
4140     return 1;
4141 }
4142
4143 /* Adjust large bignum and vector objects. This will adjust the
4144  * allocated region if the size has shrunk, and move unboxed objects
4145  * into unboxed pages. The pages are not promoted here, and the
4146  * promoted region is not added to the new_regions; this is really
4147  * only designed to be called from preserve_pointer(). Shouldn't fail
4148  * if this is missed, just may delay the moving of objects to unboxed
4149  * pages, and the freeing of pages. */
4150 static void
4151 maybe_adjust_large_object(lispobj *where)
4152 {
4153     int first_page;
4154     int nwords;
4155
4156     int remaining_bytes;
4157     int next_page;
4158     int bytes_freed;
4159     int old_bytes_used;
4160
4161     int boxed;
4162
4163     /* Check whether it's a vector or bignum object. */
4164     switch (TypeOf(where[0])) {
4165     case type_SimpleVector:
4166         boxed = BOXED_PAGE;
4167         break;
4168     case type_Bignum:
4169     case type_SimpleString:
4170     case type_SimpleBitVector:
4171     case type_SimpleArrayUnsignedByte2:
4172     case type_SimpleArrayUnsignedByte4:
4173     case type_SimpleArrayUnsignedByte8:
4174     case type_SimpleArrayUnsignedByte16:
4175     case type_SimpleArrayUnsignedByte32:
4176 #ifdef type_SimpleArraySignedByte8
4177     case type_SimpleArraySignedByte8:
4178 #endif
4179 #ifdef type_SimpleArraySignedByte16
4180     case type_SimpleArraySignedByte16:
4181 #endif
4182 #ifdef type_SimpleArraySignedByte30
4183     case type_SimpleArraySignedByte30:
4184 #endif
4185 #ifdef type_SimpleArraySignedByte32
4186     case type_SimpleArraySignedByte32:
4187 #endif
4188     case type_SimpleArraySingleFloat:
4189     case type_SimpleArrayDoubleFloat:
4190 #ifdef type_SimpleArrayLongFloat
4191     case type_SimpleArrayLongFloat:
4192 #endif
4193 #ifdef type_SimpleArrayComplexSingleFloat
4194     case type_SimpleArrayComplexSingleFloat:
4195 #endif
4196 #ifdef type_SimpleArrayComplexDoubleFloat
4197     case type_SimpleArrayComplexDoubleFloat:
4198 #endif
4199 #ifdef type_SimpleArrayComplexLongFloat
4200     case type_SimpleArrayComplexLongFloat:
4201 #endif
4202         boxed = UNBOXED_PAGE;
4203         break;
4204     default:
4205         return;
4206     }
4207
4208     /* Find its current size. */
4209     nwords = (sizetab[TypeOf(where[0])])(where);
4210
4211     first_page = find_page_index((void *)where);
4212     gc_assert(first_page >= 0);
4213
4214     /* Note: Any page write-protection must be removed, else a later
4215      * scavenge_newspace may incorrectly not scavenge these pages.
4216      * This would not be necessary if they are added to the new areas,
4217      * but lets do it for them all (they'll probably be written
4218      * anyway?). */
4219
4220     gc_assert(page_table[first_page].first_object_offset == 0);
4221
4222     next_page = first_page;
4223     remaining_bytes = nwords*4;
4224     while (remaining_bytes > 4096) {
4225         gc_assert(page_table[next_page].gen == from_space);
4226         gc_assert((page_table[next_page].allocated == BOXED_PAGE)
4227                   || (page_table[next_page].allocated == UNBOXED_PAGE));
4228         gc_assert(page_table[next_page].large_object);
4229         gc_assert(page_table[next_page].first_object_offset ==
4230                   -4096*(next_page-first_page));
4231         gc_assert(page_table[next_page].bytes_used == 4096);
4232
4233         page_table[next_page].allocated = boxed;
4234
4235         /* Shouldn't be write-protected at this stage. Essential that the
4236          * pages aren't. */
4237         gc_assert(!page_table[next_page].write_protected);
4238         remaining_bytes -= 4096;
4239         next_page++;
4240     }
4241
4242     /* Now only one page remains, but the object may have shrunk so
4243      * there may be more unused pages which will be freed. */
4244
4245     /* Object may have shrunk but shouldn't have grown - check. */
4246     gc_assert(page_table[next_page].bytes_used >= remaining_bytes);
4247
4248     page_table[next_page].allocated = boxed;
4249     gc_assert(page_table[next_page].allocated ==
4250               page_table[first_page].allocated);
4251
4252     /* Adjust the bytes_used. */
4253     old_bytes_used = page_table[next_page].bytes_used;
4254     page_table[next_page].bytes_used = remaining_bytes;
4255
4256     bytes_freed = old_bytes_used - remaining_bytes;
4257
4258     /* Free any remaining pages; needs care. */
4259     next_page++;
4260     while ((old_bytes_used == 4096) &&
4261            (page_table[next_page].gen == from_space) &&
4262            ((page_table[next_page].allocated == UNBOXED_PAGE)
4263             || (page_table[next_page].allocated == BOXED_PAGE)) &&
4264            page_table[next_page].large_object &&
4265            (page_table[next_page].first_object_offset ==
4266             -(next_page - first_page)*4096)) {
4267         /* It checks out OK, free the page. We don't need to both zeroing
4268          * pages as this should have been done before shrinking the
4269          * object. These pages shouldn't be write protected as they
4270          * should be zero filled. */
4271         gc_assert(page_table[next_page].write_protected == 0);
4272
4273         old_bytes_used = page_table[next_page].bytes_used;
4274         page_table[next_page].allocated = FREE_PAGE;
4275         page_table[next_page].bytes_used = 0;
4276         bytes_freed += old_bytes_used;
4277         next_page++;
4278     }
4279
4280     if ((bytes_freed > 0) && gencgc_verbose) {
4281         FSHOW((stderr,
4282                "/maybe_adjust_large_object() freed %d\n",
4283                bytes_freed));
4284     }
4285
4286     generations[from_space].bytes_allocated -= bytes_freed;
4287     bytes_allocated -= bytes_freed;
4288
4289     return;
4290 }
4291
4292 /* Take a possible pointer to a Lisp object and mark its page in the
4293  * page_table so that it will not be relocated during a GC.
4294  *
4295  * This involves locating the page it points to, then backing up to
4296  * the first page that has its first object start at offset 0, and
4297  * then marking all pages dont_move from the first until a page that
4298  * ends by being full, or having free gen.
4299  *
4300  * This ensures that objects spanning pages are not broken.
4301  *
4302  * It is assumed that all the page static flags have been cleared at
4303  * the start of a GC.
4304  *
4305  * It is also assumed that the current gc_alloc() region has been
4306  * flushed and the tables updated. */
4307 static void
4308 preserve_pointer(void *addr)
4309 {
4310     int addr_page_index = find_page_index(addr);
4311     int first_page;
4312     int i;
4313     unsigned region_allocation;
4314
4315     /* quick check 1: Address is quite likely to have been invalid. */
4316     if ((addr_page_index == -1)
4317         || (page_table[addr_page_index].allocated == FREE_PAGE)
4318         || (page_table[addr_page_index].bytes_used == 0)
4319         || (page_table[addr_page_index].gen != from_space)
4320         /* Skip if already marked dont_move. */
4321         || (page_table[addr_page_index].dont_move != 0))
4322         return;
4323
4324     /* (Now that we know that addr_page_index is in range, it's
4325      * safe to index into page_table[] with it.) */
4326     region_allocation = page_table[addr_page_index].allocated;
4327
4328     /* quick check 2: Check the offset within the page.
4329      *
4330      * FIXME: The mask should have a symbolic name, and ideally should
4331      * be derived from page size instead of hardwired to 0xfff.
4332      * (Also fix other uses of 0xfff, elsewhere.) */
4333     if (((unsigned)addr & 0xfff) > page_table[addr_page_index].bytes_used)
4334         return;
4335
4336     /* Filter out anything which can't be a pointer to a Lisp object
4337      * (or, as a special case which also requires dont_move, a return
4338      * address referring to something in a CodeObject). This is
4339      * expensive but important, since it vastly reduces the
4340      * probability that random garbage will be bogusly interpreter as
4341      * a pointer which prevents a page from moving. */
4342     if (!possibly_valid_dynamic_space_pointer(addr))
4343         return;
4344
4345     /* Work backwards to find a page with a first_object_offset of 0.
4346      * The pages should be contiguous with all bytes used in the same
4347      * gen. Assumes the first_object_offset is negative or zero. */
4348     first_page = addr_page_index;
4349     while (page_table[first_page].first_object_offset != 0) {
4350         --first_page;
4351         /* Do some checks. */
4352         gc_assert(page_table[first_page].bytes_used == 4096);
4353         gc_assert(page_table[first_page].gen == from_space);
4354         gc_assert(page_table[first_page].allocated == region_allocation);
4355     }
4356
4357     /* Adjust any large objects before promotion as they won't be
4358      * copied after promotion. */
4359     if (page_table[first_page].large_object) {
4360         maybe_adjust_large_object(page_address(first_page));
4361         /* If a large object has shrunk then addr may now point to a
4362          * free area in which case it's ignored here. Note it gets
4363          * through the valid pointer test above because the tail looks
4364          * like conses. */
4365         if ((page_table[addr_page_index].allocated == FREE_PAGE)
4366             || (page_table[addr_page_index].bytes_used == 0)
4367             /* Check the offset within the page. */
4368             || (((unsigned)addr & 0xfff)
4369                 > page_table[addr_page_index].bytes_used)) {
4370             FSHOW((stderr,
4371                    "weird? ignore ptr 0x%x to freed area of large object\n",
4372                    addr));
4373             return;
4374         }
4375         /* It may have moved to unboxed pages. */
4376         region_allocation = page_table[first_page].allocated;
4377     }
4378
4379     /* Now work forward until the end of this contiguous area is found,
4380      * marking all pages as dont_move. */
4381     for (i = first_page; ;i++) {
4382         gc_assert(page_table[i].allocated == region_allocation);
4383
4384         /* Mark the page static. */
4385         page_table[i].dont_move = 1;
4386
4387         /* Move the page to the new_space. XX I'd rather not do this
4388          * but the GC logic is not quite able to copy with the static
4389          * pages remaining in the from space. This also requires the
4390          * generation bytes_allocated counters be updated. */
4391         page_table[i].gen = new_space;
4392         generations[new_space].bytes_allocated += page_table[i].bytes_used;
4393         generations[from_space].bytes_allocated -= page_table[i].bytes_used;
4394
4395         /* It is essential that the pages are not write protected as
4396          * they may have pointers into the old-space which need
4397          * scavenging. They shouldn't be write protected at this
4398          * stage. */
4399         gc_assert(!page_table[i].write_protected);
4400
4401         /* Check whether this is the last page in this contiguous block.. */
4402         if ((page_table[i].bytes_used < 4096)
4403             /* ..or it is 4096 and is the last in the block */
4404             || (page_table[i+1].allocated == FREE_PAGE)
4405             || (page_table[i+1].bytes_used == 0) /* next page free */
4406             || (page_table[i+1].gen != from_space) /* diff. gen */
4407             || (page_table[i+1].first_object_offset == 0))
4408             break;
4409     }
4410
4411     /* Check that the page is now static. */
4412     gc_assert(page_table[addr_page_index].dont_move != 0);
4413 }
4414 \f
4415 /* If the given page is not write-protected, then scan it for pointers
4416  * to younger generations or the top temp. generation, if no
4417  * suspicious pointers are found then the page is write-protected.
4418  *
4419  * Care is taken to check for pointers to the current gc_alloc()
4420  * region if it is a younger generation or the temp. generation. This
4421  * frees the caller from doing a gc_alloc_update_page_tables(). Actually
4422  * the gc_alloc_generation does not need to be checked as this is only
4423  * called from scavenge_generation() when the gc_alloc generation is
4424  * younger, so it just checks if there is a pointer to the current
4425  * region.
4426  *
4427  * We return 1 if the page was write-protected, else 0. */
4428 static int
4429 update_page_write_prot(int page)
4430 {
4431     int gen = page_table[page].gen;
4432     int j;
4433     int wp_it = 1;
4434     void **page_addr = (void **)page_address(page);
4435     int num_words = page_table[page].bytes_used / 4;
4436
4437     /* Shouldn't be a free page. */
4438     gc_assert(page_table[page].allocated != FREE_PAGE);
4439     gc_assert(page_table[page].bytes_used != 0);
4440
4441     /* Skip if it's already write-protected or an unboxed page. */
4442     if (page_table[page].write_protected
4443         || (page_table[page].allocated == UNBOXED_PAGE))
4444         return (0);
4445
4446     /* Scan the page for pointers to younger generations or the
4447      * top temp. generation. */
4448
4449     for (j = 0; j < num_words; j++) {
4450         void *ptr = *(page_addr+j);
4451         int index = find_page_index(ptr);
4452
4453         /* Check that it's in the dynamic space */
4454         if (index != -1)
4455             if (/* Does it point to a younger or the temp. generation? */
4456                 ((page_table[index].allocated != FREE_PAGE)
4457                  && (page_table[index].bytes_used != 0)
4458                  && ((page_table[index].gen < gen)
4459                      || (page_table[index].gen == NUM_GENERATIONS)))
4460
4461                 /* Or does it point within a current gc_alloc() region? */
4462                 || ((boxed_region.start_addr <= ptr)
4463                     && (ptr <= boxed_region.free_pointer))
4464                 || ((unboxed_region.start_addr <= ptr)
4465                     && (ptr <= unboxed_region.free_pointer))) {
4466                 wp_it = 0;
4467                 break;
4468             }
4469     }
4470
4471     if (wp_it == 1) {
4472         /* Write-protect the page. */
4473         /*FSHOW((stderr, "/write-protecting page %d gen %d\n", page, gen));*/
4474
4475         os_protect((void *)page_addr,
4476                    4096,
4477                    OS_VM_PROT_READ|OS_VM_PROT_EXECUTE);
4478
4479         /* Note the page as protected in the page tables. */
4480         page_table[page].write_protected = 1;
4481     }
4482
4483     return (wp_it);
4484 }
4485
4486 /* Scavenge a generation.
4487  *
4488  * This will not resolve all pointers when generation is the new
4489  * space, as new objects may be added which are not check here - use
4490  * scavenge_newspace generation.
4491  *
4492  * Write-protected pages should not have any pointers to the
4493  * from_space so do need scavenging; thus write-protected pages are
4494  * not always scavenged. There is some code to check that these pages
4495  * are not written; but to check fully the write-protected pages need
4496  * to be scavenged by disabling the code to skip them.
4497  *
4498  * Under the current scheme when a generation is GCed the younger
4499  * generations will be empty. So, when a generation is being GCed it
4500  * is only necessary to scavenge the older generations for pointers
4501  * not the younger. So a page that does not have pointers to younger
4502  * generations does not need to be scavenged.
4503  *
4504  * The write-protection can be used to note pages that don't have
4505  * pointers to younger pages. But pages can be written without having
4506  * pointers to younger generations. After the pages are scavenged here
4507  * they can be scanned for pointers to younger generations and if
4508  * there are none the page can be write-protected.
4509  *
4510  * One complication is when the newspace is the top temp. generation.
4511  *
4512  * Enabling SC_GEN_CK scavenges the write-protected pages and checks
4513  * that none were written, which they shouldn't be as they should have
4514  * no pointers to younger generations. This breaks down for weak
4515  * pointers as the objects contain a link to the next and are written
4516  * if a weak pointer is scavenged. Still it's a useful check. */
4517 static void
4518 scavenge_generation(int generation)
4519 {
4520     int i;
4521     int num_wp = 0;
4522
4523 #define SC_GEN_CK 0
4524 #if SC_GEN_CK
4525     /* Clear the write_protected_cleared flags on all pages. */
4526     for (i = 0; i < NUM_PAGES; i++)
4527         page_table[i].write_protected_cleared = 0;
4528 #endif
4529
4530     for (i = 0; i < last_free_page; i++) {
4531         if ((page_table[i].allocated == BOXED_PAGE)
4532             && (page_table[i].bytes_used != 0)
4533             && (page_table[i].gen == generation)) {
4534             int last_page;
4535
4536             /* This should be the start of a contiguous block. */
4537             gc_assert(page_table[i].first_object_offset == 0);
4538
4539             /* We need to find the full extent of this contiguous
4540              * block in case objects span pages. */
4541
4542             /* Now work forward until the end of this contiguous area
4543              * is found. A small area is preferred as there is a
4544              * better chance of its pages being write-protected. */
4545             for (last_page = i; ; last_page++)
4546                 /* Check whether this is the last page in this contiguous
4547                  * block. */
4548                 if ((page_table[last_page].bytes_used < 4096)
4549                     /* Or it is 4096 and is the last in the block */
4550                     || (page_table[last_page+1].allocated != BOXED_PAGE)
4551                     || (page_table[last_page+1].bytes_used == 0)
4552                     || (page_table[last_page+1].gen != generation)
4553                     || (page_table[last_page+1].first_object_offset == 0))
4554                     break;
4555
4556             /* Do a limited check for write_protected pages. If all pages
4557              * are write_protected then there is no need to scavenge. */
4558             {
4559                 int j, all_wp = 1;
4560                 for (j = i; j <= last_page; j++)
4561                     if (page_table[j].write_protected == 0) {
4562                         all_wp = 0;
4563                         break;
4564                     }
4565 #if !SC_GEN_CK
4566                 if (all_wp == 0)
4567 #endif
4568                     {
4569                         scavenge(page_address(i), (page_table[last_page].bytes_used
4570                                                    + (last_page-i)*4096)/4);
4571
4572                         /* Now scan the pages and write protect those
4573                          * that don't have pointers to younger
4574                          * generations. */
4575                         if (enable_page_protection) {
4576                             for (j = i; j <= last_page; j++) {
4577                                 num_wp += update_page_write_prot(j);
4578                             }
4579                         }
4580                     }
4581             }
4582             i = last_page;
4583         }
4584     }
4585
4586     if ((gencgc_verbose > 1) && (num_wp != 0)) {
4587         FSHOW((stderr,
4588                "/write protected %d pages within generation %d\n",
4589                num_wp, generation));
4590     }
4591
4592 #if SC_GEN_CK
4593     /* Check that none of the write_protected pages in this generation
4594      * have been written to. */
4595     for (i = 0; i < NUM_PAGES; i++) {
4596         if ((page_table[i].allocation ! =FREE_PAGE)
4597             && (page_table[i].bytes_used != 0)
4598             && (page_table[i].gen == generation)
4599             && (page_table[i].write_protected_cleared != 0)) {
4600             FSHOW((stderr, "/scavenge_generation() %d\n", generation));
4601             FSHOW((stderr,
4602                    "/page bytes_used=%d first_object_offset=%d dont_move=%d\n",
4603                     page_table[i].bytes_used,
4604                     page_table[i].first_object_offset,
4605                     page_table[i].dont_move));
4606             lose("write to protected page %d in scavenge_generation()", i);
4607         }
4608     }
4609 #endif
4610 }
4611
4612 \f
4613 /* Scavenge a newspace generation. As it is scavenged new objects may
4614  * be allocated to it; these will also need to be scavenged. This
4615  * repeats until there are no more objects unscavenged in the
4616  * newspace generation.
4617  *
4618  * To help improve the efficiency, areas written are recorded by
4619  * gc_alloc() and only these scavenged. Sometimes a little more will be
4620  * scavenged, but this causes no harm. An easy check is done that the
4621  * scavenged bytes equals the number allocated in the previous
4622  * scavenge.
4623  *
4624  * Write-protected pages are not scanned except if they are marked
4625  * dont_move in which case they may have been promoted and still have
4626  * pointers to the from space.
4627  *
4628  * Write-protected pages could potentially be written by alloc however
4629  * to avoid having to handle re-scavenging of write-protected pages
4630  * gc_alloc() does not write to write-protected pages.
4631  *
4632  * New areas of objects allocated are recorded alternatively in the two
4633  * new_areas arrays below. */
4634 static struct new_area new_areas_1[NUM_NEW_AREAS];
4635 static struct new_area new_areas_2[NUM_NEW_AREAS];
4636
4637 /* Do one full scan of the new space generation. This is not enough to
4638  * complete the job as new objects may be added to the generation in
4639  * the process which are not scavenged. */
4640 static void
4641 scavenge_newspace_generation_one_scan(int generation)
4642 {
4643     int i;
4644
4645     FSHOW((stderr,
4646            "/starting one full scan of newspace generation %d\n",
4647            generation));
4648
4649     for (i = 0; i < last_free_page; i++) {
4650         if ((page_table[i].allocated == BOXED_PAGE)
4651             && (page_table[i].bytes_used != 0)
4652             && (page_table[i].gen == generation)
4653             && ((page_table[i].write_protected == 0)
4654                 /* (This may be redundant as write_protected is now
4655                  * cleared before promotion.) */
4656                 || (page_table[i].dont_move == 1))) {
4657             int last_page;
4658
4659             /* The scavenge will start at the first_object_offset of page i.
4660              *
4661              * We need to find the full extent of this contiguous
4662              * block in case objects span pages.
4663              *
4664              * Now work forward until the end of this contiguous area
4665              * is found. A small area is preferred as there is a
4666              * better chance of its pages being write-protected. */
4667             for (last_page = i; ;last_page++) {
4668                 /* Check whether this is the last page in this
4669                  * contiguous block */
4670                 if ((page_table[last_page].bytes_used < 4096)
4671                     /* Or it is 4096 and is the last in the block */
4672                     || (page_table[last_page+1].allocated != BOXED_PAGE)
4673                     || (page_table[last_page+1].bytes_used == 0)
4674                     || (page_table[last_page+1].gen != generation)
4675                     || (page_table[last_page+1].first_object_offset == 0))
4676                     break;
4677             }
4678
4679             /* Do a limited check for write-protected pages. If all
4680              * pages are write-protected then no need to scavenge,
4681              * except if the pages are marked dont_move. */
4682             {
4683                 int j, all_wp = 1;
4684                 for (j = i; j <= last_page; j++)
4685                     if ((page_table[j].write_protected == 0)
4686                         || (page_table[j].dont_move != 0)) {
4687                         all_wp = 0;
4688                         break;
4689                     }
4690
4691                 if (!all_wp) {
4692                     int size;
4693
4694                     /* Calculate the size. */
4695                     if (last_page == i)
4696                         size = (page_table[last_page].bytes_used
4697                                 - page_table[i].first_object_offset)/4;
4698                     else
4699                         size = (page_table[last_page].bytes_used
4700                                 + (last_page-i)*4096
4701                                 - page_table[i].first_object_offset)/4;
4702                     
4703                     {
4704                         new_areas_ignore_page = last_page;
4705                         
4706                         scavenge(page_address(i) +
4707                                  page_table[i].first_object_offset,
4708                                  size);
4709
4710                     }
4711                 }
4712             }
4713
4714             i = last_page;
4715         }
4716     }
4717     FSHOW((stderr,
4718            "/done with one full scan of newspace generation %d\n",
4719            generation));
4720 }
4721
4722 /* Do a complete scavenge of the newspace generation. */
4723 static void
4724 scavenge_newspace_generation(int generation)
4725 {
4726     int i;
4727
4728     /* the new_areas array currently being written to by gc_alloc() */
4729     struct new_area (*current_new_areas)[] = &new_areas_1;
4730     int current_new_areas_index;
4731
4732     /* the new_areas created but the previous scavenge cycle */
4733     struct new_area (*previous_new_areas)[] = NULL;
4734     int previous_new_areas_index;
4735
4736     /* Flush the current regions updating the tables. */
4737     gc_alloc_update_page_tables(0, &boxed_region);
4738     gc_alloc_update_page_tables(1, &unboxed_region);
4739
4740     /* Turn on the recording of new areas by gc_alloc(). */
4741     new_areas = current_new_areas;
4742     new_areas_index = 0;
4743
4744     /* Don't need to record new areas that get scavenged anyway during
4745      * scavenge_newspace_generation_one_scan. */
4746     record_new_objects = 1;
4747
4748     /* Start with a full scavenge. */
4749     scavenge_newspace_generation_one_scan(generation);
4750
4751     /* Record all new areas now. */
4752     record_new_objects = 2;
4753
4754     /* Flush the current regions updating the tables. */
4755     gc_alloc_update_page_tables(0, &boxed_region);
4756     gc_alloc_update_page_tables(1, &unboxed_region);
4757
4758     /* Grab new_areas_index. */
4759     current_new_areas_index = new_areas_index;
4760
4761     /*FSHOW((stderr,
4762              "The first scan is finished; current_new_areas_index=%d.\n",
4763              current_new_areas_index));*/
4764
4765     while (current_new_areas_index > 0) {
4766         /* Move the current to the previous new areas */
4767         previous_new_areas = current_new_areas;
4768         previous_new_areas_index = current_new_areas_index;
4769
4770         /* Scavenge all the areas in previous new areas. Any new areas
4771          * allocated are saved in current_new_areas. */
4772
4773         /* Allocate an array for current_new_areas; alternating between
4774          * new_areas_1 and 2 */
4775         if (previous_new_areas == &new_areas_1)
4776             current_new_areas = &new_areas_2;
4777         else
4778             current_new_areas = &new_areas_1;
4779
4780         /* Set up for gc_alloc(). */
4781         new_areas = current_new_areas;
4782         new_areas_index = 0;
4783
4784         /* Check whether previous_new_areas had overflowed. */
4785         if (previous_new_areas_index >= NUM_NEW_AREAS) {
4786
4787             /* New areas of objects allocated have been lost so need to do a
4788              * full scan to be sure! If this becomes a problem try
4789              * increasing NUM_NEW_AREAS. */
4790             if (gencgc_verbose)
4791                 SHOW("new_areas overflow, doing full scavenge");
4792
4793             /* Don't need to record new areas that get scavenge anyway
4794              * during scavenge_newspace_generation_one_scan. */
4795             record_new_objects = 1;
4796
4797             scavenge_newspace_generation_one_scan(generation);
4798
4799             /* Record all new areas now. */
4800             record_new_objects = 2;
4801
4802             /* Flush the current regions updating the tables. */
4803             gc_alloc_update_page_tables(0, &boxed_region);
4804             gc_alloc_update_page_tables(1, &unboxed_region);
4805
4806         } else {
4807
4808             /* Work through previous_new_areas. */
4809             for (i = 0; i < previous_new_areas_index; i++) {
4810                 /* FIXME: All these bare *4 and /4 should be something
4811                  * like BYTES_PER_WORD or WBYTES. */
4812                 int page = (*previous_new_areas)[i].page;
4813                 int offset = (*previous_new_areas)[i].offset;
4814                 int size = (*previous_new_areas)[i].size / 4;
4815                 gc_assert((*previous_new_areas)[i].size % 4 == 0);
4816
4817                 scavenge(page_address(page)+offset, size);
4818             }
4819
4820             /* Flush the current regions updating the tables. */
4821             gc_alloc_update_page_tables(0, &boxed_region);
4822             gc_alloc_update_page_tables(1, &unboxed_region);
4823         }
4824
4825         current_new_areas_index = new_areas_index;
4826
4827         /*FSHOW((stderr,
4828                  "The re-scan has finished; current_new_areas_index=%d.\n",
4829                  current_new_areas_index));*/
4830     }
4831
4832     /* Turn off recording of areas allocated by gc_alloc(). */
4833     record_new_objects = 0;
4834
4835 #if SC_NS_GEN_CK
4836     /* Check that none of the write_protected pages in this generation
4837      * have been written to. */
4838     for (i = 0; i < NUM_PAGES; i++) {
4839         if ((page_table[i].allocation != FREE_PAGE)
4840             && (page_table[i].bytes_used != 0)
4841             && (page_table[i].gen == generation)
4842             && (page_table[i].write_protected_cleared != 0)
4843             && (page_table[i].dont_move == 0)) {
4844             lose("write protected page %d written to in scavenge_newspace_generation\ngeneration=%d dont_move=%d",
4845                  i, generation, page_table[i].dont_move);
4846         }
4847     }
4848 #endif
4849 }
4850 \f
4851 /* Un-write-protect all the pages in from_space. This is done at the
4852  * start of a GC else there may be many page faults while scavenging
4853  * the newspace (I've seen drive the system time to 99%). These pages
4854  * would need to be unprotected anyway before unmapping in
4855  * free_oldspace; not sure what effect this has on paging.. */
4856 static void
4857 unprotect_oldspace(void)
4858 {
4859     int i;
4860
4861     for (i = 0; i < last_free_page; i++) {
4862         if ((page_table[i].allocated != FREE_PAGE)
4863             && (page_table[i].bytes_used != 0)
4864             && (page_table[i].gen == from_space)) {
4865             void *page_start;
4866
4867             page_start = (void *)page_address(i);
4868
4869             /* Remove any write-protection. We should be able to rely
4870              * on the write-protect flag to avoid redundant calls. */
4871             if (page_table[i].write_protected) {
4872                 os_protect(page_start, 4096, OS_VM_PROT_ALL);
4873                 page_table[i].write_protected = 0;
4874             }
4875         }
4876     }
4877 }
4878
4879 /* Work through all the pages and free any in from_space. This
4880  * assumes that all objects have been copied or promoted to an older
4881  * generation. Bytes_allocated and the generation bytes_allocated
4882  * counter are updated. The number of bytes freed is returned. */
4883 extern void i586_bzero(void *addr, int nbytes);
4884 static int
4885 free_oldspace(void)
4886 {
4887     int bytes_freed = 0;
4888     int first_page, last_page;
4889
4890     first_page = 0;
4891
4892     do {
4893         /* Find a first page for the next region of pages. */
4894         while ((first_page < last_free_page)
4895                && ((page_table[first_page].allocated == FREE_PAGE)
4896                    || (page_table[first_page].bytes_used == 0)
4897                    || (page_table[first_page].gen != from_space)))
4898             first_page++;
4899
4900         if (first_page >= last_free_page)
4901             break;
4902
4903         /* Find the last page of this region. */
4904         last_page = first_page;
4905
4906         do {
4907             /* Free the page. */
4908             bytes_freed += page_table[last_page].bytes_used;
4909             generations[page_table[last_page].gen].bytes_allocated -=
4910                 page_table[last_page].bytes_used;
4911             page_table[last_page].allocated = FREE_PAGE;
4912             page_table[last_page].bytes_used = 0;
4913
4914             /* Remove any write-protection. We should be able to rely
4915              * on the write-protect flag to avoid redundant calls. */
4916             {
4917                 void  *page_start = (void *)page_address(last_page);
4918         
4919                 if (page_table[last_page].write_protected) {
4920                     os_protect(page_start, 4096, OS_VM_PROT_ALL);
4921                     page_table[last_page].write_protected = 0;
4922                 }
4923             }
4924             last_page++;
4925         }
4926         while ((last_page < last_free_page)
4927                && (page_table[last_page].allocated != FREE_PAGE)
4928                && (page_table[last_page].bytes_used != 0)
4929                && (page_table[last_page].gen == from_space));
4930
4931         /* Zero pages from first_page to (last_page-1).
4932          *
4933          * FIXME: Why not use os_zero(..) function instead of
4934          * hand-coding this again? (Check other gencgc_unmap_zero
4935          * stuff too. */
4936         if (gencgc_unmap_zero) {
4937             void *page_start, *addr;
4938
4939             page_start = (void *)page_address(first_page);
4940
4941             os_invalidate(page_start, 4096*(last_page-first_page));
4942             addr = os_validate(page_start, 4096*(last_page-first_page));
4943             if (addr == NULL || addr != page_start) {
4944                 /* Is this an error condition? I couldn't really tell from
4945                  * the old CMU CL code, which fprintf'ed a message with
4946                  * an exclamation point at the end. But I've never seen the
4947                  * message, so it must at least be unusual..
4948                  *
4949                  * (The same condition is also tested for in gc_free_heap.)
4950                  *
4951                  * -- WHN 19991129 */
4952                 lose("i586_bzero: page moved, 0x%08x ==> 0x%08x",
4953                      page_start,
4954                      addr);
4955             }
4956         } else {
4957             int *page_start;
4958
4959             page_start = (int *)page_address(first_page);
4960             i586_bzero(page_start, 4096*(last_page-first_page));
4961         }
4962
4963         first_page = last_page;
4964
4965     } while (first_page < last_free_page);
4966
4967     bytes_allocated -= bytes_freed;
4968     return bytes_freed;
4969 }
4970 \f
4971 #if 0
4972 /* Print some information about a pointer at the given address. */
4973 static void
4974 print_ptr(lispobj *addr)
4975 {
4976     /* If addr is in the dynamic space then out the page information. */
4977     int pi1 = find_page_index((void*)addr);
4978
4979     if (pi1 != -1)
4980         fprintf(stderr,"  %x: page %d  alloc %d  gen %d  bytes_used %d  offset %d  dont_move %d\n",
4981                 (unsigned int) addr,
4982                 pi1,
4983                 page_table[pi1].allocated,
4984                 page_table[pi1].gen,
4985                 page_table[pi1].bytes_used,
4986                 page_table[pi1].first_object_offset,
4987                 page_table[pi1].dont_move);
4988     fprintf(stderr,"  %x %x %x %x (%x) %x %x %x %x\n",
4989             *(addr-4),
4990             *(addr-3),
4991             *(addr-2),
4992             *(addr-1),
4993             *(addr-0),
4994             *(addr+1),
4995             *(addr+2),
4996             *(addr+3),
4997             *(addr+4));
4998 }
4999 #endif
5000
5001 extern int undefined_tramp;
5002
5003 static void
5004 verify_space(lispobj *start, size_t words)
5005 {
5006     int is_in_dynamic_space = (find_page_index((void*)start) != -1);
5007     int is_in_readonly_space =
5008         (READ_ONLY_SPACE_START <= (unsigned)start &&
5009          (unsigned)start < SymbolValue(READ_ONLY_SPACE_FREE_POINTER));
5010
5011     while (words > 0) {
5012         size_t count = 1;
5013         lispobj thing = *(lispobj*)start;
5014
5015         if (is_lisp_pointer(thing)) {
5016             int page_index = find_page_index((void*)thing);
5017             int to_readonly_space =
5018                 (READ_ONLY_SPACE_START <= thing &&
5019                  thing < SymbolValue(READ_ONLY_SPACE_FREE_POINTER));
5020             int to_static_space =
5021                 (STATIC_SPACE_START <= thing &&
5022                  thing < SymbolValue(STATIC_SPACE_FREE_POINTER));
5023
5024             /* Does it point to the dynamic space? */
5025             if (page_index != -1) {
5026                 /* If it's within the dynamic space it should point to a used
5027                  * page. XX Could check the offset too. */
5028                 if ((page_table[page_index].allocated != FREE_PAGE)
5029                     && (page_table[page_index].bytes_used == 0))
5030                     lose ("Ptr %x @ %x sees free page.", thing, start);
5031                 /* Check that it doesn't point to a forwarding pointer! */
5032                 if (*((lispobj *)native_pointer(thing)) == 0x01) {
5033                     lose("Ptr %x @ %x sees forwarding ptr.", thing, start);
5034                 }
5035                 /* Check that its not in the RO space as it would then be a
5036                  * pointer from the RO to the dynamic space. */
5037                 if (is_in_readonly_space) {
5038                     lose("ptr to dynamic space %x from RO space %x",
5039                          thing, start);
5040                 }
5041                 /* Does it point to a plausible object? This check slows
5042                  * it down a lot (so it's commented out).
5043                  *
5044                  * FIXME: Add a variable to enable this dynamically. */
5045                 /* if (!possibly_valid_dynamic_space_pointer((lispobj *)thing)) {
5046                  *     lose("ptr %x to invalid object %x", thing, start); */
5047             } else {
5048                 /* Verify that it points to another valid space. */
5049                 if (!to_readonly_space && !to_static_space
5050                     && (thing != (unsigned)&undefined_tramp)) {
5051                     lose("Ptr %x @ %x sees junk.", thing, start);
5052                 }
5053             }
5054         } else {
5055             if (thing & 0x3) { /* Skip fixnums. FIXME: There should be an
5056                                 * is_fixnum for this. */
5057
5058                 switch(TypeOf(*start)) {
5059
5060                     /* boxed objects */
5061                 case type_SimpleVector:
5062                 case type_Ratio:
5063                 case type_Complex:
5064                 case type_SimpleArray:
5065                 case type_ComplexString:
5066                 case type_ComplexBitVector:
5067                 case type_ComplexVector:
5068                 case type_ComplexArray:
5069                 case type_ClosureHeader:
5070                 case type_FuncallableInstanceHeader:
5071                 case type_ByteCodeFunction:
5072                 case type_ByteCodeClosure:
5073                 case type_ValueCellHeader:
5074                 case type_SymbolHeader:
5075                 case type_BaseChar:
5076                 case type_UnboundMarker:
5077                 case type_InstanceHeader:
5078                 case type_Fdefn:
5079                     count = 1;
5080                     break;
5081
5082                 case type_CodeHeader:
5083                     {
5084                         lispobj object = *start;
5085                         struct code *code;
5086                         int nheader_words, ncode_words, nwords;
5087                         lispobj fheaderl;
5088                         struct function *fheaderp;
5089
5090                         code = (struct code *) start;
5091
5092                         /* Check that it's not in the dynamic space.
5093                          * FIXME: Isn't is supposed to be OK for code
5094                          * objects to be in the dynamic space these days? */
5095                         if (is_in_dynamic_space
5096                             /* It's ok if it's byte compiled code. The trace
5097                              * table offset will be a fixnum if it's x86
5098                              * compiled code - check.
5099                              *
5100                              * FIXME: #^#@@! lack of abstraction here..
5101                              * This line can probably go away now that
5102                              * there's no byte compiler, but I've got
5103                              * too much to worry about right now to try
5104                              * to make sure. -- WHN 2001-10-06 */
5105                             && !(code->trace_table_offset & 0x3)
5106                             /* Only when enabled */
5107                             && verify_dynamic_code_check) {
5108                             FSHOW((stderr,
5109                                    "/code object at %x in the dynamic space\n",
5110                                    start));
5111                         }
5112
5113                         ncode_words = fixnum_value(code->code_size);
5114                         nheader_words = HeaderValue(object);
5115                         nwords = ncode_words + nheader_words;
5116                         nwords = CEILING(nwords, 2);
5117                         /* Scavenge the boxed section of the code data block */
5118                         verify_space(start + 1, nheader_words - 1);
5119
5120                         /* Scavenge the boxed section of each function object in
5121                          * the code data block. */
5122                         fheaderl = code->entry_points;
5123                         while (fheaderl != NIL) {
5124                             fheaderp = (struct function *) native_pointer(fheaderl);
5125                             gc_assert(TypeOf(fheaderp->header) == type_FunctionHeader);
5126                             verify_space(&fheaderp->name, 1);
5127                             verify_space(&fheaderp->arglist, 1);
5128                             verify_space(&fheaderp->type, 1);
5129                             fheaderl = fheaderp->next;
5130                         }
5131                         count = nwords;
5132                         break;
5133                     }
5134         
5135                     /* unboxed objects */
5136                 case type_Bignum:
5137                 case type_SingleFloat:
5138                 case type_DoubleFloat:
5139 #ifdef type_ComplexLongFloat
5140                 case type_LongFloat:
5141 #endif
5142 #ifdef type_ComplexSingleFloat
5143                 case type_ComplexSingleFloat:
5144 #endif
5145 #ifdef type_ComplexDoubleFloat
5146                 case type_ComplexDoubleFloat:
5147 #endif
5148 #ifdef type_ComplexLongFloat
5149                 case type_ComplexLongFloat:
5150 #endif
5151                 case type_SimpleString:
5152                 case type_SimpleBitVector:
5153                 case type_SimpleArrayUnsignedByte2:
5154                 case type_SimpleArrayUnsignedByte4:
5155                 case type_SimpleArrayUnsignedByte8:
5156                 case type_SimpleArrayUnsignedByte16:
5157                 case type_SimpleArrayUnsignedByte32:
5158 #ifdef type_SimpleArraySignedByte8
5159                 case type_SimpleArraySignedByte8:
5160 #endif
5161 #ifdef type_SimpleArraySignedByte16
5162                 case type_SimpleArraySignedByte16:
5163 #endif
5164 #ifdef type_SimpleArraySignedByte30
5165                 case type_SimpleArraySignedByte30:
5166 #endif
5167 #ifdef type_SimpleArraySignedByte32
5168                 case type_SimpleArraySignedByte32:
5169 #endif
5170                 case type_SimpleArraySingleFloat:
5171                 case type_SimpleArrayDoubleFloat:
5172 #ifdef type_SimpleArrayComplexLongFloat
5173                 case type_SimpleArrayLongFloat:
5174 #endif
5175 #ifdef type_SimpleArrayComplexSingleFloat
5176                 case type_SimpleArrayComplexSingleFloat:
5177 #endif
5178 #ifdef type_SimpleArrayComplexDoubleFloat
5179                 case type_SimpleArrayComplexDoubleFloat:
5180 #endif
5181 #ifdef type_SimpleArrayComplexLongFloat
5182                 case type_SimpleArrayComplexLongFloat:
5183 #endif
5184                 case type_Sap:
5185                 case type_WeakPointer:
5186                     count = (sizetab[TypeOf(*start)])(start);
5187                     break;
5188
5189                 default:
5190                     gc_abort();
5191                 }
5192             }
5193         }
5194         start += count;
5195         words -= count;
5196     }
5197 }
5198
5199 static void
5200 verify_gc(void)
5201 {
5202     /* FIXME: It would be nice to make names consistent so that
5203      * foo_size meant size *in* *bytes* instead of size in some
5204      * arbitrary units. (Yes, this caused a bug, how did you guess?:-)
5205      * Some counts of lispobjs are called foo_count; it might be good
5206      * to grep for all foo_size and rename the appropriate ones to
5207      * foo_count. */
5208     int read_only_space_size =
5209         (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER)
5210         - (lispobj*)READ_ONLY_SPACE_START;
5211     int static_space_size =
5212         (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER)
5213         - (lispobj*)STATIC_SPACE_START;
5214     int binding_stack_size =
5215         (lispobj*)SymbolValue(BINDING_STACK_POINTER)
5216         - (lispobj*)BINDING_STACK_START;
5217
5218     verify_space((lispobj*)READ_ONLY_SPACE_START, read_only_space_size);
5219     verify_space((lispobj*)STATIC_SPACE_START   , static_space_size);
5220     verify_space((lispobj*)BINDING_STACK_START  , binding_stack_size);
5221 }
5222
5223 static void
5224 verify_generation(int  generation)
5225 {
5226     int i;
5227
5228     for (i = 0; i < last_free_page; i++) {
5229         if ((page_table[i].allocated != FREE_PAGE)
5230             && (page_table[i].bytes_used != 0)
5231             && (page_table[i].gen == generation)) {
5232             int last_page;
5233             int region_allocation = page_table[i].allocated;
5234
5235             /* This should be the start of a contiguous block */
5236             gc_assert(page_table[i].first_object_offset == 0);
5237
5238             /* Need to find the full extent of this contiguous block in case
5239                objects span pages. */
5240
5241             /* Now work forward until the end of this contiguous area is
5242                found. */
5243             for (last_page = i; ;last_page++)
5244                 /* Check whether this is the last page in this contiguous
5245                  * block. */
5246                 if ((page_table[last_page].bytes_used < 4096)
5247                     /* Or it is 4096 and is the last in the block */
5248                     || (page_table[last_page+1].allocated != region_allocation)
5249                     || (page_table[last_page+1].bytes_used == 0)
5250                     || (page_table[last_page+1].gen != generation)
5251                     || (page_table[last_page+1].first_object_offset == 0))
5252                     break;
5253
5254             verify_space(page_address(i), (page_table[last_page].bytes_used
5255                                            + (last_page-i)*4096)/4);
5256             i = last_page;
5257         }
5258     }
5259 }
5260
5261 /* Check that all the free space is zero filled. */
5262 static void
5263 verify_zero_fill(void)
5264 {
5265     int page;
5266
5267     for (page = 0; page < last_free_page; page++) {
5268         if (page_table[page].allocated == FREE_PAGE) {
5269             /* The whole page should be zero filled. */
5270             int *start_addr = (int *)page_address(page);
5271             int size = 1024;
5272             int i;
5273             for (i = 0; i < size; i++) {
5274                 if (start_addr[i] != 0) {
5275                     lose("free page not zero at %x", start_addr + i);
5276                 }
5277             }
5278         } else {
5279             int free_bytes = 4096 - page_table[page].bytes_used;
5280             if (free_bytes > 0) {
5281                 int *start_addr = (int *)((unsigned)page_address(page)
5282                                           + page_table[page].bytes_used);
5283                 int size = free_bytes / 4;
5284                 int i;
5285                 for (i = 0; i < size; i++) {
5286                     if (start_addr[i] != 0) {
5287                         lose("free region not zero at %x", start_addr + i);
5288                     }
5289                 }
5290             }
5291         }
5292     }
5293 }
5294
5295 /* External entry point for verify_zero_fill */
5296 void
5297 gencgc_verify_zero_fill(void)
5298 {
5299     /* Flush the alloc regions updating the tables. */
5300     boxed_region.free_pointer = current_region_free_pointer;
5301     gc_alloc_update_page_tables(0, &boxed_region);
5302     gc_alloc_update_page_tables(1, &unboxed_region);
5303     SHOW("verifying zero fill");
5304     verify_zero_fill();
5305     current_region_free_pointer = boxed_region.free_pointer;
5306     current_region_end_addr = boxed_region.end_addr;
5307 }
5308
5309 static void
5310 verify_dynamic_space(void)
5311 {
5312     int i;
5313
5314     for (i = 0; i < NUM_GENERATIONS; i++)
5315         verify_generation(i);
5316
5317     if (gencgc_enable_verify_zero_fill)
5318         verify_zero_fill();
5319 }
5320 \f
5321 /* Write-protect all the dynamic boxed pages in the given generation. */
5322 static void
5323 write_protect_generation_pages(int generation)
5324 {
5325     int i;
5326
5327     gc_assert(generation < NUM_GENERATIONS);
5328
5329     for (i = 0; i < last_free_page; i++)
5330         if ((page_table[i].allocated == BOXED_PAGE)
5331             && (page_table[i].bytes_used != 0)
5332             && (page_table[i].gen == generation))  {
5333             void *page_start;
5334
5335             page_start = (void *)page_address(i);
5336
5337             os_protect(page_start,
5338                        4096,
5339                        OS_VM_PROT_READ | OS_VM_PROT_EXECUTE);
5340
5341             /* Note the page as protected in the page tables. */
5342             page_table[i].write_protected = 1;
5343         }
5344
5345     if (gencgc_verbose > 1) {
5346         FSHOW((stderr,
5347                "/write protected %d of %d pages in generation %d\n",
5348                count_write_protect_generation_pages(generation),
5349                count_generation_pages(generation),
5350                generation));
5351     }
5352 }
5353
5354 /* Garbage collect a generation. If raise is 0 then the remains of the
5355  * generation are not raised to the next generation. */
5356 static void
5357 garbage_collect_generation(int generation, int raise)
5358 {
5359     unsigned long bytes_freed;
5360     unsigned long i;
5361     unsigned long static_space_size;
5362
5363     gc_assert(generation <= (NUM_GENERATIONS-1));
5364
5365     /* The oldest generation can't be raised. */
5366     gc_assert((generation != (NUM_GENERATIONS-1)) || (raise == 0));
5367
5368     /* Initialize the weak pointer list. */
5369     weak_pointers = NULL;
5370
5371     /* When a generation is not being raised it is transported to a
5372      * temporary generation (NUM_GENERATIONS), and lowered when
5373      * done. Set up this new generation. There should be no pages
5374      * allocated to it yet. */
5375     if (!raise)
5376         gc_assert(generations[NUM_GENERATIONS].bytes_allocated == 0);
5377
5378     /* Set the global src and dest. generations */
5379     from_space = generation;
5380     if (raise)
5381         new_space = generation+1;
5382     else
5383         new_space = NUM_GENERATIONS;
5384
5385     /* Change to a new space for allocation, resetting the alloc_start_page */
5386     gc_alloc_generation = new_space;
5387     generations[new_space].alloc_start_page = 0;
5388     generations[new_space].alloc_unboxed_start_page = 0;
5389     generations[new_space].alloc_large_start_page = 0;
5390     generations[new_space].alloc_large_unboxed_start_page = 0;
5391
5392     /* Before any pointers are preserved, the dont_move flags on the
5393      * pages need to be cleared. */
5394     for (i = 0; i < last_free_page; i++)
5395         page_table[i].dont_move = 0;
5396
5397     /* Un-write-protect the old-space pages. This is essential for the
5398      * promoted pages as they may contain pointers into the old-space
5399      * which need to be scavenged. It also helps avoid unnecessary page
5400      * faults as forwarding pointers are written into them. They need to
5401      * be un-protected anyway before unmapping later. */
5402     unprotect_oldspace();
5403
5404     /* Scavenge the stack's conservative roots. */
5405     {
5406         void **ptr;
5407         for (ptr = (void **)CONTROL_STACK_END - 1;
5408              ptr > (void **)&raise;
5409              ptr--) {
5410             preserve_pointer(*ptr);
5411         }
5412     }
5413
5414 #if QSHOW
5415     if (gencgc_verbose > 1) {
5416         int num_dont_move_pages = count_dont_move_pages();
5417         fprintf(stderr,
5418                 "/non-movable pages due to conservative pointers = %d (%d bytes)\n",
5419                 num_dont_move_pages,
5420                 /* FIXME: 4096 should be symbolic constant here and
5421                  * prob'ly elsewhere too. */
5422                 num_dont_move_pages * 4096);
5423     }
5424 #endif
5425
5426     /* Scavenge all the rest of the roots. */
5427
5428     /* Scavenge the Lisp functions of the interrupt handlers, taking
5429      * care to avoid SIG_DFL and SIG_IGN. */
5430     for (i = 0; i < NSIG; i++) {
5431         union interrupt_handler handler = interrupt_handlers[i];
5432         if (!ARE_SAME_HANDLER(handler.c, SIG_IGN) &&
5433             !ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
5434             scavenge((lispobj *)(interrupt_handlers + i), 1);
5435         }
5436     }
5437
5438     /* Scavenge the binding stack. */
5439     scavenge((lispobj *) BINDING_STACK_START,
5440              (lispobj *)SymbolValue(BINDING_STACK_POINTER) -
5441              (lispobj *)BINDING_STACK_START);
5442
5443     /* The original CMU CL code had scavenge-read-only-space code
5444      * controlled by the Lisp-level variable
5445      * *SCAVENGE-READ-ONLY-SPACE*. It was disabled by default, and it
5446      * wasn't documented under what circumstances it was useful or
5447      * safe to turn it on, so it's been turned off in SBCL. If you
5448      * want/need this functionality, and can test and document it,
5449      * please submit a patch. */
5450 #if 0
5451     if (SymbolValue(SCAVENGE_READ_ONLY_SPACE) != NIL) {
5452         unsigned long read_only_space_size =
5453             (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER) -
5454             (lispobj*)READ_ONLY_SPACE_START;
5455         FSHOW((stderr,
5456                "/scavenge read only space: %d bytes\n",
5457                read_only_space_size * sizeof(lispobj)));
5458         scavenge( (lispobj *) READ_ONLY_SPACE_START, read_only_space_size);
5459     }
5460 #endif
5461
5462     /* Scavenge static space. */
5463     static_space_size =
5464         (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER) -
5465         (lispobj *)STATIC_SPACE_START;
5466     if (gencgc_verbose > 1) {
5467         FSHOW((stderr,
5468                "/scavenge static space: %d bytes\n",
5469                static_space_size * sizeof(lispobj)));
5470     }
5471     scavenge( (lispobj *) STATIC_SPACE_START, static_space_size);
5472
5473     /* All generations but the generation being GCed need to be
5474      * scavenged. The new_space generation needs special handling as
5475      * objects may be moved in - it is handled separately below. */
5476     for (i = 0; i < NUM_GENERATIONS; i++) {
5477         if ((i != generation) && (i != new_space)) {
5478             scavenge_generation(i);
5479         }
5480     }
5481
5482     /* Finally scavenge the new_space generation. Keep going until no
5483      * more objects are moved into the new generation */
5484     scavenge_newspace_generation(new_space);
5485
5486     /* FIXME: I tried reenabling this check when debugging unrelated
5487      * GC weirdness ca. sbcl-0.6.12.45, and it failed immediately.
5488      * Since the current GC code seems to work well, I'm guessing that
5489      * this debugging code is just stale, but I haven't tried to
5490      * figure it out. It should be figured out and then either made to
5491      * work or just deleted. */
5492 #define RESCAN_CHECK 0
5493 #if RESCAN_CHECK
5494     /* As a check re-scavenge the newspace once; no new objects should
5495      * be found. */
5496     {
5497         int old_bytes_allocated = bytes_allocated;
5498         int bytes_allocated;
5499
5500         /* Start with a full scavenge. */
5501         scavenge_newspace_generation_one_scan(new_space);
5502
5503         /* Flush the current regions, updating the tables. */
5504         gc_alloc_update_page_tables(0, &boxed_region);
5505         gc_alloc_update_page_tables(1, &unboxed_region);
5506
5507         bytes_allocated = bytes_allocated - old_bytes_allocated;
5508
5509         if (bytes_allocated != 0) {
5510             lose("Rescan of new_space allocated %d more bytes.",
5511                  bytes_allocated);
5512         }
5513     }
5514 #endif
5515
5516     scan_weak_pointers();
5517
5518     /* Flush the current regions, updating the tables. */
5519     gc_alloc_update_page_tables(0, &boxed_region);
5520     gc_alloc_update_page_tables(1, &unboxed_region);
5521
5522     /* Free the pages in oldspace, but not those marked dont_move. */
5523     bytes_freed = free_oldspace();
5524
5525     /* If the GC is not raising the age then lower the generation back
5526      * to its normal generation number */
5527     if (!raise) {
5528         for (i = 0; i < last_free_page; i++)
5529             if ((page_table[i].bytes_used != 0)
5530                 && (page_table[i].gen == NUM_GENERATIONS))
5531                 page_table[i].gen = generation;
5532         gc_assert(generations[generation].bytes_allocated == 0);
5533         generations[generation].bytes_allocated =
5534             generations[NUM_GENERATIONS].bytes_allocated;
5535         generations[NUM_GENERATIONS].bytes_allocated = 0;
5536     }
5537
5538     /* Reset the alloc_start_page for generation. */
5539     generations[generation].alloc_start_page = 0;
5540     generations[generation].alloc_unboxed_start_page = 0;
5541     generations[generation].alloc_large_start_page = 0;
5542     generations[generation].alloc_large_unboxed_start_page = 0;
5543
5544     if (generation >= verify_gens) {
5545         if (gencgc_verbose)
5546             SHOW("verifying");
5547         verify_gc();
5548         verify_dynamic_space();
5549     }
5550
5551     /* Set the new gc trigger for the GCed generation. */
5552     generations[generation].gc_trigger =
5553         generations[generation].bytes_allocated
5554         + generations[generation].bytes_consed_between_gc;
5555
5556     if (raise)
5557         generations[generation].num_gc = 0;
5558     else
5559         ++generations[generation].num_gc;
5560 }
5561
5562 /* Update last_free_page, then SymbolValue(ALLOCATION_POINTER). */
5563 int
5564 update_x86_dynamic_space_free_pointer(void)
5565 {
5566     int last_page = -1;
5567     int i;
5568
5569     for (i = 0; i < NUM_PAGES; i++)
5570         if ((page_table[i].allocated != FREE_PAGE)
5571             && (page_table[i].bytes_used != 0))
5572             last_page = i;
5573
5574     last_free_page = last_page+1;
5575
5576     SetSymbolValue(ALLOCATION_POINTER,
5577                    (lispobj)(((char *)heap_base) + last_free_page*4096));
5578     return 0; /* dummy value: return something ... */
5579 }
5580
5581 /* GC all generations below last_gen, raising their objects to the
5582  * next generation until all generations below last_gen are empty.
5583  * Then if last_gen is due for a GC then GC it. In the special case
5584  * that last_gen==NUM_GENERATIONS, the last generation is always
5585  * GC'ed. The valid range for last_gen is: 0,1,...,NUM_GENERATIONS.
5586  *
5587  * The oldest generation to be GCed will always be
5588  * gencgc_oldest_gen_to_gc, partly ignoring last_gen if necessary. */
5589 void
5590 collect_garbage(unsigned last_gen)
5591 {
5592     int gen = 0;
5593     int raise;
5594     int gen_to_wp;
5595     int i;
5596
5597     boxed_region.free_pointer = current_region_free_pointer;
5598
5599     FSHOW((stderr, "/entering collect_garbage(%d)\n", last_gen));
5600
5601     if (last_gen > NUM_GENERATIONS) {
5602         FSHOW((stderr,
5603                "/collect_garbage: last_gen = %d, doing a level 0 GC\n",
5604                last_gen));
5605         last_gen = 0;
5606     }
5607
5608     /* Flush the alloc regions updating the tables. */
5609     gc_alloc_update_page_tables(0, &boxed_region);
5610     gc_alloc_update_page_tables(1, &unboxed_region);
5611
5612     /* Verify the new objects created by Lisp code. */
5613     if (pre_verify_gen_0) {
5614         SHOW((stderr, "pre-checking generation 0\n"));
5615         verify_generation(0);
5616     }
5617
5618     if (gencgc_verbose > 1)
5619         print_generation_stats(0);
5620
5621     do {
5622         /* Collect the generation. */
5623
5624         if (gen >= gencgc_oldest_gen_to_gc) {
5625             /* Never raise the oldest generation. */
5626             raise = 0;
5627         } else {
5628             raise =
5629                 (gen < last_gen)
5630                 || (generations[gen].num_gc >= generations[gen].trigger_age);
5631         }
5632
5633         if (gencgc_verbose > 1) {
5634             FSHOW((stderr,
5635                    "starting GC of generation %d with raise=%d alloc=%d trig=%d GCs=%d\n",
5636                    gen,
5637                    raise,
5638                    generations[gen].bytes_allocated,
5639                    generations[gen].gc_trigger,
5640                    generations[gen].num_gc));
5641         }
5642
5643         /* If an older generation is being filled, then update its
5644          * memory age. */
5645         if (raise == 1) {
5646             generations[gen+1].cum_sum_bytes_allocated +=
5647                 generations[gen+1].bytes_allocated;
5648         }
5649
5650         garbage_collect_generation(gen, raise);
5651
5652         /* Reset the memory age cum_sum. */
5653         generations[gen].cum_sum_bytes_allocated = 0;
5654
5655         if (gencgc_verbose > 1) {
5656             FSHOW((stderr, "GC of generation %d finished:\n", gen));
5657             print_generation_stats(0);
5658         }
5659
5660         gen++;
5661     } while ((gen <= gencgc_oldest_gen_to_gc)
5662              && ((gen < last_gen)
5663                  || ((gen <= gencgc_oldest_gen_to_gc)
5664                      && raise
5665                      && (generations[gen].bytes_allocated
5666                          > generations[gen].gc_trigger)
5667                      && (gen_av_mem_age(gen)
5668                          > generations[gen].min_av_mem_age))));
5669
5670     /* Now if gen-1 was raised all generations before gen are empty.
5671      * If it wasn't raised then all generations before gen-1 are empty.
5672      *
5673      * Now objects within this gen's pages cannot point to younger
5674      * generations unless they are written to. This can be exploited
5675      * by write-protecting the pages of gen; then when younger
5676      * generations are GCed only the pages which have been written
5677      * need scanning. */
5678     if (raise)
5679         gen_to_wp = gen;
5680     else
5681         gen_to_wp = gen - 1;
5682
5683     /* There's not much point in WPing pages in generation 0 as it is
5684      * never scavenged (except promoted pages). */
5685     if ((gen_to_wp > 0) && enable_page_protection) {
5686         /* Check that they are all empty. */
5687         for (i = 0; i < gen_to_wp; i++) {
5688             if (generations[i].bytes_allocated)
5689                 lose("trying to write-protect gen. %d when gen. %d nonempty",
5690                      gen_to_wp, i);
5691         }
5692         write_protect_generation_pages(gen_to_wp);
5693     }
5694
5695     /* Set gc_alloc() back to generation 0. The current regions should
5696      * be flushed after the above GCs. */
5697     gc_assert((boxed_region.free_pointer - boxed_region.start_addr) == 0);
5698     gc_alloc_generation = 0;
5699
5700     update_x86_dynamic_space_free_pointer();
5701
5702     /* This is now done by Lisp SCRUB-CONTROL-STACK in Lisp SUB-GC, so
5703      * we needn't do it here: */
5704     /*  zero_stack();*/
5705
5706     current_region_free_pointer = boxed_region.free_pointer;
5707     current_region_end_addr = boxed_region.end_addr;
5708
5709     SHOW("returning from collect_garbage");
5710 }
5711
5712 /* This is called by Lisp PURIFY when it is finished. All live objects
5713  * will have been moved to the RO and Static heaps. The dynamic space
5714  * will need a full re-initialization. We don't bother having Lisp
5715  * PURIFY flush the current gc_alloc() region, as the page_tables are
5716  * re-initialized, and every page is zeroed to be sure. */
5717 void
5718 gc_free_heap(void)
5719 {
5720     int page;
5721
5722     if (gencgc_verbose > 1)
5723         SHOW("entering gc_free_heap");
5724
5725     for (page = 0; page < NUM_PAGES; page++) {
5726         /* Skip free pages which should already be zero filled. */
5727         if (page_table[page].allocated != FREE_PAGE) {
5728             void *page_start, *addr;
5729
5730             /* Mark the page free. The other slots are assumed invalid
5731              * when it is a FREE_PAGE and bytes_used is 0 and it
5732              * should not be write-protected -- except that the
5733              * generation is used for the current region but it sets
5734              * that up. */
5735             page_table[page].allocated = FREE_PAGE;
5736             page_table[page].bytes_used = 0;
5737
5738             /* Zero the page. */
5739             page_start = (void *)page_address(page);
5740
5741             /* First, remove any write-protection. */
5742             os_protect(page_start, 4096, OS_VM_PROT_ALL);
5743             page_table[page].write_protected = 0;
5744
5745             os_invalidate(page_start,4096);
5746             addr = os_validate(page_start,4096);
5747             if (addr == NULL || addr != page_start) {
5748                 lose("gc_free_heap: page moved, 0x%08x ==> 0x%08x",
5749                      page_start,
5750                      addr);
5751             }
5752         } else if (gencgc_zero_check_during_free_heap) {
5753             /* Double-check that the page is zero filled. */
5754             int *page_start, i;
5755             gc_assert(page_table[page].allocated == FREE_PAGE);
5756             gc_assert(page_table[page].bytes_used == 0);
5757             page_start = (int *)page_address(page);
5758             for (i=0; i<1024; i++) {
5759                 if (page_start[i] != 0) {
5760                     lose("free region not zero at %x", page_start + i);
5761                 }
5762             }
5763         }
5764     }
5765
5766     bytes_allocated = 0;
5767
5768     /* Initialize the generations. */
5769     for (page = 0; page < NUM_GENERATIONS; page++) {
5770         generations[page].alloc_start_page = 0;
5771         generations[page].alloc_unboxed_start_page = 0;
5772         generations[page].alloc_large_start_page = 0;
5773         generations[page].alloc_large_unboxed_start_page = 0;
5774         generations[page].bytes_allocated = 0;
5775         generations[page].gc_trigger = 2000000;
5776         generations[page].num_gc = 0;
5777         generations[page].cum_sum_bytes_allocated = 0;
5778     }
5779
5780     if (gencgc_verbose > 1)
5781         print_generation_stats(0);
5782
5783     /* Initialize gc_alloc(). */
5784     gc_alloc_generation = 0;
5785     boxed_region.first_page = 0;
5786     boxed_region.last_page = -1;
5787     boxed_region.start_addr = page_address(0);
5788     boxed_region.free_pointer = page_address(0);
5789     boxed_region.end_addr = page_address(0);
5790     unboxed_region.first_page = 0;
5791     unboxed_region.last_page = -1;
5792     unboxed_region.start_addr = page_address(0);
5793     unboxed_region.free_pointer = page_address(0);
5794     unboxed_region.end_addr = page_address(0);
5795
5796 #if 0 /* Lisp PURIFY is currently running on the C stack so don't do this. */
5797     zero_stack();
5798 #endif
5799
5800     last_free_page = 0;
5801     SetSymbolValue(ALLOCATION_POINTER, (lispobj)((char *)heap_base));
5802
5803     current_region_free_pointer = boxed_region.free_pointer;
5804     current_region_end_addr = boxed_region.end_addr;
5805
5806     if (verify_after_free_heap) {
5807         /* Check whether purify has left any bad pointers. */
5808         if (gencgc_verbose)
5809             SHOW("checking after free_heap\n");
5810         verify_gc();
5811     }
5812 }
5813 \f
5814 void
5815 gc_init(void)
5816 {
5817     int i;
5818
5819     gc_init_tables();
5820
5821     heap_base = (void*)DYNAMIC_SPACE_START;
5822
5823     /* Initialize each page structure. */
5824     for (i = 0; i < NUM_PAGES; i++) {
5825         /* Initialize all pages as free. */
5826         page_table[i].allocated = FREE_PAGE;
5827         page_table[i].bytes_used = 0;
5828
5829         /* Pages are not write-protected at startup. */
5830         page_table[i].write_protected = 0;
5831     }
5832
5833     bytes_allocated = 0;
5834
5835     /* Initialize the generations.
5836      *
5837      * FIXME: very similar to code in gc_free_heap(), should be shared */
5838     for (i = 0; i < NUM_GENERATIONS; i++) {
5839         generations[i].alloc_start_page = 0;
5840         generations[i].alloc_unboxed_start_page = 0;
5841         generations[i].alloc_large_start_page = 0;
5842         generations[i].alloc_large_unboxed_start_page = 0;
5843         generations[i].bytes_allocated = 0;
5844         generations[i].gc_trigger = 2000000;
5845         generations[i].num_gc = 0;
5846         generations[i].cum_sum_bytes_allocated = 0;
5847         /* the tune-able parameters */
5848         generations[i].bytes_consed_between_gc = 2000000;
5849         generations[i].trigger_age = 1;
5850         generations[i].min_av_mem_age = 0.75;
5851     }
5852
5853     /* Initialize gc_alloc.
5854      *
5855      * FIXME: identical with code in gc_free_heap(), should be shared */
5856     gc_alloc_generation = 0;
5857     boxed_region.first_page = 0;
5858     boxed_region.last_page = -1;
5859     boxed_region.start_addr = page_address(0);
5860     boxed_region.free_pointer = page_address(0);
5861     boxed_region.end_addr = page_address(0);
5862     unboxed_region.first_page = 0;
5863     unboxed_region.last_page = -1;
5864     unboxed_region.start_addr = page_address(0);
5865     unboxed_region.free_pointer = page_address(0);
5866     unboxed_region.end_addr = page_address(0);
5867
5868     last_free_page = 0;
5869
5870     current_region_free_pointer = boxed_region.free_pointer;
5871     current_region_end_addr = boxed_region.end_addr;
5872 }
5873
5874 /*  Pick up the dynamic space from after a core load.
5875  *
5876  *  The ALLOCATION_POINTER points to the end of the dynamic space.
5877  *
5878  *  XX A scan is needed to identify the closest first objects for pages. */
5879 void
5880 gencgc_pickup_dynamic(void)
5881 {
5882     int page = 0;
5883     int addr = DYNAMIC_SPACE_START;
5884     int alloc_ptr = SymbolValue(ALLOCATION_POINTER);
5885
5886     /* Initialize the first region. */
5887     do {
5888         page_table[page].allocated = BOXED_PAGE;
5889         page_table[page].gen = 0;
5890         page_table[page].bytes_used = 4096;
5891         page_table[page].large_object = 0;
5892         page_table[page].first_object_offset =
5893             (void *)DYNAMIC_SPACE_START - page_address(page);
5894         addr += 4096;
5895         page++;
5896     } while (addr < alloc_ptr);
5897
5898     generations[0].bytes_allocated = 4096*page;
5899     bytes_allocated = 4096*page;
5900
5901     current_region_free_pointer = boxed_region.free_pointer;
5902     current_region_end_addr = boxed_region.end_addr;
5903 }
5904 \f
5905 /* a counter for how deep we are in alloc(..) calls */
5906 int alloc_entered = 0;
5907
5908 /* alloc(..) is the external interface for memory allocation. It
5909  * allocates to generation 0. It is not called from within the garbage
5910  * collector as it is only external uses that need the check for heap
5911  * size (GC trigger) and to disable the interrupts (interrupts are
5912  * always disabled during a GC).
5913  *
5914  * The vops that call alloc(..) assume that the returned space is zero-filled.
5915  * (E.g. the most significant word of a 2-word bignum in MOVE-FROM-UNSIGNED.)
5916  *
5917  * The check for a GC trigger is only performed when the current
5918  * region is full, so in most cases it's not needed. Further MAYBE-GC
5919  * is only called once because Lisp will remember "need to collect
5920  * garbage" and get around to it when it can. */
5921 char *
5922 alloc(int nbytes)
5923 {
5924     /* Check for alignment allocation problems. */
5925     gc_assert((((unsigned)current_region_free_pointer & 0x7) == 0)
5926               && ((nbytes & 0x7) == 0));
5927
5928     if (SymbolValue(PSEUDO_ATOMIC_ATOMIC)) {/* if already in a pseudo atomic */
5929         
5930         void *new_free_pointer;
5931
5932     retry1:
5933         if (alloc_entered) {
5934             SHOW("alloc re-entered in already-pseudo-atomic case");
5935         }
5936         ++alloc_entered;
5937
5938         /* Check whether there is room in the current region. */
5939         new_free_pointer = current_region_free_pointer + nbytes;
5940
5941         /* FIXME: Shouldn't we be doing some sort of lock here, to
5942          * keep from getting screwed if an interrupt service routine
5943          * allocates memory between the time we calculate new_free_pointer
5944          * and the time we write it back to current_region_free_pointer?
5945          * Perhaps I just don't understand pseudo-atomics..
5946          *
5947          * Perhaps I don't. It looks as though what happens is if we
5948          * were interrupted any time during the pseudo-atomic
5949          * interval (which includes now) we discard the allocated
5950          * memory and try again. So, at least we don't return
5951          * a memory area that was allocated out from underneath us
5952          * by code in an ISR.
5953          * Still, that doesn't seem to prevent
5954          * current_region_free_pointer from getting corrupted:
5955          *   We read current_region_free_pointer.
5956          *   They read current_region_free_pointer.
5957          *   They write current_region_free_pointer.
5958          *   We write current_region_free_pointer, scribbling over
5959          *     whatever they wrote. */
5960
5961         if (new_free_pointer <= boxed_region.end_addr) {
5962             /* If so then allocate from the current region. */
5963             void  *new_obj = current_region_free_pointer;
5964             current_region_free_pointer = new_free_pointer;
5965             alloc_entered--;
5966             return((void *)new_obj);
5967         }
5968
5969         if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
5970             /* Double the trigger. */
5971             auto_gc_trigger *= 2;
5972             alloc_entered--;
5973             /* Exit the pseudo-atomic. */
5974             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
5975             if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED) != 0) {
5976                 /* Handle any interrupts that occurred during
5977                  * gc_alloc(..). */
5978                 do_pending_interrupt();
5979             }
5980             funcall0(SymbolFunction(MAYBE_GC));
5981             /* Re-enter the pseudo-atomic. */
5982             SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED, make_fixnum(0));
5983             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(1));
5984             goto retry1;
5985         }
5986         /* Call gc_alloc(). */
5987         boxed_region.free_pointer = current_region_free_pointer;
5988         {
5989             void *new_obj = gc_alloc(nbytes);
5990             current_region_free_pointer = boxed_region.free_pointer;
5991             current_region_end_addr = boxed_region.end_addr;
5992             alloc_entered--;
5993             return (new_obj);
5994         }
5995     } else {
5996         void *result;
5997         void *new_free_pointer;
5998
5999     retry2:
6000         /* At least wrap this allocation in a pseudo atomic to prevent
6001          * gc_alloc() from being re-entered. */
6002         SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED, make_fixnum(0));
6003         SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(1));
6004
6005         if (alloc_entered)
6006             SHOW("alloc re-entered in not-already-pseudo-atomic case");
6007         ++alloc_entered;
6008
6009         /* Check whether there is room in the current region. */
6010         new_free_pointer = current_region_free_pointer + nbytes;
6011
6012         if (new_free_pointer <= boxed_region.end_addr) {
6013             /* If so then allocate from the current region. */
6014             void *new_obj = current_region_free_pointer;
6015             current_region_free_pointer = new_free_pointer;
6016             alloc_entered--;
6017             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
6018             if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED)) {
6019                 /* Handle any interrupts that occurred during
6020                  * gc_alloc(..). */
6021                 do_pending_interrupt();
6022                 goto retry2;
6023             }
6024
6025             return((void *)new_obj);
6026         }
6027
6028         /* KLUDGE: There's lots of code around here shared with the
6029          * the other branch. Is there some way to factor out the
6030          * duplicate code? -- WHN 19991129 */
6031         if (auto_gc_trigger && bytes_allocated > auto_gc_trigger) {
6032             /* Double the trigger. */
6033             auto_gc_trigger *= 2;
6034             alloc_entered--;
6035             /* Exit the pseudo atomic. */
6036             SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
6037             if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED) != 0) {
6038                 /* Handle any interrupts that occurred during
6039                  * gc_alloc(..); */
6040                 do_pending_interrupt();
6041             }
6042             funcall0(SymbolFunction(MAYBE_GC));
6043             goto retry2;
6044         }
6045
6046         /* Else call gc_alloc(). */
6047         boxed_region.free_pointer = current_region_free_pointer;
6048         result = gc_alloc(nbytes);
6049         current_region_free_pointer = boxed_region.free_pointer;
6050         current_region_end_addr = boxed_region.end_addr;
6051
6052         alloc_entered--;
6053         SetSymbolValue(PSEUDO_ATOMIC_ATOMIC, make_fixnum(0));
6054         if (SymbolValue(PSEUDO_ATOMIC_INTERRUPTED) != 0) {
6055             /* Handle any interrupts that occurred during gc_alloc(..). */
6056             do_pending_interrupt();
6057             goto retry2;
6058         }
6059
6060         return result;
6061     }
6062 }
6063 \f
6064 /*
6065  * noise to manipulate the gc trigger stuff
6066  */
6067
6068 void
6069 set_auto_gc_trigger(os_vm_size_t dynamic_usage)
6070 {
6071     auto_gc_trigger += dynamic_usage;
6072 }
6073
6074 void
6075 clear_auto_gc_trigger(void)
6076 {
6077     auto_gc_trigger = 0;
6078 }
6079 \f
6080 /* Find the code object for the given pc, or return NULL on failure.
6081  *
6082  * FIXME: PC shouldn't be lispobj*, should it? Maybe void*? */
6083 lispobj *
6084 component_ptr_from_pc(lispobj *pc)
6085 {
6086     lispobj *object = NULL;
6087
6088     if ( (object = search_read_only_space(pc)) )
6089         ;
6090     else if ( (object = search_static_space(pc)) )
6091         ;
6092     else
6093         object = search_dynamic_space(pc);
6094
6095     if (object) /* if we found something */
6096         if (TypeOf(*object) == type_CodeHeader) /* if it's a code object */
6097             return(object);
6098
6099     return (NULL);
6100 }
6101 \f
6102 /*
6103  * shared support for the OS-dependent signal handlers which
6104  * catch GENCGC-related write-protect violations
6105  */
6106
6107 void unhandled_sigmemoryfault(void);
6108
6109 /* Depending on which OS we're running under, different signals might
6110  * be raised for a violation of write protection in the heap. This
6111  * function factors out the common generational GC magic which needs
6112  * to invoked in this case, and should be called from whatever signal
6113  * handler is appropriate for the OS we're running under.
6114  *
6115  * Return true if this signal is a normal generational GC thing that
6116  * we were able to handle, or false if it was abnormal and control
6117  * should fall through to the general SIGSEGV/SIGBUS/whatever logic. */
6118 int
6119 gencgc_handle_wp_violation(void* fault_addr)
6120 {
6121     int  page_index = find_page_index(fault_addr);
6122
6123 #if defined QSHOW_SIGNALS
6124     FSHOW((stderr, "heap WP violation? fault_addr=%x, page_index=%d\n",
6125            fault_addr, page_index));
6126 #endif
6127
6128     /* Check whether the fault is within the dynamic space. */
6129     if (page_index == (-1)) {
6130
6131         /* It can be helpful to be able to put a breakpoint on this
6132          * case to help diagnose low-level problems. */
6133         unhandled_sigmemoryfault();
6134
6135         /* not within the dynamic space -- not our responsibility */
6136         return 0;
6137
6138     } else {
6139
6140         /* The only acceptable reason for an signal like this from the
6141          * heap is that the generational GC write-protected the page. */
6142         if (page_table[page_index].write_protected != 1) {
6143             lose("access failure in heap page not marked as write-protected");
6144         }
6145         
6146         /* Unprotect the page. */
6147         os_protect(page_address(page_index), 4096, OS_VM_PROT_ALL);
6148         page_table[page_index].write_protected = 0;
6149         page_table[page_index].write_protected_cleared = 1;
6150
6151         /* Don't worry, we can handle it. */
6152         return 1;
6153     }
6154 }
6155
6156 /* This is to be called when we catch a SIGSEGV/SIGBUS, determine that
6157  * it's not just a case of the program hitting the write barrier, and
6158  * are about to let Lisp deal with it. It's basically just a
6159  * convenient place to set a gdb breakpoint. */
6160 void
6161 unhandled_sigmemoryfault()
6162 {}